#!/bin/sh -
do_opt=1
best=0
rot=0
a4=0
eps=0
usage="Usage: $0 [-no_opt] [-best] [-rot] [-a4] [-eps] in.ps [out.pdf]"

case "x$1" in
"x-no_opt") do_opt=0 ; shift ;;
esac

case "x$1" in
"x-best") best=1 ; shift ;;
esac

case "x$1" in
"x-rot") rot=1 ; shift ;;
esac

case "x$1" in
"x-a4") a4=1 ; shift ;;
esac

case "x$1" in
"x-eps") eps=1 ; shift ;;
esac

case $# in
2) ifilename=$1 ; ofilename=$2 ;;
1) ifilename=$1
   if `echo $1 | grep -i '\.e*ps$' > /dev/null`
   then
      ofilename=`echo $1 | sed 's/\..*$/.pdf/'`
   else
      echo "$usage" 1>&2
      exit 1
   fi ;;
*) echo "$usage" 1>&2 ; exit 1 ;;
esac

if [ $best == 1 ]
then
	options="-dPDFSETTINGS=/prepress \
	-r1200 \
	-dMonoImageResolution=1200 \
	-dGrayImageResolution=1200 \
	-dColorImageResolution=1200 \
	-dDownsampleMonoImages=false \
	-dDownsampleGrayImages=false \
	-dDownsampleColorImages=false \
	-dAutoFilterMonoImages=false \
	-dAutoFilterGrayImages=false \
	-dAutoFilterColorImages=false \
	-dMonoImageFilter=/FlateEncode \
	-dGrayImageFilter=/FlateEncode \
	-dColorImageFilter=/FlateEncode"
else
	options="-dPDFSETTINGS=/prepress \
	-r600 \
	-dDownsampleMonoImages=true \
	-dDownsampleGrayImages=true \
	-dDownsampleColorImages=true \
	-dMonoImageDownsampleThreshold=2.0 \
	-dGrayImageDownsampleThreshold=1.5 \
	-dColorImageDownsampleThreshold=1.5 \
	-dMonoImageResolution=600 \
	-dGrayImageResolution=600 \
	-dColorImageResolution=600 \
	-dAutoFilterMonoImages=false \
	-dMonoImageFilter=/FlateEncode \
	-dAutoFilterGrayImages=true \
	-dAutoFilterColorImages=true"
fi

if [ $rot == 1 ]
then
	options="$options -dAutoRotatePages=/PageByPage"
fi

if [ $eps == 1 ]
then
	options="$options -dEPSCrop"
fi

set -x

if [ $a4 == 1 ]
then
	# Resize from A4 to letter size
	psresize -Pa4 -pletter "$ifilename" myps2pdf.temp.ps
	ifilename=myps2pdf.temp.ps
fi

gs -q -dSAFER -dNOPAUSE -dBATCH  \
	-sDEVICE=pdfwrite -sPAPERSIZE=letter -sOutputFile=myps2pdf.temp.pdf \
	-dCompatibilityLevel=1.3 \
	$options \
	-dMaxSubsetPct=100 \
	-dSubsetFonts=true \
	-dEmbedAllFonts=true \
	-dColorConversionStrategy=/LeaveColorUnchanged \
	-dDoThumbnails=true \
	-dPreserveEPSInfo=true \
	-c .setpdfwrite -f "$ifilename"

if [ $do_opt == 1 ]
then
	pdfopt myps2pdf.temp.pdf $ofilename
else
	mv myps2pdf.temp.pdf $ofilename
fi
rm -f myps2pdf.temp.pdf myps2pdf.temp.ps
