#!/usr/bin/perl
use warnings;
use strict;
use autodie;
use Data::Dump qw(dump);

my $filename = 'Intervali_Openface_novi_rad_Boris_export.txt';

sub col2nr {
	my @c = @_;
	my $i = 0;
	my $out;
	$out->{$_} = $i++ foreach @c;
	warn "# col2nr ", dump( $out );
	return $out;
}

open(my $fh, '<', $filename);

my $h = <$fh>; chomp $h;
my @cols = split(/\t/, $h);
my $col2nr = col2nr @cols;

my $file2;
my $fh2;
my $last_id;

my @h2;
my $h2nr;
my $tell2;


while(<$fh>) {
	chomp;
	my @v = split(/\t/, $_);
	#warn "#[ $_ ]\n";

	if ( ! $last_id || $last_id ne $v[0] ) {
		$file2 = glob $v[0] . '*.txt';

		next unless $file2; # FIXME

		warn "# file2 $file2 [$v[0]]";
		open($fh2, '<', $file2);
		$last_id = $v[0];
	}

	sub col_v {
		my $name = shift;
		my $i = $col2nr->{$name};
		die "can't find $name" unless defined $i;
		my $v = $v[$i];
		die "can't find $i : $name in ",dump( \@v ) unless defined $v;
		return $v;
	}

	#my $start = $v[ $col2nr->{'Start (s)'} ];
	#my $stop  = $v[ $col2nr->{'Stop (s)'} ];

	my $start = col_v 'Start (s)';
	my $stop  = col_v 'Stop (s)';

	my @sum;
	my $count = 0;

	while(<$fh2>) {
		chomp;
		warn "##[ $_ ]\n";
		my @v2 = split(/\t/,$_);
		if ( ! @h2 ) {
			@h2 = @v2;
			$h2nr = col2nr @h2;
			$tell2 = tell($fh2);
			warn "# h2nr ",dump( $h2nr );
			next;
		}

		sub col_v2 {
			my $name = shift;
			my $i = $h2nr->{$name};
			die "can't find $name in ",dump( $h2nr ) unless defined $i;
			my $v = $v2[$i];
			die "can't find $i : $name in ",dump( \@v2 ) unless defined $v;
			return "### col_v2($name) = $v";
			return $v;
		}


		#my $timestamp = $v2[ $h2nr->{'timestamp'} ] || die;
		my $timestamp = col_v2 'timestamp';

		if ( $timestamp < $start ) {
			warn "# < $start @v2";
		} elsif ( $timestamp < $stop ) {
			$tell2 = tell($fh2);
			foreach my $n ( $h2nr->{'AU01_r'} .. $h2nr->{'AU45_c'} ) {
				$sum[$n] += $v[$n];
			}
			$count++;
		} else {
			warn "# seek $tell2";
			seek $fh2, $tell2, 0;

			print join("\t", @v,
				map { $sum[$_] / $count } ( $h2nr->{'AU01_r'} .. $h2nr->{'AU45_r'} ),
				map { $sum[$_] }          ( $h2nr->{'AU01_c'} .. $h2nr->{'AU45_c'} ),
			);
		}
	}
}

__END__


my $col2nr;

# prema filenamenu iz $v[0]
# Start (s)       Stop (s)

my $lookup_file = '

# col timestamp
# 
