#!/bin/csh -f
#
# Script to automatically reduce CCD images with IRAF.
# Requires WCSTOOLS for image coregistration (i.e. alignment). 
# DS9 is also useful but not required.
#
# GSS 2006.05.19-21, split from align.csh 2006.09.23.
#
# to do: cosmic ray randling, better selection of nstatpix and minrad

set GAIN=1.
set RDNOISE=0.
# settings for IMSTAR for star detection
set minrad=2
set nstatpix=200
# number of iterations for IRAF to use when calculating shifts
set niter=10
# pixel rejection algorithm for combined images
set reject="none"
set pclip=-0.6

if !( -e login.cl ) then
 if ( -e ${HOME}/login.cl ) then 
  echo "No login.cl in current directory, linking from ${HOME}."
  ln -s ${HOME}/login.cl .
 else
  echo "No login.cl in current directory or ${HOME}. Run mkiraf and edit login.cl appropriately."
  exit
 endif
endif

if !( -e badpix ) then
 echo "badpix not found. Creating empty badpix."
 touch badpix.empty
 set badpix="badpix.empty"
else
 set badpix="badpix"
endif

if !( -X cl ) then
 echo "IRAF not found in path, aborting."
 exit
endif

chmod a+rw *.{f,F}{i,I}{t,T}{,s,S}
\rm -f Zero.fits Dark.fits Flat.fits ref.fits tmp*.fits average.fits median.fits *.lst logfile ds9.reg sum.fits A_*.fits >& /dev/null

if !( -d backup ) mkdir backup
echo -n "Backing up FITS files ..."
if  ( -X rsync ) then
  rsync -u -t -q *.{f,F}{i,I}{t,T}{,s,S} backup/
else
  \cp -f *.{f,F}{i,I}{t,T}{,s,S} backup
endif
echo " done."

foreach f (`ls *.{f,F}{i,I}{t,T}{,s,S}`)
  set g=`echo $f | awk '{ print tolower($1) }' | sed -e 's/fit$/fits/g'`
  \mv $f $g
end
( ls *{b,B}{i,I}{a,A}{s,S}*.fits > bias.lst ) >& /dev/null
if ( `wc -l bias.lst | awk '{ print $1 }'` == 0 ) then
 echo "No BIAS images; assuming DARK images have correct exposure times"
 echo "   and continuing."
 set zerocorr="no"
else
 set zerocorr="yes"
endif
ls *{f,F}{l,L}{a,A}{t,T}*.fits > flat.lst
ls *{d,D}{r,R}{k,K}*.fits *{d,D}{a,A}{r,R}{k,K}*.fits > dark.lst
ls *.fits | egrep -iv "tmp|bias|dark|flat|Zero|Dark|Flat|BPM|ref|test|average|median|sum" > obj.lst
cat bias.lst flat.lst dark.lst obj.lst > all.lst

echo "Processing images with IRAF, this may take some time."
cl >& /dev/null << EOF

stty vt100
noao
imred
ccdred
util
ccdproc.noproc=no
ccdproc.fixpix=no
ccdproc.oversca=no
ccdproc.trim=no
ccdproc.zerocor=${zerocorr}
ccdproc.darkcor=yes
ccdproc.flatcor=yes
ccdproc.illumco=no
ccdproc.fringec=no
ccdproc.scancor=no
ccdproc.zero="Zero.fits"
ccdproc.dark="Dark.fits"
ccdproc.flat="Flat.fits"
!echo "     Adding IMAGETYP to headers" |& egrep -v ioctl > /dev/stderr
hedit ("@bias.lst", "imagetyp", "zero", add=yes, addonly=no, delete=no,\
 verify=no, show=no, update=yes)
hedit ("@dark.lst", "imagetyp", "dark", add=yes, addonly=no, delete=no,\
 verify=no, show=no, update=yes)
hedit ("@flat.lst", "imagetyp", "flat", add=yes, addonly=no, delete=no,\
 verify=no, show=no, update=yes)
hedit ("@obj.lst", "imagetyp", "object", add=yes, addonly=no, delete=no,\
 verify=no, show=no, update=yes)

!echo "     Fixing known bad pixels"
fixpix ("@all.lst", "${badpix}", linterp="INDEF", cinterp="INDEF", \
 verbose=no, pixels=no)

print "     Combining BIAS images"
zerocomb ("@bias.lst",\
 output="Zero",combine="average",reject="minmax",ccdtype="zero",process=no,\
 delete=yes, scale="none", statsec="", nlow=0, nhigh=1, nkeep=1,\
 mclip=yes, lsigma=3., hsigma=3.,\
 rdnoise="${RDNOISE}",gain="${GAIN}",\
 snoise="0.", pclip=-0.5, blank=0.)

print "     Combining DARK images"
darkcomb ("@dark.lst",\
 output="Dark", combine="average", reject="minmax", ccdtype="dark",\
 process=yes, delete=yes, scale="exposure", statsec="", nlow=0,\
 nhigh=1, nkeep=1, mclip=yes, lsigma=3., hsigma=3.,\
 rdnoise="${RDNOISE}",gain="${GAIN}",\
 snoise="0.", pclip=-0.5, blank=0.)

print "     Combining FLAT images"
flatcomb ("@flat.lst",\
 output="Flat", combine="average", reject="avsigclip", ccdtype="flat",\
 process=yes, subsets=yes, delete=yes, scale="mode", statsec="",\
 nlow=1, nhigh=1, nkeep=1, mclip=yes, lsigma=3., hsigma=3., \
 rdnoise="${RDNOISE}",gain="${GAIN}",\
 snoise="0.", pclip=-0.5, blank=1.)

print "     Processing science images"
ccdproc ("@obj.lst",
output="", ccdtype="object", max_cache=0, noproc=no, fixpix=no, overscan=no,\
trim=no, zerocor=${zerocorr}, darkcor=yes, flatcor=yes, illumcor=no, fringecor=no,\
readcor=no, scancor=no, readaxis="line", fixfile="", biassec="", trimsec="",\
zero="Zero", dark="Dark", flat="Flat", illum="", fringe="", minreplace=1.,\
scantype="shortscan", nscan=1, interactive=no, function="legendre", order=1,\
sample="*", naverage=1, niterate=1, low_reject=3., high_reject=3., grow=0.)

logout
EOF
echo "     Done."

setenv PATH ${PATH}:.
rehash
if !( -X align.csh ) then
  echo ""
  echo "Cannot find align.csh in path, so cannot do realignment. Aborting."
  echo -n "^U"
  exit
else
  echo ""
  echo "About to  start  alignment. Pick a good image and copy it to 'ref.fits'."
  echo "(If ref.fits is not found, the script will try to pick an image itself.)"
  echo ""
  echo "Press [ENTER] when ready to continue or CTRL-C to abort (reduced images"
  echo "will be left in the current directory.)"
  $<
  exec align.csh
endif
