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

use db_link;
use projects;

my @arg_pairs = split (/\-/, (join ' ', @ARGV));
my %args=();
my @unigene_build_ids;
foreach (@arg_pairs){
	$_ or next;
	my ($flag, @val)=split /\s+/;
	$args{$flag}=$val[0];
}
my $project=$args{'p'};
my $out_prefix=$args{'o'};

$project or die "You must set the project with the -p flag.\n";
$out_prefix||="/tmp/";

my $outfile = $out_prefix."${project}_unigene_builds.txt";

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

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

my %builds=();
my ($build_id, $org, $build_nr, $build_date, $ungene_count);

# get information for each build
my $stm = "select b.unigene_build_id, o.organism_name, b.build_nr, b.build_date  from unigene_build as b, organism as o where b.organism_id=o.organism_id";
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(\$build_id, \$org, \$build_nr, \$build_date);
while ($sth->fetch) {
	push @{$builds{$build_id}}, ($org, $build_nr, $build_date);
}
$sth->finish;

# get number of unigenes for each build
my $unigene_count;
foreach (keys %builds){
	$stm = "select count(unigene_id) from unigenes where unigene_build_id='$_'";
	$sth = $dbh->prepare($stm)
	|| die "Can't prepare statement: $DBI::errstr";
	$rv = $sth->execute
	|| die "Can't execute statement: $DBI::errstr";
	$rc = $sth->bind_columns(\$unigene_count);
	if ($sth->fetch){
		push @{$builds{$_}}, $unigene_count;
	}
	$sth->finish;
}

db_link::disconnect_db($dbh);

# print output file
open (F, ">${outfile}") || die "Can't open ${outfile}";
foreach (sort {$b <=> $a} keys %builds){
	print F "$_\t$builds{$_}[0]\t$builds{$_}[1]\t$builds{$_}[2]\t$builds{$_}[3]\n";
}
