#!/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
#
# Hvard Berland  http://www.math.ntnu.no/~berland
#
# $Id: figtex2eps,v 1.6 2003/08/14 14:55:48 berland Exp $
# $Source: /home/abel/c/berland/etc/cvsrepository/figtex2eps/prog/figtex2eps,v $
#

function usage 
{
    echo "figtex2eps <figfile.fig>"
    echo "Options: -v  verbose, and don't delete temp files"
    echo ""
    echo " - Script written by Hvard Berland"
    echo "                     http://www.math.ntnu.no/~berland"
    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 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)"

# 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

