#!/usr/bin/perl
# 
# apply a flatfield frame to set of images
#
# Modified so it doesn't look in FITS header for keyword FILTER,
#   since ST9 doesn't put this in if filterwheel is not attached.
#   MWR 6/21/2004

# if set to 0, will not actually do work, just print commands
$do_it = 1;

$debug = 1;

# WCSTOOLS dir
$wcs_dir = "~/x2/kwfc_devel/wcstools/bin/";

# determine the mean value of each flatfield 
#@filters = ("B", "V");
@filters = ("clear");
#@filters = ("B");
#@filters = ("B", "V", "R", "I");
foreach $filter (@filters) {
  $lc_filter = lc($filter);
  $flat = sprintf("flat%s.fts", $lc_filter);
  #$flat = sprintf("domeflat%s.fts", $lc_filter);
  printf "next flat is $flat\n";
  $cmd = "mn $flat";
  $ret = exec_cmd($cmd);
}


@files1 = glob("asas14cv*.fit");
#@files1 = glob("dqher*.fit");
#@files1 = glob("ugc*.fit");
#foreach $img (@files1) {
foreach $img (@files1, @files2, @files3) {
  printf "next image is $img \n";

  if (1) {
   # pick out the filter for this image -- strip out white space from result
   $filt = `picksym file=$img filter`;
   #$cmd = "$wcs_dir/gethead $img filter";
   #$filt = exec_cmd($cmd);
   $filt =~ s/\s+//;
   printf "image $img has filter $filt\n";
   $flat = sprintf("flat%s.fts", lc($filt));
   #$flat = sprintf("domeflat%s.fts", lc($filt));
   #$flat = sprintf("flat%s_shift.fts", lc($filt));
  }
  else {
   $flat = "flat_clear.fts";
  }

  if (-e $img) {
    # image exists, we'll do stuff to it in a moment
  } else {
    printf "file $img doesn't exist, skip it\n";
    next;
  }

  $cmd = "div $img $flat flat";
  printf "cmd is $cmd\n";
  if ($do_it == 1) {
    $result = exec_cmd($cmd);
  }
  printf "result of div is ..$result..\n";

  $datestr = `date`;
  $comment = "divided by flat $flat on $datestr";
  $cmd = "comment $img $comment";
  printf "cmd is $cmd\n";
  if ($do_it == 1) {
    $result  = exec_cmd($cmd);
  }
  printf "result of comment is ..$result..\n";

}


exit 0;
  



##############################################################################
# PROCEDURE: exec_cmd
#
# DESCRIPTION: Execute the given shell command line.  If the $debug flag
#              is set, we print to stdout the command line, and
#              also print out the result string.
#
# RETURNS:
#              the result of the command
#
#
sub exec_cmd {

  my($cmd, $ret);

  $cmd = $_[0];

  if ($debug > 0) {
    printf "cmd is ..$cmd.. \n";
  }
  $ret = `$cmd`;
  if ($debug > 0) {
    printf "ret is ..$ret.. \n";
  }

  return($ret);
}


