#!/usr/bin/perl
#
# Go through a set of directories, picking out a file with
#    instrumental photometry for the target.  
#    Apply a simple calibration, putting the magnitudes
#    roughly on a standard scale.  Compute the phase from
#    the JD of observation and known period and epoch
#    of the star. 
#
#    Create a text file with JD, phase, mag.
#
#    Use the text file to create a graph showing calibrated mag
#    vs. phase.
#
# MWR 11/13/2021
#
# Modified to create a datafile with intensities of target and comp star.
#
# MWR 2/23/2022

$debug = 0;
$BAD_MAG = 99.00;

# should we print out one line per image with phase?
$print_jd_phase = 0;

# directory holding file with target info: RA, Dec, period, epoch, etc.
$target_info_dir = "/y/capstone/eclipsing";
# file with the target into
$target_file = "eclipsing_target.dat";

$filter = "r";
$target = "rtand";
# magnitude of the comparison star in this filter
$comp_mag = 10.127;



# grab info on the target from the target info file
($period, $epoch, $retcode) = 
   grab_target_info($target, $target_info_dir, $target_file);
if ($retcode != 0) {
  printf "grab_target_info fails with code %s \n", $retcode;
  exit(1);
} else {
  if ($debug > 0) {
    printf "target info: %s %s %s \n", $target, $period, $epoch;
  }
}



#create_inten("/home/richmond/z1/ritobs/aug30_2020/work/pff_rtand", 5, "A");
#create_inten("/home/richmond/z1/ritobs/sep04_2020/work/pff_rtand", 5, "A");
#create_inten("/home/richmond/z1/ritobs/sep20_2020/work/pff_rtand", 5, "A");
#create_inten("/home/richmond/z1/ritobs/nov06_2020/work/pff_rtand_r", 9, "A");
#create_inten("/home/richmond/z1/ritobs/nov07_2020/work/pff_rtand_r", 9, "A");
create_inten("/home/richmond/z1/ritobs/nov12_2020/work/pff_rtand", 9, "A");



exit 0;


######################################################################3
# PROCEDURE: process
#
# DESCRIPTION: Grab data from one night, calibrate, compute phase,
#              and append the results into a growing output file.
#
# USAGE:     process     dir   aper  comp_star
#
#                 dir           name of directory with data
#
#                 aper          aperture to use (may be several in one dir)
#                                   is radius of aperture in pixels
#
#                 comp_star     name of comparison star
#
# RETURNS:   0         if all goes well
#            1         if a problem occurs
#      
sub process {

  my($dir, $aper);
  
  $dir = $_[0];
  $aper = $_[1];
  $comp_star = $_[2];

  if ($debug > 0) {
    printf "next dir is %s \n", $dir;
  }


  # locate the file with comparison star photometry
  $globstr = sprintf "%s/star%s_*%s.dat%d", $dir, $comp_star, $filter, $aper;
  if ($debug > 0) {
    printf "globstr is ..%s.. \n", $globstr;
  }
  @globfiles = glob($globstr);
  $num = $#globfiles;
  # printf "num is $num \n";
  # read the first line from this file, pick out the instrumental mag
  #    of the comparison star
  $comp_ens_mag = -99.0;
  foreach $file (@globfiles) {
    open(COMPSTAR, $file) || die("can't open compstar file $file");
    $line = <COMPSTAR>;
    @words = split(/\s+/, $line);
    $comp_ens_mag = $words[5];
    close(COMPSTAR);
  }
  if ($debug > 0) {
    printf "comp_ens_mag is %6.3f \n", $comp_ens_mag;
  }
  

  # locate the file with instrumental photometry
  $globstr = sprintf "%s/star_%s_*%s.dat%d", $dir, $target, $filter, $aper;
  if ($debug > 0) {
    printf "globstr is ..%s.. \n", $globstr;
  }
  @globfiles = glob($globstr);
  $num = $#globfiles;
  # printf "num is $num \n";
  $file = $globfiles[0];
  if ($debug > 0) {
    printf " next file is %s \n", $file;
  }
  
  # go through the instrumental photometry of the target, line by line
  #    for each line, 
  #      a) pick out JD and instrumental mag
  #      b) compute calibrated mag
  #      c) compute phase
  #      d) print one line with results to stdout
  open(TARGET_FILE, "$file") || die("can't open target file $file");
  while (<TARGET_FILE>) {
    $line = $_;
    @words = split(/\s+/, $line);
    $jd = $words[4];
    $target_ens_mag = $words[5];
    $target_mag = $words[6];
    if ($debug > 0) {
      printf " raw target  JD %12.5f  ensmag %6.3f  mag %6.3f \n",
              $jd, $target_ens_mag, $target_mag;
    }

    # compute phase
    $phase = ($jd - $epoch)/$period;
    $phase = $phase - int($phase);
    if ($debug > 0) {
      printf "phase is %10.5f \n", $phase;
    }

    # compute calibrated mag of target
    $offset = $comp_mag - $comp_ens_mag;
    $calib_mag = $target_mag + $offset;
    if ($debug > 0) {
      printf " offset is %6.3f  calib_mag %6.3f  \n", $offset, $calib_mag;
    }

    # print one line to output
    if ($print_jd_phase == 1) {
      printf " JD %12.5f  phase %10.5f  ens %6.3f  calib %6.3f \n", 
          $jd, $phase, $target_ens_mag, $calib_mag;
    }

  }
  close(TARGET_FILE);

  

  return(0);
}




######################################################################3
# PROCEDURE: create_inten
#
# DESCRIPTION: Grab data from one night, for a set of stars as well
#              as the target, and compute intensities based on the
#              magnitudes.  Print one line per image with intensities
#              from all comp stars and target.
#
#              We use fixed list of comp stars: A, D, E
#
# USAGE:     create_inten  dir   aper  
#
#                 dir           name of directory with data
#
#                 aper          aperture to use (may be several in one dir)
#                                   is radius of aperture in pixels
#
# RETURNS:   0         if all goes well
#            1         if a problem occurs
#      
sub create_inten {

  my($dir, $aper);
  
  $dir = $_[0];
  $aper = $_[1];

  if ($debug > 0) {
    printf "next dir is %s \n", $dir;
  }

  # first, we read all the lines for the target star, and save them 
  #   all in arrays
  # locate the file with instrumental photometry

  $globstr = sprintf "%s/star_%s_*%s.dat%d", $dir, $target, $filter, $aper;
  if ($debug > 0) {
    printf "globstr is ..%s.. \n", $globstr;
  }
  @globfiles = glob($globstr);
  $num = $#globfiles;
  # printf "num is $num \n";
  $file = $globfiles[0];
  if ($debug > 0) {
    printf " next file is %s \n", $file;
  }
  
  # go through the instrumental photometry of the target, line by line
  #    for each line, 
  #      a) pick out JD and instrumental mag
  #      b) compute calibrated mag
  #      c) compute phase
  #      d) print one line with results to stdout
  $num_targ = 0;
  open(TARGET_FILE, "$file") || die("can't open target file $file");
  while (<TARGET_FILE>) {
    $line = $_;
    @words = split(/\s+/, $line);
    $jd = $words[4];
    $target_ens_mag = $words[5];
    $target_mag = $words[6];
    if ($debug > 0) {
      printf " raw target  JD %12.5f  ensmag %6.3f  mag %6.3f \n",
              $jd, $target_ens_mag, $target_mag;
    }

    # compute phase
    $phase = ($jd - $epoch)/$period;
    $phase = $phase - int($phase);
    if ($debug > 0) {
      printf "phase is %10.5f \n", $phase;
    }

    # compute calibrated mag of target
    $offset = $comp_mag - $comp_ens_mag;
    $calib_mag = $target_mag + $offset;
    if ($debug > 0) {
      printf " offset is %6.3f  calib_mag %6.3f  \n", $offset, $calib_mag;
    }

    # save results in array
    $targ_jd_array[$num_targ] = $jd;
    $targ_phase_array[$num_targ] = $phase;
    $targ_mag_array[$num_targ] = $target_mag;
    $targ_calib_array[$num_targ] = $BAD_MAG;
    $num_targ++;

    # print one line to output
    if ($print_jd_phase == 1) {
      printf " JD %12.5f  phase %10.5f  ens %6.3f  calib %6.3f \n", 
          $jd, $phase, $target_mag, $calib_mag;
    }

  }
  close(TARGET_FILE);

  # set all comp star elements of array to BAD_MAG
  #   We'll overwrite them with good values as we locate the 
  #   measurements.
  for ($i = 0; $i < $num_targ; $i++) {
    $targ_starA_array[$i] = $BAD_MAG;
    $targ_starC_array[$i] = $BAD_MAG;
    $targ_starD_array[$i] = $BAD_MAG;
    $targ_starE_array[$i] = $BAD_MAG;
  }


  # now, we read data for star "A".  If we find a line with same
  #   JD as for target, we set the "starA" element of array
  #   equal to its instrumental mag; if not, we leave "starA"
  #   element equal to $BAD_MAG.
  $globstr = sprintf "%s/star%s_%s.dat%d", $dir, "A", $filter, $aper;
  if ($debug > 0) {
    printf "globstr is ..%s.. \n", $globstr;
  }
  @globfiles = glob($globstr);
  $num = $#globfiles;
  # printf "num is $num \n";
  $file = $globfiles[0];
  if ($debug > 0) {
    printf " next file is %s \n", $file;
  }
  open(COMP_FILE, "$file") || die("can't open comp file $file");
  while (<COMP_FILE>) {
    $line = $_;
    @words = split(/\s+/, $line);
    $jd = $words[4];
    $comp_ens_mag = $words[5];
    $comp_mag = $words[6];
    if ($debug > 0) {
      printf " raw A  JD %12.5f  ensmag %6.3f  mag %6.3f \n",
              $jd, $comp_ens_mag, $comp_mag;
    }

    # check to see if this same JD appears in target array;
    #    if so, set "starA" element equal to the instrumental mag
    for ($i = 0; $i < $num_targ; $i++) {
      if ($targ_jd_array[$i] == $jd) {
        $targ_starA_array[$i] = $comp_mag;
        if ($debug > 0) {
          printf " JD %12.5f  starA %6.3f  \n", 
               $jd, $comp_mag;
        }
        last;
      }
    }
  }
  close(COMP_FILE);

  # now, we read data for star "C".  If we find a line with same
  #   JD as for target, we set the "starA" element of array
  #   equal to its instrumental mag; if not, we leave "starC"
  #   element equal to $BAD_MAG.
  $globstr = sprintf "%s/star%s_%s.dat%d", $dir, "C", $filter, $aper;
  if ($debug > 0) {
    printf "globstr is ..%s.. \n", $globstr;
  }
  @globfiles = glob($globstr);
  $num = $#globfiles;
  # printf "num is $num \n";
  $file = $globfiles[0];
  if ($debug > 0) {
    printf " next file is %s \n", $file;
  }
  open(COMP_FILE, "$file") || die("can't open comp file $file");
  while (<COMP_FILE>) {
    $line = $_;
    @words = split(/\s+/, $line);
    $jd = $words[4];
    $comp_ens_mag = $words[5];
    $comp_mag = $words[6];
    if ($debug > 0) {
      printf " raw C  JD %12.5f  ensmag %6.3f  mag %6.3f \n",
              $jd, $comp_ens_mag, $comp_mag;
    }

    # check to see if this same JD appears in target array;
    #    if so, set "starC" element equal to the instrumental mag
    for ($i = 0; $i < $num_targ; $i++) {
      if ($targ_jd_array[$i] == $jd) {
        $targ_starC_array[$i] = $comp_mag;
        if ($debug > 0) {
          printf " JD %12.5f  starC %6.3f  \n", 
               $jd, $comp_mag;
        }
        last;
      }
    }
  }
  close(COMP_FILE);



  # now, we read data for star "D".  If we find a line with same
  #   JD as for target, we set the "starD" element of array
  #   equal to its instrumental mag; if not, we leave "starD"
  #   element equal to $BAD_MAG.
  $globstr = sprintf "%s/star%s_%s.dat%d", $dir, "D", $filter, $aper;
  if ($debug > 0) {
    printf "globstr is ..%s.. \n", $globstr;
  }
  @globfiles = glob($globstr);
  $num = $#globfiles;
  # printf "num is $num \n";
  $file = $globfiles[0];
  if ($debug > 0) {
    printf " next file is %s \n", $file;
  }
  open(COMP_FILE, "$file") || die("can't open comp file $file");
  while (<COMP_FILE>) {
    $line = $_;
    @words = split(/\s+/, $line);
    $jd = $words[4];
    $comp_ens_mag = $words[5];
    $comp_mag = $words[6];
    if ($debug > 0) {
      printf " raw D  JD %12.5f  ensmag %6.3f  mag %6.3f \n",
              $jd, $comp_ens_mag, $comp_mag;
    }

    # check to see if this same JD appears in target array;
    #    if so, set "starD" element equal to the instrumental mag
    for ($i = 0; $i < $num_targ; $i++) {
      if ($targ_jd_array[$i] == $jd) {
        $targ_starD_array[$i] = $comp_mag;
        if ($debug > 0) {
          printf " JD %12.5f  starD %6.3f  \n", 
               $jd, $comp_mag;
        }
        last;
      }
    }
  }
  close(COMP_FILE);


  # now, we read data for star "E".  If we find a line with same
  #   JD as for target, we set the "starE" element of array
  #   equal to its instrumental mag; if not, we leave "starE"
  #   element equal to $BAD_MAG.
  $globstr = sprintf "%s/star%s_%s.dat%d", $dir, "E", $filter, $aper;
  if ($debug > 0) {
    printf "globstr is ..%s.. \n", $globstr;
  }
  @globfiles = glob($globstr);
  $num = $#globfiles;
  # printf "num is $num \n";
  $file = $globfiles[0];
  if ($debug > 0) {
    printf " next file is %s \n", $file;
  }
  open(COMP_FILE, "$file") || die("can't open comp file $file");
  while (<COMP_FILE>) {
    $line = $_;
    @words = split(/\s+/, $line);
    $jd = $words[4];
    $comp_ens_mag = $words[5];
    $comp_mag = $words[6];
    if ($debug > 0) {
      printf " raw E  JD %12.5f  ensmag %6.3f  mag %6.3f \n",
              $jd, $comp_ens_mag, $comp_mag;
    }

    # check to see if this same JD appears in target array;
    #    if so, set "starD" element equal to the instrumental mag
    for ($i = 0; $i < $num_targ; $i++) {
      if ($targ_jd_array[$i] == $jd) {
        $targ_starE_array[$i] = $comp_mag;
        if ($debug > 0) {
          printf " JD %12.5f  starE %6.3f  \n", 
               $jd, $comp_mag;
        }
        last;
      }
    }
  }
  close(COMP_FILE);


  # finally, we are ready to print out one line per image,
  #   with the instrumental mags of target and A, RT_And (in B's place),
  #   C, D, E.
  #   Only print out a line if all five stars have good measurements.
  #   Otherwise, skip the image
  for ($i = 0; $i < $num_targ; $i++) {
    if (($targ_mag_array[$i] != $BAD_MAG) &&
        ($targ_starA_array[$i] != $BAD_MAG) &&
        ($targ_starC_array[$i] != $BAD_MAG) &&
        ($targ_starD_array[$i] != $BAD_MAG) &&
        ($targ_starE_array[$i] != $BAD_MAG)) {

       $targ_inten = 10.0**(0.4*(15.0 - $targ_mag_array[$i]));
       $starA_inten = 10.0**(0.4*(15.0 - $targ_starA_array[$i]));
       $starC_inten = 10.0**(0.4*(15.0 - $targ_starC_array[$i]));
       $starD_inten = 10.0**(0.4*(15.0 - $targ_starD_array[$i]));
       $starE_inten = 10.0**(0.4*(15.0 - $targ_starE_array[$i]));

       printf " %12.5f  %9.1f  %9.1f  %9.1f  %9.1f  %9.1f \n",
            $targ_jd_array[$i],
            $starA_inten, $targ_inten, $starC_inten, $starD_inten, $starE_inten;
    }
  }





  
if (0 == 1) {
  
  @compstar_list = ("A", "D", "E");
  foreach $comp_star (@compstar_list) {

			 # locate the file with comparison star photometry
			 $globstr = sprintf "%s/star%s_*%s.dat%d", $dir, $comp_star, $filter, $aper;
			 if ($debug > 0) {
				printf "globstr is ..%s.. \n", $globstr;
			 }
			 @globfiles = glob($globstr);
			 $num = $#globfiles;
			 # printf "num is $num \n";
			 # read the first line from this file, pick out the instrumental mag
			 #    of the comparison star
			 $comp_ens_mag = -99.0;
			 foreach $file (@globfiles) {
				open(COMPSTAR, $file) || die("can't open compstar file $file");
				$line = <COMPSTAR>;
				@words = split(/\s+/, $line);
				$comp_ens_mag = $words[5];
				close(COMPSTAR);
			 }
			 if ($debug > 0) {
				printf "comp_ens_mag is %6.3f \n", $comp_ens_mag;
			 }
  }
			 

  # locate the file with instrumental photometry
  $globstr = sprintf "%s/star_%s_*%s.dat%d", $dir, $target, $filter, $aper;
  if ($debug > 0) {
    printf "globstr is ..%s.. \n", $globstr;
  }
  @globfiles = glob($globstr);
  $num = $#globfiles;
  # printf "num is $num \n";
  $file = $globfiles[0];
  if ($debug > 0) {
    printf " next file is %s \n", $file;
  }
  
  # go through the instrumental photometry of the target, line by line
  #    for each line, 
  #      a) pick out JD and instrumental mag
  #      b) compute calibrated mag
  #      c) compute phase
  #      d) print one line with results to stdout
  open(TARGET_FILE, "$file") || die("can't open target file $file");
  while (<TARGET_FILE>) {
    $line = $_;
    @words = split(/\s+/, $line);
    $jd = $words[4];
    $target_ens_mag = $words[5];
    $target_mag = $words[6];
    if ($debug > 0) {
      printf " raw target  JD %12.5f  ensmag %6.3f  mag %6.3f \n",
              $jd, $target_ens_mag, $target_mag;
    }

    # compute phase
    $phase = ($jd - $epoch)/$period;
    $phase = $phase - int($phase);
    if ($debug > 0) {
      printf "phase is %10.5f \n", $phase;
    }

    # compute calibrated mag of target
    $offset = $comp_mag - $comp_ens_mag;
    $calib_mag = $target_mag + $offset;
    if ($debug > 0) {
      printf " offset is %6.3f  calib_mag %6.3f  \n", $offset, $calib_mag;
    }

    # print one line to output
    if ($print_jd_phase == 1) {
      printf " JD %12.5f  phase %10.5f  ens %6.3f  calib %6.3f \n", 
          $jd, $phase, $target_ens_mag, $calib_mag;
    }

  }
  close(TARGET_FILE);

}
  

  return(0);
}



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


###########################################################################
# PROCEDURE: grab_target_info
# 
# DESCRIPTION: Read information on a set of targets from the given
#              text file.  Look for a target of the given name.
#              If found, return properties of that target.
#
# USAGE:     grab_target_info   target   dir   file
#
#              target              is name of target
# 
#              dir                 directory holding the file with info
#
#              file                name of file with information on a set
#                                       of targets
#
# RETURNS:    (period, epoch, retcode)
#
#               period             period of star, in days
#
#               epoch              JD of primary minimum 
#
#               retcode            0    if all goes well
#                                  1    if an error occurs
#
#
sub grab_target_info {

  my($target, $dir, $file);
  my($period, $epoch, $retcode);
  my($this_name, $this_equinox, $this_period, $this_epoch, $this_ra, $this_dec);
  my($line, @words);
  my($fullname);

  $target = $_[0];
  $dir = $_[1];
  $file = $_[2];

  $period = -1;
  $epoch = -1;
  $retcode = 1;

  if ($debug > 0) {
    printf "grab_target_info: target    %s \n", $target;
    printf "grab_target_info: dir       %s \n", $dir;
    printf "grab_target_info: file       %s \n", $file;
  }

  $fullname = sprintf "%s/%s", $dir, $file;
  open(FULLNAME, $fullname) || die("grab_target_info: can't open file $fullname");
  while (<FULLNAME>) {
    $line = $_;
    @words = split(/\s+/, $line);
    
    $this_name = $words[0];
    $this_equinox = $words[1];
    $this_ra = $words[2];
    $this_dec = $words[3];
    $this_period = $words[4];
    $this_epoch = $words[5];

    if ($this_name eq $target) {
      $period = $this_period;
      $epoch = $this_epoch;
      $retcode = 0;
      if ($debug > 0) {
        printf "grab_target_info: found info for target %s \n", $target;
      }
      last;
    }
  }
  close(FULLNAME);


  return($period, $epoch, $retcode);
}
