#!/usr/bin/perl
use XML::Simple;
use Data::Dumper;
# slurp in the xml file
$xmlfile = $ARGV[0];
$ref = XMLin($xmlfile, keyattr => {task => 'id', resource => 'name'});
# dump it to the screen for debugging only
#print Dumper($ref);

@allocray = @{$ref->{allocations}->{allocation}};
# get scientist units out of allocation array all tasks
foreach $allocref (@allocray) {
	print "resource-id = $allocref->{'resource-id'}, task = $allocref->{'task-id'}, units = $allocref->{units}\n";
}
%taskhashtop = %{$ref->{tasks}->{task}};
foreach $key (keys %taskhashtop) {
    print "key = $key name = $taskhashtop{$key}->{name}\n";
    if (exists $taskhashtop{$key}->{task}) {
	print "subtasks exist\n";
	%taskhashsub = %{$taskhashtop{$key}->{task}};
	foreach $keysub (keys %taskhashsub) {
	    print "keysub = $keysub name = $taskhashsub{$keysub}->{name}\n";
	    $taskhash{$keysub} = $taskhashsub{$keysub};
	}
    } else {
	$taskhash{$key} = $taskhashtop{$key};
    }
}
# loop over all of the tasks, sorted by task id
foreach $key (keys %taskhash) {
    print "working on task $key = $taskhash{$key}->{name}, work = $taskhash{$key}->{work}\n";
    @allocs = get_allocs($key);
    print "allocs = $allocs[0], $allocs[1]\n";
    $tot = $allocs[0] + $allocs[1];
    $sum[0] += $taskhash{$key}->{work}*$allocs[0]/$tot;
    $sum[1] += $taskhash{$key}->{work}*$allocs[1]/$tot;
}

$staff = $sum[1]/(5*8*60*60);
$contrib = $sum[0]/(5*8*60*60);
$total = $staff + $contrib;

print "staff = $staff, contrib = $contrib, total = $total\n";

exit;

sub get_allocs {
    my ($key) = @_;
    print "key = $key\n";
    @allocs = ();
    foreach $allocref (@allocray) {
	$task_id = $allocref->{'task-id'};
	print "task_id = $task_id ";
	if ($task_id == $key) {
	    print "$allocref->{'resource-id'} $allocref->{'units'}\n";
	    $allocs[$allocref->{'resource-id'} - 1] = $allocref->{'units'};
	}
    }
    return @allocs;
}
