#!/usr/local/bin/perl -s

# Generate the HTML table of contents for the PNG spec
# Usage: makecontents [-PN] <master >output

$inseclist = 0;
$insubseclist = 0;

$Chapter = 0;
$Section = 0;
$Paragraph = 0;

print STDOUT "<UL>\n";

while (<STDIN>) {

    # number H2 tag
    if (/<H2>.+NAME.+>/i) {
         $Chapter++;
         $Section = 0;
         $Paragraph = 0;
	 s|(<H2>[^>]+>)|$1$Chapter. |i;
    }

    # number H3 tag
    if (/<H3>.+NAME.+>/i) {
         $Section++;
         $Paragraph = 0;
	 s|(<H3>[^>]+>)|$1$Chapter.$Section. |i;
    }

    # number H4 tag
    if (/<H4>.+NAME.+>/i) {
         $Paragraph++;
	 s|(<H4>[^>]+>)|$1$Chapter.$Section.$Paragraph. |i;
    }

    if (m|<H2><A NAME="([^"]+)">(.+)</A></H2>|i) {
	if ($insubseclist) {
		print STDOUT "</UL>\n";
		$insubseclist = 0;
	}
	if ($inseclist) {
		print STDOUT "</UL>\n";
		$inseclist = 0;
	}
	if ($PN) {print STDOUT "<LI><A HREF=\"$1\">$2</A>!$1!\n";}
	else {print STDOUT "<LI><A HREF=\"$1\">$2</A>\n";}
	$chapterfile = $1;
    }

    if (m|<H3><A NAME="([^"]+)">(.+)</A></H3>|i) {
	if ($insubseclist) {
		print STDOUT "</UL>\n";
		$insubseclist = 0;
	}
	if (! $inseclist) {
		print STDOUT "<UL>\n";
		$inseclist = 1;
	}
	if ($PN) {print STDOUT "<LI><A HREF=\"$chapterfile#$1\">$2</A>!$1!\n";}
	else {print STDOUT "<LI><A HREF=\"$chapterfile#$1\">$2</A>\n";}
    }

    if (m|<H4><A NAME="([^"]+)">(.+)</A></H4>|i) {
	if (! $insubseclist) {
		print STDOUT "<UL>\n";
		$insubseclist = 1;
	}
	if ($PN) {print STDOUT "<LI><A HREF=\"$chapterfile#$1\">$2</A>!$1!\n";}
	else {print STDOUT "<LI><A HREF=\"$chapterfile#$1\">$2</A>\n";}
    }
}

if ($insubseclist) {
    print STDOUT "</UL>\n";
}

if ($inseclist) {
    print STDOUT "</UL>\n";
}

print STDOUT "</UL>\n";
