#!/usr/bin/env bash
# -*- mode: sh; coding: us-ascii-unix -*-

source libstacktrace || true
set -e -u -E

MANUAL="
Usage: $0 INFILE OUTFILE [BLURRADIUS;default:20px]

Takes a document scan INFILE (an image) and produces a monochromatized
output file version.

If INFILE=OUTFILE, creates a backup file INFILE.000.bak etc. 

If Only INFILE is given, uses BLURRADIUS=0 and OUTFILE=INFILE, which
is useful when editing a mono-chromed file has inflated its file size.  

Note that OUTFILE will always be a PNG file, regardless of extension.



The method for removing the background brightness gradient is based on
the discussion

  http://superuser.com/questions/693339/
"

if [[ "${1:-}" = "-?" ]] || [[ "${1:-}" = "-h" ]] || \
       [[ "${1:-}" = "--help" ]] || [[ $# -lt 1 ]]; then 
    echo "$MANUAL"
    exit 0
fi

INFILE="$(readlink -m "$1")"
if [[ $# -gt 1 ]]; then 
    BLURRADIUS="${3:-20}"
    OUTFILE="$(readlink -m "$2")"
else
    BLURRADIUS=0
    OUTFILE="$INFILE"
fi
TMPDIR="$(mktemp -d)"
cd "$TMPDIR"

if [[ $INFILE = $OUTFILE ]]; then
    bakname() { printf "$INFILE.%03d.bak" "$1"; }
    i=0;
    while [[ -e $(bakname $i) ]]; do i=$((i+1)); done 
    BAKNAME=$(bakname "$i")
    cp "$INFILE" "$BAKNAME"
fi
if [[ $BLURRADIUS -ne 0 ]]; then 
    convert -density 150 "$INFILE" -background white -flatten -colorspace  Gray 01.png
    convert 01.png -blur "${BLURRADIUS}x${BLURRADIUS}" 02.tif
    convert 01.png 02.tif -compose Divide_Src -composite 03.tif 
    convert 03.tif -threshold 80% -type bilevel -compress group4 png:"$OUTFILE"
else
    convert "$INFILE" -threshold 80% -type bilevel -compress group4 png:"$OUTFILE"
fi

rm -f 01.png 02.tif 03.tif
rmdir "$TMPDIR"