#!/usr/bin/perl
#
#NAME
#  PShdr - Add labels to top of PostScript document
#
#SYNOPSIS
#  PShdr <left> <center> <right>
#
#DESCRIPTION
#  Takes a PS file on stdin and outputs the same file with the three  strings
#  at the top.
#
#  If the <center> string starts with '+', it means to put the  string  (with
#  the  '+'  stripped off) at the top of all pages, including the first.  The
#  default is to not print the <center> string on the first page, since  most
#  pages have some sort of title info there.
#  
#
#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?
#
#IDEAS
#  We should add bottom labels, too. And a way to include the date.
#
#AUTHOR John Chambers <jc@trillian.mit.edu> February 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;
$page = 0;
$Llbl = shift | '';	# Text at top left
$Clbl = shift | '';	# Text at top center
$Rlbl = shift | '';	# Text at top right

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

$tm = $te - $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;

if ($Clbl =~ s/^\+//) {$firstlbl = 1} else {$firstlbl = 0}

while (<>) {
	if (/^%%Page:/) {
		if ($flag) {
			print "grestore\n";
		}
		$flag = 1;
		$page ++;
		print $_;
		print "gsave\n";
#		print ".20 setgray\n";	# Do we want grayed labels?
		print "/Helvetica findfont $fh scalefont setfont\n";
		if ($Llbl) {
			print "$lm $tm moveto\n";
			print "(" . &expand($Llbl) . ") show\n";
		}
		if ($Clbl && ($page>1 || $firstlbl)) {
			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"; # if $Rlbl;	# Why did we do this?
		}
		print "grestore\n";
	} else {
		print;
	}
}

exit 0;

# Expand %X inclusions:
sub expand {
	local($s) = @_;
	$s =~ s/%P\b/$page/g;
	$s =~ s/%D\b/$YY-$MM-$DD/g;
	return $s;
}
