#!/usr/bin/perl

# perl LengthAnalysis TestScoreFile  A/B colscore [minscore]

open(DIST,"/home/jairo/bio/TMalign/bssplengths");


while (<DIST>) {
 #   chop();
  @line=split(/[\s]+/);
  $domlength{$line[0]}=$line[1];
}
close(DIST);

if ($ARGV[1] eq "A") {
  $collength=0;
}
else {
  $collength=1;
}

$colscore=$ARGV[2];
$scoremin=$ARGV[3];

$maxl = 1147;
open(LIST,$ARGV[0]);

while (<LIST>) {
  @line=split(/\s+/);
  if (defined($domlength{$line[$collength]})) {
  $len1 = $domlength{$line[$collength]};
  }
  else {
    print "$line[$collength] not defined.\n";
  }
  $score=$line[$colscore];
  if ($score >= $scoremin){ 
    $counter[$len1]++;
    $scoresum[$len1] += $score;
  }
}

close(LIST);

for ($i=0;$i<=$maxl;$i++) {
   if ($counter[$i] > 0) {
     $scoresum[$i] /= $counter[$i];
   }
}


open(SAL,">LengthStats$ARGV[0]$ARGV[1]$ARGV[3]");
for ($i=0;$i<=$maxl;$i++) {
  if ($counter[$i] > 0) {
   print SAL "$i $counter[$i] $scoresum[$i]\n";
  }
}
close(SAL);

