#!/bin/sh
# correct a set of files for illumination errors
# usage: 
#
#	example% light_correct grey.v im1.v im2.v 
#
# writes output images ic_im1.v and ic_im2.v 

# default prefix
VIPSHOME=${VIPSHOME-@prefix@}

# get name we were run as
name=$0
bname=`basename $name`

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

# check args
if [ $# -lt 2 ]; then
	echo "${bname}: usage: $bname <grey> <image1> <image2> ..."
	exit 1
fi

echo "Preparing grey ..."
grey=$1
shift

# 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 

# grey correct images in order
for i in "$@"; do
	echo "Correcting $i as ic_$i ..."
	$VIPSHOME/bin/vips im_multiply $t2.v "$i" $t1.v
	$VIPSHOME/bin/vips im_clip $t1.v "ic_$i"

	# remove the .desc as well
        name=`echo $name | sed -e 's/\.[^\.]*//'`
        /bin/rm -f "ic_$name.desc"
done

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