use strict;
use FileHandle;


my $File1Name=$ARGV[0];
my $File2Name=$ARGV[1];

my %FileHandle1;
my %FileHandle2;
my %chrlist;

open(File1,$File1Name);
open(File2,$File2Name);

while(my $line1=<File1>)
{
	my $line2=<File2>;
	chomp($line1);
	chomp($line2);
	my $read1status=substr($line1,length($line1)-2,2);
	my $read2status=substr($line2,length($line2)-2,2);
	#next if( ($read1status eq "NM" or $read1status eq "MT") and ($read2status eq "NM" or $read2status eq "MT");
	my @array1=split("\t",$line1);
	my @array2=split("\t",$line2);
	my $chr1="";
	my $chr2="";
	if(scalar(@array1) eq 4)
	{
		if($array1[3]=~/(chr\S*?)\|/)
		{$chr1=$1;}
	}
	if(scalar(@array2) eq 4)
	{
        	if($array2[3]=~/(chr\S*?)\|/)
        	{$chr2=$1;}
	}
	my $chr=$chr1;
	if ($chr eq "")
	{
		next if($chr2 eq "");
		$chr=$chr2;
	}
	else
	{
		 next if($chr2 ne "" and $chr2 ne $chr);
		
	}
	next if $chr eq "";
	if(exists $chrlist{$chr})
	{
		my $fout1= $FileHandle1{$chr};
		my $fout2= $FileHandle2{$chr};
		if($read1status eq "MT")
		{
			print $fout1 $array1[0],"\t",$array1[1],"\tMT\n";
		}
		else
		{
			print $fout1 $line1,"\n";
		}
		if($read2status eq "MT")
                {
                        print $fout2 $array2[0],"\t",$array2[1],"\tMT\n";
                }
                else
                {
                        print $fout2 $line2,"\n";
                }



	}
	else
	{
		$chrlist{$chr}=1;
		my $fout1= new FileHandle;
		open($fout1, ">".$File1Name.".".$chr);
		$FileHandle1{$chr}=$fout1;
	
		my $fout2= new FileHandle;
                open($fout2, ">".$File2Name.".".$chr);
                $FileHandle2{$chr}=$fout2;
		
	}

}

foreach my $fout1 (keys %FileHandle1)
{
	close($fout1);
}
foreach my $fout2 (keys %FileHandle2)
{
        close($fout2);
}

close(File1);
close(File2);
