#!/usr/bin/perl

use strict;

#type: propagationdelay.pl <trace file> <source node> <destination node> <flow id> > file

my $infile	= $ARGV[0];
my $fromnode	= $ARGV[1];
my $tonode	= $ARGV[2];
my $flow	= $ARGV[3];


# Fields in the trace file
my $event;
my $time;
my $from;
my $to;
my $pkttype;
my $pktsize;
my $flags;
my $fid;
my $source;
my $destination;
my $sequenceNum;
my $uniqueId;

# Temp variables
my $line;
my $travelTime;

# Contains all packets start and ending time, form:
# $packets[<sequenceNumber>][0] = <sendtime>
# $packets[<sequenceNumber>][1] = <arrivaltime>
my @packets;

# Opening file
open(DATA, "<$infile") || die "Can't open $infile";

# Looping through file
while ($line = <DATA>) {
	# Splitting line into fields
	($event, $time, $from, $to, $pkttype, $pktsize, $flags, $fid, $source, $destination, $sequenceNum, $uniqueId) = split(' ', $line);
	
	# Checking if the event is a send event (+) AND
	# if the originating node is the specified source node AND
	# if the source node is the specified source node AND
	# if the destination node is the specified destination node AND
	# if the flow id is the specified flow id
	if ( $event eq '+' && int $from eq int $fromnode
	    && int $source eq int $fromnode && int $destination eq int $tonode 
	    && int $fid eq int $flow ) {
	    	# If so, save the time variable as the sending time.
		$packets[$sequenceNum][0] = $time;
	}

	# Checking if the event is a recieve event (r) AND
	# if the arriving node is the specified destination node AND
	# if the source node is the specified source node AND
	# if the destination node is the specified destination node AND
	# if the flow id is the specified flow id
	if ( ($event eq 'r') && (int $to eq int $tonode) 
	    && (int $source eq int $fromnode) && (int $destination eq int $tonode) 
	    && (int $fid eq int $flow) ) {
	    	# If so, save the time variable as the arrival time.
		$packets[$sequenceNum][1] = $time;

		# If so, calculate the propagation delay and send it to STDOUT
		# If a packet arrived, it must have been send...
		$travelTime = $packets[$sequenceNum][1]-$packets[$sequenceNum][0];
		print STDOUT "$sequenceNum $travelTime\n";
	}
	
}

close DATA;
