use strict;

############################
#BEGIN myGenome
{

#directive stuff
package myGenome;
require Exporter;
#add any paths for use/require directives

use lib "/usr2/people/khuang/bin/Genomics/Perl/modules";

#any other modules needed
use GenomicsUtils;
setDebug(10);
#exporting not all that important with objects/classes (I *think*)
our @ISA = qw(Exporter);
our @EXPORT = qw(); #export by default
our @EXPORT_OK = qw(); #export by request

#symbol list: list re/evant symbols here


#load data files

sub BEGIN()
{
#METHOD PROTOTYPES - put method prototypes here in order to have
#them executed at the time the module is compiled
}


########################

#put actual functions here

#must have a new function
sub new()
{
    my $self = {};
    bless $self;

    return($self);
}

#must have a DESTROY function
sub DESTROY()
{
}


## fasta2hash(), gets a fasta file and return a reference of a hash with fasta headers
sub fasta2hash($){
    my $fastaF = shift;
    my $header = "";
    my %hash = ();
    open FASTA, "$fastaF" or die "Can't open $fastaF: $!\n";
    
    while (<FASTA>){
	s/\n//;
	if (/>/){
	    s/>//;
	    $header = $_;
	}
	else{
	    $hash{$header}.=$_;
	}
    }
    close FASTA;
    #map{print $_."\t".substr($hash{$_}, 0, 5)."\n" if $_ =~ /2662206_fasta.screen.Contig619/} keys %hash;
    return \%hash;
}

sub model2hash($$$){
    my ($modelF, $source, $scaffoldsR) = @_;
    my %hash = ();
    if ($source eq "Critica"){

	open CRITICA, "$modelF" or die "Can't open $modelF: $!\n";
	my @out = <CRITICA>;
	close CRITICA;
	    
	foreach my $scaffold (keys %$scaffoldsR){
#	    print $scaffold."&&&&\n";
	    my $genomeSeq = $scaffoldsR->{$scaffold};
#	    print length($genomeSeq)."****\n";
#	    my @models = grep {/^Desulfovibrio\W/} @out;
	    my @models = grep {/^\s*$scaffold\W/} @out;
	    foreach my $model (@models){
		#print $model."===\n";
		$model =~ s/^\s+//;
		my @temp = split /\s+/, $model; #$temp[3] and $temp[4] are the positions
		my $strand = $temp[3]<$temp[4]?'+':'-';
		my $start = $strand eq '+'?$temp[3]:$temp[4];
		my $end = $strand eq '+'?$temp[4]:$temp[3];
		#Critica starts counting position from 1, substr starts from 0 !!
		# substr($genome, $offset, $length)
		my $transcript = substr($genomeSeq, ( $start-1 ), ( $end-$start+1 ));
		if ($strand eq '-'){
		    #reverse complement for genes on minus strand:
		    $transcript = GenomicsUtils::reverseComplement($transcript);
		}
		my $protein = GenomicsUtils::translation($transcript);
		$protein =~ s/\*//;
		$hash{$scaffold}{$start} = join "\t", $strand, $start, $end, $transcript, $protein;
		print join "\t", $strand, $start, $end."====\n";
		#die;
	    }

	}
	
	
    }
    return \%hash;
    ## %hash is a hash of arrays, keys are scaffold headers, each scaffold has an array of models

}

} #END GENOMICS
###########################

return 1;
