#!/usr/bin/env perl

use strict;

my $debug = 0;

my $listfilename = "resultlist.txt";
open(my $fh, '<', $listfilename ) or die "Can't open $listfilename: $!";

my $count = 0;
my $splitstring = "\_";

my $stastring = "sta";
my $sampastring = "sampa";

my $sta = 0;
my $ch = 0;

my @nTests; # 100000 - 
my @filestring;

my $minChip = 100000;
my $maxChip = 999999;

for ($ch=$minChip; $ch<=$maxChip; $ch++) {
    $nTests[$ch][0] = 0;
    $nTests[$ch][1] = 0;
    $filestring[$ch] = "";
}
$minChip = $maxChip;
$maxChip = 0;

#while ( (my $filename = <$fh>) && ($count<10) ) # test
while (my $filename = <$fh>) 
{
    chomp($filename);
    print "filename $filename\n";
    
# in case we want to check filesizes etc also...
#    (my $dev, my $ino, my $mode, my $nlink, my $uid, my $gid,
#      my $rdev, my $size, my $atime, my $mtime, my $ctime,
#     my $blksize, my $blocks) = stat($filename);
    
# ok, could be something interesting
    my  @dirs = split("\/", $filename);
    if ($debug>0) { print "dirs3 $dirs[3] dirs4 $dirs[4] dirs5 $dirs[5]\n"; }
    my  @arr = split($splitstring, $dirs[5]);
    if ($debug>0) { print "arr1 $arr[1] arr2 $arr[2] arr3 $arr[3]\n"; }

    $_ = $arr[1];
    s/$stastring//g;
    $sta = $_ + 0;
  
    $_ = $arr[2];
    s/$sampastring//g;
    $ch = $_ + 0;

    if ($debug>0) { print "sta $sta ch $ch\n"; }
    if ($minChip > $ch) { $minChip = $ch; }
    if ($maxChip < $ch) { $maxChip = $ch; }

    $filestring[$ch] = $filename; # last tested file
    $nTests[$ch][$sta]++; 

    $count++;
}

print "found $count files\n";

# how many different descstrings, temp and cap values do we have?
#my @unique_chip = uniq @chip;
#my @sorted_chip = sort { $a <=> $b } @unique_chip;

my $outputFilename = "filelist\_last.txt";
open(OUTP, ">$outputFilename");

my $tray = 0;
my $result = 0;
my @trays;
my @traysOK;
my $minTray = 10;
my $maxTray = 1000;
for ($tray=$minTray; $tray<=$maxTray; $tray++) {
    $trays[$tray] = 0;
    $traysOK[$tray] = 0;
}
$minTray = $maxTray;
$maxTray = 0;

# loop over all sorted descriptors, frequencies and mV values
for ($ch=$minChip; $ch<=$maxChip; $ch++) {
    my $nt = $nTests[$ch][1] + $nTests[$ch][2]; 
    if ($nt > 0 ) {
# which tray is this chip on?
	$tray = `grep $ch chipsQR.out | awk '{print \$1}'`;
	chomp $tray;
	$tray = $tray + 0;
	$trays[$tray]++;

	if ($minTray > $tray) { $minTray = $tray; }
	if ($maxTray < $tray) { $maxTray = $tray; }

# what was the result from the last test?
	$result = `tail -1 $filestring[$ch] | awk '{print \$NF}'`;
	chomp $result;
	$result = $result + 0;
	if ($result == 0) {
	    $traysOK[$tray]++;
	}
	print OUTP "$nt $tray $result $filestring[$ch]\n";
    }
}
close OUTP;

$outputFilename = "tray_stats.txt";
open(OUTP, ">$outputFilename");

for ($tray=$minTray; $tray<=$maxTray; $tray++) {
    if ( $trays[$tray] > 0 ) {
	print OUTP "$tray $trays[$tray] $traysOK[$tray]\n";
    }
}
close OUTP;
