#!/usr/bin/perl 

use strict;

use warnings;

use Bio::DB::EUtilities;
 
my @ids = qw(4826782 157749793);
 
my $factory = Bio::DB::EUtilities->new(-eutil => 'epost',
                                       -email => 'pat.boutet@gmail.com',
                                       -db => 'protein',
                                       -id => \@ids,
                                       -keep_histories => 1);
 


my $count = scalar(@ids);

print $count."\n";;

# get history from queue
my $hist = $factory->next_History || die 'No history data returned';
print "History returned\n";
# note db carries over from above
$factory->set_parameters(-eutil => 'efetch',
                         -rettype => 'gb',
                         -history => $hist);
 
my $retry = 0;
my ($retmax, $retstart) = (500,0);
 
open (my $out, '>', 'output.txt') || die "Can't open file:$!";
 
RETRIEVE_SEQS:
while ($retstart < $count) {
    $factory->set_parameters(-retmax => $retmax,
                            -retstart => $retstart);
    eval{
        $factory->get_Response(-cb => sub {my ($data) = @_; print $out $data});
    };
    if ($@) {
        die "Server error: $@.  Try again later" if $retry == 5;
        print STDERR "Server error, redo #$retry\n";
        $retry++ && redo RETRIEVE_SEQS;
    }
    print "Retrieved $retstart";
    $retstart += $retmax;
}
 
close $out;
