package GeneticCode::Util;
BEGIN{ push(@INC, $ENV{LOCAL_PERL_MODULES}); }
use Carp;
use warnings;
use strict;
use GeneticCode::Tables;
use GeneticCode::IUPAC;

###################################################
sub translate {
    my $dnaSeq = shift or croak "DNA sequence is not specified.";
    my $codeID = shift or croak "Genetic code ID is not specified.";
    my $flgPartial5 = shift;
    my $table = GeneticCode::Tables::getTable($codeID);
    my $initCodons = GeneticCode::Tables::getInitCodons($codeID);
    $dnaSeq = capital( $dnaSeq );
    my $pepSeq;
    for( my $i=0 ; $i<length($dnaSeq) ; $i+=3 ){
	my $codon = substr($dnaSeq, $i, 3);
	next if length($codon)<3;
	my $aa;
	if( !$flgPartial5 and $i==0 ){
	    unless( $initCodons->{$codon} ){
		die "Invalid initiate codon: " . $codon;
	    }
	    $aa = $initCodons->{$codon};
	} else {
	    if( $table->{$codon} ){
		$aa = $table->{$codon};
	    } else {
		if( GeneticCode::IUPAC::isValidCodon($codon) ){
		    $aa = GeneticCode::IUPAC::codon2aa($codon, $table);
		    # print $codon . "\t" . $aa . "\n";
		} else {
		    die "Invalid codon: " . $codon;
		}
	    }
	}
	$pepSeq .= $aa;
    }
    return $pepSeq;
}

###################################################
sub isInitCodon {
    my $codon  = shift;
    my $codeID = shift;
    my $initCodons = GeneticCode::Tables::getInitCodons($codeID);
    return $initCodons->{$codon};
}

###################################################
sub capital {
    my $seq = shift;
    $seq =~ s/a/A/g;
    $seq =~ s/c/C/g;
    $seq =~ s/g/G/g;
    $seq =~ s/t/T/g;
    return $seq;
}

1;
