#!/bin/bash
# This script takes as an argument an xfig figure file which is presumed to
# contain latex commands within its text and converts the output to an eps
# file.  If your diagram uses latex commands that you have created, a second
# argument may be provided with the package name (with or without the .sty
# extension) and this will allow those commands to be included as well when
# creating your figure.  Note that I have commented out a command to convert
# the postscript file to an eps or epsi file which contains a bitmap of the
# image.  You can uncomment that and the line to delete the temporary
# postscript file if you want.  I found that it ruined the bounding box on
# one of my figures and didn't really add anything.  Also on my old machine
# the ps2epsi script which comes with ghostscript was broken so I had to
# hack it based on something I saw on the web to make it work at all.  On
# a newer machine you may just want to try ps2epsi directly again.
# This shell script is based on a perl script fig2eps which I saw on the web
# but seemed to be broken.
BASE=$(basename $1)
if [ $# -eq 2 ]
    then
    STYLEFILE=$(basename $2)
fi
FIG2=$BASE".fig2"
PSTEX=$BASE".pstex" 
PSTEX_T=$BASE".pstex_t" 
DRIVER=$BASE".driver"
DVI=$BASE".dvi"
PS=$BASE".ps"
EPS=$BASE".eps"
LOG=$BASE".log"  # These last two are created by LaTeX,
AUX=$BASE".aux"
cp $BASE $FIG2
# Convert from fig format to combined PS/LaTeX
fig2dev -Lpstex   $FIG2 $PSTEX
fig2dev -Lpstex_t -p $PSTEX $FIG2 $PSTEX_T
WIDTH="100cm"
HEIGHT="100cm"
echo "\\documentclass[10pt]{article}" > $DRIVER
echo "\\usepackage{color}" >> $DRIVER
if [ $# -eq 2 ]
    then
    echo "\\usepackage{$STYLEFILE}" >> $DRIVER
fi
echo "\\usepackage{epsfig}" >> $DRIVER
echo "\\setlength{\\textwidth}{$WIDTH}" >> $DRIVER
echo "\\setlength{\\textheight}{$HEIGHT}" >> $DRIVER
echo "\\begin{document}" >> $DRIVER
echo "\\pagestyle{empty}" >> $DRIVER
echo "\\input{$PSTEX_T}" >> $DRIVER
echo "\\end{document}" >> $DRIVER
# Use the driver to create an EPS from the exported fig
if latex $DRIVER
then
    dvips -E $DVI -o $PS
# Finally, convert (full-page) postscript file we got into
# nicer, smaller EPS file.
# At some point, this became nessescary - In the past dvips did the job
# correctly.  I don't really understand what changed, but this works.
#./myps2epsi $PS $EPS
#ps2epsi $PS $EPS
fi
# Delete the gaggle of useless files.
rm $FIG2
rm $PSTEX   
rm $PSTEX_T 
rm $DRIVER 
rm $DVI 
#rm $PS 
rm $LOG 
rm $AUX 
