#!/usr/bin/perl -w
#read first N symbols

use strict;

#delete peaks which intersect with masked regions

use strict;
use warnings;
use diagnostics;


my $usage = qq{
    deleteRegions.pl

    -----------------------------
    mandatory parameters:
    
    -f input_file               input file 
    -r bad_regions_file         tab delimited file with masked regions 
    
    -----------------------------
    optional parameters:
    
    -w flanks	  (delault 0) flank to add to masked regions
};

if(scalar(@ARGV) == 0){
    print $usage;
    exit(0);
}

my $input_file = "";
my $mark_file="";
my $window = 0;

while(scalar(@ARGV) > 0){
    my $this_arg = shift @ARGV;
    if ( $this_arg eq '-h') {print "$usage\n"; exit; }

    elsif ( $this_arg eq '-f') {$input_file = shift @ARGV;}
    elsif ( $this_arg eq '-r') {$mark_file= shift @ARGV;}

    elsif ( $this_arg eq '-w') {$window = shift @ARGV;}

    elsif ( $this_arg =~ m/^-/ ) { print "unknown flag: $this_arg\n";}
}


if ( $input_file eq ""){
    die "you should specify input file\n";
}
if( $mark_file eq ""){
    die "you should specify file with masked regions\n";
}


open (MARK, "<$mark_file") or die "Cannot open file $mark_file!!!!: $!";
open (FILE, "<$input_file ") or die "Cannot open file $input_file !!!!: $!";

my $result_file = "accepted_$input_file ";
my $excluded_file = "excluded_$input_file ";


my %hash;

while (<MARK>) {
	chomp;	
	if (/(chr.*)\s(\d+)\s(\d+)/){
		my $chro = $1;		
		$chro =~ s/.fa//;
				
		unless (exists($hash{$chro})) {
			my %h;
			$hash{$chro}=\%h;
		}
		$hash{$chro}->{$2-$window}=$3+$window;
	}
	if (/(chr.*):(\d+)-(\d+)/){
		my $chro = $1;		
		$chro =~ s/.fa//;
		unless (exists($hash{$chro})) {
			my %h;
			$hash{$chro}=\%h;
		}
		$hash{$chro}->{$2-$window}=$3+$window;
	}
}

close MARK;


open (OUT, ">$result_file") or die "Cannot open $result_file file!!!!: $!";
open (JUNK, ">$excluded_file ") or die "Cannot open $excluded_file file!!!!: $!";

print JUNK "Regions to be excluded:\n";

while (<FILE>) {
	chomp;
	if (/\d+\s\d+\s\d+/) {
		my @a = split/\s/;
		
		my $chro = $a[1];
		
		unless ($chro=~/chr/) {
		        $chro = "chr".$chro;
    		}
    		if ($chro=~/.fa/) {
			$chro =~ s/.fa//;
    		}
		
		my $start= $a[2];
		my $end= $a[3];
		#my $score = $a[5];
		my $exlude = 0;
		
		for my $left (keys %{$hash{$chro}}) {
			my $right = $hash{$chro}->{$left};
						
			if (($left <= $start)&&($right >= $start)){
				$exlude = 1;
			}
			if (($left <= $end)&&($right >= $end)){
				$exlude = 1;
			}
			if (($start <= $left)&&($right <= $end)){
				$exlude = 1;
			}			
		}
		if ($exlude) {
			print JUNK ;
			print JUNK "\n";
		}
		else {
			print OUT ;
			print OUT "\n";
		}
	}
}

close FILE;
close OUT;
close JUNK;
