#! /bin/sh -e
#	duplex_to_l7380 - send print to l7380

#  15 Aug 08  Henry Grebler    First cut. (Cannibalised from ...)
#=============================================================================#
# psmandup --- produce a version of a PS file to print in manual Duplex.

# Copyright (c) 1998, 1999 Akim Demaille, Miguel Santana

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, you can either send email to this
# program's maintainer or write to: The Free Software Foundation,
# Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA.

# Author: Akim Demaille <Akim.Demaille@freefriends.org>
#----------------------------------------------------------------------#
# Issues	15 August 2008

# Here are the issues: I think the case of even total pages is
# probably ok. As far as the case of odd total pages is concerned,
# there are 2 possibilities: put an extra blank page through the
# printer; or treat the last page as special.

# I don't much like feeding extra sheets through the printer
# unnecessarily. (I'm sure others don't share my sensibilities.)

# The printer shuffles the pages, so the top page in the input hopper
# ends up as the bottom page of the output hopper. The pages go in
# orientated "naturally" ie one could look at them and read them and
# come out with the writing upside down. The side to be printed is at
# the bottom on the way in and on the top on the way out.

# The most "natural" arrangement would see the final output exactly
# ready for use (as near as possible). So page 1 would be on the top,
# face up (albeit with the writing upside down, but fixing that is
# another degree of difficulty - and hardly worth it); page 2 on its
# back; page 3 below page 1, and so on.

# The nearest next of kin would see the whole output bundle upside
# down: page 1 at the bottom facing downwards; page 2 on its back;
# page 3 above page 1, and so on. One would pick up the entire output
# bundle and turn it over.

#--------------
# Decision
#--------------

# Here's what I've decided for jobs with an odd number of pages.

#	print the even pages descending (eg 6,4,2)
#	issue the instruction "Take the output, rotate horizontally
#		through 180 degrees (so east faces west); and place in
#		the input hopper. Cover with a single blank sheet."
#	print the odd pages ascending (eg 1,3,5,7)

# Result

# Pages come out "naturally"; last page only goes through once.

# Downside

# Well, it's not the best arrangement for a printer which is far from
# the user and/or shared between many people. But I'm right next to my
# printer and can do all the manipulations without getting out of my
# chair.

#----------------------------------------------------------------------#
# HMG changes	14 August 2008

# Let PSSELECT do the work (avoid thinking).

# Call the odd pages "odds" and the even pages "evens" (was the other
# way around). (Since I wrote the previous sentence, I've dispensed
# with the variables "odds" and "evens".)

# Print even pages ascending first; then odd pages descending. This
# results in the last page on the output stacker being page 1 above
# page 3, 5, etc. Perfect. Just rotate horizontally through 180
# degrees. (Was odd forwards, even backwards.)

# Don't PSFIX anything. (I might change my mind later.)

# Don't delete temporary files.

# I don't really understand what the original did: what I do is
# display instructions on how and what to print; and then what to
# delete.

# Basically I liked the principle of what they did, pretty much; but
# the detail didn't suit me.

#----------------------------------------------------------------------#


# Get the name of the program
program=`echo $0 | sed 's#.*/##g'`

# Local vars
address=0	# Where to put the manual feed feature
back=:		# Print the back side pages.
debug=
file=
front=:		# Print the front side pages.
output=-	# Default is stdout
#fixps=${FIXPS:-fixps}
echo "HMG - deliberately not using fixps"
fixps=
message=
psselect=${PSSELECT:-psselect}
psset=${PSSET:-psset}
tmpdir=`mktemp -d -t psmandup.XXXXXX` || { echo "$program: Cannot create temporary dir!" >&2 ; exit 1; }

# These two must be kept in synch.  They are opposed.
verbose=echo
quiet=:

# The version/usage strings
version="psmandup 2.1 (GNU a2ps 4.14)
Written by Akim Demaille.

Copyright (c) 1998-1999 Akim Demaille, Miguel Santana
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."

usage="\
Usage: $program FILE
Tries to produce a version of the PostScript FILE to print in manual
Duplex.

Options:
 -h, --help           display this help and exit
 -v, --version        display version information and exit
 -q, --quiet          don't print informational messages
 -o, --output=FILE    save result in FILE.  If FILE is \`-', send to stdout
 -n, --no-fix         don't call fixps to fix PS problems in FILE
 -f, --front          output only the front pages (recto) on the regular
                      tray
 -b, --back           output only the back pages (verso) on the manual
                      feed tray

Produced output is meant for PS level 2 printers which don't support
Duplex printing, but support Manual Feed.  Once the first set of pages
is printed (odd pages), manual feed is asked: introduce the odd pages
to print the even pages on the other side.

Because there is usually a short time out for manually fed jobs, you
should really be next to the printer.  If ever the time out expired,
use the option -b to send only the missing part.

Environment variables FIXPS, PSSELECT and PSSET, if defined, are used
to find the tools.

News, updates and documentation: http://www.inf.enst.fr/~demaille/a2ps/
Report bugs to <bug-a2ps@gnu.org>"

help="Try \`$program --help' for more information."

# Parse command line arguments.
option_without_arguments='vhsqnDbf'

# Push a token among the arguments that will be used to notice when
# we ended options/arguments parsing.
arg_sep="$$--$$"
set dummy ${1+"$@"} "$arg_sep"
shift
while test "x$1" != "x$arg_sep"; do

  # Handle --option=value by splitting apart and putting back on argv.
  case "$1" in
    --*=*)
      opt=`echo "$1" | sed -e 's/=.*//'`
      val=`echo "$1" | sed -e 's/[^=]*=//'`
      shift
      set dummy "$opt" "$val" ${1+"$@"}
      shift
      ;;

    -[$option_without_arguments]?*)
      # Prefix $1 with x to avoid running `echo -na' for instance.
      opt=`echo "x$1" | sed -e 's/x-\(.\).*/-\1/'`
      rest=`echo "x$1" | sed -e 's/x-.\(.*\)/-\1/'`
      shift
      set dummy "$opt" "$rest" ${1+"$@"}
      shift
      ;;

    # This case needs to be protected so that the case `-??*' does
    # not split long options without arguments
    --*)
      ;;

    # This is an option with argument.  Split apart and put back on argv.
    -??*)
      opt=`echo "x$1" | sed -e 's/x-\(.\).*/-\1/'`
      arg=`echo "x$1" | sed -e 's/x-.\(.*\)/\1/'`
      shift
      set dummy "$opt" "$arg" ${1+"$@"}
      shift
      ;;
  esac

  # Now, handle the options.  $1 is the option *only*.  If it has an
  # argument, it is now necessarily in $2 etc.  Remember to shift
  # when fetching an argument.
  case "$1" in
    -v | --v*) echo "$version"; exit 0;;
    -h | --h*) echo "$usage"; exit 0;;
    -q | -s | --s* | --q*) verbose=:; quiet=echo;;
    # Delay debugging so that options parsing does not appear
    -D | --deb*) debug=-D ;;
    -o | --out*) shift ; output=$1 ;;
    -b | --bac*) front= ; back=: ;;
    -f | --fro*) front=: ; back= ;;
    -) # We are working with stdin ;;
       set dummy "$@" "$1"
       shift
       ;;
    -n | --no*) fixps= ;;

    --) # What remains are not options.
      shift
      while test "x$1" != "x$arg_sep"; do
        set dummy ${1+"$@"} "$1"
        shift
	shift
      done
      break;;

    -*)
      echo "$program: Unknown or ambiguous option \`$1'." >&2
      echo "$program: Try \`--help' for more information." >&2
      exit 1;;
    *) set dummy ${1+"$@"} "$1"
       shift
       ;;
   esac
   shift
done
# Pop the token
shift


# Check the number of arguments.
case $# in
  0)  file=-;;
  1)  file=$1;;
  *)  echo "$program: too many arguments" 1>&2
      echo "$help"  1>&2
      exit 1;;
esac

if test -n "$debug"; then
  # Set -x now if debugging
  set -x
else
  # Temp dir.  Get ready not to leave junk (if not debugging)
###  trap "/bin/rm -rf $tmpdir" 0 1 2 3 13 15
	:
fi

# If printing from stdin, save into a tmp file
if test $file = '-'; then
  file=$tmpdir/stdin.ps
  cat > $file
fi

# Fix the file beforehand, so that we can really expect to find the
# page numbers.
if test -n "$fixps"; then
  $fixps $file -o $tmpdir/fixed.ps `$quiet -q`
  file=$tmpdir/fixed.ps
fi

# Get the number of pages of the document
num_pages=`sed -ne '/^%%Pages:/{
s/%%Pages: \\([0-9]*\\).*$/\\1/p
q
}' $file`

	fbn=`basename $file`

	odd_flag=false
	case "$num_pages" in
		*[13579])	odd_flag=true;;
	esac


# Reorder the pages
# $psselect -q $odds$separator$evens $file > $tmpdir/ordered.ps

	echo Reordering the pages. There are $num_pages pages in this job.
	set -x
	$psselect -p1-$num_pages -e $file > $tmpdir/$fbn.evens.ps
	$psselect -p1-$num_pages -o -r $file > $tmpdir/$fbn.odds.ps
	set +x

	cat <<EOF
Here's what to do:

	lp $tmpdir/$fbn.evens.ps

Take the bundle of pages from the output hopper and rotate them 180
degrees horizontally (so east now points west). Do NOT invert; the
printed side should be on top.

EOF

	$odd_flag && cat <<EOF
As the total number of pages is odd, put a blank sheet on top of the
bundle.

EOF
	cat <<EOF
Place the bundle into the input hopper.

	lp $tmpdir/$fbn.odds.ps

	rm -rf $tmpdir

Good luck!

EOF

	exit 0
