#!/usr/bin/perl -s

use strict;
use warnings;

use CGI qw(:standard);
use CQP;
use Data::Dumper;

# directoria onde estão registados os corpora 
my $regis = "/usr/local/share/cwb/registry";

my $corpus = lc(param('corpus')) || '';
my $cqp;
my $n = param('n') || '1 tu';
my $max = param('max') || '20';
my @result = ();

if ($corpus) {
	$cqp = CQP -> new("-b 10 -D ".uc($corpus));
} else {
	$cqp = CQP -> new("-b 10 ");
}


# array com todos os corpora que tenho disponíveis
my @corpora = map {s/^\s*//; ucfirst(lc($_))} $cqp -> exec("show corpora");

# teste dos que sao paralelos
my $registry= param('r') || $regis ;
my $paral=`grep ALIGNED $registry/$corpus`;
chomp $paral;
$paral =~ s/ALIGNED\s*(\S+)/$1/;

# lista de opções associadas ao corpora escolhido
my %corpora;
for (@corpora) {
   $cqp = CQP->new("-b 10 -D ".uc($_));
	my @tags = $cqp -> exec("show cd");
	my @tags1;
	for my $tag (@tags) {
		push (@tags1,$tag) if ($tag !~ /s-Att[.]*/);
	}
	$corpora{$_}=[@tags1];
}

# inicio do html a gerar
print header;
print start_html("-title"=>"Corpora Forge"),
		h1("Ferramenta de pesquisa em corpora"), hr;
print p("Escolha um corpora dispon&iacute;vel");

#showInfo($corpus);

print start_form({"name"=>"form"}),
	"<p><select name=\"corpus\" size=\"1\" onChange=\"redirect(this.options.selectedIndex)\">";

my @ordem = keys %corpora;

for (@ordem) {
	print "<option>$_</option>";
}

print "</select>",
	"<select name=\"tag\" size=\"1\">";

for (@{$corpora{$ordem[0]}}) {
	print "<option value=\"$_\">$_</option>\n";
}

print "</select>";

print "<script>
//<!--
var groups=document.form.corpus.options.length;
var group=new Array(groups);
for (i=0; i<groups; i++)
group[i]=new Array();
";
my ($i,$j) = (0,0);

for (@ordem) {
	for (@{$corpora{$_}})  {
		print "group[$i][$j]=new Option(\"$_\",\"$_\");","\n";
		$j++;
	}
	$i++;
	$j=0;
}

print "var temp=document.form.tag;

function redirectXXX(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null;
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value);
}
temp.options[0].selected=true;
}
//-->
</script>
",
	table(
			Tr(
				td(["procurar"," contexto"," max"])),
			Tr(
				td([textfield('k'),
					popup_menu('n',["1 tu","7 words","20 words","1 s","1 p","0 words"]),
					popup_menu('max',[20,200,1000,2000])]))
		),

end_form;
print br;
print "<a onClick='window.location=\"info.pl?corpus=\"+document.form.corpus.options[document.form.corpus.options.selectedIndex].text' \">Informa&ccedil;&atilde;o sobre o corpus</a>\n";

if(param()) {
	
	print br;

   $cqp = CQP->new("-b 10 -D ".uc($corpus));
	
	my $pat = param('k');
	$pat = doyourbest($pat);
	print "<pre>\n$pat\n</pre>\n";

   $cqp->exec("set HardBoundary 15;");
   $cqp->exec("set LeftContext $n ;");
   $cqp->exec("set RightContext $n ;");
   $cqp->exec("set LeftKWICDelim  '<b>' ;");
   $cqp->exec("set RightKWICDelim '</b>' ;");
   $cqp->exec("show +$paral ;") if $paral;

	$cqp -> exec("A = $pat;");
	@result = $cqp -> exec("cat A 1 $max;");

	print "Foram encontradas ",
		b($cqp -> exec("size A;"))," ocorrencias",
		hr;

	if($paral){
     print "<table border='1' >\n";
     while(@result){
       my $a=shift(@result);
       my $b=shift(@result);
       $b =~ s/-->$paral?://;
       print Tr(td([$a,$b]));
     }
     print "</table>\n";
   }
   else{ 
     print ol(li([@result]));
   }
 }
		
sub doyourbest{ 
	my $pat = shift;
   $pat =~ s/^\s*(\w+)\s*$/"$1";/;
	$pat =~ s/\b(alema|apos)\s*=\s*"(.*?)"/$1 contains "$2"/g;
   $pat
}
__END__
