#!/bin/bash
# Creates and mails 1col version of a file
# Needs: pdftex pdfinfo mimeit
# mail1col -h for usage

while [ $# -gt 0 ]
do
  case "$1" in
    -f) SOURCE=$2; shift;;
    -s) SUBJECT=$2; shift;; 
    -d) DEST=$2; shift;;
     *) cat <<END >&2
Usage: mail1col [-f file.pdf] [-d address] [-s "subject"]
Converts file.pdf using 1colpdf and mails result to address
     -f file   file in AAAI 2col proceeding PDF format (required)
     -d addr   address to use for email message (required)
     -s str    subject to use for email message (default: "Read: file name")
END
        exit 0;;
  esac
  shift
done

if [ ! -f "$SOURCE" ]
  then echo "No pdf file specified. Aborting."
       exit
fi

if [ -z "$DEST" ]
  then echo "No mail address specified. Aborting."
       exit
fi

SIZE=`pdfinfo $SOURCE | grep "Page size:" | grep letter`
if [ -z "$SIZE" ]
  then echo "File $SOURCE is not letter size PDF. Aborting."
       exit
fi

PAGES=`pdfinfo $SOURCE | grep Pages: | sed -e 's/.*: *\([0-9]*\)/\1/'`
if [ -z "$PAGES" ]
  then echo "No page count for file $SOURCE. Aborting."
       exit
fi

if [ -z "$SUBJECT" ]
  then echo "No mail subject specified. Using the file name."
       SUBJECT="Read: $SOURCE"
fi

pdftex -interaction batchmode \
"\\def\\pdffile{$SOURCE}" \
"\\def\\pageCount{$PAGES}" \
'\csname pdfmapfile\endcsname{}' \
'\pdfpagewidth=300bp\relax' \
'\def\title{\pdfvorigin=375bp\relax\pdfpageheight=100bp\relax' \
'  \setbox0=\hbox{\pdfximage width 400bp page 1{\pdffile}' \
'    \pdfrefximage\pdflastximage}' \
'  \pdfhorigin=-53bp\relax\ht0=\pdfpageheight' \
'  \shipout\box0\relax}' \
'\def\page#1{' \
'  \setbox0=\hbox{\pdfximage width 745bp page #1{\pdffile}' \
'    \pdfrefximage\pdflastximage}' \
'  \pdfhorigin=-64bp\relax\ht0=\pdfpageheight' \
'  \shipout\box0\relax' \
'  \setbox0=\hbox{\pdfximage width 745bp page #1{\pdffile}' \
'    \pdfrefximage\pdflastximage}' \
'  \pdfhorigin=-387bp\relax\ht0=\pdfpageheight' \
'  \shipout\box0\relax}' \
'\def\allpages#1{\pdfvorigin=105bp\relax\pdfpageheight=795bp\relax' \
'  \count0=1\relax ' \
'  \loop\page{\the\count0}\ifnum\count0<#1\advance\count0by1\repeat}' \
'\title\allpages{\pageCount}' \
'\csname @@end\endcsname' \
'\end'

echo "Mailing 1col version of $SOURCE to $DEST"
metasend -b -s "$SUBJECT"  -S 5000000 -t "$DEST" \
-e 7bit -m "TEXT/PLAIN" -f /dev/null -n \
-e base64 -m "APPLICATION/pdf" -f texput.pdf
echo "Cleaning up"
rm texput.*
