#!/bin/bash

# correct a set of files for illumination errors
#
# usage:
#
#       example% light_correct <grey> image1 image2 etc
#
# writes output images ic_image1.* and ic_image2.* where * is the new file type.

name=`basename $0`

# check args
if [ $# -lt 2 ]; then
	echo "usage: $name <grey> image1 image2 ..."
	echo "writes ic_image1 ic_image2 ..."
	exit 1
fi

grey=$1
shift

# names of our temp files
t1="light_correct_temp1"
t2="light_correct_temp2"

echo "Preparing grey ..."

# find image size
width=`$VIPSHOME/bin/vips im_header_int Xsize $grey`
height=`$VIPSHOME/bin/vips im_header_int Ysize $grey`

# smooth the grey out
$VIPSHOME/bin/vips im_shrink $grey $t1.v 20 20
$VIPSHOME/bin/vips im_resize_linear $t1.v $t2.v $width $height

# and make the correction image
mean=`$VIPSHOME/bin/vips im_avg $t2.v`
$VIPSHOME/bin/vips im_powtra $t2.v $t1.v -1
$VIPSHOME/bin/vips im_lintra $mean $t1.v 0 $t2.v

# convert each argument
for i in $*; do
	path=`dirname $i`
	base=`basename $i`
	new=$path/ic_$base

	echo "Light correcting $i to produce $new ..."
	if [ -f $new ]; then
		echo "($new already exists, skipping)"
	else
		$VIPSHOME/bin/vips im_multiply $t2.v $i $t1.v
		$VIPSHOME/bin/vips im_clip $t1.v $new

		# remove the .desc as well, needed by old ip global balance
		name=${new%*.*}
		/bin/rm -f $name.desc
	fi
done

# more cleanup
echo "Cleaning up ..."
/bin/rm -f $t1.v $t1.desc
/bin/rm -f $t2.v $t2.desc


