#!/usr/bin/perl -w
#use strict;
use warnings;
use DBI();
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);


my $cgi = new CGI;

my %list_mol=();

my $all_seq = $cgi->param('all');

my $pdb_lst = $cgi->param('pdb');
my $mol_lst = $cgi->param('mol');
my @pdb_al=split /,\s*/,$pdb_lst;
my @mol_al=split /;\s*/,$mol_lst;
for(my $j=0; $j<scalar @pdb_al; $j++){
	my @brk_id=split  /,\s*/,$mol_al[$j];
	for( my $k=0; $k<scalar @brk_id; $k++){
		$list_mol{$pdb_al[$j]}{$brk_id[$k]}=$cgi->param('search');
	}
}

my $upload_fh = $cgi->upload("file");
while(<$upload_fh>){
	chomp $_;
        my @list=split /,\s*/,$_;
        for(my $i=1; $i<scalar @list;$i++){
                $list_mol{$list[0]}{$list[$i]}=$cgi->param('search');
        }

}

print $cgi->header(
  -type => 'application/octet-stream',
  -Content_Disposition => "attachment"
);


#connect to database
#==================
my $dbh=DBI->connect("DBI:mysql:database=HDRNAS;host=localhost", "debasish", "debasish**2014",{'RaiseError'=>1});
if(!$all_seq){
foreach my $k(sort keys %list_mol){
#        print "<div id=\"$k\">";
	my $tmp1="\$fl$k";
        foreach my $p(sort keys %{$list_mol{$k}}){
		my $vth=$dbh->prepare("SELECT variables.mol_org, variables.length, variables.mol_fasta FROM variables WHERE mol_id=\"$k\_$p\"");
                $vth->execute();
		my $ver_prop=$vth->fetchrow_hashref();
                print ">$k | $p | $ver_prop->{'mol_org'} | $ver_prop->{'length'}\n$ver_prop->{'mol_fasta'}\n";
        }
}
}
else{
	my $vth=$dbh->prepare("SELECT variables.mol_org, variables.mol_id, variables.length, variables.mol_fasta FROM variables ");
	$vth->execute();
	while(my $ver_prop=$vth->fetchrow_hashref()){
		my $pdb=$ver_prop->{'mol_id'};
		$pdb=~ s/_\d+//;
		my $id=$ver_prop->{'mol_id'};
		$id=~ s/\w+_//;
		print ">$pdb | $id | $ver_prop->{'mol_org'} | $ver_prop->{'length'}\n$ver_prop->{'mol_fasta'}\n";
	}
}

