#! /usr/bin/perl
#############################################################################
# 
#############################################################################
#  
#   GLOBAL VARIABLES {
#
#############################################################################
 
 
$dirname = ".";
$subdir = "false";

$replace=$ARGV[0];
$by=$ARGV[1];
$extention=$ARGV[2];
$rec=$ARGV[3];

   
if (($replace eq "") || ($by eq "") || ($extention eq "" ) || ($extention eq "-r" ) ) {
    print"\n USAGE: \n\tabsolute.pl   current_string  replace_by_string extension [-r]. You may select  ALL for extention\n\n";
    exit();
}
if (  $rec eq "-r")
{$subdir="true";}

print "Replacing $replace with $by \n";
    
handledir($dirname,0);



sub handledir() {
local($dir,$l)=@_;
print "$dir\n";
opendir(DIR, $dir) || die "no dir .";
foreach $fn ( readdir(DIR)) {
	#if ($l >= 5) {continue;}

	if ($fn eq ".") { next;}
	elsif ($fn eq "..") { next;}
	

	$fn=$dir."/".$fn;

	if (-d $fn) {
	        if ( $x =readlink($fn) ) {
		    print "SKIPPING THE LINK at $fn --> $x \n";
		    next;
		}
		$l+=1;
		if ($subdir eq "true") {
		    handledir($fn,$l);
		}
		$l-=1;
	} else {
	    if ($extention eq "ALL" ) {;}
	    elsif (!($fn =~ /.$extention\b/ )){next;}
	    handlefile($fn,$l);	
	}
}
}

sub handlefile(){
local($file,$l)=@_;
#$margin="";
#for ($i=0;$i<$l;$i++){
#   	$margin.=" ";
#}
#print "$margin $file \n";
print "$file \n";

 open(IN, "<$file"); 
$of=$file."___";
 open(OUT, ">$of"); 

	 while (<IN>) {
		$line=$_;
		#print "replacing $replace $by\n";
		$line=~ s/$replace/$by/g;

#		$line=~ s/\(String\)rs.getString\(\"(\w+)\"\)/Util.null2str\(rs.getString\(\"$1\"\)\)/g;
#		$line=~ s/rs.getString\(\"(\w+)\"\)/Util.null2str\(rs.getString\(\"$1\"\)\)/g;
#		$line=~ s/\(String\)Util/Util/g;

#	$line=~ s/\=rs.getString\(\"(\w+)\"\)/\=Util.null2str\(rs.getString\(\"$1\"\)\)/g;
#       $line=~ s/\(String\)rs.getString\((.*)\)/Util.null2str\(rs.getString\($1\)\)/g;

#  		$line=~ s/\+\"\"\+/\+/g;
#  		$line=~ s/\+ \"\"\+/\+/g;
#  		$line=~ s/\+\=\"\"\+/\+\=/g;
#		$line=~ s/\(String\) \"\"/\"\"/g;
		

#  		if ($line =~  /\(String\)rs.getString/  && 
#  		    (  $line =~  /put/ || 
#  		       $line =~/\=\(String\)rs.getString/) 
#  		    )
#  		{
#  		    $line=~ s/\(String\)rs.getString/\"\"\+rs.getString/g;
#  		}

	 	print OUT $line;
	}
 close(IN);
 close(OUT);

 rename($of,$file);

}
