#!/usr/bin/perl -w
#input the grades.csv file from coursework
#input marks.csv from  crowd mark
#
#modify grades.csv to input grades (marks) from crowdmark
#
#Author: Wojciech Wieczorek

use strict;

my $coursework = shift;
$coursework = "grades.csv" unless $coursework;
my $crowd = "marks.csv";
###### all fields: count from 1.
my $crfield =14; ### in crowdmarks file (marks.csv) which filed to extract?
my $crname = 2;  ### in crowdmark: which field has email
my $sufield = 12; #### in coursework (grades.csv) which field you want to insert into
my $suname = 1;  ### which field on coursework sunet id is in

my %oceny =();

open(IN, "<$crowd") || die "Couldn't open $crowd: $!\n";
#open(OUT, ">grades.crowd") || die "Couldn't open grades.crowd file: $!\n";

my $field;
my $name;

##################### populate hash %oceny 
while ( my $this = <IN>){
next if $.==1;
    chomp $this;
$field =1;
while ($this =~m`(?=.)((?:\s?"((?:""|[^"]+)*)")?([^,]*))(,?)`sg) {
  if($field == $crname){
    $name = $1;
    $name =~s!@.*$!!; 
    $field++;
    next;}
  if($field == $crfield){
    $oceny{$name} =$1 if $name; 
    last;}
$field++;
}#while: fields in a row
} #while: lines in input file
close(IN);

########## put the results in grades.csv:
my $outstr ="";
open(IN, "<$coursework") || die "Couldn't open $coursework: $!\n";
while ( my $this = <IN>){
  if($.==1){## first line
       $outstr = $this;
       next;
  }
    chomp $this;
$field =1;
while ($this =~m`(?=.)((?:\s?"((?:""|[^"]+)*)")?([^,]*))(,?)`sg) {
$outstr .="," unless $field ==1;
  if($field == $suname){ ## extract name
    $name = $1;
    }
  if($field == $sufield){ ## deal with exam grade
    $outstr .= $oceny{$name} if defined $oceny{$name}; #####
    $field++;
    next;
    }
 $outstr .= "$1";
 $field++;
}#while: fields in a row
$outstr .= "\n";
} #while: lines in input file


close(IN);

print $outstr;

if(0){
for (keys %oceny){
print "$_: $oceny{$_}\n";
}}

#close(OUT);
