#!/usr/local/bin/perl
#digest version 0.1  part of the WN server package

$MAINTAINER="mailto:john@math.nwu.edu";
$VERSION = "0.1";

$file=$ARGV[0];
$separator = $ARGV[1];
$section = $ARGV[2];
$marker = "<!-- Range list generated by digest/$VERSION -->";
$endmarker = "<!-- End of range list generated by digest/$VERSION -->";

if ( $section =~ s/^\$//) {
	$skip2next = 1;
}

$OUT="$file.index.html";
$OLDOUT=$OUT."~";
if ( rename( $OUT, $OLDOUT)) {
	$firstfile = 0;
	open( OUTFILE, ">$OUT");
	open( OLD, "<$OLDOUT");
	open( IN, "<$file");

}
else
{
	$firstfile = 1;
	open( OUTFILE, ">$OUT");
	open( IN, "<$file");
}

$startline=0;
$linecnt=0;

if ( $firstfile) {
	printf( OUTFILE "<html>\n<head>\n");
	printf( OUTFILE "<title>Sections of %s</title>\n", $file);
	printf( OUTFILE "</head>\n");
	printf( OUTFILE "<body>\n<h2>Sections of %s</h2>\n", $file);
	printf( OUTFILE $marker, "\n");

}
else {
	while ( $line = <OLD>) {
		if ( $line =~ "<!-- Range list generated by digest") {
			print OUTFILE $marker, "\n";
			last;
		}
		else {
			print OUTFILE $line;
		}
	}
}

printf( OUTFILE "<ul>\n");
while ( $line = <IN> ) {
	$linecnt++;
	if ( $line =~ /$separator/) {
		if ( $startline > 0 ) {
			&printline();
		}
		$startline = $linecnt;
		if ( $skip2next) {
			$line = <IN>;
			$linecnt++;
		}
	}
	if ( $line =~ s/^.*$section//) {
		$title = $line;
		chop( $title);
		$title =~ s/&/&amp;/g;
		$title =~ s/</&lt;/g;
		$title =~ s/>/&gt;/g;
	}
}
&printline();
printf( OUTFILE "</ul>\n");

if ( $firstfile) {
	print OUTFILE $endmarker, "\n";
	print OUTFILE "</body>\n</html>\n";
}
else {
	while ( $line = <OLD>) {
		if ( $line =~ "<!-- End of range list generated by digest") {
			last;
		}
	}
	print OUTFILE $endmarker, "\n";
	while ( $line = <OLD>) {
			print OUTFILE $line;
	}
	close( OLD);
}

close( OUTFILE);


sub printline {
	printf( OUTFILE "    <li> <a href=\"%s;lines=%d-%d\">", 
		$file, $startline, $linecnt-1 );
	printf( OUTFILE "%s</a>\n", $title);
}
