#!/usr/bin/perl -w 
###	extract flat files in which Sources include "Metazoa" key word
###	then extract fasta files that have the same gi with mito_metazoa_flat.txt  
 
open TXT1 , "<./flat_file.txt" or die "can't open file1:$!";

$out_file_1 = "./mito_metazoa_flat.txt";

system "rm $out_file_1";
open OUT1 , ">>./$out_file_1";

$i = 0;
@gi_array = ();

while(<TXT1>)
{
	chomp;

	if($_=~/^LOCUS.*/)
	{
		@annota = ();
		$gi = "";
		$j = 0;
	}

	push @annota,"$_\n"; 

	if($_=~/^VERSION.*GI:(\d+).*/)
	{
		$gi = $1;
#		print "$gi\n";		

	}

	if($_=~/\s+ORGANISM.*/)
	{
		
		$i = 1;		

	}

	if($_=~/^REFERENCE.*/)
	{

		$i = 0;

	}


	if($i == 1)	
	{

		if($_=~/.*Metazoa.*/)
		{
			$j = 1;
			push @gi_array,$gi; 
			
		}

	}

	if($_=~/^\/\/.*/ && $j == 1)
	{
		print OUT1"@annota";		


	}

}

close TXT1;

open TXT2 , "<../nt_mito_fasta.txt" or die "can't open file1:$!";

$out_file_2 = "./mito_metazoa_fasta.txt";

system "rm $out_file_2";
open OUT2 , ">>./$out_file_2";

$k = 0;
$m = 0;
while(<TXT2>)
{
	chomp;
	
	if($_=~/^\>gi\|(\d+)\|.*/)
	{
		$gi_2 = $1;
		$k = 1;	
		$m = 0;
		foreach $gi_num (@gi_array)
		{
			if($gi_2 == $gi_num)
			{
				$m = 1;
				print OUT2 "$_\n";
				last;	
			}
			
		}	

	}else{$k = 0;}
	
	if($k == 0 && $m == 1)
	{
		print OUT2 "$_\n";
		

	}



}




