#! /usr/local/bin/perl
#
#	stream.pl			Version 0.2
#	Usage: perl stream.pl str_A file_A file_B 
#
#		replace str_A in file_A by str_B in file_B
#
#						Seke Wei
#						1998.10.23.
#
#print @ARGV,"\n";
#print $#ARGV,"\n";
#print $0,"\n";

#
#	determine destination file type by $0
#
$toolname = $0;
$purpose = "replace str_A in file_A by str_B in file_B";
$ext = "tmp";
#

if ($#ARGV < 2){
	print "$toolname\t$purpose\nUsage:\t$toolname str_A file_A file_B\n";
	exit;
}

#
#	get str_A from first argument
#

  $str_a = shift (@ARGV);		#str_a is the first element of @ARGV
  print "str_a = $str_a\n";

#
#	get str_B from file_B
#

   $filename_b = pop (@ARGV);		#file_b is the last element of @ARGV
   open(fileb,"$filename_b");
   $str_b = "";
   while(<fileb>) {
   	$str_b .= $_;			#concatenate each line of fileb to str_B
   }
   close(fileb);
   chop($str_b);			#discard the last <cr>
   print "str_b = $str_b\n";

#
#	do the substitution file by file
#
NEXT_FILE:
for $file (@ARGV){

	$ofile = substr($file, 0, index($file, ".")) . '.' . $ext;
   	print "$file -> $ofile\n";

	open(IN, $file);
	open(OUT, ">$ofile");

	while(<IN>) {
		$line = $_;
		print $line,"\n";
		$line =~ s/$str_a/$str_b/g;
		print $line,"\n";
		print OUT $line;
	}
	close (IN);
	close (OUT);

	print "  '$ofile' -> '$file'\n";
	unlink ($file);			#delete old input file
	rename ($ofile, $file);		#rename result to old input file
	utime $atime, $atime, $file;
}
exit 0;
