
# Script type: perl

# tc2html-toc - examine tc2html output for a table of contents and move
# it to the correct location.

# The TOC is indicated by two HTML comments:
# <!-- TOC BEGIN -->
# <!-- TOC END -->

# The location to which the TOC should be moved may be specified explicitly
# in the troff input files by invoking the .H*toc*title request, which writes
# the title and this HTML comment:
# <!-- INSERT TOC HERE -->

# Macro package redefinitions can make a guess about where the TOC should be
# located in the absence of an explicit location marker.  To do so, the
# redefinition should write the following advisory marker comment:
# <!-- INSERT TOC HERE, MAYBE -->

# 20 Feb 97
# Paul DuBois
# dubois@primate.wisc.edu
# http://www.primate.wisc.edu/people/dubois

# 20 Feb 97 V1.00
# - Created.

($prog = $0) =~ s|.*//||;		# get script name for messages

@line = <>;			# slurp entire input

@toc = ();
$bodyloc = -1;			# line number of <BODY>
$tocloc = -1;			# line number of TOC location marker
$tocloc2 = -1;			# line number of advisory TOC location marker
$tocbegin = -1;			# beginning line number of TOC
$tocend = -1;			# ending line number of TOC

$lno = -1;
foreach (@line)
{
	++$lno;
	if (/^<BODY>/)
	{
		$bodyloc = $lno;
		next;
	}
	next unless /^<!--/;	# not a comment, ignore
	if (/^<!-- INSERT TOC HERE -->/)
	{
		$tocloc = $lno;
	}
	elsif (/^<!-- INSERT TOC HERE, MAYBE -->/)
	{
		$tocloc2 = $lno;
	}
	elsif (/^<!-- TOC BEGIN -->/)
	{
		$tocbegin = $lno;
	}
	elsif (/^<!-- TOC END -->/)
	{
		$tocend = $lno;
	}
}

# use advisory location if no explicit location was found
# (if no advisory was found, either, move to the beginning of
# the document body.)

$tocloc = $tocloc2 if $tocloc < 0;
$tocloc = $bodyloc if $tocloc < 0;

# Die if there is a TOC but the TOC location cannot be determined

if ($tocbegin >= 0 && tocloc < 0)
{
	die "$prog: cannot determine where to move TOC\n";
}

# Check some anomalous conditions (which should not occur)

if ($tocloc > $tocbegin && $tocloc < $tocend)
{
	die "$prog: TOC location marker is in middle of TOC!\n";
}

# Move TOC to desired location if one was found.  (If none was found,
# the input is written to the output unchanged.)

if ($tocbegin >= 0)
{
	# extract TOC from document
	@toc = splice (@line, $tocbegin, $tocend - $tocbegin + 1);
	# adjust location if desired location follows TOC
	$tocloc -= scalar (@toc) if $tocloc > $tocbegin;
	# reinsert TOC at correct location
	splice (@line, $tocloc+1, 0, @toc);
}

print @line;

exit (0);
