#!/usr/bin/perl -w
#####################################################
#Written By Ian Byrell Stanaway
#bard@u.washington.edu
####################################################
use strict;
my %arg;
#&parseCommandLine;
my $region_interval_list = "gene_interval_list2";#$arg{-region_interval_list};
#my $gene_exon_interval_definition = "/nfs/home/bard/public_html/references/hg19/codon_positions_mutation/seq_gene_hg19.md.Primary_Assembly";#$arg{-gene_exon_interval_definition};
my $gene_exon_interval_definition = "/nfs/home/bard/public_html/references/hg18/codon_positions_mutation/seq_gene_hg18.md.reference";#$arg{-gene_exon_interval_definition};

my %chr_position_1;

&get_definitons;

sub get_definitons
{
	open (FILE, $region_interval_list) or die "Can't open def 1\n";
	while (<FILE>)
	{
		my $line = $_;
		chomp $line;
		if ($line =~ m/^>/g)
		{}
		else
		{
			my @line_contents = split(/\s+/, $line);
			my $chr = $line_contents[0];
			$chr =~ s/chr//g;
			my $start = $line_contents[1];
			my $stop = $line_contents[2];
			#my $gene = $line_contents[3];
			#$chr_start_stop_info_1{$chr}{$start}{'s'} = $stop;
			#$chr_start_stop_info_1{$chr}{$start}{'g'} = $gene;
			for my $pos ($start .. $stop)
			{
				$chr_position_1{$chr}{$pos} = 0;
			}
		}
	}
	close FILE;


	my $outfile = "$region_interval_list.exons";
	open (OUTFILE, ">$outfile") or die "Can't open \n";
	open (FILE, $gene_exon_interval_definition) or die "Can't open def 2\n";
	while (<FILE>)
	{
		my $line = $_;
		chomp $line;
		if ($line =~ m/^>/g)
		{}
		else
		{
			my @line_contents = split(/\s+/, $line);
			my $chr = $line_contents[1];
			$chr =~ s/chr//g;
			my $start = $line_contents[2];
			my $stop = $line_contents[3];
			my $gene = $line_contents[9];
			my $dna_type = $line_contents[11];
			my $boolean = 0;
			for my $pos ($start .. $stop)
			{
				if (exists $chr_position_1{$chr}{$pos})
				{
					if ($dna_type eq "CDS")
					{
						$chr_position_1{$chr}{$pos} = 1;
						$boolean = 1;
					}
				}
			}
			if ($boolean == 1)
			{
				print OUTFILE "chr$chr\t$start\t$stop\n";
			}
		}
	}
	close FILE;
	close OUTFILE;
}

sub parseCommandLine
{
	my ($useage) = "

-region_interval_list 

-gene_exon_interval_definition 

";

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