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

if [ -z "$HYPERLATEX_PATH" ]; then

## Edit the following line to reflect your choice of the
## Hyperlatex directory:

  HYPERLATEX_PATH="/usr/share/emacs/site-lisp/hyperlatex"

  export HYPERLATEX_PATH
fi

if [ -z "$HYPERLATEX_DIR" ]; then
## Add /etc/hyperlatex as a user init directory for hyperlatex:
  HYPERLATEX_DIR="/etc/hyperlatex:$HYPERLATEX_PATH"
else
  HYPERLATEX_DIR=$HYPERLATEX_DIR:$HYPERLATEX_PATH
fi

export HYPERLATEX_DIR

EMACS=/usr/bin/emacs
if [ ! -x $EMACS ]; then
  EMACS=/usr/bin/xemacs
  if [ ! -x $EMACS ]; then
    echo "hyperlatex: cannot find emacs or xemacs" 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;;
  *.ltx) name=$1;;
  *)     name=$1.tex
esac

if [ ! -r $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/'`
    TEMPPATH=$PATH
    if [ -e $HYPERLATEX_PATH/ps2gif ]; then
	    PATH=$HYPERLATEX_PATH:$PATH
    else
	    PATH=.:$PATH
    fi
    export PATH
    /bin/sh $script
    PATH=$TEMPPATH; export PATH
  fi

else

  HLXEL=$HYPERLATEX_PATH/hyperlatex.elc
  if [ ! -r $HLXEL ]; then
    HLXEL=$HYPERLATEX_PATH/hyperlatex.el
  fi
    
  $EMACS -batch -no-init-file -no-site-file \
    -l $HLXEL -funcall batch-hyperlatex-format \
    $name

fi
