#!/usr/bin/perl
# Convert a datafile of the form
#
#       YYYYMMDD.dddd   mag*10
#
#       20050805.2333   123
#
# into the form
#
#       (JD - 2,450,000)  mag
#
# MWR 8/14/2005

use POSIX;

$debug = 0;


while (<STDIN>) {
  $line = $_;
  if ($line =~ /^#/) {
    print $line;
    next;
  }

  $line = " " . $line;
  @words = split(/\s+/, $line);
  $date = $words[1];
  $mag_times_10 = $words[2];
  if ($debug > 0) {
    printf "  date ..%s..  mag_times_10 ..%s.. \n", $date, $mag_times_10;
  }
  
  # we have to deal with each month separately
  $year_str = substr($date, 0, 4);
  $month_str = substr($date, 4, 2);
  $day_str = substr($date, 6, 6);
  if ($debug > 0) {
    printf " year ..%s.. month ..%s.. day ..%s.. \n", 
           $year_str, $month_str, $day_str;
  }

  # calculate the UT hour, minute, second of the observation
  $day_frac = $day_str - floor($day_str);
  if ($debug > 0) {
    printf "day_frac is ..%lf.. \n", $day_frac;
  }
  $x = $day_frac*24.0;
  $hour = floor($x);
  $x = $x - $hour;
  if ($debug > 0) {
    printf "hour is ..%lf..  x  is ..%lf.. \n", $hour, $x;
  }
  $x = $x*60.0;
  $minute = floor($x);
  $x = $x - $minute;
  if ($debug > 0) {
    printf "minute is ..%lf..  x  is ..%lf.. \n", $minute, $x;
  }
  $x = $x*60.0;
  $second = floor($x);
  $x = $x - $second; 
  if ($debug > 0) {
    printf "second is ..%lf..  x  is ..%lf.. \n", $second, $x;
  }

  # now prepare to call the "jd" program to calc JD.
  #   We need a string for the UT date, in form DD/MM/YYYY
  #   and a string for the UT time, in form HH:MM:SS
  #
  $date_str = sprintf "%02d/%02d/%04d", $day_str, $month_str, $year_str;
  $time_str = sprintf "%02d:%02d:%02d", $hour, $minute, $second;
  if ($debug > 0) {
    printf "date_str ..%s..   time_str ..%s.. \n", $date_str, $time_str;
  }

  # run the "jd" program to compute the Julian Date of observation
  $cmd = "~/bait/jd ut=$time_str date=$date_str ";
  if ($debug > 0) {
    printf " about to run cmd ..%s.. \n", $cmd;
  }
  $ret = `$cmd`;
  if ($debug > 0) {
    printf " ret is ..%s.. \n", $ret;
  }
  $jd = $ret;
  chomp($jd);
  if ($debug > 0) {
    printf " jd is ..%12.5f.. \n", $jd;
  }

  # finally, we calculate a truncated Julian Date
  #     mjd = jd - 2,450,000
  $mjd = $jd - 2450000.0;

  # and print out the truncated JD, followed by magnitude
  $mag = $mag_times_10/10.0;

  printf " %12.5f %6.2f \n", $mjd, $mag;
}


exit 0;
