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

# 0 for normal operation
my $debug = 0;

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

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

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

my %args=();

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

#set defaults for io, script filename, etc
$project or die "Please specify a project (cgn, fgn, pgn) using the -p flag\n";
$tempfile ||= "/data/shared/pgn_data_processing/blast_annotations/${project}/evalue.tmp";

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

#Main body of the script
########################
my $start_time=time;

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

# open temp file for writing
open (TEMP, ">$tempfile");

# get all unigene_blast_result_ids and evalues from unigene_blast_result table
my ($blast_id, $evalue);
my $sth = $dbh->prepare("select unigene_blast_result_id, evalue from unigene_blast_result;") or die "Can't prepare statement: $DBI::errstr";
my $rv = $sth->execute or die "Can't execute statement: $DBI::errstr";
my $rc = $sth->bind_columns(\$blast_id, \$evalue);
while ($sth->fetch){
	print TEMP "$blast_id\t$evalue\n";
}

close(TEMP);

# update new_blast_result table with correct evalues
open(TEMP, "<$tempfile");
my @lines = <TEMP>;
close(TEMP);
foreach my $line (@lines) {
	chop $line;
	my ($blast_id, $evalue) = split(/\t/, $line);
	#$evalue =~ s/e/E/;
	#print "$blast_id <=> $evalue\n";
	$sth = $dbh->prepare("update new_blast_result set evalue='$evalue' where unigene_blast_result_id='$blast_id';") or die "Can't prepare statement: $DBI::errstr";
	my $rv = $sth->execute or die "Can't execute statement: $DBI::errstr";
}

runtime::runtime_print($start_time, "Copying evalues");
db_link::disconnect_db($dbh);

