#! /usr/bin/perl -w

open (FILE, shift @ARGV) or die "Cannot open data file.";
@filedata = <FILE>;
chomp @filedata;
close FILE or warn "Could not close data file.";

while ( scalar(@filedata) > 0 ) {
	$line = shift @filedata;
	next unless $line;
	if ( $line =~ m/[0-9]{5}$/ ) {
#		next if ( $line =~ m/CANCELLED/ );
#		$section = substr $line, 1, 3;
		$instructor = substr $line, 35, 15;
		$instructor =~ s/\s+$//;
		$students = substr $line, 55, 2;
		$students =~ s/^\s+//;
		$students = 0 unless $students;
		$term{$semester}{$course}{$instructor}{'sections'}++;
		$term{$semester}{$course}{$instructor}{'students'} += $students;
		$semcoursetotal{$semester}{$course}{'sections'}++;
		$semcoursetotal{$semester}{$course}{'students'} += $students;
		$semestertotal{$semester}{'sections'}++;
		$semestertotal{$semester}{'students'} += $students;
		$total{$course}{$instructor}{'sections'}++;
		$total{$course}{$instructor}{'students'} += $students;
		$coursetotal{$course}{'sections'}++;
		$coursetotal{$course}{'students'} += $students;
		$grandtotal{'sections'}++;
		$grandtotal{'students'} += $students;
#		print "$year,$semester,$course,$title,$instructor,$section,$students\n";
	} elsif ($line =~ m/Course Section Scan/ ) {
		$course = substr $line, 43, 3;
		$title = substr $line, 50;
		$courses{$course} = $title;
	} elsif ($line =~ m/Term: [0-9]{3}/ ) {
#		$year = 20 . substr $line, 54, 2;
		$semester = substr $line, 56, 1;
	} else {
		next;
	}
}
print "TIME PERIOD,COURSE TITLE,INSTRUCTOR,SECTIONS,STUDENTS\n";
print "2012,ALL COURSES,ALL INSTRUCTORS," . $grandtotal{'sections'} . "," . $grandtotal{'students'} . "\n";
for my $course ( sort keys %total ) {
	print "2012,MATH" . $course . " " . $courses{$course} . ",ALL INSTRUCTORS," . $coursetotal{$course}{'sections'} . "," . $coursetotal{$course}{'students'} . "\n";
	for my $instructor ( sort keys %{$total{$course}} ) {
		print "2012,MATH" . $course . " " . $courses{$course} . "," . $instructor . "," . $total{$course}{$instructor}{'sections'} . "," . $total{$course}{$instructor}{'students'} . "\n";
	}
}
print "\n\n\n";

for my $semester ( 2, 3, 1 ) {
	$name = "Fall" if ($semester==1);
	$name = "Spring" if ($semester==2);
	$name = "Summer" if ($semester==3);
	print "2012 $name,ALL COURSES,ALL INSTRUCTORS," . $semestertotal{$semester}{'sections'} . "," . $semestertotal{$semester}{'students'} . "\n";
	for my $course ( sort keys %{$term{$semester}} ) {
		print "2012 $name,MATH" . $course . " " . $courses{$course} . ",," . $semcoursetotal{$semester}{$course}{'sections'} . "," . $semcoursetotal{$semester}{$course}{'students'} . "\n";
		for my $instructor ( sort keys %{$term{$semester}{$course}} ) {
			print "2012 $name,MATH" . $course . " " . $courses{$course} . "," . $instructor . "," . $term{$semester}{$course}{$instructor}{'sections'} . "," . $term{$semester}{$course}{$instructor}{'students'} . "\n";
		}
	}
	print "\n\n";
}

