#!/bin/sh
# Script to convert an arbitrary PostScript image to an encapsulated
# PostScript image with a bitmap, suitable for incorporation into
# FrameMaker, LaTeX, troff, etc.
#
# Options:
#	-gs	Use ghostscript to convert to EPSI
#	-news	Use Sun's X/NeWS (OpenWindows) to convert to EPSI
#	-strip	Strip all %% directives from the source file -- useful
#		when dealing with Adobe Illustrator and others who
#		use directives incompatible with this coversion.
#
# Note in the USAGE line below, the source PostScript file must end
# in a .ps extention.  This is a GhostScript requirement, not mine...
#
# I am providing this without any guarantee.
#
# Thu Nov 29 10:57:05 EST 1990
#
# Doug Crabill dgc@cs.purdue.edu

USAGE="Usage: $0 [ -gs | -news ] [ -strip ] <file>.ps <file>.epsi"

########################## Edit these variables #####################
GS='/usr/local/bin/X11/gs'
PSTOPPM='/usr/local/libdata/X11/gs/pstoppm.ps'
PBMTOEPSI='./pbmtoepsi'
RASTTOPNM='/usr/local/pbm/rasttopnm'
INTERP='gs'
STRIP='false'
PSTORAST='./pstorast'
######################################################################

for A do
	case $A in
	-gs)	INTERP='gs'
		shift
		;;
	-news)	INTERP='news'
		shift
		;;
	-strip)	STRIP='true'
		shift
		;;
	*)	break
		;;
	esac
done

BASE=`basename "$1" .ps`

if [ $# -ne 2 -o ! -f "$1" -o "$1" = "$BASE" ] ; then
	echo $USAGE 1>&2
	exit 1
fi

TMP1="/tmp/$USER.1.$$"
TMP2="/tmp/$USER.2.$$"
TMP3="/tmp/$USER.3.$$"
trap 'rm -f $TMP1 $TMP2 ${BASE}.ppm; exit' 1 2 3 4 13 15

if [ "true" = "$STRIP" ] ; then
	awk '/^%%/ { next } {print}' < $1 > $TMP3
else
	TMP3="$1"
fi

if [ "gs" = "$INTERP" ] ; then
	$GS -q -dNODISPLAY $PSTOPPM << DGC
	($BASE) ppm1run
DGC
	$PBMTOEPSI ${BASE}.ppm > $TMP1
	cat $TMP1 $TMP3 > $2
else
	$PSTORAST -in $TMP3 -out $TMP1
	$RASTTOPNM < $TMP1 | $PBMTOEPSI > $TMP2
	cat $TMP2 $TMP3 > $2
fi

if [ "$1" != "$TMP3" ] ; then
	rm -f $TMP3
fi
rm -f $TMP1 $TMP2 ${BASE}.ppm

exit 0
