#!/bin/sh

#-----[ variable ]------------------------------------------
declare DIR_DEFAULT_EXEC="$SOFT/SpecInt2000.or32";
#declare DIR_DEFAULT_EXEC="$SOFT/Basic_test.or32";
declare DIR_CONFIG="$IPS/processor/M_CPU/Configuration_files/Architecture"
declare DIR_PLATFORMS="$PLATFORMS/Generic";
declare DEFAULT_EXEC="$DIR_DEFAULT_EXEC/bin/soft.x";

declare CONFIGURATION;
declare EXECUTE;
declare NB_CYCLE;

#-----[ usage ]---------------------------------------------
function usage ()
{
    echo "usage : $0 [config [nb_cycle [exec]]]";
    echo "      * if config is not indicated, execute the more recent executable";
    echo "      * nb_cycle : number of simulated cycle";
    echo "      * if exec   is not indicated, execute \"$DEFAULT_EXEC\"";
    exit 1;
}

#-----[ test_usage ]----------------------------------------
function test_usage ()
{
    if test $# == 0 -o $# -gt 3;
	then
	usage;
    fi
}

#-----[ make_arg ]------------------------------------------

function make_arg ()
{
    local CONFIG;
    local EXEC;
    local CYCLE;
# Construction du nom de la configuration
    if [ $# -ge 1 ];
	then
	CONFIG="system_"$1""
	
    # Recompile l'executable
	( 
	    cd $DIR_PLATFORMS;

	    make M_CPU_CONFIGURATION_DIRECTORY="$DIR_CONFIG/m_cpu_configuration_$1" \
  		 M_CPU_CONFIGURATION_FILENAME="m_cpu_configuration.h"               \
		 ID="$1";
	)
    else
    # Test la presence du repertoire contenant les binaires
	if test ! -d $DIR_PLATFORMS/bin;
	    then
	    echo "Directory don't exist : \"$DIR_PLATFORMS/bin\", you need a configuration"
	    usage;
	fi;

	CONFIG=(`ls -t $DIR_PLATFORMS/bin/*`);
	CONFIG=`basename ${CONFIG[0]} :`;
    fi

#nombre de cycle
    if [ $# -ge 2 ];
	then
	CYCLE=$2;
    fi;

#executable
    if [ $# -ge 3 ];
	then
	if [ -f $2 ];
	    then
	    EXEC=$2;
	else
	    echo "$2 : file not exist";
	    usage;
	fi
    else
	EXEC=$DEFAULT_EXEC;

	(cd $DIR_DEFAULT_EXEC; make;)

	if [ $? -ne 0 ]
	    then
	    echo "Error of compilation"
	    exit 1;
	fi
    fi

    eval "CONFIGURATION=$CONFIG";
    eval "EXECUTE=$EXEC";
    eval "NB_CYCLE=$CYCLE";
}

#-----[ main ]----------------------------------------------
function main ()
{
    test_usage $*;
    make_arg   $*;

# Lancement de l'executable

#OPTION=--c
    OPTION=
    time $DIR_PLATFORMS/bin/$CONFIGURATION $OPTION $EXECUTE $NB_CYCLE;
    killall xtty;
#valgrind --tool=memcheck 
}

#-----[ Corps ]---------------------------------------------
main $*;
