#!/usr/common/usg/languages/perl/5.16.0/bin/perl -w
#
# prefixer2i.pl by Jarrod Chapman <jchapman@lbl.gov> Sun Apr  1 06:34:21 PDT 2012
# Copyright 2012 Jarrod Chapman. All rights reserved.
#

use Getopt::Std;
my %opts = ();
my $validLine = getopts('p:d:M:W:', \%opts);
my @required = ("p","d",);
my $nRequired = 0;
map {$nRequired += exists($opts{$_})} @required;
$validLine &= ($nRequired == @required);
if ($validLine != 1) {
    print "Usage: ./prefixer2i.pl <-p prefixerFile> <-d depth> <<-M minPrefix>> <<-W weighting>>\n";
    exit;
}

my $prefixerFile = $opts{"p"};
my $depth = $opts{"d"};

my $minPrefix = 0;
if (exists($opts{"M"})) {
    $minPrefix = $opts{"M"};
}

my $weighting = 1;
if (exists($opts{"W"})) {
    $weighting = $opts{"W"};
}

open (P,$prefixerFile) || die "Couldn't open $prefixerFile\n";

my %prefixInfo = ();
my %pLen2Counts = ();
my %pLen2Distinct = ();
my @prefixes = ();

while (my $line = <P>) {
    chomp $line;
    my ($p,$c,$d,$e) = split(/\s+/,$line);
    my $l = length($p);

    unless ($l >= $minPrefix) {
	next;
    }

    push(@prefixes,$p);
    $prefixInfo{$p} = [$c,$d,$e];
    $pLen2Counts{$l} += $c;
    $pLen2Distinct{$l} += $d;
}
close P;

my @lengths = sort {$b <=> $a} keys(%pLen2Counts);
#foreach my $l (@lengths) {
#    $c = $pLen2Counts{$l};
#    $d = $pLen2Distinct{$l};
#    print "$l\t$c\t$d\n";
#}

my $maxLength = $lengths[0];
my $maxWeightMaxLen = 0;

my %prefixWeight = ();
while (my ($p,$i) = each(%prefixInfo)) {
    my ($c,$d,$e) = @{$i};
    my $l = length($p);
    my $fd = $d/$pLen2Distinct{$l};
    my $fc = $c/$pLen2Counts{$l};
    my $weight = $fd+$fc*$e*$depth;
    $prefixWeight{$p} = $weight;

    if (($l == $maxLength) && ($weight > $maxWeightMaxLen)) {
	$maxWeightMaxLen = $weight;
    }
}

while (my ($p,$w) = each(%prefixWeight)) {
    my $normWeight = $w/$maxWeightMaxLen;
    $prefixWeight{$p} = $normWeight;
}

my %parentOf = ();

foreach my $p (@prefixes) {
    my @kids = ($p."A",$p."C",$p."G",$p."T");
    my $parent = $p;
    chop $parent;

    $parentOf{$p} = "";
    if (exists($prefixWeight{$parent})) {
	$parentOf{$p} = $parent;
    }
}

my @sortedP = sort {(length($a) <=> length($b)) || ($prefixWeight{$a} <=> $prefixWeight{$b})} @prefixes;

my %placed = ();
#my $weightThreshold = 1;
my $weightThreshold = $weighting;

foreach my $p (@sortedP) {
    my $weight = $prefixWeight{$p};
    my $parent = $parentOf{$p};

    if ($parent) {
	if (exists($placed{$parent})) {
	    $placed{$p} = 1;
	    next;
	}
    }

    if ($weight <= $weightThreshold) {
	print "$p\t$weight\n";
	$placed{$p} = 1;
    }
}



