#!/bin/sh

opts=""
file=""

setfile() {
  if [ x"$file" = x ]
  then
    file="$1";
  else
    echo "*** `basename $0`: file specified twice" 1>&2
    exit 1
  fi
}

while [ $# -ne 0 ]
do
  case x"$1" in
    x-) setfile $1;;
    x-*) opts="$opts $1";;
    x*) setfile $1;;
  esac
  shift
done

if [ x"$file" = x ]
then
  echo "*** `basename $0`: no file specified" 1>&2
  exit 1
elif [ x"$file" = x- ]
then
  tmp=/tmp/runsato-$$.dimacs
  cat > $tmp
else
  tmp="$file"
fi

if [ ! -f $tmp ]
then
  echo "*** `basename $0`: file $file not found" 1>&2
  exit 1
fi

log=/tmp/runsato-$$.log

trap "rm -f $log" 2

time sato $opts $tmp 2>&1 | tee $log

if [ ! x"`grep '^Model' $log`" = x ]
then
  echo 
  echo "=========================================================="
  echo "Translation of Counterexample"
  echo "=========================================================="
  (
    sed -e '/^c /!d' $tmp;
    awk '/^Model/{
           getline; while(getline > 0 && $1 != "The")if(NF > 0)print;}' $log
  ) | \
  awk '/^c /{a[$2]=$4; next}
       /[0-9]/{for(i=1;i<=NF;i++) b[$i]=1;}
       END{
         for(s in a){
	   printf a[s] "	";
	   if(b[s]) print "1"; else print "0";
	 }
       }' | \
  sed -e '/S[0-9]*/d' \
      -e 's,\(.*\)\<V\([0-9]*\)_\(.*\),\2	\1\3,' \
      -e 's,\[\([0-9]*\)\],	\1,' | \
  sort -n | uniq | \
  awk '
    BEGIN{state = 0; DEBUG=0}
    /./{
      if(DEBUG) print "DEBUG " $0
      if(state != $1) {
	print ""
	print "--- " state ". state ---------------------------------"
	print ""
        for(s in v) print s " = " v[s]
        for(s in v) v[s] = 0
	state = $1
      }
      n=$4
      for(i=0; i<$3; i++) n *= 2
      v[$2] += n
      if(DEBUG) for(s in v) print "DEBUG " s " = " v[s]
      if(DEBUG) print "DEBUG n = " n
    }
    END {
      print ""
      print "--- " state ". state ---------------------------------"
      print ""
      for(s in v) print s " = " v[s]
    }'
fi

if [ x"$file" = x"-" ]; then rm -f $tmp; fi
rm -f $log
