#!/usr/bin/perl
#
# usage: grab_pos.pl  <  pipeline_output_file
#
# sift through the output of the Mark IV pipeline, putting together
#   information on each target image:
#
#          filename       JD       central_RA  central_Dec
#
# print this information in a 4-column format as output.
#
# MWR 5/31/2001

$debug = 0;

$line_counter = 0;

# read in the entire file ...
while (<STDIN>) {
  $line[$line_counter++] = $_;
}

# search for lines matching "retcode", which are close to the lines
#   we want to use
for ($i = 0; $i < $line_counter; $i++) {
  if ($line[$i] =~ /retcode/) {
    $radec_line = $line[$i+5];
    $name_line = $line[$i-25];
    
    # first, figure out if this is a proper section of the output file.
    # If we can read RA and Dec from the radec line, then it is.
    @radec = get_radec($radec_line);
    $ra = $radec[0];
    $dec = $radec[1];
    if (($ra == -99) && ($dec == -99)) {
      if ($debug > 0) {
        printf "nope, that was an invalid radec line\n";
      }
      next;
    } 
    else {
      if ($debug > 0) {
        printf "RA %9.4f  Dec %9.4f \n", $ra, $dec;
      }
    }

    # next, we read the file name and JD from the $name_line
    @namejd = get_namejd($name_line);
    $name = $namejd[0];
    $jd = $namejd[1];
    if ($debug > 0) {
      printf "name is $name, JD is $jd\n";
    }

    # okay, at this point, we can print out a single line with 
    #   all the information in one place.
    printf "%20s %14.5f  %8.4f %8.4f \n", $name, $jd, $ra, $dec;

  }
}


exit 0;


###########################################################################
# Check to see if the given line has the form:
#
#       new RA xxx.xxx   new Dec  xxx.xxxx
#
# If it does, place the RA and Dec values into a 2-element
# return list.  If not, place "-99 -99" into a 2-element return list.
#
sub get_radec {
  my($line);
  my(@words, $ra, $dec, @retlist);

  $line = $_[0];

  if ($debug > 0) {
    printf "get_radec: line is ..%s..\n", $line;
  }
  if ($line =~ /new RA/) {
    @words = split(/\s+/, $line);
    $ra = $words[3];
    $dec = $words[6];
    @retlist = ($ra, $dec);
  }
  else {
    @retlist = (-99, -99);
  }

  return(@retlist);
}


############################################################################
# Given a line which ought to look like this (all one line):
#
#      get_ra_dec: pair_list is {name hira2028683.fits} {filter I} 
#              {jd 2452029.68311} {exposure 100.0} {type object} 
#              {ra 180.0} {dec 0.3}
#
# grab the file name and JD, and return them as a 2-element list.
#
sub get_namejd {
  my($line);
  my(@words);

  $line = $_[0];
  @words = split(/\s+/, $line);
  if ($#words != 17) {
    printf "grab_namejd: following line has %d words, not 17 \n", $#words;
    printf "%s ", $line;
  }
  $name = $words[5];
  $name =~ s/\}//;
  $jd = $words[9];
  $jd =~ s/\}//;
  if ($debug > 0) {
    printf "get_namejd: name is $name  JD is $jd \n";
  }

  @retlist = ($name, $jd);
  return(@retlist);
}
