#!/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

$debug = 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;
  }
}



process("/home/richmond/z1/ritobs/aug30_2020/work/pff_rtand", 5, "A");
#process("/home/richmond/z1/ritobs/sep04_2020/work/pff_rtand", 5, "A");
process("/home/richmond/z1/ritobs/sep20_2020/work/pff_rtand", 5, "A");
process("/home/richmond/z1/ritobs/nov06_2020/work/pff_rtand_r", 9, "A");
process("/home/richmond/z1/ritobs/nov07_2020/work/pff_rtand_r", 9, "A");
process("/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
    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
  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
    printf " JD %12.5f  phase %10.5f  ens %6.3f  calib %6.3f \n", 
          $jd, $phase, $target_ens_mag, $calib_mag;

  }
  close(TARGET_FILE);

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