#!/usr/bin/env perl
use warnings;
use strict;
use Getopt::Long;
use FindBin qw($Bin $Script);
use File::Basename qw(basename dirname);
use Cwd qw(abs_path);

my %opts;
GetOptions(\%opts,"c=s","s=s","h");
if(!defined($opts{c}) || !defined($opts{s}) ||defined($opts{h})){
        print <<"       Usage End.";

Description:
              Version:v1.0.3

Usage:
    -c        config           <file>       must be given
    -s        run step         <int>        must be given
              step number:
              0:                  run all step
              1:                  run BSTMatrixPB
              2:                  run IgBlast
              3:                  run CreateMatrix
              4:                  run Basic stat 
              5:                  run web report

    -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 $cfgfile = abs_path($opts{c});
my $step = $opts{s} ;

## reading cfg file
my %hcfg = ();
&reading_cfg_file($cfgfile, \%hcfg);

##create output directory
my $od = $hcfg{OUTDIR};
mkdir($od,0755) unless -d $od;

##judge step
my @numbers = split /\,/, $step ;
@numbers = sort {$a<=>$b} @numbers ;
if ($numbers[0] == 0){
    @numbers = (1,2,3,4,5);
}

###########main process-step1
for my $num (@numbers){
    if($num == 1){
        mkdir("$od/01.BSTMatrixPb",0755) unless -d "$od/01.BSTMatrixPb";
        mkdir("$od/01.BSTMatrixPb/IG",0755) unless -d "$od/01.BSTMatrixPb/IG";
        mkdir("$od/01.BSTMatrixPb/TR",0755) unless -d "$od/01.BSTMatrixPb/TR";
        ##IG
        my $cmd = "$Bin/BSTMatrixPb/BSTMatrixPb -i $hcfg{CCS_IG} -c $cfgfile -s 0 -k IG -o $od/01.BSTMatrixPb/IG\n";
        &run_or_die($cmd);
        $cmd = "$Bin/BSTMatrixPb/BSTMatrixPb -i $hcfg{CCS_TR} -c $cfgfile -s 0 -k TR -o $od/01.BSTMatrixPb/TR\n";
        &run_or_die($cmd);
    }
    elsif($num == 2){
        mkdir("$od/02.IgBlast",0755) unless -d "$od/02.IgBlast";
        ##IG
        my $readinfo = "$od/01.BSTMatrixPb/IG/02.fastq2BcUmi/IG.bc_type_cor.umi";
        my $idmap = "$od/01.BSTMatrixPb/IG/02.fastq2BcUmi/IG.id_map";
        #my $cmd = "perl $Bin/IgBlast_vdj.pl -i $readinfo -v $idmap -f $hcfg{CCS_IG} -t IG -o $od/02.IgBlast/$hcfg{PREFIX}.IG -k $hcfg{PREFIX} -p $hcfg{Threads}\n";
        my $cmd = "perl $Bin/IgBlast_vdj.pl -i $readinfo -v $idmap -f1 $od/01.BSTMatrixPb/IG/01.cutread1/IG.cut.ccs.fastq -f2 $hcfg{CCS_IG} -t IG -o $od/02.IgBlast/$hcfg{PREFIX}.IG -k $hcfg{PREFIX} -p $hcfg{Threads}\n";
        &run_or_die($cmd);
        ##TR
        $readinfo = "$od/01.BSTMatrixPb/TR/02.fastq2BcUmi/TR.bc_type_cor.umi";
        $idmap = "$od/01.BSTMatrixPb/TR/02.fastq2BcUmi/TR.id_map";
        #$cmd = "perl $Bin/IgBlast_vdj.pl -i $readinfo -v $idmap -f $hcfg{CCS_TR} -t TR -o $od/02.IgBlast/$hcfg{PREFIX}.TR -k $hcfg{PREFIX} -p $hcfg{Threads}\n";
        $cmd = "perl $Bin/IgBlast_vdj.pl -i $readinfo -v $idmap -f1 $od/01.BSTMatrixPb/TR/01.cutread1/TR.cut.ccs.fastq -f2 $hcfg{CCS_TR} -t TR -o $od/02.IgBlast/$hcfg{PREFIX}.TR -k $hcfg{PREFIX} -p $hcfg{Threads}\n";
        &run_or_die($cmd);
    }elsif($num == 3){
        if(-d "$od/03.Matrix"){
            `rm -rf $od/03.Matrix`;
            mkdir("$od/03.Matrix",0755) unless -d "$od/03.Matrix";
        }else{
            mkdir("$od/03.Matrix",0755) unless -d "$od/03.Matrix";
        }
        mkdir("$od/03.Matrix/$hcfg{PREFIX}.IG",0755) unless -d "$od/03.Matrix/$hcfg{PREFIX}.IG";
        mkdir("$od/03.Matrix/$hcfg{PREFIX}.TR",0755) unless -d "$od/03.Matrix/$hcfg{PREFIX}.TR";
        ##barcode vs level.xls Cell.xls
        &generate_LNCell("IG");
        &generate_LNCell("TR");
        ##productive -> matrix
        &create_matrix("$od/03.Matrix/$hcfg{PREFIX}.IG","$od/02.IgBlast/$hcfg{PREFIX}.IG/$hcfg{PREFIX}.read.result.xls","IG");
        &create_matrix("$od/03.Matrix/$hcfg{PREFIX}.TR","$od/02.IgBlast/$hcfg{PREFIX}.TR/$hcfg{PREFIX}.read.result.xls","TR");
    }elsif($num == 4){
        mkdir("$od/04.Basic_stat",0755) unless -d "$od/04.Basic_stat";
        mkdir("$od/04.Basic_stat/$hcfg{PREFIX}.IG",0755) unless -d "$od/04.Basic_stat/$hcfg{PREFIX}.IG";
        mkdir("$od/04.Basic_stat/$hcfg{PREFIX}.TR",0755) unless -d "$od/04.Basic_stat/$hcfg{PREFIX}.TR";
        &create_clonotype("$od/03.Matrix/$hcfg{PREFIX}.IG","$od/02.IgBlast/$hcfg{PREFIX}.IG/$hcfg{PREFIX}.read.result.xls","$od/04.Basic_stat/$hcfg{PREFIX}.IG");
        &create_clonotype("$od/03.Matrix/$hcfg{PREFIX}.TR","$od/02.IgBlast/$hcfg{PREFIX}.TR/$hcfg{PREFIX}.read.result.xls","$od/04.Basic_stat/$hcfg{PREFIX}.TR");
        &clonotype_num("$od/03.Matrix/$hcfg{PREFIX}.IG","IG","$od/04.Basic_stat/$hcfg{PREFIX}.IG");
        &clonotype_num("$od/03.Matrix/$hcfg{PREFIX}.TR","TR","$od/04.Basic_stat/$hcfg{PREFIX}.TR");
    }elsif($num == 5){
        mkdir("$od/05.Web_Report",0755) unless -d "$od/05.Web_Report";
        my $cmd = "perl $Bin/web_report/create_report.pl -c $cfgfile\n";
        &run_or_die($cmd);
    }
}

#################################log
sub reading_cfg_file()
{
    my ($cfgfile, $ahcfg) = @_ ;

    open (IN, $cfgfile) || die "$cfgfile, $!\n" ;
    while(<IN>){
        chomp ;
        next if (m/^\#|^\s*$/);
        my ($key, $value) = split /\s+/ ;
        $ahcfg->{$key} = $value ;
    }
    close(IN);
    if (!defined $ahcfg->{CCS_IG} || !-f $ahcfg->{CCS_IG}){
        &show_log("Error: CCS_IG file must be given and exist while -s 1 is select.");
        exit(1);
    }
    if (!defined $ahcfg->{CCS_TR} || !-f $ahcfg->{CCS_TR}){
        &show_log("Error: CCS_TR file must be given and exist while -s 1 is select.");
        exit(1);
    }
    if (!defined $ahcfg->{LinkBcChip} || !-d $ahcfg->{LinkBcChip}){
        &show_log("Error: LinkBcChip dir must be given and exist while -s 1 is select.");
        exit(1);
    }
    if (!defined $ahcfg->{CellSplit} || !-d $ahcfg->{CellSplit}){
        &show_log("Error: CellSplit dir must be given and exist while -s 1 is select.");
        exit(1);
    }
    if (!defined $ahcfg->{HE} && !defined $ahcfg->{he_hr} && !defined $ahcfg->{fluorescence}){
        &show_log("Error: HE/he_hr/fluorescence file must be at least given one while -s 4 is select.");
        exit(1);
    }
    if (defined $ahcfg->{HE} && !-f $ahcfg->{HE}){
        &show_log("HE file not exist, please check: $ahcfg->{HE}");
        exit(1);
    }
    if (defined $ahcfg->{he_hr} && !-f $ahcfg->{he_hr}){
        &show_log("he_hr file not exist, please check: $ahcfg->{he_hr}");
        exit(1);
    }
    if (!defined $ahcfg->{HE} && !defined $ahcfg->{he_hr} && defined $ahcfg->{fluorescence} && !-f $ahcfg->{fluorescence}){
        &show_log("fluorescence file not exist, please check: $ahcfg->{fluorescence}");
        exit(1);
    }
    die "The OUTDIR dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{OUTDIR});
    die "The Threads dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{Threads});
    die "The PREFIX dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{PREFIX});
    die "The CHIP dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{CHIP});
    die "The BCType dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{BCType});
    die "The ReadNum dose not exists, please check $cfgfile\n" if (!exists $ahcfg->{ReadNum});
    return ;
}


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


##########################################################
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);
}

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

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 ;
}

sub generate_LNCell(){
    my ($igtr) = @_ ;
    my @s1000 = qw /1 2 3 4 5 6 7 13/;
    my @s3000 = qw /1 2 3 4 5 7 9 18/;
    if($hcfg{CHIP} eq "S1000"){
        for(my $i = 0;$i < @s1000;$i++){
            my $cmd = "cd $od/03.Matrix/$hcfg{PREFIX}.$igtr && perl $Bin/BC2LNCell/barcode2LNCell.pl -b $od/01.BSTMatrixPb/$igtr/$igtr/barcode.tsv -c $od/01.BSTMatrixPb/$igtr/04.AllheStat/level_matrix/level_$s1000[$i]/barcodes_cluster.tsv.gz -k L$s1000[$i] -p $od/01.BSTMatrixPb/$igtr/04.AllheStat/heAuto_level_matrix/subdata/L$s1000[$i]_heAuto/barcodes_pos.tsv.gz";
            $cmd .= " -cs $hcfg{CellSplit}/cell_split_result/all_barcode_num.txt\n" if $s1000[$i] == 1;
            $cmd .= "\n" if $s1000[$i] != 1;
            &run_or_die($cmd);
        }
    }elsif($hcfg{CHIP} eq "S3000"){
        for(my $i = 0;$i < @s3000;$i++){
            my $cmd = "cd $od/03.Matrix/$hcfg{PREFIX}.$igtr && perl $Bin/BC2LNCell/barcode2LNCell.pl -b $od/01.BSTMatrixPb/$igtr/$igtr/barcode.tsv -c $od/01.BSTMatrixPb/$igtr/04.AllheStat/level_matrix/level_$s3000[$i]/barcodes_cluster.tsv.gz -k L$s3000[$i] -p $od/01.BSTMatrixPb/$igtr/04.AllheStat/heAuto_level_matrix/subdata/L$s3000[$i]_heAuto/barcodes_pos.tsv.gz";
            $cmd .= " -cs $hcfg{CellSplit}/cell_split_result/all_barcode_num.txt\n" if $s3000[$i] == 1;
            $cmd .= "\n" if $s3000[$i] != 1;
            &run_or_die($cmd);
        }
    }
}

sub create_matrix(){
    my ($dir,$readresult,$type) = @_;
    my @level = glob "$dir/*.xls";
    foreach (@level){
        chomp;
        my $base = basename($_);
        $base =~ s/.xls$//;
        mkdir("$dir/$base",0755) unless -d "$dir/$base";
        my $cmd = "cd $dir/$base && perl $Bin/BC2LNCell/IgBlast_LNCell_stat.pl $readresult $type $_ $base $hcfg{PREFIX} $hcfg{ReadNum}";
        $cmd .= "&& Rscript $Bin/create_matrix/create_matrix_level.R $_  $hcfg{PREFIX}.$base.Productive.xls $base && perl $Bin/create_matrix/pivot.pl matriX.xls $base.csv && Rscript $Bin/create_matrix/create_matrix.R $base.csv $base\_matrix\n" if $base ne 'Cell';
        $cmd .= "&& Rscript $Bin/create_matrix/create_matrix_cell.R $_  $hcfg{PREFIX}.$base.Productive.xls $base && Rscript $Bin/create_matrix/create_matrix.R $base.csv $base\_matrix\n" if $base eq 'Cell';
        &run_or_die($cmd);
        ##IG和TR共用一张切片
        $cmd = "cp $od/01.BSTMatrixPb/$type/04.AllheStat/allhe/he_roi_small.png $dir/$base/$base\_matrix && cp $od/01.BSTMatrixPb/$type/04.AllheStat/heAuto_level_matrix/subdata/$base\_heAuto/barcodes_pos.tsv.gz $dir/$base/$base\_matrix\n" if $base ne 'Cell';
        $cmd = "cp $od/01.BSTMatrixPb/$type/04.AllheStat/allhe/he_roi_small.png $dir/$base/$base\_matrix && cp $hcfg{CellSplit}/mtx/barcodes_pos.tsv.gz $dir/$base/$base\_matrix\n" if $base eq 'Cell';
        &run_or_die($cmd);
        $cmd = "cd $dir/$base && Rscript $Bin/create_matrix/createRDS.R $base\_matrix $hcfg{CHIP} $base level\n" if $base ne 'Cell';
        $cmd = "cd $dir/$base && Rscript $Bin/create_matrix/createRDS.R $base\_matrix $hcfg{CHIP} $base Cell\n" if $base eq 'Cell';
        &run_or_die($cmd);
    }
}

sub create_clonotype(){
    my ($dir,$readresult,$path) = @_;
    my @level = glob "$dir/*.xls";
    foreach (@level){
        chomp;
        my $base = basename($_);
        $base =~ s/.xls$//;
        my $cmd = "cd $path && perl $Bin/IgBlast_clonotype_stat.pl $dir/$base/$hcfg{PREFIX}.$base.Productive.xls $readresult $base\n";
        &run_or_die($cmd);
    }
    #my $clonotype = join (" ",glob "$path/*.clonotype.xls");
    #my $cmd = "cd $path && /share/nas2/genome/biosoft/java/jdk/current/bin/java -Xmx10G -jar $Bin/software/vdjtools-1.2.1/vdjtools-1.2.1.jar CalcDiversityStats $clonotype $hcfg{PREFIX}\n";
    #&run_or_die($cmd);
}

sub clonotype_num(){
    my ($dir,$type,$path) = @_;
    my @level = glob "$dir/*.xls"; 
    open OUT,">$path/$hcfg{PREFIX}.$type.chain.clonotype.num.xls" or die $!;
    foreach (@level){
        chomp;
        my $base = basename($_);
        $base =~ s/.xls$//;
        if($type eq 'IG'){
            my $IGH = `grep 'IGH' $dir/$base/$hcfg{PREFIX}.$base.Productive.xls | cut -f 5 |sort |uniq |wc -l`;chomp $IGH;
            my $IGK = `grep 'IGK' $dir/$base/$hcfg{PREFIX}.$base.Productive.xls | cut -f 5 |sort |uniq |wc -l`;chomp $IGK;
            my $IGL = `grep 'IGL' $dir/$base/$hcfg{PREFIX}.$base.Productive.xls | cut -f 5 |sort |uniq |wc -l`;chomp $IGL;
            my $IGHA = `grep 'IGHA' $dir/$base/$hcfg{PREFIX}.$base.Productive.addCgene.xls | cut -f 5 |sort |uniq |wc -l`;chomp $IGHA;
            my $IGHD = `grep 'IGHD' $dir/$base/$hcfg{PREFIX}.$base.Productive.addCgene.xls | cut -f 5 |sort |uniq |wc -l`;chomp $IGHD;
            my $IGHE = `grep 'IGHE' $dir/$base/$hcfg{PREFIX}.$base.Productive.addCgene.xls | cut -f 5 |sort |uniq |wc -l`;chomp $IGHE;
            my $IGHG = `grep 'IGHG' $dir/$base/$hcfg{PREFIX}.$base.Productive.addCgene.xls | cut -f 5 |sort |uniq |wc -l`;chomp $IGHG;
            my $IGHM = `grep 'IGHM' $dir/$base/$hcfg{PREFIX}.$base.Productive.addCgene.xls | cut -f 5 |sort |uniq |wc -l`;chomp $IGHM;
            print OUT "$base\t$IGH\t$IGK\t$IGL\t$IGHA\t$IGHD\t$IGHE\t$IGHG\t$IGHM\n";
        }elsif($type eq 'TR'){
            my $TRA = `grep 'TRA' $dir/$base/$hcfg{PREFIX}.$base.Productive.xls | cut -f 5 |sort |uniq |wc -l`;chomp $TRA;
            my $TRB = `grep 'TRB' $dir/$base/$hcfg{PREFIX}.$base.Productive.xls | cut -f 5 |sort |uniq |wc -l`;chomp $TRB;
            print OUT "$base\t$TRA\t$TRB\n";
        }else{
            next;
        }
    }
    close OUT;
}
















