#!/bin/sh
#################################################################
#
#	@(#) rearrange	(c) Aug 2013 by hoz hznet.de
#	
#	This script is mainly used to bring the "Table of Content"
#	or similar pages from the end to the begining of a postscript
#	document.
#
#	The script takes a postscript file as input and produces
#	a pdf document.
#	It picks up the last 'n' pages (selected by -n, where 'n'
#	is the number of pages) of a postscript document, and put
#	these after the page given by option -p'x', where 'x' is
#	the page number.
#
#	Jun 2017	Option -r added
#
#	Example:
#		$ rearrange -2 -p3 example.ps
#	Takes the last two pages from example.ps and puts it after
#	the third page in the output pdf file "example.pdf".
#
#	The hard work is done by psselect and ps2pdf.
#	The script just gets and calculates the necessary parameters
#	and options for psselect.
#
#	Be careful: Like other ps* commands, this script will
#	create (and overwrite) an outputfile "<basename>.pdf". 
#
#################################################################
PATH=/bin:/usr/bin:/usr/local/bin

PROGNAME=`basename $0`

pages=1		# number of pages taken from the end of the document
		# default is 1
pos=1		# position to insert the pages (default is after the first page)

debug=0		# just print the command instead of running it if debug is set to 1
quiet=""	# set option -q for psselect
replace=0	

usage()
{
	test "$1" && echo "$1" 1>&2
	echo "usage: $PROGNAME [-d] [-#] [-p#] <file>.ps" 1>&2
	echo "\t-d\tdebug (just print out the psselect command but don't run it)" 1>&2
	echo "\t-q\tquiet (do not print page progress)" 1>&2
	echo "\t-#\tnumber of pages taken from the end (default is 1)" 1>&2
	echo "\t-p #\tinsert position page number" 1>&2
	echo "\t-r #\treplace the pages at pos -p " 1>&2
	echo "Be careful: $PROGNAME creates a outputfile <file>.pdf !" 1>&2
	exit 1
}

while test $# -gt 0
do
	case $1 in
	-[0-9])	# number of pages taken from the end of the document
		pages=`echo $1 | tr -cd "0-9"`
		;;
	-d)	debug=1
		;;
	-q)	quiet="-q"
		;;
	-p[0-9]*)
		pos=`echo $1 | tr -cd "0-9"`
		;;
	-p)	shift
		pos=`echo $1 | tr -cd "0-9"`
		;;
	-r)	replace=1
		;;
	-*)	usage "illegal option $1"
		;;
	*)	break
		;;
	esac
	shift
done

case "$1" in
*.ps)	infile=$1
	;;
"")	usage "no input file given"
	;;
*)	usage "no postscript file"
	;;
esac
dir=`dirname $infile`
outfile=`basename $infile .ps`
outfile="$dir/${outfile}.pdf"

# create pagelist for psselect
topages=`expr $pages + 1`

if test $pos -gt 1
then
	pagelist="-p1-$pos"
else
	pagelist="-p1"
fi
if test $pages -gt 1
then
	pagelist="$pagelist,_${pages}-_1"
else
	pagelist="$pagelist,_${pages}"
fi

if test $replace -eq 1
then
	pos=`expr $pos + $pages + 1`
else
	pos=`expr $pos + 1`
fi

pagelist="$pagelist,${pos}-_${topages}"

test $debug -eq 1 && echo "psselect $quiet $pagelist $infile | ps2pdf - $outfile" 1>&2 && exit 2
psselect $quiet $pagelist $infile | ps2pdf - $outfile
