#! /bin/sh
#ident $Revision: 1.22 $
#
#	Files whose first line is
#		'\"! text
#	are processed by the command line "text" with the file provided
#	as the standard input.
#	Files whose first line is
#		'\"macro name
#	where "name" is the name of a file in TMMACRO will be run off with
#	that macro package.  "name"s begining "-" will be flag arguments
#	to nroff.
#

# since mmdoc is recursive when tbl or eqn are required, set PATH so that
# it can find itself
PATH=${TOOLROOT}/usr/lib/doc/tools:$PATH

umask 0		#	nroff must be able to write into files it closes
while [ -n "$1" ]
do
	case $1 in
	-T* )
		TERM=`expr $1 : '-T\(.*\)'`
		case ${TERM} in
			psc)
				post="|psdit |lp -oh"
				flavor=troff
				export TERM
				;;

			PS)
				post="|psdit"
				flavor=troff
				TERM=psc
				export TERM
				;;
			*)
				post=
				flavor=nroff
				;;
		esac
		export post flavor
		;;
	-?* )
		flags="$flags $1"
		export flags
		;;
	- | * )
		break
	esac
	shift
done
if [ $# = 0 ]
then
	set -- -
fi
for i
{
	if [ "$i" != "-" -a ! -s "$i" ]
	then
		echo "Cannot input file: $i"
		continue
	fi	
	case $i in
	- )
		;;
	* )
		Line1=`line <$i`
	esac

	MacrO=${TMMACRO}

	case "${Line1}" in
	"'\\\"!"* )
		cmd=`echo "${Line1}"  |  sed 's/^....//'`
		if [ "$flavor" != troff ]
		then
			cmd=`echo " ${cmd} " | sed 's/ eqn / neqn /'`
			cmd=`echo " ${cmd} " | sed 's/ tbl / tbl -TX /'`
		fi
		Line1=`sed -n -e 2p -e 2q ${i}`
		export Line1
		if [ "$flavor" = troff ]
		then
			eval '<$i' $cmd
		else
			TERM=lp
			eval '<$i' $cmd
		fi
		;;
	"'\\\"macro"* )
		cmd=`echo "${Line1}"  |
			sed '	s/.."macro//'"
				s:[ 	]\([^- 	]\): ${TMMACRO?}/\1:g"`
		cmd=`echo $cmd|sed "s;[ 	]*.*/stdmacro;${MacrO?}/stdmacro;"`
		cmd="$cmd $OTHERFILES"
		if [ "$flavor" = troff ]
		then
			case "$cmd" in
			*stdmacro*)
				flags="${flags} -rs1"
			esac
			eval troff -T${TERM} ${flags} ${cmd} $i ${post}
		else
			eval nroff ${flags} ${cmd} $i
		fi
		;;
	* )
		echo "mmdoc: error (typo?) in this line: ${Line1}" >&2
		continue
		;;
	esac
}
