#! /usr/bin/perl -w

=head1 NAME

=head1 SYNOPSIS

  perl genbank2cds_aa.pl [-f genbank file] [-o output fasta file] [-h help]

=head1 DESCRIPTION

  This script reads a genbank file and extracts translated CDS. The header is composed by locus_tag|old_locus_tag|protein_id

  
Typical usage is as follows:

  % perl genbank2cds_aa.pl -f test.gb -o output.fa 
  
=head2 Options

The following options are accepted:

 --f=<genbank file>   	(Mandatory).


 --o=<file>		  		Output file (default output.fa)

 --help                   	This documentation.


=head1 AUTHOR

Luca Cozzuto <luca.cozzuto@crg.es> 

=cut
use warnings;
use strict;
use Data::Dumper;
use File::Basename;
use Pod::Usage;
use Getopt::Long;
use Bio::SeqIO;
use Bio::Seq;
use Data::Dumper;

my $USAGE = "perl genbank2cds_aa.pl [-f genbank file] [-o output fasta file] [-h help]";

my ($input_file,$outfile,$length,$symbol,$show_help);

&GetOptions(    	
			'input_file|f=s'	=> \$input_file,
			'outfile|o=s'		=> \$outfile,
			'help|h'        	=> \$show_help
			)
  or pod2usage(-verbose=>2);
pod2usage(-verbose=>2) if $show_help;

if (!$outfile) { $outfile = "output.fa"}
if (!$input_file) { die ("Please specify input file")}


my $seq_in = Bio::SeqIO->new( -format => 'genbank',
                              -file   => $input_file,
                             );


my $seq_out = Bio::SeqIO->new( -file   => ">$outfile",
                               -format => 'Fasta',
                             );



my $seq_object = $seq_in ->next_seq;


for my $feat_object ($seq_object->get_SeqFeatures) {
    if ($feat_object->primary_tag eq "CDS") {
    	my $info =  $feat_object->{'_gsf_tag_hash'};
    	my $header = $info->{"locus_tag"}[0]."|".$info->{"old_locus_tag"}[0]."|".$info->{"protein_id"}[0];
    	my $seq	   = $info->{"translation"}[0];
		
		my $seq_obj = Bio::Seq->new(-seq=>$seq,
                         -display_id => $header,
                         -alphabet => "protein" );
        
		
	    $seq_out->write_seq($seq_obj); 
    }
}

