#!/bin/bash

# Wrapper to bibtex. Pass it a .aux file as normal. Or wrongly give it a
# .tex/.pdf/.dvi file and it will strip the extension off and replace it with
# .aux. Or even specify nothing, or nothing helpful and it will go through all
# the aux files picking the first one that actually seems to make a document (a
# .dvi or .pdf).

if [ -e "$1".aux ] ; then
	name="$1"
else
	name=`echo $1 | sed 's/\.[a-z]\{0,3\}$//'`
	if [ \! -e "$name".aux ] ; then
		for b in *.bbl ; do
			name=${b%.bbl}
			if [ -e "$name".aux ] ; then
				break
			fi
		done
		for b in *.aux ; do
			name=${b%.aux}
			if [ -e "$name".dvi -o -e "$name".pdf ] ; then
				break
			fi
		done
		if [ \! -e "$name".aux ] ; then
			echo Sorry I can not find a suitable .aux file
			exit 1
		fi
	fi
fi

echo $name
/usr/bin/bibtex "$name"

