#!/usr/bin/perl

use lib "$ENV{'LIA_UTIL_PACK'}/script/perlmod";

use Utils;

use strict;
use warnings;
use File::Basename;

#-------------------------------------------
# MAIN
#-------------------------------------------

# options variables
my $help = 0;
my $inDir = ".";
my $outDir = ".";
my $inExt = "wlat";
my $outWlat = "mwlat";
my $outWlatInf = "mwlatinf";
my $timeSill = 3*100;

# usefull variables
my @filesList;
my %mergedHash;

# Parse options and print usage if there is a syntax
# error, or if usage was explicitly requested
GetOptions('help|?' => \$help, 
	   'inDir=s' => \$inDir,
	   'inExt=s' => \$inExt,
	   'timeSill=s' => \$timeSill,
	   'outDir=s' => \$outDir,
	   'outWlatExt=s' => \$outWlat,
	   'outWlatInfoExt=s' => \$outWlatInf);

# Options test
pod2usage(1) if($help);

Utils::fill_array_from_dir($inDir, $inExt, \@filesList);

#
# on trie les wlat par le temps (suite temporelle)
#
@filesList = sort wlat_sort @filesList;

my $previousEnd;
my $currentMergedWlat;
my @currentWlatTimeTab;
foreach my $wlatFile (@filesList){
	#
	# recuperer a partir du nom du fichier wlat les information temporelle de debut et fin
	#
	@currentWlatTimeTab = obtainWlatTimeInfo($wlatFile);
	#
	# on recuperer le nombre de noeud du reseau de confusion (ligne 2)
	#
	my $nbNodes;
	my $file;
	open($file, $wlatFile) or die("Cannot open file : $wlatFile");
	my $cpt = 1;
	while(<$file>){
		if($cpt == 2){
			my @splittedLine = split(/ /, $_);
			$nbNodes = $splittedLine[1];	
		}
		if($cpt == 3){
			last;
		}
		$cpt++;
	}
	die("Error : no nodes number\n") if(!$nbNodes);
	#
	# si on est au debut ou si le temps separant deux wlat successifs excede le seuil de temps fixe
	#  => creation d'une nouvelle entree
	#
	if(!$previousEnd || $currentWlatTimeTab[0] - $previousEnd > $timeSill){
		$currentMergedWlat = $wlatFile;
		#
		# si on est dans le second cas on creer les fichiers utiles
		#
		if($previousEnd){
			saveMerge($currentWlatTimeTab, $previousEnd, $mergedHash{$currentMergedWlat})		
		}
		#
		# recupere le nom du fichier sans extension ni chemin => sert de cles
		#
		my $wlatFileBasename = basename($wlatFile, ".".$inExt);
		$currentMergedWlat = $wlatFileBasename;
		if(exists $mergedHash{$currentMergedWlat}){
			die("error : $currentMergedWlat appear 2 times");
		} else{
			#
			# creation de la structure adequate : 
			# tab :
			# - 0 : nb de noeuds dans le reseau
			# - 1 : contenu du reseau
			# - 2 : information pour identifier les composantes du reseau de conf merge
			#
			my @contentTab = ();
			my $lastNode = $nbNodes - 1;
			my @infoTab = ("$wlatFile 0 $lastNode\n");
			my @tab = ($nbNodes, \@contentTab, \@infoTab);
			$mergedHash{$currentMergedWlat} = \@tab;	
		}
	} else{
		my $newInitNode = ${$mergedHash{$currentMergedWlat}}[0];
		my $newLastNode = $newInitNode + $nbNodes - 1;
		#
		# ajout du nombre de nodes qui vont etre rajoutes
		# et du champ de couverture (en terme de noeud)
		#
		${$mergedHash{$currentMergedWlat}}[0] += $nbNodes;
		push(@{${$mergedHash{$currentMergedWlat}}[2]}, "$wlatFile $newInitNode $newLastNode\n");
	} 
	while(<$file>){
		#
		# on recupere la ligne sauf les deux premiers champs (<=> `align <nb_node>`)
		#
		$_ =~ /(.+) (.+) (.+)$/;
		push(@{${$mergedHash{$currentMergedWlat}}[1]}, $3);
	}
	close($file);
}
#
# pour le dernier fichier - creation des derniers fichiers
#
saveMerge($currentMergedWlat, $currentWlatTimeTab[1], $mergedHash{$currentMergedWlat})		

#-------------------------------------------
# SUB-ROUTINES
#-------------------------------------------

#
# \brief recuperation des informations temporelles contenues dans le nom du fichier (temps de debut + temps de fin)
# tab :
# -0 : temps de debut
# -1 ; temps de fin
#
sub obtainWlatTimeInfo{
	my ($fileName) = @_;
	my @splitedFileName= split(/#/, $fileName);
	my @splitedTimeInfo= split(/:/, $splitedFileName[1]);

	return ($splitedTimeInfo[0], $splittedTimeInfo[0]+$splitedTimeInfo[1]);	
}

#
# \brief creation des fichiers mwlat et mwlatinfo
#
sub saveMerge{
	my ($fileName, $newEnd, $specialTab) = @_;
	#
	# creation du nom du fichier de sortie 
	# show#<beginTime>:<newDuration (= newEndTime - beginTimei)>
	# 
	my @splittedFileName = split(/:/, $fileName);
	my @initialInfo = obtainWlatTimeInfo($fileName);
	my $newDuration = $newEnd - $initialInfo[0]; 
	my $newFileBasename = "$splittedFileName[0]:$newDuration";
	#
	# creation du ficher wlat
	#
	my $mwlatFile;
	open($mwlatFile, ">$outDir/$newFileBasename.$outWlatExt");
	print $mwlatFile "name $fileName\n";
	print $mwlatFile "numaligns ${$specialTab}[0]\n";
	print $mwlatFile "posteriors 1\n";
	my $node = 0;
	foreach my $mwlatContent (@{${$specialTab}[1]}) {
		print $mwlatFile "align $node $mwlatContent";
		$node++;
	}
	close($mwlatFile);
	#
	# creation du fichier wlatinfo
	#
	my $mwlatInfoFile,
	open($mwlatInfoFile, ">$outDir/$newFileBasename.$outWlatInfoExt");
	foreach my $mwlatInfoContent (@{${$specialTab}[2]}){
		print $mwlatInfoFile $mwlatInfoContent;
	}
	close($mwlatInfoFile);
}

#
# \brief tri des ficher wlat en fonction du temps
#
sub wlat_sort
{
	my @afmt = split(/#/, $a);
	my @bfmt = split(/#/, $b);
	my @subafmt = split(/:/, $afmt[1]);
	my @subbfmt = split(/:/, $bfmt[1]);
	$subafmt[0] <=> $subbfmt[0];
}
=head1 NAME

mergeWlat.pl - merge cowalt

=head1 SYNOPSIS

mergeWlat.pl [options] 

Options:
	-help|?		brief help message

	-inDir		input dir containing wlat files (default .)

	-inExt		wlat file extension (default wlat)

	-sill		time sill used to merge wlat file

	-outDir		output dir will contain merged wlat files (default .)

	-outWlatExt	output merged wlat file extension (default mwlat)
	
	-outWlatInfoExt	output merged wlat information file extension (default mwlatinf)
