#!/usr/local/bin/bash
## #############################################################
## printing a postscript file in A5 book format
## 
## Usage:
##          shufflea5 -[switch] [-P printer] [-f file] document.ps   
## Synopsis:
##   Printing booklets
## #############################################################
## @TABLE OF CONTENTS:		       [TOCD: 17:00 19 Jul 2001]
##
##      [0.1] Preview
##      [0.2] To File
##      [0.3] -- not to FILE --------------------------------
## ##########################################################
## @FILE:    shufflea5
## @PLACE:   Linux Homestation
## @FORMAT:  bash script
## @AUTHOR:  M. Oliver M'o'ller     <omoeller@verify-it.de>
## @BEGUN:   Tue Jun 20 22:19:45 2000
## @VERSION: V1.7                       Mon Nov 18 20:07:15 2002
## #############################################################
## 
SHELL=/usr/local/bin/bash
## -- BRICS R3 ----------------------------------------
PRINT_COMMAND="xlpr -P ";
PRINTER_OPTION="r312";
PRINTER_TUMBLE="-g -F";
PRINTER_TUMBLE_ARG="\"*PageSize A4,*Duplex DuplexTumble,*Manual Feed True\"";
PRINTER_LINEEND="";
PRINT_MEDIA="a4";
## ----------------------------------------------------
if [ ! -z "${DUPLEX_PRINTER}" ]; then
  PRINTER_OPTION=$DUPLEX_PRINTER;
fi;
## ----------------------------------------------------
NUMBER_OPTION="";
PSBOOK_OPTIONS="-g";
DELAY_SECONDS="10"; ## delay before printing
EVEN_OFFSET="00mm";
NPAGES="";
USE_A2PS=false;
A2PS_OPTIONS="-o- --portrait --columns=1 --medium=${PRINT_MEDIA} ";
## ----------------------------------------------------
ORDER_REVERSED="cat";  ## no reverse
FLIP_COMMAND="cat -";  ## no flip
ORDER_REVERSE_COMMAND="psselect -r";
X_OFFSET="0";
Y_OFFSET="0";
VERBOSE="false";
PREVIEW="true";
PREVIEW_PAGES="0- ";
PREVIEW_BLOCK="false";
FILE="";
SCALE="1.0";
MARGIN="";
FILTER="cat";
FRONT_ACCESS="cat";
SPLITUP_JOBS=false;
CREATE_FRONT_AND_BACK=false;
ASSUME_QUERRICHTUNG=false; ## (only affects israfil);
                           ## set -aq, if printer is set on Querrichtung
## -- secondary ---------------------------------------
OFIXPS_VERBOSE_FLAG="" ## no secondary verbose
## -- VERSION -----------------------------------------
VERSION_NUMBER="V1.7 ";
VERSION_DATE="Mon Nov 18 20:07:15 2002" ;
VERSION="$VERSION_NUMBER $VERSION_DATE";
## -- conversion constants -------------------------------------------------
export ONE_POINT=0.3514598; #mm
export ONE_INCH=25.4      ; #mm
## -- some aux functions ---------------------------------------------------
function point_to_mm {
  echo "0$1 * ${ONE_POINT}" |bc -l
}
function mm_to_point {
  echo "0$1 / ${ONE_POINT}" |bc -l
}
function inch_to_mm {
  echo "0$1 * ${ONE_INCH}" |bc -l
}
function mm_to_inch {
  echo "0$1 / ${ONE_INCH}" |bc -l
}
function point_to_inch {
  echo $(mm_to_inch  $(point_to_mm $1));
}
function inch_to_point {
  echo $(mm_to_point  $(inch_to_mm $1));
}
function convert_to_point { # only bare number
  case $1 in
    *[0-9-]mm   ) echo $(mm_to_point ${1:0:$((${#1}-2))});;
    *[0-9-]cm   ) echo $(mm_to_point $(echo "10 * ${1:0:$((${#1}-2))}"|bc -l));;
    *[0-9-]dm   ) echo $(mm_to_point $(echo "100 * ${1:0:$((${#1}-2))}"|bc -l));;
    *[0-9-]m   ) echo $(mm_to_point $(echo "1000 * ${1:0:$((${#1}-1))}"|bc -l));;
    *[0-9-]i    ) echo $(inch_to_point ${1:0:$((${#1}-1))});;
    *[0-9-]in   ) echo $(inch_to_point ${1:0:$((${#1}-2))});;
    *[0-9-]inch ) echo $(inch_to_point ${1:0:$((${#1}-4))});;
    *[0-9-]pt   ) echo ${1:0:$((${#1}-2))};;
    *[0-9-]     ) echo $1;;
    * ) abort "Illegal length: $1";; ## error
  esac
}
function convert_to_mm { # only bare number
  case $1 in
    *[0-9-]mm   ) echo ${1:0:$((${#1}-2))};;
    *[0-9-]cm   ) echo 10.0*${1:0:$((${#1}-2))}|bc -l;;
    *[0-9-]dm   ) echo 100.0*${1:0:$((${#1}-2))}|bc -l;;
    *[0-9-]m    ) echo 1000.0*${1:0:$((${#1}-1))}|bc -l;;
    *[0-9-]i    ) echo $(inch_to_mm ${1:0:$((${#1}-1))});;
    *[0-9-]in   ) echo $(inch_to_mm ${1:0:$((${#1}-2))});;
    *[0-9-]inch ) echo $(inch_to_mm ${1:0:$((${#1}-4))});;
    *[0-9-]pt   ) echo $(point_to_mm ${1:0:$((${#1}-2))});;
    *[0-9-]     ) echo $(point_to_mm $1);;
    * ) abort "Illegal length: $1";; ## error
  esac
}
## -- other aux functions:
function first_element { # -- get the first element in a list
  echo $@ | cut -d' ' -f 1
}
function abort { ## -- clear the temp files --
  echo "$0: ERROR: $1"
  echo "** shufflea5 aborted."
  exit 1;
}
function get_version_number_of_script { ## 0.00: nonexistent!
  PROG=$(which $1 2>/dev/null);
  if [ ! -z $PROG ] && [ -x $PROG ]; then
    $PROG --version 2>/dev/null |sed -e "s/@//g" |sed -e "s/\\./@/1" | sed -e "s/[^0123456789@]//g" | sed -e "s/@/./g" ;
  else
    echo "0.00";
  fi
}
function compute_minus { ## minus, scaled (used for comparison of floats)
  echo "10000000.0*(($1)-($2))" | bc -l | cut -d'.' -f 1;
}
function stripoffsuffix { ## remove last suffix (if present)
  if [ -z "$(echo $1 |grep  "\\.")" ]; then
    echo $1;
  else
    POS=${#1};
    while [ "${1:${POS}:1}" != "." ]; do
      POS=$((${POS}-1));
    done;
    echo ${1:0:${POS}};
  fi;
}
function stripoffpssuffix { ## remove last suffix (if .ps)
  if [ -z "$(echo $1 |grep  "\\.ps$")" ]; then
    echo $1;
  else
    POS=${#1};
    while [ "${1:${POS}:1}" != "." ]; do
      POS=$((${POS}-1));
    done;
    echo ${1:0:${POS}};
  fi;
}
function getfrontandback {
  if [ ! -e $1 ]; then
    abort "input file >>$1<< for getfrontandback does not seem to exist.";
  else
    GETFRONT_NAME=$(stripoffpssuffix $1);
    OUTNAME_FRONT=${GETFRONT_NAME}.front.ps;
    OUTNAME_BACK=${GETFRONT_NAME}.back.ps;
    while [ -e $OUTNAME_FRONT ]; do
      OUTNAME_FRONT=${OUTNAME_FRONT}.ps
    done;
    while [ -e ${OUTNAME_BACK} ]; do
      OUTNAME_BACK=${OUTNAME_BACK}.ps
    done;
    echo "** splitting $1 into $OUTNAME_FRONT and $OUTNAME_BACK";
    psselect -p1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127,129,131,133,135,137,139,141,143,145,147,149,151,153,155,157,159,161,163,165,167,169,171,173,175,177,179,181,183,185,187,189,191,193,195,197,199,201,203,205,207,209,211,213,215,217,219,221,223,225,227,229,231,233,235,237,239,241,243,245,247,249,251,253,255,257,259,261,263,265,267,269,271,273,275,277,279,281,283,285,287,289,291,293,295,297,299\
     $1 > ${OUTNAME_FRONT};
    psselect -p2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,274,276,278,280,282,284,286,288,290,292,294,296,298\
     $1 > ${OUTNAME_BACK};
    echo "** FACE-DOWN printers: lpr ${OUTNAME_BACK}; <REINSERT> ;lpr ${OUTNAME_FRONT} "
    echo "** FACE-UP   printers: lpr ${OUTNAME_BACK}; <REINSERT> ;psselect -r ${OUTNAME_FRONT} |lpr"
  fi
}
## -------------------------------------------------------------------------
## -- fix options -------------------------------------
if [ "$LOCATION" == "uu" ]; then ## -- Uppsala --------
  PRINTER_OPTION="pr1424_duplex2";
  PRINT_COMMAND="lpr -P ";
  PRINTER_LINEEND="";
  PRINTER_TUMBLE="";
  PRINTER_TUMBLE_ARG="";
fi;
if [ "$LOCATION" == "sri" ]; then ## -- SRI -----------
  # duplex simplex 2up landscape
  PRINT_MEDIA="letter";
  PRINT_COMMAND="lp -oduplex -onobanner -d";
  PRINTER_LINEEND="";
  PRINTER_TUMBLE="";
  PRINTER_TUMBLE_ARG="";
  OFIXPS_VERSION=$(get_version_number_of_script ofixps);
  if [ $(compute_minus 0$OFIXPS_VERSION 1.5) -lt 0 ]; then
    echo "$0: Need ofixps 1.5 or higher. " 1>&2;
    echo "Sorry. " 1>&2;
    exit 1;
  fi;
  ## later:  FLIP_COMMAND="ofixps -q -t -a -e ${EVEN_OFFSET} - - ";
fi;
if [ "$LOCATION" == "verified" ]; then ## -- Verified: israfil,falcon ------
  PRINT_MEDIA="a4";
  PRINT_COMMAND="lpr ";
  PRINTER_OPTION=" " ;
  DUPLEX_PRINTER=" " ;
  PRINTER_LINEEND="";
  PRINTER_TUMBLE="";
  PRINTER_TUMBLE_ARG="";
  OFIXPS_VERSION=$(get_version_number_of_script ofixps);
  if [ $(compute_minus 0$OFIXPS_VERSION 1.6) -lt 0 ]; then
    echo "$0: Need ofixps 1.6 or higher. " 1>&2;
    echo "Sorry. " 1>&2;
    exit 1;
  fi;
  ## later:  FLIP_COMMAND="ofixps -q -t -a -e ${EVEN_OFFSET} - - ";
fi;
if [ "$LOCATION" == "aalborg" ]; then ## -- AALBORG --------
  # duplex simplex 2up landscape
  PRINT_COMMAND="lp -oduplex -d";
  PRINTER_LINEEND="";
  PRINTER_TUMBLE="";
  PRINTER_TUMBLE_ARG="";
  OFIXPS_VERSION=$(get_version_number_of_script ofixps);
  if [ $(compute_minus 0$OFIXPS_VERSION 1.5) -lt 0 ]; then
    echo "$0: Need ofixps 1.5 or higher. " 1>&2;
    echo "Sorry. " 1>&2;
    exit 1;
  fi;
  ## later:  FLIP_COMMAND="ofixps -q -t -a -e ${EVEN_OFFSET} - - ";
fi;

## -- functions ------------------------------------------------------------
function print_usage()
{
  echo "usage:  shufflea5 [SWITCHES] [-P PRINTER] [-f file] [-m MARGIN] [-s SCALE] [-x X_OFFSET] [-y Y_OFFSET] [-# NUMBER] document.ps"
  echo "        -aq             : assume 'Querrichtung' (printer set to tumble)"
  echo "        -a              : print ASCII (through a2ps, one column)"
  echo "        -ao OPTIONS --  : additional a2ps options (only with -a)"
  echo "        -n		: don't send to printer"
  echo "        -N PAGES	: set number of pages explicitly"
  echo "        -v		: verbose output"
  echo "        -p		: preview before printing"
  echo "        -np		: NO preview before printing (whatever)"
  echo "        -pp PAGES	: preview only PAGES, e.g., 4-8 or 1,2,3"
  echo "        -R		: reverse order"
  echo "        -d PAGES        : divide into booklets with PAGES pages"
  echo "        -S		: split up to n/4 separate print jobs"
  echo "        -s SCALE	: magnification factor (from lower left pt)"
  echo "        -P PRINTER      : send to PRINTER; default: $PRINTER_OPTION"
  echo "        -f file         : write folded to file instead of printer"
  echo "        -b              : create separate files for front and back (only with -f)"
  echo "        -m MARGIN       : add a margin,e.g -1cm (negative margins scale up page)"
  echo "        -x X_OFFSET     : move pages X_OFFSET to the right"
  echo "        -y Y_OFFSET     : move pages Y_OFFSET to the right"
  echo "        -e EVEN_OFFSET  : add an extra x-offset to even pages (e.g. 10mm)"
  echo "        -# number       : number of copies"
  echo "        -i              : print immediately (default: wait ${DELAY_SECONDS} sec)";
  echo "        -h              : print this help text"
  echo "        -help           : print this help text"
  echo "        --version       : print version ($VERSION)"
}
function print_help()
{
 print_usage
 echo "";
 echo "description:";
 echo " Takes postscript file, scales it to A5 and creates a small booklet."
 echo " By default, this is directly sent to the printer (with ${DELAY_SECONDS} seconds delay";
 echo " in order to abort this process).";
 echo " If output is a file, no preview is shown.";
 echo "";
 echo " Before printing, a scaled preview (MARGIN/SCALE/OFFSET) displayed (via gv)."
 echo " The original may be in .gz .bz or bz2 form.";
 echo " The lengths given for offsets can be point ([]/pt), mm, cm, or inch.";
 echo " PDF files can be printed as well (filtered through gs).";
 echo " If -d is used, a number of print jobs (or files with numbers [1],2,3,..)";
 echo " is created. The preview operates on the complete input in this case.";
 echo "";
 echo " If -a is set AND not .ps[(gz|bz2)] ending is found, the input is assumed"
 echo " to be ASCII and is filtered through a2ps. If additional options should be ";
 echo " handed to a2ps, they have to be between -ao and the next --; e.g, to print ";
 echo " every 5th line with a number, use ... -a -ao --line-numbers=5 -- ..." ;
 echo "";
 echo "relies on:    psnup psbook psselect grep gs gzip bzip bzip2 a2ps";
 echo "              ofixps (V1.6 or higher) pstops";
 echo " ";
 echo "known problems: ";
 echo " * sometimes preview does not work properly for postscript generated from pdf";
 echo " ";
 echo " Remember to abort printing if it does not fit."
 echo "";
 echo "author:     M. Oliver M\"oller  <omoeller@verify-it.de>";
 exit;  
}
## -- AUX functions ---------------------------------------------
function gettheending { ## $1: name $2: desired ending
LENGTH=${#1}
POS=$(($LENGTH-${#2}));
if [ $POS -lt 0 ]; then
    POS=0
fi;
RESULT="*error*";
NOTDONE=true;
while($NOTDONE)do
    RESULT="${1:0:$POS}$2";
    if [ "${RESULT:0:$LENGTH}" == "$1" ]; then
	NOTDONE=false;
    fi;
    POS=$(($POS+1));
done;  
echo $RESULT
}
## -- required sub-scripts -------------------------------------------------
OFIXPS_VERSION=$(get_version_number_of_script ofixps);
if [ $(compute_minus 0$OFIXPS_VERSION 1.6) -lt 0 ]; then
  echo "$0: Need ofixps 1.6 or higher. " 1>&2;
  echo "Sorry. " 1>&2;
  exit 1;
fi;
## -- start ------------------------------
if [ "$1" == "" ]; then 
   print_usage
   exit;
fi;
for switch in $@; do
  case $AWAIT in
	   -P  ) PRINTER_OPTION="$switch";AWAIT="";;
	   -N  ) NPAGES="$switch";AWAIT="";;
	   -e  ) EVEN_OFFSET="$(convert_to_mm $switch)mm";AWAIT="";;
	   -f  ) FILE="$switch";AWAIT="";;
	   -m  ) MARGIN="$(convert_to_mm $switch)mm";AWAIT="";;
	   -d  ) DIVIDE="$switch";AWAIT="";;
	   -s  ) SCALE="$switch";AWAIT="";;
	   -x  ) X_OFFSET=$(convert_to_point $switch);AWAIT="";;
	   -#  ) NUMBER_OPTION="-# $switch";AWAIT="";;
	   -y  ) Y_OFFSET=$(convert_to_point $switch);AWAIT="";;
	  -pp  ) PREVIEW_PAGES="$switch";AWAIT="";;
	  -ao  ) if [ "$switch" == "--" ]; then \
	            AWAIT=""; \
  	         else  \
  	            A2PS_OPTIONS="${A2PS_OPTIONS} $switch" ; \
 	         fi;;
	    *  ) case $switch in
	     --help ) print_help;;
	      -help ) print_help;;
	      -h ) print_help;;
	        -aq ) ASSUME_QUERRICHTUNG=true;;
	        -ao ) AWAIT="-ao";;
	         -a ) USE_A2PS=true;;
	         -b ) CREATE_FRONT_AND_BACK=true;;
	         -i ) DELAY_SECONDS=0;;
	         -n ) PSBOOK_OPTIONS="";;
	         -v ) VERBOSE=true;;
	        -np ) PREVIEW_BLOCK=true;;
	        -pp ) AWAIT="-pp";;
	         -p ) PREVIEW=true;;
	         -R ) ORDER_REVERSED=${ORDER_REVERSE_COMMAND};;
	         -P ) AWAIT="-P";;
	         -S ) SPLITUP_JOBS=true;;
	         -N ) AWAIT="-N";;
	         -e ) AWAIT="-e";;
	         -f ) AWAIT="-f";;
	         -d ) AWAIT="-d";;
	         -# ) AWAIT="-#";;
	         -m ) AWAIT="-m";;
	         -s ) AWAIT="-s";;
	         -x ) AWAIT="-x";;
	         -y ) AWAIT="-y";;
          --version ) echo "Version: $VERSION";exit 1;;
		 -* ) print_help;;
                 *  ) NAME=$switch;;
	         esac
  esac
done;
## -- propagate ------------------------------------------------------------
if [ "${FILE}" != "" ]; then
  SPLITUP_JOBS=false;
fi;
if ${VERBOSE}; then
  OFIXPS_VERBOSE_FLAG="-vE";
fi;
## -- option-depending fixes -----------------------------------------------
#SCALE_FILTER="ofixps -q -s ${SCALE} -x ${X_OFFSET} -y ${Y_OFFSET} -e ${EVEN_OFFSET} - -"
SCALE_FILTER="pstops 1:0@${SCALE}(${X_OFFSET},${Y_OFFSET})";
if [ "$LOCATION" == "sri" ]; then ## -- SRI --------------------------------
  FLIP_COMMAND="ofixps -q ${OFIXPS_VERBOSE_FLAG} -a4 -t -a  - - ";
  SCALE_FILTER="ofixps -q ${OFIXPS_VERBOSE_FLAG} -a4 -s ${SCALE} -a -x ${X_OFFSET} -y ${Y_OFFSET} -e ${EVEN_OFFSET} - -"
fi;
if [ "$LOCATION" == "verified" ]; then ## -- Verified: israfil, falcon --------
  FLIP_COMMAND="ofixps -q ${OFIXPS_VERBOSE_FLAG} -a4 -t  -y 15mm -x -3mm -e 6mm - - ";
  #if switched on "Bindung: Querrichung", uncomment line below
  if ${ASSUME_QUERRICHTUNG}; then
    FLIP_COMMAND="cat -" ;
  fi;
  ## -----------------------------------------------------------
  ## below should be unneccessary.
  ##SCALE_FILTER="ofixps -q ${OFIXPS_VERBOSE_FLAG} -a4 -s ${SCALE} -x ${X_OFFSET} -y ${Y_OFFSET} -e ${EVEN_OFFSET} - -"
fi
if [ "$LOCATION" == "aalborg" ]; then ## -- AALBORG ------------------------
  FLIP_COMMAND="ofixps -q ${OFIXPS_VERBOSE_FLAG} -a4 -t -E 15mm - - ";
  SCALE_FILTER="ofixps -q ${OFIXPS_VERBOSE_FLAG} -a4 -s ${SCALE} -x ${X_OFFSET} -y ${Y_OFFSET} -e ${EVEN_OFFSET} - -"
fi;
## OLD: pstops 1:0@${SCALE}\\(${X_OFFSET},${Y_OFFSET});
FOUND_NON_ASCII=false;
if [ -e $NAME ] && [ "$(head -c 4 $NAME)" == "%!PS" ]; then
  FOUND_NON_ASCII=true;
fi;
## -- find right access ----------------------------------------------------
if [ ! -e $NAME ] && [ -e $(gettheending $NAME .ps) ]; then
  NAME=$(gettheending $NAME .ps);
  FOUND_NON_ASCII=true;
fi;
if [ ! -e $NAME ] && [ -e $(gettheending $NAME .eps) ]; then
  NAME=$(gettheending $NAME .eps);
  FOUND_NON_ASCII=true;
fi;
## -- unzipping required ------------------------------
if [ -e $(gettheending $NAME .ps.gz) ]; then
  NAME=$(gettheending $NAME .ps.gz);
  FILTER=" gzip -d -c ";
  FOUND_NON_ASCII=true;
fi;
if [ -e $(gettheending $NAME .ps.bz) ]; then
  NAME=$(gettheending $NAME .ps.bz);
  FILTER=" bzip -d -c ";
  FOUND_NON_ASCII=true;
fi;
if [ -e $(gettheending $NAME .ps.bz2) ]; then
  NAME=$(gettheending $NAME .ps.bz2);
  FILTER=" bzip2 -d -c ";
  FOUND_NON_ASCII=true;
fi;
## -- PDF files (unzipped) ----------------------------
if [ -e $(gettheending $NAME .pdf) ]; then
  NAME=$(gettheending $NAME .pdf);
  FRONT_ACCESS="gs -q -dNOPAUSE -dBATCH -sDEVICE=pswrite -sOutputFile=- -f ";
  FILTER="cat";
  FOUND_NON_ASCII=true;
fi;
## NOTE: zipped PDF files would apparently require some temporary files
##  (since the gs option "-" appears to be broken) and are therefore
##  not treated.
## -------------------------------------------------------------
## -- ASCII ----------------------------------------------------
if ${USE_A2PS} && ! ${FOUND_NON_ASCII}; then
  FRONT_ACCESS="a2ps ${A2PS_OPTIONS} ";
fi;
## -------------------------------------------------------------
if [ -z "$NPAGES" ]; then
  NPAGES=$(first_element $(${FRONT_ACCESS} $NAME|${FILTER}| grep "^\\%\\%Pages: [0123456789]+" |cut -d' ' -f 2 ));
fi;
## -- second try --------------------------------------
if [ -z "$NPAGES" ] || [ "$NPAGES" == "0" ]; then
  NPAGES=$(${FRONT_ACCESS} $NAME|${FILTER} |grep -c '^%%Page: [0123456789"]');
fi;
## -- third try ---------------------------------------
if [ -z "$NPAGES" ] || [ "$NPAGES" == "0" ]; then
  NPAGES=$(${FRONT_ACCESS} $NAME|${FILTER} |grep '^%%Pages: [0-9]'|cut -d':' -f 2|sed 's/ //g');
fi;
## --------------------------------------------------------------
if [ -z ${DIVIDE} ]; then
  DIVIDE=$NPAGES;
fi;
## -------------------------------------------------------------------------
if $VERBOSE; then
  echo "NAME:                  $NAME";
  echo "FILTER:                $FILTER";
  echo "USE_A2PS:              $USE_A2PS";
  echo "A2PS_OPTIONS:          $A2PS_OPTIONS";
  echo "PSBOOK_OPTIONS:        $PSBOOK_OPTIONS";
  echo "FILE:                  $FILE";	    
  echo "CREATE_FRONT_AND_BACK: $CREATE_FRONT_AND_BACK";	    
  echo "PREVIEW (switch):      $PREVIEW";
  echo "PREVIEW_BLOCK:         $PREVIEW_BLOCK";
  echo "SPLITUP_JOBS           $SPLITUP_JOBS";
  echo "NPAGES:                $NPAGES";
  echo "DIVIDE:                $DIVIDE";
  echo "PREVIEW_PAGES:         $PREVIEW_PAGES";
  echo "PRINTER_OPTION:        $PRINTER_OPTION";
  echo "PRINT_MEDIA:           $PRINT_MEDIA";
  echo "PRINT_COMMAND:         $PRINT_COMMAND";
  echo "PRINTER_TUMBLE:        $PRINTER_TUMBLE";
  echo "PRINTER_TUMBLE_ARG:    $PRINTER_TUMBLE_ARG";
  echo "NUMBER_OPTION:         $NUMBER_OPTION";
  echo "MARGIN:                $MARGIN";
  echo "SCALE:                 $SCALE";
  echo "X_OFFSET:              $X_OFFSET";
  echo "Y_OFFSET:              $Y_OFFSET";
  echo "EVEN_OFFSET:           $EVEN_OFFSET";
  echo "FLIP_COMMAND:          $FLIP_COMMAND";
fi;
## -- sanity check ------------------------------------
if [ ! -e ${NAME} ]; then
  echo "ERROR: no input file >>${NAME}<< exist";
  exit 1;
fi;
## ----------------------------------------------------
TMP_MARGIN="0mm";
if [ ! -z "$MARGIN" ]; then
  TMP_MARGIN=$MARGIN;
fi;
## ###############################################
## [0.1] Preview
## ###############################################
#echo "** Checkpoint 1";
if ! ${PREVIEW_BLOCK}; then
  if [ ! -z "$MARGIN" ] || \
   [ "${X_OFFSET}" != "0" ] || \
   [ "${Y_OFFSET}" != "0" ] || \
   [ "${EVEN_OFFSET}" != "00mm" ] || \
   [ "${ORDER_REVERSED}" != "cat" ] || \
   [ "${SCALE}" != "1.0" ] || \
   ${PREVIEW}; then
    ${FRONT_ACCESS} ${NAME} | \
     ${FILTER} | \
     psselect -p${PREVIEW_PAGES} | \
      ${SCALE_FILTER} | \
     ${ORDER_REVERSED}| \
     psnup -p${PRINT_MEDIA} -m${TMP_MARGIN}| \
     ${FLIP_COMMAND} | \
     gv -magstep -2  - ;
  fi;
fi;
#echo "** Checkpoint 2";
## ###############################################
## [0.2] To File (also when splitting up jobs)
## ###############################################
if ${SPLITUP_JOBS}; then
  FILE=/tmp/tmp.shuffla5.$$.for.job.splitup.ps
fi;
## ----------------------------------------------------
if [ "$FILE" != "" ]; then
  PART=1;
  FROM=1;
  TO=$DIVIDE;
  while [ $FROM -lt $NPAGES ]; do
    if [ $PART -eq 1 ]; then
      EXTENSION="";
    else
      EXTENSION="-$PART.ps";
    fi;
    if ${FRONT_ACCESS} ${NAME} | ${FILTER} | pstops "1:0@${SCALE}(${X_OFFSET},${Y_OFFSET})" |${ORDER_REVERSED}| psselect -p${FROM}-${TO} | psnup -m${TMP_MARGIN} | psbook | psnup -p${PRINT_MEDIA} -2| ${FLIP_COMMAND} | cat - > ${FILE}${EXTENSION}; then 
      echo "** booklet written to $FILE$EXTENSION" ;
      ## -- possibly: create front and back -------------------------
      if $CREATE_FRONT_AND_BACK; then
	getfrontandback "${FILE}${EXTENSION}";
      fi
    else
      echo "** Some failure occured. Sorry.";
      exit 1;
    fi;
    PART=$((${PART}+1));
    FROM=$(($FROM+$DIVIDE));
    TO=$(($TO+$DIVIDE));
  done;
  exit 0;
fi;
## ###############################################
## [0.3] -- not to FILE --------------------------------
## ###############################################
echo "** ****************************************"
echo "**    Printing on  $PRINTER_OPTION  in ${DELAY_SECONDS} seconds...  "
if [ "${FILE}" != "" ]; then
  echo "** tmp file residing as   $FILE";
fi;
echo "** ****************************************"
sleep ${DELAY_SECONDS};

if [ "${FILE}" == "" ]; then
  ## -- print in one or seversal chunks ------------------------------------

  #  if ${FRONT_ACCESS} ${NAME} | ${FILTER} | ${SCALE_FILTER} |${ORDER_REVERSED}| psnup -p${PRINT_MEDIA} -m${TMP_MARGIN} | psbook | psnup -p${PRINT_MEDIA} -2 | ${FLIP_COMMAND} | if [ -z "${PRINTER_TUMBLE}" ]; then ${PRINT_COMMAND} ${PRINTER_OPTION} ${NUMBER_OPTION} ${PRINTER_LINEEND}; else ${PRINT_COMMAND} ${PRINTER_OPTION}  ${NUMBER_OPTION} ${PRINTER_TUMBLE} ${PRINTER_TUMBLE_ARG} ${PRINTER_LINEEND}; fi; then
#    sleep 0;
#  else
#    echo "** Some failure occured. Sorry."
#    exit 1;
#  fi;
  
  FROM=1;
  TO=$DIVIDE;
  while [ $FROM -lt $NPAGES ]; do
    if ${VERBOSE}; then
      echo "** doing: ${FRONT_ACCESS} ${NAME} | ${FILTER} | pstops \"1:0@${SCALE}(${X_OFFSET},${Y_OFFSET})\" |${ORDER_REVERSED}| psselect -p${FROM}-${TO}| psnup -m${TMP_MARGIN}  | psbook | psnup -p${PRINT_MEDIA} -2 | ${FLIP_COMMAND} | if [ -z \"${PRINTER_TUMBLE}\" ]; then ${PRINT_COMMAND} ${PRINTER_OPTION} ${NUMBER_OPTION} ${PRINTER_LINEEND}; else ${PRINT_COMMAND} ${PRINTER_OPTION}  ${NUMBER_OPTION} ${PRINTER_TUMBLE} ${PRINTER_TUMBLE_ARG} ${PRINTER_LINEEND};"
    fi;
    if ${FRONT_ACCESS} ${NAME} | ${FILTER} | pstops "1:0@${SCALE}(${X_OFFSET},${Y_OFFSET})" |${ORDER_REVERSED}| psselect -p${FROM}-${TO}| psnup -m${TMP_MARGIN}  | psbook | psnup -p${PRINT_MEDIA} -2 | ${FLIP_COMMAND} | if [ -z "${PRINTER_TUMBLE}" ]; then ${PRINT_COMMAND} ${PRINTER_OPTION} ${NUMBER_OPTION} ${PRINTER_LINEEND}; else ${PRINT_COMMAND} ${PRINTER_OPTION}  ${NUMBER_OPTION} ${PRINTER_TUMBLE} ${PRINTER_TUMBLE_ARG} ${PRINTER_LINEEND}; fi; then
      FROM=$(($FROM+$DIVIDE));
      TO=$(($TO+$DIVIDE));
    else
      echo "** Some failure occured. Sorry."
      exit 1;
    fi;
  done;
else
  ## -- print in 2-page-parts ---------------------------------
  ## -- get # pages ---------------------------------
  if [ -z "$NPAGES" ]; then
    NPAGES=$(first_element $(cat ${FILE} | grep "^\\%\\%Pages: [0123456789]*" |cut -d' ' -f 2 ));
  fi;
  ## -- second try ----------------------------------
  if [ -z "$NPAGES" ]; then
    NPAGES=$(cat ${FILE} | grep -c "^\\%\\%Page: [0123456789]");
  fi;
  ## ------------------------------------------------
  echo "** Found $NPAGES folded pages."
  ## ------------------------------------------------
  PAGE=1;
  while [ ${PAGE} -le ${NPAGES} ]; do
    if cat ${FILE} | psselect -p${PAGE},$((${PAGE}+1))| if [ -z "${PRINTER_TUMBLE}" ]; then ${PRINT_COMMAND} ${PRINTER_OPTION} ${NUMBER_OPTION} ${PRINTER_LINEEND}; else ${PRINT_COMMAND} ${PRINTER_OPTION}  ${NUMBER_OPTION} ${PRINTER_TUMBLE} ${PRINTER_TUMBLE_ARG} ${PRINTER_LINEEND}; fi; then
      ##if cat ${FILE} | psselect -p${PAGE},$((${PAGE}+1)) > a${PAGE}.ps; then
      echo "** printed double page $PAGE/$(($PAGE+1))";
      PAGE=$((${PAGE}+2));
    else
      echo "** Some failure occured. Sorry."
      rm $FILE;
      exit 1;
    fi;
  done;
  sleep 3;
  rm ${FILE};
fi;
    
echo "** printer queue: ******************************"
if [ -z ${PRINTER_OPTION} ]; then
  lpq
else
  lpq -P $PRINTER_OPTION;
fi;
echo "** *********************************************"
echo "** done."
exit 0; ## --- OK ------------------------------

### Local Variables: ***
### mode: ksh ***
### eval: (defun update-global-date () (let ((pos (point-marker))) (goto-char (point-min)) (if (search-forward-regexp "^VERSION_DATE=" (point-max) t) (progn (kill-line) (insert (format "\"%s\" ;" (current-time-string))) (basic-save-buffer) (message "** Version Date Updated."))) (goto-char pos))) ***
### eval: (defun new-global-hh-insert-disclaimer () (interactive) (insert-disclaimer) (update-global-date) (ksh-mode) (font-lock-mode)(local-set-key [f4] #'new-global-hh-insert-disclaimer)) ***
### eval: (progn (ksh-mode)(font-lock-mode) (local-set-key [f4] #'new-global-hh-insert-disclaimer)) ***
### comment-column:0 ***
### comment-start: "### "  ***
### comment-end:"***" ***
### End: **
