#!/usr/local/bin/perl 
# fitps: a script to slightly transform an EPS file so that:
#   a) it is guarenteed to start at the 0,0 coordinate
#   b) it sets a page size exactly corresponding to the BoundingBox
# This means that when GhostScript renders it, the result needs no
# cropping. GhostScript can then write a graphic file direct without
# the tedious pnmcrop etc. It needs a Level 2 PS interpreter.
#
# If the bounding box is not right, of course, you have problems...
#
# The only thing I have not allowed for is the case of
# "%%BoundingBox: (atend)", which is more complicated.
#
# Sebastian Rahtz, for Elsevier Science
$filedate="1996/07/10";
$fileversion="1.1";
$Filename=$ARGV[0];
open(TMP,"<$Filename") ||  die "Usage: fitps <filename>";
$bbneeded=1;
local $bbpatt="[0-9\.\-]";
while (<TMP>) { 
 if ( /%%BoundingBox: (atend)/) {
	$bbneeded = 0;
        print;
	}
 elsif ( /%%BoundingBox:(\s$bbpatt+)\s($bbpatt+)\s($bbpatt+)\s($bbpatt+)/ ) 
 { 
# only read the *first* bounding box
     if ($bbneeded) {
	 $width = $3 - $1;
	 $height = $4 - $2;
	 $xoffset = 0 - $1;
	 $yoffset = 0 - $2;
	 print "%%BoundingBox: 0 0 $width $height\n";
	 print "<< /PageSize [$width $height] >> setpagedevice\n";
	 print "gsave $xoffset $yoffset translate\n";
	 $bbneeded=0;
     }
# else ignore that embedded BoundingBox anyway
 }
else
 {    print;  }
}
close(TMP);
print "grestore\n";

;


