#!/usr/bin/perl
#
# Author: Prabu, School of Computer Science, FIU
#         prabu@cs.fiu.edu
#         2/27/2005
#
# Parses a class list (student enrollment) file (comma separated file)
# and generates two text files as
#   - text file for Excel spreadsheet input (tab separated values)
#   - class student profile text file (space separated values)
# Manually edit these text files later to correct exceptional names such as
#   Mccarthy => McCarthy
#   Macintire => MacIntire
#   A-wen => A-Wen

# check for correct number of arguments
if ($#ARGV != 0) { # in Perl, argcnt is zero for one argument
    die "Usage: $0 ClassListFile.txt \n";
}
$classListFile = $ARGV[0]; # Class enrollment file (values separated by tabs)
if (!(-e $classListFile)) {
   die "Error: file $classListFile does not exist - $!\n";
}
open(classF, "<".$classListFile) || die "cannot open input $classListFile - $!";
($className) = split(/\./, $classListFile);
$excelFile = $className . "Excel.txt";
$accessFile = $className . "Access.txt";

open(excelF, ">".$excelFile) || die "cannot open output $excelFile - $!";
open(accessF, ">".$accessFile) || die "cannot open output $accessFile - $!";

while (<classF>) {
  s/\s*$//i; # remove trailing whitespace on the current line
  s/","/	/g; # subtitute each comma with a tab
  s/"//g;
  s/@.*//;
  if ( /\d{7}/ ) { # currentline contains a seven digit PantherID
    ($name, $id, $f3, $f4, $f5, $f6, $f7, $userName, $phone) = split(/	/, $_);
    $codeWord = $id;
    $codeWord =~ s/^\d{3}(\d{4})$/$1/; # strip first 3 digits
    $userName =~ s/^\s*([^\s]+)\s*$/$1/;
    &processName();
    print excelF "$id\t$lastName, $firstName\t$userName\n";
    print accessF "$id $lastName, $firstName $userName $codeWord \n";
  }
}
close(accessF);
close(excelF);
close(classF);
exit(0);

sub processName{
# process the name field and generate two strings (lastname and firstname)
# The generated lastname/firsname should not have any space
# Capitalize only the first letter and convert the rest to lowercase
  $name =~ s/^\s*"(.*)"\s*$/$1/;
  ($surName, $firstName) = split(/,/, $name);
  $firstName =~ s/^\s*(\w)([\w\.\-]*)\s*.*$/\U$1\L$2/;
  # surName may have more than one word - process each separately
  @nameToken = split(/ /, $surName);
  $lastName = @nameToken[0];
  $lastName =~ s/^\s*(\w)([\w\.\-]*)\s*$/\U$1\L$2/;
  for ($i = 1; $i <= $#nameToken; $i++) {
   $token = @nameToken[$i];
   $token =~ s/^\s*(\w)([\w\.\-]*)\s*$/\U$1\L$2/;
   $lastName .= "_$token";
  }
}
