#!/bin/sh
# pnmcopier - emulate a badly-photocopied document to stdout
# created by scruss on Jan 1 02004

tmp_infile=/tmp/pnmcopier1$$
tmp_info=/tmp/pnmcopier2$$
tmp_rotated=/tmp/pnmcopier3$$
tmp_noise=/tmp/pnmcopier4$$
tmp_convol=/tmp/pnmcopier5$$
rm -f $tmp_infile $tmp_info $tmp_rotated $tmp_noise $tmp_convol

# Capture input file in a tmp file, in case it's a pipe
cat $@ > $tmp_infile

# get file details
pnmfile $tmp_infile > $tmp_info
read x x x pnmwidth x pnmheight x x < $tmp_info
rm -f $tmp_info

# for page skew emulation, a random angle +/-2 deg
random_small_angle=`echo "scale=5; $RANDOM / 8192 - 2" | bc | xargs -n 1 printf "%.2f\n"`

# make temporary convolution file for smoothing
cat <<CONVOL > $tmp_convol
P2
3 3
18
10 10 10
10 10 10
10 10 10
CONVOL

# rotate page, greyscale and smooth
pnmrotate $random_small_angle $tmp_infile 2> /dev/null | ppmtopgm | pnmconvol $tmp_convol  > $tmp_rotated
rm -f $tmp_infile

# get rotated file details
pnmfile $tmp_rotated > $tmp_info
read x x x newpnmwidth x newpnmheight x x < $tmp_info

# get crop offsets to restore to original size
x_offset=`echo "( $newpnmwidth - $pnmwidth ) / 2" | bc`
y_offset=`echo "( $newpnmheight - $pnmheight ) / 2" | bc`

# make PBM noise file
pgmnoise $newpnmwidth $newpnmheight | pnmconvol $tmp_convol | pgmtopbm -threshold -value 0.2 > $tmp_noise

# overlay the rotated and noise files
# crop to original size
# edge-enhance
# and threshold to simple b&w
pnmarith -multiply $tmp_rotated $tmp_noise 2> /dev/null | pnmcut $x_offset $y_offset $pnmwidth $pnmheight | pgmenhance | pgmtopbm -threshold

# clean up
rm -f $tmp_infile $tmp_info $tmp_rotated $tmp_noise $tmp_convol
