#!/usr/bin/perl
#use warnings;
#use strict;
use Time::Stopwatch; 

#printing usage if no argument set
if (!$ARGV[0] or !$ARGV[1]){
  $0 =~ s/.*\\(.*)/$1/; #name of this script without path
  print "\nUSAGE:\nperl $0 <dir with tagged files> patrons.txt\n";
  exit;
}

tie my $timer, 'Time::Stopwatch'; #start counting time

#openning the dir. with extracted titles and description
my $dir = $ARGV[0];

#creating saving directory
use File::Path;
my $path = './'.$dir.'/found';
rmtree($path);
mkdir($path);

opendir(DIR, $dir) or die "I cannot open dir: $dir";

print "\n";

while (my $file = readdir(DIR)) { #open directory
   next unless ($file =~ m/_t.txt$/); #open each file.txt
   
    my @token; 
    my @lemma;
    my @pos;
    
    #opening a sourcefile
    open(TEXTE,"<:utf8", $dir."/".$file) or die $!;
    
    while (my $ligne = <TEXTE>){
    
      #if no punctuation
      if ($ligne !~/SENT/) { #Cordial equvivalent PCTFORTE
       
        #on traite la ligne et on remplit les 3 listes : TOKEN, LEMME, POS
        #on transforme la chaine $ligne en une liste (le premier élément est une forme, le seconde un lemme etc.)
        #$ligne contient qq chose comme : "Faiseurs\tfaisieur\NOM"
        
        chomp($ligne);
        my @range = split(/\t/,$ligne); # @range has three words
        
        push(@token,$range[0]);
        push(@pos,$range[1]);
        push(@lemma,$range[2]); #for cordial lemma and pos inversed
                  
      }
      
      else {
        
        &listedepos($path."/".$file,\@pos,\@token);
        #&listedepos($file);
         
        @token=();
        @lemma=();
        @pos=();
      }
    }
  close(TEXTE);
  
  print "$file \t done\n";
  
}
close(DIR);

print "\n\n === DONE in $timer s ===\n"; #printing time

sub listedepos {

  my $pos = $_[1];#reference pos
  my $token = $_[2]; #reference token
                                                            
  my $chain = join("#",@$pos); #pos joined together
   #print "pos chain: $chain \n";
  my $save = substr($_[0],0,-6)."_p.txt";
    
  open(PATRONE,"<:utf8", $ARGV[1]);
  open(SAVE,">>:utf8",$save);
   
  #lecture du patrone
  while(my $terme=<PATRONE>){
    #$terme contientparexmple: NC[A-Z]+#PREP#NC[A-Z]+

    my $n = 0;
    chomp($terme);
    
    while($chain =~/$terme/g){
  
      my $avant=$`;
      my $apres=$';
      my $nd = 0; #nombre de diese
      my $ndt = 0; #nombre de diese terme traite
      
      while($avant=~/\#/g){
        $nd++;        
      }
      
      while($terme=~/\#/g){
        $ndt++;
      }
      
      for (my $i = $nd; $i<=$ndt+$nd; $i++){
        print SAVE $$token[$i]," ";
      }
           
      print SAVE "\n";  
      
    }  
          
  }
  
  close(PATRONE);
  close(SAVE);
}
