#!/usr/bin/perl
#
# Go back to directories with SN 2013ej data and
#    re-compute the magnitudes of the SN from the
#    instrumental magnitude data. 
#      
# MWR 8/5/2013

$debug = 1;

$num_lines = 0;
@passband_list = ("B", "V", "R", "I");
$output_file = "sn2013ej_mags.out";

# we copy this color-term file into all directories and use it to re-compute mags
$def_color_term_file = "color_terms.dat";
$bak_color_term_file = "color_terms.old";
$new_color_term_file = "./color_terms_aug05_2013.dat";

$topdir = "~/z1/ritobs/";
$globstr = sprintf "%s/?????_201[3]", $topdir;
@dirglob = glob("$globstr");
foreach $dir (@dirglob) {
  if ($debug > 1) {
    printf  "next dir is ..%s.. \n", $dir;
  }

  $snfile = sprintf "%s/work/pff/calc_sn_mags.out", $dir;
  if (!-f $snfile) {
    next;
  }

  $pff_dir = "$dir/work/pff/";
  if ($debug > 0) {
    printf " next dir is $pff_dir \n";
  }



  # move the old color-term file to a different name
  $cmd = "cp $pff_dir/$def_color_term_file $pff_dir/$bak_color_term_file ";
  $ret = exec_cmd($cmd);
  # copy the current color-term datafile into this directory
  $cmd = "cp $new_color_term_file $pff_dir";
  $ret = exec_cmd($cmd);
  # and give the new file the default name
  $cmd = "cp $pff_dir/$new_color_term_file $pff_dir/$def_color_term_file";
  $ret = exec_cmd($cmd);

 
  # now run the Perl script to compute SN mags, and place the output
  #    in the file "sn2013ej_mags.out" in that dir
  $cmd = "(cd $pff_dir; perl calc_sn_mags.pl > calc_sn_mags.out )";
  $ret = exec_cmd($cmd);
 


}



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);
}




