#!/bin/sh
# tf: a simple script to tex and display a file
# tries to decide between latex, texsis, and plain tex

# Mike Creutz

# extract the base file name
filename=$1
directory=`dirname $1`

# trickery so can use file, file.tex, and file. 
# different implementations of basename make this tricky
filename=`basename $filename  .tex`
if [ ! -r $directory/$filename.tex ]
then
 filename=`basename $filename .`
fi

if [ ! -r $directory/$filename.tex ]
then
 commandname=`basename $0`
 echo "input file not found"
 echo "$commandname usage: $commandname "
 echo "  processes (.tex)"
 echo "  attempting to decide automatically between tex, latex, and texis"
 echo "  If successful, use dvips to make a postscript file."
 echo "  If x is available, display the result with ghostview."
 echo "  (including the extension .tex on the filename is optional)"
 exit
fi

# remove old files
if test -f $filename.dvi
then
 rm $filename.dvi 
fi

if test -f $filename.aux
then
 rm $filename.aux
fi

if test -f $filename.ps
then
 rm $filename.ps
fi

# is it latex?
if head -500 $directory/$filename.tex | grep -s "{document"
then
 latex $directory/$filename 

# is bibtex involved
if grep \bibliography $directory/$filename.tex
then
 bibtex $directory/$filename
 latex $directory/$filename 
fi

 if grep Rerun $filename.log 
 then
# do it twice because of silly aux files
 latex $directory/$filename
 fi
else
# is it texsis; assumes the word texsis is near the beginning of the file
 if head -50 $directory/$filename.tex | grep -s -i texsis
 then
  texsis $directory/$filename
 else
# assume it is plain tex
  tex $directory/$filename
 fi
fi

if test -f $filename.log
then
  if grep "^!" $filename.log
  then
   exit
  fi
fi

if test -f $filename.dvi
then
# make a postscript file
 dvips -o $filename.ps $filename
 rm $filename.dvi

 if [ ! -z "$DISPLAY" ]
# view the file  
 then
#   if test -x /usr/local/bin/gv || test -x /usr/bin/X11/gv
  if which gv
   then
    viewer=gv
   else
    viewer=ghostview
   fi
   echo the display is set to $DISPLAY
   echo starting $viewer to see the file
   $viewer "$filename".ps
 else
   echo Since the display is not set 
   echo I will not try to display the result
   echo the postscript result of $0 is in the file $filename.ps
 fi
fi