#!/usr/local/bin/perl
require "/w/class.01/cs/cs131/cs131ta/risc/grades/column_names";

# Prints out $max number of students' grades across screen.  Formatted by field names in
# first line of $grade_file
# syntax is sg2 student [student2 student3 ...]
#  where student is something to search for, you may enter a list of students for side-by-side
# comparison.  student is anything to search for, can be a regular expression (may need ")
# Search must narrow down to no more than 2*$max students, $max is currently 4

#max number of students to print across
$max=5;

$students=join ('|', @ARGV);
unless ($students) {
  print "Syntax is sg2 student, where student is some string to search for\n";
  exit;
}
&readgrades;
@fields=split (/,/, shift @grades);
chomp @fields;
@matches=grep /$students/io, @grades;

if ($#matches>=(2*$max)) { # 2 rows of max columns of students + header names
  print "Too many matches\n";
  exit;
}

push @fields, "Avg.";

while (@matches) {
  $#averages=-1; $#trueavgs=-1;
  for ($i=0; $i<$max; $i++) {
    $name="values"."$i";
    next unless (@matches);
    @{$name}=split(/,/, shift @matches);
    foreach $value (@{$name}) { #make only first letter capital
      $value=~ tr/[A-Z]/[a-z]/;  #$value= lc $value;  #faster?
      $value=~ s:\n::;
      $value =~ s:(\w):\u$1:;
      $value =~ s:\s(\w)(\w\b)?: \u$1\u$2:;#capitalize after space, for middle names
    }
    #average and caaverage scripts need something unique to search for, otherwise they hang
    #waiting for user choice, so use sid
    $t="${$name}[$columns{'sid'}]"; 
    $avg=`classavg $t`;
    $avg=~ m:raw=(\d+.\d+) of (\d+\.\d+), avg=(\d+.\d+):;
    push @{$name}, sprintf "%2.0f/%2d|%2.0f", $1, $2, $3;
  }
  $i=0;
  foreach $field (@fields) {
    unless ($field =~m:\S:) {$i++; next;}
    printf ("%7s:",$field);
    for ($j=0; $j<$max; $j++) {
      $name="values"."$j";
      printf ("%16s", ${$name}[$i]);
    }
    print "\n";
    $i++;
  }
  print "\n";
}

