#!/bin/sh
# makempx -- make an MPX file from a MetaPost source file.
# Based on John Hobby's original (though there's not much of it left by now).

: ${MPTOTEX="mpto -tex"}
: ${MPTOTR="mpto -troff"}
: ${DVITOMP=dvitomp}
: ${DMP=dmp}
: ${NEWER=newer}
: ${TEX=tex}
: ${TROFF='eqn -d\$\$ | troff -Tpost'}

# These names are documented in the MetaPost manual, so it's
# unwise to change them.
ERRLOG=mpxerr.log		# file for an error log if necessary
TEXERR=mpxerr.tex		# file for erroneous TeX if any
DVIERR=mpxerr.dvi		# troublesome dvi file if any
TROFF_IN_ERR=mpxerr		# file for erroneous troff input, if any
TROFF_OUT_ERR=mpxerr.t		# file for troublesome troff output, if any


usage="Usage: $0 MPFILE MPXFILE.
If MPXFILE is older than MPFILE, update it by running
\`$MPTOTEX', \`$TEX', and \`$DVITOMP'.
The current directory is used for writing temporary files.
Errors are left in mpxerr.{tex,log,dvi}."

#####################################################
# Everything below here should seldom need changing #
#####################################################
MPFILE=$1			# input file
MPXFILE=$2			# output file
NL='
'

trap "rm -f mpx$$.* $ERRLOG; exit 4" 1 2 15


if $NEWER $MPFILE $MPXFILE
then
    $MPTOTEX $MPFILE >mpx$$.tex 2>$ERRLOG
    case $? in
    0)	;;
    *)	echo "$NL"'Command failed: ' $MPTOTEX $MPFILE
	cat $ERRLOG
	rm -f mpx$$.tex
	exit 1
	;;
    esac

    $TEX '\batchmode\input 'mpx$$ >/dev/null
    case $? in
    0)	;;
    *)	mv -f mpx$$.tex $TEXERR
	mv -f mpx$$.log $ERRLOG
	echo "$NL"'Command failed:' $TEX $TEXERR $NL'See' $ERRLOG
	rm -f mpx$$.*
	exit 2
	;;
    esac

    $DVITOMP mpx$$.dvi $MPXFILE >$ERRLOG
    case $? in
    0)	;;
    *)  mv -f mpx$$.dvi $DVIERR
	echo "$NL"'Command failed:' $DVITOMP $DVIERR
	cat $ERRLOG
	rm -f mpx$$.*
	exit 3
	;;
    esac

    rm -f $ERRLOG mpx$$.*
fi
