#!/usr/bin/perl

# Una possibile soluzione all'Esercizio 2 (non l'unica)

use strict;
use warnings;

my $time = shift || 2; # Tempo specificato oppure 2 (secondi)

my $mem_free_precedente = 0;
my $counter = 0;
my @incrementi = ();
my @decrementi = ();
while (42) {
    sleep $time;

    my @mem_free_line = split(/\s+/, `cat /proc/meminfo | grep ^MemFree:`);
    my $diff = $mem_free_line[1] - $mem_free_precedente;
    $mem_free_precedente = $mem_free_line[1];

    if ($diff > 0) {
        print '>';
        push @incrementi, $diff;
    } elsif ($diff < 0) {
        print '<';
        push @decrementi, $diff;
    } else {
        print '=';
    }

    print ' ', $diff, ' ', $mem_free_line[2], "\n";

    $counter++;
    
    if ($counter == 5) {
        open(my $log_fh, ">>", "mem_free.log") or die "Can't open >> mem_free.log: $!";

        print $log_fh "i\n";
        print $log_fh join(",", @incrementi), "\n";

        print $log_fh "d\n";
        print $log_fh join(",", @decrementi), "\n";

        print $log_fh '-' x 10, "\n";

        close $log_fh;

        @incrementi = ();
        @decrementi = ();
        $counter = 0;
    }

}
