: use /bin/sh
#    Copyright 1991, Chris Lewis, All Rights Reserved.
#
#    Permission to copy and further distribute is freely given provided
#    this copyright notice remains intact and that this software is not
#    sold for profit.
#
trap "rm -f /tmp/?$$" 0
rm -f /tmp/?$$

pages=2
#	Default is reversed for use with psroff with psxlate in the
#	pipeline to reverse pages.
reverse=true
start=1

for i
do
    case $i in
	-p2 | -p4 | -p8 | -p16)
	    pages=`echo $i | sed -e 's/^..//'`
	    if [ -z "$pages" -o -n "`echo $pages | sed -e 's/[0-9]*//'`" ]
	    then
		echo "$0: Non-numeric pages per sheet option $i" >&2
		exit 1
	    fi
	    ;;
	-p*)
	    echo "$0: -p option ($i) must be 2, 4, 8 or 16" >&2
	    exit 1
	    ;;
	-r)
	    reverse=false
	    ;;
	-R)
	    reverse=true
	    ;;
	-s*)
	    start=`echo $i | sed -e 's/^..//'`
	    if [ -z "$start" -o -n "`echo $start | sed -e 's/[0-9]*//'`" ]
	    then
		echo "$0: Non-numeric start spot option $i" >&2
		exit 1
	    fi
	    ;;
	-*)
	    echo "$0: invalid option $i" >&2
	    echo "usage: $0 [-pn] [-r | -t] [-sn] files" >&2
	    exit 1
	    ;;
	*)
	    files="$files $i"
	    ;;
    esac
    shift
done
if [ $start -gt $pages ]
then
    echo "$0: start option (-s$start) must be <= pages/sheet (-p$pages)" \
	>&2
    exit 1
fi
#echo pages $pages
#echo rev $reverse
#echo start $start

eof=`echo X | tr 'X' '\004'`

if [ -z "$files" ]
then
    files=-
fi

touch /tmp/A$$ /tmp/B$$

(
    cat $files
    echo
) | sed -e '1w /tmp/A'$$ \
	-e '1d' \
	-e '/^'$eof'$/w /tmp/B'$$ \
	-e '/^'$eof'$/d' > /tmp/C$$

if grep '^%' /tmp/A$$ > /dev/null
then
    cat /tmp/A$$
    > /tmp/A$$
else
    echo "%!"
fi

sed -e '/@#@Pages@#@/s//'$pages'/' \
    -e '/@#@Rev@#@/s//'$reverse'/' \
    -e '/@#@Start@#@/s//'$start'/' <<\!ENDPRO
@@@nup.pro@@@
!ENDPRO

cat /tmp/A$$
cat /tmp/C$$

cat <<\!ENDEPI
@@@nup.epi@@@
!ENDEPI
if [ -s /tmp/B$$ ]
then
    echo "\c" > /tmp/A$$
    if [ -s /tmp/A$$ ]
    then
	echo -n "$eof"
    else
	echo "$eof\c"
    fi
fi
