#!/usr/bin/perl -w

use FileHandle;

sub slurp_file {
    my $fname = shift;
    my $data = shift;
    my $cp = shift;

    my $fh = new FileHandle $fname,"r";
    die unless defined($fh);

    die unless defined($data);
    die unless defined($cp);

    my @pe;
    my @pa;
    my @pb;
    my @pc;
    while (<$fh>) {
	chomp;
	my ($e,$a,$b,$c) = split;
	push @pe,$e;
	push @pa,$a;
	push @pb,$b;
	push @pc,$c;

	$data->{$e}{$cp} = $a;
    }
    return (\@pe, \@pa, \@pb, \@pc);
}

sub process_file {
    my $fname = shift;
    my $data = shift;

    die "Can't parse $fname" unless
	$fname =~ /.*_numu_(\d+)_(\d+).*\.vec/;

    my $bl=$1;
    my $cp=$2;

    print STDERR "cp=$cp\n";

    my ($e, $a, $b, $c) = slurp_file ($fname,$data,$cp);
}

my $outdir = shift @ARGV;

die "outdir: $outdir is not a dir" if -f $outdir;
mkdir $outdir unless -d $outdir;

print "output going to $outdir\n";

my %data;
foreach $file (@ARGV) {
    print STDERR "$file\n";
    process_file ($file,\%data)
}
foreach $energy (keys %data) {
    my $fh = new FileHandle "$outdir/cpnue-${energy}.vec","w";
    die unless defined ($fh);
    foreach $cp (keys %{$data{$energy}}) {
	print $fh "$cp $energy $data{$energy}{$cp}\n";
    }
    undef $fh;
}


