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

# Generate the table of contents for the PNG spec
# Usage: makecontents <master >output

$inchapter = 0;
$inlist = 0;

$Chapter = -1;
$Section = 0;
$Paragraph = 0;
$dt_level = '1';

while (<STDIN>) {

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

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

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

    # handle DT tag
    if (/<DT>.+NAME.+>/i) {
	if ($dt_level =~ /3/) {
         $Section++;
	 s|(<DT>[^>]+>)|$1$Chapter.$Section. |i;
     }
	if ($dt_level =~ /4/) {
         $Paragraph++;
	 s|(<DT>[^>]+>)|$1$Chapter.$Section.$Paragraph. |i;
     }
     }

    if (m|<H2><A NAME="([^"]+)">(.+)</A></H2>|i) {
	if ($inlist) {
		print STDOUT "</UL>\n";
		$inlist = 0;
	}
	if ($PN) {print STDOUT "<LI><A HREF=\"$1\">$2</A>!$1!\n";}
	else {print STDOUT "<LI><A HREF=\"$1\">$2</A>\n";}
	$chapter = $1;
	$inchapter = 1;
    }
    if ((m|<H3><A NAME="([^"]+)">(.+)</A></H3>|i) ||
        (($dt_level =~ /3/)&&(m|<DT><A NAME="([^"]+)">(.+)</A>|i) ) ) {
	if ($inpara) {
		print STDOUT "</UL>\n";
		$inpara = 0;
	}
	if (! $inlist) {
		print STDOUT "<UL>\n";
		$inlist = 1;
	}
	if ($PN) {print STDOUT "<LI><A HREF=\"$chapter#$1\">$2</A>!$1!\n";}
	else {print STDOUT "<LI><A HREF=\"$chapter#$1\">$2</A>\n";}
    }
    if ( (m|<H4><A NAME="([^"]+)">(.+)</A></H3>|i) ||
        (($dt_level =~ /4/)&&(m|<DT><A NAME="([^"]+)">(.+)</A>|i) ) ) {
	if (! $inpara) {
		$inpara = 1;
		print STDOUT "<UL>\n";
	}
	if ($PN) {print STDOUT "<LI><A HREF=\"$chapter#$1\">$2</A>!$1!\n";}
	else {print STDOUT "<LI><A HREF=\"$chapter#$1\">$2</A>\n";}
    }
}

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