#!/bin/bash
THIS_SCRIPT="$0"
echo AT "$@"
echo AT "$@" 1>&2 
echo AT "$@"  > /tmp/AT

if [ -z "$pCMD" ]
then
	pCMD=/usr/bin/pdflatex
fi

echo pCMD $pCMD

echo "$*" | grep -o '\b[^ ]*.tex' | head -n1 | (
	read texfile
	if grep '^%PREAM ' $texfile > $texfile.pream
	then 
		echo TEXFILE $texfile
		mv $texfile $texfile.orig
		sed 's/^%PREAM //' < $texfile.pream > $texfile
		"$THIS_SCRIPT".strip_preamble.py < $texfile.orig >> $texfile
		$pCMD "$@"
		ERROR_CODE=$!
		rm $texfile.mod
		mv $texfile $texfile.mod
		mv $texfile.orig $texfile
		exit $ERROR_CODE
	else
		
		exec /usr/bin/pdflatex "$@"
	fi
)
