#!/usr/bin/perl

use strict;
use warnings;

#
# Generate reference lists of unique k-mers from chromosome/subchromosome sequences
#
# usage:
#   generate_reference_lists.pl WORDLENGTH CHROMOSOME_FILES
#
# The chromosome-specific lists are named
#   BASENAME_WLEN.list
# Where BASENAME is the filename of chromosome with path and suffix stripped
#

if (!defined ($ARGV[1])) {
  printf (STDERR "Usage:\n    generate_reference_lists.pl WORDLENGTH CHROMOSOME_FILES...\n");
  exit(1);
}

# Path to GenomeTester4 programs
my $gt4path = ".";
# Number of threads (for glistmaker)
my $nthreads = 16;
# Name of temporary full-genome list file
my $alltmp = "allchrs";
# name of temporary directory
my $tmpdir = "grl_temp";
# Print out command lines etc.
my $debug = 1;

my $glm = "$gt4path/glistmaker";
my $glc = "$gt4path/glistcompare";

my $wlen = $ARGV[0];

my @allchrs = splice (@ARGV, 1, @ARGV - 1);
my $allchrs = join (" ", @allchrs);

system ("mkdir $tmpdir");

# Generate master blacklist (of all k-mers with count >= 2)
my $cmd = "$glm $allchrs -w $wlen -c 2 --num_threads $nthreads -o $tmpdir/$alltmp";
if ($debug) {
  printf (STDERR "%s\n", $cmd);
}
if (system ($cmd)) {
  printf (STDERR "Cannot create list of all chromosmes\n");
  printf (STDERR "Command was:\n$cmd\n");
  die $!;
}

# Generate chromosome-specific lists
foreach (@allchrs) {
  my @t = split ("/", $_);
  @t = split ("\\.", $t[-1]);
  my $list = $t[0];
  my $tmp = "${list}_tmp";
  $cmd = "$glm $_ -w $wlen -o $tmpdir/$tmp";
  if ($debug) {
    printf (STDERR "%s\n", $cmd);
  }
  if (system ($cmd)) {
    printf (STDERR "Cannot create chromosome %s list\n", $list);
    printf (STDERR "Command was:\n$cmd\n");
    die $!;
  }
  $cmd = "$glc $tmpdir/${tmp}_$wlen.list $tmpdir/${alltmp}_$wlen.list -d -o $tmpdir/$tmp";
  if ($debug) {
    printf (STDERR "%s\n", $cmd);
  }
  if (system ($cmd)) {
    printf (STDERR "Cannot create chromosome %s unique list\n", $list);
    printf (STDERR "Command was:\n$cmd\n");
    die $!;
  }
  system ("mv $tmpdir/${tmp}_${wlen}_0_diff1.list ${list}_$wlen.list");
  system ("rm $tmpdir/${tmp}_$wlen.list");
}
system ("rm $tmpdir/${alltmp}_$wlen.list");
system ("rmdir $tmpdir");
