#!/bin/sh

rm -rf $1.xcd

echo " --> running cdbpreproc"
cdbpreproc $1
if ! [ $? = 0 ]; then
   echo "cdbpreproc encountered an error"
   echo "Try running $1 through cbpreproc at the command line."
   exit 1
fi

echo " --> running cadabra"
cadabra --xcadabra < $1.cdb > $1.xcd
if ! [ $? = 0 ]; then
   echo "cadabra encountered an error"
   echo "Try running $1.cdb through cadabra at the command line."
   exit 1
fi

echo " --> running cdbmerge"
cdbmerge $1
if ! [ $? = 0 ]; then
   echo "cdbmerge encountered an error"
   echo "The most likely cause is a line of Cadabra output exceeded 20000 characters."
   echo "Is that what you expected?."
   exit 1
fi

echo " --> running cdbpstproc"
cdbpstproc $1 keep-tags
if ! [ $? = 0 ]; then
   echo "cdbpstproc encountered an error"
   echo "Try running $1.tex through cdbpstproc at the command line."
   exit 1
fi

mv $1.notag $1.tex

echo " --> running pdflatex"
pdflatex -halt-on-error -interaction=batchmode $1 > /dev/null
if ! [ $? = 0 ]; then
   echo "LaTeX encountered an error"
   echo "Try running $1.tex through latex at the command line."
   exit 1
fi

# if xpdf is not running, fire it up and display our file
# otherwise assume it's already displaying our file

num=`ps | grep xdvi | grep -v grep - | wc | cut -c1-8`
if ! [ $num == 1 ]; then
  xpdf -paper match -remote $1 $1.pdf &>/dev/null &
else
  xpdf -paper match -remote $1 $1.pdf &>/dev/null
fi

rm -rf $1.aux $1.log $1.xcd $1.eqn $1.tmp
