#!/bin/csh -f
# Create an average sky from specified images

if ( $#argv < 5 ) then
caterr <<'EOF'
Create an average sky from specified images
  usage: skyavg2 result threshold area image1 image2 [...]
  Arguments: result - average sky image file to be created
	     threshold - the detection threshold in sky sigma
	     area - the minimum detection area
	     image1 image2 ... - images to be used

  Pairs of images are differenced and the objects are detected
  with the specified detection threshold and minimum area and 
  a 5 x 5 detection filter.  The images are then averaged excluding
  the detected objects.  If objects overlap on all images a zero
  value is assigned.  A temporary working directory skyavg.tmp
  is created and removed.
'EOF'
exit
endif

set sky=$1
set th=$2
set ar=$3
shift
shift
shift
# Make working directory
mkdir skyavg.tmp
foreach i ($argv)
ln $i skyavg.tmp/a$i
end
cd skyavg.tmp

set cat=($argv)
set i=1
set j=2
while ($i < $#argv)
opimg a$argv[$i] a$argv[$j] - = skyavg >& /dev/null
setcat skyavg.cat >&/dev/null <<EOF
y
skyavg











$th
$th

$ar

skyavg.areas

y
y
EOF
detect skyavg.cat
set cat[$i]=${argv[$i]}.cat
ffilter G D <skyavg.cat >$cat[$i]
setcat $cat[$i] >&/dev/null <<EOF
y
a$argv[$i]
















skyavg.areas

EOF
@ i++
@ j++
end
set cat[$i]=${argv[$i]}.tmp
ffilter F D <skyavg.cat >$cat[$i]
setcat $cat[$i] >&/dev/null <<EOF
y
a$argv[$i]















skyavg.areas

EOF
avgsky ../$sky $cat
cd ..
rm -r skyavg.tmp
