#!/bin/sh -efu
# This script is intended to help in preparing figures for LaTeX
# documents. The main idea is to have one set of figure sources
# accompained with the appropriate TeX template files and to produce
# final TeX and graphical files from them automatically. The main
# variable parameter this script is focused at is the final figure
# scale. With different figure sources and graphical composition
# features the plain PostScript scaling of the picture area may be
# undesirable. Especially, when you want to have all text on the
# figures to be rendered by TeX without rescaling.
#
#  Copyright (C) 2008 Paul Wolneykien.
#
#  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 3 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, see <http://www.gnu.org/licenses/>.
#
#  Contact information:
#
#  Paul Wolneykien
#  SMTP: wolneykien [at] gmail [dot] com
#  XMPP: wolneykien [at] jabber [dot] org
#

# Set initial variables
PROG="$0"
PROG_VERSION="1.0"

. shell-error
. shell-args

# Process the command-line arguments
show_help()
{
	cat <<EOF
Usage: $PROG [Options] fig1 [fig2 ...] [ scale ]

$PROG is intended to help in preparing figures for LaTeX
documents. The main idea is to have one set of figure sources
accompained with the appropriate TeX template files and to produce
final TeX and graphical files from them automatically.

Options:
  -c,--command=CMD    use LaTeX command CMD instead of
                      'includegraphics';
  -e,--environment    the command is an environment (and neads
                      'begin' and 'end' statements;
  -a,--args=ARGS      additional arguments to the LaTeX command;

  -V,--version        print program version and exit;
  -h,--help           show this text and exit.

EOF
	exit 0
}

print_version()
{
	cat <<EOF
$PROG version $PROG_VERSION
Written by Paul Wolneykien <manowar@altlinux.org>

Copyright (C) 2009 Paul Wolneykien <manowar@altlinux.org>
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
EOF
        exit
}

TEMP=`getopt -n $PROG -o c:,e,a:,V,h \
             -l command:,environment,args:,version,help -- "$@"` || \
        show_usage
eval set -- "$TEMP"

cmd="includegraphics"
env=0
args=
while :; do
        case "$1" in
                -c|--command) shift; cmd="$1";;
		-e|--environment) env=1;;
		-a|--args) shift; args="$1";;
		-V|--version) print_version;;
                -h|--help) show_help;;
                --) shift; break;;
                *) fatal "unrecognized option: $1";;
        esac
	shift
done

# Setting up the figure directory if it has not been set. The default
# figure directory is the directory where the script is placed.
BASEDIR=${PWD:-`pwd`}

# The figure template list to be constructed.
FIGS=

# Attempt to get the scale parameter. If specified, it should be the
# last command argument.
IFS=' '
SCALE=1.0
# Add all but the last argument to the figure list, filtering out the
# files that do not exist.
x0=
for x in $@; do
    if [ ! -z "$x0" ]; then
	if [ -e "$BASEDIR/$x0.tex.in" ]; then
	    FIGS="$FIGS $x0"
	else
	    echo "File $BASEDIR/$x0.tex.in not found. Skipped."
	fi
    fi
    x0=$x
done
# The last argument, if doesn't specify a file name is interpreted as
# the scale parameter.
if [ ! -z "$x0" ]; then
    if [ ! -e "$BASEDIR/$x0.tex.in" ]; then
	SCALE=${x0:-$SCALE}
    else
	for x in $FIGS; do
	    if [ "$x0" = "$x" ]; then
		SCALE=${x0:-$SCALE}
		unset x0
		break
	    fi
	done
	if [ ! -z "$x0" ]; then
	    FIGS="$FIGS $x0"
	fi
    fi
fi

# Print out the final figure list and the scale factor.
echo "List of figures: $FIGS"
echo "Scale: $SCALE"

# Process each figure template file replace each line that matches the
# pattern
# @graphic GRAPHIC-NAME [SCALE]
# with the output code produced by an other script from the specified
# graphic source. Processed template is output to the current
# directory under the name that is similar to the template name with
# the `.in' suffix stripped out.
IFS=' '
for t in $FIGS; do
    FIGDIR="`dirname \"$t\"`"
    FIG="$BASEDIR/$t.tex.in"
    echo "Processing figure template " `basename "$FIG"` " in the $BASEDIR/$FIGDIR"
    LANG_OLD=${LANG:-}
    LANG=C
    PATH="$FIGDIR:$PATH"
    export MK_FIG_CMD="$cmd"
    export MK_FIG_CMD_ARGS="$args"
    export MK_FIG_ENV=$env
    set -o pipefail
    awk "
    BEGIN { print \"% Do not edit this file. It is produced from \" \\
                   \" the\\n% $FIG\\n% automatically.\\n\" }
    {
        if (\$1 == \"@graphic\")
        {
            cmd = \"make-\" \$2 \" $BASEDIR \" \"$FIGDIR/\" \$3 \" \" (\$4  * $SCALE) \" \" \$5 \" \" \$6 \" \" \$7
            while ((cmd | getline) > 0)
            {
                print
            }
            stat = close(cmd)
            if (stat != 0)
            {
                print cmd \" exit code: \" stat | \"cat 1>&2\"
                exit 1
            }
        }
        else if (\$1 == \"@endgraphic\")
	{
	    cmd = \"make-\" \$2
            while ((cmd | getline) > 0)
            {
                print
            }
            stat = close(cmd)
            if (stat != 0)
            {
                print cmd (end) \" exit code: \" stat | \"cat 1>&2\"
                exit 1
            }
        }
        else
        {
            print
        }
    }" $FIG | sed "s/@SCALE/$SCALE/g" > "$BASEDIR/`basename \"$FIG\" .in`"
    RET=$?
    LANG=$LANG_OLD
    if [ "$RET" -ne 0 ]; then
	rm -f $t.tex
	exit $RET
    fi
done
