#!/bin/sh

set -e

LATEXPRG=${LATEXPRG:-latex}

while true; do
    pid=$$
    export pid
    rm -f /tmp/rlok$pid
    (
	if ${LATEXPRG} $*
	then
	    touch /tmp/rlok$pid
	fi
    ) | tee /tmp/rlso$pid

    if [ ! -f /tmp/rlok$pid ]
    then
	rm -f /tmp/rlso$pid
	echo >&2 "$(basename $0): Exiting in error"
	exit 1
    fi

    if ! grep -E '^(LaTeX Warning: (Label\(s\) may|There were undefined references)|Package longtable Warning: Table widths have changed)' /tmp/rlso$pid >/dev/null
    then
	rm -f /tmp/rlso$pid
	exit 0
    fi
    echo "Re-running LaTeX"
done
