#!/usr/bin/perl
#
# Create a single combined image from many images.
#   Try both median (no scaling) and sum.
#   Output files: master_median.fit, master_sum.fit
#
#

$debug = 1;

# subtract the sky value from each image first
$cmd = "box 1 cr=109 cc=81 nr=88 nc=90";
if ($debug > 0) {
  printf "cmd is ..$cmd.. \n";
}
$ret = `$cmd`;

$median_cmd = "median ";
$sum_cmd = "add ";
foreach $i (2, 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 21) {
  $str = sprintf "varvul-%03d.fit", $i;

  # determine the sky value in this image
  $cmd = "sky $str box=1 bin=4";
  if ($debug > 0) {
    printf "cmd is ..$cmd.. \n";
  }
  $ret = `$cmd`;
  if ($debug > 0) {
    printf "ret is ..$ret.. \n";
  }
  
  # make a copy of the image and subtract the sky
  $copy_img = sprintf "QQ$str";
  $cmd = "cp $str $copy_img";
  if ($debug > 0) {
    printf "cmd is ..$cmd.. \n";
  }
  $ret = `$cmd`;
  $cmd = "sub $copy_img const=sky";
  if ($debug > 0) {
    printf "cmd is ..$cmd.. \n";
  }
  $ret = `$cmd`;

  $median_cmd .= " $copy_img ";
  $sum_cmd .= " $copy_img ";
}

# create the master median output file
$median_cmd .= " outfile=master_median.fit ";
if ($debug > 0) {
  printf "median_cmd is ..$median_cmd.. \n";
}
$ret = `$median_cmd`;

# create the master summed output file
$sum_cmd .= " outfile=master_sum.fit norm ";
if ($debug > 0) {
  printf "sum_cmd is ..$sum_cmd.. \n";
}
$ret = `$sum_cmd`;


# the median yields negative pixel values at the centers of saturated stars
#   so turn them into positive saturated value
if (0 == 1) {
  $cmd = "clip master_median.fit min=0 vmin=32767";
  if ($debug > 0) {
    printf "cmd is ..$cmd.. \n";
  }
  $ret = `$cmd`;
}

exit 0;
