#!/usr/bin/perl
# modelsort - sort models output by dlv into a unique order for easy comparison
# by Robert Bihlmeyer <robbe@orcus.priv.at>

# In each model, predicates are sorted lexically. The list of models itself is
# not sorted. Lines not holding models are output in original order, before any
# of the models.

# Syntax checking is strict, so as to not cover-up errors.

@models=();

while (<>)
{
  if ( /^{(.*)}$/ )
  {				# Sie ist ein model, und sie sieht gut aus ...
    push(@models,"{".predsort($1)."}\n");
  }

  elsif ( /^(.*bravely true.*){(.*)}$/ )
  {
    push(@models,"$1"."{".predsort($2)."}\n");
  }
  elsif ( /^(.*cautiously false.*){(.*)}$/ )
  {
    push(@models,"$1"."{".predsort($2)."}\n");
  }

  elsif ( /^Diagnosis: (.*)/ )
  {
    push(@models,"Diagnosis: ".diagsort($1)."\n");
  }

  elsif ( /^(STATE [0-9]*): (.*)/ )
  {
    push(@models,"$1: ".predsort($2)."\n");
  }
  elsif ( /^(ACTIONS:.*)/ )
  {
    push(@models,"$1\n");
  }

  elsif ( /^(.*Best model:.*){(.*)}$/ )
  {
    push(@models,"$1"."{".predsort($2)."}\n");
  }

  else
  {				# Not a valid model, output immediately.
    print;
  }
}
##############
#print (@models);
##############
# replaced with
##############
foreach $model (@models)
{
  if ( $model =~ /^{(.*)}$/ )
  {
    @preds=split(/, /,$1);
    print (join("\n",@preds));
  }
  else
  {
    print $model;
  }
}

sub predsort($ )
{
  my @p=split(/, /,$_[0]);
  return join(", ",sort(@p));
}

sub diagsort($ )
{
  my @p=split(/ /,$_[0]);
  return join(" ",sort(@p));
}
