#!/bin/csh
# 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 

# get name we were run as
set name=$0
set bname=$name:t

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

# check args
if( $#argv < 2 ) then
	echo "${bname}: usage: $bname <grey> <image1> <image2> ..."
	exit 1
endif

echo "Preparing grey ..."

# find image size
set width=`$VIPSHOME/bin/header $1 Xsize`
set height=`$VIPSHOME/bin/header $1 Ysize`

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

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

# grey correct images in order
foreach i ( $argv[2-] )
	echo "Correcting $i as ic_$i ..."
	$VIPSHOME/bin/im_multiply $t2.v $i $t1.v
	$VIPSHOME/bin/im_clip $t1.v ic_$i

	# remove the .desc as well
	set name = $i:r
	/bin/rm -f ic_$name.desc
end

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