#! /usr/bin/perl


# Usage: overallGrade.pl -m M0100/T-10a
# -----

# ----------------------------------------------------------------------
use Getopt::Std;
getopts('m:');

$dbDir   = "/home/l_tester/ptr/moduleDB";
my @temp;
my @grade;
my @i150V;

$#temp = -1;
$#grade = -1;
$#i150V = -1;

push(@temp, "T-10a");
push(@temp, "T-10b");
push(@temp, "T+17a");

print "\n\noverallGrade> Appending $dbDir/$opt_m/gradingTest.txt --->  $dbDir/$opt_m/summaryTest.txt\n\n";

if ( (-e  "$dbDir/$opt_m/gradingTest.txt") && (-e  "$dbDir/$opt_m/summaryTest.txt") ) {
    system("/bin/cat $dbDir/$opt_m/gradingTest.txt >> $dbDir/$opt_m/summaryTest.txt");
}
else {
    print "overallGrade> !!!!!!!!!  ----> COULD NOT FIND ONE OF THE FOLLOWING FILES: \n $dbDir/$opt_m/gradingTest.txt \n $dbDir/$opt_m/summaryTest.txt\n";
}

open(OVERALL, ">>$dbDir/$opt_m/summaryTest.txt") || die "==> Cannot open $dbDir/$opt_m/summaryTest.txt\n";

foreach $dir ( @temp ) {
    
    $file = "$dbDir/$opt_m/../$dir/summaryTest.txt";
    if(-e $file) { getGrades($file); }
    
}

print "overallGrade> $opt_m\n";
$tmpGrade = "A";
foreach $i (0 .. $#grade) {

    chop($grade[$i]);
    print "overallGrade> @temp[$i] GRADE     ...$grade[$i]\n";

    if ( $grade[$i] eq "C" ) { $tmpGrade = "C"; last; }
    if ( $grade[$i] eq "B" ) { $tmpGrade = "B"; next; }
}

if ( @i150V[2]!=0 ) { $ratio = @i150V[1]/@i150V[2]; }

if ( $ratio ) { 

    print "overallGrade> 17/10 RATIO   $ratio\n"; 
    print OVERALL "RATIO $ratio\n";
}
else { 

    print "overallGrade> 17/10 RATIO   N/A\n"; 
    print OVERALL "RATIO 0\n";
}

#if ( $ratio > 1.5 ) { $tmpGrade = "C"; print "Ratio of $opt_m = $ratio\n"; }

if ( $tmpGrade eq "A" ) { print OVERALL "OVERALL GRADE $tmpGrade\n"; }
if ( $tmpGrade eq "B" ) { print OVERALL "OVERALL GRADE $tmpGrade\n"; }
if ( $tmpGrade eq "C" ) { print OVERALL "OVERALL GRADE $tmpGrade\n"; }

print "overallGrade> OVERALL GRADE    ... $tmpGrade\n";
print "overallGrade> .. written to $dbDir/$opt_m/summaryTest.txt ...\n\n\n";
close(OVERALL);

if ( (-e  "$dbDir/$opt_m/gradingTest.txt") ) {
    system("rm -f $dbDir/$opt_m/gradingTest.txt");
}

#---------------------------------------------------------------------------------------------
sub getGrades() {
    my ($f) = @_;
    
    open(IN, "$f") || die "Cannot open $file\n";
    while (<IN>) {	
	if (/Grade/) {
	    s/Grade //g; 
	    push(@grade, $_);
	}
	
	if (/I\ 150/) {
	    s/I\ 150 //g;
	    push(@i150V, $_);
	}
	
    }
}
