#! /usr/bin/perl -w

# Compares sample.filtered with one or more ref.filtered.
#
# Like compareFiltered.pl but without the check for SV type.
# 
# 1. Searches for overlaps (+- additional space) from link1 in ref.filtered
# 2. if no overlap 
#       than print line from sample.filtered into sample.compared
#       else 3.
# 3. compare link2 (+- add. space) with corresponding link2 in ref.filtered
# 4. if no overlap
#      than next candidate from step 1. or next link1
#           if no candidate fits, than print to sample.compared
#      else 5.
# (5. compare correspondig SV type)
# 6. if not equal
#      than print to sample.compared
#      else 7.
# 7. print to sample.ref.compared:
#      ident_num + row_from_sample
#      ident_num + row_from_ref + "Name ref"

#Format sample or ref file:
# col0 = chr link1
# col1 = start link1
# col2 = stop link1
# col3 = chr link2
# col4 = start link2
# col5 = stop link2
# col16 = sv type

#USAGE: compareFilterd3.pl X sample.filtered ref1.filtered ref2.filtered ...
#where: X = additional space to detect the overlaps


use strict;
use FindBin;
use lib $FindBin::Bin;
use OverlappingIntervals;

#command line options
my $space = shift;
my $sampleFile = shift;
my @refFiles = @ARGV;

#constants
my %svequal = ('SMALL_DUPLI' => 1, 'LARGE_DUPLI' => 1);

# Read the sample file and create intervals object
my %chrInts; #chr => intervals
open(SAMPLE, $sampleFile) or die "ERROR:  Can not open $sampleFile";
while (my $line = <SAMPLE>) {
    chomp $line;
    my @a = split(/\t/, $line);
    my $chr1 = $a[0];
    $chrInts{$chr1} = OverlappingIntervals->new() unless exists $chrInts{$chr1};
    ($chrInts{$chr1})->add($a[1]-$space,$a[2]+$space,\$line);
}

#compare refs link1 with sample
my $outlineNumber=0;
my %outlineSampleRef; #sample_line => [[ref_file,ref_line]]
foreach my $refFile (@refFiles) {
    open(REF,$refFile) or die "ERROR: Can not open $refFile";
    while (my $refLine = <REF>) {
	chomp $refLine;
	my @r = split(/\t/,$refLine);
	my $overlaps = [];
	$overlaps = ($chrInts{$r[0]})->search($r[1],$r[2]) if exists $chrInts{$r[0]};
	foreach my $overlapInt (@$overlaps) {
	    my @s = split(/\t/,${$overlapInt->[2]});
	    if (areOverlapping([$s[3],$s[4]-$space,$s[5]+$space],
			       [$r[3],$r[4],$r[5]])) {
		#same sv type?
		#if (eqsv($s[16],$r[16])) {
		push(@{$outlineSampleRef{${$overlapInt->[2]}}}, 
		     [$refFile,$refLine]);
		#}
	    }
	}
    }
    close REF;
}

#create output files
open(SAMPLE_REF_COMPARED, ">sample.ref.compared")
    or die "ERROR: Can not open sample.ref.compared";

#output sample.ref.compared
my $num=0;
while (my ($sampleLine, $refLines) = each %outlineSampleRef) {
    print SAMPLE_REF_COMPARED "$num\t$sampleFile\t$sampleLine\n";
    foreach my $ref (@$refLines) {
	print SAMPLE_REF_COMPARED "$num\t$ref->[0]\t$ref->[1]\n";
    }
    $num++;
}
close SAMPLE_REF_COMPARED;

#output sample.compared
open(SAMPLE_COMPARED, ">sample.compared") 
    or die "ERROR: Can not open sample.compared";
open(SAMPLE, $sampleFile) or die "ERROR: Can not open $sampleFile";
while (<SAMPLE>) {
    chomp;
    print SAMPLE_COMPARED "$_\n" unless exists $outlineSampleRef{$_};
}
close SAMPLE;
close SAMPLE_COMPARED;

sub areOverlapping {
    #Check if 2 intervals are overlapping
    #IN: [chr,start,end]
    #IN: [chr,start,end]
    #OUT: 1 if overlap, 0 otherwise
    my @ints = @_;
    return 0 if $ints[0][0] ne $ints[1][0];
    return 1 if ($ints[0][1] >= $ints[1][1] and $ints[0][1] <= $ints[1][2])
	or ($ints[0][2] >= $ints[1][1] and $ints[0][2] <= $ints[1][2])
	or ($ints[0][1] <= $ints[1][1] and $ints[0][2] >= $ints[1][2])
	or ($ints[0][1] >= $ints[1][1] and $ints[0][2] <= $ints[1][2]);
    return 0;
}

sub eqsv {
    #Compares the SV type.
    #SMALL_DUPLI == LARGE_DUPLI
    my $a = shift;
    my $b = shift;
    if (exists $svequal{$a} and exists $svequal{$b}) {
	return ($svequal{$a} == $svequal{$b});
    } else {
	return ($a eq $b);
    }
}
