#!/usr/bin/perl
#la methode de JMD

open(TERMINO,"$ARGV[0]");
while(my $terme=<TERMINO>){
	chomp $terme;
	$terme=~s/ +/ /g;
	$terme=~s/\r$//g ;
	open(CORDIAL,"$ARGV[1]");
	#on affiche les resultats dans des fichiers distincts : le nom du fichier est compose du nom du fichier Cordial sur lequel on travail et de la ligne du patron traite
	$out="$ARGV[1]-extrait-$terme.txt" ; 
	open (OUT, ">$out");
	my @POS=() ; 
	my @TOKEN=() ;  
	
	while(my $ligne=<CORDIAL>){
		chomp $ligne;
		$ligne=~s/\r//g;
		if ($ligne!~/PCT/){
			my @LISTE=split(/\t/,$ligne);
			#print "PATRON LU <$terme> : Ligne lue <@LISTE>\n";
			push(@POS,$LISTE[2]);
			push(@TOKEN,$LISTE[0]);
		}
		else {
			#print "<@TOKEN>/n";
			#print "<@POS>/n";
			#print "TERME CHERCHE : $terme \n";
			my $pos=join(" ",@POS);
			my $token=join(" ",@TOKEN);
			while($pos=~/$terme/g){
				my $comptagedeblancdansterme=0;
				while ($terme=~/\s/g){
					$comptagedeblancdansterme++ ;  
				}
				my $avantlacorrespondance=$`;
				my $comptagedeblanc=0;
				while($avantlacorrespondance=~/ /g){
					$comptagedeblanc++;
				}
				for (my $i=$comptagedeblanc;$i<=$comptagedeblanc+$comptagedeblancdansterme;$i++){
					print OUT $TOKEN[$i]." ";
				}
				print OUT "\n";
			}
			@POS=();
			@TOKEN=();
		}
	}
	close(CORDIAL);
}
close(TERMINO);