#!/bin/sh
#
# This file created to convert X window PostScript files
# (generated by xwd and xpr)
# to EPSI suitable for inclusion in a Frame document.
#

if (test $1)
then
	file=/tmp/EPS$$
	image=/tmp/EPSimage$$

	while (test $1)
	do
		echo -n "$1: "

		# check the file exists
		if (test ! -r $1)
		then
			echo 'Cannot access this file - skipping'
			shift; continue
		fi

		# check it's a PostScript file
		if (file $1 | grep -v PostScript > /dev/null 2>&1)
		then
			echo 'Not a PostScript file - skipping'
			shift; continue
		fi

		# check it hasn't been converted already
		if (echo $epsfline | grep '^%!PS-Adobe-2.0 EPSF-1.2$' > /dev/null 2>&1)
		then
			echo 'Already converted - skipping'
			shift; continue
		fi

		# construct screen image
		grep '^[0-9a-f][0-9a-f]*$' $1 | sed 'y/0123456789abcdef/fedcba9876543210/' > $image

		bitdumpline=`grep '^[0-9]* [0-9]* [0-9]* bitdump$' $1`
		width=`echo $bitdumpline | awk '{print $1}'`
		height=`echo $bitdumpline | awk '{print $2}'`
		awk " \
			/^%!PS-Adobe-[0-9].[0-9]/ \
				{print \"%!PS-Adobe-2.0 EPSF-1.2\"; next} \
			/^%%BoundingBox: [0-9-][0-9]* [0-9-][0-9]* [0-9-][0-9]* [0-9-][0-9]*\$/ \
				{print \"%%BoundingBox: 0 0 $width $height\"; next} \
			/^%%EndComments\$/ \
				{print; \
				print \"%%BeginPreview\"; \
				print \"%%ImageWidth:$width\"; \
				print \"%%ImageHeight:$height\"; \
				print \"%%ImageDepth:1\"; \
				print \"%%BeginImage:$height\"; \
				print \"%%EndImage\"; \
				print \"%%EndPreview\"; \
				next} \
			/^\/bitdump \% stk: width, height, iscale\$/ \
				{print \"/bitdump % stk: width, height\"; next} \
			/^\% scaling by iscale/ \
				{next} \
			/^	\/iscale exch def\$/ \
				{next} \
			/^	width iscale mul height iscale mul scale\$/ \
				{print \"	width height scale\"; next} \
			/^72 300 div dup scale\$/ \
				{next} \
			/^[0-9]* [0-9]* translate\$/ \
				{next} \
			/^[0-9]* [0-9]* [0-9]* bitdump\$/ \
				{print \$1\" \"\$2\" bitdump\"; next} \
			{print} \
		" $1 > $file

		# Merge in the screen image
		sed "/^%%BeginImage:/r $image" $file > $1
		rm $image

		rm $file

		echo 'Converted to Frame EPS'

		shift
	done
else
	echo 'Usage: XpsToEPS <file(s)>'
fi
