#!/usr/bin/perl -w

# Use screen width 120 to view this.
# Author: Don Koks, 2000.

$| = 1; # don't buffer output

if (!defined $ARGV[1]) {
    use File::Basename;
    $0 = basename $0;
    die ("Usage: $0 <stringOld> <stringNew>\n",
	 "Changes files in current directory, substituting stringNew for stringOld.\n",
	 "It's not recursive.\n",
	 "A file called fred.tex will be changed but still called fred.tex,\n",
	 "with the original version called fred.tex.unmodified.\n\n",
	 "You might have to quote and escape some characters, such as a backslash,\n",
	 "but only in the first argument...\n",
	 "Example: in a latex file, to change \\abc to \\Abc, do:\n",
	 "$0 \"\\\\abc\" \"\\Abc\"\n",
	 "So to change \\section to \\section*, do:\n",
	 "$0 \"\\\\section\" \"\\section*\"\n\n");
}

$stringOld = $ARGV[0];
$stringNew = $ARGV[1];


print("Do you want the substitutions done automatically (type y)\n",
      "or do you want to be asked each time, just to check what's happening? (type n): ");

do { chomp($changeAutomatically = <STDIN>); }
until ( ($changeAutomatically eq "y") or ($changeAutomatically eq "n") );


open (LIST, "ls -p |") or die "Problem: can't do an ls!  Exiting with no changes.\n";

while (<LIST>) {
    next if /\.(dvi|ps|pdf|gif|jpg|eps|aux|log|png)$/;
    next if /\/$/;
    chomp($currentFile = $_);
    print "\nLooking in $currentFile...\n";
    open CURRENT_FILE, $currentFile;
    $modifyThis = 0; # Initialise a flag

    while (<CURRENT_FILE>) {
	if (/$stringOld/) { $modifyThis = 1; }  # flag the file for modifying
    }
    close CURRENT_FILE;

    if ($modifyThis == 1) { 
	# $currentFile contains the to-be-changed string, so modify it.  First, change its name
	# to reflect its status before being modified.
	rename "$currentFile", "$currentFile.unmodified";
	open CURRENT_FILE_UNMODIFIED, "$currentFile.unmodified";
	open CURRENT_FILE_MODIFIED,  ">$currentFile.modified";
	while (<CURRENT_FILE_UNMODIFIED>) {
	    if (/$stringOld/) {
		if ($changeAutomatically eq "y") {
		    # User wants substitutions done automatically.
		    s/$stringOld/$stringNew/g;
		}
		else {
		    # User wants to be asked each time.
		    do { 
			print "\n$_ Substitute in this line? (y/n) ";
			chomp($answer = <STDIN>);
		    } until ( ($answer eq "y") or ($answer eq "n") );
		    if ($answer eq "y") { s/$stringOld/$stringNew/g; }
		}
	    }
	    print CURRENT_FILE_MODIFIED;
	}
	close CURRENT_FILE_UNMODIFIED;
	close CURRENT_FILE_MODIFIED;

	# Now that we've finished modifying this file, rename the modified version to the original
	# name.  That way the original file name won't appear until the modified version is completely 
	# built.
	rename "$currentFile.modified", "$currentFile";
    }
}
