#!/usr/bin/perl -T
#
#NAME
#  PSftr - Add labels to bottom of PostScript document
#
#SYNOPSIS
#  PSftr <left> <center> <right>
#
#DESCRIPTION
#  Takes a PS file on stdin and outputs the same file with the  three
#  strings at the bottom, aligned to the left, center and right.
#
#BUGS
#  The physical page size here is  US  "letter",  with  usable  edges
#  determined experimentally on an HP LaserJet 4L printer.  The edges
#  are probably different for other printers, but I  don't  yet  know
#  how  to  determine them.  Wouldn't it be great if we could ask the
#  printer from within the PS?
#
#SUBSTITUTIONS
#  If the following tokens appear in the fields, they are expanded:
#
#  %D  The current date, in ISO standard format (CCYY-MM-DD)
#  %T  The current time, UT if the locale isn't defined
#  %P  The page number
#
#SEE ALSO
#  PShdr
#
#AUTHOR John Chambers <jc@trillian.mit.edu> March 2002
#  You can do anything you like with this program, except claim  that
#  you wrote it.  If you make any improvements, send me email.

$flag = 0;
$gray = 0;			# Do we want grayed labels?
$page = 0;
$llbl = shift | '';	# Text at bottom left
$clbl = shift | '';	# Text at bottom center
$rlbl = shift | '';	# Text at bottom right

$fh =   8;			# Font height for labels
$lm =  18;			# Don't print left of this
$rm = 588;			# Don't print right of this
$te = 782;			# Don't print above this
$be =  30;			# Don't print below this

$tm = $be - $fh;	# Highest text position
$pw = $rm - $lm;	# Usable page width
#ph = $te - $be;	# Usable page height (not used)

($ss,$mm,$hh,$DD,$MM,$YY) = gmtime(time);
$MM ++;
$YY += 1900;

while (<>) {
	if (/^%%Page:/) {
		if ($flag) {
			print "grestore\n";
		}
		$flag = 1;
		$page ++;
		$Llbl = &expand($llbl);
		$Clbl = &expand($clbl);
		$Rlbl = &expand($rlbl);
		print $_;
		print "gsave\n";
		print ".20 setgray\n" if $gray;	# Do we want grayed labels?
		print "/Helvetica-Bold-Condensed findfont $fh scalefont setfont\n";
		if ($Llbl) {
			print "$lm $tm moveto\n";
			print "(" . &expand($Llbl) . ") show\n";
		}
		if ($Clbl) {
			print "$pw 2 idiv ($Clbl) stringwidth pop 2 div round sub $lm add\n";
			print "$tm moveto\n";
			print "(" . &expand($Clbl) . ") show\n";
		}
		if ($Rlbl) {
			print "$rm ($Rlbl) stringwidth pop sub\n";
			print "$tm moveto\n";	# Height of text
			print "(" . &expand($Rlbl) . ") show\n"; 
	#		print "($Rlbl) show\n";
		}
		print "grestore\n";
	} else {
		print;
	}
}

exit 0;

# Expand %X inclusions:
sub expand {
	local($s) = @_;
	$s =~ s/%P\b/$page/g;
	$s =~ s/%D\b/sprintf('%04d-%02d-%02d',$YY,$MM,$DD)/eg;
	$s =~ s/%T\b/sprintf('%02d:%02d:%02d',$hh,$mm,$ss)/eg;
	return $s;
}
