#! /usr/bin/perl
#Created by Vinicius Mota www.dcc.ufmg.br/~vfsmota
package bin;
use strict;
use warnings;

use Getopt::Long;

my $inFileName;

my $usage = '
usage: -input <inputFileName>
';

GetOptions("input=s" => \$inFileName);

if (not @ARGV) {
    print "Missing required parameter(s)\n";
    print $usage;
    exit();
}

my $infileHeader = "$ARGV[0].ns_params";
my $inFile  = "$ARGV[0].ns_movements";

my $outfile = "$inFile.one";
my $tempfile = "nsorder";
print "$infileHeader";

open (FILEHEADER, $infileHeader) or die "Can't open $infileHeader: $!";
my @header = <FILEHEADER>;
#First line of the file should be the offset header. Syntax of the header should be:
#minTime maxTime minX maxX minY maxY minZ maxZ 
#print @header;
my $minTime = 0;
my $minX = 0;
my $minY = 0;

for(my $i=0; $i < 4; $i++) {

	$header[$i] =~s/[a-zA-Z()\n\t]//g;

}
	open (OUTFILE, ">$outfile") or die "Can't open $outfile for output: $!";
	print OUTFILE "$minTime\t$header[3]\t $minX\t $header[0]\t $minY\t$header[1]\n";

open (INFILE, $inFile) or die "can't open $inFile: $!";
open (TEMPFILE, ">$tempfile") or die "Can't open $tempfile for output: $!";
#time id xPos yPos
while (<INFILE>) {
    my ($time, $id, $x, $y) = parseLine($_);
    unless ($time eq 1){
     if (not defined $y && $time ne "-1"){
     print TEMPFILE "$time\t$id\t$x\t";	
     next;
     } 
     if (not defined $x){
	print TEMPFILE "$y  \n";
     }
     if (defined $time && defined  $id && defined $x && defined $y) {
	print  TEMPFILE "$time\t$id\t$x\t$y  \n";
     } 
     }
   #next unless defined $y;
   # if ($time > $limits[0]) { # min time location are already there
	#print OUTFILE "$time $id $x $y \n";
	#print  "$time, $id, $x, $y  \n";
   # }
}


close(TEMPFILE);

system "sort -n $tempfile > sorted";
my $sortfile = "sorted";

open (SORTFILE, $sortfile) or die "Can't open $sortfile for output: $!";

while (<SORTFILE> ) {

my $line = getLine($_);
print OUTFILE $line;    

}

system "rm -rf $tempfile";
system "rm -rf $sortfile";


sub getLine {
my $line = shift;

return $line
}

sub parseLine {
    my $line = shift;
      my $x;
    my $y;
    my $time = -1;
    my $id;
   
     my @data = split(/\s+/, $line);
    #except the comment lines
    unless ($line =~ /\#/){
 

     
   
      #look for inicialization of nodes 
      unless ($line =~ /setdest/){
	 $data[0] =~ s/[a-z_\(\)\$]//g;
	 $id = $data[0];
      	if ($line =~ /X/){
	 $x = $data[3]
	}
        else{	 	
	 $y = $data[3];
	}
	 $time = 0;	 
	}
	if ($line =~ /setdest/){
	  $time = $data[2];
	  $data[3] =~ s/[a-z_\(\)\$\"]//g;
	  $id = $data[3];
	  $x =$data[5];
	  $y = $data[6];
	  
	} 
  	
    }
        #put the comment lines
	else {
	if ($line =~ /setdest/){
	  $time = $data[3];
	  $data[4] =~ s/[a-z_\(\)\$\"]//g;
	  $id = $data[4];
	  $x =$data[6];
	  $y = $data[7];
	  
	} 
	  
	} #fim do else
      return ($time,$id,$x,$y);
}
  
  	
    #print @data;
    





 



