#!/usr/bin/perl
#
# Given input on stdin with several columns of data,
#    we read values from one column (call it "time")
#    and key on it to interpolate and resample a second
#    column (call it "data") at regular intervals.
#
# We use simple linear interpolation between the nearest
#    two actual data points in time.
#
# MWR 9/28/2004

$debug = 0;

$time_col = 1;
$data_col = 2;
$interval = 0.0005;

# if you don't have a specific start time in mind, set this
#    to -99 and the program will pick a time just after the 
#    first time value.
$start_time = 2453275.55108;
#$start_time = -99.0;


# first, we read in all the data
$num_lines = 0;
while (<STDIN>) {
  if ($_ =~ /^#/) {
    next;
  }
  $line = " " . $_;
  @words = split(/\s+/, $line);
  $time_array[$num_lines] = $words[$time_col];
  $data_array[$num_lines] = $words[$data_col];
  if ($debug > 0) {
    printf "  line %6d  time %12.5f  data %7.3f \n", $num_lines, 
              $time_array[$num_lines], $data_array[$num_lines];
  }
  $num_lines++;
}
if ($debug > 0) {
  printf " num_lines $num_lines\n";
}

# next, we define the starting and ending times, 
#    which are just after the data starts and just before it ends
if ($start_time == -99) {
  $start_time = $time_array[0] + ($interval*0.5);
}
$end_time  = $time_array[$num_lines-1] - ($interval*0.5);
if ($debug > 0) {
  printf " start_time $start_time   end_time $end_time \n";
}

# and now we interpolate through the array
$prev_i = 0;
for ($time = $start_time; $time <= $end_time; $time += $interval) {

  # find the time values which span the current "time"
  while (($prev_i < $num_lines - 1) && ($time_array[$prev_i + 1] < $time)) {
    $prev_i++;
  }
  if ($debug > 0) {
    printf "   prev %6d %12.5f  time %12.5f   next %12.5f \n", 
           $prev_i, $time_array[$prev_i], $time, $time_array[$prev_i + 1];
  }

  # linearly interpolate between the two corresponding data values
  $frac = ($time - $time_array[$prev_i])/($time_array[$prev_i + 1] - $time_array[$prev_i]);
  $this_data = $data_array[$prev_i] + 
                       $frac*($data_array[$prev_i + 1] - $data_array[$prev_i]);

  printf " %12.5f %8.4f \n", $time, $this_data;

}



exit 0;
