#!/usr/bin/perl -w

#	Sample script to do bulk Block Searches locally
#	Extract all sequences from a file of sequences in FASTA format
#	Arguments are <file of query sequences in FASTA format>
#	Output files are named seq.*

# Read in the sequences (in FASTA format), one at a time, and then
# execute block searcher locally.

$blocks = "sample.blocks";			# Blocks database
$blimps_dir = "../..";		# Or use environment var $BLIMPS_DIR
$frq = "$blimps_dir/docs/default.amino.frq";	# Amino acid frequencies
$qij = "$blimps_dir/docs/default.qij";		# Amino acid substitution freqs
$blimps = "$blimps_dir/bin/blimps";
$blkprob = "$blimps_dir/bin/blkprob";

if (@ARGV < 1)
{
   print "USAGE batch-search.pl <file of sequences in fasta format>\n";
   exit(-1);
}
open(SEQS, $ARGV[0]);
$nseq = $count = 0;
while (<SEQS>)
{
   if ($_ =~ m/^>/)		#	start of new sequence
   {
      if ($count > 0)		#	process previous sequence
      {
         close(SEQ);
	 &ex_blimps($nseq);
         $count = 0;
      }
      $nseq++;
      open(SEQ, ">$$.seq.$nseq");
   }  # end of new seq
   print SEQ "$_";
   $count++;
}
close(SEQS);

#	Last sequence
close(SEQ);
if ($count > 0)
{ &ex_blimps($nseq); }

exit(0);
#----------------------------------------------------------------------------
#  Write the blimps configuration file, execute blimps and blkprob
sub ex_blimps
{
   local($nseq) = @_;
	 #	Make the blimps configuration file
	 #	Change this for your site
	 open(CF, ">$$.cf");
	 #	Basic options
	 print CF "DB\t$blocks\n";		# Blocks database
	 print CF "SQ\t$$.seq.$nseq\n";		# Query sequence
	 print CF "TY\tauto\n";			# Sequence type
	 print CF "OU\t$$.raw.$nseq\n";		# Output file
	 print CF "FR\t$frq\n";			# Amino acid frquencies
	 print CF "CO\t3\n";			# PSSM type (don't change)
	 print CF "OP alts: 5.0 $qij :alts\n";	# Pseudo-count calculation
	 #	Search options
	 print CF "RE\tyes\n";			# Repeats allowed
						#  no=> only best score reported
	 #	Ignore raw scores < 945, use only for searching large dbs
#	 print CF "SV\tyes\n";			# no => consider all raw scores
	 print CF "NU\t0\n";			# Number of results to report
						#  0=> program decides
	 #	Options for translated DNA query sequences
	 print CF "ST\t2\n";			# Strands to search (DNA only)
	 print CF "GE\t0\n";			# Genetic code (DNA only)
	 #	Other output options
	 print CF "ER\t2\n";			# Error level
	 print CF "HI\tno\n";			# Score histogram

	 close(CF);
	 #	Execute blimps (raw scores) and blkprob (evalue)
 	 system("$blimps $$.cf");
	 #	-mast = mast statistics, don't change
	 #	-E = evalue cutoff
	 #	-all => all output; alternatives are -sum or -gff
 	 system("$blkprob $$.cf -mast -E 1.0 -all > $$.out.$nseq");
	 #	Remove unneeded files
#	 system("rm -f $$.cf $$.seq.$nseq $$.raw.$nseq");
}  # end of ex_blimps
