#!/usr/bin/perl -w
#Author: Feng Cheng
use warnings;
use strict;

my $dirw = $ARGV[0];
#--blastp best hit---------------
my $in = "$dirw/temp/a2b.all_delTandem";
open(FR,$in);
my $out = "$dirw/temp/a2b.all_delTandem_bestHit";
open(FW,">$out");
my %a2rec = ();
while(defined($_=<FR>)) {
  /^([^\t]+)\t/;
  if(!exists($a2rec{$1})) {
    $a2rec{$1} = $_;
    print FW "$_";
  }
}
close(FR);
close(FW);

#--add position and sort--------------------------------
my $in1 = "$dirw/temp/b_gene_sorted_delTandem";
open(FR1,$in1);
my $in2 = "$dirw/temp/a_gene_sorted_delTandem";
open(FR2,$in2);
my $in3 = "$dirw/temp/a2b.all_delTandem";
open(FR3,$in3);
my $out1 = "$dirw/temp/a2b.all_delTandem_pos";
open(FW1,">$out1");
my $out2 = "$dirw/temp/temp";
open(FW2,">$out2");
my %bGenePosi = ();
while(defined($_=<FR1>)) {
  /^([^\t]+)\t([^\t]+\t\d+\t\d+)\n/;
  $bGenePosi{$1} = $2;
}
close(FR1);
my %aGenePosi = ();
while(defined($_=<FR2>)) {
  /^([^\t]+)\t([^\t]+\t\d+\t\d+)\n/;
  $aGenePosi{$1} = $2;
}
close(FR2);
my ($aGene,$bGene,$eValue);
while(defined($_=<FR3>)) {
  /^([^\t]+)\t([^\t]+)\t([^\n]+)\n/;
  $aGene = $1;
  $bGene = $2;
  $eValue = $3;
  if(exists($aGenePosi{$aGene}) && exists($bGenePosi{$bGene})) {
    print FW1 "$aGene\t$aGenePosi{$aGene}\t$bGene\t$bGenePosi{$bGene}\t$eValue\n";
  }
  else {
    #print FW2 $_;
  }
}
close(FR3);
close(FW1);
close(FW2);
unlink $out2;
unlink $in3;

#--sort and filter the p2p result-----------------  run in server need for big memory
$in1 = "$dirw/temp/a2b.all_delTandem_pos";
open(FR,$in1);
$out1 = "$dirw/temp/a2b.all_delTandem_pos.filter";
open(FW1,">$out1");
$out2 = "$dirw/temp/a2b.all_delTandem_pos.temp";
open(FW2,">$out2");

my @input1 = map{[$_,(split(/\t/))[1],(split(/\t/))[2],(split(/\t/))[3]]} <FR>;
my @input2 = sort{$a->[1] cmp $b->[1] || $a->[2] <=> $b->[2] || $a->[3] <=> $b->[3]} @input1;
my @sorted = map{$_->[0]} @input2;

for(@sorted) {
  print FW2 "$_";
}
close(FW2);

open(FR2,$out2);
my %gene2evalue = ();
my %agene2bgene = ();
while(defined($_=<FR2>)) {
  /^([^\t]+)/;
  $aGene = $1;
  /\t([^\t]+)$/;
  $eValue = $1;
  /^[^\t]+\t[^\t]+\t[^\t]+\t[^\t]+\t([^\t]+)\t/;
  $bGene = $1;
  my $temp = $aGene.$bGene;
  if(!exists($gene2evalue{$aGene})) {
    $gene2evalue{$aGene} = $eValue;
    print FW1 $_;
    $agene2bgene{$temp} = "Y";
  }
  elsif(!exists($agene2bgene{$temp}) && ($gene2evalue{$aGene} eq $eValue || $eValue<=1e-20)) {
    print FW1 $_;
    $agene2bgene{$temp} = "Y";
  }
}
close(FR2);
close(FW1);
unlink $in1;
unlink $out2;


