#! /bin/csh -f
#
# Run latex at least once.  If there are undefined citations, run bibtex
# and then additional latex runs.  Keep going until most undefined
# references and label changes are gone.
#
#   runlatex [-bib bibdirectory] [-bibonly bibdirectory] [-onetrip]
#           file.tex
#
#   -bib bibdirectory:
#
#       Add bibdirectory to BIBINPUTS before runing bibtex.
#
#   -bibonly bibdirectory:
#
#       Set BIBINPUTS to bibdirectory before runing bibtex.
#
#   -nobib:
#
#       Don't run bibtex, whatever the other flags.
#
#   -onetrip:
#
#       Run latex only once, whether or not there are unresolved
#       labels and references.
#
#   -pdf:
#
#       Produce PDF output rather than Postscript.
#
#   -pdfprinter:
#
#       Produce PDF output for printing on high(ish) quality printers
#
#   -pdfprepress:
#
#       Produce even higher quality PDF output than with -pdfprinter
#
#   -pdfimage:
#
#       Produce PDF output with maximum quality images
#
#   -norotate
#
#       Don't auto-rotate PDF pages.  Used mostly with draftdatetime package
#
#   -a4:
#
#       a4 paper (for Prosper and documents from/for Europe)
#
#   -clean:
#
#       Clean up intermediate files, leaving only output file.
#
# Bugs:
#
#   Doesn't check for failures in bibtex.
#

set max_run_count = 3   # Maximum number of LaTeX runs after bibtex

set norotateflag	# in case its not used

while ( $#argv >= 1 )

    if ( "$argv[1]" !~ \-* ) \
        break

    switch ( "$argv[1]" )

    case "-bib"
    case "--bib"
        if ( $#argv < 2 ) then
            echo "Need to specify bibliography directory\!"
            exit 1
        endif
        if ( ! $?bibinputs ) \
            set bibinputs = ""
        set bibinputs = ${bibinputs}:$argv[2]
        shift
        breaksw

    case "-bibonly"
    case "--bibonly"
        if ( $#argv < 2 ) then
            echo "Need to specify bibliography directory\!"
            exit 1
        endif
        unsetenv BIBINPUTS
        if ( ! $?bibinputs ) then
            set bibinputs = $argv[2]
        else
            set bibinputs = ${bibinputs}:$argv[2]
        endif
        shift
        breaksw

    case "-nobib"
    case "--nobib"
        set nobib
        breaksw

    case "-onetrip"
    case "--onetrip"
        set onetrip
        breaksw

    case "-pdf"
    case "--pdf"
        set pdf
        set pdfflags = "-dCompatibilityLevel=1.4"
        breaksw

    case "-pdfprinter"
    case "--pdfprinter"
        set pdf
        set pdfflags = "-dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer"
        breaksw

    case "-pdfprepress"
    case "--pdfprepress"
        set pdf
        set pdfflags = "-dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress"
        breaksw

    case "-pdfimage"
    case "--pdfimage"
        set pdf
        # There must be a better way...
        set pdfflags = ( -dPDFSETTINGS=/prepress \
	    -dCompatibilityLevel=1.4 \
	    -dAutoFilterColorImages=false \
	    -dAutoFilterGrayImages=false \
	    -dColorImageFilter=/FlateEncode \
	    -dGrayImageFilter=/FlateEncode \
	    -dMonoImageFilter=/FlateEncode \
	    -dDownsampleColorImages=false \
	    -dDownsampleGrayImages=false )
        breaksw

    case "-norotate"
    case "--norotate"
        set norotateflag = "-dAutoRotatePages=/None"
        breaksw

    case "-a4"
    case "--a4"
    case "-A4"
    case "--A4"
        set a4
        breaksw

    case "-clean"
    case "--clean"
        set clean
        breaksw

    case "-nooutput"
    case "--nooutput"
    	set nooutput
        breaksw

    default:
        echo "runlatex: unknown flag or argument ($argv[1])\!"
        exit 1
        breaksw

    endsw

    shift

end

if ( $#argv < 1 ) then
echo "runlatex [-bib bibdir] [-bibonly bibdir] [-onetrip] [-pdf] [-a4] file.tex"
    exit 1
endif

if ( $?a4) then
    set a4flag = "-t a4"
    setenv GS_OPTIONS "-sPAPERSIZE=a4"
else
    set a4flag = "-t letter"
    setenv GS_OPTIONS "-sPAPERSIZE=letter"
endif

set basename = $argv[1]:r

set latexlog = runlatex.logfile.$$  # try to avoid filename conflicts!

onintr interrupt

echo runlatex: latex $argv[1-]
echo ""

latex $argv[1-] | tee $latexlog
if ( $status != 0 ) then
    echo "abnormal termination..."
    /bin/rm -f $latexlog
    exit 1
endif

if ( $?onetrip ) goto skipbibtex

grep 'LaTeX Warning: Citation.*undefined' $latexlog > /dev/null
set runbibtex = $status
grep 'Package natbib Warning: Citation.*undefined' $latexlog > /dev/null
set runbibtexnatbib = $status

if ( ( $runbibtex == 0 ) || ( $runbibtexnatbib == 0 ) ) then

    if ( $?bibinputs ) then
        if ( $?BIBINPUTS ) then
            setenv BIBINPUTS ${BIBINPUTS}:$bibinputs
        else
            setenv BIBINPUTS $bibinputs
        endif
    endif

    echo ""
    echo runlatex: bibtex $basename
    echo ""

    bibtex $basename
    latex $argv[1-] | tee $latexlog

endif

if ( $?nobib ) goto skipbibtex

if ( { grep -s 'LaTeX Warning: There were undefined references' $latexlog } || \
    { grep -s 'LaTeX Warning: Label(s) may have changed. Rerun to get' \
        $latexlog } || \
    { grep -s 'LaTeX Warning: Citation.*undefined' $latexlog } ) \
    set rerun

set run_count = 1

while ( $?rerun && ( $run_count <= $max_run_count ) )

    echo ""
    echo runlatex: latex $argv[1-]
    echo ""

    latex $argv[1-] | tee $latexlog

    if ( $status != 0 ) then
        echo "abnormal termination..."
        /bin/rm -f $latexlog
        exit 1
    endif

    unset rerun

    if ( { grep -s 'LaTeX Warning: There were undefined references' \
            $latexlog } || \
       { grep -s 'LaTeX Warning: Label(s) may have changed. Rerun to get' \
            $latexlog } || \
       { grep -s 'LaTeX Warning: Citation.*undefined' $latexlog } ) \
        set rerun

    @ run_count = $run_count + 1

end

if ( $?rerun ) then
    echo ""
    echo "runlatex: references still unresolved\!"
    echo ""
endif

skipbibtex:

if ( $?nooutput ) goto interrupt

if ( $?pdf ) then
    dvips -Ppdf -G0 $a4flag -o - $basename.dvi | \
        ps2pdf $pdfflags $norotateflag - $basename.pdf

    # dvips -Ppdf -G0 $a4flag -o - $basename.dvi | \
    #   ps2pdf $pdfflags - $basename.pdf
else
    dvips -Ppdf -G0 $a4flag -o - $basename.dvi >$basename.ps
endif

interrupt:
/bin/rm -f $latexlog

if ( $?clean ) then
    /bin/rm -f  \
        ${basename}.aux \
        ${basename}.dvi \
        ${basename}.log \
        ${basename}.toc \
        ${basename}.bbl \
        ${basename}.blg \
        ${basename}.adx \
        ${basename}.and \
        ${basename}.ilg \
        ${basename}.fff \
        ${basename}.ttt \
        ${basename}.lof \
        ${basename}.cb \
        ${basename}.idx \
        ${basename}.thm \
        ${basename}.out
endif
