#!/usr/bin/env perl

sub landscape_letter {
   $ph = 11.0 * 72;
   $pw = 8.5 * 72;
   $margin = 36;
}

sub epscat {

    local(@files)=@_;
    local($version)='#(@)$Version$';
    local(@date)=localtime(time);
    local($date)=join("/",@date[4,3,5]);
    local($pages)=$#files;

    print <<EOF;
%!PS-Adobe-2.0
%%Title: Slides
%%Creator: epscat @files
%%CreationDate: $date
%%Orientation: Landscape
%%Pages: $pages
%%BoundingBox: 0 0 $pw $ph
%%BeginSetup
%%IncludeFeature: *PageSize Letter
%%EndSetup
%%EndComments

EOF

    $page = 0;
    foreach (@_) {
	$page++;
	print "\n%%Page: $page $page\ngsave\n";
	open(IN,"<$_");
	while(<IN>) {
	    if (($x1,$y1,$x2,$y2) = /^%%BoundingBox: (\d+) (\d+) (\d+) (\d+)/){
	        if ( $flopit ) {
                   ($y1,$x1,$y2,$x2) = ($x1,$y1,$x2,$y2);
                   print "\n90 rotate 0 -$pw translate\n";
                }
		print "% debug $x1 $y1 $x2 $y2\n";
		$w = $x2 - $x1;
		$h = $y2 - $y1;
		print "%debug w $w h $h pw $pw ph $ph\n";
		$scale = ($pw - 2 * $margin) / ($w + 0.0);
		$xc = ($x2 + $x1 + 1 ) / 2.0 * $scale;
		$yc = ($y2 + $y1 + 1 ) / 2.0 * $scale;
		$pxc = $pw / 2.0;
		$pyc = $ph / 2.0;
		$xs = $pxc - $xc;
		$ys = $pyc - $yc;
		print "%debug scale $scale xc $xc yc $yc xs $xs ys $ys\n";
		print "$scale $scale scale \n";
		print "$xs $ys translate\n";
	    }
	    if (/^%%/) {
	       s/^/%% /o;
	    }
	    print $_;
	}
	close(IN);
	print "\nshowpage\ngrestore\n"
    }
    print "%%Trailer\n";
    print "%%EOF\n";
}

$flopit = 0;
&landscape_letter;

if ( $ARGV[0] eq '-f' ) {
   $flopit = 1;
   shift @ARGV;
}

&epscat (@ARGV);
