#!/usr/bin/perl

use warnings;

# Default zero at top (brightness meter)
$zero="top";

#default Gnuplot executable
$gnuplot="gnuplot";

# Grab command line arguments
  foreach (@ARGV) {
     if(substr($_, 0, 2) eq "-h") {
	print STDERR "Usage: $0 [options]\n";
	print STDERR "  Options: [-sSLEEPTIME] default 120 seconds\n";
	print STDERR "           [-gGRAPHICFILE] default sqmleg.gif\n\n";
	print STDERR "           [-uUPDATELOCATION] place to scp graphics file\n\n";
	print STDERR "           [-z] Zero at bottom of plot\n\n";
	print STDERR "           [-e] executable location of Gnuplot\n\n";
	print STDERR "  Example:\n";
	print STDERR "       $0 log.txt 120 \n";
	exit;
     }

     if(substr($_, 0, 2) eq "-z") {
       # Zero at bottom (darkness meter)
       $zero="bottom";
     }

     if(substr($_, 0, 2) eq "-s") {
       $sleep_sec=substr($_, 2);
       if ($sleep_sec<=1) {
         print STDERR "The sleep time must be greater than 1 second\n";
         exit;
       }
     }

     if(substr($_, 0, 2) eq "-u") {
       $updatelocation=substr($_, 2);
     }

     if(substr($_, 0, 2) eq "-g") {
         print STDERR "Graphics file definition not implemented yet\n";
     }

     #Check for user defined Gnuplot executable
     if(substr($_, 0, 2) eq "-e") {
	$gnuplot=substr($_, 2);
     }

  }

if (! defined($sleep_sec)) {
  $sleep_sec = 120;
  print STDERR "Sleep time not provided, so $sleep_sec seconds assumed\n";
}

# Graph y axis settings
$y_lower_limit=-22.0;
$y_upper_limit=-16.0;
#Check if reversed plot is required, then swap limits
if ($zero eq "bottom"){
  ($y_lower_limit, $y_upper_limit) = ($y_upper_limit, $y_lower_limit);
  $y_lower_limit=$y_lower_limit*-1;
  $y_upper_limit=$y_upper_limit*-1;
}

# Initialize internal error checking
$yesterday_log_error=0;
$today_log_error=0;


while(1){

  $currenttime=time;

  # create empty arrays to hold data set
  @x=(); @y=();



	#Clear out previous data points
	open(DATAFILE,">","tmpdata.txt") or die "Failed to create temporary data file.";
	print DATAFILE "";
	close(DATAFILE);


  #read in yesterdays logfile
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($currenttime-86400);
  $logfile =sprintf("%04d%02d%02d.log",$year+1900,$mon+1,$mday);
  $fileopenedfailed=0;
  open(LOGFILE, $logfile) or $fileopenedfailed=1;
  if ($fileopenedfailed==0){
	$yesterday_log_error=0;
	@raw_data=<LOGFILE>;
	close(LOGFILE);
	open(DATAFILE,">","tmpdata.txt") or die "Failed to create temporary data file.";
	foreach $LINE_VAR (@raw_data) {
		#Only gather data from past 24 hours for plotting 
		if (substr($LINE_VAR,0,2)>=$hour+1){
		  # Get x value
		  push(@x,substr($LINE_VAR,0,2)+substr($LINE_VAR,3,2)/60.0+substr($LINE_VAR,6,2)/3600.0-24);
		  $x_value=substr($LINE_VAR,0,2)+substr($LINE_VAR,3,2)/60.0+substr($LINE_VAR,6,2)/3600.0-24;
		  # Get y value
		  if ($zero eq "bottom"){
			$y_value=substr($LINE_VAR,8,6);
		  }else{
			$y_value=substr($LINE_VAR,8,6)*-1;
		  }
		  #Apply limits to plotted line
		  if ($y_value>$y_upper_limit) {$y_value=$y_upper_limit;}
		  if ($y_value<$y_lower_limit) {$y_value=$y_lower_limit;}
		  push(@y,$y_value);
		  print DATAFILE "$x_value $y_value\n";
		}
	}
	close(DATAFILE);
  }else{
	if ($yesterday_log_error==0) {
		print STDERR "Could not open yesterdays log file ".$logfile."\n";
		$yesterday_log_error=1;
	}

  }
  #read in todays logfile
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($currenttime);
  $logfile =sprintf("%04d%02d%02d.log",$year+1900,$mon+1,$mday);
  $fileopenedfailed=0;
  open(LOGFILE, $logfile) or $fileopenedfailed=1;
  if ($fileopenedfailed==0){
	$today_log_error=0;
	@raw_data=<LOGFILE>;
	close(LOGFILE);
	open(DATAFILE,">>","tmpdata.txt") or die "Failed to create temporary data file.";
	foreach $LINE_VAR (@raw_data) {
		# Get x value
		push(@x,substr($LINE_VAR,0,2)+substr($LINE_VAR,3,2)/60.0+substr($LINE_VAR,6,2)/3600.0);
		$x_value=substr($LINE_VAR,0,2)+substr($LINE_VAR,3,2)/60.0+substr($LINE_VAR,6,2)/3600.0;
		# Get y value
		if ($zero eq "bottom"){
			$y_value=substr($LINE_VAR,8,6);
		}else{
			$y_value=substr($LINE_VAR,8,6)*-1;
		}
		#Apply limits to plotted line
		if ($y_value>$y_upper_limit) {$y_value=$y_upper_limit;}
		if ($y_value<$y_lower_limit) {$y_value=$y_lower_limit;}
		push(@y,$y_value);
		print DATAFILE "$x_value $y_value\n";
	}
	close(DATAFILE);

  }else{
	if ($today_log_error==0) {
		print STDERR "Could not open todays log file ".$logfile."\n";
		$today_log_error=1;
	}
  }
  # Prepare graph title showing days covered in graph
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($currenttime-86400);
  $yesterday = sprintf("%04d-%02d-%02d",$year+1900,$mon+1,$mday);

  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($currenttime);
  $today = sprintf("%04d-%02d-%02d",$year+1900,$mon+1,$mday);

#Only plot if there is some data in array
if (@y>0) {

#Time Of Day label correction
sub todlabel{
	# Get time of day parameter
	my $xlval=shift;
	# Correct for negative time labels
	if ($xlval<0) {$xlval=$xlval+24}
	# Corect for AM/PM
	$m="a"; # default
	if ($xlval==12) {$m="p"}
	if ($xlval==0) {$m="a";$xlval=12;}
	if ($xlval>12) {$m="p";$xlval=$xlval-12;}
	#Return corrected time of day suitable for plot x axis label
	return $xlval. ":00".$m;
}

	$xvalstr='';
	for ($xlval = $hour-23; $xlval < $hour+1; $xlval++){
		#Time of day, major tics
		$xvalstr=$xvalstr . " '" . todlabel($xlval). "' " . $xlval. " 0,";
		#Empty labels, minor tics
		for ($i=1; $i < 4; $i++){
			$xlval++;
			$xvalstr=$xvalstr . "' ' " . $xlval . " 1,";
		}
	}
	# Current hour is last label
	$endhour=$hour+1;
	$xvalstr=$xvalstr . " '" . todlabel($endhour% 24) . "' " . $endhour. " 0";


	#Create temporary plot file with properties of the chart
	open(PLOTFILE,">","tmpplot.txt") or die "Failed to create temporary plot file";
	print PLOTFILE "set output 'sqmleg.gif'\n";
	print PLOTFILE "set terminal gif transparent size 318,183\n";
	print PLOTFILE "set ylabel 'mpsas' noenhanced\n";
	$xrangemin=$hour-23;
	$xrangemax=$hour+1;
	print PLOTFILE "set xrange [$xrangemin:$xrangemax]\n";
	print PLOTFILE "set title '$yesterday - $today' noenhanced\n";
	print PLOTFILE "set yrange [$y_lower_limit:$y_upper_limit]\n";
	print PLOTFILE "set border 3\n";
	if ($^O eq "MSWin32"){
		print PLOTFILE "set lmargin 3.5\n";
		print PLOTFILE "set rmargin 1.8\n";
	}
	print PLOTFILE "set title '$yesterday - $today' font ',30'\n";
	printf PLOTFILE "set xtics nomirror out scale 3,1 (%s)\n",$xvalstr;
	print PLOTFILE "set grid mxtics mytics xtics ytics\n";

	if ($zero eq "bottom"){
		print PLOTFILE "set ytics nomirror out scale 3,1 ('14' 14 0,' ' 15 1, '16' 16 0,' ' 17 1,'18' 18 0,' ' 19 1,'20' 20 0,' ' 21 1,'22' 22 0)\n";
	}else{
		print PLOTFILE "set ytics nomirror out scale 3,1 ('14' -14 0,' ' -15 1, '16' -16 0,' ' -17 1,'18' -18 0,' ' -19 1,'20' -20 0,' ' -21 1,'22' -22 0)\n";
	}

	print PLOTFILE "plot 'tmpdata.txt' title '' with lines\n";
	close(PLOTFILE);

	#Set the gnuplot executable location, be specific if it is not in the PATH.
	$gnuplot="gnuplot";

	# Plot the data set on the chart
	system("$gnuplot tmpplot.txt");


    if (defined($updatelocation)) {
      system "scp -P 30000 sqmleg.gif ".$updatelocation." > null";
    }

  }


    sleep($sleep_sec);
}

