#!/bin/sh

LATEX=latex
PS2PDF=ps2pdf
DVIPS=dvips


function usage() { 
	echo -n `basename $0`
	echo    ":"
	echo
	echo -n "    usage: "
	echo -n `basename $0`
	echo -n " [-dvi] [-ps] [-pdf] [-aux] [-log] <file>"
	echo
	echo 
	echo    "        -dvi, -ps, -pdf    one or more output formats  must be selected."
	echo    "        -aux, -log         optionally keep the output from the latex run" 
	echo
}

output_dvi="no"
output_ps="no"
output_pdf="no"
output_log="no"
output_aux="no"
filename=""
for arg in $@; do
	case $arg in
		-dvi) output_dvi="yes"
		;;
		-ps) output_ps="yes"
		;;
		-pdf) output_pdf="yes"
		;;
		-log) output_log="yes"
		;;
		-aux) output_aux="yes"
		;;
		*) filename=$arg
		;;
	esac
done


if [ $output_dvi == "no" ] && 
   [ $output_ps == "no" ] &&
   [ $output_pdf == "no" ]; then
	usage;
	exit;
fi

if [ -z $filename ]; then
	usage;
	exit;
fi


removefiles="aux log dvi ps pdf"

# check if the file is relative or absolute
oldpwd=`pwd`
d=`dirname "$filename"`
f=`basename "$filename"`
str=${filename:0:1}

if [ $str == "/" ]; then
	absfilename=$filename
else
	absfilename=`pwd`/$filename
fi

echo "Processing: $absfilename"

filenoext=`basename $absfilename .tex`
tempfiledvi=/tmp/$filenoext.dvi
outputfileps=$filenoext.ps
outputfilepdf=$filenoext.pdf

# make sure all the temporary files go into /tmp
cd /tmp

$LATEX -interaction=nonstopmode "$absfilename"

if [ $output_pdf == "yes" ] ||
   [ $output_ps  == "yes" ]; then

	$DVIPS -f $tempfiledvi > $outputfileps
fi


if [ $output_dvi == "yes" ]; then
	cp $tempfiledvi $oldpwd
fi
if [ $output_ps == "yes" ]; then
	cp $outputfileps $oldpwd
fi
if [ $output_pdf == "yes" ]; then
	$PS2PDF $outputfileps $outputfilepdf
	cp $outputfilepdf $oldpwd
fi


if [ $output_log == "yes" ]; then
	cp /tmp/$filenoext.log $oldpwd
fi
if [ $output_aux == "yes" ]; then
	cp /tmp/$filenoext.aux $oldpwd
fi

for i in $removefiles; do
	rm -f "/tmp/$filenoext.$i";
done
