#!/bin/sh
# psnup: put multiple pages onto one physical sheet of paper.
# usage:
#       psnup [-w<dim>] [-h<dim>] [-ppaper] [-l] [-2|-4|-8|-9] [file...]
#               -w<dim> sets the paper width
#               -h<dim> sets the paper height
#               -ppaper sets the paper size (width and height) by name
#               -l      is used if the pages are in landscape orientation

io= landscape=0 nup=1 width=-w21cm height=-h29.7cm

while test $# != 0
do      case "$1" in
        -w*)    width=$1 ;;
        -h*)    height=$1 ;;
        -p*)    paper=`echo "$1" | sed "s/^-./@/"` ;;
        -m*)    margins=`echo "$1" | sed "s/^-./@/"` ;; # not implemented yet
        -l)     landscape=1 ;;
        -2)     nup=2 ;;
        -4)     nup=4 ;;
        -8)     nup=8 ;;
        -9)     nup=9 ;;
        -s*)    xscale=`echo "$1" | sed "s/^-./@/"` ;;
        *)      io="$io $1"
        esac
        shift
done

case "$paper" in
a3|A3)  width=-w29.7cm height=-h42cm ;;
a4|A4)  width=-w21cm height=-h29.7cm ;;
a5|A5)  width=-w14.85cm height=-h21cm ;;
letter) width=-w8.5in height=-h11in ;;
legal)  width=-w8.5in height=-h14in ;;
esac

scale= offset=
case "$nup" in
2)      scale=@.707
        if [ $landscape = 0 ]
        then offset="(1w,0) (1w,.5h)"
        else offset="(0,.5h) (0,0)"
        fi
        landscape=`expr 1 - $landscape` ;;
4)      scale=@.5
        if [ $landscape = 0 ]
        then offset="(0,.5h) (.5w,.5h) (0,0) (.5w,0)"
        else offset="(.5w,0) (.5w,.5h) (1w,0) (1w,.5h)"
        fi ;;
8)      scale=@.3536
        if [ $landscape = 0 ]
        then offset="(.5w,0) (.5w,.25h) (.5w,.5h) (.5w,.75h)\
                     (1w,0) (1w,.25h) (1w,.5h) (1w,.75h)"
        else offset="(0,.75h) (.5w,.75h) (0,.5h) (.5w,.5h)\
                     (0,.25h) (.5w,.25h) (0,0) (.5w,0)"
        fi
        landscape=`expr 1 - $landscape` ;;
9)      scale=@.3333
        if [ $landscape = 0 ]
        then offset="(0,.666h) (.333w,.666h) (.666w,.666h)\
                     (0,.333h) (.333w,.333h) (.666w,.333h)\
                     (0,0) (.333w,0) (.666w,0)"
        else offset="(.333w,0) (.333w,.333h) (.333w,.666h)\
                     (.666w,0) (.666w,.333h) (.666w,.666h)\
                     (1w,0) (1w,.333h) (1w,.666h)"
        fi ;;
esac

if [ "X$xscale" != "X" ]
then scale=$xscale
fi

if [ $landscape = 0 ]
then rotate=
else rotate=L
fi

options= sep= page=0

set ""${offset}
while [ $page -lt $nup ]
do      options="$options${sep}$page$rotate$scale$1"
        sep=+
        page=`expr $page + 1`
        shift
done

pstops $width $height "$nup:$options" $io
