#!/bin/sh

clean()
{
  # Remove the temporary files
  for suffix in log lof lot glo idx ind ilg toc out aux cb
  do
    temp=$basefile.$suffix
    rm -f $temp*
  done
}

log_dump()
{
  cat $1 | awk '
  /^l\.[0-9]+/{
    for (i=0; i < 10; i++) { print line[i]; }
    print $0;
  }
  {
    for (i = 0; i < 9; i++) { line[i]=line[i+1]; }
    line[9]=$0;
  }'
}

# Inputpath setting
inputpath=""

# Beware, blank spaces in the path are forbidden
add_inputpath_one()
{
  if [ $# -gt 1 ]; then
    echo "Warning: '$*': invalid input path (contains blank); skipped"
  else
    inputpath="$inputpath{$1//}"
  fi
}

add_inputpath_range()
{
  for i in $1; do
    add_inputpath_one "$i"
  done
}

add_inputpath_tex()
{
  cat <<eof > $2
\makeatletter
\def\input@path{$inputpath}
\makeatother
eof
cat $1 >> $2
}

scriptpath=`dirname $0`;

# (la)tex engine to use, and the expected output extension.
xtex=latex
oxt=dvi

while true
do
  case "$1" in
  --texpost) execpost="$2"; shift;;
  --tex) xtex="$2"; shift;;
  --oxt) oxt="$2"; shift;;
  --src) add_inputpath_one $2; shift;;
  --xpath) add_inputpath_range "$2"; shift;;
  -*) shift;; # ignore silently the unknown option
  *)  break;;
  esac
  shift
done

if [ $# -lt 1 ]; then
  echo "`basename $0` [options] file.tex"
  exit 1
fi

srcfile="$1"
file=`basename "$srcfile" .tex`
srcout=$file.$oxt
file=${file}_tmp
basefile=$file
file=${file}.tex
pathfile=`dirname $file`
auxfile=$pathfile/$basefile.aux
logfile=$pathfile/$basefile.log
outfile=$pathfile/$basefile.$oxt
verbose=1


# Build the tex file with input@path set
add_inputpath_tex "$srcfile" $file

run=1
while [ $run -ne 0 ]
do 
  echo "$xtex $file"
  $xtex -interaction=batchmode $file
  if [ $? -ne 0 ]; then
    echo "*** latex error"
    if [ $verbose -ne 0 ]; then
      log_dump $logfile
    fi
    clean
    exit 1
  fi
  run=`grep -s Rerun $logfile|wc -l`
done

# Make the index if needed
if [ -f $basefile.idx ]; then
  sz=`cat $basefile.idx|wc -l`
  if [ $sz -ne 0 ]; then
    makeindex -s $scriptpath/doc.ist $basefile.idx
    $xtex -interaction=batchmode $file
    $xtex -interaction=batchmode $file
  fi
fi

# Execute post-action if needed
if [ "$execpost" != "" ]; then
  $execpost $file

  # Run latex again for the final output
  $xtex -interaction=batchmode $file
fi

# Remove the temporary files
clean

# The temporary file becomes the output file
mv $outfile $srcout

exit 0
