#!/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 XYZ (Section N)".
# Usage: makeshowxrefs <master >showxrefs; showxrefs <master >output

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

print STDOUT <<'ENDLIT';
#!/usr/local/bin/perl
# Mechanically generated by makeshowxrefs -- do not edit
$sectionID = "";		# indicates no substitution active
while (<STDIN>) {
  checkformatch:
    for (;;) {
	if ($sectionID) {
	    if (s|</A>| ($sectionID)</A>|i) {
		# change format if at end of parenthetical remark
		s| \($sectionID\)</A>\)|, $sectionID</A>)|;
		s| \($sectionID\)</A>\.\)|, $sectionID</A>.)|;
		$sectionID = "";
	    }
	}
	if (! m|<A HREF="([^"]+)">|i) {
	    last checkformatch;	# No more to do on this line
	}
	$tag = $1;
	warn "Mismatched <A>...</A> before $_" if $sectionID;
	if (m|^(.*<A HREF="[^"]+">)(.*)$|i) {
	    print STDOUT $1;
	    $_ = $2 . "\n";
	} else {
	    warn "Failed to split $_";
	}
ENDLIT

while (<STDIN>) {

    # handle H2 tag
    if (m|<H2><A NAME="(.+)">(.+)</A></H2>|i) {
	$Chapter++;
	$Section = 0;
	$Paragraph = 0;
	print STDOUT <<"ENDCODE";
	if (\$tag eq "$1") {
	    \$sectionID = "Chapter $Chapter";
	    next checkformatch;
	}
ENDCODE
    }

    # 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 <<"ENDCODE";
	if (\$tag eq "$Label") {
	    \$sectionID = "Section $Chapter.$Section";
	    next checkformatch;
	}
ENDCODE
	} else {
	    # Unabbreviated section names require special treatment
	    print STDOUT <<"ENDCODE";
	if (\$tag =~ m|#$Label\$|) {
	    \$sectionID = "Section $Chapter.$Section";
	    next checkformatch;
	}
ENDCODE
	}
    }

    # 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 <<"ENDCODE";
	if (\$tag eq "$Label") {
	    \$sectionID = "Paragraph $Chapter.$Section.$Paragraph";
	    next checkformatch;
	}
ENDCODE
    }
}

# Enable this for debugging
print STDOUT <<'ENDLIT';
#	warn "Did not recognize tag $tag\n";
ENDLIT

print STDOUT <<'ENDLIT';
    } # end of checkformatch loop
  print STDOUT $_;
}
ENDLIT
