#!/usr/bin/perl

$oldline = "";
$oldread = "";
@oldlines1 = (); @oldlines2 = ();

$dist_min = $ARGV[0];
$dist_max = $ARGV[1];
$diff_chr = $ARGV[2];

print "read_id\tpos1\tchr1\tfamily1\tpos2\tchr2\tfamily2\n";

while($_=<STDIN>) {
  chop();
  m/^([^\t]+).([12])\t/;
  $read = $1;
  $pair = $2;
  #print STDERR "MATCHED $read PAIR $pair\n";
  if(($read eq $oldread) || ($oldread eq "")) {
    if($pair eq "1") {
      push(@oldlines1, $_);
    } else {
      push(@oldlines2, $_);
    }
  } else {
    $len1 = scalar @oldlines1;
    $len2 = scalar @oldlines2;
    #print STDERR "LENGTHS = $len1;$len2\n";
    for($i=0;$i<$len1;$i++) {
      for($j=0;$j<$len2;$j++) {
        ($read1,$beg1,$end1,$chr1,$annot1) = split("\t",$oldlines1[$i]);
        ($read2,$beg2,$end2,$chr2,$annot2) = split("\t",$oldlines2[$j]);
        $read1 =~ m/([0-9]+\.[0-9]+)\/[12]/;
        $r1 = $1;
        $read2 =~ m/([0-9]+\.[0-9]+)\/[12]/;
        $r2 = $1;
        $pos1 = int(($beg1 + $end1)/2);
        $pos2 = int(($beg2 + $end2)/2);
        next if(($diff_chr eq "FALSE") && ($chr1 ne $chr2));
        next if(($chr1 eq $chr2) && ((abs($pos2-$pos1) < $dist_min) || (abs($pos2-$pos1) > $dist_max)));
        $annot1 =~ m/annot=([^;\n]*);*/;
        $a1 = $1;
        $annot2 =~ m/annot=([^;\n]*);*/;
        $a2 = $1;
        next if(($a1 eq "") || ($a2 eq ""));
        if($r1 ne $r2) {
          die "Error. Attempting to pair reads that do not form a pair. Exiting."
        }
        print "$r1\t$pos1\t$chr1\t$a1\t$pos2\t$chr2\t$a2\n";
        #print "$oldlines1[$i]\t$oldlines2[$j]\n";
      }
    }
    undef @oldlines1; undef @oldlines2;
    $oldlines1 = (); $oldlines2 = ();
    if($pair eq "1") {
      push(@oldlines1, $_);
    } else {
      push(@oldlines2, $_);
    }
  }
  $oldread = $read;
}

    $len1 = scalar @oldlines1;
    $len2 = scalar @oldlines2;
    for($i=0;$i<$len1;$i++) {
      for($j=0;$j<$len2;$j++) {
        ($read1,$beg1,$end1,$chr1,$annot1) = split("\t",$oldlines1[$i]);
        ($read2,$beg2,$end2,$chr2,$annot2) = split("\t",$oldlines2[$j]);
        $read1 =~ m/([0-9]+\.[0-9]+)\/[12]/;
        $r1 = $1;
        $read2 =~ m/([0-9]+\.[0-9]+)\/[12]/;
        $r2 = $1;
        $pos1 = int(($beg1 + $end1)/2);
        $pos2 = int(($beg2 + $end2)/2);
        $annot1 =~ m/annot=([^;\n]*);*/;
        $a1 = $1;
        $annot2 =~ m/annot=([^;\n]*);*/;
        $a2 = $1;
        next if(($a1 eq "") || ($a2 eq ""));
        if($r1 ne $r2) {
          die "Error. Attempting to pair reads that do not form a pair. Exiting."
        }
        next if(($diff_chr eq "FALSE") && ($chr1 ne $chr2));
        next if(($chr eq $chr2) && ((abs($pos2-$pos1) < $dist_min) || (abs($pos2-$pos1) > $dist_max)));
        print "$r1\t$pos1\t$chr1\t$a1\t$pos2\t$chr2\t$a2\n";
        #print "$oldlines1[$i]\t$oldlines2[$j]\n";
      }
    }
    

