#!/usr/bin/perl -w

use Modern::Perl;
use Bio::Tools::Run::RemoteBlast;
my $prog  = 'blastx';
my $db    = 'nr';
my $e_val = '1e-10';

my @params = (
    '-prog'       => $prog,
    '-data'       => $db,
    '-verbose'    => 1,
    '-expect'     => $e_val,
    '-readmethod' => 'SearchIO'
);

my $factory = Bio::Tools::Run::RemoteBlast->new(@params);

#$Bio::Tools::Run::RemoteBlast::HEADER{'SERVICE'} = 'blastx';

#$v is just to turn on and off the messages
my $v = 1;

my $str = Bio::SeqIO->new(
    -file   => 'example.fa',
    -format => 'fasta'
);

while ( my $input = $str->next_seq() ) {
    print STDERR "waiting..." if ( $v > 0 );

    #Blast a sequence against a database:

    #Alternatively, you could  pass in a file with many
    #sequences rather than loop through sequence one at a time
    #Remove the loop starting 'while (my $input = $str->next_seq())'
    #and swap the two lines below for an example of that.
    my $r = $factory->submit_blast($input);

    #my $r = $factory->submit_blast('amino.fa');

    while ( my @rids = $factory->each_rid ) {
        print "Checking for RID...\n";
        foreach my $rid (@rids) {
            my $rc = $factory->retrieve_blast($rid);
            if ( !ref($rc) ) {
                if ( $rc < 0 ) {
                    print "removing rid as rc is < 0";
                    $factory->remove_rid($rid);
                }
                print STDERR "." if ( $v > 0 );
                sleep 5;
            }
            else {
                my $result = $rc->next_result();

                #save the output
                print "saving to file";
                my $filename = "contig_236.out"; #$result->query_name()."\.out";
                $factory->save_output($filename);
                $factory->remove_rid($rid);
                print "\nQuery Name: ", $result->query_name(), "\n";
                while ( my $hit = $result->next_hit ) {
                    next unless ( $v > 0 );
                    print "\thit name is ", $hit->name, "\n";
                    while ( my $hsp = $hit->next_hsp ) {
                        print "\t\tscore is ", $hsp->score, "\n";
                    }
                }
            }
        }
    }
}
