#! /bin/sh
# doctype - synthesize proper command line for troff
#	adapted from Kernighan & Pike
#	last edit:	86/08/25	D A Gwyn
#	SCCS ID:	@(#)doctype.sh	1.8
# adapted to UofT: now understands -man, -me, -ms.zoo & -mz /Geoff Collyer
PATH=/bin:/usr/bin; export PATH
MACDIR=/usr/lib/tmac

: ${troff=troff}
eopt=
macs=
opts=
topt=
for arg
do
	case "$arg" in
	-e)	eopt="$arg";		shift;;
	-m*)	macs="$macs $arg";	shift;;
	-T*)	topt=" $arg";		shift;;
	--)				shift;	break;;
	-)					break;;
	-*)	opts="$opts $arg";	shift;;
	*)					break;;
	esac
done

if [ $# -gt 0 ]
then	s="cat $* | "
else	s=
fi

cat >/tmp/dt$$ <<'!'
/^\.EQ/ { eqn++ }
/^\.TS/ { tbl++ }
/^\.\[/ { refer++ }
/^\.P$/ { mm++ }
/^\.PP/ { ms++ }
/^\.LP/ { leftpara++ }
/^\.PS/ { pic++ }
/^\.TH/ { man++ }
/^\.G1/ { grap++ }
/^\.IS/ { ideal++ }
/^\.(SE|HS|BR|IL)/ { mszoo++ }
/^\.(SP|NF)/ { mz++ }
/^\.pp/ { me++ }
END {
	if (refer > 0)	printf "refer | "
	if (grap > 0)	printf "grap | "
	if (grap > 0 || pic > 0)	printf "_PIC_ | "
	if (ideal > 0)	printf "ideal | "
	if (tbl > 0)	printf "tbl | "
	if (eqn > 0)	printf "_EQN_ | "
	printf "_TROFF_"
	if (grap > 0 || pic > 0)	printf " -mpic"
	if (leftpara && man == 0)	ms++
	if (mm > 0)	printf " -mm"
	else if (man > 0)	printf " -man"
	else if (ms > 0 && mszoo > 0)	printf " -ms.zoo"
	else if (ms > 0)	printf " -ms"
	else if (mz > 0)	printf " -mz"
	else if (me > 0)	printf " -me"
	printf " -\n"
}
!
t=`cat $* |
	egrep '^\.(EQ|TS|\[|P|LP|TH|G1|IS|SE|HS|BR|IL|SP|NF|pp)' |
	sort -u |
	awk -f /tmp/dt$$ |
	sed	-e s/_PIC_/"pic$topt"/ \
		-e s/_EQN_/"eqn$topt"/ \
		-e s/_TROFF_/"$troff$topt$opts$macs"/ \
		 `
#		-e s%' -m'%" $MACDIR/tmac."%g \
rm -f /tmp/dt$$

if [ -n "$eopt" ]
then	eval "$s$t"
else	echo $s$t
fi
