#!/usr/bin/perl

# extract_plan --- takes as an input a model that corresponds with a
# valid plan, seeks all executed planning actions, and constructs a
# total ordering of the partial ordering of actions. If the input file
# doesn't contain  any models, extract_plan exits with value 1,
# otherwise it exits with 0.

# usage: extract_plan [predicate list] < model
#
# The predicate list should contain a number of atom names, one each
# line that correspond with the action predicates. If none are
# given, it uses as default atom names given in array @actions.

while ($act = shift) {
  push @actions, $act;
  $operators_defined = 1;
}

if (!$operators_defined) {
  @actions = ("^suction",  "^move[^s]");
}
$found = 0;

while(<>) {
  if( /Stable Model:/) {
    $found = 1;
    #jump over model definition
    @atoms = split;
    shift @atoms;
    shift @atoms;
    last;
  } elsif (/^Model:/) {
    @atoms = split;
    shift @atoms;
    $found = 1;
  }
}
if (!$found) {
    exit(1);
}

@plan = ( [], [], [], [], [], [] );

$max = 0;

@nums = ( 0, 0, 0, 0, 0, 0, 0,0);

while ($atom = shift @atoms) {
#    print "$atom\n";
    if ($atom =~ /([0-9]+)\)/) {
	$num = $1;

	for ($i = 0; $i <= $#actions; $i++) {
#	    print "$atom : $actions[$i]: ", $atom =~ /$actions[$i]/," \n";
	    if ($atom =~ /$actions[$i]/) {
#		print "!!!$atom\n";
		$plan[$num][$nums[$num]] =  $atom;
#		print "$atom: $num: $nums[$num]: $plan[$num][$nums]";
		$nums[$num]++;
#		print ": $nums[$num]\n";
		if ($num > $max) {
		    $max = $num;
		}
		last;
	    }
	}
    }
}

#print "\n";

$total = 1;
#print "$max\n";
for ($i = 1; $i <= $max; $i++) {
    print "$i: \n";
    for ($j = 0; $j < $nums[$i]; $j++) {
	$atom = $plan[$i][$j];
	$atom =~ s/([0-9]+)\)/$total\)/;
	$total++;
	print "$atom\n";
    }
}

exit(0);
