#!/usr/bin/perl -w
use strict;

#person in charge of this script
#this should be the person currently in charge of scripts for the SGN project
my $script_maintainer='Teri Solow <tms45@cornell.edu>';

use lib '/soldb/local_scripts/custom_packages';

#local packages to use
use runtime;
use db_link_coffee;


@ARGV or print "No input parameters, proceeding with default.\n";

my @arg_pairs = split (/\-/, (join ' ', @ARGV));

my %args=();

foreach (@arg_pairs){

    $_ or next;
    my ($flag, $val)=split /\s+/;
    $args{$flag}=$val;
}

my $lib=$args{'l'};
my $out_dir=$args{'o'};



$lib or die "No library specified, try '-l library_name'\n";

#set defaults for io, script filename, etc
$out_dir ||= "/tmp/";

#uniform trailing slashes
$out_dir=~/\/$/ or $out_dir.='/';

my $out_file=$out_dir."$lib";
my $db='cgn';
my $blastexecdir='/usr/local/sbin/';

my $script_file=__FILE__;


#main body of script
#####################

my $start_time=time;

open FILEOUT, ">$out_file";

# try to open the database
my $dbh = db_link_coffee::connect_db($db);


#pull all sequences and relevant information for this library
my ($seq_id, $seq, $clone_name, $organism, $tissue);
my %sequences=();

my $stm = "select s.seq_id, s.sequence_data, c.external_id, o.organism_name, l.tissue from sequence as s, est_info as e, est_library as l, other_identifier as c, organism as o where l.library_name='$lib' and l.est_library_id=e.est_library_id and l.organism_id=o.organism_id and e.seq_id=c.local_db_id and c.external_id_type='1' and e.seq_id=s.seq_id and s.quality_pass='2'";
my $sth = $dbh->prepare($stm) 
    || die "Can't prepare statement: $DBI::errstr";
my $rv = $sth->execute
    || die "Can't execute statement: $DBI::errstr";
my $rc = $sth->bind_columns(\$seq_id, \$seq, \$clone_name, \$organism, \$tissue);

while ($sth->fetch){
    print FILEOUT ">$seq_id | $clone_name - $organism $tissue\n$seq\n";
}

#close the database link
db_link_coffee::disconnect_db($dbh);



#running formatdb on the fasta sequences
$start_time=time;
my $syscmd=$blastexecdir."formatdb -i $out_file -p F -o T";
system($syscmd);
