#!/bin/csh -f

if ($#argv != 1) then
  echo "Usage: lat file"
  exit(1)
endif

set fileroot = $1:r

set exts = (aux)
# Or might want next line to remove or add e.g.: glo idx index lof lot toc
if (-f $fileroot.exts) set exts = (`cat $fileroot.exts`)

foreach ext ($exts)
  mv $fileroot.${ext}hold $fileroot.${ext} >& /dev/null
  cp -p $fileroot.$ext $fileroot.${ext}hold >& /dev/null
end

pdflatex $1 # used to be latex rather than pdflatex
set latexresult = $status
if ($latexresult) then
  echo "lat: exit status $latexresult from latex; keeping 'hold' files"
else
  grep '\\citation' $fileroot.aux | sort -u > $fileroot.newcitations
  # Remember: a || b executes b if a is unsuccessful (status >0)
  #           a && b executes b if a is successful (status 0)
  #    diff succeeds if no difference
  #    grep succeeds if something found
  if ( -s $fileroot.newcitations) then
    diff $fileroot.{new,}citations > /dev/null || \
        (echo CITATIONDIFF; mv $fileroot.newcitations $fileroot.citations; del . $fileroot.bbl; bibtex $fileroot; rm $fileroot.*hold; lat $fileroot)
    grep '\\bibcite' $fileroot.aux | sort -u > $fileroot.newbibcites
    diff $fileroot.{new,}bibcites > /dev/null || (echo BIBCITEDIFF; mv $fileroot.newbibcites $fileroot.bibcites; rm $fileroot.*hold; lat $fileroot)
  else
    rm $fileroot.newcitations
  endif
  grep -c 'Rerun to get cross-references right' $fileroot.log && (echo RERUNCROSSREFS; rm $fileroot.*hold; lat $fileroot)
  grep -c 'Rerun LaTeX' $fileroot.log && (echo RERUN; rm $fileroot.*hold; lat $fileroot)
  grep -c 'There were undefined references' $fileroot.log && echo 'UNDEFINED REFRENCES MAY BE DUE TO ERRONEOUS USE OF \\nofiles'
  grep -c 'Citation .* undefined.' $fileroot.log && echo 'UNDEFINED CITATION MAY BE DUE TO ERRONEOUS USE OF \\nofiles'
  rm $fileroot.*hold $fileroot.new{citations,bibcites} >& /dev/null
  # Maybe add in deletion of zero-sized .citations and .bibcites files.
endif
