#!/usr/bin/perl -w
if(scalar(@ARGV) == 0) {
        print "Usage: linkify <files generated by pod2html & htmlStrip>\n\n";
        exit -1;
}

$LWARN = "<!-- linkified by npp_html/linkify -->\n";
@files = @ARGV;
foreach $file (@files){
    `mv $file\.html $file\.bak`;

    open(IN, "$file.bak") || die($!);
    open(OUT, ">$file.html") || die($!);
    
    print OUT $LWARN;
    $dupe = 0;
    while(<IN>) {
        if($_ eq $LWARN) {
            $dupe = 1;
        }
        foreach $kw (@files) {
            next if($kw eq $file);
	    $keyword = basename($kw);
            next if(! ($keyword =~ /glod(\w+)/));
            # add the hyperlinks
            $h = "./$keyword.html";
            s/\b$keyword[ifv]*/\<a href=\"$h\">$keyword\<\/a\>/g;
        }
        print OUT $_;
    }
    if($dupe) {
        #print "dupe\n";
        close(OUT);
        close(IN);
        `mv $file.bak $file.html`;
    } else {
        unlink("$file.bak");
    }
}

exit 0;



sub basename {
	my $word; my $last;
	$word = $_[0];
	if($word =~ /\//) { # it is a directory 
		$last = rindex($word, "/");
		if($last < length($word) - 1) {
			$word = substr($word, $last+1);
		} else {
			$word = substr($word, 0, length($word) - 1);
		}
	}
	return $word;	
}
