#!/usr/bin/perl
# usage: $ perl filter_RAW.pl -list target_list.txt -file MIDORI_RAW.fasta 

use strict;
use utf8;
use Getopt::Long;

our %Opt;

END { system("/bin/ps -o pid,vsz,args -e -q $$ >&2"); }

&main();

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

	# opening input file 
	open(my $input, $Opt{file}) or die("file not found.");

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

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

	my $output;
	for( <$input> ){
		chomp;
		if( /^>[^\s]+[\s#]+(.+)/ ){
			# taxa 
			$output = $remove;
			my @l = split(/[;\s]/, $1);
			for( @l ){
				my $key1 = $_;
				(my $key2 = $_ ) =~ s/^class_//;
				if( $$list{$key1} || $$list{$key2}){
					$output = $target;
					last;
				}
			}
		}
		print $output "$_\n";
	}	
}


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