#!/bin/sh

### mp2eps.sh -- Convert METAPOST output to PostScript

# Author: Michael Grünewald
# Date: Sat 10 Dec 2005 09:58:48 GMT


# Global Variables:

AUTHOR="Michael Grünewald <michipili@gmail.com>"
COPYRIGHT="©2005–2014"
PROGNAME=`basename "$0"`


# Ancillary functions

prerr()
{
    echo "$@" 1>&2
}

HELP()
{
    iconv -f utf-8 <<EOF
Usage: $PROGNAME [-h] [file1 [file2 [...]]]
 Convert METAPOST output to encapsulated PostScript
Options:
 -h Display a cheerful help message to you.
Notes:
 The conversion is done thanks to TeX and epsf.tex.  This tool is
 useful to circumvent a bug in Ghostscript which does not interpret
 correctly bounding boxes.
Author: Michael Grünewald
Copyright: ${COPYRIGHT}
EOF
}

INVALIDOPT() {
    prerr "${PROGNAME}: unknown option: $1"
}

is_yes ()
{
    case "$1" in
	[Yy][Ee][Ss]) return 0;;
	*) 		return 1;;
	esac
}

is_no ()
{
    case "$1" in
	[Nn][Oo])	return 0;;
	*)		return 1;;
	esac
}

# Working Functions

process_arg() {
    inputfile="$1";
    basename="${inputfile%.mps}"
    texbase=$(mktemp ${basename}_XXXX)
    texfile="$texbase.tex"
    epsfile="$basename.eps"

    cat > $texfile <<EOF
\nopagenumbers
\input epsf
\setbox0=\vbox{%
  \offinterlineskip
  \hbox to 0pt{\epsfbox{$inputfile}\hss}%
  \offinterlineskip
}%
\shipout\box0\relax
\end
EOF

    tex "$texfile"
    dvips $DVIPS_OPTS -E -j -o "$epsfile" "$texbase"
    rm -f "$texbase"*
}


# Process Arguments

DEBUG=no
while getopts "Dh" OPTION; do
    case $OPTION in
	D)	DEBUG=yes;;
	h)	HELP; exit 0;;
	?)	INVALIDOPT $OPTION; HELP; exit 1;;
    esac
done

if [ $DEBUG = no ]; then
    exec 2>/dev/null 1>/dev/null
else
    echo Debugging 1>&2
fi

shift $(expr $OPTIND - 1)

for arg in "$@"; do process_arg "$arg"; done

### End of file `mp2eps.sh'
