#!/usr/local/bin/perl

# Generate the multi-file HTML representation of the PNG spec
# Usage: makemulti <master

# table of chapter abbreviations
$cname{"DR"} = "DataRep";
$cname{"C"} = "Chunks";
$cname{"E"} = "Encoders";
$cname{"D"} = "Decoders";
$cname{"R"} = "Rationale";
$cname{"CR"} = "Credits";

$chapter = '-1';
$section = '0';
$paragraph = '0';

$pre_indent = '0';

open(OUTPUT, ">png.html") || die "Couldn't write png.html: $!\n";

open(HEADER, ">header-tmp") || die "Couldn't write header-tmp: $!\n";
$header_open = 1;

while (<STDIN>) {
	&process_line($_);
}

close OUTPUT;
unlink "header-tmp";
exit;

sub process_line {
	local($line) = @_;

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

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

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

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

        # handle PRE tag
        if ($line =~ /<.PRE>/) {$pre_indent = 0;}
        if ($pre_indent =~ /1/) {$line =~ s|^|   |;}
        if ($line =~ /<PRE>/) {$pre_indent = 1;}

	# handle new-file command
	if ($line =~ /<!-- NEW FILE (\S+) -->/i) {
	  print OUTPUT "\n</BODY>\n</HTML>\n";
	  close OUTPUT;
	  open(OUTPUT, ">$1") || die "Couldn't write $1: $!\n";
	  if ($header_open) {
		warn "NEW FILE before END HEADER!?\n";
	  } else {
	    open(INPUT, "header-tmp") || die "Couldn't read header-tmp: $!\n";
	    while (<INPUT>) {
		print OUTPUT $_;
	    }
	    close INPUT;
	  }
	  return;
	}

	# handle end-header command
	if ($line =~ /<!-- END HEADER -->/i) {
	  if ($header_open) {
		close HEADER;
		$header_open = 0;
	  } else {
		warn "Ignoring duplicate end-header command\n";
	  }
	  return;
	}

	# handle multi-link command
	if ($line =~ /<!-- MULTI LINK (\S+) (.+) -->/i) {
	  print OUTPUT "<P>\n<A HREF=\"$1\">$2</A>\n";
	  return;
	}

	# handle inclusion
	if ($line =~ /<!-- INCLUDE (\S+) -->/i) {
	  if (open(INPUT, $1)) {
		while (<INPUT>) {
			&process_line($_);
		}
		close INPUT;
	  } else {
		warn "Couldn't open $1: $!\n";
	  }
	  return;
	}

	# note: ignore HREFs containing / or @

	# expand abbreviated section crossreferences
	$line =~ s|HREF="([^"/@#\.]+)\.([^"/@#]+)"|HREF="$cname{$1}#$1.$2"|gi;
	# fix general section crossreferences
	$line =~ s|HREF="([^"/@#\.]+)#([^"/@#]+)"|HREF="PNG-$1.html#$2"|gi;
	# fix chapter crossreferences
	$line =~ s|HREF="([^"/@#\.]+)"|HREF="PNG-$1.html"|gi;

	print OUTPUT $line;
	print HEADER $line if $header_open;
}
