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_fasta = $ARGV[$arg++] or die $usage;
my $file_motif = $ARGV[$arg++] or die $usage;
my $fileFasta = $ARGV[$arg++] or die $usage;
my $filenameMotif = $ARGV[$arg++] or die $usage;
my $taskID  = $ARGV[$arg++] or die $usage;
my $use_repeats = 0;
my $strand = 0;
my $falsePositives = 0;
my $addThresh = 0;
my $interval = 0;
my $use_redundant = 0;
my $dataname = "";
while(my $option = $ARGV[$arg++]){
	if(uc($option) eq "-THRESH"){ $addThresh = $ARGV[$arg++]; }
	elsif(uc($option) eq "-USEREP"){ $use_repeats = 1; }
	elsif(uc($option) eq "-REDUND"){ $use_redundant = 1; }
	elsif(uc($option) eq "-STRAND"){ $strand = $ARGV[$arg++]; }
	elsif(uc($option) eq "-FP"){ $falsePositives = $ARGV[$arg++]; }
	elsif(uc($option) eq "-INT"){ $interval = $ARGV[$arg++]; }
	elsif(uc($option) eq "-DATA"){ $dataname = $ARGV[$arg++]; }
	else{ die "ERROR: Wrong option $option\n"; }
}
my $outputIDsearch = $taskID+1;
my $outputIDfreq = $taskID+2;
my $outputIDabund = $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/patternScan",
	"-i $PATH_DATA/$filenameMotif",
	"-f $PATH_DATA/$fileFasta",
	"-o $PATH_OUTPUT/$outputIDsearch.txt"
);
if($use_repeats==1){ push(@command,"-userep"); }
if($use_redundant==1){ push(@command,"-redund"); }
if($addThresh){ push(@command,"-thresh $addThresh"); }
if($falsePositives){ push(@command,"-fp $falsePositives"); }
if($strand){ push(@command,"-strand $strand"); }
my $fileConserv = "$PATH_DATA/$fileFasta";
$fileConserv =~ s/\.fa$/.cons/;
if(file_exist($fileConserv)){ push(@command,"-cons $fileConserv"); }
my $string = join(' ',@command);
my $response = `$string`;

open (OUTPUT, ">>$PATH_OUTPUT/$taskID.txt");
print OUTPUT "$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);
}
print OUTPUT "<p><b>Output in plain text:</b>\n";
print OUTPUT "<a href=../output/$outputIDsearch.txt target=_BLANK1634>Search results, raw file</a><p>\n";

print OUTPUT "<FORM NAME=cisfinder ACTION=$CGI_ADDRESS/cisfinder.cgi METHOD=POST\">\n";
print OUTPUT "<INPUT NAME=\"loginname\" TYPE=\"hidden\" VALUE=\"$loginname\">\n";
print OUTPUT "<INPUT NAME=\"sessionID\" TYPE=\"hidden\" VALUE=\"$sessionID\">\n";
print OUTPUT "<INPUT NAME=\"data\" TYPE=\"hidden\" VALUE=\"$dataname\">\n";
print OUTPUT "<INPUT NAME=\"action\" TYPE=\"hidden\" VALUE=\"save_search\">\n";
print OUTPUT "<INPUT NAME=\"file_search_output\" TYPE=\"hidden\" VALUE=\"$outputIDsearch.txt\">\n";
print OUTPUT "<INPUT NAME=\"file_freq\" TYPE=\"hidden\" VALUE=$outputIDfreq.txt>\n";
print OUTPUT "<INPUT NAME=\"file_abund\" TYPE=\"hidden\" VALUE=$outputIDabund.txt>\n";
print OUTPUT "<INPUT NAME=\"file_fasta\" TYPE=\"hidden\" VALUE=$file_fasta>\n";
print OUTPUT "<INPUT NAME=\"file_motif\" TYPE=\"hidden\" VALUE=$file_motif>\n";
print OUTPUT "<INPUT NAME=\"interval\" TYPE=\"hidden\" VALUE=$interval>\n";
print OUTPUT "<INPUT NAME=\"motif\" TYPE=\"hidden\">\n";
print OUTPUT "<INPUT NAME=\"show_frequency\" TYPE=\"hidden\" VALUE=1>\n";
print OUTPUT "<b>Save the file with search results as:</b> &nbsp; &nbsp; &nbsp; <INPUT NAME=\"file_search\" SIZE=20 VALUE=\"\"><br>\n";
print OUTPUT "Description:  &nbsp; &nbsp; &nbsp; <INPUT NAME=\"description\" SIZE=80 VALUE=\"Motifs from $file_motif found in sequences $file_fasta\">&nbsp;(modify if needed)<br>\n";
print OUTPUT "<INPUT NAME=\"save_search_button\" TYPE=button VALUE=\"Save search results\" onClick=\"return save_search_file();\">\n";
print OUTPUT "<INPUT NAME=\"close_button\" TYPE=button VALUE=\"Cancel\" LANGUAGE=\"javascript\" onClick=\"window.close();\"><p>\n";

my @command=(
	"$PATH_BIN/patternDistrib",
	"-i $PATH_OUTPUT/$outputIDsearch.txt",
	"-f $PATH_OUTPUT/$outputIDfreq.txt",
	"-a $PATH_OUTPUT/$outputIDabund.txt",
	"-int $interval"
);
print OUTPUT "<b>Making frequency and abundance tables...</b>\n";
my $string = join(' ',@command);
#print OUTPUT "$string\n";
my $response = `$string`;

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 "</HTML>\n";
	exit(0);
}
my @items=split(/ +/,$response);
my $nSeq = $items[3];
my $nMotifs = $items[5];
my $maxPos = $items[7];
if(!$nMotifs){
	print OUTPUT "<b>No motifs in the file!</b><p>\n";
	print OUTPUT "</HTML>\n";
	exit(0);
}
print OUTPUT "<b>Output in text format:</b><br>\n";
print OUTPUT "<a href=../output/$outputIDsearch.txt target=_BLANK1621>Search results</a><br>\n";
print OUTPUT "<a href=../output/$outputIDfreq.txt target=_BLANK1634>Frequency table</a><br>\n";
print OUTPUT "<a href=../output/$outputIDabund.txt target=_BLANK1623>Abundance table</a><p>\n";

# Display results
print OUTPUT "<INPUT NAME=\"show_search_motif_button\" TYPE=button VALUE=\"Show motifs\" onClick=\"show_motifs();\">\n";
print OUTPUT "<INPUT NAME=\"show_search_sequence_button\" TYPE=button VALUE=\"Show sequences\" onClick=\"show_sequences();\"><p>\n";
print OUTPUT "<INPUT NAME=\"nMotifs\" TYPE=\"hidden\" VALUE=$nMotifs>\n";
print OUTPUT "<INPUT NAME=\"search\" TYPE=\"hidden\" VALUE=0>\n";

print OUTPUT "<HR NOSHADE COLOR=BLUE></HR>\n";

print OUTPUT "<h3><INPUT NAME=\"search_button\" TYPE=button VALUE=\"Search\" onClick=\"search_sequences();\"> &nbsp; &nbsp; &nbsp; &nbsp; Find sequences</h3>\n";
print OUTPUT "<table border=0>\n";
print OUTPUT "<tr><td><b>Name search:</b><td><input size=20 name=search_term>\n";
print OUTPUT "<td><select name=field>\n";
print OUTPUT "	<option value=default>----- Select -----\n";
print OUTPUT "	<option value=sequence>Sequence name\n";
print OUTPUT "	<option value=symbol>Gene Symbol\n";
print OUTPUT "</select>\n";
print OUTPUT "<tr><td><b>Distance from TSS:</b>\n";
print OUTPUT "<td><select name=distanceTSS><option value=0>No limit<option value=100>100<option value=200>200<option value=500>500<option value=1000>1000<option value=2000>2000<option value=5000>5000<option value=10000>10000<option value=20000>20000<option value=50000>50000<option value=100000>100000<option value=200000>200000\n";
print OUTPUT "</select>\n";
print OUTPUT "</table>\n";

# Make motif selection menu
my @motifs=();
if(!open(INFO, "$PATH_DATA/$filenameMotif")){
	print OUTPUT "Motif file not found!\n";
	print OUTPUT "</HTML>\n";
	exit(0);
}
while(my $line = <INFO>){
	if($line =~ />/){
		$line =~ s/\n$//;
		$line =~ s/^>//;
		my($name,$junk)=split(/\t/,$line);
		push(@motifs,$name);
	}
}
close INFO;
my $select_motifs="<OPTION VALUE=\"\">----- Select motif -----\n";
foreach my $name (sort @motifs){
	$select_motifs .= "<OPTION VALUE=$name>$name\n";
}

print OUTPUT "<table><tr><td>No.<td>Motif<td>From<td>To<td>N hits<td>Conser-<br>vation %<td>Score<td>Strand\n";
for(my $iTF=1; $iTF<=3; ++$iTF){
	print OUTPUT "<tr><td>$iTF.<td><SELECT NAME=TF$iTF>$select_motifs\n";
	print OUTPUT "</SELECT>\n";
	print OUTPUT "<td><input name=startTF$iTF size=7 value=0>\n";
	print OUTPUT "<td><input name=endTF$iTF size=7 value=1000000>\n";
	print OUTPUT "<td>N&ge;<select name=nhitsTF$iTF><option value=1>1<option value=2>2<option value=3>3<option value=5>5<option value=10>10\n";
	print OUTPUT "<td><SELECT name=conservTF$iTF>\n";
	for(my $ic=0; $ic<10; ++$ic){
		my $cons = $ic*10;
		print OUTPUT "<OPTION VALUE=$cons>$cons";
	}
	print OUTPUT "</SELECT>\n";
	print OUTPUT "<td><SELECT name=scoreTF1>\n";
	for(my $is=4; $is<12; ++$is){
		print OUTPUT "<OPTION VALUE=$is>$is";
	}
	print OUTPUT "</SELECT>\n";
	print OUTPUT "<td><SELECT name=strandTF1>\n";
	print OUTPUT "<OPTION VALUE=0>N/A<OPTION VALUE=1>+<OPTION VALUE=-1>-\n";
	print OUTPUT "</SELECT>\n";
	print OUTPUT "<td><input type=button onClick=get_info($iTF); value=\"Motif Info\">\n";
}
print OUTPUT "</TABLE>\n";
print OUTPUT "<b>Combine motifs:</b> <SELECT NAME=combineMotifs>\n";
print OUTPUT "<OPTION VALUE=and>And\n";
print OUTPUT "<OPTION VALUE=or>Or\n";
print OUTPUT "<OPTION VALUE=dist>Distance\n";
print OUTPUT "</SELECT>\n";
print OUTPUT "&nbsp; &nbsp;Max distance: <SELECT NAME=distance><OPTION VALUE=10>10<OPTION VALUE=20>20<OPTION VALUE=50 SELECTED>50<OPTION VALUE=100>100<OPTION VALUE=200>200\n";
print OUTPUT "</SELECT>\n";
print OUTPUT "</FORM>\n";
print OUTPUT "</BODY>\n";
print OUTPUT "</HTML>\n";
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;
}

#***********************************
sub file_exist
#***********************************
{
	if(open (INFO_TEMP, $_[0])){ close INFO_TEMP; 1; }
	else { 0; }
}

