#!/usr/bin/perl

use strict;
#use List::MoreUtils qw(uniq);

open FILE, $ARGV[0] or die $!;
my $last="";
my %regions;
while(<FILE>)
{    
    chomp();
    my @tmp = split("\t",$_);
    $tmp[3] =~ tr/_/\t/;
    $tmp[8] =~ tr/_/\t/;
    if ($last ne join("\t", @tmp[0,1,2])) {$last=join("\t", @tmp[0,1,2])};
#    {
	if ($tmp[3] ne ".")
	    {
		my @toPush1 = split("\t",join("\t",@tmp[3,4,5,6,7],"old"));
		push @{$regions{$last}}, \@toPush1;
	    }
    	if ($tmp[8] ne ".")
	    {
		my @toPush2 = split("\t",join("\t",@tmp[8,9,10,11,12],"new"));
		push @{$regions{$last}}, \@toPush2;
	    }
#	push @{$regions{$last}},split("\t",join("\t",@tmp[8,9,10,11,12],"new"))[0,1,2,3,4] if $tmp[8] ne ".";
#    }
#    else
#    {
#	$last=join("\t", @tmp[0,1,2]);
#	$regions{$last}[0]=split("\t",join("\t",@tmp[3,4,5,6,7],"old")) if $tmp[3] ne ".";
#	push @{$regions{$last}},split("\t",join("\t",@tmp[8,9,10,11,12],"new")) if $tmp[8] ne ".";
#   };
};



foreach my $key (sort(keys(%regions)))
{
    my @tmp = sort {$a->[1] <=> $b->[2]} @{$regions{$key}};
    my @info;
    my $coords;
    my $regions=0;
    my $plast;
    my %seen;
    foreach (@tmp)
    {
	$plast = 0; 
	my $line = join(".",@{$_});
	if ($seen{$line})
	{
	    next;
	}
	else
	{
	    $seen{$line} = 1;
	};
	unless (@info)
	{
	    for (my $i=0; $i < @{$_}; $i++)
	    {
		$info[$i] = @{$_}[$i];
	    }
	    $coords = join("_",@{$_}[0,1,2]);
	    $regions = 1;
	    next;
	};
	if (@{$_}[1] < $info[2])
	{

	    $info[2] = @{$_}[2];
	    for (my $i=3; $i < @{$_}; $i++)
	    {
		$info[$i] = join(",",$info[$i],@{$_}[$i]);
	    }
	    $coords .= ",".join("_",@{$_}[0,1,2]);
	    $regions += 1;
	}
	else
	{
	    print join("\t",$key,@info,$regions,$coords),"\n";
	    $plast = 1;
	    $info[1] = @{$_}[1];
	    $info[2] = @{$_}[2];
	    for (my $i=0; $i < @{$_}; $i++)
	    {
		$info[$i] = @{$_}[$i];
	    }
	    $coords = join("_",@{$_}[0,1,2]);
	    $regions = 1;
	};
    }
    print join("\t",$key,@info,$regions,$coords),"\n" if $plast = 0;    
}

sub lmerge
{
    my @tmp = sort {$a <=> $b} @_;
    return ($tmp[0],$tmp[3]);
}

sub overlap
{
    my $start1=@_[0];
    my $end1=@_[1];
    my $start2=@_[2];
    my $end2=@_[3];

    if (($end1 >= $start2 && $start1<=$end2) || ($end2 >= $start1 && $start2 <= $end1))
    {return 1}
    else
    {return 0};
};
