#!/afs/athena/contrib/perl/perl

open(TABLE, "$ENV{'HOME'}/.htmlinks");

while(<TABLE>){
    split;
    $url = $_[0];
    $blah = join(' ', @_[1..$#_]);
    @lnames=();
    while($blah =~ /{{([^}]*)}}/g){
	$name = $1;
	$name =~ s/\s/\\s+/g;
	push(@lnames, $name);
    }
    for $lname (@lnames){
	print("$lname points to $url\n");
	$links{$lname} = $url;
    }
}
for $file (@ARGV){
    open(FILE, $file);

    $doc = '';
    while(<FILE>){
	$doc .= $_;
    }
    close(FILE);
    rename($file, $file.'.bak');
    open(OUT, ">$file");

    @words = keys %links;

    for $match (keys %links){
	print STDOUT "Looking for $match...($doc)\n";
	$n=0;
	$checkdoc =$doc; $findoc = '';
	while($checkdoc =~ /([\s])($match)([\s])/g){
	    print STDOUT "Found a match...($')\n";
	    if($` !~ /<a [^>]+>[^<]+$/){
		$findoc .= $`."<a href=\"$links{$match}\">".$&."</a>";
		$checkdoc = $';
		$n++;
	    }
	}

	print(STDOUT "Made $n changes\n") if $n;
    }    
$findoc = $findoc.$checkdoc;
    print OUT $findoc;
    close(OUT);
}
