#!/bin/bash
#
# Digital Camera + This Software + Printer = A Document Photocopier
#
# Input:  pictures of B&W Text documents taken with a digital camera using
#         flash from about 3 feet away with no dark border around the page.
#
# Output1: b-file.tif (a very small B&W TIF file)
# Output2: g-file.jpg (a alternative grayscale file)
#
# If input is purely black and white,  Output1 should be better
# If input is not purely black and white, Output2 may be better
#
# Corey Satten, corey @ cac.washington.edu, March 2007

do1 () {
   echo starting $1 1>&2
   BASE="${1##*/}"; NAME=${BASE%.[jJ][pP][gG]}; TMP1="t-$BASE"; TMP2="x-$BASE"
   trap 'rm -f "$TMP1" "$TMP2"; exit' 0 1 2 13 15
   CGQ="-colorspace gray -quality"
   CGT="-compress group4 -density 480x480"

   convert $CGQ 99 "$1" -resize 5120x5120 "$TMP2"
   convert $CGQ 99 "$1" -resize 1024x1024 -negate -blur 15,15 -resize 5120x5120 "$TMP1"
   composite $CGQ 99 -compose plus "$TMP2" "$TMP1" "$TMP1"
   convert $CGQ 60 "$TMP1" -normalize -level 50,85% "g-$BASE"
   convert $CGT "$TMP1" -normalize -threshold 85% "b-$NAME.tif"
   rm -f "$TMP1" "$TMP2"
}

# This tries to detect multiprocessors and run 2 conversions in parallel
# Move CPUS=1 after the test to effectively disable the test.
CPUS=1
if [ -f /proc/cpuinfo ] ;then
    CPUS=`grep ^processor /proc/cpuinfo | wc -l`
    if [ "$CPUS" -lt 2 ] ;then CPUS=1; fi
fi

for i in "$@"; do
   case $#/$CPUS in
    0/*) exit;;                                     # done
    1/*) do1 "$1"; shift;;                          # only one file to do
    */1) do1 "$1"; shift;;                          # only one cpu to use
      *) do1 "$1" & do1 "$2"; wait; shift; shift;;  # process 2 files at once
   esac
done

exit 0
