#!/usr/bin/perl -w
use strict;

#person in charge of this script
#this should be the person currently in charge of scripts for the SGN project
my $script_maintainer='Dan Ilut <dci1@cornell.edu>';

use lib '/soldb/local_scripts/custom_packages';

#local packages to use
use runtime;


@ARGV or print "No input parameters, proceeding with default.\n";

my @arg_pairs = split (/\-/, (join ' ', @ARGV));

my %args=();

foreach (@arg_pairs){

    $_ or next;
    my ($flag, $val)=split /\s+/;
    $args{$flag}=$val;
}

my $out_file=$args{'o'};
my $in_file=$args{'i'};

open FILEIN, $in_file or die "couldn't open $in_file for reading\n";

my %matches=();

while(<FILEIN>){  
    /^[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)/
	and push @{$matches{$1}{"$2-$3"}},[$4,$5];
}

close FILEIN;

print "Finished reading input\n";

open (FILEOUT, ">$out_file");

my $min_ln;
foreach $min_ln (sort{$a<=>$b} keys %matches){
    my $seq_matches=int(keys %{$matches{$min_ln}});
    print FILEOUT "Minimum match length of $min_ln: $seq_matches matches\n";
    my $seq_id;
    my %matches_in_seq=();
    foreach $seq_id (keys %{$matches{$min_ln}}){
	my $nr_matches=int(@{$matches{$min_ln}{$seq_id}});
	$matches_in_seq{$nr_matches}++;


	if ($min_ln==12 and $nr_matches==1){ 
	    print "$seq_id: |";
	    foreach (@{$matches{$min_ln}{$seq_id}}){
		print join (',',@{$_}) . '|';
	    }
	    print "\n";
	}

    }
    foreach (keys %matches_in_seq){
	print FILEOUT "\t$_ match" . (($_==1) ? '' : 'es') . ": $matches_in_seq{$_}\n";
    }
    print FILEOUT '#'x80 . "\n";
}

close FILEOUT;
