#!/usr/athena/bin/perl
eval "exec /afs/net/tools/@sys/perl -s -S $0 $*"
    if $running_under_some_shell;
			# this emulates #! processing on NIH machines.
			# (remove #! line above if indigestible)

$LISTFILE = "/afs/net/user/tytso/projects/perl/list";
$CTLFILE = "/afs/net/user/tytso/projects/perl/ctl";

$addr = &round_robin($LISTFILE, $CTLFILE);

print "addr = $addr\n";

while (<>) {
	if (/^\n$/) {
		print "End of header\n";
		last;
	}
	print;
}

sub round_robin {
	local($LISTFILE, $CTLFILE) = @_;
	local($addr, @list, %random);

	srand(time|$$);

	open(LIST, "+<" . $LISTFILE) || die "Couldn't open $LISTFILE";

	if (open(CTL, "+<" . $CTLFILE)) {
		$num = <CTL>;
		$num++;
	} else {
		$num = 1;
		open(CTL, ">" . $CTLFILE);
	}

	loop:
	while (1) {
		for ($i = 0; $i < $num; $i++) {
			if (eof(LIST)) {
				$num = 1;
				@list = sort sort_random @list;
				print @list;
				seek(LIST, 0, 0);
				print LIST @list;
				truncate(LIST, tell(LIST));
				seek(LIST, 0, 0);
				next loop;
			}
			$list[$i] = $addr = <LIST>;
			$random{$addr} = rand() * 100;
		}
		last loop;
	}

	chop $addr;
	close LIST;

	seek(CTL, 0, 0);
	print CTL "$num\n";
	close CTL;

	$addr;
}

sub sort_random {
	$random{$a} <=> $random{$b};
}	

