#!/bin/csh -f

# For each argument, as created with sc2txt from my standard type of
# grade spreadsheet (e.g., foo.txt), create foo-gmail.csv, suitable
# for importing a list of contacts into Gmail.  Also use foo.access to
# include alternative email addresses.  The fields in the .csv file
# are Name, Course, and Email address.  The course is in the form
# "$year$term/$course", where $year, $term, and and $course are
# inferred from the directory path name.  The Name and Email address
# are straightforward extractions from foo.txt; when working with an
# altemail entry in foo.access, the "Email address" is the alternative
# email address, and the "Name" is the primary email address.  For a
# grader entry in foo.access, the "Name" is "grader$course$term$year".

# With no arguments, assume grades.txt

set files = ($*)
if ($#argv == 0) set files = grades.txt

foreach file ($files)
  if (! -e $file) break
  set gradesfile = `echo $file | sed 's+^\([^/]\)+./\1+'`
  set dir = "`pwd`"
  set course = $dir:h:t$dir:t
  set term = "`echo $dir:t | sed 's+[0-9]*++g'`"
  set year = "`echo $dir:t | sed 's+[^0-9]*++g'`"
  if ($term == "f") set term = "fa"
  if ($term == "s") set term = "Sp"
  if ($year < 90) set year = "20$year"
  if ($year < 100) set year = "19$year"
  set course = "$dir:h:t"
  echo "Name,Course,Email address" > $gradesfile:r-gmail.csv
  stripgradestats $gradesfile | excol NAME EADDR | tail -n +2 | sed 's+abel\.++' | sed -n "s+ *\(.*\),\(.*[^ ]\)  *\([^ ]*@[^ ]*\)+\1 ~\2,$year$term/$course,\3+p" >> $gradesfile:r-gmail.csv
  if (! -e $gradesfile:r.access) touch $gradesfile:r.access
  awk '$1 == "grader" {print "grader'$course$term$year',grader '$year$term/$course'," $2}\
       $1 == "altemail" {print $4 ",'$year$term/$course'," $2}\' \
      $gradesfile:r.access >> $gradesfile:r-gmail.csv

end
