#! /usr/local/bin/perl -w

# Zizhen Yao
# CVS $Id: filter.pl,v 3.1 2006/03/07 19:22:09 yzizhen Exp $

use Getopt::Long;

do "io.pl";

$threshold = 0;

GetOptions(
	   "w" => \$do_weight,
           "s" => \$do_score,	   
	   "t=f" => \$threshold,
       );

$file_name = shift @ARGV;
$out_file = shift @ARGV;

print $file_name, "\t", $out_file, "\t", $threshold, "\n";

sub filter{
    my $threshold = shift @_;
    my $alignment = shift @_;    
    
    my $temp = ($alignment->seqs);
    my %seqs = %$temp;
    $temp = ($alignment->flags);
    my %flags  = %$temp;
    if ($do_weight && ! exists $flags{"WGT"}) {
	die "No weight info is available in the alignment ";
    }
    if ($do_score && ! exists $flags{"SC"}) {
	die "No score info is available in the alignment ";
    }
    foreach $acc (keys %seqs) {
	if ($do_weight) {
	    if ($seqs{$acc}->weight < $threshold) {
		delete $seqs{$acc};
	    }
	}
	if ($do_score) {
	    if ($seqs{$acc}->score < $threshold) {
		print "Delete $acc ", $seqs{$acc}->score, "\n";
		delete $seqs{$acc};
	    }
	}
	
    }
    $alignment->seqs(\%seqs);
    return ($alignment);
}

$alignment = read_stockholm($file_name);
$alignment = filter($threshold, $alignment);
write_stockholm($alignment, $out_file);
