#!/usr/local/bin/perl

# Generate the single-file HTML representation of the PNG spec
# Usage: makesingle <master >output

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

$pre_indent = '0';

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

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) {
#	  warn "Ignoring output to $1\n";
	  return;
	}

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

	# handle multi-link command
	if ($line =~ /<!-- MULTI LINK (\S+) (.+) -->/i) {
#	  warn "Ignoring multi-link command\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 @

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

	print STDOUT $line;
}
