#!/bin/csh
#
# call "photom_match" repeatedly for all the .ast files in the directory.
# Note that the difference between adjacent PHT files is about 3.8 degrees
#
# User must set 
#
#      CATSTR    to have proper bandpass and column for catalog file
#      DETSTR    to have proper bandpass and column for detected stars
#      BRIGHTMAG to be faint limit on catalog mags for zero-point calculations
#
set CATSTR="i=8"
#      col 6 is default aperture, col 8 is smaller, col 10 is larger
set DETSTR="i=4"
set BRIGHTMAG=11.0

set PHOTOM_PROG=~/scr/match/photom_match
set CATALOG=~/scr/misc/landolt.ast
set CATRA=2
set CATDEC=3
set CATEQUINOX=2000
set DETRA=2
set DETDEC=3
set DETEQUINOX=2000
set LOG=photomall.log
set TMP=photomall.$$
set TMP2=photomall2.$$
set AWKFILE=photomall.awk

/bin/rm -rf $LOG

echo '{ if ($7 < QQ) { print $8 } }' > $TMP
sed -e "s/QQ/$BRIGHTMAG/" $TMP > $AWKFILE

foreach file (r249*.ast)

  echo "running photom_match on file $file" >> $LOG
  
  # find the matching pairs, write output into temp file
  $PHOTOM_PROG $file    $DETRA $DETDEC $DETEQUINOX $DETSTR \
               $CATALOG $CATRA $CATDEC $CATEQUINOX $CATSTR    > $TMP

  if ($status != 0) then
    echo "photomall.csh: failed for file $file"
    exit 1
  endif

  #
  # now, check to see if we have decent results ... if so, figure out
  #   a mean zero-point offset, using only stars which have magnitudes
  #   less than $BRIGHTMAG in the catalog
  set nline=`grep -v "#" $TMP | wc | awk '{ print $1 }'`
  if ($nline != 0) then
    cat $TMP >> $LOG
    set statstr=`grep -v '#' $TMP | awk -f $AWKFILE > $TMP2`
    set ngood=`wc $TMP2 | awk '{ print $1 }'`
    if ($ngood > 0) then
      set rastr=`grep -v '#' $TMP | awk '{ print $1 }' | stats`
      set ra=`printf "%6.1f" $rastr[9]`
      set statstr=`stats < $TMP2`
      set nstar=$statstr[3]
      set delta=$statstr[9]
      set stdev=$statstr[12]
      printf "#  subsample RA %6.1f  N %3d   mean  %7.3f  stdev  %7.3f\n" \
                                   $ra $nstar $delta $stdev >> $LOG
    endif
  endif

  echo " " >> $LOG
             
end
  


/bin/rm -rf $TMP $TMP2 $AWKFILE

exit 0
