#!/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 $in_dir=$args{'i'};


#set default treshold values
my $polyA_treshold=10;


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

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

my $seq_in_file=$in_dir."seqs_fasta.trimmed";
my $qual_in_file=$in_dir."seqs_fasta.trimmed.qual";

my $db='cgn';

my $script_file=__FILE__;


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

my $start_time=time;

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

my %sequences=();

#read in the sequences that haven't been evaluated
my $stm = "select s.seq_id, o.external_id, s.sequence_data, q.quality_values from est_info as e left join sequence as s on e.seq_id=s.seq_id left join sequence_read_quality as q on s.seq_id=q.seq_id left join other_identifier as o on s.seq_id=o.local_db_id where o.external_id_type='1'";
my $sth = $dbh->prepare($stm) 
    || die "Can't prepare statement: $DBI::errstr";
my $rv = $sth->execute
    || die "Can't execute statement: $DBI::errstr";
my ($seq_id, $clone_id, $seq, $qual);
my $rc = $sth->bind_columns(\$seq_id,\$clone_id, \$seq, \$qual);

while ($sth->fetch){
    $sequences{$seq_id}=[$seq, $qual, $clone_id];
}


my %early_polyA=();

foreach (keys %sequences){



    my @seq=split(//,$sequences{$_}[0]);
    my @qual= split (/\s/, $sequences{$_}[1]);
    my $clone=$sequences{$_}[2];

#look for clear polyA tail

    my $i;
    my $a_region_ln=0;
    my $a_region_start=0;
    for ($i=0;$i<@seq;$i++){
	if($seq[$i] eq 'A') {
	    unless($a_region_ln){
		$a_region_start=$i;
	    }
	    $a_region_ln++;
	}
	else{
	    $a_region_ln=0;
	}

	if($a_region_ln==$polyA_treshold){

#see if it starts in the first half of the sequence
	    if($a_region_start<(@seq/4)){
		$early_polyA{$_}=$clone;
	    }
	}

    }

}

foreach (keys %early_polyA){
    print "$early_polyA{$_}\n";
}



#update the database
#foreach (keys %qual_val){
#    $stm = "update sequence set quality_pass='$qual_val{$_}' where seq_id='$_'";
#    $sth = $dbh->prepare($stm) 
#	|| die "Can't prepare statement: $DBI::errstr";
#    $rv = $sth->execute
#	|| die "Can't execute statement: $DBI::errstr";
#}



db_link_coffee::disconnect_db($dbh);



# runtime::runtime_print($start_time, "Database upload");


