#!/bin/bash
HELP="
  Converts a bunch of image files into a PDF file with 4 images per page.
  Usage: slides2pdf outputname imagefile1 imagefile2 ...
  There are some settings to tweak inside the script (`which $0`).

  Written by Eran Tromer <eran@tromer>, last change on 2004-03-31.
  Distributed under the GNU Genereal Public License without any warranty.
"
#==============================================================================
# Tweakables:

# Number of input images per output page (default: 1)
NUP=4;

# Rescaled image size in pixels (determines resolution).
# Leave undefined to avoid scaling)undefined to avois
SIZE="-geometry 600x600"

# Force number of colors:
#COLORS="-colors 240"

# Output page size:
PAPER=a4

# Margin around each logical image (before shrinking)
MARGIN=1cm

#==============================================================================

function tell {
	echo "> $*" > /dev/stderr
	"$@"
}
function cleanup { 
	tell rm -fr "$TMPDIR"
	trap - 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15
}

set -e 
if [ \! $# -ge 2 ]; then echo "$HELP"; exit 1; fi
OUTFILE="${1%.pdf}.pdf"
shift
FILES=( "$@" )
MERGED=_merged_
unset RFILES || true

# Create temporary directory:
TMPDIR=`mktemp -d /tmp/slides.XXXXXX` || { echo "Can't create temporaty directory"; exit 1; }
trap "cleanup; exit 1" 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15

# Convert to EPS:
for IN in "${FILES[@]}"; do 
	OUT="$IN._.eps"; RFILES[${#RFILES[@]}]="$OUT";
	tell convert ${SIZE:-} -compress RLE ${COLORS:-} "$IN" "EPS:$TMPDIR/$OUT"
done

pushd $TMPDIR

# Create LaTeX file
perl -pe "s/PAPER/${PAPER}paper/g; s/MARGIN/${MARGIN}/g;" > ${MERGED}.tex << 'EOF'
\documentclass{article}
\usepackage{geometry,graphicx}\pagestyle{empty}
\geometry{verbose,PAPER,tmargin=MARGIN,bmargin=MARGIN,lmargin=MARGIN,rmargin=MARGIN}
\begin{document}\thispagestyle{empty}
EOF
for RIN in "${RFILES[@]}"; do echo "\includegraphics[keepaspectratio=true,width=\textwidth]{$RIN}" >> ${MERGED}.tex; done
echo "\end{document}" >> ${MERGED}.tex

# Process LaTeX file
tell latex ${MERGED}.tex
tell dvips ${MERGED}.dvi -t$PAPER -o ${MERGED}.ps
if [ ${NUP:-1} == 1 ]; then
  cp ${MERGED}.ps ${MERGED}_NUP_.ps 
else
  tell psnup -p${PAPER} -m20 -d -$NUP ${MERGED}.ps > ${MERGED}_NUP_.ps 
fi
tell ghostscript -dNOPAUSE -sDEVICE=pdfwrite -dBATCH -dAutoFilterColorImages=false -dAutoFilterGrayImages=false -dGrayImageFilter=/FlateEncode  -dColorImageFilter=/FlateEncode  -dMonoImageFilter=/FlateEncode -dLZWEncodePages=true -dUseFlateCompression=true -dCompatibilityLevel=1.3 -sOutputFile=${MERGED}_NUP_.pdf ${MERGED}_NUP_.ps

popd
tell cp $TMPDIR/${MERGED}_NUP_.pdf "$OUTFILE"
cleanup
echo
echo "$OUTFILE" at your service.

