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

my $dir = $ARGV[0];
my $dirw = $ARGV[1];
#my $numIG = $ARGV[2];
my $numIG = 5;
# format to tandem input datafile----------------------
my $in1 = "$dirw/temp/a2a.all";
open(FR1,$in1);
my $in2 = "$dirw/temp/a_coordfile";
open(FR2,$in2);
my $out1 = "$dirw/temp/a2a_datatemp";
open(FW1,">$out1");
my $out2 = "$dirw/temp/a_datafile";
open(FW2,">$out2");
my %gene2chr = ();
while(defined($_=<FR2>)) {
  /^([^\t]+)\t([^\t]+)\t/;
  if(!exists($gene2chr{$2})) {
    $gene2chr{$2} = $1;
  }
}
close(FR2);
while(defined($_=<FR1>)) {
  /^([^\t]+)\t([^\t]+)\t([^\n]+)\n/;
  if(exists($gene2chr{$1}) && exists($gene2chr{$2})) {
    print FW1 "$gene2chr{$1}\t$1\t$gene2chr{$2}\t$2\t$3\n";
  }
  else {
    #print "$1\t$2\t$3\n";
  }
}
close(FR1);
close(FW1);
open(FR3,$out1);
my %gene2rec = ();
while(defined($_=<FR3>)) {
  /^([^\t]+\t[^\t]+\t[^\t]+\t[^\t]+)\t/;
  my $temp = $1;
  /^[^\t]+\t([^\t]+)\t[^\t]+\t([^\t]+)\t([^\n]+)\n/;
  if($1 ne $2 && !exists($gene2rec{$temp}) && $3<=1e-20) {
    $gene2rec{$temp} = $_;
    print FW2 "$_";
  }
}
close(FR3);
close(FW2);
#unlink $in1;
unlink $out1;


$in1 = "$dirw/temp/b2b.all";
open(FR1,$in1);
$in2 = "$dirw/temp/b_coordfile";
open(FR2,$in2);
$out1 = "$dirw/temp/b2b_datatemp";
open(FW1,">$out1");
$out2 = "$dirw/temp/b_datafile";
open(FW2,">$out2");
%gene2chr = ();
while(defined($_=<FR2>)) {
  /^([^\t]+)\t([^\t]+)\t/;
  if(!exists($gene2chr{$2})) {
    $gene2chr{$2} = $1;
  }
}
close(FR2);
while(defined($_=<FR1>)) {
  /^([^\t]+)\t([^\t]+)\t([^\n]+)\n/;
  if(exists($gene2chr{$1}) && exists($gene2chr{$2})) {
    print FW1 "$gene2chr{$1}\t$1\t$gene2chr{$2}\t$2\t$3\n";
  }
  else {
    #print "$1\t$2\t$3\n";
  }
}
close(FR1);
close(FW1);
open(FR3,$out1);
%gene2rec = ();
while(defined($_=<FR3>)) {
  /^([^\t]+\t[^\t]+\t[^\t]+\t[^\t]+)\t/;
  my $temp = $1;
  /^[^\t]+\t([^\t]+)\t[^\t]+\t([^\t]+)\t([^\n]+)\n/;
  if($1 ne $2 && !exists($gene2rec{$temp}) && $3<=1e-20) {
    $gene2rec{$temp} = $_;
    print FW2 "$_";
  }
}
close(FR3);
close(FW2);
#unlink $in1;
unlink $out1;

#system("perl $dir/bin/findTandemGeneDuplicates.pl $dirw/temp/a_coordfile temp/a_datafile > $dirw/temp/a2aTandemDups");
#system("perl $dir/bin/findTandemGeneDuplicates.pl $dirw/temp/b_coordfile temp/b_datafile > $dirw/temp/b2bTandemDups");
system("perl $dir/bin/tandem_determination.pl $dirw/temp/a_coordfile temp/a_datafile $numIG $dirw/temp/a2aTandemDups");
system("perl $dir/bin/tandem_determination.pl $dirw/temp/b_coordfile temp/b_datafile $numIG $dirw/temp/b2bTandemDups");

unlink "$dirw/temp/a_coordfile";
unlink "$dirw/temp/a_datafile";
unlink "$dirw/temp/b_coordfile";
unlink "$dirw/temp/b_datafile";


