#!/bin/sh

[ -s chkvotes.stp ] && exit
[ -s chkvotes.lck ] && exit
date >chkvotes.lck

find Ballot_Images_11.3.20 -name "*.tif" -type f |
sort | uniq |
while read fx
do
export fx
[ ! -f chkvotes.lck ] && break
echo "${fx}"
fn="$( basename ${fx} | sed -e "s~\.tif~~" )"; export fn
tab="$( dirname ${fx} | cut -d "/" -f 2 )"; export tab
bch="$( dirname ${fx} | cut -d "/" -f 3 )"; export bch
[ ! -d "votes" ] && mkdir votes
[ ! -d "votes/${tab}" ] && mkdir votes/${tab}
[ ! -d "votes/${tab}/${bch}" ] && mkdir votes/${tab}/${bch}
dir="votes/${tab}/${bch}"; export dir

for i in 0 1 2
do
[ ! -s "${dir}/${fn}-${i}.gif" ] && {
convert \
${fx}[${i}] \
${dir}/${fn}-${i}.gif
} >chkvotes.void 2>&1
done

[ "${tab}" = "Tabulator00180" ] && continue
[ "${tab}" = "Tabulator00190" ] && continue

### crop qrcode
[ ! -s "${dir}/${fn}-qrcode.gif" ] && {
convert \
${dir}/${fn}-0.gif \
-crop 800x400+40+550 \
+repage \
-trim \
+repage \
-density 150 \
-bordercolor 'white' \
-border 5 \
${dir}/${fn}-qrcode.gif
}

#### crop tallypres
[ ! -s "${dir}/${fn}-tallypres.gif" ] && {
convert \
${dir}/${fn}-2.gif \
-crop 600x55+20+100 \
+repage \
-trim \
+repage \
-density 150 \
-bordercolor 'white' \
-border 5 \
${dir}/${fn}-tallypres.gif
}
done

rm -f chkvotes.lck
