#!/usr/bin/perl

use encoding "utf8";
use strict;

foreach my $file (@ARGV) {
    printf "%5.2f  %s\n", &average($file), $file;
}

sub average {
    my $file = shift @_;
    local *FH;

    my $total_len = 0;
    my $total_sub = 0;
    my $coll_str = undef;
    my $state = 0;
    my $len;

    if(!open(FH, "< $file")) {
        warn "Could not open $file: $!\n";
        return undef;
    }

    while(defined(my $line = <FH>)) {
        $line =~ s/[\x0a\x0d]+//gso;

        if($state == 0) {
            # Current line is ID
            $state = 1;
            next;
        }
        if($state == 1) {
            # Current line is time
            $state = 2;
            next;
        }

        my $len = length $line;

        if($len == 0) {
            # Current line is empty (NEW SUB)
            my $coll_len = length $coll_str;

            # printf "%3d  %s\n", $coll_len, $coll_str;
            ++$total_sub;
            $total_len += $coll_len;
            $coll_str   = undef;
            $state      = 0;
            next;
        }

        if(length($coll_str) == 0) {
            # First line of a sub
            $coll_str = $line;
        } else {
            # Further lines
            $coll_str .= " ".$line;
        }
    }

    close FH;
    # printf "%3d  AVERAGE OVER %d SUBS\n", $total_len / $total_sub, $total_sub;
    return $total_len / $total_sub;
}
