#!/bin/sh

# gastex2pdf - version 0.9 beta
# Copyright (C) 2005 Jerome Cornet 

# Modifiée par Matthieu Moy le 2 Novembre (gestion des chemins absolu,
# relatifs, ...), compilation dans /tmp, options -o, -p, -po.

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

function usage
{
    cat << EOF
Usage: $(basename $0) [options] INPUT [options]

Compiles a GasTeX source file into a PDF file with adequate size and
margins.

Options:
	-o FILE              use FILE as output
	-p PACKAGE           add \usepackage{PACKAGE}
        -po OPT PACKAGE      add \usepackage[OPTION]{PACKAGE}
        --preamble FILE      use the content of FILE as the preamble
                             (from the beginning of the file to
                              \begin{document})
        -m MARGIN            use MARGIN argument for pdfcrop

INPUT is a file containing a GasTeX picture, like

  \begin{picture}(70,15)(0,0)
    \node(A)(0,10){\$\$}
    \node(B)(50,10){\$1\$}
    \only<2->{
      \drawedge(A,B){\$1\leq x \leq 2,1\leq y\leq 2\$}
    }
  \end{picture}

The resulting file can be included into a LaTeX file to be compiled
with pdflatex as follows:

  \documentclass{beamer}
  \usepackage{graphicx}
  ...
  \begin{document}
  ...
  \input graph.pdftex_t
  ...
  \end{document}

If you need to specify some LaTeX commands to be run before processing
your GasTeX source, create a file <whatever>.sty, and use 
$(basename $0) -p <whatever> ...
EOF
    exit 0
}

function command_failed
{
    echo "Command $1 failed"
    /bin/rm -f "$BASENAME".{tex,dvi,aux,log,pdf,-crop.pdf}
    exit 1
}

outfile=""
sourcefile=""
packages=""
preamble=""
margin=20

while test $# -ne 0; do
    case "$1" in
        "--help"|"-h")
            usage
            ;;
        "-o")
            shift
            outfile="$1"
            shift
            ;;
        "-p"|"--package")
            shift
            packages="$packages
\usepackage{$1}"
            shift
            ;;
        "-po"|"--package-option")
            shift
            packages="$packages
\usepackage[$1]{$2}"
            shift
            shift
            ;;
        "--preamble")
            shift
            preamble=$(cat "$1")
            shift
            ;;
        "-m"|"--margin")
            shift
            margin=$1
            shift
            ;;
        *)
            sourcefile="$1"
            shift
            ;;
    esac
done

if [ "x$sourcefile" = "x" ]
then
    usage
fi

if [ "x$outfile" = "x" ]
then
    outfile=$(echo $sourcefile | sed 's/\.[^.]*$/\.pdf/')
fi


tmpfile=`tempfile`
BASENAME=$(basename "$tmpfile")
TMPDIR=$(dirname "$tmpfile")

if echo "$sourcefile" | grep -q "^[^/]"
then
    # Relative filename
    sourcefile="$(pwd)/$sourcefile"
fi


if echo "$outfile" | grep -q "^[^/]"
then
    # Relative filename
    outfile="$(pwd)/$outfile"
fi

cd "$TMPDIR" || exit 1

if [ "x$preamble" = "x" ] 
then
    preamble="\documentclass{beamer}
\usepackage{gastex}
\setbeamercovered{transparent}
\setbeamertemplate{navigation symbols}{}
\setbeamercolor{normal text}{bg=}

\beamersetleftmargin{0mm}
\beamersetrightmargin{0mm}
%\abovedisplayskip=1ex
%\belowdisplayskip=1ex
%\parskip=.5ex
%\parindent=0pt
$packages

"
fi

(echo "$preamble"; echo "\begin{document}
\frame{
\input{$sourcefile}
}
\end{document}") > "$BASENAME".tex

echo compiling "$BASENAME".tex

latex "$BASENAME".tex || command_failed latex
if [ ! -f "$BASENAME".dvi ]
then
    command_failed latex
fi

dvipdf "$BASENAME".dvi "$BASENAME".pdf || command_failed dvipdf
# For some reason, pdfcrop doesn't seem to accept an output in a
# different directory.
pdfcrop-uni --verbose --margins $margin "$BASENAME".pdf "$BASENAME"-num.pdf | tee "$BASENAME"-pdfcrop.log || command_failed pdfcrop-uni
#pdf2ps "$BASENAME"-crop.pdf "$BASENAME"-crop.ps
# Using %d in OutputFile works only from ps to ps :-(
#gs -dBATCH -dNOPAUSE -sDEVICE=pswrite -sOutputFile="${BASENAME}-num%d.ps" -f "$BASENAME"-crop.ps

total=0
# Not necessarily in order. 10 comes before 9 ...
for file in ${BASENAME}-num-*.pdf
do
    total=$(expr $total + 1)
    num=$(echo $file | sed 's/.*-num-\(.*\).pdf/\1/')
    destfile=$(echo $outfile | sed "s/\.[^\.]*\$/-$num.pdf/")
    echo mv $file $destfile
    mv $file $destfile
done

# cat > "$outfile" <<EOF
# \newcount\imagenum
# \animate<1-$total>
# \animatevalue<1-$total>{\imagenum}{1}{$total}
# \includegraphics{$(echo $outfile | sed "s/\.[^\.]*\$//")-\the\imagenum.pdf}
# EOF

for i in $(seq $total)
do
    cat <<EOF
\only<$i>{%
\includegraphics{$(echo $outfile | sed "s/\.[^\.]*\$//")-$i.pdf}%
}%
EOF
    done > "$outfile"

\rm -f "$BASENAME"*
echo "Created $outfile"
