#!/bin/sh
#
# @(#)psnup	1.4 9/1/90 (cc.utexas.edu) /usr/share/src/public/postscript/psnup/SCCS/s.psnup
#

# Psnup -- take a postscript file and filter it to give n-up printing.
# The real work is done by the nup.pro and nup.pre postscript scripts
# supplied by Ned Batchelder at U. Penn. <ned@UPenn.CSNet>.
#
# Roy Smith <phri!roy> Wed Apr 22 13:33:39 EST 1987.

# Where to find the prologue and epilogue files.
lib=/usr/local/lib/ps
prologue=$lib/nup.pro
epilogue=$lib/nup.epi

# Default parameters.
Nup=2		# 2 spots per page.
Reverse=false	# No reversal (upper left to lower right).
Start=0		# First page goes in spot number 0.
File=""		# No file (read from standard input).

#
# Canonicalize arguments and complain about usage.
# This uses Rich Salz's getopt(1) which in turn needs getopt(3),
# both of which are public domain and in the mod.sources archive.
#
set -- `getopt "n:rs:" $@`
if [ $? != 0 ]
then
	echo "usage: psnup [-n 2|4|8|16] [-r] [-s #] [file]" >&2
	exit 1
fi

# Step through arguments.
skip=0
for flag
do
	if [ $skip -eq 1 ]
	then
		shift
		skip=0
		continue
	fi

	case "$flag" in
		-n)	case "$2" in
			   2|4|8|16) Nup="$2"
			             ;;
			   *)        echo psnup: -n must be 2, 4, 8, or 16 >&2
			             exit 1
			             ;;
			esac
			skip=1
			;;
		-r)	Reverse=true
			;;
		-s)	Start="$2"
			skip=1
			;;
		--)	break
			;;
	esac
	shift
done
shift		# because "--" causes break and skips shift after esac.
File="$1"	# if any arguments left, use the first as a file name.

#
# Before we begin, make sure all the files are readable.
#
if [ ! -r $prologue ]
then
	echo psnup: error reading $prologue, call for help. >&2
	exit 1
fi
if [ -n "$File" -a ! -r "$File" ]
then
	echo psnup: "$File" unreadable or non-existant. >&2
	exit 1
fi
if [ ! -r $epilogue ]
then
	echo psnup: error reading $epilogue, call for help. >&2
	exit 1
fi

#
# Emit the prologue, inserting parameters along the way.
#
sed	-e "s/@#@Pages@#@/$Nup/" \
	-e "s/@#@Rev@#@/$Reverse/" \
	-e "s/@#@Start@#@/$Start/" \
	$prologue

#
# Emit the file.  Note that if there was no file name, $File
# is the null string and this just copies stdin to stdout.
cat $File

#
# Emit the epilogue
#
cat $epilogue
