#!/usr/local/bin/perl
require "/home/roger/lib/weblib.lib";
require "/home/todd/private/toddweb.env";
$PAGEHOMEDIR.="/private";
open(INDEX,"$PAGEHOMEDIR/private/articles/index");
while(<INDEX>){
chop;
($artfile,$title)=split(/:/,$_);
$index{$artfile}=1;
$title{$artfile}=$title;
}
close(INDEX);
$i=0;
open(INDEX,"$PAGEHOMEDIR/trconn.dat");
while(<INDEX>){
	last if /^EOD$/;
	chop;
	($section,$artlist)=split(/\s+/);
	$section[$i]=$section;
	$section{$section}=sprintf("%03d",$i);
	$i++;
	@articles=split(/,/,$artlist);
	foreach $article(@articles){
		if(!$index{$article}){
			print STDERR "Listed article not in index! ($article/$section)\n";
			next;
		}
		if($index{$article} eq "1"){$index{$article}=$section;}
		else{$index{$article}.=",$section";}
	}
}
while(<INDEX>){
	chop;
	($sectiontitle)=split(/\t/);
	($section,$title)=split(/#/,$sectiontitle,2);
	$section{$section}.=":$title";
}
close(INDEX);
opendir(DIR,"$PAGEHOMEDIR/articles");
chdir("$PAGEHOMEDIR/articles");
@files=grep(/\.art$/,readdir(DIR));
#open(FILE2,">/tmp/keywords");
foreach $file(@files){
if(!$index{$file}){
	print STDERR "Article in $file not in index -- skipping\n";
	next;
}
open(FILE,$file);
while(<FILE>){
if(/^<!-- keywords:/){
	chop($keywords=$_);
	$keywords=~s/\r/ /g;
	if($_!~/-->/){
		while(<FILE>){
			chop;
			s/\r/ /g;
			$keywords.=$_;
			last if /-->/;
		}
	}
#	print FILE2 "$file: $keywords\n";
	&dokeywords;
	next;
}
}
}
$BODYENHANCE=" bgcolor=#ffffff";
$style=<<EOF;
body {font: 8pt Verdana, Helvetica;}
EOF
&htmlopen("$PAGENAME|","style=$style");
print &htmltable("<font size=7>Master Index</font>");
print "<tr><th colspan=2>";
foreach $keyword(sort nocase keys %keyword){
	$oldfirst=$first;
	($first=substr($keyword,0,1))=~tr/a-z/A-Z/;
	if($first ne $oldfirst){
		print "<a href=#$first>$first</a> ";
		push(@table,&htmlrowhead("2y<a name=$first href=#>$first</a>"));
	}
	push(@table,"<tr><th align=left valign=top>$keyword</th><td>\n");
	chop($keyword{$keyword});
	foreach $article(split(/,/,$keyword{$keyword})){
		@section=split(/,/,$index{$article});
		foreach $section(sort byvalue @section){
			($index,$title)=split(/:/,$section{$section},2);
			push(@table,"<a href=/trconn.php/article=$article>$title</a> ($title{$article})<br>");
		}
	}
	push(@table,"</td></tr>\n");
}
print "</th></tr>\n";
print @table;
print &htmltableend;
print $PAGETAIL;
print "</body></html>\n";
close HTML;
sub dokeywords{
	$keywords=~/<!-- keywords:\s*(.*)\s*-->/;
	@keywords=split(/,/,$1);
	foreach $keyword(@keywords){
		$keywords=~s/\r/ /g;
		$keyword=~s/^\s+//;
		$keyword=~s/\s+$//;
		$keyword=~s/;/,/g;
		$keyword{$keyword}.="$file,";
	}
}
sub nocase{
local($acase)=$a;
local($bcase)=$b;
$acase=~tr/A-Z/a-z/;
$bcase=~tr/A-Z/a-z/;
$acase cmp $bcase;
}
sub byvalue{
$section{$a} cmp $section{$b};
}
