#! /bin/sh
cmd=$0

# cmd file height ( compress | nocompress )
# Set bounding box of Mathematica graphics for inclusion in TeX

# 12/18/1991 adaptation by Dan Dill dan@chem.bu.edu of
# original written by Cameron Smith cameron@midd.bitnet
#	.  to work with Mathematica 2.0 
#	.  to handle fontsize by Mathematica system variable $DefaultFont
#	.  to use the zcat (compressed file) capability of Psfig/TeX 1.8
#	...  write bounding box information to file.bb as well as in file
#	...  optionally compress output to file.Z

# 1/1/1992 Dan Dill dan@chem.bu.edu
# Add -f to compress so previously compressed files will be silently
# overwritten

# Thanks to Gunnar Ekolin <ekolin@math.chalmers.se>:
# 2/4/1992 Dan Dill dan@chem.bu.edu
# Write *.bb file only if compression requested.  Delete *.{bb,Z} otherwise.

if [ $# -lt 3 ]
then
	echo Usage: $cmd file height \( compress \| nocompress \)
	echo Adjust height and set bounding box of Mathematica PostScript graphics.
	echo See the $cmd shell script for details
	exit 1
fi


# Pickup arguments
file=$1
height=$2
compressyesno=$3


# Save stdin (the graphic) to a temporary file
cat >/tmp/mmatemp.$$.ps


# get width
asprat=`awk '/AspectRatio/&&flag==0 {print $2; flag=1}' /tmp/mmatemp.$$.ps`
width=`echo "$height / $asprat" | bc`


# emit bounding box file
if [ "$compressyesno" = compress ]
then
echo "%!
%%BoundingBox: 0 0 $width $height" > $file.bb
else
# Delete compressed file (if any) so dvips doesn't get confused
rm -f $file.bb $file.Z
fi

# emit graphics file header
echo "%!
%%For TeX/Mathematica prologue tex-mma-2.0
%%BoundingBox: 0 0 $width $height
Mathdict begin
/Mwidth $width def
/Mheight $height def
/Mnodistort true def
end" > $file
#
# .. and rest of file
cat /tmp/mmatemp.$$.ps >> $file
#
# .. and optionally compress it
if [ "$compressyesno" = compress ]
then
	compress -f $file
fi


# remove temp file
rm /tmp/mmatemp.$$.ps
