#!/bin/sh

#
# latex2ps - translate TeX-file to PS und clean up tempfiles
#

DVIPSOPTS=''
LATEXOPTS=''
TEXFILE=''
FILEPREFIX=''
TIMES=x
INDEX='no'
USAGEMSG="USAGE:\n\
\t`basename $0` [-?] [dvipsopts] <file>\n\
OPTIONS:\n\
\t-?     prints usage message\n\
\t<file> name of latex file\n\
\t       extension 'tex' or '.tex' can be omitted\n\
\n\
\tother options are passed directly to dvips\n\
\tuseful option can be -Pcmz for type1 cm-fonts"


# argument loop
while [ $# -gt 0 ]
do
	case "$1" in
		-\?)   echo -e "$USAGEMSG"; exit 0;;
		-*) DVIPSOPTS="$DVIPSOPTS $1";;
		*)    TEXFILE="$1";;
	esac
	shift
done
if [ -z "$TEXFILE" ]
then
	echo -e "$USAGEMSG" 1>&2
	exit 1
fi

# find texfile
if [ ! -e $TEXFILE ]
then
	test -e ${TEXFILE}.tex && TEXFILE=${TEXFILE}.tex
	test -e ${TEXFILE}tex && TEXFILE=${TEXFILE}tex
fi
if [ ! -e "$TEXFILE" ]
then
	echo -e "$USAGEMSG" 1>&2
	exit 1
fi

# do we need to call makeindex?
grep -q '^[^%]*\\makeindex' $TEXFILE && INDEX="yes"

# some files need double processing
grep -q '\\ref{\|\\cite{\|\\tableofcontents\|{longtable' $TEXFILE && \
	TIMES="x x"

# translate
FILEPREFIX=`basename $TEXFILE .tex`
if [ "$INDEX" = "yes" ]
then
	latex $TEXFILE && latex $TEXFILE && makeindex $FILEPREFIX && latex $TEXFILE
	RC=$?
else
	for t in $TIMES
	do
		latex $TEXFILE 
		RC=$?
		test $RC = 0 || break
	done
fi
if [ $RC = 0 ]
then
	dvips $DVIPSOPTS -o $FILEPREFIX.ps $FILEPREFIX.dvi
fi

# clean up
rm -f $FILEPREFIX.dvi $FILEPREFIX.log $FILEPREFIX.aux \
	$FILEPREFIX.toc $FILEPREFIX.out \
	$FILEPREFIX.idx $FILEPREFIX.ind $FILEPREFIX.ilg

exit $RC
