#!/bin/sh
#
# pshalf <files>
#
# Make Postscript output two pages to a page (rotated, approx 1/2 size).
#
# reads stdin or files, writes stdout.  Takes miminally conforming PostScript 
# input and produces minimally conforming PostScript output.
#
# Caveat: the output has mungled around with the showpage operator, which
# means that it cannot be used as input to any other program that must
# capture the showpage operator (for example psdraft, or pshalf itself).
#
# Written by Denise Draper	denise@cwi.nl
#

awk '
BEGIN			{ firsthalf = 1; outpages = 0;
print "%!PS-"
print "% This file has been run through pshalf; it should not be run"
print "% through any other PostScript post-processors."
print "/real$showpage/showpage load def/showpage/newpath load def"
			}
/^%%Pages:/		{ next }
/^%%PageFonts:/		{ next }
/^%%Page:/		{ if( firsthalf ) {
				if( outpages != 0 )
					print "HfDict begin ep end"
				outpages = outpages + 1
				print "%%Page: ? " outpages
				print "HfDict begin bp end"
			  } else {
				print "HfDict begin hp end"
			  }
			  firsthalf = 1 - firsthalf
			  next
			}
/^%%EndProlog/		{ 
print "% --Pshalf, by Denise Draper--"
print "/HfDict 20 dict def HfDict begin gsave/T matrix currentmatrix matrix"
print "defaultmatrix matrix invertmatrix matrix concatmatrix def initgraphics"
print "clippath pathbbox/y2 exch def/x2 exch def/y1 exch def/x1 exch def/X x2"
print "x1 sub def/Y y2 y1 sub def 90 rotate/XY X Y div def/Y2X Y X 2 mul div"
print "def/Tx y1 x1 Y2X mul sub def/Ty x2 y1 XY mul add neg def[Y2X 0 0 XY Tx"
print "Ty]concat matrix currentmatrix/O1D exch def X 0 translate matrix"
print "currentmatrix/O2D exch def grestore/nclip{initclip newpath x1 y1"
print "moveto x1 y2 lineto x2 y2 lineto x2 y1 lineto closepath clip newpath}"
print "def/bp{gsave O1D setmatrix nclip T concat}def/hp{grestore gsave O2D"
print "setmatrix nclip T concat}def/ep{real$showpage grestore}bind def end"
print "save"
print "% --End Pshalf--"
print "%%Pages: (atend)"
print "%%EndProlog"
			  next
			}
/^%%Trailer/		{ if( outpages != 0 )
				print "HfDict begin ep end"
			  print "%%Trailer"
			  print "%%Pages: " outpages
			  next
			}
			{ print $0 } ' $@
