#!/usr/local/bin/perl

use strict;
use Getopt::Long;

my %opt;
my @options = ( "h", "i=i", "o=i" );
GetOptions( \%opt, @options );
usage() if ($opt{'h'} || !$opt{'i'} || !$opt{'o'});

my ($query, $hit);
my %pairs;
my %cluster;
my %tag;

#-------------------------------------------------------------#
# Main
#-------------------------------------------------------------#

# Read blast and store valid pairs
while (<>) {

	if (/^Query=\s*(\S+)/) {
	
		$query = $1;
		next;
	}

	if (/^>(\S+)/) {

		$hit = $1;
		next;
	}

	if (/^\sIdentities = \d+\/(\d+)\s+\((\d+)/) {

		if ($1 >= $opt{'i'} && $2 >= $opt{'o'}) {

			if ($query gt $hit) {

				my $tmp = $query;
				$query = $hit;
				$hit = $tmp;
			}

			$pairs{$query}{$hit} = 1;
		}
	}
}

# Add cluster-tags to each sequence
my $i = 0;
my $tag;
foreach $query (sort keys %pairs) {

	if (defined($tag{$query})) {

		$tag = $tag{$query};
	}
	else {
		$i++;
		$tag = $i;
		$tag{$query} = $tag;
	}
	
	foreach $hit (sort keys %{$pairs{$query}}) {

		$tag{$hit} = $tag;
	}
}

# Group tags
foreach $query (keys %tag) {

	$cluster{$tag{$query}}{$query} = 1;
}

# Print clusters
foreach $i (sort keys %cluster) {
	
	open(CLUSTER,">cluster$i");
	#print ">cluster$i\n";
	
	foreach $query (sort keys %{$cluster{$i}}) {

		print CLUSTER "$query\n";
		#print "\t$query\n";
	}
	
	close(CLUSTER);
}

#-------------------------------------------------------------#
# Usage
#-------------------------------------------------------------#
sub usage {

print STDERR <<EOF;

cluster.pl [options] blast_file

where options are:

	-o <int> Number of minimum bp overlap
	-i <int> Minimum % of identity in the overlap

EOF
exit(0);
}
