#!/bin/bash

. $(which munch)

limit=250
leftrotation=200
rightrotation=-200

rotmatch $1 $(hundredths $leftrotation) $2
lefterror=$mindiff

rotmatch $1 $(hundredths $rightrotation) $2
righterror=$mindiff

iterlimit=12

while [ $iterlimit -gt 0 ] ; do

  iterlimit=$[iterlimit-1]
  
  adjust=$[(leftrotation-rightrotation)/4]

  if [ $lefterror -gt $righterror ] ; then
    echo "** Adjusting left limit **"
    leftrotation=$[leftrotation-adjust]
    rotmatch $1 $(hundredths $leftrotation) $2
    lefterror=$mindiff
  else
    echo "** Adjusting right limit **"
    rightrotation=$[rightrotation+adjust]
    rotmatch $1 $(hundredths $rightrotation) $2
    righterror=$mindiff
  fi

done

center=$[(leftrotation+rightrotation)/2]

echo "** Take center of remaining angle **"

rotmatch $1 $(hundredths $center) $2

echo ""
echo "** Ended with error $mindiff at rotation of $(hundredths $center) degrees **"
echo ""

echo ""
echo "** Performing brightness-match optimization **"
echo ""

brightmatch $tmp/strip.ppm $tmp/best.ppm

echo ""
echo "** Creating corrected right-side image **"
echo ""

ppmbrighten -v $(hundredths $brighter) < $tmp/rotated.ppm > $tmp/corrected.ppm

echo ""
echo "** Splicing images **"
echo ""

splice $1-1 $tmp/corrected.ppm

mv $tmp/final.tif $1-autojoin.tif

