#!/usr/bin/perl

use strict;
use warnings;

#
# Usage:
#   make_final_lists.pl WORDLENGTH CHR_LIST_DIR BLACKLIST WHITELIST_FEM WHITELIST_MALE
#
# It expects per-chromsome lists to have names:
#   CHR_WORLDEN.list
# Resulting lists are named:
#   CHR_cleaned_WORDLEN.list
#

if (!defined ($ARGV[2])) {
  printf (STDERR "Usage:\n");
  printf (STDERR "  make_final_lists.pl WORDLENGTH CHR_LIST_DIR BLACKLIST [WHITELIST]\n");
  exit (1);
}

my $glc = "./glistcompare";

my $wlen = $ARGV[0];
my $chr_dir = $ARGV[1];
my $blacklist = $ARGV[2];
my $whitelist = "";
if (defined ($ARGV[3])) {
  $whitelist = $ARGV[3];
}

my @chromosomes = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "X", "Y");

sub mysys {
  my $cmd = $_[0];
  printf (STDERR "%s\n", $cmd);
  if (system ($cmd)) {
    printf (STDERR "Cannot execute: %s\n", $cmd);
    exit (1);
  }
}

foreach (@chromosomes) {
  my $chr = $_;
  printf (STDERR "Chr %s\n", $chr);
  my $chrlist = "${chr_dir}/${chr}_${wlen}.list";
  my $cmd = "$glc $chrlist $blacklist -d -o tmp1";
  mysys ($cmd);
  my $result = "tmp1_${wlen}_0_diff1.list";
  if ($whitelist ne "") {
    $cmd = "$glc $result $whitelist -i -o tmp2";
    mysys ($cmd);
    mysys ("rm $result");
    $result = "tmp2_${wlen}_intrsec.list";
  }
  mysys ("mv $result ${chr}_cleaned_${wlen}.list");
}

printf (STDERR "Finished\n");
