#!/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 db_link;
use projects;
use runtime;

@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_file=$args{'i'};
my $out_file=$args{'o'};
my $project=$args{'p'};


$project or die "Please specify a project (cgn, fgn, pgn) using the -p flag\n";

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


#set defaults for io, script filename, etc
$out_file ||= "$in_file.gc_content";


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


open FILEIN, $in_file or die "Couldn't open $in_file\n";
my @clone_ids;
while(<FILEIN>){
    chomp;
    push @clone_ids, $_;
}
close FILEIN;


# 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);

open FILEOUT, ">$out_file" or die "can't open $out_file for write\n";

foreach (@clone_ids){
    $stm = "select em.gc_content from est_metadata as em, other_identifier as o where em.seq_id=o.local_db_id and o.external_id='$_' and o.external_id_type='1'";
    
    $sth = $dbh->prepare($stm) 
	|| die "Can't prepare statement: $DBI::errstr";
    $rv = $sth->execute
	|| die "Can't execute statement: $DBI::errstr";
    my $gc_content;
    $rc = $sth->bind_columns(\$gc_content);
    $sth->fetch and print FILEOUT "$gc_content\n";

}

close FILEOUT;

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

