#!/usr/bin/perl
#
# add a pseudo-FITS header to .pht file
#   correct the time in FITS header for the delay in transferring 
#   data to computer, so that time is proper for mid-exposure.

$suffix = "";

# first, we generate the list of files to be reduced
$nframes = 0;
@files1 = glob("iy*fit");
@files2 = glob("dqher*.fit");
#@files1 = glob("ugc*clear*.fit");
#@files1 = glob("ei???-???.fit");
foreach $file (@files1, @files2) {
  $frame_array[$nframes] = $file; 
  $nframes++;
}

# create a log file, too
$logfile = "addheader.log";
open(LOGFILE, ">$logfile") || die("can't open file $logfile");

# now process each frame in turn
#@frame_array = ("121", "123", "124", "126");
foreach $frame (@frame_array) {
  $base = $frame;
  $base =~ s/\.fit//;
  printf "now working on frame $frame = $base\n";

  $fitsfile = "${base}.fit";
  $phtfile = "${base}_fit.pht";
  if ((-e $fitsfile) && (-e $phtfile)) {
     # okay
  } else {
     printf "skipping image $base - missing .fts or .pht file\n";
     next;
  }

  # create the pseudo-FITS header, put in a file with name like 
  #    pff/image24.pht
  $fixed_ut = $wrong_ut;
  $outfile = "pff${suffix}/${base}.pht";
  open(OUTFILE, ">$outfile") || die("can't open file $outfile");
  printf OUTFILE "DATID   = '$base' \n";
  $object = "pg1633";
  printf OUTFILE "OBJECT  = '%s' \n", $object;
  if (1) {
   $filt = `picksym file=$fitsfile filter`;
   $filt =~ s/\s+//;
   $filt = lc($filt);
  }
  else {
   $filt = "clear";
  }
  printf OUTFILE "FILTER  = '%s'     \n", $filt;
  $exptime = `picksym file=$fitsfile exptime`;
  chomp($exptime);
  printf OUTFILE "EXPTIME = $exptime \n";
  printf OUTFILE "AIRMASS = 1.5    /  this is not true airmass  \n";
  $dateobs = `picksym file=$fitsfile date-obs`;
  chomp($dateobs);

  # convert DATE-OBS value from ST-8 form "YYYY-MM-DD" to "YYYY/MM/DD"
  $dateobs = convert_dateobs($dateobs);

  printf OUTFILE "DATE-OBS= '$dateobs' \n";
  $ut = `picksym file=$fitsfile time-obs`;
  chomp($ut);
  $fixed_ut = fix_ut($exptime, $ut);
  printf OUTFILE "UT      = '$fixed_ut' \n";

  
  # we must add a pseudo-comment describing the aperture used
  printf OUTFILE "COMMENT   aper=3,4,5 \n";

  printf OUTFILE "END\n";
  close(OUTFILE);

$cmd = "~/y1/old_spiff/home/richmond/bait/jd ut=$fixed_ut date=$dateobs ";
printf "JD about to run cmd ..$cmd.. \n";
$ret = `$cmd`;
printf "  JD2 ret is ..$ret.. \n";
$jd = $ret;
chomp($jd);


  # print information about this image to the log file
  printf LOGFILE "%-6d %15s %15s %2s  %4.0f  %10s %10s \n",
                    $frame, $fitsfile, $object, $filt, $exptime, $dateobs, 
						  $fixed_ut;
  

  # now we print the JD at the end of every line in input file 
  open(INFILE, "$phtfile") || die("can't open input file $infile");
  open(OUTFILE, ">$outfile") || die("can't open output file $outfile ");
  while (<INFILE>) {
    $line = $_;
    chomp($line);
    printf OUTFILE "%s %12.5f \n", $line, $jd;
  }
  close(OUTFILE);
  close(INFILE);


}

close(LOGFILE);


exit 0;
  


##############################################################################
# correct the given UT so that it contains the actual UT at time of 
#   midexposure.  We make two corrections:
#    
#      1. fix an error in the hour of the UT:
#                 true hour = given hour - $hour_offset
#                 
#      2. fix the error in reported time, which is actually the
#         start of the exposure.  We want the mid-exposure time.
#         
#                 midexposure = given time + (1/2 exposure time)
#
# Return the time of midexposure in UT with a format like this:
#            '08:34:21'
#
sub fix_ut {

  my($exp_length, $wrong_ut);
  my($fixed_ut);
  my(@fields, $f);
  
  $exp_length = $_[0];
  $wrong_ut = $_[1];

  @fields = split(/:/, $wrong_ut);
  $hour = $fields[0];
  $min = $fields[1];
  $sec = $fields[2];
 
  # these may vary from one run to another
  $hour_offset = 0;    # true UT = wrong UT - hour_offset
  $readout_delay = 0;  # seconds

  # fix the hour offset problem
  $hour = $hour - $hour_offset;

  # now subtract the amount of time necessary to calc mid-exposure correctly
  $frac_hour = $hour + ($min/60.0) + ($sec/3600.0);
  # and this is half the exposure length (which is expressed in seconds)
  $frac_hour += 0.5*($exp_length/3600.0);

  $hour = int($frac_hour);
  $min = int(($frac_hour - $hour)*60.0);
  $sec = (($frac_hour - $hour)*60.0 - $min)*60.0;

  # now, watch out for 60
  $ssec = sprintf("%02.0f", $sec);
  if ($ssec eq "60") {
    $sec = 0.0;
	 $min += 1;
	 if ($min == 60) {
	   $min = 0;
		$hour += 1;
    }
  }


  printf "wrong_ut is ..$wrong_ut..\n";
  printf "frac_hour %9.5f  hour %2d  min %2d  sec %4.1f \n", $frac_hour,
                   $hour, $min, $sec;
  
  $fixed_ut = sprintf("%02d:%02d:%02.0f", $hour, $min, $sec);
  printf "fixed_ut is ..$fixed_ut..\n";


  return($fixed_ut);
}



##############################################################################
# Convert the value of DATE-OBS from the form provided by ST-8 camera
#   to the form expected by the "multipht" program.
#
#         ST-8  creates             YYYY-MM-DD
#         multipht requires         DD/MM/YYYY
#
# Usage:
#          convert_dateobs     old_dateobs
#    
# RETURN:
#   the converted string
#
sub convert_dateobs {

  my($old_format, $new_format);
  my($year, $month, $day);
  
  $old_format = $_[0];

  @words = split(/-/, $old_format);
  $year = $words[0];
  $month = $words[1];
  $day = $words[2];
  printf "year ..%s..  month ..%s..   day ..%s.. \n", $year, $month, $day;
  $new_format = sprintf("%02d/%02d/%04d", $day, $month, $year);
  
  return($new_format);
}


