#! /bin/sh
# AWFLIB is where the pieces live
AWFLIB=${AWFLIB-/usr/pkg/share/awf}
AWK=${AWK-/usr/bin/awk}

tmp=/tmp/awp$$			# tempfile for building pass 2
errs=/tmp/awe$$		# error messages (awk can't send to stderr)

case "$1" in
-ms)	mac=ms	;;
-man)	mac=man	;;
*)	echo "$0: must specify -ms or -man" >&2
	exit 2
	;;
esac
shift

dev="$AWFLIB/dev.$TERM"
if test ! -r $dev
then
	dev="$AWFLIB/dev.dumb"
fi

trap "rm -f $tmp $errs ; exit 0" 0 1 2

# build the full, macro-set-dependent, pass-2 awk program
(
	sed -n '1,/^#include/p' $AWFLIB/pass2.base
	cat $AWFLIB/pass2.$mac
	sed -n '/^#include/,$p' $AWFLIB/pass2.base
) >$tmp

# do it
(
	echo ".^x $errs"
	echo ".^b"
	echo ".^# 1 <prolog>"
	cat $dev $AWFLIB/common $AWFLIB/mac.$mac
	if test " $*" = " "
	then
		echo ".^# 1 <stdin>"
		cat
	else
		for f
		do
			echo ".^# 1 $f"
			cat $f
		done
	fi
	echo ".^e"
) | $AWK -f $AWFLIB/pass1 | $AWK -f $tmp | $AWK -f $AWFLIB/pass3

# error messages, if any
if test -s $errs
then
	cat $errs >&2
	exit 1
else
	exit 0
fi
