#!/usr/bin/perl
#
# strong-hits -- find matches in an alignment that meet specified
#                constraints for length and strength
#
# Please see the PipTools Program Reference (.../docs/piptools_ref.html)
# for a description of what this program does and how to use it.
#
# This program was suggested by John Pedan.
#
# $Revision: 1.10 $$Date: 2003/07/08 19:02:39 $

use 5.6.0;
use strict;
use warnings;
use Class::Struct;
use FindBin;

use lib "$FindBin::Bin";     # this script's directory
use piplib::lav;
use piplib::exons;

$0 = $FindBin::Script;

my $usage = "$0: Usage:\n\n$0 align_file -len min_length -pct min_ident " .
            "[-gap max_gap_size -step max_ident_step] " .
            "[-overlaps interval_file [-inseq2] [-exons-only]] > output_file\n";
my $debug = 0;

my $align_file;		# Alignment file.
my $interval_file;	# Any form of interval file.
my $min_len;		# Minimum segment length.
my $min_pct;		# Minimum bp and identity pct.
my $max_gap = 0;	# Longest allowable gap between adjacent segments
my $max_step = 0;	# Maximum difference in these segments' identities
my $inseq2 = 0;		# Intervals in sequence 2?
my $exonly = 0;		# Only use exons from exons file.
my $seg_arr;		# Reference to array of alignment info.
my $start;		# Interval references (stored as parallel arrays.)
my $end;
my $gene_name;
my $exon_name;
my $dir;
my $nint = 0;		# Length of parallel arrays.
my $first = -1;		# Index of group's first segment.
my $score;		# One group's score
my $tot_score = 0;	# Sum of (score * len) for group.
my $tot_len = 0;	# Total length of group, excluding gaps.
my $hdr2;		# Header.
my $printed = "";	# Previously printed header.
my $i = 0;		# Array index.
my $len = 0;		# Length of segment.
my $nhits = 0;		# Number of hits found.


# Get arguments.

get_args();
die $usage if (!defined($align_file) || !defined($min_len) || !defined($min_pct) ||
		$min_len < 1 || $min_pct < 1 || $min_pct > 100 || $max_gap < 0 || 
		$max_step < 0 || (($max_gap && !$max_step) || ($max_step && !$max_gap)) ||
		(($inseq2 || $exonly) && !$interval_file));

# Try to open files.

open (ALIGN_FILE, $align_file) ||
    die "$0: Cannot open \"$align_file\": $!\n";


# Read alignment file into Segment array.

$seg_arr = get_align(*ALIGN_FILE, $align_file, 0);
die "$0: 2nd-sequence overlap intervals do not work with multiple contigs.\n"
    if (has_multi_contig($seg_arr) && $inseq2);
print_align() if $debug;


# Read interval file into parallel arrays.

if ($exonly) {
    open (EXON_FILE, $interval_file) ||
        die "$0: Cannot open file \"$interval_file\": $!\n";
    ($nint, $start, $end, $dir, $gene_name, $exon_name) = get_exons();
    print_exons($nint, $start, $end, $dir, $gene_name, $exon_name) if ($debug);
} else {
    ($nint, $start, $end) = get_intervals(*INTERVAL_FILE) if (defined($interval_file));
    print_ints() if ($debug && defined($interval_file));
}


# Print title.

if ($max_gap) {
    print "Groups of segments in $align_file\n" ,
    	  "with overall length >= $min_len bp" ,
    	  " and individual identity >= $min_pct%,\n" ,
    	  "where gaps are <= $max_gap bp, and identity steps are <= $max_step%";
} else {
    print "Gap-free segments in $align_file\nwith length >= $min_len " ,
          "bp and identity >= $min_pct%";
}

if (defined($interval_file)) {
    print ",\nshowing ", ($exonly ? "exons" : "intervals"), " from $interval_file that overlap them in sequence ";
    print ($inseq2 ? "2" : "1");
}
print ":\n\n";


# Find strong matches.

for ($i = 0; @$seg_arr[$i]->type ne "z"; $i++) {
    if (@$seg_arr[$i]->type eq "l") {
	$score = @$seg_arr[$i]->score;
	$len = abs(@$seg_arr[$i]->x1 - @$seg_arr[$i]->x0) + 1;

	if ($first < 0) {
	    if ($score >= $min_pct) {
		# Start new group.
		$first = $i;
		$tot_score = $score * $len;
		$tot_len = $len;
	    }
	} elsif ((same_local($first, $i, $seg_arr)) && 
		 (prec_gap ($seg_arr, $i) <= $max_gap) &&
		 ($score >= $min_pct) &&
		 (abs($score - @$seg_arr[$i-1]->score) <= $max_step)) {
	    # Continue current group.
	    $tot_score += $score * $len;
	    $tot_len += $len; 	# Don't include gap.
	} else {
	    # Finish current group.
	    if ($tot_len >= $min_len) {
		print_group($seg_arr, $first, $i-1, $tot_score, $tot_len, $max_gap,
			    $printed, $start, $end, $gene_name, $nint, $exonly, $inseq2);
		$nhits++;
	    }
	    $first = -1;
	    $i--;	# Re-examine this segment as a possible new first.
	}
    }
}

# Finish last group.
if ($first >= 0 && $tot_len >= $min_len) {
    print_group($seg_arr, $first, $i-1, $tot_score, $tot_len, $max_gap,
             	$printed, $start, $end, $gene_name, $nint, $exonly, $inseq2);
    $nhits++;
}

if (!$nhits) {
    print "No aligned segments matched these criteria.\n";
} else {
    print "\n$nhits hit";
    print ($nhits == 1 ? ".\n" : "s.\n");
}


# Close files.

close (ALIGN_FILE) ||
    die "$0: Cannot close \"$align_file\": $!\n";
if ($exonly) {
    close (EXON_FILE) ||
        die "$0: Cannot close \"$interval_file\": $!\n";
}



# Read arguments.

sub get_args {

    while ($_ = shift(@ARGV)) {
	if (/^-len$/) {
	    $min_len = shift(@ARGV);
	    die "$0: Invalid min_length value.\n" unless (defined($min_len) && 
		$min_len =~ /-?(\d+\.?\d*|\.\d+)$/);
	    $min_len = int($min_len);
	} elsif (/^-pct$/) {
	    $min_pct = shift(@ARGV);
            die "$0: Invalid min_ident value.\n" unless (defined($min_pct) &&
		$min_pct =~ /-?(\d+\.?\d*|\.\d+)$/);
	    $min_pct = int($min_pct);
	} elsif (/^-gap$/) {
	    $max_gap = shift(@ARGV);
            die "$0: Invalid max_gap_size value.\n" unless (defined($max_gap) &&
                $max_gap =~ /-?(\d+\.?\d*|\.\d+)$/);
	    $max_gap = int($max_gap);
	} elsif (/^-step$/) {
            $max_step = shift(@ARGV);
            die "$0: Invalid max_ident_step value.\n" unless (defined($max_step) &&
                $max_step =~ /-?(\d+\.?\d*|\.\d+)$/);
            $max_step = int($max_step);
	} elsif (/^-overlaps$/) {
	    $interval_file = shift(@ARGV);
	    die $usage unless defined($interval_file);
	} elsif (/^-inseq2$/) {
	    $inseq2 = 1;
	} elsif (/^-exons-only$/) {
	    $exonly = 1;
	} elsif (!defined($align_file)) {
	    $align_file = $_;
	} else {
	    die $usage;
	}
    }
}


# Loop through interval file and store all intervals into parallel arrays.

sub get_intervals {

    local *INTERVAL_FILE = @_;
    my ($start, $end);		# New interval to be added.
    my (@start, @end);		# The parallel arrays of intervals.

    open (INTERVAL_FILE, $interval_file) ||
        die "$0: Cannot open \"$interval_file\": $!\n";

    while (<INTERVAL_FILE>) {
	next if /^\s*$/;
	next if /^\s*#/;
	($start, $end) = /^(?:(?:\s*)|(?:.+\s+)|(?:\s*[>|<+]\s*))(\d+)\s+(\d+)/;
	if (defined($end)) {
	    push (@start, $start);
	    push (@end, $end);
	}
    }

    close (INTERVAL_FILE) ||
        die "$0: Cannot close \"$interval_file\": $!\n";

    return ($#start + 1, \@start, \@end);
}


# Compute size of the gap preceding a particular segment.

sub prec_gap {

    my ($seg, $i) = @_;
    my ($xgap, $ygap);

    die "Internal error" unless ($i > 0 && @$seg[$i-1]->type eq 'l' && @$seg[$i]->type eq 'l');
    $xgap = abs (@$seg[$i]->x0 - @$seg[$i-1]->x1) - 1;
    $ygap = abs (@$seg[$i]->y0 - @$seg[$i-1]->y1) - 1;
    die "Internal error" unless ($xgap <= abs (@$seg[$i]->x1 - @$seg[$i-1]->x0) - 1);
    die "Internal error" unless ($ygap <= abs (@$seg[$i]->y1 - @$seg[$i-1]->y0) - 1);
    die "Internal error" unless (!$xgap || !$ygap);

    return ($xgap + $ygap);
}


# Print output line for group.

sub print_group {

    (my $seg, my $first, my $i, my $tot_score, my $tot_len, my $max_gap, $printed,
        my $start, my $end, my $gene_name, my $nint, my $exonly, my $inseq2) = @_;
    my ($hdr2, $j, $last);
    my ($x0, $x1, $y0, $y1);

    # Print seq2 header.
    die "$0: Missing sequence header for segment $first.\n" unless
	$hdr2 = get_hdr2($first, $seg);
    if ($hdr2 ne $printed) {
	print "$hdr2\n";
	$printed = $hdr2;
    }

    # Get group endpoints.
    for ($j = $first; $j <= $i && @$seg[$j]->type eq 'l'; $j++) { };  # Drop trailing s,a.

    $last = $j-1;
    $x0 = @$seg[$first]->x0;
    $x1 = @$seg[$last]->x1;
    $y0 = @$seg[$first]->y0;
    $y1 = @$seg[$last]->y1;
    die "Internal error" unless (abs ($x0 - $x1) >= abs (@$seg[$first]->x0 - @$seg[$last]->x1));
    die "Internal error" unless (abs ($y0 - $y1) >= abs (@$seg[$first]->y0 - @$seg[$last]->y1));

    # Print output lines.

    print "    $x0-$x1 <--> $y0-$y1 ", sprintf("%.0f", ($tot_score * 1.0 / $tot_len)), "% ($tot_len nt";
    print ("; ", ($last - $first + 1), " seg") if ($max_gap);
    print ")";
    print " (reverse complement)" if (@$seg_arr[$i]->reverse);
    if (!$inseq2) {
        print_overlaps ($x0, $x1, $start, $end, $gene_name, $nint, $exonly);
    } else {
        print_overlaps ($y0, $y1, $start, $end, $gene_name, $nint, $exonly);
    }
    print "\n";
}


# Print overlaps from interval file.

sub print_overlaps {

    my ($a0, $a1, $start, $end, $gname, $nint, $exonly) = @_;
    my ($j, $count) = 0;

    for ($j = 0; $j < $nint; $j++) {
	if ($exonly && @$gname[$j]) {		# Skip gene and cds.
	    $j++;
	    next;
	}
	if (overlaps ($a0, $a1, @$start[$j], @$end[$j])) {
	    print (!$count ? "; overlaps" : ",");
	    print " @$start[$j]-@$end[$j]";
	    $count++;
	}
    }
}


# Print Segment array when debugging.

sub print_align {

    print "--------------------------------------------------------------\n\n";
    print "Seg array read in from file $align_file:";
    for (my $n = 0; $n < @$seg_arr; $n++) {
        print  "\n\nSEGMENT $n:\n";
        print "type " . (@$seg_arr[$n]->type || "undef") . "\n";
        print "x0 " . (@$seg_arr[$n]->x0 || "undef") . " x1 " .  (@$seg_arr[$n]->x1 || "undef") . "\n";
        print "y0 " . (@$seg_arr[$n]->y0 || "undef") . " y1 " .  (@$seg_arr[$n]->y1 || "undef") . "\n";
        print "rev " . (defined(@$seg_arr[$n]->reverse) ? @$seg_arr[$n]->reverse : "undef") . "\n";
        print "hdr2 " . (@$seg_arr[$n]->hdr2 || "undef") . "\n";
        print "score " . (defined(@$seg_arr[$n]->score) ? @$seg_arr[$n]->score : "undef") . "\n";
    }
    print "\n\n";
    print "--------------------------------------------------------------\n\n";
}


# Print intervals when in debugging mode.

sub print_ints {

    print "Interval arrays found in file $interval_file:\n";
    for (my $i = 0; $i < @$start ; $i++) {
	print "Start: ";
	print @$start[$i];
	print " End: ";
	print @$end[$i];
	print "\n";
    }
    print "\n\n";
    print "--------------------------------------------------------------\n\n";
}


# Print exons when in debugging mode.

sub print_exons {

    my ($exlen, $beg, $end, $dir, $gene_name, $exon_name) = @_;

    print "--------------------------------------------------------------\n\n";
    print "Exons read in from file $interval_file\n";
    print "(BEG END DIR GENE_NAME EXON_NAME):\n\n";
    for (my $q = 0 ; $q < $exlen ; $q++) {
        print "  |@$beg[$q]";
        print "  |@$end[$q]";
        print "  |@$dir[$q]";
        print "  |@$gene_name[$q]";
        print "  |@$exon_name[$q]\n";
    }
    print "--------------------------------------------------------------\n\n";
}
