#!/usr/bin/perl
#
# Look in files with names like
#
#     do_photom_b.out, do_photom_v.out, ...
# 
# to get the BVRI magnitudes for stars in the ensemble.
# Then create a single file with all the data, with format like this:
#
#   #istar    B     sigB    V     sigV     R    sigR     I     sigI
#   A       1.387   0.032  0.845  0.032  0.732  0.011   0.441  0.009
#   B       1.387   0.032  0.845  0.032  0.732  0.011   0.441  0.009
#   SN      1.387   0.032  0.845  0.032  0.732  0.011   0.441  0.009

# If a star doesn't have ensemble data, use magnitude value 99.0
#
# MWR 8/1/2013
#
# Modified from original form to leave stars "D" and "H" out
#   of the photometric calibration for SN 2016coj in NGC 4125
#  
# MWR 6/17/2016

$debug = 1;


@star_list = ("A", "B", "C", "D", "E", "F", "G", "H", "SN");
@star_list = ("A", "B", "C",      "E", "F", "G",      "SN");
@filter_list = ("B", "V", "R", "I");
@aper_list =   ("3", "3", "3", "3");

$num_filter = 0;
foreach $filter (@filter_list) {
  $filter_array[$num_filter] = $filter;
  $num_filter++;
}
$num = 0;
foreach $aper (@aper_list) {
  $aper_array[$num] = $aper;
  $num++;
}
foreach $star (@star_list) {
  foreach $filter (@filter_list) {
    $filter_lc = lc($filter);
    $obs_mag{$star}{$filter_lc} = 99.0;
    if ($debug > 1) {
      printf " initializing obs_mag %s %s to %6.3f \n",
            $star, $filter_lc, $obs_mag{$star}{$filter_lc};
    }
  }
}



$ensemble_file = "./ngc4125_ensemble.dat";
open(ENSEMBLE_FILE, ">$ensemble_file") || die("can't open $ensemble_file");
printf ENSEMBLE_FILE "%-8s %8s %8s %8s %8s \n",
   "#star", "B", "V", "R", "I";



$num_obs_stars = 0;
foreach $filter (@filter_list) {
  $filter_lc = lc($filter);
  $filter_uc = uc($filter);
  $photom_file = sprintf "do_photom_%s.out", $filter_lc;
  open(PHOTOM_FILE, "$photom_file") || die("can't open file $photom_file");
  while (<PHOTOM_FILE>) {
    $line = $_;
    if ($line =~ /^#/) {
      next;
    }
    @words = split(/\s+/, " " . $line);
    $name = $words[1];
    $id = $words[2];
    $mag = $words[3];
    $magerr = $words[4];

    $obs_mag{$name}{$filter_lc} = $mag;
    $obs_magerr{$name}{$filter_lc} = $magerr;
    if ($debug > 0) {
      printf " setting obs_mag %s %s to %6.3f \n",
              $name, $filter_lc, $obs_mag{$name}{$filter_lc};
    }
  }
  close(PHOTOM_FILE);

}



foreach $star (@star_list) {

  printf ENSEMBLE_FILE "%-8s ", $star;

  foreach $filter (@filter_list) {
    $filter_lc = lc($filter);
    $filter_uc = uc($filter);
    printf ENSEMBLE_FILE " %6.3f %6.3f  ", 
            $obs_mag{$star}{$filter_lc},
            $obs_magerr{$star}{$filter_lc};
  }
 
  printf ENSEMBLE_FILE "\n";

}
close(ENSEMBLE_FILE);

exit 0;


