#!/usr/local/gnu/bin/perl

#
# Layout of chemistry events: N x y spec reac time
#
$Efile = "Events_0.0M_3_19415.seed=142";
#
# Layout of trajectory events:
#
# N:
# x1 y1 t1
# x2 y2 t2
# ...
#
$Tfile = "Traj_0.0M_3_19415.seed=142";

EVENT;
TRAJ;

print STDERR "Using Efile = $Efile\n";
print STDERR "Using Tfile = $Tfile\n";

die "Usage: mergeET N\n" unless $#ARGV >= 0;

$part = $ARGV[0]; shift;

print STDERR "Merging stuff for particle # $part ...\n";

@E_array = ();
@T_array = ();

open TRAJ, "<$Tfile" || die "Couldn't open() $Tfile";

while (<TRAJ>)
{
    if (/^$part:$/o)
    {
        #
        # Throw out first trajectory; it's also in Event file.
        #
        <TRAJ>;

        until (($_ = <TRAJ>) =~ /^[0-9]+:$/)
        {
            push @T_array, $_;
        }

        break;
    }
}

close TRAJ;

open EVENT, "<$Efile" || die "Couldn't open() $Efile";

while (<EVENT>)
{
    if (/^$part /o)
    {
        ($a,$b,$c,$d,$e,$f) = split(' ', $_);
        #
        # Don't save the final Event; it's also in Trajectory.
        #
        push @E_array, "$b $c $f $d\n" unless ($e == -1 && $f > 0);
    }
}

close EVENT;

@merged = ();

sub bythirdcolumn
{
    ($a1,$a2,$a3) = split(' ', $a);
    ($b1,$b2,$b3) = split(' ', $b);

    $a3 <=> $b3;
}

@merged = sort bythirdcolumn @E_array, @T_array;

$lastspec = 0;

for ($i = 0; $i <= $#merged; $i++)
{
    ($a,$b,$c,$d) = split(' ', $merged[$i]);

    if ($d =~ /[0-9]+/)
    {
        $lastspec = $d;
    }
    else
    {
        $merged[$i] = "$a $b $c $lastspec\n";
    }
}

print @merged;
