#!/usr/bin/perl -w

#	Sample script to do bulk Block Searches
#	Replaces Email Block Searcher
#	Arguments are <file of query sequences in FASTA format> <return email>
#	Requires libwww-perl         (http://www.linpro.no/lwp/)

#       Form                            Mail
#       database=plus | minus | prints  #DB PLUS | MINUS | PRINTS
#       ty=auto | AA | DNA              #TY AUTO | AA | DNA
#       st=0 | 1 | -1                   #ST BOTH | FORWARD | REVERSE
#       ge=0 to 16                      #GE 0 to 16
#       ou=all | sum | gff | old | raw  #OU ALL | SUM | GFF | OLD | RAW
#                                       #FO TEXT | HTML
#       ex=n                            #EX n
#       sequence=                       #SQ

use lib '/usr/local/perl';
use LWP 5.63;
use HTTP::Request::Common;
use strict;

# URL of Blockmaker script
my $script_url = 'http://blocks.fhcrc.org/blocks-bin/blocks_search';

# Defaults for the form fields
#	Other possible values at http://blocks.fhcrc.org/www/blocks_search.html
my %form_data = (
	database 	=>	'plus',
	ex		=>	1,
	ou		=>	'all',
	ty		=>	'auto',
	st		=>	2,
	ge		=>	0);



# HTML named entities to convert
my %convert = (
	amp		=>	'&',
	lt		=>	'<',
	gt		=>	'>',
	quot		=>	'"');


unless ($#ARGV == 1) {
	die "Usage: $0 seq_file email_address\n";
}

# Create the user agent
my $ua = LWP::UserAgent->new();
$ua->agent('Batch Blocks Searcher');
$ua->from($ARGV[1]);


# Read in the sequences (in FASTA format), one at a time, and then
# call block searcher.
open(SEQS, $ARGV[0]);

my $seq;

my $count = 0;

for ( ; ; ) {
	$_ = <SEQS>;

	if ($seq && ((! $_) || (/^>/))) {
		++$count;
		
		if ($count > 1) {
			print '#' x 80;
		}
		
		$form_data{'sequence'} = $seq;
		my $response = $ua->request(POST $script_url, \%form_data);
		
		if ($response->is_success()) {
			my $data = $response->content;

			# Strip out the header
			$data =~ s/^.*BLKPROB/BLKPROB/s;

			# and the footer
			$data =~ s/<\/PRE>//;
			$data =~ s/<\/PRE>.*//s;

			# Strip out HTML Tags
			$data =~ s/<[^>]+>//g;

			foreach (keys(%convert)) {
				$data =~ s/&$_;/$convert{$_}/g;
			}
			
			if ($data =~ /Here are your search results/) {
				print $data;
			} else {
				warn "Blockmaker request #$count failed: $data\n";
			}
		} else {
			warn "Blockmaker request #$count failed, ", $response->status_line(), "\n";
		}

		undef $seq;
	}

	if (! $_) {
		last;
	}
	
	$seq .= $_;
}

close(SEQS);
exit;
