#!/usr/local/perl
# 
# Add together individual FITS images generated from a videotape
# 
# Place the co-added images into a new subdirectory of their own.
#   Give them names which increase by 1 with each set of added frames.
#   Thus, first co-added image is number 1  (really frames 1-10)
#   Thus, next  co-added image is number 2  (really frames 11-20)
#   and so forth
#
# MWR 1/7/2006
#
# Modified for use with FITS images from RIT Obs 
#
# MWR 7/20/2009

$debug = 1;

# how many original frames do we co-add?
$coadd_num = 3;

# how many original frames in each subdir?
$frames_in_subdir = 172;

$output_dir = sprintf "./coadded_%d", $coadd_num;
if (-d $output_dir) {
  # okay, the directory already exists, do nothing
}
else {
  # must create subdirectory for coadded images
  mkdir($output_dir);
}

$new_index = 1;

@dirs = glob("./");
foreach $dir (@dirs) {

  $new_index_start = $new_index;
  $new_index_end = $new_index_start + ($frames_in_subdir/$coadd_num);

  for ($new_index = $new_index_start; $new_index < $new_index_end;
                             $new_index++) {

    # what original FITS images will we need?
    $orig_index_start = ($new_index - 1)*$coadd_num + 1;
    $orig_index_end = ($new_index*$coadd_num);

    # we check to see if the original FITS images for this coadd
    #   are existing
    $all_exist_flag = 1;
    $name_count = 0;
    for ($orig_index = $orig_index_start; $orig_index <= $orig_index_end; 
                       $orig_index++) {

      $orig_fits_file[$name_count] = sprintf "%s/sdss-%03d.fit", $dir, $orig_index;
      if (-e $orig_fits_file[$name_count]) {
        printf "$orig_fits_file[$name_count] exists ... \n";
      } else {
        printf "$orig_fits_file[$name_count] does not exist \n";
        printf "  skipping creation of new index %d \n", $new_index;
        $all_exist_flag = 0;
      }
      $name_count++;
    }
 


    if ($all_exist_flag == 1) {

      # this is the name of the new coadded FITS image
      $newname = sprintf "%s/coadd-%08d.fits", $output_dir, $new_index;

      # next, we add them to make the co-added FITS image
      $cmd = "add ";
      for ($i = 0; $i < $coadd_num; $i++) {
        $cmd .= " $orig_fits_file[$i] ";
      }
      $cmd .= " outfile=$newname ";
      $cmd .= " norm ";
      if ($debug > 0) {
        printf "cmd is ..$cmd.. \n";
      }
      $ret = `$cmd`;
  
    }


    # move on to the next group
  }
    
}


exit 0;
