#!/usr/bin/perl
#
# generate a median sky flat from a large set of images 

$do_it = 1;

#foreach $filter ("b", "r", "i", "v") {
foreach $filter ("i") {
#foreach $filter ("r", "clear") {
#foreach $filter ("b", "v") {
#foreach $filter ("clear") {

#  if ($filter eq "clear") {
#    $filt_abbr = "c";
#  }
#  else {
    $filt_abbr = lc($filter);
#  }
  
  # remove pre-measured mean values
  system("sed -e '/mn_/d' < ~/.sym > ~/.sym.tmp; mv ~/.sym.tmp ~/.sym");
  
  
  # first, we generate the list of files to be combined
  $cmd = "median ";
  $frameglob = sprintf("flat%s-???.fit", $filter);
#  $frameglob = sprintf("domeflat%s-?????.fit", $filter);
#  $frameglob = sprintf("flat%s-00??%s.fit", $filter, $filt_abbr);
#  $frameglob = sprintf("flat%s-0???.fit", $filter);
#  $frameglob = sprintf("flat-0??%s.fit", $filt_abbr);
#  $frameglob = sprintf("flat_%s-0??*.fit", $filter);
#  $frameglob = sprintf("flat%s-00??%s.fit", $filter, $filt_abbr);
#  $frameglob = sprintf("flat_%s-0??.fit", $filt_abbr);
#  $frameglob = sprintf("flat-00??_v_2.fit", $filt_abbr);
#  $frameglob = sprintf("domeflat_clear-00??.fit", $filt_abbr);
  #$frameglob = sprintf("flatclear-0[012]?%s.fit", $filt_abbr);
printf "frameglob is ..%s.. \n", $frameglob;
  @frames = glob($frameglob);
  $nframes = @frames;
  foreach $img (@frames) {
    $cmd = $cmd . " $img"; 
  }
  
  $outfile= sprintf("flat%s.fts", $filter);
#  $outfile= sprintf("domeflat%s.fts", $filter);
  
  $cmd = $cmd . " iqm outfile=$outfile verbose ";
  
  printf "cmd is $cmd\n";
  if ($do_it == 1) {
    $result = `$cmd`;
  }
  printf "result of median is ..$result..\n";
  
  $datestr = `date`;
  $comment = "median of $nframes target frames, created $datestr";
  if ($do_it == 1) {
    $result  = `comment $outfile $comment`;
  }
  printf "result of comment is ..$result..\n";

}
  

exit 0;
  
