#!/usr/bin/perl
# usage: $ perl filter_QIIME.pl -list target_list.txt -fasta MIDORI_QIIME.fasta -taxon MIDORI_QIIME.taxon 

use strict;
use utf8;
use Getopt::Long;
our %Opt;

&main();

sub main{
	Getopt::Long::GetOptions( \%Opt, qw( list=s fasta=s taxon=s ) );
	
	# reading list
	my $list = readList($Opt{list});

	# -------------------------------------------------------
	# open taxon file 
	open(my $input_taxon, $Opt{taxon}) or die("file not found.");

	# target
	(my $file1 = $Opt{taxon}) =~ s/(\..+)/_target$1/;
	open(my $target_taxon, ">$file1") or die("$file1 can't open.");

	# remove
	(my $file2 = $Opt{taxon}) =~ s/(\..+)/_remove$1/;
	open(my $remove_taxon, ">$file2") or die("$file2 can't open.");

	# -------------------------------------------------------
	# open fasta file 
	open(my $input_fasta, $Opt{fasta}) or die("file not found.");

	# target
	(my $file3 = $Opt{fasta}) =~ s/(\..+)/_target$1/;
	open(my $target_fasta, ">$file3") or die("$file3 can't open.");

	# remove
	(my $file4 = $Opt{fasta}) =~ s/(\..+)/_remove$1/;
	open(my $remove_fasta, ">$file4") or die("$file4 can't open.");


	my( %key ); # fasta file search key 
	my $output_taxon;
	# processing taxon file  
	for( <$input_taxon> ){
		chomp;
		if( /([^\s]+)[\s#]+(.+)/ ){
			my $key_db = $1;
			# taxon 
			$output_taxon = $remove_taxon;
			my @l = split(/;/, $2);
			for( @l ){
				my $key1 = $_;
				(my $key2 = $_ ) =~ s/^\w__//;
				if( $$list{$key1} || $$list{$key2}){
					$key{$key_db} = 1;					
					$output_taxon = $target_taxon;
					last;
				}
			}
		}
		print $output_taxon "$_\n";
	}


	# processing fasta
	my $output_fasta;
	for( <$input_fasta> ){
		chomp;
		if( /^>(.+)/ ){
			$output_fasta = $remove_fasta;
			if( $key{$1} ){
				$output_fasta = $target_fasta;
			}
		}
		print $output_fasta "$_\n";
	}
}


sub readList{
	my( $file ) = @_;
	my %h;
	open(my $list, $file) or die("list not found.");
	for( <$list> ){
		chomp;
		$h{$_} = 1;
	}
	return \%h;	
}
