#!/usr/local/bin/perl

$WafeLib = $ENV{'WAFELIB'} || "/usr/lib/X11/wafe";
$WafeLib = $ENV{'WAFELIB'} || "/goodies/lib/wafe";
if ($#ARGV != 0) {
    die "Usage: $0 fileName\n"
}
$inputFile = $ARGV[$[];
die "Cannot open $inputFile for reading\n" unless -r $inputFile;
die "Cannot create backup copy of $inputFile.bak\n" 
    unless ($rc = system "/bin/cp $inputFile $inputFile.bak") == 0;

undef $/;
@pattern = ();
@files = (<$WafeLib/tcllib/bc/*.tcl>) ;
die "Cannot find alias files $WafeLib/tcllib/bc/*.tcl\n" 
    unless $#files > -1;
foreach $file (@files) {
    print "using $file\n";
#    next if $file =~ /XT\.tcl$/;
    open(F,"<$file") && ($_ = <F>) && close(F) || die "can't read $file";
    foreach (split(/\n/,$_)) {
	if (m/^alias (\S+) (\S+) *$/) {
	    if (length($1)<6) {
		#short commands like label or form are dangeous!
		push(@pattern,"s/([^\\\${])\\b$1\\b( [a-zA-Z])/\\1$2\\2/g");
	    } else {
		push(@pattern,"s/\\b$1\\b/$2/g");
	    }
	}
    }
}
$change_expr = join(";",@pattern);

open(OUT,">$inputFile") || die "Cannot overwrite $inputFile\n";
open(IN,"<$inputFile.bak") || die "Cannot read backup copy $inputFile.bak\n";


#$/ = "";
while (<IN>) {
    eval $change_expr;
    print OUT $_;
}

close (OUT);
system "diff -c $inputFile.bak $inputFile"
