#!/usr/bin/perl

# Get SIAM SeaHorse data using GetOrignaDataServlet	URL


use LWP::Simple;

#Get Current GMT Time
($Second, $Minute, $Hour, $Day, $Month, $Year, $WeekDay, $DayOfYear) = gmtime; 
$YearBase = 1900;
$MonthBase = 1;

#Compute Hours back to last existing file.

# Deal with command line args

$numHoursBack = (defined $ARGV[0]) ? $ARGV[0] : 6; 
$endDate = (defined $ARGV[1]) ? $ARGV[1] : sprintf("%4d%02d%02d.%02d%02d%02d",$YearBase+$Year,$MonthBase+$Month,$Day,$Hour,$Minute,$Second);
$outDir = (defined $ARGV[2]) ? $ARGV[2] : "SeaHorseFiles";
$deviceID = (defined $ARGV[3]) ? $ARGV[3] : 1405;
$platformID = (defined $ARGV[4]) ? $ARGV[4] : 1481;
$ssdsSserver = (defined $ARGV[5]) ? $ARGV[5] : 'ssdspub.mbari.org';

$ssdsSserver = 'new-ssds.mbari.org';

$ZipDir = "./ZipFiles";



$limitGet = "&numHoursOffset=$numHoursBack";
$endDateTime = "&endDateTime=$endDate";

$packets = $numHoursBack/4;



# Read from SSDS bucket

$url = "http://$ssdsSserver:8080/servlet/GetOriginalDataServlet?deviceID=$deviceID&convertTo=hex&noHTMLHeader=1&prependWith=oasis&lastNumberOfPackets=$packets";  #$limitGet$endDateTime";


print STDOUT "Getting data from URL:\n$url\n";
$data =	get($url);


#Make new, empty temporary directory
#open(MKTEMP, "r; mkdir $tempDir|");
#<MKTEMP>;
#close(MKTEMP);



open(OUT, "> $ZipDir/temp.txt") || die "Cannot open $ZipDir/temp.txt: $!\n";
print OUT $data;
close OUT;

open(DATA, "grep -v '<' $ZipDir/temp.txt | grep -v databuffer|"); #Strip out html stuff
    while (<DATA>) { 
      ($date,$data) = split; 
#Convert data buffer to binary and store in filename cooresponding to date field.
      $n = length $data;
      $bindata = pack("H$n",$data);

#Store data in zip file and then extract to appropriate directory.  Remove .zip when finished.
      open(ZIPFILE, "> $ZipDir/$date.zip");
      print ZIPFILE $bindata;
      close(ZIPFILE);
      open(EXTRACT, "unzip -d $outDir -oq $ZipDir/$date.zip|");
      <EXTRACT>;
      close(EXTRACT);
#      open(REMOVE,"rm $ZipDir/$date.zip|");
#      <REMOVE>;
#      close(REMOVE);
   } 
close(DATA); 

#Remove temporary directory
#open(RMTEMP, "rm -r $ZipDir|");
#<RMTEMP>;
#close(RMTEMP);



#Use SBE tools to convert data, this is tricky because the DatCnvW.exe tool looks in a windows .ini file
#for information.  The command line options are supposed to over-ride, but aren't reliable.


