#!/usr/bin/perl

#package:	UAM Text Tools
#component:	gph
#version:	1.0
#author:	Tomasz Obrebski

use strict;
use Getopt::Long;

my @process;
my $help=0;
my $reset;
my $interactive=1;

GetOptions("process|p=s" => \@process,
	   "help|h" => \$help,
	   "reset|r=s" => \$reset,
	   "interactive|i" => \$interactive);

if($help)
{
    print <<'END'
Usage: gph [OPTIONS]

Options:
   -p tag		Process segments with this tag as nodes.
   -r tag		Start new graph at this tag.
   -f filename		Input file (NIE DZIALA).
   -o filename		Output file (NIE DZIALA).
   -i			Toggle interactive mode (default=on).
END
;
    exit 0;
}


$|=1 if $interactive;

my @prev;

my $n=0;

while(<>)
{
    chomp;
    my $do=0;

    my @line = split /\s+/;

    if($line[2] eq $reset)
    {
	$n=0;
	@prev = ();
    }

    for my $p (@process)
    {
	$do=1 if $line[2] eq $p;
    }

    if($do)
    {
	@preds = ();
	shift @prev while @prev+0 && $prev[0]->[1] + $prev[0]->[2] < $line[0];
	for my $p (@prev)
	{
	    push(@preds, $p->[0]) if $p->[1] + $p->[2] == $line[0];
	}
	push @prev, [$n, $line[0], $line[1]];
	
	$gph=' gph:'.$n.':'.join(',',@preds);

	$n++;
    }
    else
    {
	for my $p (@prev)
	{
	    if($p->[1]+$p->[2] == $line[0])
	    {
		$p->[2] += $line[1];
	    }
	}

	$gph='';

    }

    print $_.$gph."\n";    
}
