#!/usr/local/bin/perl -s
# script to create listing of .html files in subdirectory and add missing to 
# 'index.html' file
# use -all to make a simple list of all the html files
# JW Morris Aug 1997



#unlink "htmllist";
#system ("ls \*\.html > htmllist");

open (LIST, "ls \*\.html|");
while (<LIST>){
    chop;

    $name = $_;
    print "-1 file is $name\n";
    $file{$name} = 0;
}
$file{"index.html"} = 1;
@keys = sort (keys %file);
print "files are @keys\n";

if ($ARGV[0] ne ""){
    $suff = $ARGV[0];
    open (SUFF, "ls \*$suff|");
    while (<SUFF>){
	chop;

	$name = $_;
	print "-1 file is $name\n";
	$suffile{$name} = 0;
    }
    @suffkeys = sort (keys %suffile);
    print "files are @suffkeys\n";
}
if (!(defined($all))){
CHECK: foreach $file (@keys){
    print "-2 file is $file\n";

    open (REF, "$file");
    while (<REF>){

#	s/\"/ /g;
	if ($_ =~ /HTML files not otherwise referenced/){
	    close REF;
	    next CHECK;
	}
# check the html references
	if ($_ =~ /[Hh][Rr][Ee][Ff] *= *\"/){
	    foreach $name (@keys){
		if ($_ =~ /[Hh][Rr][Ee][Ff] *= *\"*$name/){
		    $file{$name} = 1;
#	if ($_ =~ /$name/){
#	    print "Found ref:$_";
		}
	    }
# check the suffix file references
	    foreach $name (@suffkeys){
		if ($_ =~ /[Hh][Rr][Ee][Ff] *= *\"*$name/){
		    $suffile{$name} = 1;
		}
		

	    }
	}
    }
    close REF;
}

}

open (IND, "index.html");
open (TMP, ">index.tmp");

while (<IND>){
    if ($_ =~ /HTML files not otherwise referenced/){
	$flg = 1;
    }

    print TMP unless ($flg == 1);
}
# check if any of the html files are unreferenced

foreach $name (@keys){

    if ($file{$name} == 0){
	$flg2 = 1;
    }
}
# print unreferenced file names
if ($flg2 == 1){
    print TMP "HTML files not otherwise referenced\n<ul>\n";
    foreach $name (@keys){
	$short = $name;
	$short =~s/\.html$//;
	if ($file{$name} == 0){
	    print TMP "<li><a href=\"$name\">$short</a>\n"
	    }
    }
    print TMP "</ul>\n";
}
#check if any of the suffix files are unreferenced
foreach $name (@suffkeys){

    if ($suffile{$name} == 0){
	$flg3 = 1;
    }
}
if ($flg3 == 1){
    print TMP "Files with suffix $suff not otherwise referenced\n<ul>\n";
    foreach $name (@suffkeys){

	if ($suffile{$name} == 0){
	    print TMP "<li><a href=\"$name\">$name</a>\n"
	    }
    }
    print TMP "</ul>\n";

}
close TMP;
rename ("index.tmp", "index.html");
unlink 'htmllist';

