#!/usr/bin/perl -w
# 
# Copyright (c) BIO_MARK 2021
# Writer:         Dengdj <dengdj@biomarker.com.cn>
# Program Date:   2021
# Modifier:       Dengdj <dengdj@biomarker.com.cn>
# Last Modified:  2021
my $ver="v1.1";

use strict;
use Getopt::Long;
use FindBin qw($Bin $Script);
use File::Basename qw(basename dirname);
use threads;
use threads::shared;

#####################

my %opts;
GetOptions(\%opts,"i1=s","i2=s","d=s","p=s","k=s","r=s","m=s","c=s","t=s","h" );

#&help()if(defined $opts{h});
if(!defined($opts{i1}) || !defined($opts{i2}) || !defined($opts{d}) || !defined($opts{p}) || defined($opts{h}))
{
	print <<"	Usage End.";
	Description:
		
		Version: $ver

	Usage:

		-i1          read1 file                              <infile>     must be given
		-i2          read2 file                              <infile>     must be given
		-d           result dir                              <outdir>     must be given
		-p           outfile prefix                          <string>     must be given
		-k           kmer file                               [infile]     optional
		-r           ref_seq dir                             [indir]      optional
		-c           collect dir                             [outdir]     optional
		-t           thread num                              [default 8]  optional
		-h           Help document

	Usage End.

	exit;
}

###############Time
my $Time_Start;
$Time_Start = sub_format_datetime(localtime(time()));
&show_log("Start Time :[$Time_Start]");
################
$| = 1 ;
## get parameters
my $read1file = $opts{i1} ;
my $read2file = $opts{i2} ;
my $outdir = $opts{d} ;
mkdir $outdir if (!-d $outdir);
my $prefix = $opts{p} ;
#my $collect_dir = defined $opts{c} ? $opts{c} : "$outdir/../$prefix" ;
#mkdir $collect_dir if (!-d $collect_dir) ;
my $threads = defined $opts{t} ? $opts{t} : 8;

## check para
&check_para(\%opts);

## process
my $kmerfile ;
if (!defined $opts{k} && !defined $opts{r}){
    $kmerfile = "$Bin/../ref_file_SC/Sk6.kmerfile" ;
}
elsif (defined $opts{k}){
    $kmerfile = $opts{k} ;
}
else{
    #$kmerfile = &generate_kmerfile($opts{r}, $outdir, $prefix);
}
&show_log("use kmerfile: $kmerfile");

##############################################################################多线程处理
if($read1file =~ /.gz$/){
	# 计算文件总行数
	my $total_num = `zcat $read1file | awk 'END{print NR}'`;
	# 每个子文件的行数
	my $size = (int($total_num / ($threads * 4)) + 1)*4;
	##########快速拆分fastq 数据，需要判断数据是否gz压缩
	`zcat $read1file | awk -v sz=$size  'BEGIN{i=1}{ print \$0 > "$outdir/$prefix." i ".tmp.fq"; if (NR>=i*sz){close("$prefix." i ".tmp.fq");i++}}'`;
}else{
	# 计算文件总行数
	my $total_num = `awk 'END{print NR}' $read1file`;
	# 每个子文件的行数
	my $size = (int($total_num / ($threads * 4)) + 1)*4;
	##########快速拆分fastq 数据，需要判断数据是否gz压缩
	`awk -v sz=$size  'BEGIN{i=1}{ print \$0 > "$outdir/$prefix." i ".tmp.fq"; if (NR>=i*sz){close("$prefix." i ".tmp.fq");i++}}' $read1file`;
}

#######################并行运行,确保捕获的FQ数据是按照顺序来的
my @files;
foreach(1..$threads){
    push @files,"$outdir/$prefix.$_.tmp.fq";
}
#my @files = glob "$outdir/*.tmp.fq";
# 开始多线程
foreach (0..$threads-1){
    my $thr = threads -> create(\&get_bc, $files[$_], $outdir,$prefix,$kmerfile, $_);
}

# join各个线程的结果
my @num_array2;
while(threads -> list()){
    foreach my $t(threads -> list(threads::joinable)){
        my $tmp = $t -> join();
        push @num_array2,$tmp;
    }
}
print "threads:@num_array2\n";
unlink @files;

###########################
#&get_bc($read1file, $outdir, $prefix, $kmerfile);
######get_bc结果整理合并

`rm $outdir/$prefix.umi` if -e "$outdir/$prefix.umi";
`rm $outdir/$prefix.filter ` if -e "$outdir/$prefix.filter";
foreach (0..$threads-1){
	`cat $outdir/$prefix.$_.umi >>$outdir/$prefix.umi`;
	`cat $outdir/$prefix.$_.filter >>$outdir/$prefix.filter`;
	`rm $outdir/$prefix.$_.umi $outdir/$prefix.$_.filter`;
}

##########质量统计合并
my @qual_stat = glob "$outdir/$prefix.*.qual.stat";
my ($total_Reads,$valid_barcode,$valid_umi,$final_valid_Reads);
foreach my $qual_stat(@qual_stat){
	chomp $qual_stat;
	open IN,$qual_stat or die $!;
	while(<IN>){
		chomp;
		next if /^\s*$/;
		my ($id,$num,$ratio) = split /\t+/;
		$total_Reads += $num if $id eq "Number of Reads";
		$valid_barcode += $num if $id eq "Valid Barcodes";
		$valid_umi += $num if $id eq "Valid UMIs";
		$final_valid_Reads += $num if $id eq "Final Valid Reads";
	}
	close IN;
}
open OUT, ">$outdir/$prefix.qual.stat" or die $!;
my $valid_barcode_ratio = sprintf "%.2f",$valid_barcode / $total_Reads * 100;
my $valid_umi_ratio = sprintf "%.2f",$valid_umi / $total_Reads * 100;
my $final_valid_Reads_ratio = sprintf "%.2f",$final_valid_Reads / $total_Reads * 100;
print OUT "Number of Reads\t$total_Reads\t100\n";
print OUT "Valid Barcodes\t$valid_barcode\t$valid_barcode_ratio\n";
print OUT "Valid UMIs\t$valid_umi\t$valid_umi_ratio\n";
print OUT "Final Valid Reads\t$final_valid_Reads\t$final_valid_Reads_ratio\n";
print OUT "\n";
close OUT;
##########barcode统计合并
my @bc_stat = glob "$outdir/$prefix.*.bc_stat";
my ($bc1,$bc1_bc2,$bc1_bc2_bc3,$bc1_bc3,$bc2,$bc2_bc3,$bc3);
foreach my $bc_stat(@bc_stat){
	chomp $bc_stat;
	open IN,$bc_stat or die $!;
	while(<IN>){
		chomp;
		next if /^\s*$/;
		next if /^\#/;
		last if /^\===/;
		my ($id,$num,$ratio) = split;
		if($id eq "bc1"){
			$bc1 += $num;
			next;
		}elsif($id eq "bc1-bc2"){
			$bc1_bc2 += $num;
			next;
		}elsif($id eq "bc1-bc2-bc3"){
			$bc1_bc2_bc3 += $num;
			next;
		}elsif($id eq "bc1-bc3"){
			$bc1_bc3 += $num;
			next;
		}elsif($id eq "bc2"){
			$bc2 += $num;
		}elsif($id eq "bc2-bc3"){
			$bc2_bc3 += $num;
		}elsif($id eq "bc3"){
			$bc3 += $num;
			next;
		}
	}
	close IN;
}
my $bc1_ratio = sprintf "%.2f",$bc1 / $total_Reads * 100;
my $bc2_ratio = sprintf "%.2f",$bc2 / $total_Reads * 100;
my $bc3_ratio = sprintf "%.2f",$bc3 / $total_Reads * 100;
my $bc1_bc2_ratio = sprintf "%.2f",$bc1_bc2 / $total_Reads * 100;
my $bc1_bc2_bc3_ratio = sprintf "%.2f",$bc1_bc2_bc3 / $total_Reads * 100;
my $bc1_bc3_ratio = sprintf "%.2f",$bc1_bc3 / $total_Reads * 100;
my $bc2_bc3_ratio = sprintf "%.2f",$bc2_bc3 / $total_Reads * 100;
my $bc1_single = $bc1 + $bc1_bc2 + $bc1_bc2_bc3 + $bc1_bc3;
my $bc2_single = $bc2 + $bc2_bc3 + $bc1_bc2_bc3 + $bc1_bc2; 
my $bc3_single = $bc3 + $bc1_bc3 + $bc1_bc2_bc3 + $bc2_bc3; 
my $bc1_single_ratio = sprintf "%.2f",$bc1_single / $total_Reads * 100;
my $bc2_single_ratio = sprintf "%.2f",$bc2_single / $total_Reads * 100;
my $bc3_single_ratio = sprintf "%.2f",$bc3_single / $total_Reads * 100;
open OUT, ">$outdir/$prefix.bc_stat" or die $!;
print OUT "#Type\tReadsNum\tPercent(%)\n";
print OUT "bc1\t$bc1\t$bc1_ratio\n";
print OUT "bc1-bc2\t$bc1_bc2\t$bc1_bc2_ratio\n";
print OUT "bc1-bc2-bc3\t$bc1_bc2_bc3\t$bc1_bc2_bc3_ratio\n";
print OUT "bc1-bc3\t$bc1_bc3\t$bc1_bc3_ratio\n";
print OUT "bc2\t$bc2\t$bc2_ratio\n";
print OUT "bc2-bc3\t$bc2_bc3\t$bc2_bc3_ratio\n";
print OUT "bc3\t$bc3\t$bc3_ratio\n";
print OUT "======== single stat ========\n";
print OUT "bc1\t$bc1_single\t$bc1_single_ratio\n";
print OUT "bc2\t$bc2_single\t$bc2_single_ratio\n";
print OUT "bc3\t$bc3_single\t$bc3_single_ratio\n";
close OUT;
##########stat统计合并
my @stat;
for(my $i = 0;$i < $threads;$i++){
	push @stat,"$outdir/$prefix.$i.stat";
}
my ($full,$part,$null,$umi,$final);
foreach my $stat(@stat){
	chomp $stat;
	open IN,$stat or die $!;
	while(<IN>){
		chomp;
		next if /^\s*$/;
		next if /^===/;
		my ($id,$num,$ratio) = split;
		$full += $num if $id eq "Full";
		$part += $num if $id eq "Part";
		$umi += $num if $id eq "UMI";
		$final += $num if $id eq "Final";
	}
	close IN;
}
my $full_ratio = sprintf "%.2f",$full / $total_Reads * 100;
my $part_ratio = sprintf "%.2f",$part / $total_Reads * 100;
my $umi_ratio = sprintf "%.2f",$umi / $total_Reads * 100;
my $final_ratio = sprintf "%.2f",$final / $total_Reads * 100;
$null = $total_Reads - $full - $part;
my $null_ratio = sprintf "%.2f",$null / $total_Reads * 100;
open OUT, ">$outdir/$prefix.stat" or die $!;
print OUT "Total\t$total_Reads\t100\n";
print OUT "Full\t$full\t$full_ratio\n";
print OUT "Part\t$part\t$part_ratio\n";
print OUT "Null\t$null\t$null_ratio\n";
print OUT "============\n";
print OUT "UMI\t$umi\t$umi_ratio\n";
print OUT "Final\t$final\t$final_ratio\n";
close OUT;

#########清理中间文件
for(my $i = 0;$i < $threads;$i++){
	`rm $outdir/$prefix.$i.qual.stat`;
	`rm $outdir/$prefix.$i.bc_stat`;
	`rm $outdir/$prefix.$i.stat`;
}
##################################################################################################
#my $cmd = "perl $Bin/barcode_rec/umi_correct.pl -i $outdir/$prefix.umi -o $outdir/$prefix" ;
#&run_or_die($cmd) ;
#&collect_result($outdir, $prefix, $collect_dir);

###############Time
my $Time_End;
$Time_End = sub_format_datetime(localtime(time()));
&show_log("End Time :[$Time_End]");

###############Subs
sub sub_format_datetime {#Time calculation subroutine
    my($sec, $min, $hour, $day, $mon, $year, $wday, $yday, $isdst) = @_;
	$wday = $yday = $isdst = 0;
    sprintf("%4d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon+1, $day, $hour, $min, $sec);
}


# &show_log("txt")
sub show_log()
{
	my ($txt) = @_ ;
	my $time = time();
	my $Time = &sub_format_datetime(localtime($time));
	print "$Time:\t$txt\n" ;
	return ($time) ;
}

#&run_or_die($cmd);
sub run_or_die()
{
	my ($cmd) = @_ ;
	my $start_time = &show_log($cmd);
	my $flag = system($cmd) ;
	if ($flag != 0){
		my $end_time = &show_log("Error: command fail: $cmd");
		&show_log("Elaseped time: ".($end_time - $start_time)."s\n");
		exit(1);
	}
	my $end_time = &show_log("done.");
	&show_log("Elaseped time: ".($end_time - $start_time)."s\n");
	return ;
}

#&check_para(\%opts);
sub check_para()
{
    my ($ahopts) = @_ ;

    if (!-f $ahopts->{i1}){
        &show_log("reads file not exist, please check: -i1 ".$ahopts->{i1});
        exit(1);
    }
    if (!-f $ahopts->{i2}){
        &show_log("reads file not exist, please check: -i2 ".$ahopts->{i2});
        exit(1);
    }
    if (defined $ahopts->{k} && !-f $ahopts->{k}){
        &show_log("kmer file not exist, please check: -k ".$ahopts->{k});
        exit(1);
    }
    if (defined $ahopts->{r}){
        my $ref_dir = $ahopts->{r} ;
        if (!-d $ref_dir){
            &show_log("-r $ref_dir not exist, please check");
            exit(1);
        }
        if (!-f "$ref_dir/bc1.fa" || !-f "$ref_dir/bc2.fa" || !-f "$ref_dir/bc3.fa" || !-f "$ref_dir/ref_seq.fa"){
            &show_log("$ref_dir must contain: bc1.fa bc2.fa bc3.fa ref_seq.fa, please check");
            exit(1);
        }
    }

    return ;
}

#$kmerfile = &generate_kmerfile($opts{r}, $outdir, $prefix);
sub generate_kmerfile()
{
    my ($ref_dir, $outdir, $prefix) = @_ ;

    my $kmerfile = "$outdir/$prefix.kmerfile" ;
    my $cmd = "perl $Bin/tools/get_uniq_kmer_v1.2.new_bc.pl $ref_dir/bc1.fa $ref_dir/bc2.fa $ref_dir/bc3.fa $ref_dir/ref_seq.fa $kmerfile" ;
    &run_or_die($cmd) ;

    return($kmerfile);
}

#&get_bc($readsfile, $outdir, $prefix, $kmerfile, $minkmernum);
sub get_bc()
{
    my ($readsfile, $outdir, $prefix, $kmerfile,$num) = @_ ;

    my $bcfile = "$Bin/../ref_file_SC/bcs.fa" ;
    my $cmd = "perl $Bin/get_reads_bc_type_v2.2.pl -i $readsfile -k $kmerfile -b $bcfile -d $outdir -p $prefix.$num" ;
    &run_or_die($cmd) ;

    return ($num);
}

#&collect_result($outdir, $prefix, $collect_dir);
sub collect_result()
{
    my ($outdir, $prefix, $collect_dir) = @_ ;

    my $cmd = "cp $outdir/$prefix.bc_umi_read.tsv $collect_dir/bc_umi_read.tsv && gzip -f $collect_dir/bc_umi_read.tsv" ;
    &run_or_die($cmd) ;
    $cmd = "cp $outdir/$prefix.barcodes.tsv $collect_dir/barcodes.tsv && gzip -f $collect_dir/barcodes.tsv" ;
    &run_or_die($cmd) ;

    return ;
}

