#!/bin/bash

MODULI=$1
FIRME=$2
TMP="tmp.out"

rm -f ${TMP}.*

cat /dev/null > ${TMP}.mod
cat /dev/null > ${TMP}.firma
cat /dev/null > risultato
cat /dev/null > tempi_smodels

cp -f ${MODULI} ${TMP}.mod

#let M=15

let M=1

echo " MOD & F-IN & MSG & F-OUT & BIT & CHOICE & TIME (Sec)\\\\">> risultato 

while test $M -ge 1;
do 

    MODVAL=`head -1 ${TMP}.mod`
    tail +2 ${TMP}.mod > ${TMP}; mv -f ${TMP} ${TMP}.mod

    BITVAL=`head -1 ${TMP}.mod`
    tail +2 ${TMP}.mod > ${TMP}; mv -f ${TMP} ${TMP}.mod

#    let N=55
    let N=4
    cp -f ${FIRME} ${TMP}.firma

    while test $N -ge 1; 
    do
	SIGNVAL=`head -1 ${TMP}.firma`
	SIGNVAL=`minimizza -m $MODVAL -f $SIGNVAL`
	tail +2 ${TMP}.firma > ${TMP}; mv -f ${TMP} ${TMP}.firma
	
	preprocessor -m ${MODVAL} -f ${SIGNVAL} > out.txt

	grep  "false" out.txt | sed "s/false:- //" > messaggio.txt 
	codifica_msg -file messaggio.txt -bits ${BITVAL} > ${TMP}
	MSG=`head -1 ${TMP}` 
   
	lparse -c b=${BITVAL} codifica.txt codifica2.txt out.txt> ${TMP}
	smodels < ${TMP} > ${TMP}.result

	RESULT=`grep -c "Stable" ${TMP}.result`
	CP=`grep  "wrong choices" ${TMP}.result | sed "s/Number of wrong choices://"` 
	
	D=`grep  "Duration" ${TMP}.result | sed "s/Duration://"`
	echo "$D" >>tempi_smodels 
	if test ${RESULT} -gt 0;
        then
	    sed "s/[a-eg-z0-9_]\+([^)]*)//g" ${TMP}.result | sed "s/zero_1//g" | sed "s/[A-Za-z: ]*//g" | tail +3 | head -1 > sign.txt
	    SIGNOUT=`codifica_sign -file sign.txt`
	fi
	
	if test ${RESULT} -gt 0;
	then
	    RESULT_VALUE=`minimizza -m $MODVAL -f $SIGNOUT`
	else
	    RESULT_VALUE="n.a."
	fi
        
	echo " $MODVAL & $SIGNVAL & $MSG & $RESULT_VALUE & $BITVAL & $CP & $D">> risultato 
#	echo " $MODVAL & $SIGNVAL & $MSG & $RESULT_VALUE" >> risultato 

	let N-=1
    done
    
    let M-=1
    echo " ">>tempi_smodels
done
 
echo "********* L'output e' nel file : risultato *********"  		
