#!/bin/bash
if [ $# -ge 2 -a "x$1" = "x-M" ]; then

  ##########################################################
  # Automagically find dependancies for tex files

  function samedir
  {
    [ "x`pwd`" = "x`cd "$1"; pwd`" ]
  }

  shift
  newline="`echo -e '\nx'`"
  newline="${newline%x}"
  N=2
  nums="2"
  deps="${1}.d: ${1}.tex"

  # sed commands
  rmcomment='s:\([^\\]\|^\)%.*$::'
  curly=' *{\([^}]*\)}'
  square=' *\(\[[^]]*\]\)\?'
  bs='\\'

  # tex dependancies
  for f in `sed -n "${rmcomment}; s:^.*${bs}input${square}${curly}.*$:\2:p" "${1}.tex"`; do
    N=$[ $N + 1 ]
    nums="$nums $N"
    samedir "`dirname "$f"`" && f="`basename "$f"`"
    if echo "$f" | grep '/' >/dev/null; then
      deps="$deps${newline}${1}.d: \$(call extdep,${f}.d)"
    else
      deps="$deps${newline}${1}.d: ${f}.d"
    fi
  done

  # eps dependancies
  for f in `sed -n "${rmcomment}; s:^.*${bs}includegraphics${square}${curly}.*$:\2:p" "${1}.tex"`; do
    N=$[ $N + 1 ]
    nums="$nums $N"
    samedir "`dirname "$f"`" && f="`basename "$f"`"
    if echo "$f" | grep '/' >/dev/null; then
      deps="$deps${newline}${1}.d: \$(call extdep,${f})"
    else
      deps="$deps${newline}${1}.d: ${f}"
    fi
  done

  # bibliography dependancies
  for f in `sed -n "${rmcomment}; s:^.*${bs}bibliography${square}${curly}.*$:\2:p" "${1}.tex"`; do
    N=$[ $N + 1 ]
    nums="$nums $N"
    samedir "`dirname "$f"`" && f="`basename "$f"`"
    if echo "$f" | grep '/' >/dev/null; then
      deps="$deps${newline}${1}.d: \$(call extdep,${f}.bib)"
    else
      deps="$deps${newline}${1}.d: ${f}.bib"
    fi
  done

  echo "$nums"
  echo "$deps"
else

  ##########################################################
  # Compile latex document

  function cont { [ -f "$1" ] && od "$1"; }

  redo=yes
  while [ $redo = yes ]; do
    aux="`cont "$1.aux"`"
    toc="`cont "$1.toc"`"
    lof="`cont "$1.lof"`"
    lot="`cont "$1.lot"`"
    lol="`cont "$1.lol"`"
    bbl="`cont "$1.bbl"`"

    echo
    echo '  Running latex'
    echo
    echo -n | latex "$1.tex" || exit $?

    if grep '^\\bibdata{' "$1.aux" >/dev/null; then
      echo
      echo '  Running bibtex'
      echo
      bibtex "$1" || exit $?
    fi

    redo=no
    [ "x$aux" != "x`cont "$1.aux"`" ] && redo=yes
    [ "x$toc" != "x`cont "$1.toc"`" ] && redo=yes
    [ "x$lof" != "x`cont "$1.lof"`" ] && redo=yes
    [ "x$lot" != "x`cont "$1.lot"`" ] && redo=yes
    [ "x$lol" != "x`cont "$1.lol"`" ] && redo=yes
    [ "x$bbl" != "x`cont "$1.bbl"`" ] && redo=yes

    if [ $redo = no ]; then
      if grep -i 'warning.*undefined' "$1.log" &>/dev/null; then
        echo "Got LaTeX warnings!"
        rm -f "$1.dvi"
        exit 1
      fi
    fi
  done
fi

exit 0