#!/usr/bin/perl
#
#Script to read-in obc time data and generate plot 
#Update to run as cgi-script
#
# plot_ra24_pl - Ken Heller 04/17/2015
#
#       Description: Reads RA24 data file and plots temperature and humidity
#                    
#       Usage: plot_ra24.pl 
#
#       Output:
#
# History:
#        Date      Who   Description
#      ---------   ---   ---------------------------------------------------
#      04/17/2015  KH    Create from plot_obctime.pl
###############################################################################
##require "getopts.pl";
require "flush.pl";
require "ctime.pl";
require "timelocal.pl";

$VERSION = "v1.0";

#
# Fix for GNUPLOT font error
#
$ENV{'GDFONTPATH'} = '/usr/share/fonts/default/Type1';
$ENV{'GNUPLOT_DEFAULT_GDFONT'} = 'n019063l.pfb';
#$ENV{'GNUPLOT_DEFAULT_GDFONT'} = 'c059013l.pfb';
#
# Create key/value parameter pairs based on the request method
#
if ($#ARGV >= 0) {@pairs = @ARGV; $otype="ascii";}
if ($ENV{'REQUEST_METHOD'} eq "POST")
     {read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
      @pairs = split(/&/, $buffer);
      } 
else {@pairs = split(/&/, $ENV{'QUERY_STRING'});
      $buffer = "$ENV{'QUERY_STRING'}";
      }

print "Content-type: image/png\n\n";
#print "Content-type: text/html\n\n";

#
# Put the keys and values in an associative array.
# The value of a form variable can then be referenced
# as $form{variable_name}
#

foreach $pair (@pairs) {
    ($key, $value) = split(/=/, $pair);
    $key =~ tr/+/ /;
    $key =~ s/%([a-fA-F0-9]{2})/pack("C", hex($1))/eg;
    $key =~ tr/\cM/\n/;
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9]{2})/pack("C", hex($1))/eg;
    $value =~ tr/\cM/\n/;
    $opt{$key} = $value;
    #print "opt{$key} = $value\n";
}

&flush(STDOUT);

if (defined $opt{'i'}) {$data_file = "$opt{'i'}";}
if (defined $opt{'x'}) {$set_xrange = "set xrange [$opt{'x'}]";}
if (defined $opt{'y'}) {$set_yrange = "set yrange [$opt{'y'}]";}
if (defined $opt{'O'}) {$set_output = "set output \"$opt{'O'}\"";}
		  else {$set_output = "";}
if (defined $opt{'l'}) {$linestyle = "$opt{'l'}";}
		  else {$linestyle = "lines";}
if (defined $opt{'c'}) {$plot_color = "$opt{'c'}";}
		  else {$plot_color = "ls 2";}
if (! defined $opt{'LastN'} || $opt{'LastN'} eq "") {$opt{'LastN'} = 120;}


#For debugging
#print "ARGS=$#ARGV\n"; 
#exit;

##if ($#ARGV < 0 && $ENV{'REQUEST_METHOD'} eq "" && $ENV{'QUERY_STRING'} eq "")
##   {print STDERR "$0 - $VERSION\n";
##    print "Usage: $0 [O=out_imgfile] [x=\"yyyy/mm/dd hh:mm:ss\":\"yyyy/mm/dd ##hh:mm:ss\"] [y=ymin:ymax] <i=ping_data_file[,datafile,...]>\n";
##    print <<"EndUsage";
##EndUsage
##    exit;
##    }

#read start of datafile to get title info
#open(IN,"$data_file") || die "Unable to open ra24 datafile: $data_file\n";
#while ($line = <IN>)
#     {next if ($line =~ /^#/);
#     ($date,$time,$int_temp,$int_humd,$ext_temp,$pge_ph_0,$pge_ph_1,$pge_ph_2,$ups_ph_0,$ups_ph_1,$ups_ph_2,$motion,$door) = split(' ',$line);
##      ($date,$time,$jday,$shore_time,$clk_str,$micro_sec,$jitter) = split(' ',$line);
#      last;
#      }
#close(IN);

#check file size to figure x-label format string
#roughly 1-line is 1sec and ~53 chars (bytes)
if ($opt{'LastN'} > 86400)     {$x_format_str = "%m/%d";
                                $set_xlabel = "set xlabel \"Time mon/day\"";
				}
elsif  ($opt{'LastN'} > 60) {$x_format_str = "%H:%M";
		                $set_xlabel = "set xlabel \"Time hh:mm\"";
				}
else  		      {$x_format_str = "%M:%S";
		       $set_xlabel = "set xlabel \"Time mm:ss\"";
		       }

####################################################

$url1 = "http://ssds-prod.mbari.org/ssds/data/raw-data?deviceID=1780&lastNumberOfPackets=15000&isi=0&noHTMLHeader=1";

$data = get($url1);

# remove the file when the reference goes away with UNLINK option (1 remove 0 keep)
$tmp_fh = new File::Temp( UNLINK => 0 );

my @lines = split /\n/, $data;

foreach my $line (@lines) {

@fields = split /, /, $line;
$GF375 = $fields[1];
$GF375com = $fields[2];
$GF48 = $fields[3];
$GF48com = $fields[4];
$datetime = $fields[6];

print $tmp_fh "$datetime $GF375 $GF375com $GF48 $GF48com\n";
}


#######################################################

#Generate GNUPlot
$script = <<"EndScript";
set terminal png x000000 xdddddd x004400
set size .75,.5
set xdata time
set timefmt "%Y/%m/%d %H:%M:%S"
set format x "$x_format_str"
$set_xrange
$set_yrange
set grid
set key samplen 1
set xtics nomirror
set xtics rotate
set ytics nomirror
set ylabel "Degress F"
$set_xlabel
set title "EOI Room Temperature"
$set_output
EndScript

#$script .= "plot \"<tail -$opt{'LastN'} $data_file\" using 1:5 title \"$ext_temp\"  with $linestyle $plot_color\n";

#$script .= "plot \"<tail -$opt{'LastN'} $data_file\" using 1:5 title \"\" with $linestyle $plot_color\n";

$script .= "plot \"tmp_fh\" using 1:3 title \"\" with $linestyle $plot_color\n";

#$script .= "plot \"<tail -$opt{'LastN'} /webdata/MarsDCSData/ra24/ra24.dat\" using 1:5 title \"\" with $linestyle $plot_color\n";

print "$script\n";

#Execute script
open(GP,"|gnuplot");
print GP $script;
close(GP);
exit;

#
#Subroutines Follow
#
sub gmtimestamp {local($no_gmtlabel) = $_[0];
        local($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime;
        # zero fill hour,min,sec and month
        if ($sec < 10) {$sec = "0$sec";}
        if ($min < 10) {$min = "0$min";}
        if ($hour < 10) {$hour = "0$hour";}
        $mon += 1; #from gmtime defined 0-11, make it 1-12
        if ($mon < 10) {$mon = "0$mon";}
        if ($mday < 10) {$mday = "0$mday";}
   	#make year 4-digits - Note: Year is years since 1900
   	$year += 1900; 
	if ($no_gmtlabel)
             {return "$year/$mon/$mday $hour:$min:$sec";}
        else {return "$year/$mon/$mday $hour:$min:$sec GMT";}
}

