#!/usr/bin/perl -w
#####################################################
#Written By Ian Byrell Stanaway
#bard@u.washington.edu
####################################################
use strict;
my %arg;
&parseCommandLine;
my $exon_file = $arg{-exon_file};
my %Genes_chr_exon_start_stop;
my %chr_pos;

&get_exon_file;
my $seq_count = 0;
my $outfile = $exon_file . ".collapsed_to_chr_exon_start_stop";
open (OUTFILE, ">$outfile") or die "Can't open outfile\n";
foreach my $chr (sort keys %Genes_chr_exon_start_stop)
{
	foreach my $exon_start (sort {$a <=> $b} keys %{$Genes_chr_exon_start_stop{$chr}})
	{
		my $exon_stop = $Genes_chr_exon_start_stop{$chr}{$exon_start};
		print OUTFILE "chr$chr\t$exon_start\t$exon_stop\n";
	}
}
close OUTFILE;

sub get_exon_file
{
	my $all_genes_isoform_count = 0;
	open (FILE, $exon_file) or die "Can't open \n";
	while (<FILE>)
	{
		$all_genes_isoform_count++;
		my $line = $_;
		if ($line =~ m/^chr/g)
		{
			chomp $line;
			my @line_contents = split(/\s+/, $line);
			my $chr = $line_contents[0];
			$chr =~ s/chr//gi;
			my $exon_start = $line_contents[1] - 2;#get splice
			my $exon_stop = $line_contents[2] + 2;
			for my $pos ($exon_start .. $exon_stop)
			{
				$chr_pos{$chr}{$pos} = 0;
			}
		}
	}
	close FILE;

	#find the overlapping
	foreach my $chr (keys %chr_pos)
	{
		my $first_pos = 0;
		foreach my $pos (sort {$a <=> $b} keys %{$chr_pos{$chr}})
		{
			if ($first_pos == 0)
			{
				$first_pos = $pos;
			}
			my $pos_plus_one = $pos + 1;
			if (exists $chr_pos{$chr}{$pos_plus_one})
			{}
			else
			{
				$Genes_chr_exon_start_stop{$chr}{$first_pos} = $pos;
				$first_pos = 0;
			}
		}
	}
}

sub parseCommandLine
{
	my ($useage) = "

-exon_file


";

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