#!/bin/sh

# Kyle Davenport 2007 kdavenpo-at-tx-dot-rr-dot-com
# you may distribute this script under terms of the GPL

# expect pdf filename in 1st arg
base=${1%%.pdf}

# extract images
pdfimages "$1" "$base"

# multiple images.  only tiff supports 2color
# ==> this for loop fails if $base has spaces in it!
for i in $base-???.pbm ;do 
	base2=${i%%.pbm}
	convert $i -sample 50% -depth 1 $base2.tiff
	if identify -verbose $base2.tiff|grep -A2 Histogram|sort -n|tail -1|grep -q black
	then
		convert $base2.tiff -negate new.tiff
		mv new.tiff $base2.tiff
	fi
	rm -f "$i"
done

if [ "$i" == "$base-000.pbm" ]; then
	mv $base2.tiff $base.tiff
fi


