#!/usr/bin/perl
#
if ( $ARGV[0] eq '-h')
{ print "USAGE:\n        rolling.pl [-q] [-d <dir>] [{ -a | -o <outfile> }] \\\n";
  print "                   [-b <#bl>] [{-T <#toff> | -t <#tadd>}]   \\\n";
  print "                   <file-expr> &\n\n"; 
  print "OPTIONS:\n";
  print " -q            - Run quietly\n\n";
  print " -a            - Autodate = automatic input file names\n";
  print "                 from dir, date and #toff. Default: not -a but -f\n\n";
  print " -d <dir>      - Input files' directory, default = o\n";
  print " -o <outfile>  - Output file, default tmp.dat\n\n";
  print " -b <#bl>      - Length of a bunch, default=60\n\n";
  print " -T <#toff>    - Time offset #toff seconds\n\n";
  print " -t <#tadd>    - Time offset by countdown from midnight plus\n";
  print "                 #tadd seconds\n\n";
  print " <file-expr>   - File name with or without wildcards;\n";
  print "                 if with wildcards, enclose it in quotes.\n\n";
  print "This program should not be stopped with ^C but rather by\n";
  print "creating a file named STOP in the execution directory. This file\n";
  print "is removed at program start\n";
  exit
}
#
# Example: rolling.pl 'RAW_o054/G112????.054'
#
# This program copies the last $bl (60) lines of 57 bytes of an input file 
# to a temporary file whenever the size of the input file has changed
# The input file is found using the fist line of the result of unix command
#    ls -lt <file-expr>
# (i.e. the most recent file matching the expression)
#
# For testing the procedure, program slowcopy.pl can be used to produce
# files with a pseudo-realistic date in the file name.
# The date would be the current date plus an offset in order to test the
# behaviour around midnight system times.  
#
# If the file expression globs many files, processing might become slow.
#
# The 57 bytes correspond to the length of a GWR G1 record.
# Thus, this procedure copies the most recently written gravity and
# pressure data to the temporary store.
#    Use udp-client.py to single-cast the data at one line per second
# rate (with an inevitable 1-minute latency).
#
# The master procedure, slowcopy.pl , has accurate timing, and so has the
# gravimeter. 
#   This procedure uses a less precise clock for guessing at the file name. 
# It will read the  most recent file at every instance when the file size 
# has changed. 
#   The critical phase is (maybe) the moment when the file header is being 
# written. 
#
# *  We might employ a test on a minimum file size.  Must be 
#       header + 60 data lines (8187 bytes) or greater.
# *  In autodate mode we might have to add a few seconds for predicting 
#       the actual file names (but the new file is interesting only
#       one minute after midnight). 
# *  and/or shorten the sleeping interval (using the usleep function?);
# *  and/or scan for three files, one day past, the very day, and one day 
#      ahead (would not exist except after midnight). 
# *  Leap seconds will give us additional trouble (look at the last line
#      (with tail -1); if second=60, read a bunch of 61 lines then).
#
use POSIX qw(strftime);
#
$file='d/tst.dat';
$bl=60;
$out='tmp.dat';
$talk=1;
$autodate=0;
$dir='o';
$topp=0;
`rm STOP`;
#
# 
while ( $ARGV[0] =~ m/[-].*/ )
{ if     ( $ARGV[0] eq '-o' )
  { $out=$ARGV[1]; shift }
  elsif  ( $ARGV[0] eq '-b' )
  { $bl=$ARGV[1]; shift }
  elsif  ( $ARGV[0] eq '-d' )
  { $dir=$ARGV[1]; shift }
  elsif  ( $ARGV[0] eq '-q' )
  { $talk=0 }
  elsif  ( $ARGV[0] eq '-T' )
  { $toff=$ARGV[1]; shift }
  elsif  ( $ARGV[0] eq '-t' )
  { $af=1; $toff = 86400 + $ARGV[1] - (time % 86400); shift 
  }
  elsif  ( $ARGV[0] eq '-a' )
  { $autodate=1 }
  else { die "Invalid option $ARGV[0]" }
  shift
}

if ( ( ! $autodate ) || $ARGV[0] ){ $file = $ARGV[0] }
if ( $autodate )
{ $now = strftime "%y%m%d", gmtime; 
  $rct = strftime "%y%m%d", gmtime(time-100); 
  $ahd = strftime "%y%m%d", gmtime(time+100); 
  $auf = $dir.'/G1'.$now.'.054 '.$dir.'/G1'.$rct.'.054';
  print "Files for now and recently: $auf\n";
  $file=$auf 
}

print "Files: $file\n";
$osz='-1';

while ( ! stat('STOP') )
{ if ( $autodate )
  {
     $now = strftime "%y%m%d", gmtime(time+$toff); 
     $rct = strftime "%y%m%d", gmtime(time+$toff-100); 
     $file = $dir.'/G1'.$now.'.054 '.$dir.'/G1'.$rct.'.054' 
  }    
  $s = `ls -lt $file 2> /dev/null | head -1`;
  if ( ! $s ){ print "STOP: No files $file\n"; die "No files $file\n" }
  $s =~ s/\n//g;
  if ( ! $s ){ print "STOP: No files $file\n"; die "No files $file\n" }
  @flist = split(/ +/, $s);
#  print "$flist[8] $flist[4]\n"
;
  if ( $flist[4] <= 8178 ){ print "$flist[8] too small: $flist[4]\n" }
  if ( $flist[4] > 8178 && $flist[4] ne $osz )
     { if ( $talk )
          { print "$flist[8] Updated ->$flist[4]<->$osz\n"; $osz=$flist[4] }
       sleep(1);
       open (FH, $flist[8]) or die "No such file\n";
       seek (FH, -$bl*57, 2);
       open ( FU, ">".$out );
       while (<FH>)
       { chomp; 
#	 if ( m/^20\d\d / )
	 if ( 1 ){ print FU "$_\n"; print "->$_\n" } # $lr=$_ }
       }
       close(FU);
       if ( $talk ){ print "Last rec on $flist[8] :: $lr\n" }
     }
}
end

