#ifdef SYSTEMC
/*
 * $Id: Simulation_test_end.cpp 138 2010-05-12 17:34:01Z rosiere $
 *
 * [ Description ]
 * 
 */

#include "Behavioural/include/Simulation.h"
#include "Common/include/Systemc.h"
#include "Common/include/ErrorMorpheo.h"

namespace morpheo              {
namespace behavioural          {

  bool simulation_test_end (void)
  {
    msgInformation("##########[ cycle %.0f ]\n",static_cast<double>(simulation_cycle()));

    // Test if a stop condition is activate
    if ((_simulation_nb_cycle == 0) and
        (_simulation_nb_instruction == 0)
        )
      return false;

    bool end_cycle;
    bool end_inst ;

    if (_simulation_nb_cycle != 0)
      end_cycle = (_simulation_nb_cycle <= simulation_cycle());
    else
      end_cycle = true;

    if (_simulation_nb_instruction != 0)
      {
        end_inst = true;
        std::vector<double>::iterator it=_simulation_nb_instruction_commited.begin();

        switch (_simulation_stop_type)
          {
          case ALL_THREAD :
            {
              double sum_inst = 0;

              // Scan all context and test if all can finish
              while (it!=_simulation_nb_instruction_commited.end())
                {
                  sum_inst += *it;
                  it ++;
                }
              
              // Stop if sum of all instruction is higher of "simulation_nb_instruction"
              end_inst &= (_simulation_nb_instruction <= sum_inst);

              break;
            }
          case EACH_THREAD_AND_CONTINUE :
          case EACH_THREAD_AND_STOP :
            {
              // Scan all context and test if all can finish
              while (end_inst and it!=_simulation_nb_instruction_commited.end())
                {

                  // Stop if all thread have executed more that "simulation_nb_instruction" instructions.
                  end_inst &= (_simulation_nb_instruction <= *it);
                  it ++;
                }
              break;
            }
          }
      }
    else
      end_inst = true;
    
    if (end_cycle and _simulation_stop_exception)
      {
        throw ErrorMorpheo(_("Maximal cycles Reached"));
        return false;
      }
    else
      return end_cycle and end_inst;
  }

}; // end namespace behavioural          
}; // end namespace morpheo              

#endif
