#/usr/local/bin
#----------------------------------------------------------
use Tk;
use Tk::ToolBar;
use locale;
use LWP::Simple;
use Encode;
use HTML::Entities;
use Tk::NoteBook;
use Tk::SMListbox;
use Win32::Process;
use Tk::Balloon;
use Tk::Worldcanvas;


#----------------------------------------------------------
# definition interface
#----------------------------------------------------------
# creation de la fenetre principale
$mw= MainWindow->new;
$mw->title("Extracteur");

#---------------------------------------------------------
my $cadreMenu = $mw->Frame->pack(-side => 'top',
			  -fill => 'both',-anchor =>'w');
my $b_menu1=$cadreMenu->Menubutton(-text => "Fichier",
				  -tearoff => 0,
				  -relief => 'ridge',
				  -foreground=>'brown',
				  -menuitems => [
						 ['command' => 'Ouvrir un fichier ".txt"',
						  -command => \&lire_File],
						 ['command' => "Ouvrir une URL",
						  -command => \&lire_url],
						 ['command' => "Enregistrer l'éditeur",
						  -command => \&sauve_editor],
						 ['command' => "Sortie",
						  -command =>  sub {quitter()}]])->pack(-side => 'left');
						  

						  
my $b_menu3=$cadreMenu->Menubutton(-text => "Syntaxe",
				  -tearoff => 0,
				  -relief => 'ridge',
				  -foreground=>'brown',
				  -menuitems => [
						 ['command' => "Lancer Treetagger",
						  -command => \&loadtreetagger],
						 ['command' => "Lancer l'extraction de patrons NOM-ADJ",
						  -command => \&loadextractpattern],
						 ])->pack(-side => 'left');




my $cadre = $mw->Frame->pack(-side => 'top',-expand=>1,
			  -fill => 'both');
my $onglet=$cadre->NoteBook(-backpagecolor=> 'white',
				-background=>'white',
				-disabledforeground=>'brown',
				-foreground=>'brown', 
				-inactivebackground  => '#BFBFBF', #color for inactive tabs
				)->pack(-side=>'top',
					-expand=>1,
					-fill=>'both');

my $page1=$onglet->add("page1",-anchor=>'w',label=>'Editeur',-underline=>0);
my $page2=$onglet->add("page2",-anchor=>'w',label=>'Dictionnaire',-underline=>0);
my $page3=$onglet->add("page3",-anchor=>'w',label=>'Concordance Version1',-underline=>0);
 my $page3b=$onglet->add("page3b",-anchor=>'w',label=>'Concordance Version2',-underline=>0);
my $page4=$onglet->add("page4",-anchor=>'w',label=>'Treetagger',-underline=>0);
my $page5=$onglet->add("page5",-anchor=>'w',label=>'Extraction de patrons',-underline=>0);
my $page6=$onglet->add("page6",-anchor=>'w',label=>'Rapport sur le texte',-underline=>0);
$msgarea = $mw->Label(-textvariable => \$info,-borderwidth => 2, -relief => 'groove')
  ->pack(-side => 'top',-anchor => 'w', -fill => 'x');
 $balloon = $mw->Balloon(-statusbar => $msgarea);
 
 
# interface de la page 1 : edition d' URL...
#------------------------------------------------------------
$group1 = 1; # set default value
foreach (qw/URL Fichier.txt/) {
	my $rdbtt=$page1->Radiobutton(-text =>  $_, -variable => \$group1, 
		-value => $_,-foreground=>'brown')->pack(-anchor => 'w',-side => 'top', -fill => 'both',-expand=>'0');
}



my $cadreP1=$page1->Frame(-borderwidth => '2', -relief => 'groove')->pack(-side => 'top', -fill => 'both',-expand=>'0');
$cadreP1->configure(-background => 'white');
my $cadreP2b=$page1->Frame(-borderwidth => '2', -relief => 'groove')->pack(-side => 'top', -fill => 'both',-expand=>'0');
$cadreP2b->configure(-background => 'white');

my $cadreP2=$page1->Frame(-borderwidth => '2', -relief => 'groove')->pack(-side => 'top', -fill => 'both',-expand=>'1');
$cadreP2->configure(-background => 'white' );



my $URL=$cadreP1->Label(-text => "Chemin: ",
    	      -relief => 'raised',-foreground=>'brown')->pack(-side => 'left',
						  -anchor => 'n',
						  -fill => 'y'
						 );



$balloon->attach($URL, -balloonmsg => "chemin du ficher à analyser ",  
  -statusmsg => "saisir le chemin du fichier à analyser ");
$balloon->attach($msgarea, -msg => 'Affiche des précisions concernant les fonctions du logiciel ');
$cadreP1->Entry(-textvariable => \$url)->pack(-side => 'left',
						-anchor => 'n',
						-fill => 'both',
						-expand => 1);
my $go_button = $cadreP1->Button(-text => 'commencer',-background=>'#BFBFBF',-foreground=>'brown',-relief => 'raised',-command =>sub{dialogbox();})->pack(-side => 'left',
						  -anchor => 'e'
						 );	
$balloon->attach($go_button, -balloonmsg => "Commencer à analyser ",  
  -statusmsg => "Commence l'analyse du texte");	


#--------------------------- editeur fenetre principale ------------------------------------------------------------------------------

$editortexte = $cadreP2->Scrolled("Text")->pack(-side => 'bottom',
				      -fill => 'both',
					  
				      -expand => 1);
$editortexte->Text(-setgrid => 'true');
$search_string = '';
$w_string = $cadreP2b->Frame()->pack(-side => 'top', -fill => 'x');
$w_string_label = $w_string->Label(-text => 'Rechercher chaine de caractères:', -width => 30, -anchor => 'w',-foreground=>'brown');
$w_string_entry = $w_string->Entry(-textvariable => \$search_string);
$w_string_button = $w_string->Button(-text => 'Surligner',-foreground=>'brown',-background=>'#BFBFBF');
$balloon->attach($w_string_button, -balloonmsg => "Surliger une chaine de caractères ",  
  -statusmsg => "Met en relief la chaîne de caractères recherchée");

$w_string_label->pack(-side => 'left');
$w_string_entry->pack(-side => 'left');
$w_string_button->pack(-side => 'left', -pady => 5, -padx => 10);
$w_string->pack(-side => 'top', -fill => 'x');
$w_string_button->configure(-command => [sub {&text_search($editortexte, $search_string, 'search')}, $editortexte]);
$w_string_entry->bind('<Return>' => [sub {shift; &text_search($editortexte, $search_string, 'search')}, $editortexte]);
$w_string->pack(-side => 'top', -fill => 'x');
if ($mw->depth > 1) {
	text_toggle($editortexte, ['configure', 'search', -background => 'brown', -foreground => 'white'], 800,
		          ['configure', 'search', -background => undef,       -foreground => undef],   200);
     } else {
	text_toggle($editortexte, ['configure', 'search', -background => 'brown',     -foreground => 'white'], 800,
		          ['configure', 'search', -background => undef,       -foreground => undef],   200);
      }

my $cadreP3=$mw->Frame(-borderwidth => '2', -relief => 'groove')->pack(-side => 'top', -fill => 'both',-expand=>'0');
$cadreP3->configure(-background => 'brown');


# Page 2
#------------------ editeur dico ----------------------------------------------------------------------------

my $cadreDico=$page2->Frame(-borderwidth => '0', -relief => 'groove')->pack(-side => 'top', -fill => 'both',-expand=>1);
$cadreDico->configure(-background => 'white');

my $dicoG=$cadreDico->Frame(-borderwidth => '0', -relief => 'groove')->pack(-side => 'top', -fill => 'both',-expand=>0);
$dicoG->configure(-background => 'white');
my $dicoD=$cadreDico->Frame(-borderwidth => '0', -relief => 'groove')->pack(-side => 'left', -fill => 'both',-expand=>1);
$dicoD->configure(-background => 'white');
my $conc=$dicoG->Button(-text => "Lancer la Concordance",-background=>'#BFBFBF', -foreground=>'brown',-command => sub {&concor})->pack( -side => 'top',-padx => 5,-pady=>5);
 $balloon->attach($conc, -balloonmsg => "Lance la concordance ",  
   -statusmsg => "permet de demarrer une concordance");

   
   
   $group = 1; 
foreach (qw/Concordance-Version1 Concordance-Version2/) {
	$dicoG->Radiobutton(-text =>  $_, -variable => \$group, 
		-value => $_)->pack(-anchor => 'w',-side => 'top', -fill => 'both',-expand=>'0');
}
		
$dicodesformes = $dicoD->Scrolled("SMListbox",
				      -background => 'white',
				      -foreground => 'brown',
				      -textwidth => 2,
				      -highlightthickness => 2,
				      -width => 0,
				      -scrollbars => 'osoe',
				      -selectmode => 'extended',
				      -separatorcolor=>'black',
				      -separatorwidth=>2,
				      -resizeable => 1,
				      -scrollbars=>'se',
				      -columns=>[
						 [-text=> 'Forme',     
						  -textwidth => 90, 
						  -fg => 'black', 
						  -bg => '#DDDDDD',
						  -comparecmd => sub {$_[0] cmp $_[1]}
						  ],
						 [-text => 'Fréquences',
						  -textwidth => 60,
						  -fg => 'black', 
						  -bg => '#DDDDDD',
						  -comparecmd => sub {$_[0] <=> $_[1]}
						  ]
						 ]
				      )->pack(-side => 'top',
					      -expand => 'yes',
					      -fill =>'both',
					      -padx => 0,
					      -pady => 0
					      );
$dicodesformes->columnGet(0)->Subwidget("heading")->configure(-background=>'#E5E5FF',-foreground=>'red',-activebackground=>'#C0C0C0');
$dicodesformes->columnGet(1)->Subwidget("heading")->configure(-background=>'#E5E5FF',-foreground=>'red',-activebackground=>'#C0C0C0');
$dicodesformes->Subwidget("xscrollbar")->configure(-elementborderwidth=>1, -borderwidth=>1,-relief=>'solid');
$dicodesformes->Subwidget("yscrollbar")->configure(-elementborderwidth=>1, -borderwidth=>1,-relief=>'solid');


$balloon->attach($dicodesformes->columnGet(0)->Subwidget("heading"), -balloonmsg => "Trie les formes", -balloonposition => 'mouse',
 
   -statusmsg => "Trie les formes par ordre alphabétique ou par orde d'apparition");
   
   $balloon->attach($dicodesformes->columnGet(1)->Subwidget("heading"), -balloonmsg => "Trie les fréqences", -balloonposition => 'mouse',
 
   -statusmsg => "Trie les fréqences dans l'ordre croissant ou décroissant");

# Page 3a
#------------------ editeur concordance 1 --------------------------------------------------------------------
$editorconcordance = $page3->Scrolled("Text")->pack(-side => 'bottom',
				      -fill => 'both',
					  -anchor => 'e',
				      -expand => 1);
$editorconcordance->Text(-setgrid => 'true');



# Page 3b
#------------------ editeur concordance 2---------------------------------------------------------

my $cadreConcordance2=$page3b->Frame(-borderwidth => '0', -relief => 'groove')->pack(-side => 'left',-anchor => 'e', -fill => 'both',-expand=>1);
$cadreConcordance2->configure(-background => '#C0C0C0');

my $dico2D=$cadreConcordance2->Frame(-borderwidth => '0', -relief => 'groove')->pack(-side => 'left', -fill => 'both',-expand=>1);
$dico2D->configure(-background => '#C0C0C0');

$editeurconcordance2 = $dico2D->Scrolled("SMListbox",
				      -background => 'white',
				      -foreground => 'brown',
				      -textwidth => 2,
				      -highlightthickness => 2,
				      -width => 0,
				      -scrollbars => 'osoe',
				      -selectmode => 'extended',
				      -separatorcolor=>'black',
				      -separatorwidth=>2,
				      -resizeable => 1,
				      -scrollbars=>'se',
				      -columns=>[
						 [-text=> 'Contexte Gauche',     
						  -textwidth => 30, 
						  -fg => 'black', 
						  -bg => '#DDDDDD',
						  -comparecmd => sub {$_[0] cmp $_[1]}
						  ],
						 [-text => 'Forme',
						  -textwidth => 20,
						  -fg => 'black', 
						  -bg => '#DDDDDD',
						  -comparecmd => sub {$_[0] cmp $_[1]}
						  ],
						 [-text=> 'Contexte Droit',     
						  -textwidth => 30, 
						  -fg => 'black', 
						  -bg => '#DDDDDD',
						  -comparecmd => sub {$_[0] cmp $_[1]}
						  ],
						 ]
				      )->pack(-side => 'top',
					      -expand => 'yes',
					      -fill =>'both',
					      -padx => 0,
					      -pady => 0
					      );
$editeurconcordance2->columnGet(0)->Subwidget("heading")->configure(-background=>'#E5E5FF',-foreground=>'red',-activebackground=>'#C0C0C0');
$editeurconcordance2->columnGet(1)->Subwidget("heading")->configure(-background=>'#E5E5FF',-foreground=>'red',-activebackground=>'#C0C0C0');
$editeurconcordance2->columnGet(2)->Subwidget("heading")->configure(-background=>'#E5E5FF',-foreground=>'red',-activebackground=>'#C0C0C0');
$editeurconcordance2->Subwidget("xscrollbar")->configure(-elementborderwidth=>1, -borderwidth=>1,-relief=>'solid');
$editeurconcordance2->Subwidget("yscrollbar")->configure(-elementborderwidth=>1, -borderwidth=>1,-relief=>'solid');

$balloon->attach($editeurconcordance2->columnGet(0)->Subwidget("heading"), -balloonmsg => "trier le contexte gauche",-balloonposition => 'mouse',
  
   -statusmsg => "trie le contexte gauche par ordre alphabétique ou par ordre d'apparition");
   
   $balloon->attach($editeurconcordance2->columnGet(1)->Subwidget("heading"), -balloonmsg => "trier les formes",-balloonposition => 'mouse',
  
   -statusmsg => "trie les formes par ordre alphabétique ou par ordre d'apparition");
   
   $balloon->attach($editeurconcordance2->columnGet(2)->Subwidget("heading"), -balloonmsg => "trier le contexte droit",-balloonposition => 'mouse',
  
   -statusmsg => "trie le contexte droit par ordre alphabétique ou par ordre d'apparition");


#--------------------------------------------Treetagger----------------------------------------------------------
# Page 4

my $tritag=$page4->Button(-text => 'Lancer treetagger',-background=>'#BFBFBF',-foreground=>'brown',-relief => 'raised',-command =>sub{loadtreetagger();})->pack(-side => 'top',
						  -anchor => 'n',
						  -expand => 0
						 );	
						 
	$balloon->attach($tritag, -balloonmsg => "Lancer treetagger",  
   -statusmsg => "Permet de lancer un étiquetage grammatical du texte");					 
						 
						 
$editortreetagger = $page4->Scrolled("Text")->pack(-side => 'bottom',
				      -fill => 'both',
				      -expand => 1);
$editortreetagger->Text(-setgrid => 'true');


# Page 5
#------------------ extraction de patron ----------------------------------------------------------

$editorpatron = $page5->Scrolled("Text")->pack(-side => 'bottom',
				      -fill => 'both',
				      -expand => 1);
$editorpatron->Text(-setgrid => 'true');

my $patron=$page5->Button(-text => "Lancer l'extraction de patrons NOM-ADJ",-background=>'#BFBFBF',-foreground=>'brown',-relief => 'raised',-command =>sub{loadextractpattern();})->pack(-side => 'top',
						  -anchor => 'n',
						  -expand => 0
						 );


# Page 6
#------------------ editeur rapport ---------------------------------------------------------------------
$editorrapport = $page6->Scrolled("Text")->pack(-side => 'bottom',
				      -fill => 'both',
				      -expand => 1);
$editorrapport->Text(-setgrid => 'true');



#-------------------------------------------------------------------------------------------------------------
MainLoop;

#---------------------Procédures-------------------------------------------------------------------------------

#------------------------------------fichier textes--------------------------------------------------
sub lire_File {
    my $types=[
	       ['Text Files', ['.txt', '.dic', '.par']],
	       ['All Files', ['.*']] 
	       ];
    
    
    my $tmp_nom_source=$mw->getOpenFile(-filetypes=>$types); 
    print $tmp_nom_source,"\n";
    if ($tmp_nom_source=~/^$/) { 
	return; 	
    }
    my $texte="";
    $url=$tmp_nom_source;
    open(TMP,$tmp_nom_source);
    while(<TMP>) {
	$texte.=$_;
    }
    $editortexte->delete("1.0","end");
    $editortexte->insert("end",$texte);
    &makedico($texte);
	$onglet->raise('page1');
}
#----------------------------------------url-------------------------------------------------------------------

sub lire_url {
    $info="Chargement $url...";
	
    $editortexte->delete("1.0","end");
    $editorrapport->delete("1.0","end");

    my $page = get( $url );

    if ( not defined( $page ) ){
	print "Problème lors du téléchargement !\n";
   \&bad_adresse();
	} else
	{
    $editortexte->insert("end",$page);
    my $titrerapport="Rapport sur votre texte : \n";
    $editorrapport->insert("end",$titrerapport);

    $info = "chargé.";
	}
}

#--------------------------------------dictionnaire--------------------------------------------------------------------------

sub makedico {
    my $texte=shift;
    my @dico=split(/\W+/,$texte);
    my %dico2=();
    $dicodesformes->delete(0,'end');
    foreach my $a (@dico) {
	if (exists($dico2{$a})) {
	    $dico2{$a}++;
	}
	else {
	    $dico2{$a}=1;
	}

    }
    my $nombredemots=0;
    my $freqmax=0;
    my $formemax="";
    foreach my $mot (keys %dico2) {
	$dicodesformes->insert('end',[$mot , $dico2{$mot}]);
	$nombredemots++;
	if ($dico2{$mot}>$freqmax) {$freqmax=$dico2{$mot};$formemax=$mot};
    }
    my $titrerapport="Rapport sur texte : \n";
    $editorrapport->insert("end",$titrerapport);
    $editorrapport->insert("end","Nombre de mot : $nombredemots \n");
    $editorrapport->insert("end","Freq Max : $freqmax \n");
    $editorrapport->insert("end","Forme Max : $formemax \n");

}

    
#------------------------------nettoyage textes------------------------------------------------------------
    
	sub supprime_html { 
	my @balises_a_ignorer =
	    ("applet","code","embed","head","object","script","server");
	
	my $html = shift @_; 
	$html =~ s/\n+/ /g;
	$html =~ s/\r+/ /g;
	decode_entities($html);
	foreach my $balise (@balises_a_ignorer) {
	    $html=~s/<$balise.*?<\/$balise>//ig;
	}
	$html =~ s/<!--.*?-->//g;     #commentaires
	$html =~ s/<\/?p\/?>/\n/ig;   #paragraphes
	$html =~ s/<br\/?>/\n/ig;     #retours à la ligne
	$html =~ s/<\/tr>/\n/ig;      #lignes de tableau
	$html =~ s/<\/?h[1-6]>/\n/ig; #titres
	$html =~ s/<\/?div.*?>/\n/ig; #sections
	$html =~ s/<.*?>//g;          #autres balises
	$html =~ s/\s*\n\s*/\n/g;     #espaces en début/fin de ligne
	$html =~ s/ +/ /g;            #séquences de plusieurs espaces  
	return $html;
    }
    sub normalise_latin1 {
	my $chaine = shift @_;
	$chaine =~ s/[\x{2019}\x{2018}]/\'/g;
	$chaine =~ s/[\x{201C}\x{201D}]/\"/g;
	$chaine =~ s/[\x{2013}\x{2014}]/-/g;
	$chaine =~ s/\x{2026}/.../g;
	$chaine =~ s/\x{0152}/OE/g;
	$chaine =~ s/\x{0153}/oe/g;
	$chaine =~ s/[^\x{0000}-\x{00FF}]//g;
	return $chaine;
    }


#-----------------------------Sauvegarde---------------------------------------------------------------------------
sub sauve_editor {
    
    
	
  my $save = $mw->getSaveFile(-filetypes => $types, 
                             -initialfile => 'test',
                             -defaultextension => '.txt');
  $nom_fic=$save;
    open(FIC,">$nom_fic");
    print FIC $editortexte->get("1.0","end");
	print FIC $editorrapport->get("1.0","end");
	if ($save)	
		
		{ $mw->messageBox(-icon => info,
                -message => "Votre fichier a bien été sauvegardé",
                -title => "Sauvegarde",
                -type => "OK", 
                -default => 'OK'
				);
		}

	
}
#----------------------------Recherche--------------------------------------------------------------------------------

sub search_in_editor {
    
    $info="Recherche dans le fichier...";
    &text_search($editortexte, $search_string, 'search');
    if ($mw->depth > 1) {
	text_toggle($editortexte, ['configure', 'search', -background => 'SeaGreen4', -foreground => 'white'], 800,
		          ['configure', 'search', -background => undef,       -foreground => undef],   200);
      } else {
	text_toggle($editortexte, ['configure', 'search', -background => 'black',     -foreground => 'white'], 800,
		          ['configure', 'search', -background => undef,       -foreground => undef],   200);
      }

    $info= "Recherche dans Fichier terminée.";
}
#-----------------------------Recherche -------------------------------------------------------------------
sub text_search {

   

    my($w, $string, $tag) = @_;
	print aaaaaa $string;
if ($string)
{
    $w->tag('remove',  $tag, '0.0', 'end');
    (my $num_lines) = $w->index('end') =~ /(\d*)\.\d*/;
    for($i = 1; $i <=$num_lines; $i++) {
	my $line = $w->get("${i}.0", "${i}.1000");
	next if not defined $line or $line !~ /($string)/;
        my $l = length $1;
	$stringRegexp=$1;
	my $offset = 0;
	while (1) {
	    my $tmpoffset=0;
	    my $index = index $line, $stringRegexp, $tmpoffset;
	    last if $index == -1;
	    $offset += $index;
	    $w->tag('add', $tag, sprintf("%d.%d", $i, $offset), sprintf("%d.%d", $i, $offset+$l));
	    $offset += $l;
	    $line = substr $line, $index+$l;
	    if ($line=~/($string)/) { $stringRegexp=$1;
				      $l = length $1;}
	} 
    } 
}
} # end text_search
#---------------------------------------------------------------------------------------------------------------------------------
sub text_toggle {
    
    my($w, $cmd1, $sleep1, $cmd2, $sleep2) = @_;

    $w->tag(@{$cmd1});
    $w->after($sleep1, [sub {text_toggle(@_)}, $w, $cmd2, $sleep2, $cmd1, $sleep1]);
} 
#--------------------------------Concordance---------------------------------------------------------------------

sub concordance {
    $editorconcordance->delete('1.0','end');
	
    my @selection = $dicodesformes->curselection();
    if ($#selection eq -1) { 
	
	
	$mw->messageBox(-icon => info,
                -message => "Veuillez sélectionner un motif",
                -title => "Motif non sélectionné",
                -type => "OK", 
                -default => 'OK');
	
	
	
	
	return;
    }
    my @listeItem=();
    my $texte=$editortexte->get("1.0",'end');
    for (my $sel=0;$sel <= $#selection; $sel++) {
	my @formes=$dicodesformes->getRow($selection[$sel]);
	my $forme=$formes[0];
	print $forme,"\n";
	push(@listeItem,$forme);
    }
    my $opt_c=30;
	
    foreach my $item (@listeItem) {
	while($texte=~/\b$item\b/gi) {
	    my $g=$`;
	    my $p=$&;
	    my $d=$';
	    my $gauche="";
	    my $droite="";
	    if ( length($g) < $opt_c ) {
		$gauche = " " x ( $opt_c - length($g) ) . $g;
	    }
	    else {
		$gauche = substr( $g, length($g) - $opt_c, $opt_c );
	    }
	    $droite = substr ($d, 0, $opt_c );
	    $droite.="\n";

	    $editorconcordance->insert('end',$gauche,['contexte']);
	    $editorconcordance->insert('end',$p,['pivot']);
	    $editorconcordance->insert('end',$droite,['contexte']);
	    $editeurconcordance2->insert('end',[$gauche , $p,$droite]);
	}

	$editorconcordance->tagConfigure('contexte', -foreground=>'black',-font=>'{Courier New} 8',);
	$editorconcordance->tagConfigure('pivot', -foreground=>'brown',-font=>'{Courier New} 8 bold',-justify=>'center');	


	
    }
	 if( $group eq "Concordance-Version1" ) {
		$onglet->raise('page3');
	}
	 if( $group eq "Concordance-Version2" ) {
		$onglet->raise('page3b');
	}
    
}
#--------------------------Treetagger-----------------------------------------------------------------------------------------------------------

sub loadtreetagger {

	sub loadtreetaggerint {
    #----------------------------------------------------------------------------
    #il faut lancer la tokenisation
    my $texteentree=$editortexte->get("1.0","end");
    open(FIC,">INPUTTREETAGGER1.txt");
    print FIC $texteentree;
    close(FIC);
    system("perl tokenise-fr.pl INPUTTREETAGGER1.txt > INPUTTREETAGGER2.txt");
    #----------- on lance treetagger --------------------------------------------
    my $treetagger="INPUTTREETAGGER2.txt";
    my $treetaggerout="OUTPUTTREETAGGER1.txt";
    my $liblangue = "french.par";
    my $progname="tree-tagger.exe";
    my $commandetreetagger="$progname $liblangue -lemma -token -sgml -no-unknown \"$treetagger\" \"$treetaggerout\"" ;

    Win32::Process::Create($Win32::Process::Create::ProcessObj,
			   "tree-tagger.exe",
			   $commandetreetagger,           
			   0,                                  
			   NORMAL_PRIORITY_CLASS,
			   "."                        
			   ) 
	or                             
	die Win32::FormatMessage( Win32::GetLastError() ),"\n";
    $Win32::Process::Create::ProcessObj->Wait(INFINITE);
    #-----------------------------------------------------------------------------
    # on met au format XML
    system("perl treetagger2xml.pl OUTPUTTREETAGGER1.txt");
    #-----------------------------------------------------------------------------
    # il faut maintenant lire les résultats
    my $texte="";
    open(TMP,"OUTPUTTREETAGGER1.txt.xml");
    while(<TMP>) {
	$texte.=$_;
    }
    $editortreetagger->delete("1.0","end");
    $editortreetagger->insert("end",$texte);
	}
    $onglet->raise('page4');
}

#------------------------------extraction de patron nom-adj--------------------------------------------------------

sub loadextractpattern {

\&loadtreetaggerint ();

my $texteex=$editortreetagger->get("1.0",'end');
$editorpatron -> delete("1.0","end");
my @lignes=split(/\n/,$texteex);
close(FILE);
while (@lignes) {

    my $ligne=shift(@lignes);
    chomp $ligne;
    my $sequence="";
    my $longueur=0;
    if ( $ligne =~ /<element><data type=\"type\">NOM<\/data><data type=\"lemma\">[^<]+<\/data><data type=\"string\">([^<]+)<\/data><\/element>/) {
	 my $forme=$1;
	 $sequence.=$forme;
	 $longueur=1;
	 my $nextligne=$lignes[0];
	 if ( $nextligne =~ /<element><data type=\"type\">ADJ<\/data><data type=\"lemma\">[^<]+<\/data><data type=\"string\">([^<]+)<\/data><\/element>/) {
	     my $forme=$1;
	     $sequence.=" ".$forme."\n";
	     $longueur=2;
	 }
    }
    if ($longueur == 2) {
	
	$editorpatron-> insert("end",$sequence);
     $onglet->raise('page5');
    }
}
}


#-------------------------message d'erreur chargement texte-------------------------------------------------------------------

sub dialogbox { 

print $group1;
 if( $group1 eq "URL" ) {
		\& lire_url();
		}
if( $group1 eq "Fichier.txt" ) {
		\&lire_File();
		}
 if(!($group1 eq "Fichier.txt")&&!($group1 eq "URL"))
 
 {
		$mw->messageBox(-icon => info,
                -message => "Veuillez sélectionner un type de données",
                -title => "Type de données non spécifié",
                -type => "OK", 
                -default => 'OK'
				);
			
		}
	
}

#--------------------------------bouton quitter------------------------------------------------------------

	sub quitter { my $reponse = $mw->messageBox(-icon => question,
                -message => "Etes vous sûr de vouloir quitter? \n Toute donnée non enregistrée sera perdue.",
                -title => "Quitter",
                -type => "OKCancel", 
                -default => 'OK'
				);
	  if( $reponse eq "Ok" ) {
		exit;
	} 
}	

#-------------------------------Erreur boutton commencer----------------------------------
	
sub bad_adresse {
	my $response = $mw->messageBox(-icon => info,
                -message => "Veullez entrer une adresse valide",
                -title => "Adresse invalide",
                -type => "OK", 
                -default => 'OK'
				);
	 
}

##--------------------------------radiobutton concordance---------------------------------------------------------	
 sub concor {
 
 print $group;
 if( ($group eq "Concordance-Version1")||($group eq "Concordance-Version2") ) {
		\& concordance();
		
}
 if(!($group eq "Concordance-Version1")&&!($group eq "Concordance-Version2"))
 
 {
		$mw->messageBox(-icon => info,
                -message => "Veuillez sélectionner un type de Concordance",
                -title => "Type de Concordance non spécifié",
                -type => "OK", 
                -default => 'OK'
				);
			
		}
 }
 