#!/bin/bash
#
# Converts a .fig-file to a .eps-file, by using graphics from .fig as
# a backgroundpicture and latex-compiles tex-code from .fig on top
#
# Can also make pdf, by first making ps, and then running epstopdf
#
# H�vard Berland  http://www.math.ntnu.no/~berland
#
# $Id: figtex2eps,v 1.7 2003/10/28 18:55:31 berland Exp $
# $Source: /home/pvv/d/berland/etc/cvsrepo/figtex2eps/prog/figtex2eps,v $
#

function usage 
{
    echo ""
    echo "Usage:"
    echo " figtex2aeps <options> <figfile.fig>"
    echo ""
    echo " Options:  -v    Verbose, and don't delete temp files"
    echo "           -pdf  Generate pdf in addition via epstopdf"
    echo ""
    echo "Script written by H�vard Berland http://www.math.ntnu.no/~berland"
    echo "Documentation available at http://www.math.ntnu.no/~berland/figtex2eps"
    exit
}

function die
{
    echo "$1"
    echo "Exiting..."
    exit
}

# A prefix used for outputting messages to the user
errorprefix=" (Error) "
infoprefix=" (Info) "

# The file where the preamble is to be written and/or found
preamblefile=figtex2eps-preamble.tex

# Option for running latex.
latexoption="-interaction=batchmode"

# Option for dvips. These are set for tex-installations based
# on teTeX, and ensures that Type1 fonts are used (via the file
# config.pdf loaded by -Ppdf), this gives correct fonts in the 
# pdf-document. Set this variable to "" if this does not work, 
# and try to find other ways of getting Type1 fonts.
dvipsoptions="-Ppdf -G0"

# Each of these commands must be available and in $PATH !
neededcommands="latex dvips fig2dev"

for cmd in $needecommands ; do
    which $cmd >/dev/null 2>&1 \
	|| die "${errorprefix}Could not find $cmd in your path!"
done



if [ -z "$1" ]; then
    echo "${errorprefix}Mandatory input arguments not provided."
    usage
fi

# Default,  throw away unwanted output from commands.
out=">/dev/null"

# Default option to run dvips in quiet mode:
dvipsout="-q"

# If verbose, alter the above set variables.
if [ "$1" = "-v" ] ; then
    out=""
    dvipsout=""
    latexoptions=""
    shift
fi

# Check if user wants pdf (we might be called via wrapper script)
dopdf=""
if [ "$1" = "-pdf" ] ; then
    dopdf="yes"
    shift
fi

# In case of changed order of options (this way of dealing
# with options is certainly not scalable!!!)
if [ "$1" = "-v" ] ; then  ## Do SAME as above..
    out=""
    dvipsout=""
    latexoptions=""
    shift
fi



# Check our mandatory input argument
figfile=$1 # may or may not include .fig as an ending

if [ ! -f $figfile ] ; then
    # Test if user just dropped the ending:
    if [ -f "$figfile.fig" ] ; then
	figfile="$figfile.fig"
    else
	die "${errorprefix}Could not find the xfig-file $figfile"
    fi
fi

# Check that the figfile is not empty
if [ ! -s $figfile ] ; then
    die "${errorprefix}The file $figfile is empty."
fi

# If the 'file' and 'grep' command is available, we just as 
# well check that it really is a FIG, not just
# some other file with the suffix .fig
format=`which >/dev/null 2>&1 file && which >/dev/null 2>&1 grep && file $figfile`
if [ ! -z "$format" ] ; then
    if [ -z `echo "$format" | grep "FIG image text" >/dev/null && echo yes` ] ; then
	echo "${errorprefix}According to the utility 'file', $figfile is not a proper fig-file."
	die "${errorprefix}'file' says: \"$format\""
    fi
fi

base="${figfile%.fig}"
outfile=$base.eps

# The user is also allowed to provide an output file if really necessary:
if [ ! -z "$2" ]; then
	outfile=$2
fi


## Make a preamble file if it does not exist
if [ ! -s "$preamblefile" ] ; then
    echo "${infoprefix}Generating preamble file $preamblefile"
    echo "${infoprefix}You may edit to suit your needs if necessary and rerun"
    
    # CVS tip if the directory CVS exists.
    if [ -d "CVS" ] ; then
	echo "${infoprefix}You might want to do a 'cvs add $preamblefile' as well"
    fi
    touch $preamblefile \
	|| die "${errorprefix}Could not write to $preamblefile, check your permissions"

    ## This could have been redone with a HERE document..
    echo "%" > $preamblefile
    echo "% This is a preamble file for 'figtex2eps'. You may edit things" \
	>> $preamblefile
    echo "% here if necessary. Typically you might want to change the font" \
	>> $preamblefile
    echo "% size, the font or add some more packages for your latex commands" \
	>> $preamblefile
    echo "% in your figures. " >> $preamblefile
    echo "%" >> $preamblefile
    echo "% If you make errors in here, rerun figtex2eps with '-v' (verbose) and" \
	>> $preamblefile
    echo "% check the error messages from latex, and then fix here." >> $preamblefile
    echo "% You may also just delete this file if you are in trouble" >> $preamblefile
    echo "% and a new default one will be generated" >> $preamblefile
    echo "%" >> $preamblefile
    echo "\documentclass[12pt]{article}" >> $preamblefile
    echo "" >> $preamblefile
    echo "% Packages for most mathematical latex commands:" >> $preamblefile
    echo "\usepackage{amsfonts}" >> $preamblefile
    echo "\usepackage{amsmath}" >> $preamblefile
    echo "\usepackage{amssymb}" >> $preamblefile
    echo "" >> $preamblefile
    echo "\usepackage{ae}       % This is in case you also want to make pdf afterwards" \
	>> $preamblefile
    echo "" >> $preamblefile
    echo "% You might want the palatino font instead, then uncomment the following" \
	>> $preamblefile
    echo "% two lines, and do not use the ae package above" >> $preamblefile
    echo "%\usepackage{palatino}" >> $preamblefile
    echo "%\usepackage{palatcm} % Palatino math fonts " >> $preamblefile
    echo "" >> $preamblefile
    echo "\usepackage[dvips]{color}" >> $preamblefile
    echo "\usepackage{epsfig}" >> $preamblefile
fi

if [ ! -z "$out" ] ; then
	# Not verbose:
        fig2dev >/dev/null -L pstex $figfile $base.pstex 
        fig2dev >/dev/null -L pstex_t $figfile $base.pstex_t_2 
else
	# verbose
	fig2dev -L pstex $figfile $base.pstex
	fig2dev -L pstex_t $figfile $base.pstex_t_2
fi

echo "\begin{picture}(0,0)%" > $base.pstex_t
echo "\epsfig{file=$base.pstex}%" >> $base.pstex_t
echo "\end{picture}%" >> $base.pstex_t
cat $base.pstex_t_2 >> $base.pstex_t
cat $preamblefile > $base.tex
echo "\setlength{\textwidth}{100cm}"   >> $base.tex
echo "\setlength{\textheight}{100cm}" >> $base.tex
echo "\begin{document}" >> $base.tex
echo "\pagestyle{empty}" >> $base.tex
echo "\input{$base.pstex_t}" >> $base.tex
echo "\end{document}" >> $base.tex
if [ ! -z "$out" ] ; then
    # Not verbose:
    latex $latexoptions $base.tex >/dev/null \
	|| die "${errorprefix}Latex failed, rerun with '-v' (verbose)"
else
    # Verbose:
    latex $base.tex || die "${errorprefix}Latex failed"
fi

dvips -E $dvipsoptions $base.dvi $dvipsout -o $outfile \
    || die "${errorprefix}dvips failed, rerun with '-v' (verbose)"


# Make pdf if user wants to.
if [ ! -z "$dopdf" ]; then
    cmd="epstopdf"
    which $cmd >/dev/null 2>&1 \
	|| die "${errorprefix}Could not find $cmd in your path, only eps generated!"
    $cmd $base.eps --outfile=$base.pdf
fi

# delete if not verbose
if [ ! -z "$out" ]; then
    rm -f $base.pstex $base.pstex_t $base.pstex_t_2  \
	$base.tex $base.aux $base.log $base.dvi
fi


