#!/usr/bin/perl
#parr:
# rearrange conforming PS code to print the pages in an arbitrary
# order.  The -[sS] options (for signature order) assume two-up, left
# to right.  The -o option takes a list of ranges, like this:
#	1-5    1-10,11-20    11-,1-10
# usage: parr [-o list] [-s] [-S n] [file]
#
# jgreely@cis.ohio-state.edu, 89/10/23

$order='';
$signFlag='';
$signCount=0;
$DEBUG=0;
$rangePrint=0;
$TMPDIR='/tmp';

while ($_ = $ARGV[0],/^-/) {
	shift;
	last if /^-\-$/;
	/^-o/ && ($order = shift,next);
	/^-S/ && ($signCount = shift,$signFlag++,next);
	/^-s/ && ($signFlag++,next);
	/^-d/ && ($DEBUG++,next);
	/^-r/ && ($rangePrint++,next);
	die "usage: parr [-d] [-r] [-o list] [-s] [-S n] [file]\n";
}
if ($signFlag && $order) {
	die "parr: -s and -o cannot be used together\n";
}

$file = "$TMPDIR/p$$.header";
@files = ($file);
$sheet=0;
open(file,">$file") ||
  die "$file: $!, stopped";
while (<>) {
	#
	# hack to use NeXT Preview: strip old '%%Pages:' lines
	#
	next if /^%%Pages:/;
	if (/^%%Page:/) {
		close(file);
		$sheet++;
		$file = "$TMPDIR/p$$.$sheet";
		push(@files,$file);
		open(file,">$file") ||
		  die "$file: $!, stopped";
	}
	if (/^%%Trailer/) {
		close(file);
		$file = "$TMPDIR/p$$.trailer";
		push(@files,$file);
		open(file,">$file") ||
		  die "$file: $!, stopped";
	}
	print file $_;
}
close(file);

@order = ();
if ($order) {
	foreach $range (split(/,/,$order)) {
		($start,$sep,$end) = split(/(-)/,$range);
		$start = 1 unless $start;
		$end = $sheet unless $end;
		if ($sep) {
			push(@order,$start..$end);
		}else{
			push(@order,$start);
		}
	}
}elsif ($signFlag) {
	if (! $signCount) {
		$signCount = $sheet;
		$signCount += (4 - $sheet % 4) if ($sheet % 4);
	}else{
		$signCount *=4;
	}
	for($base=0;$base<$sheet;$base+=$signCount) {
		@tmp = ($signCount/2+$base);
		push(@tmp,$tmp[0]+1,$tmp[0]+2,$tmp[0]-1);
		while ($tmp[3] > $base) {
			push(@order,@tmp);
			@tmp = ($tmp[0]-2,$tmp[1]+2,$tmp[2]+2,$tmp[3]-2);
		}
	}
}else{
	@order = (1..$sheet);
}

@tmp=@order;
@order=();
foreach $page (@tmp) {
	push(@order,$page > $sheet ? "B" : $page);
}

if ($rangePrint) {
	print join(',',@order),"\n";
	unlink @files unless $DEBUG;
	exit(0);
}

open(file,"$TMPDIR/p$$.header");
$_ = <file>;
print $_,"%%Pages: (atend)\n";
print while <file>;
close(file);

foreach $page (@order) {
	$count++;
	print "%%Page: ? $count\n%%OldPage: $page\n";
	if ($page eq "B") {
		print "showpage\n";
	}else{
		open(file,"$TMPDIR/p$$.$page");
		while (<file>) {
			print unless /^%%Page:/;
		}
		close(file);
	}
}
open(file,"$TMPDIR/p$$.trailer");
print while <file>;
close(file);
print "%%Pages: $count\n";

unlink @files unless $DEBUG;
exit(0);
