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

my $dirw = $ARGV[0];
#---delete tandem genes----------------
my $in1 = "$dirw/temp/a2aTandemDups.lst";
open(FR1,$in1);
my $in2 = "$dirw/temp/a_gene_sorted";
open(FR2,$in2);
my $out = "$dirw/temp/a_gene_sorted_delTandem";
open(FW,">$out");
my %tandem2first = ();
while(defined($_=<FR1>)) {
  /\t([^;]+);/;
  my $temp = $1;
  s/\n/;/;
  while(/\t[^;]+;/) {
    s/\t([^;]+);/\t/;
    $tandem2first{$1} = $temp;
  }
}
close(FR1);
while(defined($_=<FR2>)) {
  /^([^\t]+)\t/;
  if( (exists($tandem2first{$1})&&$1 eq $tandem2first{$1}) || !exists($tandem2first{$1}) ) {
    print FW $_;
  }
}
close(FR2);
close(FW);
unlink $in2;

$in1 = "$dirw/temp/b2bTandemDups.lst";
open(FR1,$in1);
$in2 = "$dirw/temp/b_gene_sorted";
open(FR2,$in2);
$out = "$dirw/temp/b_gene_sorted_delTandem";
open(FW,">$out");
%tandem2first = ();
while(defined($_=<FR1>)) {
  /\t([^;]+);/;
  my $temp = $1;
  s/\n/;/;
  while(/\t[^;]+;/) {
    s/\t([^;]+);/\t/;
    $tandem2first{$1} = $temp;
  }
}
close(FR1);
while(defined($_=<FR2>)) {
  /^([^\t]+)\t/;
  if( (exists($tandem2first{$1})&&$1 eq $tandem2first{$1}) || !exists($tandem2first{$1}) ) {
    print FW $_;
  }
}
close(FR2);
close(FW);
unlink $in2;

#--the blastp result tandem remove----------------
$in1 = "$dirw/temp/a2aTandemDups.lst";
open(FR1,$in1);
$in2 = "$dirw/temp/b2bTandemDups.lst";
open(FR2,$in2);
my $in3 = "$dirw/temp/a2b.all";
open(FR3,$in3);
$out = "$dirw/temp/a2b.all_delTandem";
open(FW,">$out");
my $temp;
my %aTandem2first = ();
while(defined($_=<FR1>)) {
  s/\n/;/;
  /\t([^;]+);/;
  $temp = $1;
  while(/\t[^;]+;/) {
    s/\t([^;]+);/\t/;
    $aTandem2first{$1} = $temp;
  }
}
close(FR1);
my %bTandem2first = ();
while(defined($_=<FR2>)) {
  s/\n/;/;
  /\t([^;]+);/;
  $temp = $1;
  while(/\t[^;]+;/) {
    s/\t([^;]+);/\t/;
    $bTandem2first{$1} = $temp;
  }
}
close(FR2);
while(defined($_=<FR3>)) {
  /^([^\t]+)\t([^\t]+)\t([^\n]+)\n/;
  if((exists($aTandem2first{$1})&&$1 eq $aTandem2first{$1}) || !exists($aTandem2first{$1})) {
    if(exists($bTandem2first{$2})) {
      print FW "$1\t$bTandem2first{$2}\t$3\n";
    }
    else {
      print FW "$1\t$2\t$3\n";
    }
  }
}
close(FR3);
close(FW);
#unlink $in3;


