#!/usr/bin/perl
#
# Given a file which has trajectory of a pitched ball, with lines
#   like this:
#
#     QQ  t 0.0000e+00  pos -1.6764e+01 1.9812e+00 6.0960e-01  vel ....
#
#   Pick out the lines which occur at intervals of $INTERVAL
#   (probably 0.10 seconds).  
#
# We will replace the input file with a new version which has
#
#       a) the original data, just as it was
#       b) two blank lines
#       c) only the lines at intervals
#
# We can then plot either set via the "index" option in GNUPLOT.
#
# Usage:
#              make_second_stanza.pl   traj.A.dat
#
# MWR 8/6/2008
#
use POSIX;

$debug = 1;
$tempfile = "./make_second_stanza.tmp";
$INTERVAL = 0.10;
$TINY = 1.0e-6;

if ($#ARGV != 0) {
  printf "usage: make_second_stanza.pl  traj.A.dat \n";
  exit(1);
}
$infile = $ARGV[0];
if ($debug > 0) {
  printf " infile is ..%s.. \n", $infile;
}

$num_lines = 0;
open(INFILE, "$infile") || die("can't open file $infile");
while (<INFILE>) {
  $line = $_;
  chomp($line);
  $line_array[$num_lines] = $line;

  @words = split(/\s+/, $line);
  $time_array[$num_lines] = $words[3];

  $num_lines++;
}
close(INFILE);

# now we open a temp file and write into it
open(TEMPFILE, ">$tempfile") || die("can't open file $tempfile");
# copy the original data, line for line
for ($i = 0; $i < $num_lines; $i++) {
  printf TEMPFILE "%s\n", $line_array[$i];
}

# add two blank lines
printf TEMPFILE "\n\n";

# now print only the lines which occur at intervals of INTERVAL
$previous_time = 0.0;
$timer = 0;
for ($i = 0; $i < $num_lines; $i++) {
  if ($i == 0) {
    printf TEMPFILE "%s\n", $line_array[$i];
    next;
  }
  if (($INTERVAL - (fabs($time_array[$i] - $previous_time))) < $TINY) {
    $previous_time = $time_array[$i];
    printf TEMPFILE "%s\n", $line_array[$i];
  }
}

# move the temporary file into the place of the original file
$cmd = "mv $tempfile $infile";
exec_cmd($cmd);





close(TEMPFILE);


exit 0;




##############################################################################
# PROCEDURE: exec_cmd
#
# DESCRIPTION: Execute the given shell command line.  If the $debug flag
#              is set, we print to stdout the command line, and
#              also print out the result string.
#
# RETURNS:
#              the result of the command
#
#
sub exec_cmd {

  my($cmd, $ret);

  $cmd = $_[0];

  if ($debug > 0) {
    printf "cmd is ..$cmd.. \n";
  }
  $ret = `$cmd`;
  if ($debug > 0) {
    printf "ret is ..$ret.. \n";
  }

  return($ret);
}


