#!/usr/bin/perl
#syntax is avg file prefix [names]
#where file is the name of the results file and prefix is the string just before the final grade
#  avg hw2-results "Final Score is"
# output is histogram and avg/median for all students and all above $cutoff
# if names is present with any value, sorted Seas accounts will be printed with histogram
# if names is a number >=6 then it will be the number of names printed (like width)
$home="/u/cs/class/cs131/cs131xx";
$res=5;		#resolution, the size of ranges for the histogram
$cutoff=25;	#cut off value for 2nd avg/median for those above this value
$names=0;	#if true will print sorted Seas accounts with histogram

$file=shift @ARGV;
$prefix=shift @ARGV;
$prefix =~ s:\s*$::;
if ($prefix =~ m:^\s*(\d+)\s*$: || $prefix eq '') {
  $names=$prefix;
  $prefix = "Final Score is";
}
else {$names=shift @ARGV;}
if ($names && $names <5) {$names=5;}

unless ($file && $prefix) {
  print "Syntax is avg filename \"prefix\"   where filename is the name of results file
and prefix is a string before the grade such as Final Score (default)\n";
  exit;
}

@scores=`grep -i \"$prefix\" $home/*/$file`;
$sum=$sum2=$count=$count2=0;
shift @scores while ($scores[0]=~m:$home/[A-Z]:o);
foreach $score (@scores) {
  if (  $score =~ m:$home/(\w+)/.*?$prefix.*?(\d+(\.\d+)?):io)  {
    $sum+=$2;
    push @list, $2;
    $count++;
    $scores{int $2/$res}++;
    if ($2 >$cutoff) {
      $sum2+=$2;
      $count2++;
    }
    push @{$names{int $2/$res}}, $1;
  }
  else {push @nons, $score;}
}
printf ("$file average is %4.1f for $count people, w/o <=$cutoff it's %4.1f for $count2 people\n", 
	$count ? $sum/$count:0, $count2 ? $sum2/$count2: 0);
@list=sort {$b <=> $a} @list;
print "median is $list[$#list/2], w/o <=$cutoff $list[$#list-$count+$count2/2]\n";

if ($names) {
  foreach $key (sort {$b <=> $a} keys %scores) {
    $width= $scores{$key} if ($scores{$key} >$width);	#max
  }
  $width+=2;
}
$sofar=0;
foreach $key (sort {$b <=> $a} keys %scores) {  #sort decreasing
  $sofar+= 100*$scores{$key}/$count;
  printf (">= %3d  %4.1f%% (%5.1f%%)   %2d %-${width}s", $res*$key, 100*$scores{$key}/$count, 
	$sofar, $scores{$key}, "x" x $scores{$key});
  if ($names) {
    $i=1;
    $index=$#{$names{$key}};
    while ( $names*$i < $index) {
      $names{$key}[$i++*$names-1].="\n                            " . ' ' x $width . '| ';
    }
    print "|  @{$names{$key}}";
  }
  print "\n";
}

if (@nons) {
  print "no grade after \"$prefix\" for: ";
  chomp @nons;
  foreach $non (@nons) {
    $non =~s:$home/(\w+)/.*:$1:o;
    print "$non ";
  }
  print "\n";
}
