#!/usr/bin/env bash

# Do a "transpose" of sc spreadsheets.  That is, given sc spreadsheets
# in filenames of the form byemailid.sc, each of which has the same
# format (same students, same items on which scores are entered),
# produce a set of spreadsheets with names of the form ofemailid.sc
# that bring together the scores assigned to each student in files
# with names of the form oflastame.sc.  Assumes another spreadsheet
# template.sc that is the basis for filling in all the spreadsheets of
# the form byemailid.sc.  Note form of template.sc in same directory
# as this script.

# Then bring together averages of the various students from the
# ofemailid.sc spreadsheets into a single spreadsheet summary.sc

numstuds=$1

for file in `echo by*.sc`; do
  ofname=`echo $file | sed 's+by+of+'`
  sed 's+\(format [A-Z]\) [0-9]* 0 0+\1 5 2 0+' template.sc > $ofname
done

for ((line=$numstuds+1; --line;)); do
  filenum=1
  for file in `echo by*.sc`; do
    ofname=of`cat $file | sed -n "s+.* [A-Z]$line = \"\(.*\)@.*\"+\1+p"`.sc
    grep "[B-Z]$line = " $file | sed -n "s+\([B-Z]\)$line+\1$filenum+gp" >> $ofname
    echo "rightstring A$filenum = \"$file\"" >> $ofname
    filenum=$((filenum+1))
  done
done

cp /dev/null summary.txt
for file in `echo of*.sc`; do
  txtfile=`echo $file | sed 's+sc+txt+'`
  make $txtfile
  sed -n "s+ *AVG \(.*\)+\1 $txtfile+p" $txtfile | tr -d '.' >> summary.txt
done
