use strict;

use strict;
my $usage = "$0 parameters\n";
my $arg=0;
my $loginname = $ARGV[$arg++] or die $usage;
my $sessionID = $ARGV[$arg++] or die $usage;
my $file_test = $ARGV[$arg++] or die $usage;
my $taskID  = $ARGV[$arg++] or die $usage;
my $FDR  = $ARGV[$arg++] or die $usage;
my $min_ratio  = $ARGV[$arg++] or die $usage;
my $Nmatrix  = $ARGV[$arg++] or die $usage;
my $match_thresh  = $ARGV[$arg++] or die $usage;
my $max_repeat  = $ARGV[$arg++] or die $usage;
my $dataname = "";
my $file_control = "";
my $file_repeat = "";
my $use_repeats = 0;
my $strand = 0;
my $score = 0;
my $adjust_cg = 0;
my $method = 0;
my $presence = 0;
while(my $option = $ARGV[$arg++]){
	if(uc($option) eq "-C"){ $file_control = $ARGV[$arg++]; }
	elsif(uc($option) eq "-REP"){ $file_repeat = $ARGV[$arg++]; }
	elsif(uc($option) eq "-USEREP"){ $use_repeats = 1; }
	elsif(uc($option) eq "-STRAND"){ $strand = $ARGV[$arg++]; }
	elsif(uc($option) eq "-SCORE"){ $score = $ARGV[$arg++]; }
	elsif(uc($option) eq "-CG"){ $adjust_cg = 1; }
	elsif(uc($option) eq "-POS"){ $method = $ARGV[$arg++]; }
	elsif(uc($option) eq "-DATA"){ $dataname = $ARGV[$arg++]; }
	elsif(uc($option) eq "-ONE"){ $presence = 1; }
	else{ die "ERROR: Wrong option $option\n"; }
}
my $outputIDfind  = $taskID+1;
my $outputIDpos   = $taskID+2;
my $outputIDclust = $taskID+3;

my %hashIni;
read_configuration("../../cisfinder.ini",\%hashIni);
my $PATH_HOME=$hashIni{"PATH_HOME"};
my $PATH_PROG=$hashIni{"PATH_PROG"};
my $CGI_ADDRESS=$hashIni{"CGI_ADDRESS"};
my $HOME_ADDRESS=$hashIni{"HOME_ADDRESS"};
my $SECURITY=$hashIni{"SECURITY"};
my $UNIX=$hashIni{"UNIX"};
my $PATH_INFO = "$PATH_PROG/info";
my $PATH_DATA = "$PATH_PROG/data";
my $PATH_BIN = "$PATH_PROG/bin";
my $PATH_OUTPUT = "$PATH_HOME/output";

open (OUTPUT, ">$PATH_OUTPUT/$taskID.txt");
print OUTPUT "<pre>";
if(!$PATH_PROG){ print OUTPUT "Error: Configuration file not found!\n"; }
close OUTPUT;

# Assemble the command line and execute patternFind
my @command=(
	"$PATH_BIN/patternFind",
	"-i $PATH_DATA/$file_test",
	"-o $PATH_OUTPUT/$outputIDfind.txt",
	"-FDR $FDR",
	"-ratio $min_ratio",
	"-n $Nmatrix",
);
if($file_control){ push(@command,"-c $PATH_DATA/$file_control"); }
if($file_repeat){  push(@command,"-rep $PATH_DATA/$file_repeat"); }
if($use_repeats){  push(@command,"-userep"); }
if($strand){       push(@command,"-strand $strand"); }
if($score){        push(@command,"-score $score"); }
if($adjust_cg){    push(@command,"-cg"); }
if($method){       push(@command,"-pos $PATH_OUTPUT/$outputIDpos.txt"); }
if($presence){     push(@command,"-one"); }
my $command1 = join(' ',@command);
#print "$command1\n";
my $response = `$command1`;
#print "$response\n";

open (OUTPUT, ">>$PATH_OUTPUT/$taskID.txt");
print OUTPUT "\n$response</pre>\n";
if($response =~ /ERROR/i){
	print OUTPUT "<h3>Errors in program run<h3>Output was not generated<p>\n";
	print OUTPUT "</HTML>\n";
	exit(0);
}
my $page_text = "<b>Elementary motifs extracted</b><p>\n";
$page_text .= "Output as plain text:\n";
$page_text .= "<a href=../output/$outputIDfind.txt target=_BLANK675>Elementary motifs</a><p>\n";
$page_text .= "<INPUT NAME=\"show_motif_button\" TYPE=button VALUE=\"Show elementary motifs\" onClick=show_motifs('$outputIDfind.txt');>\n";
$page_text .= "<FORM NAME=cisfinder ACTION=$CGI_ADDRESS/cisfinder.cgi METHOD=POST>\n";
$page_text .= "<INPUT NAME=\"loginname\" TYPE=\"hidden\" VALUE=\"$loginname\">\n";
$page_text .= "<INPUT NAME=\"sessionID\" TYPE=\"hidden\" VALUE=\"$sessionID\">\n";
$page_text .= "<INPUT NAME=\"data\" TYPE=\"hidden\" VALUE=\"$dataname\">\n";
$page_text .= "<INPUT NAME=\"action\" TYPE=\"hidden\" VALUE=\"save_motifs\">\n";
$page_text .= "<INPUT NAME=\"file_motif_elem\" TYPE=\"hidden\">\n";
$page_text .= "<INPUT NAME=\"file_motif_output\" TYPE=\"hidden\" VALUE=\"$outputIDclust.txt\">\n";
print OUTPUT $page_text;
print OUTPUT "<p><b>Clustering motifs...</b><br>\n";

# Assemble the command line and execute patternCluster
my @command=(
	"$PATH_BIN/patternCluster",
	"-i $PATH_OUTPUT/$outputIDfind.txt",
	"-o $PATH_OUTPUT/$outputIDclust.txt",
	"-match $match_thresh",
	"-repeat $max_repeat"
);
if($method){       push(@command,"-pos $PATH_OUTPUT/$outputIDpos.txt"); }
if($method==2){    push(@command,"-posonly"); }
my $command2 = join(' ',@command);

$response = `$command2`;

print OUTPUT "<pre>$response</pre>\n";
if($response =~ /ERROR/i){
	print OUTPUT "<h3>Errors in program run<h3>Output was not generated<p>\n";
	print OUTPUT "</FORM></BODY></HTML>\n";
	exit(0);
}
if(!open(INFO, "$PATH_OUTPUT/$outputIDclust.txt")){
	print OUTPUT "Cluster output file not found!\n";
	print OUTPUT "</FORM></BODY></HTML>\n";
	exit(0);
}
my $count=0;
while(my $line = <INFO>){
	if($line =~ /^>/){ ++$count; }
}
close INFO;
my $nPages = int(($count+9)/10);
print OUTPUT "Number of clusters = $count<p>\n";
print OUTPUT "Output as plain text:\n";
print OUTPUT "<a href=../output/$outputIDclust.txt target=_BLANK443>Motif cluster</a><p>\n";
print OUTPUT "<INPUT NAME=\"show_cluster_button\" TYPE=button VALUE=\"Show clusters of motifs\" onClick=show_motifs('$outputIDclust.txt','$outputIDfind.txt');>\n";
my $file_motif_save = $file_test;
$file_motif_save =~ s/\.fa$//;
$file_motif_save =~ s/^$loginname-|^public-//;
$file_motif_save = "motif_".$file_motif_save;
print OUTPUT "File name: <INPUT NAME=\"file_motif\" SIZE=15 VALUE=$file_motif_save>\n";
print OUTPUT "Description: <INPUT NAME=\"description_motif\" SIZE=50 VALUE=\"Motifs over-represented in $file_test\"> (modify if needed)<br>\n";
print OUTPUT "<INPUT NAME=\"save_motif_button\" TYPE=button VALUE=\"Save motifs\" onClick=save_motif_file();>\n";
print OUTPUT "<SELECT NAME=\"file_motif_select\"><OPTION VALUE=$outputIDfind.txt>Elementary motifs<OPTION VALUE=$outputIDclust.txt selected>Clusters of motifs</SELECT><p>\n";
print OUTPUT "<INPUT NAME=\"close_button\" TYPE=button VALUE=\"Close window\" LANGUAGE=\"javascript\" onClick=\"window.close();\"><p>\n";
print OUTPUT "</FORM>\n";
print OUTPUT "</BODY>\n";
print OUTPUT "</HTML>\n";
close OUTPUT;
exit(0);

#***********************************
sub read_configuration
#***********************************
{
my $filename = shift;
my $hashIni_ref = shift;

open (INFO_TEMP, $filename);
while(my $line=<INFO_TEMP>){
	$line =~ s/\n$//;
	my ($keyword,$value) = split(/=/,$line);
	$hashIni_ref->{$keyword} = $value;
}
close INFO_TEMP;
return;
}

#**************************************
sub  read_config_line
#**************************************
{
my $line = shift;
my $hash_ref = shift;

%$hash_ref=();
$line =~ s/\n$//;
my @items = split(/\t/,$line);
foreach my $item (@items){
	my($key,$value) = split(/=/,$item);
	$hash_ref->{$key}=$value;
}
return;
}


