#!/usr/bin/perl -w
use strict;
use DBI();
require "toolhead.cgi";
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);


my $cgi=new CGI();

my %input=();

&HEADER("Search Result");

&GOTO_top;

&main_toolbar;

&fetch_form_data;

&CHECKIO;

print <<EOH;
<center style="padding-top:3.5cm;"><div class="body">

EOH
my $query="SELECT DISTINCT constants.pdb_id, constants.resol, variables.mol_typ, variables.mol_org, variables.length, variables.mol_id FROM constants LEFT JOIN variables USING (pdb_id) WHERE ";
#connect to database
#==================
my $dbh=DBI->connect("DBI:mysql:database=HDRNAS;host=localhost", "debasish", "debasish**2014",{'RaiseError'=>1});
my $count=0;
if(exists $input{'org'}){
        if(!$input{'org'}){
#                print"Org id not present<br>";
        }
        else{
		$count++;
		my $org=$input{'org'};
	        my $part1=substr($org,0,1);
	        my $part2=$org;
        	$part2=~ s/\w+\.?\s//;
	        $org="$part1".'%'."$part2";
                $query.=" variables.mol_org LIKE \"$org\"";
#                print"Org $input{'org'} present<br>$query</br>";
        }
}
if(exists $input{'rdoSelect'}){
        if(!$input{'rdoSelect'}){
#                print"Functional RNA not present<br>";
        }
        else{
		my $fun_rna=$input{"rdoSelect"};
		if($count >=1){
		$query.=" AND";
		}
		$count++;
	        if($fun_rna eq "tRNA"){
        	        $fun_rna.="-$input{'tRNA'}";
	        }
        	if($fun_rna eq "rRNA" ){
                	$fun_rna.="-$input{'rRNA'}";
	        }
                $query.=" variables.mol_typ LIKE \"$fun_rna\"";
#                print"Functional RNA $input{'rdoselect'} present<br>$query</br>";
        }
}
if(exists $input{'seq'}){
        if(!$input{'seq'}){
#                print"Sequence not present<br>";
        }
        else{
                if($count >=1){
                $query.=" AND";
                }
		$count++;
                $query.=" variables.mol_fasta LIKE \"\%$input{'seq'}\%\"";
#                print"Sequence $input{'seq'} present<br>$query</br>";
        }
}
if(exists $input{"nddt"} || exists $input{"stdt"}){
	if(!$input{"nddt"} && !$input{"stdt"}){
#                print"Time Period not present<br>";
        }
        else{
		my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	        my $yyyymmdd = sprintf "%.4d-%.2d-%.2d", $year+1900, $mon+1, $mday;
        	my $strt=$input{"stdt"}||'1978-04-12';
	        my $end=$input{"nddt"}||$yyyymmdd;
        	$strt=~ s/\//\-/g;
	        $end=~ s/\//\-/g;
                if($count >=1){
                $query.=" AND";
                }
                $count++;
                $query.=" constants.d_o_ent BETWEEN \"$strt\" AND \"$end\"";
#                 print"date BETWEEN $strt AND $end present<br>$query</br>";
        }
}
if(exists $input{'auth'}){
        if(!$input{'auth'}){
#                print"Author not present<br>";
        }
        else{
                if($count >=1){
                $query.=" AND";
                }
                $count++;
                $query.=" constants.auth LIKE \"\%$input{'auth'}\%\"";
#                 print"Author $input{'auth'} present<br>$query</br>";
        }
}
if(exists $input{"minres"} || exists $input{"maxres"}){
        if(!$input{"maxres"} && !$input{"minres"}){
#                print"Resolution not present<br>";
        }
	else{
		my $l_res=$input{"minres"} || '0';
        	my $h_res=$input{"maxres"} || '10';
                if($count >=1){
                $query.=" AND";
                }
                $count++;
		$query.=" constants.resol < \"$h_res\" AND resol > \"$l_res\"";
#        	print"Resolution BETWEEN $l_res AND $h_res present<br>$query</br>";
        }
}
my %pdb_hash=();
my $pdb_cnt=0;
if(exists $input{'pdb'}){
        if(!$input{'pdb'}){
#                print"PDB id not present<br>";
        }
        else{
		my $id_list=$input{'pdb'};
	        my @list=split /,\s*/,$id_list;
		$pdb_cnt++;
		foreach my $k(@list){
			$pdb_hash{$k}=1;
		}
#                $query.="constants.pdb_id LIKE \"$input{'pdb'}\"";
#                 print"PDB id $input{'pdb'} present<br>$query</br>";
        }
}
my $non_red_cnt=0;
if(exists $input{'search'}){
        $non_red_cnt++;
        $query=~s /variables/nonreduns/g;
#        print "$input{'search'}</br>$query</div>";
}

if($count >=1){
my $ath=$dbh->prepare("$query");
$ath->execute();
print <<EndOfTBL;
<center><table width=100% class=curvedEdges cellspacing=10 style="border:2px solid #199">
<tr>
<th width=10%><font color="#993366">PDB ID</font></th><th width=10%><font color="#993366">Mol ID</font></th><th width=10%><font color="#993366">Length</font></th><th width=30%><font color="#993366">Molecule Description</font></th><th width=30%><font color="#993366">Organism</font></th><th width=10%><font color="#993366">Resolution in &#197;</font></th>
EndOfTBL
while(my $all_prop=$ath->fetchrow_hashref()){
	my $id_mol=$all_prop->{'mol_id'};
	$id_mol=~ s/^\w+_//;
	my $org= lc$all_prop->{'mol_org'};
	$org=ucfirst $org;
	if($pdb_cnt >=1){
		if(exists $pdb_hash{$all_prop->{'pdb_id'}}){
			print "<tr><th><a href=\"./sql_search_dtbs?pdb=$all_prop->{'pdb_id'}\">$all_prop->{'pdb_id'}</a></th><th>$id_mol</th><th>$all_prop->{'length'}</th><th>$all_prop->{'mol_typ'}</th><th><i>$org</i></th><th>$all_prop->{'resol'}</th></tr>";
#		        print "$all_prop->{'pdb_id'} == $all_prop->{'resol'} == $all_prop->{'length'} == $all_prop->{'mol_org'} == $all_prop->{'mol_typ'} == $id_mol </br>";
		}
	}
	else{
		print "<tr><th><a href=\"./sql_search_dtbs?pdb=$all_prop->{'pdb_id'}\">$all_prop->{'pdb_id'}</a></th><th>$id_mol</th><th>$all_prop->{'length'}</th><th>$all_prop->{'mol_typ'}</th><th><i>$org</i></th><th>$all_prop->{'resol'}</th></tr>";
#		print "$all_prop->{'pdb_id'} == $all_prop->{'resol'} == $all_prop->{'length'} == $all_prop->{'mol_org'} == $all_prop->{'mol_typ'} == $id_mol </br>";
	}
}
print "</tr></table>";
$ath->finish();
}
else{
print<<Tab;
<div style="width: 100%; margin: 0 auto; padding: 20px 0 0px;">
        <ul class="tabs" data-persist="true">
Tab
foreach my $id(keys %pdb_hash){
	print "<li><a href=\"#$id\">$id</a></li>\n";
}
print"</ul>\n<div class=\"tabcontents\">\n";
foreach my $id(keys %pdb_hash){
                $id=uc$id;
		my $id_low=lc $id;
                my $cth=$dbh->prepare("SELECT * FROM constants WHERE pdb_id=\"$id\"");
                $cth->execute();
                my $con_prop=$cth->fetchrow_hashref();
		my $query=();
		if($non_red_cnt >=1){
			$query="SELECT * FROM nonreduns WHERE pdb_id=\"$id\"";
		}
		else{
	                $query="SELECT * FROM variables WHERE pdb_id=\"$id\"";
		}
                my $vth=$dbh->prepare("$query");
                $vth->execute();
                if(!$con_prop->{'pdb_id'}){
                print "<div id=\"$id\">";
                &return_error (500, "Data Not Available ",
                "Sorry we do not have the data you are looking for ! Please Try again.</div>");
                }
                else{
                print "<div id=\"$id\">";
print<<EndOfLast;
<table width=100% class="curvedEdges" cellspacing=10>
<tr>
<td> 
        <ul>
<font align=left>
<br>
<!--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!-->
<!--                 USE OF DROPDOWN MENU             -->
<!--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!-->

<!-- USE OF JAVA SCRIPT--- SO JAVA SCRIPT SHOULD BE ENABLED-->
<!--_____________________________________________________________________________________________________-->
<form class="dropDown">
<b><font color="#000000"><img src="http://127.0.0.1/HD-RNAS/view.png" border="0" height="25" width="20">&nbsp;&nbsp;View File &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font></b>
<select onchange="window.open(this.value,'','');" style="background-color:#abf;">
        <option value="">Select Type</option>
        <OPTION VALUE="http://www.rcsb.org/pdb/files/fasta.txt?structureIdList=$id">FASTA</OPTION>
        <OPTION VALUE="http://www.rcsb.org/pdb/files/$id.pdb">PDB (.txt)</OPTION>
        <OPTION VALUE="http://www.rcsb.org/pdb/files/$id.PDB? headerOnly=YES">PDB(header only)</OPTION>
        <OPTION VALUE="http://www.rcsb.org/pdb/files/$id.cif">mmCIF </OPTION>
        <OPTION VALUE="http://www.rcsb.org/pdb/files/$id.cif? headerOnly=YES">mmCIF(header only)</OPTION>
        <OPTION VALUE="http://www.rcsb.org/pdb/files/$id.xml">XML</OPTION>
        <OPTION VALUE="http://www.rcsb.org/pdb/files/$id.xml? headerOnly=YES">XML(header only)</OPTION>
</select>
</form>
<!---------------------------------------------------------------------------------------------------!-->
<!---------------------------------------------------------------------------------------------------!-->
<!--USE OF DROP DOWN USING GO BUTTON!-->
<form>
<b><font color="#000000"><img src="http://127.0.0.1/HD-RNAS/down.png" border="0" height="20" width="20">&nbsp;&nbsp;Download File </font></b>
<select onchange="window.open(this.value,'','');" style="background-color:#abf;">
<option value="">Select Type</option>
<OPTION VALUE="http://www.rcsb.org/pdb/downloadFile.do?fileFormat=fasta&amp;compression=NO&amp;structureId=$id">FASTA (.txt)</OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/downloadFile.do?fileFormat=pdb&amp;compression=NO&amp;structureId=$id">PDB (.txt)</OPTION>
<OPTION value="http://www.rcsb.org/pdb/files/$id.pdb.gz">PDB format(.gz)</OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/files/downloadFile.do?headerOnly=YES&amp;fileFormat=pdb&amp;compression=NO&amp;structureId=$id">PDB(header only)</OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/files/downloadFile.do?fileFormat=cif&amp;compression=NO&amp;structureId=$id">mmCIF </OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/files/$id.cif.gz">mmCIF(.gz)</OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/files/downloadFile.do?headerOnly=YES&amp;fileFormat=cif&amp;compression=NO&amp;structureId=$id">mmCIF(header only)</OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/files/downloadFile.do?fileFormat=xml&amp;compression=NO&amp;structureId=$id">XML</OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/files/$id.xml.gz">XML (.gz)</OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/files/downloadFile.do?headerOnly=YES&amp;fileFormat=xml&amp;compression=NO&amp;structureId=$id">mmCIF(header only)</OPTION>">XML (header only)</OPTION>
<OPTION VALUE="http://www.rcsb.org/pdb/files/$id.pdb1.gz">Biological Assembly(gz)</OPTION>
</select>
</form>
<!--------------------------------------------------------------------------------------------------------->
<form class="dropDown">
<b><font color="#000000">External Links &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font></b>
<select onchange="window.open(this.value,'','');" style="background-color:#abf;">
        <option value="">Select Type</option>
        <OPTION VALUE="http://www.cathdb.info/pdb/$id_low">CATH / Gene3D</OPTION>
        <OPTION VALUE="http://dx.doi.org/ $con_prop->{'doi'}">DOI</OPTION>
        <OPTION VALUE="http://ndbserver.rutgers.edu/service/ndb/atlas/summary?searchTarget=$id_low">NDB</OPTION>
        <OPTION VALUE="http://www.rcsb.org/pdb/explore/explore.do?structureId=$id_low">PDB</OPTION>
        <OPTION VALUE="http://www.ncbi.nlm.nih.gov/pubmed/1857417"> $con_prop->{'pubmed'} </OPTION>
        <OPTION VALUE="http://scop.mrc-lmb.cam.ac.uk/scop/search.cgi?ver=1.75&key=$id_low">SCOP</OPTION>
</select>
</form>
<!--------------------------------------------------------------------------------------------------------->
<form class="dropDown" >
<b><font color="#000000">3D Visualization &nbsp;&nbsp;&nbsp;</font></b>
<select onchange="window.open(this.value,'','');" style="background-color:#abf;">
        <option value="">Select Type</option>
        <OPTION VALUE="http://rna.bgsu.edu/FR3D/AnalyzedStructures/$id/index.html">FDR3</OPTION>
        <OPTION VALUE="http://www.rcsb.org/pdb/explore/jmol.do?structureId=$id">PDB-Jmol</OPTION>
        <OPTION VALUE="http://www.proteopedia.org/wiki/index.php/$id_low">Proteopedia-Jmol</OPTION>
        <OPTION VALUE="http://scop.mrc-lmb.cam.ac.uk/scop/rsgen.cgi?chime=1;pd=$id_low;pr=a:8-338">SCOP-Chime </OPTION>
</select>
</form>
</br>
</br>
<!--________________________________________________________________________________________________________-->
<font color=#000000><b>PDB ID:</b></font> $con_prop->{'pdb_id'}</br>
<font color=#000000><b>NDB ID:</b></font> $con_prop->{'ndb_id'}</br>
<font color=#000000><b>RCSB ID:</b></font> $con_prop->{'rcsb_id'}</br>
<font color=#000000><b>BMRB ID:</b></font> $con_prop->{'bmrb_id'}</br>
<font color=#000000><b>Molecule Title:</b></font> $con_prop->{'title'}</br>
<font color=#000000><b>Molecule Type:</b></font> $con_prop->{'dscrptr'}</br>
<font color=#000000><b>Release Date:</b></font> $con_prop->{'d_o_ent'}</br>
<font color=#000000><b>Revised Date:</b></font> $con_prop->{'d_o_rev'}</br>
<font color=#000000><b>Experiment:</b></font> $con_prop->{'expr'}</br>
<font color=#000000><b>Resolution:</b></font> $con_prop->{'resol'}</br>
<font color=#000000><b>R-value:</b></font> $con_prop->{'rval_free'}</br>
<font color=#000000><b>Primary Citation:</b></font> 
$con_prop->{'pri_cit'} $con_prop->{'journal'} , $con_prop->{'issn'}, $con_prop->{'page'}, $con_prop->{'year'},$con_prop->{'auth'}.</br></br>
<a href="http://nucleix.mbu.iisc.ernet.in/nuparm/nuparm.shtml"><b>Structural Parameter using : NUPARM<b></a>
<br><br>
<a href="http://www.saha.ac.in/biop/cgi-bin/bpfind_check.cgi?file=$id"><b>Secondary Structural using : bpfind<b></a>

</font>
        </ul>
</td>


<td>
</br>
<center><table class="curvedEdges" cellspacing=10>
<tr>
<th width=20%><font color="#993366">Chain ID</font></th><th width=20%><font color="#993366">Length</font></th><th width=20%><font color="#993366">Type</font></th><th width=20%><font color="#993366">Source</font></th><th width=20%><font color="#993366">Sequence</font></th>
</tr>           

EndOfLast
while (my $ver_prop=$vth->fetchrow_hashref()){
	my $idm=$ver_prop->{'mol_id'};
	$idm=~ s/^\w+_//;
	print "<tr><th>$idm</th><th>$ver_prop->{'length'}</th><th>$ver_prop->{'mol_typ'}</th><th>$ver_prop->{'mol_org'}</th><th><a href=\"../../cgi-bin/download?pdb=$id&mol=$idm\">sequence</a></th></tr>";
}
print "</table></br></td>\n</table>\n</div>";
                }
        $cth->finish();
        $vth->finish();
        }
print"</div></div></div></centre>";
$dbh->disconnect();



}
print  "</div>";
#)()())()())()()()())()())())()()()()()))()()()()(()
#()()()()())())()())()())()()()()()()()())()()()()()()
&FOOTER;
#----------------------------------
sub fetch_form_data {
for my $key ( $cgi->param() ) {
    $input{$key} = $cgi->param($key);
}
}
#------------------------------------------
sub CHECKIO {
foreach my $key (keys %input) {
    if ($input{$key}  =~ /[;><&\*\`\|]/ ) {
      &return_error (500, "The SINP data checker ",
      "Sorry your illegal characters have been caught and discarded.");
    }
}
}
#------------------------------------------
sub return_error
{
my $status=$_[0];
my $keyword=$_[1];
my $message=$_[2];
my $webmaster = '<i><font color=#33CCFF>dhananjay.bhattacharyya[AT]saha.ac.in</font></i>';


    print <<End_of_Error;
<center>
<h1 style="color:red;">$keyword</h1>
<hr>$message</hr>
Please contact $webmaster for more information.
</center>
End_of_Error

    exit(1);
}
1;
