#!/usr/bin/perl
#
# Go through a set of files with instrumental photometry.
# Each file has lines with RA, Dec, JD.   Use these values
# (plus an assumed latitude and longitude stored in ait.config)
# to compute the airmass for each star.  Append the airmass
# to each line
#
# MWR 10/31/2009

$debug = 1;

$temp = "./add_airmass.tmp";

@files = glob("mrdel*.radec");
foreach $file (@files) {
  if ($debug > 0) {
    printf "next file is ..%s.. \n", $file;
  }

  open(TEMP, ">$temp") || die("can't open file $temp for output");
  open(INFILE, "$file") || die("can't open file $file");
  while (<INFILE>) {
    $line = $_;
    if ($line =~ /^#/) {
      printf TEMP "%s", $line;
      next;
    }
    chomp($line);

    $line = " " . $line;
    @words = split(/\s+/, $line);
    $ra = $words[2];
    $dec = $words[3];
    $jd = $words[13];
    if ($debug > 0) {
      printf " ra %12.5lf dec %12.5lf jd %12.5f \n", $ra, $dec, $jd;
    }

    $cmd = "~/bait/airmass ra=$ra dec=$dec jd=$jd ";
    $ret = exec_cmd($cmd);
    @words = split(/\s+/, $ret);
    $airmass = $words[5];
    if ($debug > 0) {
      printf " got airmass %s \n", $airmass;
    }

    printf TEMP "%s %6.3f \n", $line, $airmass;
    
  }
  close(INFILE);
  close(TEMP);

  # now replace the original file with the temp version
  $cmd = "mv $temp $file";
  $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);
}


