#!/usr/bin/perl
###########################################################
# wn_mkdigest version 0.6  part of the WN server package
# Usage: wn_mkdigest [ -b ] separator section_title file [file...]
#
###########################################################

require "getopts.pl";

$VERSION = "0.5";

# get script name for messages;
($prog = $0) =~ s|.*/||;

$usage = "Usage: $prog [ -b ] separator section file ...";

$lineurl = 1;

&Getopts ("b") || die "$usage\n";
$lineurl = 0 if defined ($opt_b);	# do bytecount URLs

die "$usage\n" unless @ARGV >= 3;

$separator = shift;
$section = shift;

$marker = "<!-- Range list generated by wn_mkdigest/$VERSION -->";
$endmarker = "<!-- End of range list generated by wn_mkdigest/$VERSION -->";

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

$file=$ARGV[0];
$OUT="$file.index.html";

$OLDOUT=$OUT."~";
if ( rename( $OUT, $OLDOUT)) {
	$firstfile = 0;
	#open( IN, "<$file");	# no need for this...?

}
else
{
	$firstfile = 1;
}

open( OUTFILE, ">$OUT");

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 "%s\n", $marker);

}
else {
	# xxx.index.html already existed; use whatever initial
	# information was already there.
	open( OLD, "<$OLDOUT");
	while ( $line = <OLD>) {
		if ( $line =~ "<!-- Range list generated by wn_mkdigest") {
			print OUTFILE $marker, "\n";
			last;
		}
		else {
			print OUTFILE $line;
		}
	}
}

printf( OUTFILE "<ul>\n");

while ( $file = shift) {
	$startline=0;
	$linecnt=0;
	$startbyte=0;
	$bytecnt=0;
	$linelen=0;

	open( IN, "<$file");
	while ( $line = <IN> ) {
		$linecnt++;
		$linelen=length($line);
		if ( $line =~ /$separator/) {
			if ( $startline > 0 ) {
				&printline();
			}
			$startline = $linecnt;
			$startbyte = $bytecnt;
			if ( $skip2next) {
				$line = <IN>;
				$linecnt++;
				$bytecnt+=$linelen;
				$linelen=length($line);
			}
			$title = "";
		}
		if ( !$title && $line =~ s/^.*$section//) {
			$title = $line;
			chop( $title);
			$title =~ s/&/&amp;/g;
			$title =~ s/</&lt;/g;
			$title =~ s/>/&gt;/g;
		}
		$bytecnt+=$linelen;
	}
	&printline();
}


printf( OUTFILE "</ul>\n");

if ( $firstfile) {
	print OUTFILE $endmarker, "\n";
	print OUTFILE "</body>\n</html>\n";
}
else {
	# xxx.index.html already existed; use whatever trailing
	# information was already there.
	while ( $line = <OLD>) {
		if ( $line =~ "<!-- End of range list generated by wn_mkdigest") {
			last;
		}
	}
	print OUTFILE $endmarker, "\n";
	while ( $line = <OLD>) {
			print OUTFILE $line;
	}
	close( OLD);
}

close( OUTFILE);


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

