#!/usr/bin/perl
#
# Given two input files:
#
#    a) output of multipht, showing .pht file name and dr,dc for each one
#    b) solvepht.img, with .pht file name and JD
#
# create a new file which has one line per image.  The line will contain
#
#       - .pht file name
#       - JD
#       - dr
#       - dc
#
# so we can use it to plot drift as a function of JD.
#
# Print output to stdout.
#
#
# MWR 9/23/2017

$usage = "prepare_track_data.pl    multi.out  solvepht.img   ";

$debug = 0;

# parse args
if ($#ARGV != 1) {
  printf "usage: $usage \n";
  exit(1);
}
$multi_file = $ARGV[0];
$solve_file = $ARGV[1];
if ($debug > 0) {
  printf "  multi_file:   $multi_file  \n";  
  printf "  solve_file:   $solve_file  \n";
}


# step 1: read in multipht file, create array of .pht file names 
$num_pht = 0;
open(MULTI_FILE, "$multi_file") || die("can't open multi_file $multi_file");
while (<MULTI_FILE>) {
  $line = $_;
  chomp($line);
  if ($line =~ /^lists/) {
    @words = split(/\s+/, $line);
    $pht_name_array[$num_pht] = $words[2];
    $pht_dr_array[$num_pht] = $words[5];
    $pht_dc_array[$num_pht] = $words[8];
    $num_pht++;
  }

}
close(MULTI_FILE);
if ($debug > 0) {
  printf " read %5d lines from multi_file $multi_file \n", $num_pht;
  for (my $i = 0; $i < $num_pht; $i++) {
    printf " pht %5d  name %30s  dr %8.3f  dc %8.3f \n",
             $i, $pht_name_array[$i], $pht_dr_array[$i], $pht_dc_array[$i];
  }
}


# step 2: read in solvepht.img file, create array of .pht file names 
#              and JD values
$num_img = 0;
open(SOLVE_FILE, "$solve_file") || die("can't open solve_file $solve_file");
while (<SOLVE_FILE>) {
  $line = $_;
  chomp($line);
    @words = split(/\s+/, $line);
    $img_name_array[$num_img] = $words[1];
    $img_jd_array[$num_img] = $words[3];
    $num_img++;

}
close(SOLVE_FILE);
if ($debug > 0) {
  printf " read %5d lines from solve_file $solve_file \n", $num_img;
  for (my $i = 0; $i < $num_img; $i++) {
    printf " img %5d  name %30s  JD %12.5f   \n",
             $i, $img_name_array[$i], $img_jd_array[$i];
  }
}


# step 3: match up the information using the .pht file name
for (my $i = 0; $i < $num_pht; $i++) {
  $pht_name = $pht_name_array[$i];
  if ($debug > 0) {
    printf "  i = %5d  looking for pht %s \n", $i, $pht_name;
  }
  my $found = 0;
  for (my $j = 0; $j < $num_img; $j++) {
    $img_name = $img_name_array[$j];
    if ($debug > 0) {
      printf "    j = %5d  checking img %s \n", $j, $img_name;
    }
    
    if ($img_name eq $pht_name) {
      printf "  %5d %25s  %12.5f  dr %8.3f  dc %8.3f \n", 
           $i, $pht_name, $img_jd_array[$j], 
           $pht_dr_array[$i], $pht_dc_array[$i];
      $found = 1;
      last;
    }

  }

  if ($found == 0) {
    printf "can't find match for pht %5d %25s  ?! \n", 
            $i, $pht_name;
  }

}







exit 0;
