#!/usr/bin/perl

use strict;
use warnings;

#
# usage:
#   add_rows.pl CHR_LIST_DIR LISTS
#

if (!defined ($ARGV[1])) {
  printf (STDERR "Usage:\n  add_rows.pl CHR_LIST_DIR LISTS\n");
  exit (1);
}

my $chr_dir = $ARGV[0];
my @lists = splice (@ARGV, 1, @ARGV - 1);

# Program locations
my $gt4dir = ".";
my $glq = "$gt4dir/glistquery";
my $glc = "$gt4dir/glistcompare";

# Chromosome whitelists
my $chr_suffix = "_cleaned_25.list";

my @chrs = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "X", "Y");
#my @chrs = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "X", "Y", "X_0", "X_1", "X_2", "X_3", "X_4", "X_5", "X_6", "X_7", "X_8", "X_9", "X_10", "X_11", "X_12", "X_13", "X_14", "X_15", "Y_0", "Y_1", "Y_2", "Y_5" );

my @chr_total;
my @chr_gc;

foreach (@chrs) {
  my $chr = $_;
  my $list = "${chr}${chr_suffix}";
  my $cmd = "$glq ${chr_dir}/${list} -stat";
  #printf (STDOUT "%s\n", $cmd);
  my $out = qx($cmd);
  # Wordlength      32
  # NUnique 33574272
  # NTotal  39292371
  my @t = split ("\n", $out);
  my @tt = split ("\t", $t[1]);
  my $wlen = $tt[1];
  @tt = split ("\t", $t[2]);
  my $unique = $tt[1];
  @tt = split ("\t", $t[3]);
  my $total = $tt[1];
  my $gc = gc ("${chr_dir}/${list}");
  push (@chr_total, $total);
  push (@chr_gc, $gc);
}

foreach (@lists) {
  my $list = $_;
  my @t = split ("/", $list);
  my $name = $t[-1];
  @t = split ("\\.", $name);
  $name = $t[0];
  $name = substr ($name, 0, length ($name) - 3);
  printf (STDOUT "%s", $name);
  my $cmd = "$glq ${list} -stat";
  #printf (STDOUT "%s\n", $cmd);
  my $out = qx($cmd);
  # Wordlength      32
  # NUnique 33574272
  # NTotal  39292371
  @t = split ("\n", $out);
  my @tt = split ("\t", $t[1]);
  my $wlen = $tt[1];
  @tt = split ("\t", $t[2]);
  my $unique = $tt[1];
  @tt = split ("\t", $t[3]);
  my $total = $tt[1];
  my $gc = gc ("${list}");
  printf (STDOUT "\t%s", $total);
  printf (STDOUT "\t%s", $unique);
  printf (STDOUT "\t%.3f", $gc);
  
  foreach (@chrs) {
    my $chr = $_;
    my $chr_list = "${chr}${chr_suffix}";
    my $cmd = "$glc $list ${chr_dir}/${chr_list} -i --count_only";
    my $out = qx($cmd);
    printf (STDERR "%s\n%s\n", $cmd, $out);
    # NUnique 8443982
    # NTotal  8443982
    @t = split ("\n", $out);
    my @tt = split ("\t", $t[1]);
    my $b = $tt[1];
    #printf (STDOUT "%s\t%.2f\t%s\t%s\n", $_, ($a + 0.0) / $b, $a, $b);
    printf (STDOUT "\t%s", $b);
  }
  printf (STDOUT "\n");
}

sub gc {
  my $list = $_[0];
  my $cmd = "$glq $list -gc";
  #printf (STDERR "%s\n", $cmd);
  my $out = qx($cmd);
  #printf (STDERR "%s\n", $out);
  my @t = split ("\t", $out);
  my $gc = $t[1];
  #printf (STDERR "%s\n", $gc);
  return $gc;
}
