#!/usr/bin/perl
use strict;
use warnings;
##
## translate_v2.pl
##
##   translating all-frames for a DNA sequence into protein
##   sequence using a standard codon table embeeded in the script code
##

## Variables Declaration and Initialization

our ($dna_seq, $dna_revseq, %CODON_TABLE);

$dna_seq = <<'EOD'; # loading a variable using a HERE-DOC
ACCCGGGTCTCATCCCTTGACCCTGGGAACCGGGTCCACATTGAATCAGGTGCGAATGTT
CGCTCGCCTTCTCTGCCTTTCCCGCCTCCCCTCCCCCGGCCGCGGCCCCGGTTCCCCCCC
TGCGCTGCACCCTCAGAGTTGGCTGCAGCCGGCGAGCTGTTCCCGTCAATCCCTCCCTCC
TTTACACAGGATGTCCATATTAGGACATCTGCGTCAGCAGGTTTCCACGGCCGGTCCCTG
TTGTTCTGGGGGGGGGACCATCTCCGAAATCCTACACGCGGAAGGTCTAGGAGACCCCCT
AAGATCCCAAATGTGAACACTCATAGGTGAAAGATGTATGCGAAGACGGGGGTTGAAAGC
CTGGGGCGTAGAGTTGACGACAGAGCGCCCGCAGAGGGCCTTGGGGCGCGCTTCCCCCCC
CTTCCAGTTCCGCCCAGTGACGTAGGAAGTCCATCCATTCACAGCGCTTCTATAAAGGCG
CCAGCTGAGGCGCCTACTAC
EOD
# closing the HERE-DOC by using SAME marker as the opening one

$dna_seq =~ s/\s+//og; # \s == [ \t\n]
         # here, we remove all the trailing newline chars

( $dna_revseq = reverse $dna_seq ) =~ tr/acgtACGT/tgcaTGCA/;
         # reverse complement

%CODON_TABLE = ();


## Loading Translation Hash

while (<DATA>) {

    next if $_ =~ m/^\#/o;

	my @F = split /\s+/o, $_;

	$CODON_TABLE{$F[0]} = $F[1];

};


## Translate Sequence

foreach my $fr (0, 1) { # Do forward and reverse

	my $seqref = ($fr == 0) ? \$dna_seq : \$dna_revseq;

	printf STDOUT "--> %s Translations:\n",
                  (($fr == 0) ? "FORWARD" : "REVERSE");

	for (my $phase = 0; $phase < 3; $phase++) {

		# translate each phase...
		my $protein_seq = '';

		for (my $i = $phase; $i < length($$seqref); $i += 3) {

			my $codon = substr($$seqref,$i,3);

			last if length($codon) < 3;

			if (defined($CODON_TABLE{$codon})) {

				$protein_seq .= $CODON_TABLE{$codon};

			} else {

				$protein_seq .= 'X'; # Any wildcard provided by
		                             # the corresponding annotation standard...

			};

		}; # for $i

		printf STDOUT "   Phase %d : %s\n", $phase, $protein_seq;

	}; # for $phase

	print STDOUT "\n";

}; # foreach $refseq


## The End
exit(0); # optional, but to be polite with the parent shell...


## Anyting following the '__END__'
 # or '__DATA__' tokens is ignored 
__END__
# Standard Codon Table
TTT F
TTC F
TTA L
TTG L
CTT L
CTC L
CTA L
CTG L
ATT I
ATC I
ATA I
ATG M
GTT V
GTC V
GTA V
GTG V
TCT S
TCC S
TCA S
TCG S
CCT P
CCC P
CCA P
CCG P
ACT T
ACC T
ACA T
ACG T
GCT A
GCC A
GCA A
GCG A
TAT Y
TAC Y
TAA *
TAG *
CAT H
CAC H
CAA Q
CAG Q
AAT N
AAC N
AAA K
AAG K
GAT D
GAC D
GAA E
GAG E
TGT C
TGC C
TGA *
TGG W
CGT R
CGC R
CGA R
CGG R
AGT S
AGC S
AGA R
AGG R
GGT G
GGC G
GGA G
GGG G
