#! /bin/bash
# Last edited on 2023-02-20 17:16:19 by stolfi

# Concatenates serveral EPS figure files into an A4 PDF document,
# with one figure per page. 
#
# For each figure, provides a "%%Page:" indicator 
# at the beginning and a "showpage" command at the end.
# Collects all document fonts into a single "%%DocumentFonts" at
# the beginning of the file.

# Usage: ${0##*/} {EPSFILE}... > {PDFFILE}

efiles=( "$@" )

tmp="/tmp/$$"

tfile=${tmp}.ps
fnts=${tmp}.fnts

# Collect the '%%DocumentFonts'
for f in ${efiles[@]} ; do 
  cat $f \
    | egrep -e '%%DocumentFonts:' \
    | egrep -v -e '[(]atend[)]' \
    | sed -e 's/%%DocumentFonts: *//g' -e 's/ *$//g' \
    >> ${fnts}
done

# Concatenate EPS files, remove unneeded headers, insert "%%Page:"
page=1
echo "%!PS-Adobe-3.0" >> ${tfile}
echo "%%CreationDate: `date '+%Y-%m-%d %H:%M:%S'`" >> ${tfile}
echo "%%BoundingBox: 0 0 596 842" >> ${tfile}
echo "%%DocumentFonts: `cat $fnts | sort | uniq`" >> ${tfile}
echo "%%DocumentPaperSizes: a4" >> ${tfile}
for f in ${efiles[@]} ; do 
  cat $f \
    | sed \
        -e '/%!PS-Adobe/d' \
        -e '/%%CreationDate/d' \
        -e '/%%DocumentFonts/d' \
        -e '/%%BoundingBox/d' \
        -e 's/%%Trailer/showpage/g' \
        -e "s/%%Pages:[ 0-9]*$/%%Page: ${page}/g" \
        -e 's: EPS-2.0::g' \
    >> ${tfile}
  page=$(( ${page} + 1 ))
done
echo "%%Trailer" >> ${tfile}

gs -sDEVICE=pdfwrite \
  -dNOPAUSE -dBATCH -dSAFER \
  -sOutputFile=- \
  ${tfile}
  
# rm -f ${tfile}
