#!/usr/bin/perl

$course = $ARGV[0];
$semester = $ARGV[1];
$class = $course . $semester;
open(StuList, "stulist.txt");
open(OUT, ">$class". "Grade.txt");
open(OUT2, ">$class". "NeedLogin.txt");
open(OUT3, ">$class". "MailList.txt");
<StuList>; # skip title line
print OUT "Name\tLogin\tClass\tPriCollege\tPriDegree\tPriMaj1\tPhone\tHW1\tHW2\tHW3\tHW4\tHW5\tHW6\tHW7\tHW8\tMidTerm\tFinal\tProject\tBonus\tFinalPoint\tGrade\n";
while(<StuList>) {
	$line = $_;
        @col=split(/,/);
        $lastname = $col[1];
        $firstMidName=$col[2];
	$lastname =~ s/\"//g;
	$firstMidName =~ s/^ //g;
	$firstMidName =~ s/"//g;
	print "lastname=$lastname  firstMidName=$firstMidName\n";

	$lastName = ucfirst lc $lastname;
	if ($firstMidName =~ /([^\s]+)\s([^\s]*)/) {
	   $firstName = ucfirst lc $1;
	   $MiddleName = ucfirst lc $2;
        } else { # no middle name
           $firstName=ucfirst lc $firstMidName; 
           $MiddleName="";
        }
	print "pattern=$firstName\\D+$lastName\n";
	$pattern="$firstName\\D+$lastName";
	open(PASSWD, "../../list.txt");
	$found = 0;
	while (<PASSWD>) {
		@fields = split(/:/);
		$_ = $fields[4];
		if (/$pattern/i) {
			print OUT "$lastName, $firstName $MiddleName\t$fields[0]";
		   $col[3] =~ s/\"//g;
		   if ($col[3] =~ /^\d/) {
                        for $i (7, 8,9,10,16) {
                           print OUT "\t$col[$i]";
			}
		   } else { # this is case where we have , Jr or III in name
                        for $i (8, 9,10,11,17) {
                           print OUT "\t$col[$i]";
			}
		   }
                        print OUT "\n";
			print OUT3 "$fields[0]\@cs.uccs.edu\n";
			$found = 1;
		}
	}
	if ($found == 0) { 
		print OUT2 "$line";
		print OUT "$lastName, $firstName $MiddleName\t";
                if ($MiddleName) {
                     $login=lc substr($firstName,0,1).substr($MiddleName, 0, 1).substr($lastName,0,6);
                } else {
                     $login=lc substr($firstName,0,1).substr($lastName,0,7);
                }
                print OUT "$login";  # instead of xxxxxx  write out the login name
                for ($i=2;$i<=$#col; $i++) {
                    print OUT "\t$col[$i]";
                }
                #print OUT "\n";

		print OUT3 "$firstName[0]$middleName[0]$lastName\@cs.uccs.edu\n";
		
	}
	close(PASSWD);
}
close(StuList);
close(OUT);
close(OUT2);
