#! /bin/sh
#
# Convert Hyperlatex documents to dvi, html, or gif's

if [ -z "$HYPERLATEX_DIR" ]; then
  HYPERLATEX_DIR="/usr/lib/hyperlatex"
  export HYPERLATEX_DIR
fi

EMACS=/usr/bin/emacs
if [ ! -x $EMACS ]; then
  EMACS=/usr/bin/xemacs
  if [ ! -x $EMACS ]; then
    echo "hyperlatex: cannot find emacs" 1>&2
  fi
fi

usage() {
  echo "usage: hyperlatex [ -html | -dvi | -gif ] file" 1>&2
  exit 1
}

[ $# -lt 1 ] && usage

run_latex=0
make_gifs=0

case $1 in
  -html)
    shift;;
  -dvi)
    run_latex=1
    latex_flag=
    make_gifs=0
    shift;;
  -gif)
    run_latex=1
    latex_flag='\def\makegifs{}'
    make_gifs=1
    shift;;
  -*)
    usage
esac

if [ $# -lt 1 ]; then
  echo "hyperlatex: no file specified" 1>&2
  exit 2
fi

case $1 in
  *.tex) name=$1;;
  *)     name=$1.tex
esac

if [ ! -e $name ]; then
  echo "hyperlatex: Cannot find file "\"$name\" 1>&2
  exit 2
fi

if [ $run_latex -eq 1 ]; then

  latex "$latex_flag\input{$name}"
  if [ $? -eq 0 -a $make_gifs -eq 1 ]; then
    script=`echo $name | sed -e 's/\.tex$/.makegif/'`
    [ ! -d html ] && mkdir html
    PATH=$HYPERLATEX_DIR:$PATH /bin/sh $script
  fi

else

  [ ! -d html ] && mkdir html
  for bitmap in $HYPERLATEX_DIR/*.xbm; do
    [ -f html/`basename $bitmap` ] || cp -p $bitmap html/
  done

  $EMACS -batch -no-init-file -no-site-file \
    -l $HYPERLATEX_DIR/hyperlatex.el -funcall batch-hyperlatex-format \
    $name

fi
