$Lane=$ARGV[0];
$Tag=$ARGV[1];
$Length=$ARGV[2];

$Index="$Lane.$Tag.PE.fastq";

open (p1,"$Index.p1");
open (p2,"$Index.p2");
open (OutP1,">$Index.Parent1");
open (OutP2,">$Index.Parent2");

%Status=();

HERE1: while (<p1>){
	$line = $_;
	chomp($line);
	@array = split(/\t/,$line);
	$Map=$array[3];
	$Alig=$array[9];
	$ID=$array[0];
	$Chro=$array[7];
	$S=$array[8];
	if ($Map == 1){
		$Status{$ID}=$Alig;
	}
}

HERE2: while (<p2>){
	$line = $_;
	chomp($line);
	@array = split(/\t/,$line);
	$Map=$array[3];
	$Alig=$array[9];
	$ID=$array[0];
	$Chro=$array[7];
	$S=$array[8];
	$E=$array[8]+$Length-1;
	if ($Map == 1){
		if (($Status{$ID}==0 && $Alig==1) or ($Status{$ID}==1 && $Alig==2)){
			print OutP1 "$ID	$Chro	$S	$E\n";
		}elsif (($Status{$ID}==1 && $Alig==0) or ($Status{$ID}==2 && $Alig==1)){
			print OutP2 "$ID	$Chro	$S	$E\n";
		}
	}
}

close (p1);close (p2);
close (OutP1);close (OutP2);

open (OUT,">$Index.rlt");
foreach $m(1..12){
	%score=();%sub=();
	
 open (IN,"$Index.Parent1");
 while (<IN>){
  if ($_=~/^\S+	chromosome(\d+)	(\d+)	\d+/){	
    if($1 == $m){
   	$score{$_}=$2;
   	$sub{$_}="P1";
    }	
  }   
 } 
 close (IN);

 open (IN,"$Index.Parent2");
 while (<IN>){
  if ($_=~/^\S+	chromosome(\d+)	(\d+)	\d+/){	
    if($1 == $m){
   	$score{$_}=$2;
   	$sub{$_}="P2";
    }	
  }   
 } 
 close (IN);

foreach $temp (sort by_score keys %score){
  $a= $sub{$temp};
  print OUT "$a	$temp";
}	

}
close (OUT);


sub by_score { $score{$a} <=> $score {$b} }

