#!/bin/perl

$recfile = '/disk22/pub/www/classes/6.837/F98/admin/recitations';
$usage = "Usage: separate_recitations.pl dir\n";

(@ARGV == 1) || die($usage);

$dir = $ARGV[0];

open(REC,$recfile) || die("Cannot open file $recfile\n");

%students = ();
%recs = ();
$recs{'other'} = 1;

$currec = '';
while (<REC>) {
    if (/^((M|W|F)\d+\-\d+)\s*\(\d+\)\s*$/) {
	$currec = $1;
	$recs{$currec} = 1;
    }
    if (/^[A-Za-z- .]+,\s*([a-z0-9_-]+)\s*$/ && $currec) {
	$students{$1} = $currec;
    }
    if (/^notes:\w*$/) {
	break;
    }
}

close(REC);

if ($dir !~ /\/$/) {
    $dir .= '/';
}

$mode = 0770;
foreach $subdir (keys(%recs)) {
    if (!(-d "$dir$subdir")) {
	mkdir("$dir$subdir", $mode)
	    || die("Cannot make directory $dir$subdir\n");
    }
}

opendir(DIR,$dir) || die("Cannot open directory $dir\n");

while ($subdir = readdir(DIR)) {
    if (($subdir ne '.') && ($subdir ne '..') && (!$recs{$subdir})
	&& (-d "$dir$subdir")) {
	if ($recdir = $students{$subdir}) {
	    rename("$dir$subdir", "$dir$recdir/$subdir") ||
		die("Cannot move $dir$subdir\n");
	} else {
	    rename("$dir$subdir", "${dir}other/$subdir") ||
		die("Cannot move $dir$subdir\n");
	}
    }
}

closedir(DIR);
