#!/usr/bin/perl -w
use strict;
use Statistics::Descriptive;

my $SLEEP_AFTER_COMMAND = 60;
my $SLEEP_BETWEEN_MEAUREMENTS = 10;
my $NUMBER_OF_MEASUREMENTS = 10;

sub read_file {
    my ($file) = @_;
    open(my $fd, "<", $file);
    my $ret = <$fd>;
    close($fd);
    chomp($ret);
    return $ret;
}

sub write_file {
    my ($file, $data) = @_;
    open(my $fd, ">", $file)
	or die "unable to open $file for writing: $!";
    print $fd $data;
    close($fd);
}

sub get_current {
    return read_file("/sys/class/power_supply/battery/current_now");
}

sub dbg {
    my ($msg) = @_;
    printf(">dbg %s\n", $msg);
}

sub run_and_measure {
    my ($cmd) = @_;
    dbg("running $cmd");
    system($cmd);
    dbg("sleeping for $SLEEP_AFTER_COMMAND seconds for current to stabilize");
    sleep($SLEEP_AFTER_COMMAND);
    dbg("taking $NUMBER_OF_MEASUREMENTS samples with $SLEEP_BETWEEN_MEAUREMENTS-second delays");
    my $measurements =  Statistics::Descriptive::Full->new();
    for (my $i = 0; $i < $NUMBER_OF_MEASUREMENTS; $i++) {
	my $tmp = get_current();
	$measurements->add_data($tmp);
	dbg(sprintf("current now %8d, mean %9.4f, deviation %9.4f, range %9.4f",
		    $tmp,
		    $measurements->mean(),
		    $i ? $measurements->standard_deviation() : -1,
		    $measurements->sample_range()));
	sleep($SLEEP_BETWEEN_MEAUREMENTS);
    }
}

system("xset dpms 0 0 0");
system("xset dpms force on");
system("xsetroot -solid white");
run_and_measure("echo 102 > /sys/class/backlight/gta02-bl/brightness");

system("xsetroot -solid black");
run_and_measure("xset dpms force off");

