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

my $dir = getcwd;
my ($apep,$bpep,$dirb,$dirw,$flag) = ($ARGV[0],$ARGV[1],$ARGV[2],$ARGV[3],$ARGV[4]);

if(-e "$dirw/temp") {
  #system("rm -rf temp");
  #print "$dirw/temp file in $dirw\n";
}
else {
  system("mkdir $dirw/temp");
  #print "creat $dirw/temp in $dirw\n";
}
my ($apepo,$bpepo) = ($apep,$bpep);
$apep =~ /([^\/]+)$/;
$apep = $1;
$bpep =~ /([^\/]+)$/;
$bpep = $1;
my ($ablast,$bblast,$ablastb) = ($apep."_2_".$apep.".out",$bpep."_2_".$bpep.".out",$apep."_2_".$bpep.".out");

#print "\nremove previous softlinks, it's OK if they were not exist...\n";
if(-e "$dirw/temp/$apep") {
  system("rm $dirw/temp/$apep");
}
if(-e "$dirw/temp/$bpep") {
  system("rm $dirw/temp/$bpep");
}

if($flag==0) {
  system("ln -s $apepo $dirw/temp/$apep");
}
else {
  system("ln -s $dirw/$apepo $dirw/temp/$apep");
}

if($flag==0) {
  system("ln -s $bpepo $dirw/temp/$bpep");
}
else {
  system("ln -s $dirw/$bpepo $dirw/temp/$bpep");
}

$flag = 1;
if($flag==1) {
  my (@db,@qry,@out,@thr);
  ($db[0],$qry[0],$out[0]) = ("$apep","$apep","$ablast");
  ($db[1],$qry[1],$out[1]) = ("$bpep","$bpep","$bblast");
  ($db[2],$qry[2],$out[2]) = ("$bpep","$apep","$ablastb");
  for(my $i=0;$i<=2;$i+=1) {
    $thr[$i] = threads->create(\&process,$db[$i],$qry[$i],$out[$i],$i,$dirw);
  }
  for(my $i=0;$i<=2;$i+=1) {
    $thr[$i]->join;
  }
}
else {
  system("makeblastdb -in temp/$apep -dbtype prot");
  #system("blastp -db temp/$apep -query temp/$apep -outfmt 6 -out $ablast");
  #unlink "temp/".$apep.".phr";
  #unlink "temp/".$apep.".pin";
  #unlink "temp/".$apep.".psq";

  system("makeblastdb -in temp/$bpep -dbtype prot");
  system("blastp -db temp/$bpep -query temp/$bpep -outfmt 6 -out $bblast");

  print "Blastp to genes of the referece genome...\n";
  system("blastp -db temp/$bpep -query temp/$apep -outfmt 6 -out $ablastb");
  #unlink "temp/".$bpep.".phr";
  #unlink "temp/".$bpep.".pin";
  #unlink "temp/".$bpep.".psq";
}


sub process {
  my ($db,$qry,$out,$i,$dirw) = @_;
  if(!($out=~/^\//)) {
    $out = "$dirw/$out";
  }
  if(-e $out) {
    print "\n***NOTICE: DETECT previous blast results $out, if it's not the right one, stop SynOrths, remove $out, then run SynOrths again.***\n";
  }
  else {
    system("rm -rf $dirw/temp/db$i");
    system("mkdir $dirw/temp/db$i");
    system("ln -s ../$db $dirw/temp/db$i/$db");
    system("makeblastdb -in $dirw/temp/db$i/$db -dbtype prot");
    system("blastp -db $dirw/temp/db$i/$db -query $dirw/temp/$qry -outfmt 6 -out $out -num_threads 30");
    system("rm -rf $dirw/temp/db$i");
  }
}

