#!/usr/pkg/bin/perl

# Script type: perl

# troff2html - invoke troffcvt preprocessor and tc2html postprocessor

# Understands the usual troffcvt and tc2html arguments.  In addition,
# understands the following options:
# -n	no execution, just show commands that would be executed
# -p	don't run the postprocessors tc2html or tc2html-toc

# Adds the action file "actions-html" at the front of the argument list.

# Adds in redefinition files according to any macro package that is named
# in the command-line arguments.  For example, if "-ms" is specified on the
# command line, troff2html passes "-ms -a tc.ms -a tc.ms-html" to troffcvt.

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

# 03 Feb 97 V1.00
# - Created.

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

$troffcvt = "troffcvt";
$postproc = "tc2html";
$postproctoc = "tc2html-toc";

$noexec = 0;
$nopostproc = 0;

$tmp = "/tmp/tc2html$$";		# temporary filename

$preargs = "-a actions-html";
$postargs = "";

while (@ARGV)
{
	$_ = shift (@ARGV);		# get next argument
	if ($_ eq "-n")			# recognize and delete -n
	{
		$noexec = 1;
		next;
	}
	if ($_ eq "-p")			# recognize and delete -p
	{
		$nopostproc = 1;
		next;
	}
	if (!/^-./)			# not a flag, just a filename or "-"
	{
		$preargs .= " $_";
		next;
	}
	($opt, $rest) = /^-(.)(.*)/;
	if ($opt eq "m")		# -mxx macro package argument
	{
		die "$prog: -m requires macro package name\n" if $rest eq "";
		$preargs .= " -m$rest -a 'tc.m$rest' -a 'tc.m$rest-html'";
		next;
	}
	if ($opt =~ /^[ACl]$/)		# troffcvt arguments that stand alone
	{
		$preargs .= " -$opt";
		next;
	}
	if ($opt =~ /^[adrt]$/)		# troffcvt arguments that require an
	{				# additional argument
		if ($rest eq "")
		{
			die "$prog: -$opt requires following argument\n"
						if @ARGV == 0;
			$rest = shift (@ARGV);
		}
		$preargs .= " -$opt '$rest'";
		next;
	}
	if ($opt =~ /^[DE]$/)		# tc2html arguments that stand alone
	{
		$postargs .= " -$opt";
		next;
	}
	if ($opt =~ /^[T]$/)		# tc2html arguments that require an
	{				# additional argument
		if ($rest eq "")
		{
			die "$prog: -$opt requires following argument\n"
						if @ARGV == 0;
			$rest = shift (@ARGV);
		}
		$postargs .= " -$opt '$rest'";
		next;
	}
	warn ("Bad argument: -$opt\n");
}

if ($nopostproc)
{
	# basic translation
	$cmd = "$troffcvt $preargs";
	warn "$cmd\n" if $noexec;
	system $cmd if !$noexec;
}
else
{
	# basic translation
	$cmd = "$troffcvt $preargs | $postproc $postargs > $tmp";
	warn "$cmd\n" if $noexec;
	system $cmd if !$noexec;
	# move TOC to proper spot if there is one
	$cmd = "$postproctoc $tmp";
	warn "$cmd\n" if $noexec;
	system $cmd if !$noexec;
	# clobber temp file
	$cmd = "rm -f $tmp";
	warn "$cmd\n" if $noexec;
	unlink ($tmp) if !$noexec;
}

exit (0);
