#!/usr/local/bin/perl

# Generate a perl script to show cross references in the PNG spec;
# instead of just "see XYZ", the resulting text reads "see Section N, XYZ".
# Usage: makeshowxrefs <master >showxrefs; showxrefs <master >output

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

print STDOUT "\#!/usr/local/bin/perl\n";
print STDOUT "\# Mechanically generated by makeshowxrefs -- do not edit\n";
print STDOUT "while (<STDIN>) {\n";

while (<STDIN>) {

    # handle H2 tag
    if (m|<H2><A NAME="(.+)">(.+)</A></H2>|i) {
	$Chapter++;
	$Section = 0;
	$Paragraph = 0;
        print STDOUT "s|<A HREF=\"$1\">|<A HREF=\"$1\">Chapter $Chapter, |i;\n";
    }

    # handle H3 tag
    if (m|<H3><A NAME="(.+)">(.+)</A></H3>|i) {
	$Section++;
	$Paragraph = 0;
	$Label = $1;
	if ($Label =~ /^[A-Z]\./ || $Label =~ /^[A-Z][A-Z]\./) {
	    print STDOUT "s|<A HREF=\"$Label\">|<A HREF=\"$Label\">Section $Chapter.$Section, |i;\n";
	} else {
	    # Unabbreviated section names require special treatment
	    print STDOUT "s|<A HREF=\"([a-z]+)#$Label\">|<A HREF=\"\$1#$Label\">Section $Chapter.$Section, |i;\n";
	}
    }

    # handle H4 tag
    if (m|<H4><A NAME="(.+)">(.+)</A></H4>|i) {
	$Paragraph++;
	# Note: we assume all H4-level tags use abbreviated format,
	# if they are referenced at all.
        print STDOUT "s|<A HREF=\"$1\">|<A HREF=\"$1\">Paragraph $Chapter.$Section.$Paragraph, |i;\n";
    }
}

print STDOUT "print STDOUT \$_;\n";
print STDOUT "}\n";
