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

use lib '/soldb/local_scripts/custom_packages';

#local packages to use
use runtime;
use db_link_coffee;
use GD;

unless (@ARGV){
    print "Input missing, try:\n\t ./lib_histogram_draw.pl -l lib_name -o imagefile.png\n";
    exit;
}
my @arg_pairs = split (/\-/, (join ' ', @ARGV));

my %args=();

foreach (@arg_pairs){

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

my $lib=$args{'l'};
my $out_file=$args{'o'};

my $db='cgn';

#get the library numbers from db

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

my %contig_data=();

#pull the contigs (>=2 members)
my $stm = "select l.nr_components from lib_assembly as l, est_library as e where l.est_library_id=e.est_library_id and e.library_name='$lib'";
my $sth = $dbh->prepare($stm) 
    || die "Can't prepare statement: $DBI::errstr";
my $rv = $sth->execute
    || die "Can't execute statement: $DBI::errstr";
my ($nr_comp);
my $rc = $sth->bind_columns(\$nr_comp);

while ($sth->fetch){
    $contig_data{$nr_comp}++;
}


#pull the singlets
$stm = "select s.seq_id from lib_assembly_singleton as s, est_library as e where s.est_library_id=e.est_library_id and e.library_name='$lib'";
$sth = $dbh->prepare($stm) 
    || die "Can't prepare statement: $DBI::errstr";
$rv = $sth->execute
    || die "Can't execute statement: $DBI::errstr";
my ($seq_id);
$rc = $sth->bind_columns(\$seq_id);

while ($sth->fetch){
    $contig_data{1}++;
}

#close the db connection
db_link_coffee::disconnect_db($dbh);


my @freq_list = sort {$b<=>$a} keys %contig_data;
my @count_list= sort {$contig_data{$b}<=>$contig_data{$a}} keys %contig_data;

my $max_freq=$freq_list[0];
my $max_count=$contig_data{$count_list[0]};


#foreach (@freq_list){
#    print "$_:\t $contig_data{$_}\n";
#}
#print "$max_freq\n";
#print "$max_count\n";


#calculate the image dimensions, max width=720 - 20 on each side
my $x_max=720;
my $left_buffer=40;
my $right_buffer=40;
my $bottom_buffer=40;
my $top_buffer=40;
my $y_step=20;
my $tickmark_length=10;
my $font_x_offset=5;
my $font_y_offset=5;
my $percent_step=1;
my $bar_width=10;

#set total to signify 100%, then set max height to twice second tallest one's percentage
my $total_seq=0;
foreach (keys %contig_data){
    $total_seq+=$contig_data{$_};
}

my $y_max=$contig_data{$count_list[1]} / $total_seq * 100 * $y_step * 2;

#calculate the x step based on the number of possible frequency ticks
my $x_step= int (($x_max-$left_buffer-$right_buffer) / $max_freq);



 # create a new image
    $im = new GD::Image($x_max,$y_max);

# allocate some colors
    $white = $im->colorAllocate(255,255,255);
    $black = $im->colorAllocate(0,0,0);       
    $red = $im->colorAllocate(255,0,0);      
    $blue = $im->colorAllocate(0,0,255);

# make the background transparent and interlaced
    $im->transparent($white);
    $im->interlaced('true');

# Put a blue frame around the picture
    $im->rectangle(0,0,$x_max-1,$y_max-1,$blue);

#write the library name in the upper right corner

my $lib_text="Library: $lib";
my $font_height=gdMediumBoldFont->height;
my $font_width=gdMediumBoldFont->width;
my $libname_x=$x_max-$right_buffer-$font_width*(length $lib_text);
my $libname_y=$top_buffer;

$im->string(gdMediumBoldFont,$libname_x, $libname_y,$lib_text,$black);


#draw the x axis
$im->line($left_buffer, $y_max-$bottom_buffer, $x_max-$right_buffer, $y_max-$bottom_buffer, $black);


#draw and mark the x tick marks
my $x;
my $freq_nr=1;
for ($x=$left_buffer+$x_step;$x<=$x_max-$right_buffer; $x+=$x_step){
    $im->line($x, $y_max-$bottom_buffer-($tickmark_length/2), $x, $y_max-$bottom_buffer+($tickmark_length/2), $black);

    my $font_height=gdSmallFont->height;
    my $font_width=gdSmallFont->width;
    my $string_x=$x-(($font_width * (length $freq_nr))/2);
    my $string_y=$y_max-$bottom_buffer+($tickmark_length/2)+$font_y_offset;

    $im->string(gdSmallFont,$string_x, $string_y,$freq_nr,$black);
    $freq_nr++; 

}

#draw the y axis
$im->line($left_buffer, $y_max-$bottom_buffer, $left_buffer, $top_buffer, $black);


#draw and mark the y tick marks
my $y;
my $percent_nr=$percent_step;

for ($y=$y_max-$bottom_buffer-$percent_step*$y_step; $y>$top_buffer; $y-=$percent_step*$y_step){

    $im->line($left_buffer-($tickmark_length/2), $y, $left_buffer+($tickmark_length/2), $y, $black);

    my $font_height=gdSmallFont->height;
    my $font_width=gdSmallFont->width;
    my $string_x=$left_buffer-$font_x_offset-($tickmark_length/2)-(($font_width * ((length $percent_nr) + 1)));
    my $string_y=$y-($font_height/2);

    $im->string(gdSmallFont,$string_x, $string_y,$percent_nr.'%',$black);
    $percent_nr+=$percent_step;
}

#draw the histogram
my $i=1;
for ($x=$left_buffer+$x_step;$x<=$x_max-$right_buffer; $x+=$x_step){

    $contig_data{$i} or ($i++ and next);

    my $bar_height=int($contig_data{$i} / $total_seq * 100 * $y_step);

    if ($bar_height > $y_max){
	$im->filledRectangle($x-($bar_width/2), $y_max * 0.25, $x+($bar_width/2),$y_max-$bottom_buffer , $blue);
	
	my $font_height=gdSmallFont->height;
	my $font_width=gdSmallFont->width;
	my $string_x=$x-(($font_width * ((length $bar_height) + 1)))/2;
	my $string_y=$y_max * 0.25-$font_y_offset-$font_height;

	$im->string(gdSmallFont,$string_x, $string_y,$bar_height/$y_step.'%',$red);

	$im->filledRectangle($x-($bar_width/2), $top_buffer, $x+($bar_width/2),$y_max * 0.25 - $font_y_offset * 2 - $font_height , $blue);

	$i++;
	next;

    }

    $im->filledRectangle($x-($bar_width/2), $y_max-$bottom_buffer-$bar_height, $x+($bar_width/2),$y_max-$bottom_buffer , $blue);

    my $font_height=gdSmallFont->height;
    my $font_width=gdSmallFont->width;
    my $string_x=$x-(($font_width * ((length $bar_height/$y_step) + 1)))/2;
    my $string_y= $y_max-$bottom_buffer-$bar_height-$font_y_offset-$font_height;
    
    $im->string(gdSmallFont,$string_x, $string_y,$bar_height/$y_step.'%',$red);


    $i++;


}

# make sure we are writing to a binary stream
    binmode STDOUT;

# Convert the image to PNG and print it on standard output
    print $im->png;

