#!/usr/bin/perl -w
#####################################################
#Written By Ian Byrell Stanaway
#bard@u.washington.edu
####################################################
use strict;
my %arg;
&parseCommandLine;
my $target_definition = $arg{-target_definition};
my $probe_file = $arg{-probe_file};
my $genome_position_feature_def_file;
my %span;
my $span_count = 0;

&get_target;
&get_probe_file;


sub get_target
{
	open (FILE, $target_definition) or die "Can't open \n";
	while (<FILE>)
	{
		my $line = $_;
		chomp $line;
		my @line_contents = split(/\s+/, $line);
		my $chr = $line_contents[0];
		$chr =~ s/chr//gi;
		my $start = $line_contents[1];
		my $stop = $line_contents[2];
		foreach my $bp_pos ($start .. $stop)
		{
			$span{$chr}{$bp_pos} = 0;
		}
	}
}

sub get_probe_file
{
	open (FILE2, $probe_file) or die "Can't open \n";
	while (<FILE2>)
	{
		my $line = $_;
		if ($line =~ m/\s+NA\s+/g)
		{}
		else
		{
			chomp $line;
			my @line_contents = split(/\s+/, $line);
			my $chr = $line_contents[2];
			$chr =~ s/chr//gi;
			my $probe_start = $line_contents[11];#1 based
			my $probe_stop = $line_contents[12];
			foreach my $bp_pos ($probe_start .. $probe_stop)
			{
				if (exists $span{$chr}{$bp_pos})
				{
					$span{$chr}{$bp_pos} = 1;
				}
			}
		}
	}
	close FILE2;

	my $uncovered_base = 0;
	my $covered_base = 0;
	my $flanking_covered_base = 0;
	foreach my $chr (keys %span)
	{
		foreach my $bp_pos (keys %{$span{$chr}})
		{
			$span_count++;
			my $coverage_code = $span{$chr}{$bp_pos};
			if ($coverage_code == 0)
			{
				$uncovered_base++;
				print "chr$chr\t$bp_pos\n";
			}
			if ($coverage_code == 1)
			{
				$covered_base++;
			}
		}
	}
	my $fraction_uncovered = $uncovered_base / $span_count;
	my $fraction_covered = $covered_base / $span_count;
	print "$fraction_uncovered\tfraction-target_definition_uncovered\n";
	print "$uncovered_base\tuncovered_base_count\n";
	print "$fraction_covered\tfraction_covered\n";
	print "$covered_base\tcovered_base_count\n";
	print "$span_count\ttotal_base_count\n";
}

sub parseCommandLine
{
	my ($useage) = "

-target_definition

-probe_file

";

        for (my $i = 0; $i <= $#ARGV; $i++)
        {
                if ($ARGV[$i] =~ /^-/)
                {
                        $arg{$ARGV[$i]} = $ARGV[$i+1];
                }
        }
        die($useage) if (!($arg{-target_definition}));
        die($useage) if (!($arg{-probe_file}));
}
