#! /usr/bin/perl -w

use strict;
use Data::Dumper;

my $USAGE = "
$0 <combine schedule file> <advisor output name> <partial schedule file>*  >output

Takes several partial schedule files, each containing lines of the form
# TO COMBINE <advisor name>, and combines them together.
<advisor output name> is the filename that will be created by the 
super-advisor. 
<combine schedule file> contains a skeleton of the final schedule.
It contains lines of the form # ADVISORS and # OUTPUT
which will be replaces with approproate strings.
";

if(scalar(@ARGV)<1) { die $USAGE; }
my ($combine_schedule, $output, @partial_schedules) = @ARGV;


my @advisors;
if(@partial_schedules) {
    print "include:\n";
    foreach my $schedule (@partial_schedules) {
	print " @" . $schedule . "\n";

	#read advisors to be combined
	local *IN;
	open IN, "<$schedule" or die "Cannot open $schedule";
	while (my $line = <IN>) {
	    if($line =~ /\# TO COMBINE (\S+)\s*$/) {
		push @advisors, $1;
	    }
	}
	close IN;
    }
    print ":end\n\n";
}

local *IN;
open IN, "<$combine_schedule" or die "Cannot open $combine_schedule";
while (my $line = <IN>) {
    if($line =~ /^(.*)\# ADVISORS(\s*)$/) {
	print $1, join(' ', @advisors), $2;
    }
    elsif($line =~ /^(.*)\# OUTPUT(\s*)$/) {
	print $1, $output, $2;
    }
    else {
	print $line;
    }
}
close IN;
