#!/usr/bin/perl
use strict;
use warnings;
use lib "/usr/share/perl5/Bio";
use Data::Dumper;
use Bio::DB::GenBank;
use Bio::SeqIO;
#use Bio::SeqFeature;
use Bio::SeqFeature::Generic;
use Bio::Graphics;

#read input data
my $input_file = $ARGV[0];
open(DATA, $input_file);
my $head = <DATA>;
my @headers = split /\t/, $head;
my @subset = @headers[1..$#headers];

my %main;

while (<DATA>) {
	my %data;
	chomp;
	my @line = split /\t/;
#print Dumper \@line;
	@data{@subset} = @line[1..$#line]; # assign labels to each field
#print Dumper \%data;
	$main{$line[0]} = \%data;
	}
#print Dumper \%main;

my $gb = new Bio::DB::GenBank; #should only need 1 GenBank connection object
my $refseq;
foreach my $transcript (keys %main) {
	if ($transcript =~ /^NM_/) {
		my $rs = new Bio::DB::RefSeq; #special DB connection for RefSeq Entries
		$refseq = $rs->get_Seq_by_acc($transcript);#retrieve sequence and features for refseq
		my @ref_features = $refseq->all_SeqFeatures;
		
		my %sorted_f;
		for my $f (@ref_features) {
			my $tag = $f->primary_tag;
			push @{$sorted_f{$tag}},$f; #if ($tag eq 'CDS');
			} #end for my $f
		$main{$transcript}{'features'} = \%sorted_f;
		
	} else { #feature handling for alternative transcripts.
		my $alt_seq = $gb->get_Seq_by_acc($transcript);
		my @curr_features = $alt_seq->all_SeqFeatures;
		
		my %sorted_f;
		for my $f (@curr_features) {
			my $tag = $f->primary_tag;
			push @{$sorted_f{$tag}},$f; #if ($tag eq 'CDS');
			} #end for my $f
			
		$main{$transcript}{'features'} = \%sorted_f;
		} #end else
} # end for $transcript
#print Dumper \%main;

#generating basic glyph to hang everything else on. Done once only based on ref_seq.
my $wholeseq = Bio::SeqFeature::Generic->new (
		-start => 1,
		-end => $refseq->length,
		-display_name =>$refseq->display_name
		);

#draw panel
my $panel = Bio::Graphics::Panel->new(
		-length => $refseq->length,
		-key_style => 'between',
		-width => 800,
		-pad_left => 10,
		-pad_right => 10,
		-pad_top => 10,
		-pad_bottom =>10,
		);

#add basic sequence ruler
$panel->add_track($wholeseq,
		  -glyph => 'arrow',
		  -bump => 0,
		  -double => 1,
		  -tick => 2);
		  
my @colors = qw(cyan orange blue purple green chartreuse magenta yellow aqua red);
my $idx = 0;

foreach my $alt_trans (keys %main) {
	foreach my $tag (keys %{ $main{$alt_trans}{'features'} }) {

		my $feature = $main{$alt_trans}{'features'}{$tag};

		$panel->add_track($feature,
				-glyph => 'generic',
				-bgcolor => $colors[$idx++ % @colors],
				-fgcolor => 'black',
				-font2color => 'black',
				-key => $alt_trans,
				-bump => +1,
				-height => 8,
				-label => 1,
				-description => 1,
				) if ($tag eq 'CDS');

}
}

print $panel->png;
exit 0;