#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  pdfjoin - Join PDF files into a single file 
#
#SYNOPSIS
#  pdfjoin [options] [file]..
#REQUIRES
#
#DESCRIPTION
# This program uses gs (ghostscript) to combine a list of PDF files into a
# single PDF file.
#
# If a file name on the command line exists, we use it; if it doesn't  exist,
# we append ".pdf" and use that file (if it exists). So you can omit a ".pdf"
# or ".PDF" suffix if you like to save a bit of typing. This was done so that
# this  script and mkprog can both use the same list of file names with their
# suffixes omitted.
#
#OPTIONS
# 
# -O<file>
#   Write the PDF output to <file>.  The default is standard output.
#
#EXAMPLES
#
#FILES
#
#BUGS
# If files foo and foo.pdf both exist, we'll use foo rather than foo.pdf even
# if foo isn't in PDF format.  So far this hasn't been a problem.
#
#SEE ALSO
#  "man gs"
#   http://bugs.ghostscript.com/
#   comp.lang.postscript
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu> June 2016
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 1;	# Verbose level.

$outfile = '-';		# Write to stdout by default
$infiles = '';		# List of PDF files to combine

foreach $arg (@ARGV) {
	print STDERR "$P: arg=\"$arg\n" if $V>1;
	if (($flg,$opt,$val) = ($arg =~ /^([-+])(\w)(.*)$/)) {
		print STDERR "$P: flg '$flg' opt '$opt' val 'val'\n" if $V>1;
		if ($opt eq 'O' ) {
			$outfile = $val;
			print STDERR "$P: outfile=\"$outfile\"\n" if $V>1;
		} else {
			print STDERR "$P: Option $flg$opt not recognized, ignored.\n" if $V;
		}
	} elsif (-f $arg) {
		print STDERR "$P: infile=\"$arg\"\n" if $V>1;
		$infiles .= "$arg ";
	} elsif (-f "$arg.pdf") {
		print STDERR "$P: infile=\"$arg.pdf\"\n" if $V>1;
		$infiles .= "$arg.pdf ";
	} else {
		print STDERR "$P: arg \"$arg\" not recognized, ignored.\n" if $V;
	}
}

$cmd = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=$outfile $infiles";
print STDERR "$P: cmd=\"$cmd\"\n" if $V>1;
$result = `$cmd`;
$exitstat = $?;
if ($result) {
	print $result;
} else {
	print STDERR "$P: No output produced.\n" if $V>1;
	$exitstat = 1 unless $exitstat;
}

print STDERR "$P: Exit with status $exitstat.\n" if $V>1 || $exitstat;
exit $exitstat;
