#!/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>';

#local packages to use
use runtime;
use db_link;
use projects;

if (!$ARGV[0] || $ARGV[0] eq "help") {
    print <<EOF;

    Quick script to return a tab-delimited file for the specified EST 
	library with the following information on each line:
	<est_id> <raw_sequence> <raw_quality> <trimmed_sequence> <trimmed_quality>
	
	Enter 'all' as the library name to output one file for each library.
	
    Usage: $0 -p <project> -l <library_name | all> [ -o <outfile dir> ]

EOF
    exit -1;
}

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

my %args=();

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

my $project=$args{'p'};
my $lib=$args{'l'};
my $out_prefix=$args{'o'};

$project or die "Please specify a project (cgn, fgn, pgn) using the -p flag\n";
$lib or die "No library specified, try '-l library_name (-l all to process all libraries)'\n";
$out_prefix||="/tmp/";

my ($db, $usr) = @{projects::get_db_info($project)};
$db or die "No known database for project $project";

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

my $start_time=time;

# try to open the database
my $dbh = db_link::connect_db($db, $usr) or die "couldn't open database link\n";
my ($stm, $sth, $rv, $rc);

# fill an array with each library which will be processed (this only 
# matters if 'all' was entered)
my @libraries;
if ($lib eq 'all') {
	my $ql = $dbh->prepare("select library_name from est_library where library_name!='all';");
	$ql->execute();
	while(my ($library_name) = $ql->fetchrow_array()) {
		push @libraries, $library_name;
	}
}
else {
	push @libraries, $lib;
}

foreach (@libraries) {
	my $out_file = $out_prefix."/est-".$_.".txt";
	open OUT, ">$out_file" or die "Can't open $out_file for writing: $!\n";
	my $qd = $dbh->prepare("select o.external_id, e.seq_id, q.qual_criteria_id, rs.sequence_data, rq.quality_values, ts.sequence_data, tq.quality_values from est_library as l left join est_info as e on l.est_library_id=e.est_library_id left join raw_sequence as rs on e.seq_id=rs.seq_id left join raw_sequence_quality as rq on e.seq_id=rq.seq_id left join trimmed_sequence as ts on e.seq_id=ts.seq_id left join trimmed_sequence_quality as tq on e.seq_id=tq.seq_id left join other_identifier as o on o.local_db_id=e.seq_id left join quality_evaluation as q on e.seq_id=q.seq_id  where l.library_name='$_' and o.external_id_type='1';");
	$qd->execute();
	while(my ($e_id, $i_id, $q, $rs, $rq, $ts, $tq) = $qd->fetchrow_array()) {
		print OUT "$e_id\t$i_id\t$q\t$rs\t$rq\t$ts\t$tq\n";
	}
	close OUT;
}

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

runtime::runtime_print($start_time, "EST dump for $lib");
