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

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

my %opts;
GetOptions(\%opts,"c=s","o=s","s=s","i=s","k=s","h");

if(!defined($opts{c}) || !defined($opts{s}) || !defined($opts{i}) || !defined($opts{k}) || !defined($opts{o}) || defined($opts{h}))
{
	print <<"	Usage End.";
	Description:
		
		Version: v1.0

	Usage:

	        ./BSTMatrixPb -i IG.ccs.fq -c config.txt -k key -o ./ -s 0
	        ./BSTMatrixPb -i IG.ccs.fq -c config.txt -k key -o ./ -s 1,2,3,4

	Parameters:

		-i           fq  file                      <infile>     must be given
		-c           cfg file                      <infile>     must be given
		-o           outdir                        <dir>        must be given
		-k           keyword                       <str>        must be given
		-s           run step                      <int>        must be given
		             step number:
		                       0:                  run all step
		                       1:                  run cut read1
		                       2:                  run fastq2BcUmi
		                       3:                  run LinkBcChip
		                       4:                  run AllheStat
		-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 $fastq = abs_path($opts{i}) ;
my $cfgfile = abs_path($opts{c}) ;
my $step = $opts{s} ;
my $result_dir = abs_path($opts{o});
my $prefix = $opts{k};
mkdir($result_dir,0755) unless -d $result_dir;

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

## run process
&run_process($step, \%hcfg);

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

#&reading_cfg_file($cfgfile, \%hcfg);
sub reading_cfg_file()
{
    my ($cfgfile, $ahcfg) = @_ ;

    open (IN, $cfgfile) || die "$cfgfile, $!\n" ;
    while(<IN>){
        chomp ;
        next if (m/^\#|^\s*$/);
        my ($key, $value) = split ;
        $ahcfg->{$key} = $value ;
    }
    close(IN);
    return ;
}
##
sub check_para()
{
    my ($ahcfg, $anumbers) = @_ ;

    for my $num (@{$anumbers}){
        if ($num == 4){
            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);
            }
        }
    }

    return ;
}

#&run_process($step, \%hcfg);
sub run_process()
{
    my ($step, $ahcfg) = @_ ;

    my @numbers = split /\,/, $step ;
    @numbers = sort {$a<=>$b} @numbers ;
    if ($numbers[0] == 0){
        @numbers = (1,2,3,4);
    }
    &show_log("step: @numbers");
    &check_para($ahcfg, \@numbers);
    for my $num (@numbers){
        if($num == 1){
            my $outdir = "$result_dir/01.cutread1" ;
            mkdir $outdir if (!-d $outdir) ;
            my $cmd = "cd $outdir && $Bin/ccscutRead1 $fastq $prefix.cut.ccs.fastq\n";
            &run_or_die($cmd) ;
        }
        if ($num == 2){
            my $outdir = "$result_dir/02.fastq2BcUmi" ;
            mkdir $outdir if (!-d $outdir) ;
            my $threads = $ahcfg->{Threads} ;
            my $cmd = "perl $Bin/fastq2BcUmi -i1 $result_dir/01.cutread1/$prefix.cut.ccs.fastq -i2 $result_dir/01.cutread1/$prefix.cut.ccs.fastq -d $outdir -p $prefix -n $threads" ;
            if (defined $ahcfg->{KmerFile}){
                $cmd .= " -k $ahcfg->{KmerFile}" ;
            }
            if (defined $ahcfg->{BCType}){
                $cmd .= " -t $ahcfg->{BCType}" ;
            }
            &run_or_die($cmd) ;
        }
        elsif ($num == 3){
            my $outdir = "$result_dir/03.LinkBcChip" ;
            mkdir $outdir if (!-d $outdir) ;
            my $cmd = "perl $Bin/LinkBcChip -i $ahcfg->{LinkBcChip} -l $result_dir/02.fastq2BcUmi/$prefix.full_stat -d $outdir -p $prefix" ;
            &run_or_die($cmd) ;
            my $size = -s "$outdir/$prefix.barcode.tsv" ;
            if ($size == 0){
                print "$outdir/$prefix.barcode.tsv file size is 0. pelese check\n" ;
                exit(1);
            }
        }
        elsif ($num == 4){
            my $outdir = "$result_dir/04.AllheStat" ;
            mkdir $outdir if (!-d $outdir) ;
            my $python_env = " " ;
            if (defined $ahcfg->{PYTHON}){
                $python_env = "export PATH=".$ahcfg->{PYTHON}.":\$PATH && " ;
            }
            my $cmd = "" ;
            if (defined $ahcfg->{HE} && -f $ahcfg->{HE}){
                $cmd = "$python_env python $Bin/AllheStat.py -m $result_dir/$prefix/ -o $outdir -e $ahcfg->{HE}" ;
            }
            elsif (defined $ahcfg->{he_hr} && -f $ahcfg->{he_hr}){
                $cmd = "$python_env python $Bin/AllheStat.py -m $result_dir/$prefix/ -o $outdir -e $ahcfg->{he_hr}" ;
            }
            elsif (defined $ahcfg->{fluorescence} && -f $ahcfg->{fluorescence}){
                my $fluorescence_channl = defined $ahcfg->{fluorescence_channl} ? $ahcfg->{fluorescence_channl} : (defined $ahcfg->{fluorescence_channel} ? $ahcfg->{fluorescence_channel} : 0) ;
                $cmd = "$python_env python $Bin/AllheStat.py -m $result_dir/$prefix/ -o $outdir -e $ahcfg->{fluorescence} -f $fluorescence_channl" ;
            }
            else{
                &show_log("Error: HE file or fluorescence file must have one, please check your config file");
                exit(1);
            }
            if (defined $ahcfg->{GRAY}){
                my $gray_num = $ahcfg->{GRAY} ;
                $cmd .= " -g $gray_num" ;
            }
            if (defined $ahcfg->{FLGRAY}){
                my $fl_gray_num = $ahcfg->{FLGRAY} ;
                $cmd .= " -l $fl_gray_num" ;
            }
            if (defined $ahcfg->{INSIDE}){
                my $get_inside = $ahcfg->{INSIDE} ;
                $cmd .= " -s $get_inside" ;
            }
            $cmd .= " -c $ahcfg->{CHIP}" ;
            &run_or_die($cmd) ;
        }
    }
    return ;
}

