#!/bin/bash
#
# Automate running LaTeX

program=`basename $0`
tex=latex
format=dvi
appbase=$HOME/lib/tex
rerun='Rerun to get cross-references right'
maxruns=4

export TEXINPUTS=$appbase/macros::

TEMP=`getopt -o n --long tex:,pdf,help,dvi,clean,maxruns: \
     -n $program -- "$@"`
if [ $? != 0 ] ; then echo "$program: use $program --help for options" >&2 ; exit 1 ; fi
eval set -- "$TEMP"

while true ; do
    case "$1" in
        --pdf)
	    tex=pdflatex
	    format=pdf
	    shift ;;
        --dvi)
	    tex=latex
	    format=dvi
	    shift ;;
	--maxruns)
	    maxruns="$2"
	    shift 2 ;;
	--help)
	    echo "Usage:"
	    echo ""
	    echo "    $program [options] file"
	    echo ""
	    echo "Options:"
	    echo ""
	    echo "    --pdf        Use pdflatex and make .pdf images"
	    echo "    --dvi        Use latex"
	    echo "    --help       Print this message"
	    echo "    --maxruns=#  Specify maximum # runs"
	    echo "    --clean      Just remove TeX temporary files"
	    exit 0 ;;
	--clean)
	    rm -f *.idx *.ind *.ilg *.aux *.log *.lof *.out *.toc
	    exit 0
	    ;;
        --)
	    shift ; break ;;
	*)
	    echo "Internal error!" ; exit 1 ;;
    esac
done

file="$1"

# ensure .tex suffix

if [ ${file%.tex} = $file ]; then
    file=$file.tex
fi

doc=${file%.tex}

if [ -r Makefile ] && grep -q '^tex:' Makefile; then
    make tex
fi

cont=yes
done=0
while [ $cont = "yes" ]; do

					# fix index problems
    if [ -r $doc.idx ]; then
        if [ -x $appbase/correctindex ]; then
	    $appbase/correctindex $doc.idx
	fi
	cp $doc.idx $doc.idx.$$
	if [ -r $appbase/makeindex.ist ]; then
	    makeindex -s $appbase/makeindex.ist $doc
	else
	    makeindex $doc
	fi
    fi 
    if [ -r $doc.blg ]; then
        bibtex $doc
    fi
    if [ `basename $tex` = pdflatex -a -r $appbase/Makefile.pdf ]; then
        make -f $appbase/Makefile.pdf
    fi
    rm -f $doc.log
    $tex $doc
    if [ $? != 0 ]; then
        rm -f $doc.idx.$$
        exit $?;
    fi
    if grep -q "$rerun" $doc.log; then
        echo "*** Cross-references changed.  Rerunning $tex ***"
    else
        if [ -r $doc.idx -a $doc.idx.$$ ]; then
	   if cmp -s $doc.idx $doc.idx.$$; then
	      cont=no
	   else
	      echo "*** Index changed.  Rerunning $tex ***"
	   fi
        fi
    fi
    rm -f $doc.idx.$$
    done=$(($done+1))
    if [ $done = $maxruns ]; then cont=no; fi
done


