#!/usr/bin/perl
use utf8;
use Time::HiRes qw(gettimeofday tv_interval);
my $timepg = [gettimeofday];
my $filetalismane=$ARGV[0];
my $filetermino=$ARGV[1];
open my $fileT,"<:encoding(UTF-8)",$filetalismane;
open my $fileTer,"<:encoding(UTF-8)",$filetermino;
my @TERMINO=<$fileTer>,
close $fileTer;
my %dicotmp=();
my %dicoPatron=();
my $nbTerme=0;
my $nbMotInPhrase=0;
while (my $ligne=<$fileT>) {
	#c'est ici qu'on a modifié le code
	next if (($ligne=~/^1\t££/) or ($ligne=~/^\#\#/) or ($ligne=~/^$/));
	print "==>$ligne;<==";
	if ($ligne ne "\n") {
	print $ligne;
		$ligne=~/^\d+\t(.+)\n/;
		
		my $rep=<STDIN>;
		my $cle=$1;
		my $reste=$1;
		$nbMotInPhrase++;
		my $cle=$nbMotInPhrase;
		print $cle;
		my @listereste=split(/\t/,$reste);
		$dicotmp{$cle}=\@listereste;
	}
	else {
		#------------------------
		# extraction termino....
		my $phrase=" ";
		my $longueur = scalar (keys %dicotmp);
		for (my $i=1;$i<=$longueur;$i++) {
			my $LISTE=$dicotmp{$i};
			my @listedeferencee = @$LISTE;
			my $mot=$listedeferencee[0];
			my $pos=$listedeferencee[2];
			$phrase=$phrase.$mot."/".$pos." ";
				print "$phrase\n";
		}
		foreach my $patron (@TERMINO) {
			print "$phrase\n$patron\n";
			my $patron2=$patron;
			chomp($patron2);
			$patron2=~s/([^ ]+)/\[\^ \]\+\/\\b$1/g;
			print $patron2,"\n";
			print $phrase,"\n";
			my $rep=<STDIN>;
			while ($phrase=~/(?=\s($patron2))/g) { 
				my $terme=$1;
				print $terme,"\n";
				$terme=~s/\/[^ ]+//g;
				print "$terme\n";
				my $rep=<STDIN>;
				$dicoPatron{$patron}->{$terme}++;
				$nbTerme++;
			}
		}
		%dicotmp=();
		$nbMotInPhrase=0;
	}
}
close($fileT);

open my $fileResu,">:encoding(UTF-8)","perlIsTheBigOneOne.txt";
print $fileResu "$nbTerme éléments trouvés\n";
foreach my $patron (keys %dicoPatron) {
	print $fileResu "\nType de pattern: ".$patron." \n\n";
	foreach my $terme (sort {$dicoPatron{$patron}->{$b} <=> $dicoPatron{$patron}->{$a} } keys %{$dicoPatron{$patron}}) {
		print $fileResu $dicoPatron{$patron}->{$terme}."\t".$terme."\n";
	}
}
print $fileResu "\nScript execution time: " . tv_interval($timepg) . " seconds.";
close($fileResu);
