BEGIN{
    $ENV{'PATH'}=$ENV{'PATH'}.":/local/workspace01/zhangju/script/perl";
    push(@INC,"/local/workspace01/zhangju/script/perl");
}

use Bio::SeqIO;
use Bio::Seq;
use strict;
use File::Fetch;

sub each_gbk_protein_fasta{
	my $gbk_file=shift;
	my $fasta=shift;
	my $hash_name=shift;
	my %locus_table = %$hash_name;
	my $ftp_prefix="ftp://ftp.ncbi.nih.gov/genomes/Bacteria/";
	my $url=$ftp_prefix.$gbk_file;
	my $gbk=(split(/\//,$gbk_file))[1];
	my $ff = File::Fetch->new(uri => $url);
	my $where = $ff->fetch() or die $ff->error;
	if (!(-e $gbk)){
		print "Genbank file does not exist.\n";
		exit -1;
	}
	my $format="genbank";
	my $seqio_object=Bio::SeqIO->new(-file=>$gbk, -format=>$format);
	open(ParseFile,">".$fasta);
	my $seq_object = $seqio_object->next_seq;
	for my $feat_object ($seq_object->get_SeqFeatures) { 
	    if ($feat_object->primary_tag eq "CDS"){
	        my $tag_value=($feat_object->get_tag_values('locus_tag'))[0];
	        if (exists $locus_table{$tag_value}){
	        	my $translate=($feat_object->get_tag_values('translation'))[0];
	        	$locus_table{$tag_value}=$translate;
	        	my $seq_obj = Bio::Seq->new(-seq => $feat_object->spliced_seq->seq, -alphabet => 'dna' );
	        	my $prot_obj = $seq_obj->translate(-codontable_id => 11);
	        	if ($prot_obj->seq ne $translate){#."*"){
	        		print "discrepany\n".$fasta."\n".$tag_value."\n";
				print "dna-translate - ".$prot_obj->seq."\n";
				print "annotated - ".$translate."\n";
	        	}
	        	print ParseFile ">".$tag_value."\n";
	        	print ParseFile ($feat_object->get_tag_values('translation'))[0],"\n";
	        }
	    }
	}
	close(ParseFile);
}

my $data_folder="/local/workspace01/zhangju/wc1_annotation/CaZy";
chdir $data_folder;
my $index_file="/local/workspace01/zhangju/wc1_annotation/CaZy/Cazy_protein.txt";
open (IndexFile, "<", $index_file);
my $start=0;
my $end=0;
my $gbk_file_name="";
my $fasta_file="";
my %h_locus=();
my $gbk_str="";

while (<IndexFile>){
	chomp;
	if ($_ =~ /===/){
		if (($gbk_file_name ne "") && ($fasta_file ne "") && $end==1){

			each_gbk_protein_fasta($gbk_file_name, $fasta_file, \%h_locus );
			$gbk_file_name="";
			$fasta_file="";
			%h_locus=();
			$start=0;
			$end=0;
		}
		if ($start==0){
			$start=1;
		}else{
			$end=1;
		}
		next;
	}
	if (($start==1) && ($gbk_file_name eq "")){
		my @arr=split(/-/,$_);
		$gbk_file_name=$arr[0];
		my @arr2=split(/ /,$arr[1]);
		$fasta_file=join("_",@arr2).".faa";
		next;
	}	
	if ($start==1 && ($gbk_file_name ne "")){
		my @items=split(/\t/,$_);
		$h_locus{$items[0]}=""
	}
}
close(IndexFile);


