#!/usr/bin/perl

# This assembles a template from files on thecommand line
# reading their bounding boxes

if (defined $ARGV[0]) {
	$n = $#ARGV + 1;
	# print "n = ", $n, "\n";
	# for ($i=0;$i < $n; $i++) {
	# 	print "$ARGV[$i]\n";
	# }
	
	# print out preface
	
	printPreface();
	
	# get bounding boxes from figure file
	
	getBoundingBox($ARGV[0]);
	$llx0 = $llx;
	$lly0 = $lly;
	$urx0 = $urx;
	$ury0 = $ury;
	
	print "% - main figure ----------------------------------------------\n";
	print "\n";
	print "BeginEPSF\n";
	print "\n";
	print "% Make here whatever\n"; 
	print "% coordinate changes you need to in order\n";
	print "% to embed your figure correctly (usually none).\n";
	print "\n";
	print "% Figure file bounding box: $llx $lly $urx $ury", "\n";
	print "\n";
	print "%%BeginDocument: $ARGV[0]\n";
	print "\n";
	print "(", $ARGV[0], ") run\n";
	print "\n";
	print "%%EndDocument\n";
	print "EndEPSF\n";
	print "\n";

	# get bounding boxes from label files
	
	for ($i=1;$i<$n;$i++) {
		getBoundingBox($ARGV[$i]);
		print "% - labelfile  ----------------------------------------------\n";
		print "\n";
		print "BeginEPSF\n";
		print "\n";
		print "% Label bounding box: $llx $lly $urx $ury", "\n";
		print "\n";
		print "$llx0 $lly0 translate", "\n";
		print "\n";
		print "% Put further coordinate chnage here.\n";
		print "% Insert?\n";
		print "\n";
		print "-$llx -$lly translate", "\n";
		print "\n";
		print "%%BeginDocument: $ARGV[$i]\n";
		print "\n";
		print "(", $ARGV[$i], ") run\n";
		print "\n";
		print "%%EndDocument\n";
		print "EndEPSF\n";
		print "\n";
	}
	
	printTrailer();
	
} else {
	print "No input files specified!\n";
	exit;
}

sub getBoundingBox() {
	$f = $_[0];
	print STDERR "<< Opening ", $f, "... >>\n";
	open(FILE, $f) or die;
	while ($_  = <FILE>) {
		if (m/^%%BoundingBox:[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)/) {
		 	$llx = $1;
		 	$lly = $2;
		 	$urx = $3;
		 	$ury = $4;
		}
	}
}

sub printPreface {
	print "%!PS-Adobe-3.0 EPSF-3.0\n";
	print "%%BoundingBox: llx lly urx ury\n";
	print "% Insert?\n";
	print "\n";
	print "% The bounding box above\n"; 
	print "% should be the bounding box of the final document,\n";
	print "% usually that of the main figure.\n";
	print "\n";
	print "%%Pages: 1\n";
	print "\n";
	print "%%EndComments\n";
	print "%%BeginProlog\n";
	print "\n";
	print "(psepsf.inc) run\n";
	print "\n";
	print "%%EndProlog\n";
	print "\n";
	print "%%Page: 1 1\n";
	print "\n";
	print "/pagesave save def\n";
	print "\n";
}

sub printTrailer {
	print "\n";
	print "pagesave restore showpage\n";
	print "%%EOF\n";

}
