#!/usr/bin/perl

use utf8;
binmode STDOUT, "utf8";

#-------------------------------------------------------------------------------------

<<DOC;
Gabriele CHIGNOLI
MARS 2017
 usage : perl extra-term.pl file-pour-extraction motf-a-extraire
 >_ file étiqueté sur Cordial + patrons morphosyntaxiques à rechercher
 -> liste des tokens correspondants une liste en ISO et une en UTF
DOC

#-------------------------------------------------------------------------------------
open FIC,"<:encoding(iso-8859-1)",$ARGV[0];
open MOTIF,"<:encoding(iso-8859-1)",$ARGV[1];
open my $resultats,">:encoding(iso-8859-1)","extraction.txt";
my @MOTIFS=<MOTIF>;
close(MOTIF);
my @TOKENS=();
my @POS=();

while(my $ligne = <FIC>) {
	next if ($ligne!~/^[^\t]+\t[^\t]+\t[^\t]+/);
	$ligne=~s/\\r+?//g;
	if ($ligne !~/^[^\t]+\t[^\t]+\tPCTFORTE/) {
		chomp($ligne);
		my @LISTE=split(/\t/,$ligne);

		push(@TOKENS,$LISTE[0]);
		push(@POS,$LISTE[2]);
	}
	else {
		&extract;

		@TOKENS=();
		@POS=();
	}
}
close FIC;
close $resultats;
system("iconv -f ISO-8859-1 -t UTF-8 extraction.txt > extraction_utf8.txt");

#--------------------------------------------------
sub extract {
	foreach my $motif (@MOTIFS) {
		my $pos_as_string=join(" ",@POS);
		chomp($motif);
		my $blancAvant=0;
		while ($pos_as_string=~/($motif)/g) {
			my $avant=$`;
			while ($avant=~/ /g) {
				$blancAvant++;
			}
			my $blancMotif=0;
			while ($motif=~/ /g) {
				$blancMotif++;
			}
			my $total=$blancAvant+$blancMotif;
			my $tokens="@TOKENS[$blancAvant..$total]\n";
			print $resultats $tokens;
    		}
	}
}


#####
####
###
##
#
#
