#!/usr/bin/perl
#@ _COMMENT_
#by GA on Oct ,2022
#Reads in linux cmd file produce by upower commande. Records battery power every 60s and prints date and power to file.
#Process text into a file more sutable for gnuplotting
#Outputs a data file with time and battery power remaining in %.
#@ _COMMENT_

#@ _USE_
use strict;
use warnings;
use autodie; # die if io problem with file
#use 5.010;
#@ _USE_

#@ _VARDECL_
my $workingdir = "/home/greg/";
my $case="4";
my @resltRay; # array variable for later
my @procRay;
my @date;
my $time;
my $resltLg;
my $line = "";
my $line2 = "";
my $index = 0;
my $index2 = 0;
my $procRow = 0;
my @batUpdate;
my @batPower;
#@ _VARDECL_


#******* Note this section searches and does something with the files it finds
open my $infh, '<', $workingdir . '/' . $case . '.txt';
open my $outfh, '>', $workingdir . '/' . $case . 'Proc.txt';
@resltRay = <$infh>; #reads all data lines into result array
$resltLg = @resltRay;
print "$resltLg\n";
#******* Note this section searches and does something with the files it finds
#print STDOUT "Enter first few letters of  last name: ";
#my $caseNo =<STDIN>;
for (@resltRay) {
$index++;
$line = $resltRay[$index];
         if (index($line, 'updated') != -1) {
			#print ("$line\n");
			#@resltLns = split(/ /, $line);
			#print "@resltLns\n";
			  if ($line =~ /.*\((.*)\).*/ ) {      # RegEx used to grab characters in between brackets
			    #print ("$1\n");	
			    @batUpdate = split(' ', $1);	   # Split the batUpdate string to be able to pull out the time to last update
			    #print "$batUpdate[0]\n";
			    if ($batUpdate[0] < 12 ) {
					#print ("$line\n");
					$index2=1;
					while ($index2 < 20 && $index < $resltLg) {
						$index2++;
						$index++;
						#print ("$index\n");
						$line2 = $resltRay[$index];
						if (index($line2, 'percentage') != -1) {
							#print ("$line2\n");
							@batPower = split(' ', $line2);
							@date = split(' ', $line);
							my $length = length($batPower[1]);
							$length = $length -1;
							my $power = substr($batPower[1],0,$length);
							#print ("$power\n");
							#$procRay[$procRow] = $power;
							#$procRow++;
							print{$outfh} $date[5] . " " . $power;
							print{$outfh} "\n";
						}
				    }
			    }
              }
        }
 
  }
#print{$outfh} @procRay;
close $infh;
close $outfh;
