#!/usr/bin/perl -w

use strict;

#
# Processing the command line parameters.
#
if (($ARGV[0] eq "-h") | ($ARGV[0] eq "--h") | ($ARGV[0] eq "-help") | ($ARGV[0] eq "--help"))
{
  print "\nThis Script runs a number of 'make pre' and captures the out files\n";
  print "which are appended to acq.log\n\n";
  print "\nUsage: ./AcqLoop.pl <Number of Acquisitions> <Sleeping time between in seconds>\n\n";
  exit;	
}

my $AcqCycles = 10;
if (@ARGV <= 2)
{
  $AcqCycles = $ARGV[0];
}
my $AcqSleepTime = 10;
if (@ARGV == 2)
{
  $AcqSleepTime = $ARGV[1];
}

my ($Sekunden, $Minuten, $Stunden, $Monatstag, $Monat,
    $Jahr, $Wochentag, $Jahrestag, $Sommerzeit) = localtime(time);
$Monat+=1;
$Jahrestag+=1;
$Monat = $Monat < 10 ? $Monat = "0".$Monat : $Monat;
$Monatstag = $Monatstag < 10 ? $Monatstag = "0".$Monatstag : $Monatstag;
$Stunden = $Stunden < 10 ? $Stunden = "0".$Stunden : $Stunden;
$Minuten = $Minuten < 10 ? $Minuten = "0".$Minuten : $Minuten;
$Sekunden = $Sekunden < 10 ? $Sekunden = "0".$Sekunden : $Sekunden;
$Jahr+=1900;    
my $TimeTag = sprintf("%02d:%02d:%02d", $Stunden, $Minuten, $Sekunden, $Stunden*3600 + $Minuten*60 + $Sekunden);


#
# Aqcuisition output file.
#

open(OUTDAT, ">Acq.log") || die "Acq.log could not be opened for writing.!\n";

for (my $i=1; $i <= $AcqCycles; $i++)
{

  system "clear";
  
  ($Sekunden, $Minuten, $Stunden, $Monatstag, $Monat, $Jahr, $Wochentag, $Jahrestag, $Sommerzeit) = localtime(time);
  $Monat+=1;
  $Jahrestag+=1;
  $Monat = $Monat < 10 ? $Monat = "0".$Monat : $Monat;
  $Monatstag = $Monatstag < 10 ? $Monatstag = "0".$Monatstag : $Monatstag;
  $Stunden = $Stunden < 10 ? $Stunden = "0".$Stunden : $Stunden;
  $Minuten = $Minuten < 10 ? $Minuten = "0".$Minuten : $Minuten;
  $Sekunden = $Sekunden < 10 ? $Sekunden = "0".$Sekunden : $Sekunden;
  $Jahr+=1900;    
  $TimeTag = sprintf("%02d:%02d:%02d", $Stunden, $Minuten, $Sekunden, $Stunden*3600 + $Minuten*60 + $Sekunden);

  print OUTDAT "$i. Acquisition run: $TimeTag\n";
  #
  # Start TRAP sending
  # 

  print "Starting $i.th acquisition cycle.\n";

  
  
  
  qx(make pre);

  # 
  # Read in out file of make pre.
  #  

  my @Lines = ("");
  open(INDAT, "<out") || die "out could not be opened!\n";
  while(<INDAT>)
  {
     push(@Lines, $_);
  }
  close(INDAT);
  
  #
  # Append the lines to a long log.
  #

  print OUTDAT "--------------------------------\n";  
  foreach(@Lines)
  {
    print OUTDAT $_;
  }

  print OUTDAT "\n\n";  
  print "Done. Sleeping...\n";
  
  sleep($AcqSleepTime);

}

close(OUTDAT);
print "\n\nAcquisition completed.\n";


