#! /opt/gensoft/adm/bin/perl
use lib "/opt/gensoft/exe/oriTfinder/1.1/lib/perl5";
# Xiaobin Li, Meng Liu and Hong-Yu Ou on Feb-27-2018
# School of Life Sciences & Biotechnology, Shanghai Jiao Tong University

use warnings;

# use same perl interpreter
# scripts prg goes to libexec
# tools prg called from path
use Config;
my $PERL = $Config{perlpath};

my $usage1 = q(
Welcome to use oriTfinder local version!
oriTfinder is a perl-based tool to predicte the Origin of Transfers in DNA sequences of bacterial Mobile Genetic Elements. 
oriTfinder also has a web version, you can access it easily by http://bioinfo-mml.sjtu.edu.cn/oriTfinder/.
-------------------------------------------------------------------------------------------------
Usage:	perl oriTfinder_local.pl list_file

The list file should contain the names of GenBank files(*.gbk or *.gb)in the directory 'oriTfinder/gbk' line by line.
List File Format Example
=====
BN000925.gbk
NC_001735.gbk
pKPHS1.gb
pKPHS2.gb
pKPHS3.gb
pRJA166a.gbk

For more details, please see the README.txt file.

If you have any question, please feel free to contact the authors:
hyou@sjtu.edu.cn
xiaobinli@sjtu.edu.cn

);
die($usage1) if ( @ARGV < 1 );


my $filein = shift;
my @strain;
my $i=0;
my $log = "oriTfinder.log"; 

system("dos2unix $filein >/dev/null 2>&1");
open LOG, ">$log";
open FILE, "< $filein" or die "ERROR: can't open the $filein!\n$usage1";

while(my $line=<FILE>){
		chomp $line;
		$strain[$i] = trim($line);
		my $seqinput = $strain[$i]; #query files
		if ($seqinput =~ /(.+)\.gb/){
			my $acc = $1 ;
		if (-e "./gbk/$acc.gb" || -e "./gbk/$acc.gbk" ){
			my $tmp_path = "./tmp/$acc";
			if(-e $tmp_path){
				system("rm -rf $tmp_path");
			}
                        # allow mkdir to succeed even if ./tmp does not exist
			system("mkdir -p $tmp_path");
			system("chmod 777 $tmp_path");
			print LOG "Work on $acc\n";			
   
			my $candidate_gbk_1 = "./gbk/$acc.gbk";
			my $candidate_gbk_2 = "./gbk/$acc.gb";
			my $candidate_gbk = "$tmp_path/$acc.gbk";
			my $candidate_fna = "$tmp_path/$acc.fna";
			if(-e $candidate_gbk_1){
				`cp $candidate_gbk_1 $candidate_gbk`;
			}
			if(-e $candidate_gbk_2){
				`cp $candidate_gbk_2 $candidate_gbk`;
			}
			!system("seqret $candidate_gbk $candidate_fna 1>/dev/null 2>/dev/null") or die("For $acc:\n Error:  The uploaded file of $acc is not a standard GenBank format!\n$usage1");
			!system("$PERL /opt/gensoft/exe/oriTfinder/1.1/libexec/gbk2ptt_and_faa.pl $tmp_path/$acc") or die("For $acc:\n Error:  The uploaded file of $acc is not a standard GenBank format!\n$usage1");
			print "For $acc: Searching for Relaxase, oriT, T4CP, T4SS, ARs, VFs of the mobile genetic element...\n";
			
			my $cmd_relaxase_and_oriT ="$PERL /opt/gensoft/exe/oriTfinder/1.1/libexec/oriTfinder_relaxase_and_oriT.pl $acc";
			system($cmd_relaxase_and_oriT);
				
			my $cmd_T4SS ="$PERL /opt/gensoft/exe/oriTfinder/1.1/libexec/oriTfinder_T4SS.pl $acc";
			system($cmd_T4SS);
				
			my $cmd_T4CP ="$PERL /opt/gensoft/exe/oriTfinder/1.1/libexec/oriTfinder_T4CP.pl $acc";
			system($cmd_T4CP);
				
			my $cmd_ARG ="$PERL /opt/gensoft/exe/oriTfinder/1.1/libexec/oriTfinder_AR_blastp.pl $acc";
			system($cmd_ARG);
				
			my $cmd_VF ="$PERL /opt/gensoft/exe/oriTfinder/1.1/libexec/oriTfinder_VF_blastp.pl $acc";
			system($cmd_VF);

			my $cmd_summary ="$PERL /opt/gensoft/exe/oriTfinder/1.1/libexec/oriTfinder_summary.pl $acc";
			system($cmd_summary);
			}else{
				print "For $acc: \n ERROR: Can not find the GenBank file of $acc in ./gbk directory!\n";
				print LOG "For $acc: \n ERROR: Can not find the GenBank file of $acc in ./gbk directory!\n";
				}
			}else{
				print "For $seqinput: \n ERROR: $seqinput is not a standard Genbank file!\n$usage1";
				}
		$i++;	
		}
		
close FILE;
close LOG;

sub  trim { 
	my $s = shift; 
	$s =~ s/^\s+|\s+$//g; 
	return $s; 
}
exit;

sub upload_check_ptt_format {
##############################################
## check the uploaded CDS file in NCBI ptt format
##############################################
              my $file=shift;
              my $myCDSFileFormat="CDS_unkown0";
			  my $fieldno=0;
              my $lineNo=1;
              open(INPUT,"<". $file)  or die "Unable open the file ". $file." .\n";
             
              while (<INPUT>){          # retrieve file, line by line
                   
                   $lineNo++;
                   $fieldno=0;
             	   if(/[0-9]+\.\.[0-9]+/ or /proteins/ or /Location/){
             			 		
						if(( /[0-9]+\.\.[0-9]+/ ) and ($lineNo >2)){
                      		
                             my @fields = split "\t";
                               $fieldno = scalar @fields;
                             if ($fieldno > 5){
                                  $myCDSFileFormat="CDS_PTT";
                             }else{
                                 $myCDSFileFormat= "CDS_unkown2 (Num of Fields = $fieldno, Line $lineNo)";
                                 last;
                             }
                 		}
                 			
              		}else{
                             $myCDSFileFormat="CDS_unkown1 (Line $lineNo)";
                             last;
                  }
                  
               }

  return $myCDSFileFormat;
}

sub TransformCDSFile{
#####################################################################
## Transform the CDS position file format from 'NCBI PTT' into 'TSV' .
#####################################################################
        my ($infile) = @_;
        my $tempfile = "$infile.coords";
        my @start=();
        my @stop=();
        my @strand=();
        my @name=();
        my @description=();
        my $i=0;
        my $k=0;
        my $CDSNum=0;

        open(INPUT,"<".$infile)  or die "Unable open the file ".$infile." .\n";
        my $lineNo=1;
        while (<INPUT>){          # retrieve file, line by line
             $lineNo++;
             if (( /[0-9]+\.\.[0-9]+/ ) and ($lineNo >2)) {
                my @fields = split "\t";
                if ( $fields[0] =~ /([0-9]+)..([0-9]+)/){
                        $start[$CDSNum] = $1;
                        $stop[$CDSNum] = $2;
                        $strand[$CDSNum] =$fields[1];
                        $name[$CDSNum] = $fields[5];
                        if (scalar @fields > 6){$name[$CDSNum]=$name[$CDSNum]."\n";}
                        $CDSNum++;
                }
             }
          }
        close (INPUT);

        open (OUTFILE, "> $tempfile") || die "Unable open  $tempfile!\n" ;
        for($i=0;$i<$CDSNum;$i++){
                print OUTFILE $start[$i], "\t", $stop[$i], "\t", $strand[$i], "\t", $name[$i];
        }
        close (OUTFILE);
}
