#!/afs/athena/contrib/perl/perl

($me = $0) =~ s%.*/%%;

require "getopts.pl";

do 'getopts.pl' || die "Can't do getopts.pl: $@";

$USAGE = "
Usage:	$me [-H] [-p|-l] [-r num] [-c num] [-j justflags]
		[-o orderflag] [-d|-n] [filenames...]
		justflags = [t|b][,][r|l] 
		orderflag = c or r \n";

do Getopts('Hplr:c:j:o:dn') || die $USAGE;

$PSLIB = "/mit/postscript/src/multi";

# set default options

$Landscape = "true";
$Nrows = 1;
$Ncols = 2;
$Left_Right = "true";
$Up_Down = "true";
$Row_Major = "true";
$Dividers = "true";

$pflg = 0;
$dflg = 0;

# parse command line options 

if (defined($opt_H)) {print $USAGE; exit 0;}

if (defined($opt_p)) {
	$pflg++;
	$Landscape = "false";
}

if (defined($opt_l)) {
	if ($pflg) {
		die "The -l option is incompatible with -p. See man page.\n";
	}
	else {
		$Landscape = "true"; 
	}
}

if (defined($opt_r)) {
	$_ = $opt_r;
	if (! /^[0-9]*$/) {
		die "Number of rows must be a positive integer.\n";
	}
	else {
		$Nrows = $opt_r;
	}
} 

if (defined($opt_c)) {
	$_ = $opt_c;
	if (! /^[0-9]*$/) {
		die "Number of columns must be a positive integer.\n";
	}
	else {
		$Ncols = $opt_c;
	}
}

if (defined($opt_j)) {
	$_ = $opt_j;
	if (! /^(t|b)?,?(r|l)?$/) {die $USAGE;} 
	opt_j: {
		$Up_Down = "true" if /t/; 
		$Up_Down = "false" if /b/; 
		$Left_Right = "false" if /r/;
		$Left_Right = "true" if /l/;
	}
}

if (defined($opt_o)) {
	$_ = $opt_o;
	opt_o: {
		if (/^r$/) {$Row_Major = "true";}
		elsif (/^c$/) {$Row_Major = "false";}
		else {die $USAGE;}
	}
}

if (defined($opt_d)) {
	$dflg++;
	$Dividers = "true";
}

if (defined($opt_n)) {
	if ($dflg) {
		die "Option -d incompatible with -n. See man page.\n";
	}
	else {
		$Dividers = "false";
	}
}

# open the multips header file, and feed it to stdout

open (MULTIPS,"$PSLIB/multi.ps") || die "Can't open $PSLIB/multi.ps: $@";

while ($_ = <MULTIPS>) {
	print $_;
}

close(MULTIPS);

# insert the multips option line definitions

print "$Landscape $Nrows $Ncols $Left_Right ";
print "$Up_Down $Row_Major $Dividers multi\n";

# insert the .PS files

if ($#ARGV == -1) {@ARGV[0] = "-";} # will read from stdin by default

foreach $filename (@ARGV) {
	
	open(PSFILE,$filename) || die "Can't open $filename: $@";
	while ($_ = <PSFILE>) {
		s/\%\!/\%/;   # remove the ! in %! everywhere.
		print $_;
	}
	close(PSFILE);
}

print "endmulti\n";
