#!/bin/csh -f
#
#  Similar to "pshalf"...  will print 4 pages on one.
#  Hacks the scribe'd definitions, so don't run a 4up'ed
#  document through 4up again.
#
#  Takes a filename as an argument, writes to standard output.
#

set process = $$
set temp_file = /tmp/page_up.$process

set page_num = 0

#
#  Kill the standard Scribe definitions, and replace them with our
#   own definitions.
#
echo "\
	s^/BS^% REDEFINED % /BS^\
	s^/ES^% REDEFINED % /ES^" > $temp_file

#
#  Here's our definitions...
#
set first_one = `fgrep -n '%%EndProlog' $1 | awk -F: '{print $1}'`
echo "${first_one}a\\
	/BS {\\
	/tr2 exch def\\
	/tr1 exch def\\
	/SV save def\\
	1 setlinewidth\\
	306 792 moveto 306 0 lineto stroke\\
	0 396 moveto 612 396 lineto stroke\\
	tr1 tr2 translate .005 -.005 scale} def\\
	/ES {SV restore} bind def\\
	/ESNEW {showpage SV restore} bind def" >> $temp_file

#
#  Replace BS and ES to use our definitions instead.
#
foreach line_num (`fgrep -n '%%Page:' $1 | awk -F: '{print $1}'`)
	set prev_line = $line_num;  @ prev_line--
	set next_line = $line_num;  @ next_line++
	@ page_num++
	if ($page_num > 4)	set page_num = 1
	switch ($page_num)
	case 1:
		echo "${prev_line}s/ES/ESNEW/" >> $temp_file
		echo "${next_line}s/BS/0.0 792.0 BS/" >> $temp_file
		breaksw
	case 2:
		echo "${next_line}s/BS/306.0 792.0 BS/" >> $temp_file
		breaksw
	case 3:
		echo "${next_line}s/BS/0.0 396.0 BS/" >> $temp_file
		breaksw
	case 4:
		echo "${next_line}s/BS/306.0 396.0 BS/" >> $temp_file
		breaksw
	endsw
end

#
#  Special Case -- we need to catch the last one and do a showpage before
#	exiting.  Also, draw in the 'page breaks'.
#
set last_one = `fgrep -n '%%Trailer' $1 | awk -F: '{print $1}'`
@ last_one--
echo "${last_one}s/ES/ESNEW/" >> $temp_file

#
#  Execute the 'sed' file we've created on the original input file, and
#	get rid of the 'sed' script.
#
#sed -f $temp_file $1 > $1.temp
#echo File written out to $1.temp.  lpr and rm it.

sed -f $temp_file $1
rm $temp_file

