#!/usr/bin/perl 

use CGI qw(:standard);
use strict;
use Search::Dict;
use HTML::Entities;
#use Fcntl qw(:flock);

print header();

&myheader;
my $dico= param('dico');
my $key=param('key');
my $traduction = "";
my $motsuivant;
my ($traduction1,$suivant1);
my ($traduction2,$suivant2);
my $count;

my $data_dir="/var/www/abp/www/dico/";
my $ERROR;
my $mutation=0;
my $savedkey= $key;

my $racine;
my $suivant;
my $original;
my $mutedletter;
my %MUTATIONS = ("b" =>"p",
               "c'h" =>"k g",
                 "d" =>"t",
                 "f" =>"p",
                 "g" =>"k",
                 "k "=>"g",
                "kw" =>"gw",
                 "p" =>"b",
                 "t" =>"d",
                 "v" =>"m b",
                 "w" =>"gw",
                 "z" =>"d t");


#&footer;
#exit(0);


if(!$key){
 	&footer;
exit(0);   
}

$key=substr($key,0,128);


if(param('dico') eq "Dico" 
	or param('dico') eq "DICO" 
	or param('dico') eq "Dictionnaires"){
	$ERROR=" oops!...Selectionner d'abord un dico...";
&footer;
exit(0);   
}


##NETOYAGE
#il n'y a pas de c en breton
if ($dico eq "breton" and $key !~/c'?h/ ){
	#replace les c par des k
	$key=~s/c/k/ig unless $key=~/circ/i;
}
#encode_entities($key,"\200-\377"); #no accent anymore
$key=~s/^[ ]*//;# clean up leading white space
$key=~s/\s+$//;  # clean up trailing white space
$key=~s/\-/ZZ/g; #replace les traits d'union car ils sont pas alphabetises


##WILD CARD
if($key=~/(.*)[*]$/){
$key=$1;
$traduction=&wildcard($key);
&end;  
}


##PHRASES
my $nombredemots=split(/ /,$key);
#print "Vous avez entre $nombredemots";
if ($nombredemots >1){
	$dico="francais";
	#print "my key is $key";
	my $traduction=&expression($key);
	print $traduction;
	if (!$traduction){
    	$dico="breton";
    	#print "my key is $key";
   		$traduction=&expression($key);
    	print $traduction;
    	}
		if (!$traduction){
		print "sans resultat";
		}
&end;

}

## BASIC SEARCH
($traduction, $motsuivant) = &search($key);
if($traduction){
	&end;  
}

  ## AUTOMATIC CORRECTIONS

elsif ($dico eq  "francais"){
#mots pluriels francais
   if($key=~/(.*)s$/i){
   		$key=$1;
   		($traduction, $motsuivant)=&search($key);
   		&end;  
   }  
   if($key=~/(.*)e$/i){
   		$key=$1;
   		($traduction, $motsuivant)=&search($key);
   		&end;  
   } 
}

elsif($dico eq "breton"){
   	if($key=~/(.*)iou$/i or $key=~/(.*)ou$/i){
  	 print "<p> _ou et _iou sont des pluriels<br>";
  	 $key=$1;
   	($traduction, $motsuivant)=&search($key);
	&end;  
   	}
   
	#cas the w->v
	elsif($key=~/(.*)o$/i or $key=~/(.*)v$/i){
  	 $key=$1."W";
   	($traduction, $motsuivant)=&search($key);
	&end;  
   	}

	elsif($key=~/(.*)z$/i){
	$key=$1."ZH";
  	($traduction, $motsuivant)=&search($key);
  	 &end; 
   	}

    elsif($key=~/^b|c'h|d|f|g|k|kw|p|t|v|w|z/ig){
    #key can be muted
    	while(($mutedletter,$original) = each(%MUTATIONS)){
    	my ($racine1,$racine2) = &mutation($key,$mutedletter);
    	($traduction1,$suivant1)=search($racine1);
    	($traduction2,$suivant2)=search($racine2);
    	if($traduction1 and !$traduction2){
    		$motsuivant=$suivant1;
    		$mutation=1;
    		$traduction=$traduction1;
    		$racine=$racine1;
    		&end;
    		}
    	if($traduction2 and !$traduction1){
    		$motsuivant=$suivant2;
    		$traduction=$traduction2;
    		$racine=$racine2;
    		$mutation=1;
    		&end;
    		}
    	if($traduction2 and $traduction1){
    		$motsuivant="$suivant2";
    		$traduction=$traduction1;
    		$traduction.=$traduction2;
    		$mutation=1;
    		$racine ="$racine1 ou $racine2";
    		&end;
    		}
    		
         } # end of while loop
     }# end of mutation
} #end of dico breton


#if we arrive here, we give up!!!!
&nothingfound($savedkey);
&end;

 # do a grep?


#end of program############################################################################



sub mutation{
my($mot,$letter) = @_;
my $item;
my @racines = split(/ /,$MUTATIONS{$letter}); #cas de mutations pouvant provenir de deux lettres
my $mot1=$mot;
my $mot2=$mot;
$mot1=~s/^$letter(.*)/$racines[0]$1/i;
$mot2=~s/^$letter(.*)/$racines[1]$1/i;
return ($mot1,$mot2);

}


sub expression{
my $expression= shift @_;
my $resultat;

`grep -i -w "$key" /dico/francais> /var/www/abp/www/dico/tmp/$$.txt`;
 open (RESULT, "/var/www/abp/www/dico/tmp/$$.txt");
 $resultat=<RESULT>;
 $resultat=~s/$expression/<font color=blue>$expression<\/font>/ig;
 my $size=(-s "$$.txt");
 close (RESULT);
 system "rm -f /var/www/abp/www/dico/tmp/$$.txt";
 if($size == 0 or $size > 5000){
	return ("Desole, c'est pas dans le dico");
	}
return $resultat;
}


#-----------end of program------------ 
 
   
#nothing was found

sub nothingfound {
my $key= @_;
$motsuivant eq "";
my $comefrom=$ENV{'REMOTE_HOST'};
my $date=localtime(time);
open (LOG, ">>/var/www/abp/www/dico/baddicolog.txt") or print "could not open log";
print LOG "$date\t$dico\t$savedkey\n";
close LOG;	
 
$ERROR.="<p>Desole, <b>$savedkey</b> n'est pas dans le dictionnaire, <li> Cherchez vous le bon dico?";
$ERROR .="<li> Verifiez l\'orthographe. Ne mettre ni les accents, ni le feminin ni le pluriel (-ou ou -iou en breton).";

$ERROR.="<li>Pour les mots compos&eacute;s, bout de texte ou expressions idiomatiques, d&egrave;s qu'il y a plus d'un mot, la il faut bien bien mettre les accents car la recherche est differente (grep global sur l'ensemble du dico).";
$ERROR .="<li>Vous pouvez aussi utiliser l'etoile pour chercher des mots avec la m&ecirc;me racine, par exemple metre une etoile apres bihan* vous donnera une serie de mots commencant par bihan.<br>";
}
#--------end of program-----------------------


sub end{
if ($mutation){
print "<FOnt size=2 color=red>Note: $savedkey est probablement une mutation de $racine.</font>";
}
$traduction=~s/ZZ/\-/ig;
print ($traduction);
 $count =&count;
&footer;
exit(0);
}

sub myheader{
print <<"HEADER";
<HTML>
<HEAD>
<LINK REL="stylesheet" TYPE="text/css" HREF="/css/abp.css">
<TITLE> Dico Geriadur Dictionary Dictionnaire</TITLE>




<STYLE>
.fondo { 
background-color: #3874B0;
 background-position: center bottom;
  float: none; color: #FFFFFF 
  }
  </STYLE>
</HEAD>
<BODY bgcolor="white" TEXT="#333333" LINK="navy blue" >




<script type="text/javascript"><!--
google_ad_client = "pub-7654345458237551";
/* 728x90, date de crŽation 21/11/09 */
google_ad_slot = "2279404007";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>


<!--<A HREF="../"><IMG BORDER=0 SRC="../images/minilogo.gif"></a><p>-->

<Pre>


</pre>
HEADER

}


sub footer{
my $menu=param('dico');
# my $count=&count;
if ($motsuivant){
	$motsuivant=lc($motsuivant);
	my $left2=$motsuivant;
	$motsuivant=~s/ZZ/\-/ig;
	$left2=~s/&/%26/g;
	$left2=~s/;/%3B/g;
#	print "<p><font size=2>Mot suivant: <A HREF=\"dico.cgi?dico=$menu&key=$left2\">$motsuivant</a></font><p>";
    }

print <<"FOOTER";
$ERROR
<FORM METHOD=GET ACTION="dico.cgi">
<p>
<SELECT NAME="dico">
FOOTER
if($dico eq "francais"){
print "<OPTION SELECTED VALUE=\"francais\">fran\&ccedil\;ais -> breton</OPTION>"; 
print "<OPTION  VALUE=\"breton\">breton -> fran\&ccedil\;ais</OPTION></SELECT>";
}
else{
print "<OPTION SELECTED VALUE=\"breton\">breton -> fran\&ccedil\;ais</OPTION>";
print "<OPTION VALUE=\"francais\">fran\&ccedil\;ais -> breton</OPTION></SELECT>";
}
print <<"FOOTER";
<P>
<INPUT TYPE =TEXT size=30 NAME="key" value="">

&nbsp;  &nbsp;
<INPUT TYPE="SUBMIT"  class='fondo' NAME="buton" VALUE="Traduire">


<br>
(<font size=2>Ne pas entrer les accents</font>)
</FORM>
<hr noshade size=1>
<FONT face="Verdana, Arial, Helvetica, sans-serif" size=1>
<font size=1>
[<a href="../dico/credits.html">Credits</a>]&nbsp;



[<a href="http://www.ofis-bzh.org/">Office de la Langue Bretonne</a>]&nbsp;
[<a href="../dico/betisier.php">B&ecirc;tisier</a>]
[<a href="../index.php">Retour</a>]

&nbsp;&nbsp;&nbsp;&nbsp;
</font>
<p>


<!--<iframe src="http://rcm-fr.amazon.fr/e/cm?t=agencebretagn-21&o=8&p=8&l=as1&asins=2903365148&fc1=000000&IS2=1&lt1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<iframe src="http://rcm-fr.amazon.fr/e/cm?t=agencebretagn-21&o=8&p=8&l=as1&asins=2903365156&fc1=000000&IS2=1&lt1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<iframe src="http://rcm-fr.amazon.fr/e/cm?t=agencebretagn-21&o=8&p=8&l=as1&asins=2903365164&fc1=000000&IS2=1&lt1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<iframe src="http://rcm-fr.amazon.fr/e/cm?t=agencebretagn-21&o=8&p=8&l=as1&asins=2911447123&fc1=000000&IS2=1&lt1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
<iframe src="http://rcm-fr.amazon.fr/e/cm?t=agencebretagn-21&o=8&p=8&l=as1&asins=2915623163&fc1=000000&IS2=1&lt1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
<iframe src="http://rcm-fr.amazon.fr/e/cm?t=agencebretagn-21&o=8&p=8&l=as1&asins=2901383599&fc1=000000&IS2=1&lt1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>-->
<!--<script type="text/javascript">
sas_pageid='4265/27052';      // Page : locacite/agence_bretagne_presse/accueil
sas_formatid=618;             // Format : CarrŽ 250*250 250x250
sas_target='';                // Targeting
SmartAdServer(sas_pageid,sas_formatid,sas_target);
</script>

<script type="text/javascript">
sas_pageid='4265/27067';      // Page : locacite/agence_bretagne_presse/quimper
sas_formatid=618;             // Format : CarrŽ 250*250 250x250
sas_target='';                // Targeting
SmartAdServer(sas_pageid,sas_formatid,sas_target);
</script>


<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript" language="javascript">
_uacct = "UA-541574-1";
urchinTracker();
</script>-->

</BODY>
</HTML>
FOOTER
}



sub search{
my $key=shift @_;
my $result;
my $definitions;
my $position=0;
my $right="";
my $left;
open (DICO, "< /var/www/abp/www/dico/$dico") or print "could not open dico $dico";
    $position= look (*DICO, $key,1,1);
	$result = <DICO>;
	($left,$right)=split(/\]\[/,$result);
	$left=~s/\s+$//;
	if($left =~/^$key$/i and length($key)==length($left)){
	$definitions ="<p><font size=2><b>$left</b> ][ $right</font>";
	
	while ($left =~/^$key$/i and length($key)==length($left)){
    $position=$position + 1;
	    	$result = <DICO>;
	    	($left,$right)=split(/\]\[/,$result);
	    	 $left=~s/\s+$//;
	    	if($left =~/^$key$/i and length($key)==length($left)){
                     #  $left=~s/ZZ/\-/ig; #replace les traits d'union		 
                       $definitions.="<p><font size=2><b>$left</b> ][ $right";
	    	       }
		}
     } else{
	 $result=0;
	 close(DICO);
	 }
$result=~s/ZZ/\-/ig; #replace les traits d'union
return ($definitions,$left);
}


sub wildcard{
my $key=shift @_;
my $result;
my $position;
my $match=0;
my $data;
#print $key;
open (DICO, "<$dico") or die "could not open dico";
    $position= look (*DICO, $key,0,1);
    $result = <DICO>;
	my $savedposition=$position + 7;
    (my $left, my $right)=split(/\]\[/,$result);
    $left=~s/\s+$//;
    if($left =~/^$key/i){
	$match=1;
	$data ="<p><b>$left</b> ][ $right";
		while ($left =~/^$key/i){
	    	$position=$position + 1;
	    	if ($position > $savedposition){ last;}
			$result = <DICO>;
	    	($left,$right)=split(/\]\[/,$result);
	    	if($left =~/^$key/i){
		    $data.="<p><b>$left</b> ][ $right";
	    	}
     	}
	}	
	 close(DICO);
return ($data);
}

sub count{
    open (COUNT, "</var/www/abp/www/dico/countmot.txt");
    $count=(<COUNT>);
    close COUNT;
$count++;
  
    return $count;
}





