#!/usr/bin/perl 
#
# read two files, one containing distances to known planets,
#    one containing distance to 1P/Halley,
#    and print out a line with information on the most distant
#    known object for each year, like so:
#
#             1736    19.4   Neptune
#
#    where
#            year is in column 1
#            distance (AU) is in column 2
#            name is in column 3
#
# MWR 7/6/2007

$debug = 0;

$planet_file = "./mwr_planets_mod.dat";

$halley_file = "./only_halley.dat";


# step 1: read information from planets file
open(PLANET_FILE, "$planet_file") || die("can't open file $planet_file");
$num_planets = 0;
while (<PLANET_FILE>) {
  $line = $_;
  chomp($line);
  if (substr($line, 0, 1) eq "#") {
    next;
  }
  if ($debug > 0) {
   printf "next planet line is ..%s.. \n", $line;
  }

  @words = split(/\s+/, $line);
  $year = $words[3];
  $sat_dist = $words[4];
  $ura_dist = $words[5];
  $nep_dist = $words[6];
  $plu_dist = $words[7];
  if ($debug > 0) {
    printf("  %7.1f  %7.2f %7.2f %7.2f %7.2f \n",
         $year, $sat_dist, $ura_dist, $nep_dist, $plu_dist);
  }

  # find most distant planet
  $max_dist = $sat_dist;
  $max_planet = "Saturn";
  if ($ura_dist > $max_dist) {
     $max_dist = $ura_dist;
     $max_planet = "Uranus";
  }
  if ($nep_dist > $max_dist) {
     $max_dist = $nep_dist;
     $max_planet = "Neptune";
  }
  if ($plu_dist > $max_dist) {
     $max_dist = $plu_dist;
     $max_planet = "Pluto";
  }
  if ($debug > 0) {
    printf "  max dist %7.2f  %s \n", $max_dist, $max_planet;
  }

  # fill planet_array
  $planet_dist_array[$year] = $max_dist;
  $planet_name_array[$year] = $max_planet;

}
close(PLANET_FILE);


# step 2: read information from Halley file
open(HALLEY_FILE, "$halley_file") || die("can't open file $halley_file");
$num_halley = 0;
while (<HALLEY_FILE>) {
  $line = $_;
  chomp($line);
  if (substr($line, 0, 1) eq "#") {
    next;
  }
  if ($debug > 0) {
   printf "next halley line is ..%s.. \n", $line;
  }

  @words = split(/\s+/, $line);
  $year = $words[4];
  $dist = $words[12];
  # Halley determined the orbit of the comet in 1705
  if ($year < 1705) {
    $dist = 0.0;
  }
  if ($debug > 0) {
    printf "  %7.1f  %7.2f \n", $year, $dist;
  }

  # fill halley_array
  $halley_dist_array[$year] = $dist;
  $halley_name_array[$year] = "1P/Halley";

}
close(HALLEY_FILE);


# step 3: walk through time, from 1601 to 1992, 
#    and figure out which is more distant: a known planet
#    or 1P/Halley.   Print out a line for the most distant object.
#
for ($i = 1601; $i <= 1992; $i++) {

  if ($halley_dist_array[$i] > $planet_dist_array[$i]) {
    $dist = $halley_dist_array[$i];
    $name = $halley_name_array[$i];
  }
  else {
    $dist = $planet_dist_array[$i];
    $name = $planet_name_array[$i];
  }
  printf " %7.0f  %7.2f  %s \n", $i, $dist, $name;
 
}



exit 0;

