#!/usr/bin/perl

#
# usage:
#   pipe.pl BAM WORDLEN MINCOUNT TEMPDIR COMPONENT_SIZE
#

use strict;
use warnings;

my $clip = "/storage5/programs/NIPT/clip_sam.pl";
my $glistmaker = "/storage5/programs/NIPT/glistmaker";
my $glistcompare = "/storage5/programs/NIPT/glistcompare";

my $bam = $ARGV[0];
if (!(-f $bam)) {
  printf (STDERR "Usage: bam2list.pl BAM_NAME WORDSIZE MIN_COUNT [TEMP_DIR_NAME] [PART_SIZE]\n");
  exit (1);
}
my @t = split ("/", $bam);
my $bamname = $t[-1];
@t = split ("\\.", $bamname);
my $name = $t[0];

my $wordlen = $ARGV[1];
my $mincount = 2;
if (defined ($ARGV[2])) {
  $mincount = $ARGV[2];
}
my $dir = "temp";
if (defined ($ARGV[3])) {
  $dir = $ARGV[3];
}

my $compsize = 400000000;
if (defined ($ARGV[4])) {
  $compsize = $ARGV[4];
}

my $result;

if (!(-d $dir)) {
  mkdir ($dir);
}
my $cmd = "samtools view $bam | $clip $dir/t_ $compsize";
printf (STDERR "%s\n", $cmd);
printf (STDERR "%s\n", scalar(localtime));
$result = system ($cmd);
if ($result != 0) {
  die ("Error extracting FastA");
}

printf (STDERR "Creating lists\n");
printf (STDERR "%s\n", scalar(localtime));
my $files = qx(ls $dir/t_*);
my @files = split ("\n", $files);
foreach (@files) {
  chomp ($_);
  $cmd = "$glistmaker $_ -w $wordlen --num_threads 1 -o $_";
  #printf (STDERR "%s\n", $cmd);
  $result = system ($cmd);
  if ($result != 0) {
    die ("Error making list");
  }
}
system ("rm $dir/t_*.fasta");

$cmd = "$glistcompare $dir/t_*.list -u -c $mincount -o $bamname";
printf (STDERR "%s\n", scalar(localtime));
printf (STDERR "%s\n", $cmd);
$result = system ($cmd);
if ($result != 0) {
  die ("Error creating union");
}

system ("rm -rf $dir");
system ("mv ${bamname}_${wordlen}_union.list ${name}_${wordlen}.list");
printf (STDERR "%s\n", scalar(localtime));
