#!/usr/bin/perl
# extract_diurnal_curves.pl
#
# by Rob Ferber
# Version 2 - 20121001
#    fixed timestamp bug and added $ARGV[0] for the timezone offset
#    fixed bug where lines for other dates are parsed, crudely fixed
# Version 1 - 20120929
#    Reads all .txt files in current directory, parses for diurnal data
#    and writes a set of .csv files with the same name containing said data
#    Works with SMA data files as of now
#
# Copyright 2012 Rob Ferber 
#    contact rob at electronvault.com for correspondence
#
# This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#    
# 
#
#
$timezone=$ARGV[0];
@files=();

foreach (<*>) {
	print STDOUT "$_ \n";
	next if ! -f ;
	next if ! /^sunnybeam/i;
	next if ! /\.txt\z/;
	push @files,($_);
}

foreach my $blat (@files) {
	open(FILE1,"<$blat");
	open(FILE2,">$blat\.csv");
	while (<FILE1>) {
		next if ! /\A20/;
		next if ! /\d\d:\d\d:\d\d:\s/;
		/^(\d\d\d\d)(-\d\d-\d\d\s+)(\d\d)(:)(\d\d)(:)(\d\d)(:\s+)(\d+)/;
		($year,$hours,$minutes,$seconds,$watts)=($1,$3,$5,$7,$9);
		$timestamp=($hours+$timezone)/24 +($minutes/(24*60))+(($seconds)/(24*3600));
		next if ( $blat!~m/\.$year/ );
		print FILE2 "$timestamp,$watts\n";
	}
	close(FILE1);
	close(FILE2);
}

1;
