#!/bin/bash
#
# Convert single PDF document to DjVu, at low resolution.
#
# barnett 5/5/03

# help...
if [ $# -lt 2 ] ; then
cat << HELP

Usage: pdf2djvu infile[.pdf] outfile.djvu [startpage [endpage]]

Please edit script to change conversion options (DPI, etc)

HELP
	exit 0
fi

# resolution in dpi...
DPI=200

# remove .pdf from input name...
HEAD=`echo $1 | sed "s/.pdf//g"`

# decide if start and end pages...
if [ $# -lt 4 ] ; then
	ENDP=""
else
	ENDP="-l $4"
fi
if [ $# -lt 3 ] ; then
	STARTP=""
else
	STARTP="-f $3"
fi

# make sequence of PBMs... (could do in /tmp, instead use current dir)
# I found that the PBM file from pdftopbm was 6 times smaller than from gs,
# at the same dpi.
# For page limit: pdftopbm -r 150 -f 1 -l 15 $HEAD.pdf $HEAD
if [ -f "$HEAD.pdf" ] ; then
	echo "Converting $HEAD.pdf to PBMs. Please wait about 1 sec per page..."
	pdftopbm -r $DPI $STARTP $ENDP $HEAD.pdf $HEAD
else
	echo "pdf2djvu: cannot read file $HEAD.pdf"
	exit 1
fi

# convert them all to DJVU...
PBMS=$HEAD-??????.pbm
echo "Converting PBMs to DjVu..."
for INFILE in $PBMS; do
	OUTFILE=`echo "$INFILE" | sed "s/.pbm/.djvu/g"`
	echo "cjb2 -dpi $DPI $INFILE $OUTFILE"
	cjb2 -dpi $DPI $INFILE $OUTFILE
done

# Bundling...
echo "Bundling DjVu files into one document..."
DJVUS=$HEAD-??????.djvu
if [ -f "$2" ] ; then
	echo "Moving $2 to $2.old"
	mv -f $2 $2.old
fi
djvm -c $2 $DJVUS

# Tidying...
echo "Removing temporary files..."
rm -f $PBMS
rm -f $DJVUS

echo "done."
# end

