#!/bin/sh
case $# in
1)	case $1 in
	*.aux)	IN=$1 ;;
	*)	IN=$1.aux ;;
	esac ;;
*)	echo "Usage: $0 file[.aux]"; exit 1;;
esac
ROOT=`basename $IN .aux`
TMP=/tmp/slbibtex.$$
ALL=
HERE=$IN

while true			# Find ALL included .aux-files
do				# Maybe this should preserve .aux-file order?
	ALL="$ALL $HERE"
	HERE=`sed -n '/@input/s/^.*@input.\(.*\.aux\).*$/\1/p' $HERE`

	if test X = X$HERE
	then			# No more .aux-files
		break
	fi
done

trap 'rm -f $TMP.*; exit 1' 1 2 15

# Sort and remove duplicate .aux-files.
HERE=`for i in $ALL
do	# sort needs a newline thus use a for-loop instead of plain echo
	echo $i
done | sort -u`

# Extract bibtex info and convert (if needed) to LaTeX style
sed -n	-e 's/[\!\\]citation[<{]\(.*\)[>}]/\\citation{\1}/p' \
	-e 's/[\!\\]bibstyle[<{]\(.*\)[>}]/\\bibstyle{\1}/p' \
	-e 's/[\!\\]bibdata[<{]\(.*\)[>}]/\\bibdata{\1}/p' $HERE > $TMP.aux

# Run bibtex on translated bibliography information
bibtex $TMP

# Convert to SLaTeX style
l2sl < $TMP.bbl > $ROOT.bbl
sed	-e 's!'$TMP'!'$ROOT'!g' \
	-e 's/\\/!/g' \
	-e 's/{/</g' \
	-e 's/}/>/g' $TMP.blg > $ROOT.blg

rm -f $TMP.*

