diff --git a/simulators/c++2/Makefile b/simulators/c++2/Makefile
index 96637c3afd049642080de48b5af09facbae69ec3..20074b7d2debfc7d230bc6e795d175a805a26f17 100755
--- a/simulators/c++2/Makefile
+++ b/simulators/c++2/Makefile
@@ -1,23 +1,23 @@
-TARGET_ARCH = linux
-
-CC     = g++
-#CC     = test2.sh
-#CC = /packages/gcc_3.2.2/bin/g++32
-OPT    = -O1
-DEBUG  = -g
-OTHER  = -Wall
-TRY    = -Wno-deprecated
-CFLAGS = $(OPT) $(OTHER) $(TRY)
-# CFLAGS = $(DEBUG) $(OTHER)
-OBJDIR = lib
-
-MODULE = run
-include Makefile.src
-SRCS_base = TMLTask.cpp TMLCommand.cpp TMLTransaction.cpp TMLChannel.cpp CPU.cpp CPURR.cpp CPUPB.cpp CPUPBL.cpp TMLWriteCommand.cpp TMLStateChannel.cpp TMLbrbwChannel.cpp TMLnbrnbwChannel.cpp TMLbrnbwChannel.cpp TMLEventChannel.cpp TMLEventBChannel.cpp TMLEventFChannel.cpp TMLEventFBChannel.cpp TMLReadCommand.cpp TMLExeciCommand.cpp TMLActionCommand.cpp TMLChoiceCommand.cpp TMLWaitCommand.cpp TMLSendCommand.cpp TMLSelectCommand.cpp TMLRequestCommand.cpp TMLNotifiedCommand.cpp Bus.cpp simkern.cpp definitions.cpp
-SRCS_base_DIR = src_simulator
-SRCS_generated = .
-
-OBJS_simulator = $(SRCS_base:%.cpp=lib/%.o)
-OBJS = $(SRCS:%.cpp=lib/%.o)
-
-include Makefile.defs
+TARGET_ARCH = linux
+
+CC     = g++
+#CC     = test2.sh
+#CC = /packages/gcc_3.2.2/bin/g++32
+OPT    = -O1
+DEBUG  = -g
+OTHER  = -Wall
+TRY    = -Wno-deprecated
+CFLAGS = $(OPT) $(OTHER) $(TRY)
+# CFLAGS = $(DEBUG) $(OTHER)
+OBJDIR = lib
+
+MODULE = run
+include Makefile.src
+SRCS_base = TMLTask.cpp TMLCommand.cpp TMLTransaction.cpp TMLChannel.cpp CPU.cpp CPURR.cpp CPUPB.cpp CPUPBL.cpp TMLWriteCommand.cpp TMLStateChannel.cpp TMLbrbwChannel.cpp TMLnbrnbwChannel.cpp TMLbrnbwChannel.cpp TMLEventChannel.cpp TMLEventBChannel.cpp TMLEventFChannel.cpp TMLEventFBChannel.cpp TMLReadCommand.cpp TMLExeciCommand.cpp TMLActionCommand.cpp TMLChoiceCommand.cpp TMLWaitCommand.cpp TMLSendCommand.cpp TMLSelectCommand.cpp TMLRequestCommand.cpp TMLNotifiedCommand.cpp Bus.cpp simkern.cpp definitions.cpp Bridge.cpp Memory.cpp
+SRCS_base_DIR = src_simulator
+SRCS_generated = .
+
+OBJS_simulator = $(SRCS_base:%.cpp=lib/%.o)
+OBJS = $(SRCS:%.cpp=lib/%.o)
+
+include Makefile.defs
diff --git a/simulators/c++2/src_simulator/Bus.cpp b/simulators/c++2/src_simulator/Bus.cpp
index 1fec186d55102d1a29c3f6d4e7b8ea1b93150d6f..3a30e13ab9aa358f91bb0228b99cbcb01f503052 100644
--- a/simulators/c++2/src_simulator/Bus.cpp
+++ b/simulators/c++2/src_simulator/Bus.cpp
@@ -45,80 +45,116 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLTask.h>
 #include <TMLChannel.h>
 
-Bus::Bus(std::string iName, TMLLength iBurstSize, TMLTime iTimePerSample): _name(iName), _burstSize(iBurstSize), _endSchedule(0), _nextTransaction(0), schedulingNeeded(true), _timePerSample(iTimePerSample){
+Bus::Bus(std::string iName, TMLLength iBurstSize, unsigned int ibusWidth, TMLTime iTimePerSample): _name(iName), _burstSize(iBurstSize), _nextTransaction(_transactionHash.end()), _schedulingNeeded(true), _timePerSample(iTimePerSample), _busWidth(ibusWidth), _busyCycles(0){
 	_myid=++_id;
 	_transactList.reserve(BLOCK_SIZE);
 }
 
 Bus::~Bus(){
-}
-
-void Bus::registerMasterDevice(CPU* iMasterDev){
-	_masterDevices.push_back(iMasterDev);
+	/*BusTransPrioTab::iterator i;
+	std::cout << "Remaining transactions in list of bus " << _name << ": " << _transactionQueue.size() << "\n";
+	for (i=_transactionQueue.begin(); i!= _transactionQueue.end(); ++i){
+		std::cout << i->second->toString() << "\n" ;
+	}
+	std::cout << "added: " << add << "  removed: " << remove << "  max size: " << _transactionHash.max_size() << std::endl;*/
 }
 
 void Bus::schedule(){
-	TMLTransaction* aTransToExecute=0,*aTempTrans=0,*aFutureTrans=0;
+	TMLTransaction *aTempTrans;
 	TMLTime aTransTimeFuture=-1;
-	CPU* aCPUforTrans=0;
-	MasterDeviceList::iterator i;
-	if (!schedulingNeeded) return;
-	for (i=_masterDevices.begin(); aTransToExecute==0 && i != _masterDevices.end(); ++i){
-		aTempTrans=_transactionHash[*i];
-		if (aTempTrans!=0){
-			if (aTempTrans->getStartTimeOperation()<=_endSchedule){
-				//demand in the past
-				aTransToExecute=aTempTrans;
-				aCPUforTrans=*i;
-			}else{
-				//demand in the future
-				if (aTempTrans->getStartTimeOperation()<aTransTimeFuture){
-					aTransTimeFuture=aTempTrans->getStartTimeOperation();
-					aCPUforTrans=*i;
-					aFutureTrans=aTempTrans;
-				}
+	BusTransHashTab::iterator i, aTransToExecute=_transactionHash.end(), aFutureTrans=_transactionHash.end();
+	unsigned int aTransPrio=-1,aTempPrio;
+	for (i=_transactionHash.begin(); i != _transactionHash.end(); ++i){
+		aTempTrans=i->second;
+		if (aTempTrans->getStartTimeOperation()<=_endSchedule){
+			//demand in the past
+			aTempPrio=i->first->getBusPriority(this);
+			if (aTempPrio<aTransPrio){
+				aTransToExecute=i;
+				aTransPrio=aTempPrio;
+			}
+		}else{
+			//demand in the future
+			if (aTempTrans->getStartTimeOperation()<aTransTimeFuture){
+				aTransTimeFuture=aTempTrans->getStartTimeOperation();
+				aFutureTrans=i;
 			}
 		}
 	}
-	if (aTransToExecute==0) aTransToExecute=aFutureTrans;
-	if (aTransToExecute!=0){
+	if (aTransToExecute==_transactionHash.end()) aTransToExecute=aFutureTrans;
+	if (aTransToExecute!=_transactionHash.end()){
 		_nextTransaction=aTransToExecute;
-		_nextTransOnCPU=aCPUforTrans;
 		calcStartTimeLength();
 	}
-	schedulingNeeded=false;
+	_schedulingNeeded=false;
+#ifdef DEBUG_BUS
+	if (_nextTransaction==_transactionHash.end())
+		 std::cout << "Bus:schedule: decision of BUS " << _name << ": no transaction" << std::endl;
+	else
+		std::cout << "Bus:schedule: decision of BUS " << _name << ": " << _nextTransaction->second->toString() << std::endl;
+#endif
 }
 
-void Bus::registerTransaction(CPU* iCPU, TMLTransaction* iTrans){
-	_transactionHash.erase(iCPU);
-	_transactionHash[iCPU]=iTrans;
-	schedulingNeeded=true;
+void Bus::registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice){
+	//std::cout << "within Bus::registerTransaction " << std::endl;
+	if (iTrans==0){
+		_transactionHash.erase(iSourceDevice);
+	}else{
+		_transactionHash[iSourceDevice]=iTrans;
+	}
+	_schedulingNeeded=true;
+#ifdef DEBUG_BUS
+	std::cout << "Bus:registerTrans: registered at bus " << _name << ": " << iTrans->toString() << std::endl;
+#endif
+	/*std::cout << "Remaining transactions in list of bus " << _name << ": " << _transactionQueue.size() << "\n";
+	for (BusMasterPrioTab::iterator i=_transactionQueue.begin(); i!= _transactionQueue.end(); ++i){
+		std::cout << i->second->toString() << "\n";
+	}*/
 }
 
-void Bus::addTransaction(){
-	_endSchedule=_nextTransaction->getEndTime();
-	_transactList.push_back(_nextTransaction);
-	_nextTransaction=0;
-	_transactionHash.erase(_nextTransOnCPU);
-	schedulingNeeded=true;
+bool Bus::addTransaction(){
+	TMLTransaction* aNextTrans=_nextTransaction->second;
+	_endSchedule = aNextTrans->getEndTime();
+	_transactList.push_back(aNextTrans);
+	_busyCycles += aNextTrans->getOperationLength();
+#ifdef DEBUG_BUS
+	std::cout << "Bus::addTrans: add trans at bus " << _name << ": " << aNextTrans->toString() << std::endl;
+#endif
+	_transactionHash.erase(_nextTransaction);
+	_nextTransaction = _transactionHash.end();
+	/*std::cout << "   size: " << _transactionQueue.size() << std::endl;
+	std::cout << "Remaining transactions in list of bus " << _name << ": " << _transactionQueue.size() << "\n";
+	for (BusTransPrioTab::iterator i=_transactionQueue.begin(); i!= _transactionQueue.end(); ++i){
+		std::cout << i->second->toString() << "\n";
+	}*/
+	_schedulingNeeded=true;
+	return true;
 }
 
 void Bus::calcStartTimeLength(){
-	_nextTransaction->setStartTime(max(((int)_endSchedule)-((int)_nextTransaction->getPenalties()),(int)_nextTransaction->getStartTime()));
-	_nextTransaction->setLength(_nextTransaction->getVirtualLength()*_timePerSample);
+	TMLTransaction* aNextTrans=_nextTransaction->second;
+	aNextTrans->setStartTime(max(((int)_endSchedule)-((int)aNextTrans->getPenalties()),(int)aNextTrans->getStartTime()));
+	//TMLTime aLength = aNextTrans->getVirtualLength()*_timePerSample;
+	//aLength = (aLength%_busWidth == 0)? aLength/_busWidth : aLength/_busWidth+1;
+	TMLTime aLength = aNextTrans->getVirtualLength();
+	aLength = (aLength%_busWidth == 0)? (aLength/_busWidth)*_timePerSample : (aLength/_busWidth + 1)*_timePerSample;
+	aNextTrans->setLength(max(aLength, aNextTrans->getOperationLength()));
+	Slave* aSlave = aNextTrans->getChannel()->getNextSlave(aNextTrans);
+	if (aSlave!=0) aSlave->CalcTransactionLength(aNextTrans);
 	//_nextTransaction->setLength(max(_endSchedule,_nextTransaction->getStartTime())-_nextTransaction->getStartTime()+_nextTransaction->getVirtualLength());
 }
 
-TMLTransaction* Bus::getNextTransaction() const{
-	return _nextTransaction;
+TMLTransaction* Bus::getNextTransaction(){
+	if (_schedulingNeeded) schedule();
+	return (_nextTransaction==_transactionHash.end())?0:_nextTransaction->second;
 }
 
 TMLLength Bus::getBurstSize() const{
 	return _burstSize;
 }
 
-unsigned int Bus::getID(){
-	return _myid;
+void Bus::truncateToBurst(TMLTransaction* iTrans) const{
+	iTrans->setVirtualLength(min(iTrans->getVirtualLength(), _burstSize));
 }
 
 std::string Bus::toString(){
@@ -164,6 +200,9 @@ void Bus::schedule2HTML(std::ofstream& myfile){
 	myfile << "</tr>\n</table>\n";
 }
 
+void Bus::schedule2TXT(std::ofstream& myfile){
+}
+
 TMLTime Bus::getNextSignalChange(bool iInit, std::string& oSigChange, bool& oNoMoreTrans){
 	//end_idle  end_read  end_write
 	std::ostringstream outp;
@@ -234,3 +273,12 @@ TMLTime Bus::getNextSignalChange(bool iInit, std::string& oSigChange, bool& oNoM
 		}
 	}
 }
+
+/*unsigned int Bus::getBusyCycles(){
+	return _busyCycles;
+}*/
+
+void Bus::streamBenchmarks(std::ostream& s){
+	s << "*** Bus " << _name << " ***\n";
+	if (_simulatedTime!=0) s << "Utilization: " << ((float)_busyCycles)/((float)_simulatedTime) << std::endl;
+}
diff --git a/simulators/c++2/src_simulator/Bus.h b/simulators/c++2/src_simulator/Bus.h
index 99e48690a0bfbb1e8ffafc1fad47839a8af285fc..e2c5521e1a8e16ff14f0f5d515c49182ce5a30b6 100644
--- a/simulators/c++2/src_simulator/Bus.h
+++ b/simulators/c++2/src_simulator/Bus.h
@@ -42,58 +42,56 @@ Ludovic Apvrille, Renaud Pacalet
 #define BusH
 
 #include <definitions.h>
-#include <SchedulableDevice.h>
+#include <SchedulableCommDevice.h>
 #include <TraceableDevice.h>
 
 class CPU;
 class TMLTransaction;
 
-enum vcdBusVisState
+/*enum vcdBusVisState
     {
 	END_IDLE_BUS,
 	END_READ_BUS,
 	END_WRITE_BUS,
 	INIT_BUS
-};
+};*/
 
 ///Simulates the bahavior of a bus shared by several master devices
-class Bus: public SchedulableDevice, public TraceableDevice {
+class Bus: public SchedulableCommDevice, public TraceableDevice {
 public:
 	///Constructor
     	/**
       	\param iName Name of the bus
       	\param iBurstSize Size of an atomic bus transaction
     	*/
-	Bus(std::string iName, TMLLength iBurstSize, TMLTime iTimePerSample=1);
+	Bus(std::string iName, TMLLength iBurstSize, unsigned int ibusWidth=1, TMLTime iTimePerSample=1);
 	///Destructor
 	virtual ~Bus();
-	///Adds a new transaction to the internal queue and invalidates the scheduling decision
-	/**
-      	\param iCPU Pointer to the calling CPU
-      	\param iTrans Pointer to the new transaction
-    	*/
-	void registerTransaction(CPU* iCPU, TMLTransaction* iTrans);
-	///Adds a new master device to the internal device list
+	///Add a transaction waiting for execution to the internal list
 	/**
-      	\param iMasterDev Pointer to the new device
+      	\param iTrans Pointer to the transaction to add
+	\param iSourceDevice Source device
     	*/
-	void registerMasterDevice(CPU* iMasterDev);
+	void registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice);
 	///Determines the next bus transaction to be executed
 	void schedule();
 	///Adds the transaction determined by the scheduling algorithm to the internal list of scheduled transactions
-	void addTransaction();
+	bool addTransaction();
 	///Returns a pointer to the transaction determined by the scheduling algorithm
     	/**
       	\return Pointer to transaction
     	*/
-	TMLTransaction* getNextTransaction() const;
+	TMLTransaction* getNextTransaction();
 	///Returns the size of an atomic bus transaction
+	/**
+	\return Burst size
+	*/
 	TMLLength getBurstSize() const;
-	///Returns the unique ID of the Bus
+	///Truncates a transaction to the size of an atomic burst
 	/**
-      	\return Unique ID
-    	*/ 
-	unsigned int getID();
+	\param iTrans Pointer to the transaction
+	*/
+	void truncateToBurst(TMLTransaction* iTrans) const;
 	///Returns a string representation of the Bus
 	/**
 	\return Detailed string representation
@@ -109,6 +107,11 @@ public:
       	\param myfile Reference to the ofstream object representing the output file
     	*/
 	void schedule2HTML(std::ofstream& myfile);
+	///Writes a plain text representation of the schedule to an output file
+	/**
+      	\param myfile Reference to the ofstream object representing the output file
+    	*/
+	void schedule2TXT(std::ofstream& myfile);
 	///Creates a string representation of the next signal change of the device (VCD format)
 	/**
       	\param iInit If init is true, the methods starts from the first transaction
@@ -117,6 +120,7 @@ public:
 	\return Time when the signal change occurred
     	*/
 	TMLTime getNextSignalChange(bool iInit, std::string& oSigChange, bool& oNoMoreTrans);
+	virtual void streamBenchmarks(std::ostream& s);
 	
 protected:
 	///Calculates the start time and the length of the next transaction
@@ -129,22 +133,25 @@ protected:
 	static unsigned int _id;
 	///Size of an atomic bus transaction
 	TMLLength _burstSize;
-	///End time of the last scheduled transaction
-	TMLTime _endSchedule;
+	/////End time of the last scheduled transaction
+	//TMLTime _endSchedule;
 	///Pointer to the next transaction to be executed
-	TMLTransaction* _nextTransaction;
+	BusTransHashTab::iterator _nextTransaction;
 	///Pointer to the CPU on which the next transaction will be executed
-	CPU* _nextTransOnCPU;
+	Master* _nextTransOnCPU;
 	///Dirty flag of the current scheduling decision
-	bool schedulingNeeded;
-	///List containing all master devices
-	MasterDeviceList _masterDevices;
-	///Transaction queue
+	bool _schedulingNeeded;
+	///List containing all queued transactions
+	//BusMasterPrioTab _masterQueue;
 	BusTransHashTab _transactionHash;
 	///List containing all already scheduled transactions
 	TransactionList _transactList;
 	///Inverse bus speed
 	TMLTime _timePerSample;
+	///Bus width in bytes
+	unsigned int _busWidth;
+	///Busy cycles since simulation start
+	unsigned long _busyCycles;
 
 	///Actual position within transaction list (used for vcd output)
 	TransactionList::iterator _posTrasactList;
@@ -152,6 +159,10 @@ protected:
 	TMLTime _previousTransEndTime;
 	///State variable for the VCD output
 	vcdBusVisState _vcdOutputState;
+
+	//int add;
+	//int remove;
+	//bool _schedulingBlocked;
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/CPU.cpp b/simulators/c++2/src_simulator/CPU.cpp
index 48af1a04b40bdb58d88642e3247f8cc71b93d511..313e6f40ee1e384a001081dced6c6fb5a37a7f14 100644
--- a/simulators/c++2/src_simulator/CPU.cpp
+++ b/simulators/c++2/src_simulator/CPU.cpp
@@ -43,8 +43,10 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLCommand.h>
 #include <TMLTransaction.h>
 #include <Bus.h>
+#include <Slave.h>
+#include <TMLChannel.h>
 
-CPU::CPU(std::string iName, TMLTime iTimePerCycle, unsigned int iCyclesPerExeci, unsigned int iCyclesPerExecc, unsigned int iPipelineSize, unsigned int iTaskSwitchingCycles, unsigned int iBranchingMissrate, unsigned int iChangeIdleModeCycles, unsigned int iCyclesBeforeIdle, unsigned int ibyteDataSize):_name(iName), _endSchedule(0), _nextTransaction(0), _lastTransaction(0), _busNextTransaction(0), _timePerCycle(iTimePerCycle),_pipelineSize(iPipelineSize), _taskSwitchingCycles(iTaskSwitchingCycles),_brachingMissrate(iBranchingMissrate), _changeIdleModeCycles(iChangeIdleModeCycles), _cyclesBeforeIdle(iCyclesBeforeIdle), _cyclesPerExeci(iCyclesPerExeci), _timePerExeci(_cyclesPerExeci*_timePerCycle), _taskSwitchingTime(_taskSwitchingCycles*_timePerCycle), _timeBeforeIdle(_cyclesBeforeIdle*_timePerCycle), _changeIdleModeTime(_changeIdleModeCycles*_timePerCycle), _pipelineSizeTimesExeci(_pipelineSize * _timePerExeci),_missrateTimesPipelinesize(_brachingMissrate*_pipelineSize), _branchMissReminder(0), _branchMissTempReminder(0){
+CPU::CPU(std::string iName, TMLTime iTimePerCycle, unsigned int iCyclesPerExeci, unsigned int iCyclesPerExecc, unsigned int iPipelineSize, unsigned int iTaskSwitchingCycles, unsigned int iBranchingMissrate, unsigned int iChangeIdleModeCycles, unsigned int iCyclesBeforeIdle, unsigned int ibyteDataSize):_name(iName), _nextTransaction(0), _lastTransaction(0), _busNextTransaction(0), _timePerCycle(iTimePerCycle),_pipelineSize(iPipelineSize), _taskSwitchingCycles(iTaskSwitchingCycles),_brachingMissrate(iBranchingMissrate), _changeIdleModeCycles(iChangeIdleModeCycles), _cyclesBeforeIdle(iCyclesBeforeIdle), _cyclesPerExeci(iCyclesPerExeci), _busyCycles(0), _contentionDelay(0), _noBusTransactions(0),  _timePerExeci(_cyclesPerExeci*_timePerCycle), _taskSwitchingTime(_taskSwitchingCycles*_timePerCycle), _timeBeforeIdle(_cyclesBeforeIdle*_timePerCycle), _changeIdleModeTime(_changeIdleModeCycles*_timePerCycle), _pipelineSizeTimesExeci(_pipelineSize * _timePerExeci),_missrateTimesPipelinesize(_brachingMissrate*_pipelineSize), _branchMissReminder(0), _branchMissTempReminder(0){
 	_myid=++_id;
 	_transactList.reserve(BLOCK_SIZE);
 }
@@ -52,26 +54,23 @@ CPU::CPU(std::string iName, TMLTime iTimePerCycle, unsigned int iCyclesPerExeci,
 CPU::~CPU(){  
 	//unsigned int a=0;
 	TransactionList::iterator i;
-	std::cout << _transactList.size() << " elements in List of " << _name << std::endl; // << "try to delete transaction no ";
-	for(i=_transactList.begin(); i != _transactList.end(); ++i){
+	std::cout << _transactList.size() << " elements in List of " << _name << std::endl;
+	/*for(i=_transactList.begin(); i != _transactList.end(); ++i){
 		//std::cout << a++ << ", ";
 		//delete (*i);
 	}
-	std::cout << std::endl;
+	std::cout << std::endl;*/
 }
 
 void CPU::registerTask(TMLTask* iTask){
 	_taskList.push_back(iTask);
-	//iTask->setCPU(this);
 }
 
-TMLTransaction* CPU::getNextTransaction() const{
+TMLTransaction* CPU::getNextTransaction(){
 #ifdef BUS_ENABLED
 	if (_busNextTransaction==0){
-		//if (_nextTransaction==0) std::cout << "CPU " << _name << " has no next transaction.***********" << std::endl;
 		return _nextTransaction;
 	}else{
-		//std::cout << "BUS!!!!!!!!" << std::endl;
 		return (_busNextTransaction->getNextTransaction()==_nextTransaction)?_nextTransaction:0;
 	}
 #else
@@ -80,16 +79,38 @@ TMLTransaction* CPU::getNextTransaction() const{
 }
 
 void CPU::calcStartTimeLength(){
-	//immer auf volle cycle runden!!!
+#ifdef DEBUG_CPU	
+	std::cout << "CPU:calcSTL: scheduling decision of CPU " << _name << ": " << _nextTransaction->toString() << std::endl;
+#endif
+#ifdef BUS_ENABLED
+	//std::cout << "get channel " << std::endl;
+	TMLChannel* aChannel=_nextTransaction->getCommand()->getChannel();
+	//std::cout << "after get channel " << std::endl;
+	if(aChannel==0){
+		//std::cout << "no channel " << std::endl;
+		_busNextTransaction=0;
+	}else{
+		//std::cout << "get bus " << std::endl;
+		_busNextTransaction=aChannel->getFirstBus(_nextTransaction);
+		//std::cout << "after get first bus " << std::endl;
+		if (_busNextTransaction!=0){
+			//std::cout << "before register transaction at bus " << std::endl;
+			_busNextTransaction->registerTransaction(_nextTransaction,this);
+			//std::cout << "Transaction registered at bus " << std::endl;
+		}
+	}
+#endif		
+	//round to full cycles!!!
 	TMLTime aStartTime = max(_endSchedule,_nextTransaction->getRunnableTime());
 	TMLTime aReminder = aStartTime % _timePerCycle;
 	if (aReminder!=0) aStartTime+=_timePerCycle - aReminder; 
-	//_nextTransaction->setStartTime(max(_endSchedule,_nextTransaction->getRunnableTime()));
 	_nextTransaction->setStartTime(aStartTime);
 	
 #ifdef BUS_ENABLED
 	if (_busNextTransaction==0){
 		_nextTransaction->setLength(_nextTransaction->getVirtualLength()*_timePerExeci);
+	}else{
+		_busNextTransaction->truncateToBurst(_nextTransaction);
 	}
 #else
 	_nextTransaction->setLength(_nextTransaction->getVirtualLength()*_timePerExeci);
@@ -100,51 +121,106 @@ void CPU::calcStartTimeLength(){
 	if ((_nextTransaction->getStartTime()-_endSchedule) >=_timeBeforeIdle){
 		_nextTransaction->setIdlePenalty(_changeIdleModeTime);
 	} 
-	//_nextTransaction->setBranchingPenalty(_nextTransaction->getVirtualLength() * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
 	
-	_nextTransaction->setBranchingPenalty((_nextTransaction->getVirtualLength()+_branchMissReminder) * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
-	_branchMissTempReminder = (_nextTransaction->getVirtualLength()+_branchMissReminder) % (100/_brachingMissrate);
+	if (_brachingMissrate!=0){
+		_nextTransaction->setBranchingPenalty((_nextTransaction->getVirtualLength()+_branchMissReminder) * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
+		_branchMissTempReminder = (_nextTransaction->getVirtualLength()+_branchMissReminder) % (100/_brachingMissrate);
+	}
 }
 
 TMLTime CPU::truncateNextTransAt(TMLTime iTime){	
 	if (_busNextTransaction==0){
+		if (iTime < _nextTransaction->getStartTime()) return 0;
 		TMLTime aNewDuration = iTime - _nextTransaction->getStartTime();
 		TMLTime aStaticPenalty = _nextTransaction->getIdlePenalty() + _nextTransaction->getTaskSwitchingPenalty();
 		if (aNewDuration<=aStaticPenalty){
 			_nextTransaction->setLength(_timePerExeci);
 			_nextTransaction->setVirtualLength(1);
-			_nextTransaction->setBranchingPenalty((1+ _branchMissReminder) * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
-			_branchMissTempReminder = (1 +_branchMissReminder) % (100/_brachingMissrate);
+			if (_brachingMissrate!=0){
+				_nextTransaction->setBranchingPenalty((1+ _branchMissReminder) * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
+				_branchMissTempReminder = (1 +_branchMissReminder) % (100/_brachingMissrate);
+			}
+//#ifdef DEBUG_CPU
+			std::cout << "CPU:truncateNTA: transaction truncated once\n";
+//#endif
 		}else{
 			int test=0;
 			aNewDuration-=aStaticPenalty;
-			//_nextTransaction->setVirtualLength(100* aNewDuration /((_missrateTimesPipelinesize+100) * _timePerExeci));
+			std::cout << _name << " virtual length before cut: " << _nextTransaction->getVirtualLength() << std::endl;
 			_nextTransaction->setVirtualLength(100* aNewDuration /((_missrateTimesPipelinesize+100) * _timePerExeci));
 			_nextTransaction->setLength(_nextTransaction->getVirtualLength() *_timePerExeci);
-			_nextTransaction->setBranchingPenalty((_nextTransaction->getVirtualLength()+_branchMissReminder) * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
-			_branchMissTempReminder = (_nextTransaction->getVirtualLength()+_branchMissReminder) % (100/_brachingMissrate);
-			//std::cout << "While loop begin, new duration: " << aNewDuration << std::endl;
-			while (_nextTransaction->getOperationLength()+_nextTransaction->getBranchingPenalty() < aNewDuration){
-				test++;
-				_nextTransaction->setVirtualLength(_nextTransaction->getVirtualLength()+1);
-				_nextTransaction->setLength(_nextTransaction->getOperationLength() +_timePerExeci);
+			if (_brachingMissrate!=0){
 				_nextTransaction->setBranchingPenalty((_nextTransaction->getVirtualLength()+_branchMissReminder) * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
 				_branchMissTempReminder = (_nextTransaction->getVirtualLength()+_branchMissReminder) % (100/_brachingMissrate);
+				//std::cout << _name << " wants to cut transaction: " << _nextTransaction->toShortString() << std::endl;
+				//std::cout << "While loop begin, new duration: " << aNewDuration << " iTime: " << iTime << "  startTime: " << _nextTransaction->getStartTime() << std::endl;
+				while (_nextTransaction->getOperationLength()+_nextTransaction->getBranchingPenalty() < aNewDuration){
+					test++;
+					_nextTransaction->setVirtualLength(_nextTransaction->getVirtualLength()+1);
+					_nextTransaction->setLength(_nextTransaction->getOperationLength() +_timePerExeci);
+					_nextTransaction->setBranchingPenalty((_nextTransaction->getVirtualLength()+_branchMissReminder) * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
+					_branchMissTempReminder = (_nextTransaction->getVirtualLength()+_branchMissReminder) % (100/_brachingMissrate);
+				}
 			}
-			std::cout << "Truncate loop executed: " << test << " times.\n";
-			//std::cout << "While loop end\n";
-			//if (_nextTransaction->getOperationLength() < aNewDuration){
-				//FALSCH!!! aNewDuration beinhaltet auch branching penalty
-			//	_nextTransaction->setVirtualLength(_nextTransaction->getVirtualLength()+1);
-			//	_nextTransaction->setLength(_nextTransaction->getOperationLength() +_timePerExeci);
-			//}
-			//_nextTransaction->setBranchingPenalty(_nextTransaction->getVirtualLength() * _brachingMissrate / 100 *_pipelineSizeTimesExeci);
+//#ifdef DEBUG_CPU
+			std::cout << "CPU:truncateNTA: truncate loop executed: " << test << " times.\n";
+//#endif
 		}
-		//std::cout << "\n---------- cut transaction at : " << _nextTransaction->getVirtualLength() << std::endl;
+#ifdef DEBUG_CPU
+		std::cout << "CPU:truncateNTA: ### cut transaction at " << _nextTransaction->getVirtualLength() << std::endl;
+#endif
 	}
 	return _nextTransaction->getOverallLength();
 }
 
+bool CPU::addTransaction(){
+	bool aFinish;
+	//flag=false;
+	if (_busNextTransaction==0){
+		aFinish=true;
+#ifdef DEBUG_CPU
+		std::cout << _name << "CPU:addT: non bus transaction added" << std::endl;
+#endif
+	}else{
+#ifdef DEBUG_CPU
+		std::cout << _name << "CPU:addT: handling bus transaction" << std::endl;
+#endif
+		Slave* aLastSlave=_nextTransaction->getChannel()->getNextSlave(_nextTransaction);
+		_busNextTransaction=_nextTransaction->getChannel()->getNextBus(_nextTransaction);
+		if (_busNextTransaction==0){
+			//std::cout << _name << " bus transaction finished" << std::endl;
+			aFinish=true;
+			//std::cout << _name << " before loop" << std::endl;
+			_contentionDelay+=_nextTransaction->getStartTime()-_nextTransaction->getRunnableTime();
+			_noBusTransactions++;
+			SchedulableCommDevice* aTempBus =_nextTransaction->getChannel()->getFirstBus(_nextTransaction);
+			while (aTempBus!=0){
+				aTempBus->addTransaction();
+				aTempBus =_nextTransaction->getChannel()->getNextBus(_nextTransaction);
+			}
+			//std::cout << _name << " after loop" << std::endl;
+		}else{
+			//std::cout << _name << " bus transaction next round" << std::endl;
+			_busNextTransaction->registerTransaction(_nextTransaction,aLastSlave->getConnectedMaster());
+			aFinish=false;
+		}
+	}
+	if (aFinish){
+#ifdef DEBUG_CPU
+		std::cout << "CPU:addt: " << _name << " finalizing transaction " << _nextTransaction->toString() << std::endl;
+#endif
+		_nextTransaction->getCommand()->execute();
+		_endSchedule=_nextTransaction->getEndTime();
+		_simulatedTime=max(_simulatedTime,_endSchedule);
+		_transactList.push_back(_nextTransaction);
+		_lastTransaction=_nextTransaction;
+		_branchMissReminder=_branchMissTempReminder;
+		_busyCycles+=_nextTransaction->getOverallLength();
+		//std::cout << "busyCycles: " <<  _busyCycles << std::endl;
+		_nextTransaction=0;
+		return true;
+	}else return false;
+}
 
 unsigned int CPU::getID(){
 	return _myid;
@@ -199,9 +275,9 @@ void CPU::schedule2HTML(std::ofstream& myfile){
 
 
 		aCurrTime=aCurrTrans->getEndTime();
-		std::cout << "end time: " << aCurrTrans->getEndTime() << std::endl;
+		//std::cout << "end time: " << aCurrTrans->getEndTime() << std::endl;
 	}
-	std::cout << "acurrTime: " << aCurrTime << std::endl;
+	//std::cout << "acurrTime: " << aCurrTime << std::endl;
 	myfile << "</tr>\n<tr>";
 	for(aLength=0;aLength<aCurrTime;aLength++) myfile << "<th></th>";
 	myfile << "</tr>\n<tr>";
@@ -220,6 +296,8 @@ void CPU::schedule2HTML(std::ofstream& myfile){
 			if (aComment==0){
 				myfile << "<td></td><td></td><td class=\"space\"></td>";
 			}else{
+				replaceAll(aCommentString,"<","&lt;");
+				replaceAll(aCommentString,">","&gt;");
 				aMoreComments=true;
 				myfile << "<td>" << aComment->_time << "</td><td><pre>" << aCommentString << "</pre></td><td class=\"space\"></td>";
 			}	
@@ -230,6 +308,14 @@ void CPU::schedule2HTML(std::ofstream& myfile){
 	myfile << "</table>\n";
 }
 
+void CPU::schedule2TXT(std::ofstream& myfile){
+	TransactionList::iterator i;
+	myfile << "========================================\nScheduling for device: "<< _name << "\n========================================\n" ;
+	for(i=_transactList.begin(); i != _transactList.end(); ++i){
+		myfile << (*i)->toShortString() << std::endl;
+	}
+}
+
 TMLTime CPU::getNextSignalChange(bool iInit, std::string& oSigChange, bool& oNoMoreTrans){
 	std::ostringstream outp;
 	oNoMoreTrans=false;
@@ -250,6 +336,7 @@ TMLTime CPU::getNextSignalChange(bool iInit, std::string& oSigChange, bool& oNoM
 		oNoMoreTrans=true;
 		return _previousTransEndTime;
 	}else{
+		//std::cout << "VCD out trans: " << (*_posTrasactListVCD)->toShortString() << std::endl;
 		TMLTransaction* aCurrTrans=*_posTrasactListVCD;
 		switch (_vcdOutputState){
 			case END_TASK_CPU:
@@ -297,3 +384,13 @@ TMLTransaction* CPU::getTransactions1By1(bool iInit){
 	return aTrans;
 	
 }
+
+/*unsigned int CPU::getBusyCycles(){
+	return _busyCycles;
+}*/
+
+void CPU::streamBenchmarks(std::ostream& s){
+	s << "*** CPU " << _name << " ***\n"; 
+	if (_simulatedTime!=0) s << "Utilization: " << ((float)_busyCycles)/((float)_simulatedTime) << std::endl;
+	if (_noBusTransactions!=0) s << "Average contention delay: " << ((float)_contentionDelay)/((float)_noBusTransactions) << std::endl;
+}
diff --git a/simulators/c++2/src_simulator/CPU.h b/simulators/c++2/src_simulator/CPU.h
index 802eeab8f02c9ebaa81defe1f48eacae980647a4..5ec35b3f6e11b78fb4cbf1628bb4800bd3b48867 100644
--- a/simulators/c++2/src_simulator/CPU.h
+++ b/simulators/c++2/src_simulator/CPU.h
@@ -43,7 +43,9 @@ Ludovic Apvrille, Renaud Pacalet
 
 #include <definitions.h>
 #include <SchedulableDevice.h>
+#include <SchedulableCommDevice.h>
 #include <TraceableDevice.h>
+#include <Master.h>
 
 class TMLTask;
 class TMLTransaction;
@@ -57,18 +59,20 @@ enum vcdCPUVisState
 };
 
 ///Simulates the bahavior of a CPU and an operating system
-class CPU: public SchedulableDevice, public TraceableDevice{
+class CPU: public SchedulableDevice, public TraceableDevice, public Master{
 public:
 	///Constructor
     	/**
       	\param iName Name of the CPU
 	\param iTimePerCycle 1/Processor frequency
-	\param iCyclesPerExeci Cycles needed to execute one execi unit
+	\param iCyclesPerExeci Cycles needed to execute one EXECI unit
+	\param iCyclesPerExecc Cycles needed to execute one EXECC unit
 	\param iPipelineSize Pipeline size
 	\param iTaskSwitchingCycles Task switching penalty in cycles
 	\param iBranchingMissrate Branching prediction miss rate in %
 	\param iChangeIdleModeCycles Cycles needed to switch into indle mode
 	\param iCyclesBeforeIdle Idle cycles which elapse before entering idle mode
+	\param ibyteDataSize Machine word length
     	*/
 	CPU(std::string iName, TMLTime iTimePerCycle, unsigned int iCyclesPerExeci, unsigned int iCyclesPerExecc, unsigned int iPipelineSize, unsigned int iTaskSwitchingCycles, unsigned int iBranchingMissrate, unsigned int iChangeIdleModeCycles, unsigned int iCyclesBeforeIdle, unsigned int ibyteDataSize);
 	///Destructor
@@ -83,15 +87,16 @@ public:
 	///Add a transaction waiting for execution to the internal list
 	/**
       	\param iTrans Pointer to the transaction to add
+	\param iSourceDevice Source device
     	*/
-	virtual void registerTransaction(TMLTransaction* iTrans)=0;
+	virtual void registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice)=0;
 	///Adds the transaction determined by the scheduling algorithm to the internal list of scheduled transactions
-	virtual void addTransaction()=0;
+	virtual bool addTransaction();
 	///Returns a pointer to the transaction determined by the scheduling algorithm
     	/**
       	\return Pointer to transaction
     	*/
-	TMLTransaction* getNextTransaction() const;
+	TMLTransaction* getNextTransaction();
 	///Truncates the next transaction at time iTime
 	/**
 	\param iTime Indicates at what time the transaction should be truncated
@@ -131,6 +136,12 @@ public:
 	\return Pointer to the next transaction
     	*/
 	TMLTransaction* getTransactions1By1(bool iInit);
+	///Writes a plain text representation of the schedule to an output file
+	/**
+      	\param myfile Reference to the ofstream object representing the output file
+    	*/
+	void schedule2TXT(std::ofstream& myfile);
+	virtual void streamBenchmarks(std::ostream& s);
 protected:
 	///Calculates the start time and the length of the next transaction
 	void calcStartTimeLength();
@@ -140,14 +151,14 @@ protected:
 	TaskList _taskList;
 	///List containing all already scheduled transactions
 	TransactionList _transactList;
-	///End time of the last scheduled transaction
-	TMLTime _endSchedule;
+	/////End time of the last scheduled transaction
+	//TMLTime _endSchedule;
 	///Pointer to the next transaction to be executed
 	TMLTransaction* _nextTransaction;
 	///Pointer to the last transaction which has been executed
 	TMLTransaction* _lastTransaction;
 	///Pointer to the bus which will be accessed by the next transaction
-	Bus* _busNextTransaction;
+	SchedulableCommDevice* _busNextTransaction;
 	
 	///Unique ID of the CPU
 	unsigned int _myid;
@@ -168,6 +179,12 @@ protected:
 	unsigned int _cyclesBeforeIdle;
 	///Cycles needed to execute one execi unit
 	unsigned int _cyclesPerExeci;
+	///Busy cycles since simulation start
+	unsigned long _busyCycles;
+	///Contention delay of transactions (startTime-runnableTime)
+	unsigned long _contentionDelay;
+	///Number of executed transactions which have accessed a bus
+	unsigned int _noBusTransactions; 
 
 	//values deduced from CPU parameters 
 	///Time needed to execute one execi unit
diff --git a/simulators/c++2/src_simulator/CPUPB.cpp b/simulators/c++2/src_simulator/CPUPB.cpp
index ea46b1776fc73c7df476bc55c647ab7769c27356..e3d79f5eb0ccd8931d997fa58a104ad81d3ce968 100644
--- a/simulators/c++2/src_simulator/CPUPB.cpp
+++ b/simulators/c++2/src_simulator/CPUPB.cpp
@@ -53,17 +53,16 @@ CPUPB::~CPUPB(){
 
 void CPUPB::schedule(){
 	TaskList::iterator i;
-	TMLTransaction *aMarkerPast=0, *aMarkerFuture=0,*aTempTrans;
+	TMLTransaction *aMarkerPast=0, *aMarkerFuture=0,*aTempTrans, *aOldTransaction;
 	unsigned int aHighestPrioPast=-1;
 	TMLTime aTransTimeFuture=-1,aRunnableTime;
 	TMLTask* aTempTask;
 	for(i=_taskList.begin(); i != _taskList.end(); ++i){
 		aTempTask=*i;	
-		//std::cout << "before getCurrTransaction " << std::endl;
+		//std::cout << _name << " schedules, before getCurrTransaction " << std::endl;
 		if (aTempTask->getCurrCommand()!=0){
 			aTempTrans=aTempTask->getCurrCommand()->getCurrTransaction();
 			//std::cout << "after getCurrTransaction " << std::endl;
-			//if (aTempTrans!=0){ 
 			if (aTempTrans!=0 && aTempTrans->getVirtualLength()!=0){
 				aRunnableTime=aTempTrans->getRunnableTime();
 				//if (aRunnableTime<=_endSchedule && aTempTrans->getVirtualLength()!=0){
@@ -85,44 +84,21 @@ void CPUPB::schedule(){
 		}
 	}
 	//_nextTransaction=(aMarkerPast==0)?aMarkerFuture:aMarkerPast;
+	aOldTransaction=_nextTransaction;
 	if (aMarkerPast==0){
 		_nextTransaction=aMarkerFuture;
-		if (aMarkerFuture==0){
-			//std::cout << _name << " no transaction found" << std::endl;
+		/*if (aMarkerFuture==0){
+			std::cout << _name << " no transaction found" << std::endl;
 		}else{
-			//std::cout << _name << " transaction in the FUTURE found" << std::endl << _nextTransaction->toString() << std::endl;
-		}
+			std::cout << _name << " transaction in the FUTURE found" << std::endl << _nextTransaction->toString() << std::endl;
+		}*/
 	}else{
 		_nextTransaction=aMarkerPast;
 		//std::cout << std::endl << _name << " transaction in the PAST found" << std::endl << _nextTransaction->toString() << std::endl;
-		
-		
 	}
-
-	if (_nextTransaction!=0){
-	//std::cout << "Scheduling decision " << _name << _nextTransaction->toString() << std::endl;
-#ifdef BUS_ENABLED
-		TMLChannel* aChannel=_nextTransaction->getCommand()->getChannel();
-		if(aChannel==0){
-			_busNextTransaction=0;
-		}else{
-			_busNextTransaction=aChannel->getBus();
-			if (_busNextTransaction!=0) _busNextTransaction->registerTransaction(this,_nextTransaction);
-		}
-#endif		
-		calcStartTimeLength();
-	}//else
-		//std::cout << "no trans found on CPU " << _name << std::endl;
-}
-
-void CPUPB::registerTransaction(TMLTransaction* iTrans){
+	if (aOldTransaction!=0 && aOldTransaction!=_nextTransaction && _busNextTransaction!=0) _busNextTransaction->registerTransaction(0,this);
+	if (_nextTransaction!=0) calcStartTimeLength();
 }
 
-void CPUPB::addTransaction(){
-	_endSchedule=_nextTransaction->getEndTime();
-	//std::cout << std::endl << "** ADD on " << _name << " ** " << std::endl << _nextTransaction->toString() <<std::endl << "***" << std::endl;
-	_transactList.push_back(_nextTransaction);
-	_lastTransaction=_nextTransaction;
-	_branchMissReminder=_branchMissTempReminder;
-	_nextTransaction=0;
+void CPUPB::registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice){
 }
diff --git a/simulators/c++2/src_simulator/CPUPB.h b/simulators/c++2/src_simulator/CPUPB.h
index ad4fa91997dd2534e3072fb375c3d6a9ddbcd72a..f1d5fd9cf0b6b93ab9ab3e4428559aa33dfbad5d 100644
--- a/simulators/c++2/src_simulator/CPUPB.h
+++ b/simulators/c++2/src_simulator/CPUPB.h
@@ -54,21 +54,20 @@ public:
     	/**
       	\param iName Name of the CPU
 	\param iTimePerCycle 1/Processor frequency
-	\param iCyclesPerExeci Cycles needed to execute one execi unit
+	\param iCyclesPerExeci Cycles needed to execute one EXECI unit
+	\param iCyclesPerExecc Cycles needed to execute one EXECC unit
 	\param iPipelineSize Pipeline size
 	\param iTaskSwitchingCycles Task switching penalty in cycles
 	\param iBranchingMissrate Branching prediction miss rate in %
 	\param iChangeIdleModeCycles Cycles needed to switch into indle mode
 	\param iCyclesBeforeIdle Idle cycles which elapse before entering idle mode
+	\param ibyteDataSize Machine word length
     	*/
 	CPUPB(std::string iName, TMLTime iTimePerCycle, unsigned int iCyclesPerExeci, unsigned int iCyclesPerExecc, unsigned int iPipelineSize, unsigned int iTaskSwitchingCycles, unsigned int iBranchingMissrate, unsigned int iChangeIdleModeCycles, unsigned int iCyclesBeforeIdle, unsigned int ibyteDataSize);
 	///Destructor
 	~CPUPB();
-	
 	void schedule();
-	void registerTransaction(TMLTransaction* iTrans);
-	void addTransaction();
-
+	void registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice);
 protected:
 };
 
diff --git a/simulators/c++2/src_simulator/CPUPBL.cpp b/simulators/c++2/src_simulator/CPUPBL.cpp
index 8b1ecde58a2cf2ab5ba79edd3bcbf6a0dac00556..b40b1f190c60c69e4afa6bf9be44aaf32d95c848 100644
--- a/simulators/c++2/src_simulator/CPUPBL.cpp
+++ b/simulators/c++2/src_simulator/CPUPBL.cpp
@@ -57,21 +57,10 @@ void CPUPBL::schedule(){
 	}else{
 		_nextTransaction=_pastTransQueue.top();
 	}
-	if (_nextTransaction!=0){
-#ifdef BUS_ENABLED
-		TMLChannel* aChannel=_nextTransaction->getCommand()->getChannel();
-		if(aChannel==0){
-			_busNextTransaction=0;
-		}else{
-			_busNextTransaction=aChannel->getBus();
-			if (_busNextTransaction!=0) _busNextTransaction->registerTransaction(this,_nextTransaction);
-		}
-#endif		
-		calcStartTimeLength();
-	}
+	if (_nextTransaction!=0) calcStartTimeLength();
 }
 
-void CPUPBL::registerTransaction(TMLTransaction* iTrans){
+void CPUPBL::registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice){
 	if (iTrans->getRunnableTime()>_endSchedule){
 		_futureTransQueue.push(iTrans);
 	}else{
@@ -79,20 +68,18 @@ void CPUPBL::registerTransaction(TMLTransaction* iTrans){
 	}
 }
 
-void CPUPBL::addTransaction(){
-	TMLTransaction* aToPastTrans;
-	_endSchedule=_nextTransaction->getEndTime();
-	//std::cout << std::endl << "** ADD on " << _name << " ** " << std::endl << _nextTransaction->toString() <<std::endl << "***" << std::endl;
-	_transactList.push_back(_nextTransaction);
-	_lastTransaction=_nextTransaction;
-	_branchMissReminder=_branchMissTempReminder;
-	_nextTransaction=0;
-	if (_pastTransQueue.empty()) _futureTransQueue.pop(); else _pastTransQueue.pop();
-	while (!_futureTransQueue.empty()){
-		aToPastTrans=_futureTransQueue.top();
-		if (aToPastTrans->getRunnableTime()>_endSchedule) break;
-		_pastTransQueue.push(aToPastTrans);
-		_futureTransQueue.pop();	
-	}
+bool CPUPBL::addTransaction(){
+	if (CPU::addTransaction()){
+		TMLTransaction* aToPastTrans;
+		if (_pastTransQueue.empty()) _futureTransQueue.pop(); else _pastTransQueue.pop();
+		while (!_futureTransQueue.empty()){
+			aToPastTrans=_futureTransQueue.top();
+			if (aToPastTrans->getRunnableTime()>_endSchedule) break;
+			_pastTransQueue.push(aToPastTrans);
+			_futureTransQueue.pop();	
+		}
+		return true;
+	}else
+		return false;
 }
 
diff --git a/simulators/c++2/src_simulator/CPUPBL.h b/simulators/c++2/src_simulator/CPUPBL.h
index d2eabcc1bd198bdd72f452d1be3c33bbb746f482..c36647281ddb19840248d00d1d36defb91e7f564 100644
--- a/simulators/c++2/src_simulator/CPUPBL.h
+++ b/simulators/c++2/src_simulator/CPUPBL.h
@@ -54,19 +54,21 @@ public:
     	/**
       	\param iName Name of the CPU
 	\param iTimePerCycle 1/Processor frequency
-	\param iCyclesPerExeci Cycles needed to execute one execi unit
+	\param iCyclesPerExeci Cycles needed to execute one EXECI unit
+	\param iCyclesPerExecc Cycles needed to execute one EXECC unit
 	\param iPipelineSize Pipeline size
 	\param iTaskSwitchingCycles Task switching penalty in cycles
 	\param iBranchingMissrate Branching prediction miss rate in %
 	\param iChangeIdleModeCycles Cycles needed to switch into indle mode
 	\param iCyclesBeforeIdle Idle cycles which elapse before entering idle mode
+	\param ibyteDataSize Machine word length
     	*/
 	CPUPBL(std::string iName, TMLTime iTimePerCycle, unsigned int iCyclesPerExeci, unsigned int iCyclesPerExecc, unsigned int iPipelineSize, unsigned int iTaskSwitchingCycles, unsigned int iBranchingMissrate, unsigned int iChangeIdleModeCycles, unsigned int iCyclesBeforeIdle, unsigned int ibyteDataSize);
 	///Destructor
 	~CPUPBL();
 	void schedule();
-	void registerTransaction(TMLTransaction* iTrans);
-	void addTransaction();
+	void registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice);
+	bool addTransaction();
 protected:
 	///List of transaction in the future
 	FutureTransactionQueue _futureTransQueue;
diff --git a/simulators/c++2/src_simulator/CPURR.cpp b/simulators/c++2/src_simulator/CPURR.cpp
index 7c68ffc3a72a669e797e37e737ddb59a5e2437ab..412ee880f14fc2f6b58f70d97ef4cc11131edc42 100644
--- a/simulators/c++2/src_simulator/CPURR.cpp
+++ b/simulators/c++2/src_simulator/CPURR.cpp
@@ -66,24 +66,13 @@ void CPURR::schedule(){
 	}
 	
 	if (_nextTransaction!=0){
-#ifdef BUS_ENABLED
-		TMLChannel* aChannel=_nextTransaction->getCommand()->getChannel();
-		if(aChannel==0){
-			_busNextTransaction=0;
-		}else{
-			_busNextTransaction=aChannel->getBus();
-			if (_busNextTransaction!=0) _busNextTransaction->registerTransaction(this,_nextTransaction);
-		}
-#endif		
 		calcStartTimeLength();
 		if (_taskChanged) _taskStartTime = _nextTransaction->getStartTime() +  _nextTransaction->getIdlePenalty() + _nextTransaction->getTaskSwitchingPenalty();
 		if (_busNextTransaction==0 && _nextTransaction->getEndTime() > _taskStartTime + _timeQuantum) truncateNextTransAt(_taskStartTime + _timeQuantum);
-		
 	}
-	//std::cout << "End Schedule RR..." << std::endl; 
 }
 
-void CPURR::registerTransaction(TMLTransaction* iTrans){
+void CPURR::registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice){
 	//std::cout << "Register Transaction RR..." << std::endl; 
 	if (iTrans->getRunnableTime() > _endSchedule){
 		_futureTransQueue.push(iTrans);
@@ -92,30 +81,27 @@ void CPURR::registerTransaction(TMLTransaction* iTrans){
 	}
 }
 
-void CPURR::addTransaction(){
-	//std::cout << "Add Transaction RR..." << std::endl; 
-	TMLTransaction* aToPastTrans;
-	_endSchedule=_nextTransaction->getEndTime();
-	//std::cout << std::endl << "** ADD on " << _name << " ** " << std::endl << _nextTransaction->toString() <<std::endl << "***" << std::endl;
-	_transactList.push_back(_nextTransaction);
-	_lastTransaction=_nextTransaction;
-	_branchMissReminder=_branchMissTempReminder;
-	_nextTransaction=0;
-	if (_pastTransQueue.empty())
-		_futureTransQueue.pop(); 
-	else{
-		if (_taskChanged){
-			//_pastTransQueue.pop_front();
-			_pastTransQueue.erase(_pastTransQueue.begin());
-		}else{
-			_pastTransQueue.pop_back();
+bool CPURR::addTransaction(){
+	if (CPU::addTransaction()){
+		TMLTransaction* aToPastTrans;
+		if (_pastTransQueue.empty())
+			_futureTransQueue.pop(); 
+		else{
+			if (_taskChanged){
+				//_pastTransQueue.pop_front();
+				_pastTransQueue.erase(_pastTransQueue.begin());
+			}else{
+				_pastTransQueue.pop_back();
+			}
 		}
-	}
-	while (!_futureTransQueue.empty()){
-		aToPastTrans=_futureTransQueue.top();
-		if (aToPastTrans->getRunnableTime()>_endSchedule) break;
-		_pastTransQueue.push_back(aToPastTrans);
-		_futureTransQueue.pop();	
-	}
+		while (!_futureTransQueue.empty()){
+			aToPastTrans=_futureTransQueue.top();
+			if (aToPastTrans->getRunnableTime()>_endSchedule) break;
+			_pastTransQueue.push_back(aToPastTrans);
+			_futureTransQueue.pop();	
+		}
+		return true;
+	}else 
+		return false;
 }
 
diff --git a/simulators/c++2/src_simulator/CPURR.h b/simulators/c++2/src_simulator/CPURR.h
index 37407f629575e76fc6c66a3c2d73444107ebbc2c..4876fe2e4f4bd4a20793e2a0e8e757372538d36d 100644
--- a/simulators/c++2/src_simulator/CPURR.h
+++ b/simulators/c++2/src_simulator/CPURR.h
@@ -54,19 +54,21 @@ public:
     	/**
       	\param iName Name of the CPU
 	\param iTimePerCycle 1/Processor frequency
-	\param iCyclesPerExeci Cycles needed to execute one execi unit
+	\param iCyclesPerExeci Cycles needed to execute one EXECI unit
+	\param iCyclesPerExecc Cycles needed to execute one EXECC unit
 	\param iPipelineSize Pipeline size
 	\param iTaskSwitchingCycles Task switching penalty in cycles
 	\param iBranchingMissrate Branching prediction miss rate in %
 	\param iChangeIdleModeCycles Cycles needed to switch into indle mode
 	\param iCyclesBeforeIdle Idle cycles which elapse before entering idle mode
+	\param ibyteDataSize Machine word length
     	*/
 	CPURR(std::string iName, TMLTime iTimePerCycle, unsigned int iCyclesPerExeci, unsigned int iCyclesPerExecc, unsigned int iPipelineSize, unsigned int iTaskSwitchingCycles, unsigned int iBranchingMissrate, unsigned int iChangeIdleModeCycles, unsigned int iCyclesBeforeIdle, unsigned int ibyteDataSize);
 	///Destructor
 	~CPURR();
 	void schedule();
-	void registerTransaction(TMLTransaction* iTrans);
-	void addTransaction();
+	void registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice);
+	bool addTransaction();
 protected:
 	///List of transaction in the future
 	FutureTransactionQueue _futureTransQueue;
diff --git a/simulators/c++2/src_simulator/SchedulableDevice.h b/simulators/c++2/src_simulator/SchedulableDevice.h
index f5ee682a45c84d66030780354dceb72830303488..a5b8747bf4f18ca8ed4aa52d523c42f79c823932 100644
--- a/simulators/c++2/src_simulator/SchedulableDevice.h
+++ b/simulators/c++2/src_simulator/SchedulableDevice.h
@@ -41,27 +41,61 @@ Ludovic Apvrille, Renaud Pacalet
 #ifndef SchedulableDeviceH
 #define SchedulableDeviceH
 
+#include <definitions.h>
+#include <Serializable.h>
+class Master;
+
 class TMLTransaction;
 
 ///Base class for devices which perform a scheduling
-class SchedulableDevice{
+class SchedulableDevice: public Serializable{
 public:
+	SchedulableDevice():_endSchedule(0){}
 	///Determines the next transaction to be executed
 	virtual void schedule()=0;
 	///Adds the transaction determined by the scheduling algorithm to the internal list of scheduled transactions
-	virtual void addTransaction()=0;
+	virtual bool addTransaction()=0;
 	///Returns a pointer to the transaction determined by the scheduling algorithm
     	/**
       	\return Pointer to transaction
     	*/
-	virtual TMLTransaction* getNextTransaction() const=0;
+	virtual TMLTransaction* getNextTransaction()=0;
+	///Writes a HTML representation of the schedule to an output file
+	/**
+      	\param myfile Reference to the ofstream object representing the output file
+    	*/
+	///Add a transaction waiting for execution to the internal list
+	/**
+      	\param iTrans Pointer to the transaction to add
+	\param iSourceDevice Source device
+    	*/
+	virtual void registerTransaction(TMLTransaction* iTrans, Master* iSourceDevice)=0;
 	///Writes a HTML representation of the schedule to an output file
 	/**
       	\param myfile Reference to the ofstream object representing the output file
     	*/
 	virtual void schedule2HTML(std::ofstream& myfile)=0;
+	///Writes a plain text representation of the schedule to an output file
+	/**
+      	\param myfile Reference to the ofstream object representing the output file
+    	*/
+	virtual void schedule2TXT(std::ofstream& myfile)=0;
+	virtual std::string toString()=0;
 	///Destructor
 	virtual ~SchedulableDevice(){}
+	virtual std::istream& readObject(std::istream &is){
+		READ_STREAM(is,_endSchedule);
+		return is;
+	}
+	virtual std::ostream& writeObject(std::ostream &os){
+		WRITE_STREAM(os,_endSchedule);		
+		return os;
+	}
+protected:
+	///Class variable holding the simulation time
+	static TMLTime _simulatedTime;
+	///End time of the last scheduled transaction
+	TMLTime _endSchedule;
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLActionCommand.cpp b/simulators/c++2/src_simulator/TMLActionCommand.cpp
index f12f65afdada2242ba08784c67102edbe4b12291..ea9da6dccc29b5c7c6a52e462b51335d0234cee9 100644
--- a/simulators/c++2/src_simulator/TMLActionCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLActionCommand.cpp
@@ -47,13 +47,13 @@ TMLActionCommand::TMLActionCommand(TMLTask* iTask, ActionFuncPointer iActionFunc
 void TMLActionCommand::execute(){
 }
 
-bool TMLActionCommand::prepareNextTransaction(){
+TMLCommand* TMLActionCommand::prepareNextTransaction(){
 	TMLCommand* aNextCommand=getNextCommand();
 	//std::cout << "Action func CALLED length: " << *_pLength << " progress:" << _progress << std::endl;
 	(_task->*_actionFunc)();
 	_task->setCurrCommand(aNextCommand);
 	if (aNextCommand!=0) return aNextCommand->prepare();
-	return false;
+	return 0;
 }
 
 TMLTask* TMLActionCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLActionCommand.h b/simulators/c++2/src_simulator/TMLActionCommand.h
index 142a719a712e4aefefa22463e929f75365fb4083..2e0fa7e60954b0e6be026b31bcf4f1e8e330ddbc 100644
--- a/simulators/c++2/src_simulator/TMLActionCommand.h
+++ b/simulators/c++2/src_simulator/TMLActionCommand.h
@@ -63,7 +63,7 @@ public:
 protected:
 	///Member function pointer to the action function
 	ActionFuncPointer _actionFunc;
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLChannel.cpp b/simulators/c++2/src_simulator/TMLChannel.cpp
index a0464dcadc6a63d83662d31875686c2ff2bf5da3..dc4c67676d1aec49430a90c00f7d823ae3b8ab00 100644
--- a/simulators/c++2/src_simulator/TMLChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLChannel.cpp
@@ -40,12 +40,15 @@ Ludovic Apvrille, Renaud Pacalet
 
 #include <TMLChannel.h>
 #include <Bus.h>
+#include <TMLCommand.h>
+#include <TMLTransaction.h>
 
-TMLChannel::TMLChannel(std::string iName, Bus* iBus):_name(iName),_readTask(0),_writeTask(0),_bus(iBus),_burstSize(-1){
-	if (_bus!=0) _burstSize=_bus->getBurstSize();
+TMLChannel::TMLChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves):_name(iName), _readTask(0), _writeTask(0), _writeTrans(0), _readTrans(0),_numberOfHops(iNumberOfHops), _buses(iBuses), _slaves(iSlaves), _writeTransCurrHop(0), _readTransCurrHop(iNumberOfHops-1){
 }
 
 TMLChannel::~TMLChannel(){
+	if (_buses!=0) delete[] _buses;
+	if (_slaves!=0) delete[] _slaves;
 }
 
 void TMLChannel::setBlockedReadTask(TMLTask* iReadTask){
@@ -56,10 +59,71 @@ void TMLChannel::setBlockedWriteTask(TMLTask* iWriteTask){
 	_writeTask=iWriteTask;
 }
 
-Bus* TMLChannel::getBus() const{
-	return _bus;
+SchedulableCommDevice* TMLChannel::getNextBus(TMLTransaction* iTrans){
+	//if (iTrans->getCommand()->getTask()==_writeTask){
+	if (iTrans==_writeTrans){
+		_writeTransCurrHop++;
+		if (_writeTransCurrHop>0 && _buses[_writeTransCurrHop]==_buses[_writeTransCurrHop-1]) return 0;
+		return _buses[_writeTransCurrHop];
+	}else{
+		_readTransCurrHop--;
+		if (_readTransCurrHop<_numberOfHops-1 && _buses[_readTransCurrHop]==_buses[_readTransCurrHop+1]) return 0;
+		return _buses[_readTransCurrHop];
+	}
 }
 
+SchedulableCommDevice* TMLChannel::getFirstBus(TMLTransaction* iTrans){
+	//if (iTrans->getCommand()->getTask()==_writeTask){
+	if (_buses==0 || _slaves==0 || _numberOfHops==0) return 0;
+	if (iTrans==_writeTrans){
+		_writeTransCurrHop=0;
+		return _buses[_writeTransCurrHop];
+	}else{
+		_readTransCurrHop=_numberOfHops-1;
+		return _buses[_readTransCurrHop];
+	}
+}
+	
+Slave* TMLChannel::getNextSlave(TMLTransaction* iTrans){
+	//if (iTrans->getCommand()->getTask()==_writeTask){
+	if (iTrans==_writeTrans){
+		return _slaves[_writeTransCurrHop];
+	}else{
+		return _slaves[_readTransCurrHop];
+	}
+}
+
+//void TMLChannel::switchToNextBus(TMLTransaction* iTrans){
+	//if (iTrans->getCommand()->getTask()==_writeTask){
+//	if (iTrans==_writeTrans){
+		//_writeTransCurrHop++;
+//	}else{
+		//_readTransCurrHop--;
+//	}
+//}
+
+
+//SchedulableCommDevice* TMLChannel::getBus(unsigned int iIndex) const{
+//	if (_buses==0 || iIndex>=_numberOfHops) return 0;
+//	return _buses[iIndex];
+//}
+
+
+//unsigned int TMLChannel::getNumberOfHops() const{
+//	return _numberOfHops;
+//}
+
 std::string TMLChannel::toShortString(){
 	return _name;
 }
+
+std::ostream& TMLChannel::writeObject(std::ostream& s){
+	WRITE_STREAM(s,_writeTransCurrHop);
+	WRITE_STREAM(s,_readTransCurrHop);
+	return s;
+}
+std::istream& TMLChannel::readObject(std::istream& s){
+	READ_STREAM(s,_writeTransCurrHop);
+	READ_STREAM(s,_readTransCurrHop);
+	return s;
+}
diff --git a/simulators/c++2/src_simulator/TMLChannel.h b/simulators/c++2/src_simulator/TMLChannel.h
index c5e0742cc21845007124bdad0b6f726613ada9eb..de17dcb7621e40ffaf80a56d820f89b2ef53b381 100644
--- a/simulators/c++2/src_simulator/TMLChannel.h
+++ b/simulators/c++2/src_simulator/TMLChannel.h
@@ -42,6 +42,9 @@ Ludovic Apvrille, Renaud Pacalet
 #define TMLChannelH
 
 #include <definitions.h>
+#include <SchedulableCommDevice.h>
+#include <Slave.h>
+#include <Serializable.h>
 
 class TMLTransaction;
 class TMLCommand;
@@ -49,14 +52,16 @@ class TMLTask;
 class Bus;
 
 ///This class defines the basic interfaces and functionalites of a TML channel. All specific channels are derived from this base class. A channel is able to convey data and events. 
-class TMLChannel{
+class TMLChannel: public Serializable{
 public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
     	*/
-	TMLChannel(std::string iName, Bus* iBus);
+	TMLChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves);
 	///Destructor
 	virtual ~TMLChannel();
 	///Prepares a write operation
@@ -73,8 +78,6 @@ public:
 	virtual void write()=0;
 	///Performs the read operation
 	virtual bool read()=0;
-	//Cancels a pending read opeartion 
-	//virtual void cancelReadTransaction()=0;
 	///Stores a pointer to the tasks which performs read operation on the channel
 	/**
 	\param iReadTask Pointer to the task
@@ -95,11 +98,27 @@ public:
 	\return Pointer to the task
 	*/
 	virtual TMLTask* getBlockedWriteTask()const=0;
-	///Returns a pointer to the Bus on which the channel is mapped
+	///Returns the next communication link on which the given transaction is conveyed
 	/**
-	\return Pointer to the bus
+	\param iTrans Transaction
+	\return Pointer to the communication link
 	*/
-	Bus* getBus() const;
+	SchedulableCommDevice* getNextBus(TMLTransaction* iTrans);
+	///Returns the first communication link on which the given transaction is conveyed
+	/**
+	\param iTrans Transaction
+	\return Pointer to the communication link
+	*/
+	SchedulableCommDevice* getFirstBus(TMLTransaction* iTrans);
+	///Returns the next slave component to which the given transaction is sent
+	/**
+	\param iTrans Transaction
+	\return Pointer to the slave
+	*/
+	Slave* getNextSlave(TMLTransaction* iTrans);
+	//Returns the number of buses on which the channel is mapped
+	//\return Number of buses
+	//unsigned int getNumberOfHops() const;
 	///Returns a string representation of the channel
 	/**
 	\return Detailed string representation
@@ -110,6 +129,8 @@ public:
 	\return Short string representation
 	*/
 	std::string toShortString();
+	virtual std::ostream& writeObject(std::ostream& s);
+	virtual std::istream& readObject(std::istream& s);
 protected:
 	///Name of the channel
 	std::string _name;	
@@ -117,10 +138,20 @@ protected:
 	TMLTask* _readTask;
 	///Pointer to the tasks which performs write operation on the channel
 	TMLTask* _writeTask;
-	///Pointer to the bus on which the channel is mapped
-	Bus* _bus;
-	///Burst size of the associated bus (for performance reasons)
-	TMLLength _burstSize;
+	///Pointer to the transaction which attempts to write in the channel
+	TMLTransaction* _writeTrans;
+	///Pointer to the transaction which attempts to read the channel
+	TMLTransaction* _readTrans;
+	///Number of Buses/Slave devices on which the channel is mapped
+	unsigned int _numberOfHops;
+	///List of buses on which the channel is mapped
+	SchedulableCommDevice** _buses;
+	///List of slaves on which the channel is mapped
+	Slave** _slaves;
+	///Keeps track of the current Hop of a write Transaction
+	unsigned int _writeTransCurrHop;
+	///Keeps track of the current Hop of a read Transaction
+	unsigned int _readTransCurrHop;
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLChoiceCommand.cpp b/simulators/c++2/src_simulator/TMLChoiceCommand.cpp
index 0aeab8c425b947f9d8ff9c2506850837d98f42ed..661fa18ae69ee480b71912b7f3ce1334725adb99 100644
--- a/simulators/c++2/src_simulator/TMLChoiceCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLChoiceCommand.cpp
@@ -52,14 +52,14 @@ TMLCommand* TMLChoiceCommand::getNextCommand() const{
 	return _nextCommand[_indexNextCommand];
 }
 
-bool TMLChoiceCommand::prepareNextTransaction(){
+TMLCommand* TMLChoiceCommand::prepareNextTransaction(){
 	TMLCommand* aNextCommand;
 	//std::cout << "Choice func CALLED length: " << *_pLength << " progress:" << _progress << std::endl;
 	_indexNextCommand=(_task->*_condFunc)();
 	aNextCommand=getNextCommand();
 	_task->setCurrCommand(aNextCommand);
 	if (aNextCommand!=0) return aNextCommand->prepare();
-	return false;
+	return 0;
 }
 
 TMLTask* TMLChoiceCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLChoiceCommand.h b/simulators/c++2/src_simulator/TMLChoiceCommand.h
index fd9908d48af70e8e943efbdd196a97141309cfae..b5116b4221b1cb84de755e782a67ef6a9a95bc9a 100644
--- a/simulators/c++2/src_simulator/TMLChoiceCommand.h
+++ b/simulators/c++2/src_simulator/TMLChoiceCommand.h
@@ -66,7 +66,7 @@ protected:
 	///Index of the next command within the _nextCommand array
 	unsigned int _indexNextCommand;
 	TMLCommand* getNextCommand() const;
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLCommand.cpp b/simulators/c++2/src_simulator/TMLCommand.cpp
index 19f4ac02b59b000ec524976cc08bb9495ff1e211..d076a77f8d6cb44387bdfc61b2f890cb76da6568 100644
--- a/simulators/c++2/src_simulator/TMLCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLCommand.cpp
@@ -47,13 +47,6 @@ Ludovic Apvrille, Renaud Pacalet
 TMLCommand::TMLCommand(TMLTask* iTask, TMLLength iLength, Parameter<ParamType>* iParam): _length(iLength), _progress(0), _currTransaction(0), _task(iTask), _nextCommand(0), _param(iParam){
 }
 
-//TMLCommand::TMLCommand(TMLTask* iTask, TMLLength& ipLength,Parameter<ParamType>* iParam):_pLength(&ipLength),_cLength(0),_progress(0),_currTransaction(0),_task(iTask),_nextCommand(0),_param(iParam){
-//}
-
-//TMLCommand::TMLCommand(TMLTask* iTask, const TMLLength& icLength,Parameter<ParamType>* iParam):_pLength(&_cLength),_cLength(icLength),_progress(0),_currTransaction(0),_task(iTask),_nextCommand(0),_param(iParam){
-//}
-
-
 TMLCommand::~TMLCommand(){
 	if (_currTransaction!=0) delete _currTransaction;
 	//if (_currTransaction!=0) std::cout << "transaction not yet deleted: " << getCommandStr() << std::endl;
@@ -61,45 +54,32 @@ TMLCommand::~TMLCommand(){
 	if (_param!=0) delete _param;
 }
 
-bool TMLCommand::prepare(void){
+TMLCommand* TMLCommand::prepare(void){
 	TMLCommand* aNextCommand;
 	//Do not set _currTransaction=0 as specialized commands access the variable in the scope of the execute method (set terminated flag) 
-	//std::cout << "Prepare command, try to delete" << std::endl;
-	//if (_currTransaction!=0) delete _currTransaction;
-	//std::cout << "Prepare command, check pointer" << std::endl;
-	//if(*_pLength==_progress){
 	if(_length==_progress){
 		//std::cout << "COMMAND FINISHED!!!!!!!!!!!!!!!!!!!\n";
 		_progress=0;
-		//_currTransaction=0;
 		//std::cout << "Prepare command, get next command" << std::endl;
 		aNextCommand=getNextCommand();
 		//std::cout << "Prepare command, to next command" << std::endl;
 		if (aNextCommand==0){
-			//aOldTrans->setTerminatedFlag();
-			return false;
-			//_currTransaction=0;
+			return 0;
 		}else{
-			//_currTransaction=0;
 			_task->setCurrCommand(aNextCommand);			
 			//std::cout << "Prepare command, prepare next command" << std::endl;
-			//if (!aNextCommand->prepare()){
-				 //aOldTrans->setTerminatedFlag();
-				//return false;
-			//}
 			return aNextCommand->prepare();
 		}
-		//_currTransaction=0;
 	}else{
 		//std::cout << "Prepare next transaction" << std::endl;
-		bool result = prepareNextTransaction();
+		TMLCommand* result = prepareNextTransaction();
+		//if (_length==0) std::cout << "create trans with length 0: " << toString() << std::endl;
 		if (_currTransaction!=0 && _currTransaction->getVirtualLength()!=0){
-			_task->getCPU()->registerTransaction(_currTransaction);
+			_task->getCPU()->registerTransaction(_currTransaction,0);
 		}
 		return result;
 	}
-	return true;
-	//std::cout << "end Prepare command" << std::endl;
+	return 0;
 }
 
 TMLTask* TMLCommand::getTask() const{
@@ -139,3 +119,13 @@ Parameter<ParamType>* TMLCommand::getParam(){
 std::string TMLCommand::getCommentString(Comment* iCom){
 	return "no comment available";
 }
+
+std::ostream& TMLCommand::writeObject(std::ostream& s){
+	WRITE_STREAM(s,_progress);
+	return s;
+}
+
+std::istream& TMLCommand::readObject(std::istream& s){
+	READ_STREAM(s,_progress);
+	return s;
+}
diff --git a/simulators/c++2/src_simulator/TMLCommand.h b/simulators/c++2/src_simulator/TMLCommand.h
index e0b385889b1986890b50649f3d58da9fa9783acc..94b20ea763cafb5027c783b76c7a7fe2c89389d9 100644
--- a/simulators/c++2/src_simulator/TMLCommand.h
+++ b/simulators/c++2/src_simulator/TMLCommand.h
@@ -42,32 +42,22 @@ Ludovic Apvrille, Renaud Pacalet
 #define TMLCommandH
 
 #include <definitions.h>
+#include <Serializable.h>
 
 class TMLTransaction;
 class TMLTask;
 class TMLChannel;
 
 ///This class defines the basic interfaces and functionalites of a TML command. All specific commands are derived from this base class. 
-class TMLCommand{
+class TMLCommand: public Serializable{
 public:
 	///Constructor
     	/**
       	\param iTask Pointer to the task the command belongs to
-	\param icLength Constant virtual length of the command
+	\param iLength Virtual length of the command
 	\param iParam Pointer to a parameter data structure
     	*/
-	//TMLCommand(TMLTask* iTask, TMLLength icLength, Parameter* iParam);
-	//TMLCommand(TMLTask* iTask, const TMLLength& icLength,Parameter<ParamType>* iParam);
 	TMLCommand(TMLTask* iTask, TMLLength iLength,Parameter<ParamType>* iParam);
-	
-	/*///Constructor
-    	/**
-      	\param iTask Pointer to the task the command belongs to
-	\param ipLength Pointer to the virtual length of the command
-	\param iParam Pointer to a parameter data structure
-    	*/
-	//TMLCommand(TMLTask* iTask, TMLLength* ipLength,Parameter* iParam);
-	//TMLCommand(TMLTask* iTask, TMLLength& ipLength,Parameter<ParamType>* iParam);
 	///Destructor
 	virtual ~TMLCommand();
 	///Initializes the command and passes the control flow to the prepare() method of the next command if necessary
@@ -75,7 +65,7 @@ public:
       	\return True if there was a transaction to prepare
 	\sa prepareNextTransaction()
 	*/
-	bool prepare();
+	TMLCommand* prepare();
 	///Updates the inner state of the command as well as the state of all dependent objects (channel, bus,...)
 	virtual void execute()=0;
 	///Assigns a value to the pointer referencing the array of next commands
@@ -106,7 +96,7 @@ public:
 	virtual TMLChannel* getChannel() const;
 	///Indicates if the channel can be determined
 	/**
-	\return False if a nullpointer returned by getChannel() means the that command does not depend on any channel, true if a 	nullpointer returned by getChannel() indicates that the channel cannot be determined
+	\return False if a nullpointer returned by getChannel() means the that command does not depend on any channel, true if a nullpointer returned by getChannel() indicates that the channel cannot be determined
 	\sa getChannel()
 	*/
 	virtual bool channelUnknown();
@@ -125,14 +115,21 @@ public:
 	\return Short string representation
 	*/
 	virtual std::string toShortString()=0;
+	///Returns a short string representation of the command type
+	/**
+	\return Short string representation of command type
+	*/
 	virtual std::string getCommandStr()=0;
+	///Translates a comment into a readable string
+	/**
+	\param iCom Pointer to comment
+	\return Sring representation of the comment
+	*/
 	virtual std::string getCommentString(Comment* iCom);
-	
+	virtual std::ostream& writeObject(std::ostream& s);
+	virtual std::istream& readObject(std::istream& s);
 protected:
-	///Pointer to the variable length of the command
-	//TMLLength* _pLength;
-	///Constant length of the command
-	//TMLLength _cLength;
+	///Length of the command
 	TMLLength _length;
 	///Progress of the command (in execution units)
 	TMLLength _progress;
@@ -154,7 +151,7 @@ protected:
 	\return True if there was a transaction to prepare
 	\sa prepare()
 	*/
-	virtual bool prepareNextTransaction()=0;
+	virtual TMLCommand* prepareNextTransaction()=0;
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLEventBChannel.cpp b/simulators/c++2/src_simulator/TMLEventBChannel.cpp
index 7a6306e1de469bbf2849a2b1aad1ffb605fb86c7..a4973593ea8e0622dc3b1c9eb4bcd68a9d0dbb6f 100644
--- a/simulators/c++2/src_simulator/TMLEventBChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLEventBChannel.cpp
@@ -42,7 +42,34 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLTransaction.h>
 #include <TMLCommand.h>
 
-TMLEventBChannel::TMLEventBChannel(std::string iName, Bus *iBus, TMLLength iContent, bool iRequestChannel):TMLEventChannel(iName, iBus, iContent), _requestChannel(iRequestChannel){
+TMLEventBChannel::TMLEventBChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iContent, bool iRequestChannel, bool iSourceIsFile):TMLEventChannel(iName, iNumberOfHops, iBuses, iSlaves, iContent), _requestChannel(iRequestChannel), _sourceIsFile(iSourceIsFile),_eventFile(0) {
+	if (_sourceIsFile){
+		//std::cout << "new vv" << std::endl;
+		_eventFile = new std::ifstream(_name.c_str());
+		readNextEvents();
+	}
+}
+
+TMLEventBChannel::~TMLEventBChannel(){
+	if (_eventFile!=0){
+		if (_eventFile->is_open()) _eventFile->close();
+		delete _eventFile;
+	}
+}
+
+void TMLEventBChannel::readNextEvents(){
+	//std::cout << "vv" << std::endl;
+	if (_eventFile->is_open()){
+		int i=0;
+		Parameter<ParamType>* aNewParam;
+		while (++i<NO_EVENTS_TO_LOAD && !_eventFile->eof()){
+		//while (++i<2 && !_eventFile->eof()){
+			_content++;
+			aNewParam = new Parameter<ParamType>(0,0,0);
+			*_eventFile >> *aNewParam;
+			_paramQueue.push_back(aNewParam);
+		}
+	}
 }
 
 void TMLEventBChannel::testWrite(TMLTransaction* iTrans){
@@ -56,12 +83,6 @@ void TMLEventBChannel::testRead(TMLTransaction* iTrans){
 }
 
 void TMLEventBChannel::write(){
-	/*_content++;
-	_paramQueue.push_back(_writeTrans->getCommand()->getParam());
-	if (_readTrans!=0 && _readTrans->getVirtualLength()==0){
-		_readTrans->setRunnableTime(_writeTrans->getEndTime());
-		_readTrans->setVirtualLength(WAIT_SEND_VLEN);
-	}*/
 	write(_writeTrans);	
 	_writeTrans=0;
 }
@@ -81,6 +102,7 @@ bool TMLEventBChannel::read(){
 		return false;
 	}else{
 		_content--;
+		if (_content==0 && _sourceIsFile) readNextEvents();
 		pRead=_readTrans->getCommand()->getParam();
 		pWrite=_paramQueue.front();
 		if (pRead!=0 && pWrite!=0) *pRead=*pWrite;
diff --git a/simulators/c++2/src_simulator/TMLEventBChannel.h b/simulators/c++2/src_simulator/TMLEventBChannel.h
index 52ba3e72a895b701ca07369493c8001dad1b04ab..8655a0805180964c8f269ec590528fa2ae7bf733 100644
--- a/simulators/c++2/src_simulator/TMLEventBChannel.h
+++ b/simulators/c++2/src_simulator/TMLEventBChannel.h
@@ -53,10 +53,15 @@ public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
 	\param iContent Initial content of the channel
+	\param iRequestChannel Flag indicating if channel is used by a request
+	\param iSourceIsFile Flag indicating if events are read from a file
     	*/
-	TMLEventBChannel(std::string iName, Bus *iBus,TMLLength iContent, bool iRequestChannel=false);
+	TMLEventBChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iContent, bool iRequestChannel=false, bool iSourceIsFile=false);
+	~TMLEventBChannel();
 	void testWrite(TMLTransaction* iTrans);
 	void testRead(TMLTransaction* iTrans);
 	void write();
@@ -68,7 +73,12 @@ public:
 	std::string toString();
 	bool getRequestChannel();
 protected:
+	void readNextEvents();
+	///Flag indicating if channel is used by a request
 	bool _requestChannel;
+	///Flag indicating if events are read from a file
+	bool _sourceIsFile;
+	std::ifstream* _eventFile;
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLEventChannel.cpp b/simulators/c++2/src_simulator/TMLEventChannel.cpp
index 0745aa51526eb2cd0ff97c4391fb2687aae42bc2..b1a93c13f050cf1f01bf73b95e6d0a77d64c8b85 100644
--- a/simulators/c++2/src_simulator/TMLEventChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLEventChannel.cpp
@@ -40,7 +40,7 @@ Ludovic Apvrille, Renaud Pacalet
 
 #include <TMLEventChannel.h>
 
-TMLEventChannel::TMLEventChannel(std::string iName,Bus *iBus,TMLLength iContent):TMLStateChannel(iName,iBus,iContent){
+TMLEventChannel::TMLEventChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iContent): TMLStateChannel(iName, iNumberOfHops, iBuses, iSlaves, iContent){
 }
 
 TMLLength TMLEventChannel::getContent(){
@@ -51,4 +51,28 @@ bool TMLEventChannel::getRequestChannel(){
 	return false;
 }
 
+std::ostream& TMLEventChannel::writeObject(std::ostream& s){
+	ParamQueue::iterator i;
+	TMLStateChannel::writeObject(s);
+	for(i=_paramQueue.begin(); i != _paramQueue.end(); ++i){
+		(*i)->writeObject(s, (unsigned int)_writeTask);
+	}
+	//for_each( _paramQueue.begin(), _paramQueue.end(), std::bind2nd(std::bind1st(std::mem_fun(&(Parameter<ParamType>::writeObject)),s),(unsigned int)_writeTask));
+	return s;
+}
 
+std::istream& TMLEventChannel::readObject(std::istream& s){
+	TMLLength aParamNo;
+	ParamQueue::iterator i;
+	Parameter<ParamType>* aNewParam;
+	TMLStateChannel::readObject(s);
+	for(i=_paramQueue.begin(); i != _paramQueue.end(); ++i){
+		delete (*i);
+	}
+	_paramQueue.clear();
+	for(aParamNo=0; aParamNo < _content; aParamNo++){
+		aNewParam = new Parameter<ParamType>(s, (unsigned int) _writeTask);
+		_paramQueue.push_back(aNewParam);
+	}
+	return s;
+}
diff --git a/simulators/c++2/src_simulator/TMLEventChannel.h b/simulators/c++2/src_simulator/TMLEventChannel.h
index 59a51bfe80b2cb2aff1778d7d5c9f52bd72ad41b..4c0bf982ef61dbd91daa125181571b759390204c 100644
--- a/simulators/c++2/src_simulator/TMLEventChannel.h
+++ b/simulators/c++2/src_simulator/TMLEventChannel.h
@@ -52,16 +52,25 @@ public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
 	\param iContent Initial content of the channel
     	*/
-	TMLEventChannel(std::string iName,Bus *iBus,TMLLength iContent);
+	TMLEventChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iContent);
 	///Cancels a pending read operation 
 	virtual void cancelReadTransaction()=0;
 	///Returns the content of the channel (for the notified command)
 	TMLLength getContent();
+	///Returns a flag indicating if the channel is used by a request
+    	/**
+      	\return True if channel is used by a request, false otherwise
+	*/
 	virtual bool getRequestChannel();
+	virtual std::ostream& writeObject(std::ostream& s);
+	virtual std::istream& readObject(std::istream& s);
 protected:
+	///Queue for parameters
 	ParamQueue _paramQueue;
 };
 
diff --git a/simulators/c++2/src_simulator/TMLEventFBChannel.cpp b/simulators/c++2/src_simulator/TMLEventFBChannel.cpp
index 6d401425f71a8183229461da1c7b319de3689f0c..015de7dde5389ef94fe3c64c0584b3748d27c44d 100644
--- a/simulators/c++2/src_simulator/TMLEventFBChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLEventFBChannel.cpp
@@ -42,7 +42,7 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLTransaction.h>
 #include <TMLCommand.h>
 
-TMLEventFBChannel::TMLEventFBChannel(std::string iName, Bus* iBus, TMLLength iLength,TMLLength iContent):TMLEventChannel(iName,iBus,iContent),_length(iLength){
+TMLEventFBChannel::TMLEventFBChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iLength, TMLLength iContent): TMLEventChannel(iName, iNumberOfHops, iBuses, iSlaves, iContent),_length(iLength){
 }
 
 void TMLEventFBChannel::testWrite(TMLTransaction* iTrans){
diff --git a/simulators/c++2/src_simulator/TMLEventFBChannel.h b/simulators/c++2/src_simulator/TMLEventFBChannel.h
index 7cb3304154daa18401db020a17cc5a3b16eb2296..da979810d0f886a1e9747cb9e9fab2cb19d88ead 100644
--- a/simulators/c++2/src_simulator/TMLEventFBChannel.h
+++ b/simulators/c++2/src_simulator/TMLEventFBChannel.h
@@ -48,17 +48,18 @@ class TMLCommand;
 class Bus;
 
 ///This class models a blocking read blocking write channel (finite blocking FIFO).
-//class TMLbrbwChannel:public TMLChannel{
 class TMLEventFBChannel:public TMLEventChannel{
 public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
 	\param iLength Length of the channel
 	\param iContent Initial content of the channel
     	*/
-	TMLEventFBChannel(std::string iName,Bus* iBus,TMLLength iLength,TMLLength iContent);
+	TMLEventFBChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iLength, TMLLength iContent);
 	void testWrite(TMLTransaction* iTrans);
 	void testRead(TMLTransaction* iTrans);
 	void write();
@@ -68,8 +69,6 @@ public:
 	TMLTask* getBlockedWriteTask() const;
 	std::string toString();
 protected:
-	//Determines the virtual length of read and write transactions based on the state of the channel
-	//void setTransactionLength();
 	///Length of the channel
 	TMLLength _length;
 };
diff --git a/simulators/c++2/src_simulator/TMLEventFChannel.cpp b/simulators/c++2/src_simulator/TMLEventFChannel.cpp
index be04609700f4b2ec6bbad71a225fd572751e6e1a..232cd149773f764b53768dd38659ea5f47ba9e68 100644
--- a/simulators/c++2/src_simulator/TMLEventFChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLEventFChannel.cpp
@@ -42,7 +42,7 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLTransaction.h>
 #include <TMLCommand.h>
 
-TMLEventFChannel::TMLEventFChannel(std::string iName,Bus *iBus,TMLLength iLength,TMLLength iContent):TMLEventChannel(iName,iBus,iContent),_length(iLength){
+TMLEventFChannel::TMLEventFChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iLength, TMLLength iContent): TMLEventChannel(iName, iNumberOfHops, iBuses, iSlaves, iContent),_length(iLength){
 }
 
 void TMLEventFChannel::testWrite(TMLTransaction* iTrans){
diff --git a/simulators/c++2/src_simulator/TMLEventFChannel.h b/simulators/c++2/src_simulator/TMLEventFChannel.h
index 7aa2d408f75b3fb9b6cdb80e837cbc0ab2d7af6c..d37a294ad04e5fd3b67ed6ef4494e4b351762eb0 100644
--- a/simulators/c++2/src_simulator/TMLEventFChannel.h
+++ b/simulators/c++2/src_simulator/TMLEventFChannel.h
@@ -53,11 +53,13 @@ public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
 	\param iLength Length of the channel
 	\param iContent Initial content of the channel
     	*/
-	TMLEventFChannel(std::string iName,Bus *iBus,TMLLength iLength,TMLLength iContent);
+	TMLEventFChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iLength, TMLLength iContent);
 	void testWrite(TMLTransaction* iCommand);
 	void testRead(TMLTransaction* iCommand);
 	void write();
@@ -67,8 +69,6 @@ public:
 	TMLTask* getBlockedWriteTask() const;
 	std::string toString();
 protected:
-	//Determines the virtual length of read and write transactions based on the state of the channel
-	//void setTransactionLength();
 	///Length of the channel
 	TMLLength _length;
 };
diff --git a/simulators/c++2/src_simulator/TMLExeciCommand.cpp b/simulators/c++2/src_simulator/TMLExeciCommand.cpp
index 21fbed55d0d46de585633a7b2f1603799f531ae2..bc601919751f618241b9054b412958f9ce218646 100644
--- a/simulators/c++2/src_simulator/TMLExeciCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLExeciCommand.cpp
@@ -46,44 +46,35 @@ Ludovic Apvrille, Renaud Pacalet
 TMLExeciCommand::TMLExeciCommand(TMLTask* iTask, LengthFuncPointer iLengthFunc, unsigned int iType): TMLCommand(iTask,1,0), _lengthFunc(iLengthFunc), _type(iType){
 }
 
-//TMLExeciCommand::TMLExeciCommand(TMLTask* iTask, const TMLLength& iMinLen, const TMLLength& iMaxLen, unsigned int iType):TMLCommand(iTask,1,0), _pMaxLen(&_cMaxLen), _cMaxLen(iMaxLen), _pMinLen(&_cMinLen), _cMinLen(iMinLen), _type(iType){
-//}
-
-//TMLExeciCommand::TMLExeciCommand(TMLTask* iTask, const TMLLength& iMinLen, TMLLength& iMaxLen, unsigned int iType):TMLCommand(iTask,1,0),_pMaxLen(&iMaxLen),_cMaxLen(0), _pMinLen(&_cMinLen), _cMinLen(iMinLen), _type(iType){
-//}
-
-//TMLExeciCommand::TMLExeciCommand(TMLTask* iTask, TMLLength& iMinLen, const TMLLength& iMaxLen, unsigned int iType):TMLCommand(iTask,1,0), _pMaxLen(&_cMaxLen), _cMaxLen(iMaxLen), _pMinLen(&iMinLen), _cMinLen(0), _type(iType){
-//}
-
-//TMLExeciCommand::TMLExeciCommand(TMLTask* iTask, TMLLength& iMinLen, TMLLength& iMaxLen, unsigned int iType):TMLCommand(iTask,1,0),_pMaxLen(&iMaxLen),_cMaxLen(0), _pMinLen(&iMinLen), _cMinLen(0), _type(iType){
-//}
-
 void TMLExeciCommand::execute(){
-	//std::cout << "Execi execute get virt len " << _currTransaction;
 	//std::cout << _currTransaction->toShortString() << std::endl;
 	_progress+=_currTransaction->getVirtualLength();
 	//std::cout << "Execi execute set end" << std::endl;
-	_task->setEndLastTransaction(_currTransaction->getEndTime());
-	//_randLen=0;
+	//_task->setEndLastTransaction(_currTransaction->getEndTime());
+	_task->addTransaction(_currTransaction);
 	//std::cout << "Execi execute prepare" << std::endl;
-	if (!prepare()) _currTransaction->setTerminatedFlag();
-	if (_progress==0) _currTransaction=0;
+	TMLCommand* aNextCommand = prepare();
+	if (aNextCommand==0) _currTransaction->setTerminatedFlag();
+	if (_progress==0 && aNextCommand!=this) _currTransaction=0;
 }
 
-bool TMLExeciCommand::prepareNextTransaction(){
+TMLCommand* TMLExeciCommand::prepareNextTransaction(){
 	//std::cout << "ExeciCommand prepare " << toString() << std::endl;
-	//if (_randLen==0){
-	if (_progress==0) _length = (_task->*_lengthFunc)();
-		//_cLength=(*_pMaxLen==0)?*_pMinLen : (unsigned int) myrand((int)*_pMinLen,(int)*_pMaxLen);
-		//_pLength=&_cLength;
-		//std::cout << "Length is random ----------------!-!-!------------- "<< _cLength << "    "<< _progress << " "<< toString() << " " << this;
-		
-	//}
-	//std::cout << "length of execi: "<< *_pLength << std::endl;
-	//_currTransaction=new TMLTransaction(this,_progress,_cLength-_progress,_task->getEndLastTransaction());
-	_currTransaction=new TMLTransaction(this,_progress,_length-_progress,_task->getEndLastTransaction());
+	//if (_progress==0) _length = (_task->*_lengthFunc)();
+
+	//new test code
+	if (_progress==0){
+		 _length = (_task->*_lengthFunc)();
+		if (_length==0){
+			TMLCommand* aNextCommand=getNextCommand();
+			_task->setCurrCommand(aNextCommand);
+			if (aNextCommand!=0) return aNextCommand->prepare();
+		}
+	}
+
+	_currTransaction=new TMLTransaction(this, _length-_progress,_task->getEndLastTransaction());
 	//std::cout << "new fails? " << _currTransaction->toString() << std::endl;
-	return true;
+	return this;
 }
 
 TMLTask* TMLExeciCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLExeciCommand.h b/simulators/c++2/src_simulator/TMLExeciCommand.h
index 324e7dc64de860dba9d6d067588477513bea9913..696555d327a6787f78aa7f55b4896f13dfac77ab 100644
--- a/simulators/c++2/src_simulator/TMLExeciCommand.h
+++ b/simulators/c++2/src_simulator/TMLExeciCommand.h
@@ -45,57 +45,26 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLCommand.h>
 
 
-///This class models a delay due to calculating time within a TML tasks.
+///This class models the computational complexity of an algorithm
 class TMLExeciCommand:public TMLCommand{
 public:
 	///Constructor
     	/**
       	\param iTask Pointer to the task the command belongs to
-	\param iLength Constant virtual length of the command
-	\param iMaxDelay Constant maximal delay for Execi Interval commands 
+	\param iLengthFunc Pointer to the function returning the length of the command
+	\param iType Exec Type (ExecI, ExecC,...) 
     	*/
-	//TMLExeciCommand(TMLTask* iTask, const TMLLength& iLength);
-	//TMLExeciCommand(TMLTask* iTask, const TMLLength& iMinLen, const TMLLength& iMaxLen, unsigned int iType);
 	TMLExeciCommand(TMLTask* iTask, LengthFuncPointer iLengthFunc, unsigned int iType);
-	/*///Constructor
-    	/**
-      	\param iTask Pointer to the task the command belongs to
-	\param iLength Constant virtual length of the command
-	\param iMaxDelay Maximal delay for Execi Interval commands 
-    	*/
-	//TMLExeciCommand(TMLTask* iTask, const TMLLength& iMinLen, TMLLength& iMaxLen, unsigned int iType);
-	/*///Constructor
-    	/**
-      	\param iTask Pointer to the task the command belongs to
-	\param iLength Virtual length of the command
-	\param iMaxDelay Constant maximal delay for Execi Interval commands
-    	*/
-	//TMLExeciCommand(TMLTask* iTask, TMLLength& iLength);
-	//TMLExeciCommand(TMLTask* iTask, TMLLength& iMinLen, const TMLLength& iMaxLen, unsigned int iType);
-	/*///Constructor
-    	/**
-      	\param iTask Pointer to the task the command belongs to
-	\param iLength Virtual length of the command
-	\param iMaxDelay Maximal delay for Execi Interval commands
-    	*/
-	//TMLExeciCommand(TMLTask* iTask, TMLLength& iMinLen, TMLLength& iMaxLen, unsigned int iType);
 	void execute();
 	TMLTask* getDependentTask() const;
 	std::string toString();
 	std::string toShortString();
 	std::string getCommandStr();
 protected:
-	bool prepareNextTransaction();
-	///Pointer to the variable maximal length
-	//TMLLength* _pMaxLen;
-	///Constant value of the maximal length
-	//TMLLength _cMaxLen;
-	///Pointer to the variable maximal length
-	//TMLLength* _pMinLen;
-	///Constant value of the maximal length
-	//TMLLength _cMinLen;
-	///Type of exec command (execi, execc)
+	TMLCommand* prepareNextTransaction();
+	///Pointer to the function returning the length of the command
 	LengthFuncPointer _lengthFunc;
+	///Type of command: EXECI, EXECC
 	unsigned int _type;
 };
 
diff --git a/simulators/c++2/src_simulator/TMLNotifiedCommand.cpp b/simulators/c++2/src_simulator/TMLNotifiedCommand.cpp
index 5c0ffabcb1edfb1b733ee722ee8ebb819ee4c10b..52e45560ac82cb8b9c3dacc762dec7038292a571 100644
--- a/simulators/c++2/src_simulator/TMLNotifiedCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLNotifiedCommand.cpp
@@ -50,25 +50,19 @@ TMLNotifiedCommand::TMLNotifiedCommand(TMLTask* iTask,TMLEventChannel* iChannel,
 void TMLNotifiedCommand::execute(){
 	*_resultVar=_channel->getContent();
 	_progress+=_currTransaction->getVirtualLength();
-	_task->setEndLastTransaction(_currTransaction->getEndTime());
+	//_task->setEndLastTransaction(_currTransaction->getEndTime());
+	_task->addTransaction(_currTransaction);
 #ifdef ADD_COMMENTS
-	//std::ostringstream comment;
-	//comment << "Notified " << _resultVarDescr << "=" << *_resultVar;
 	_task->addComment(new Comment(_task->getEndLastTransaction(), this, *_resultVar));
 #endif
-	//_currTransaction=0;
-#if defined BUS_ENABLED && defined EVENTS_MAPPED_ON_BUS
-	Bus* bus=_channel->getBus();
-	if (bus!=0) bus->addTransaction();
-#endif
-	if (!prepare()) _currTransaction->setTerminatedFlag();
-	if (_progress==0) _currTransaction=0;
+	TMLCommand* aNextCommand = prepare();
+	if (aNextCommand==0) _currTransaction->setTerminatedFlag();
+	if (_progress==0 && aNextCommand!=this) _currTransaction=0;
 }
 
-bool TMLNotifiedCommand::prepareNextTransaction(){
-	//_currTransaction=new TMLTransaction(this,_progress,(*_pLength)-_progress,_task->getEndLastTransaction());
-	_currTransaction=new TMLTransaction(this,_progress,_length-_progress,_task->getEndLastTransaction());
-	return true;
+TMLCommand* TMLNotifiedCommand::prepareNextTransaction(){
+	_currTransaction=new TMLTransaction(this, _length-_progress,_task->getEndLastTransaction(),_channel);
+	return this;
 }
 
 TMLTask* TMLNotifiedCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLNotifiedCommand.h b/simulators/c++2/src_simulator/TMLNotifiedCommand.h
index a9c7d446b6bb6febe04367ed50fc2da842820ca9..a885000d4c28171d17ae72b24d18e70fe6d4ec09 100644
--- a/simulators/c++2/src_simulator/TMLNotifiedCommand.h
+++ b/simulators/c++2/src_simulator/TMLNotifiedCommand.h
@@ -46,7 +46,7 @@ Ludovic Apvrille, Renaud Pacalet
 
 class TMLEventChannel;
 
-///This class models the waiting for an event within a TML task.
+///This class models a TML command which determines the number of events queued in a channel
 class TMLNotifiedCommand:public TMLCommand{
 public:
 	///Constructor
@@ -54,7 +54,7 @@ public:
       	\param iTask Pointer to the task the command belongs to
 	\param iChannel Pointer to the channel on which the event is conveyed
 	\param iResultVar Pointer to the variable which has to contain the result
-	\param iResultVarDescr String representation of the result variable, for debugging purposes
+	\param iResultVarDescr String representation of the result variable
 	*/
 	TMLNotifiedCommand(TMLTask* iTask,TMLEventChannel* iChannel,TMLLength* iResultVar,const std::string& iResultVarDescr);
 	void execute();
@@ -69,8 +69,9 @@ protected:
 	TMLEventChannel* _channel;
 	///Index of the statement to execute (this value is passed to TMLTask::executeStatement())
 	TMLLength* _resultVar;
+	///String representation of the result variable
 	std::string _resultVarDescr;
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLReadCommand.cpp b/simulators/c++2/src_simulator/TMLReadCommand.cpp
index 55b075bcdd5673aa2a868cb59dbeae997871108d..44e6369790f66b95c4598ce0594bd515e14cdb24 100644
--- a/simulators/c++2/src_simulator/TMLReadCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLReadCommand.cpp
@@ -46,37 +46,37 @@ Ludovic Apvrille, Renaud Pacalet
 
 TMLReadCommand::TMLReadCommand(TMLTask* iTask, LengthFuncPointer iLengthFunc, TMLChannel* iChannel): TMLCommand(iTask,1,0),_lengthFunc(iLengthFunc), _channel(iChannel){
 }
-//TMLReadCommand::TMLReadCommand(TMLTask* iTask, const TMLLength& iLength, TMLChannel* iChannel): TMLCommand(iTask,iLength,0), _channel(iChannel){
-//	std::cout << "const read called" << std::endl;
-//}
-
-//TMLReadCommand::TMLReadCommand(TMLTask* iTask, TMLLength& iLength, TMLChannel* iChannel): TMLCommand(iTask, iLength,0), _channel(iChannel){
-//	std::cout << "variable read called" << std::endl;
-//}
 
 void TMLReadCommand::execute(){
 	_channel->read();
 	_progress+=_currTransaction->getVirtualLength();
-	_task->setEndLastTransaction(_currTransaction->getEndTime());
-	//_currTransaction=0;
-#ifdef BUS_ENABLED
-	Bus* bus=_channel->getBus();
-	if (bus!=0) bus->addTransaction();
-#endif
-	if (!prepare()) _currTransaction->setTerminatedFlag();
-	if (_progress==0) _currTransaction=0;
+	//_task->setEndLastTransaction(_currTransaction->getEndTime());
+	_task->addTransaction(_currTransaction);
+	TMLCommand* aNextCommand = prepare();
+	if (aNextCommand==0) _currTransaction->setTerminatedFlag();
+	if (_progress==0 && aNextCommand!=this) _currTransaction=0;
 }
 
-bool TMLReadCommand::prepareNextTransaction(){
+TMLCommand* TMLReadCommand::prepareNextTransaction(){
 	//std::cout << "ReadCommand prepare" << std::endl;
 	//std::cout << "length of read: "<< *_pLength << std::endl;
-	//_currTransaction=new TMLTransaction(this, _progress,(*_pLength)-_progress, _task->getEndLastTransaction(), _channel);
-	if (_progress==0) _length = (_task->*_lengthFunc)();
-	_currTransaction=new TMLTransaction(this, _progress, _length-_progress, _task->getEndLastTransaction(), _channel);
+	//if (_progress==0) _length = (_task->*_lengthFunc)();
+
+	//new test code
+	if (_progress==0){
+		 _length = (_task->*_lengthFunc)();
+		if (_length==0){
+			TMLCommand* aNextCommand=getNextCommand();
+			_task->setCurrCommand(aNextCommand);
+			if (aNextCommand!=0) return aNextCommand->prepare();
+		}
+	}
+
+	_currTransaction=new TMLTransaction(this, _length-_progress, _task->getEndLastTransaction(), _channel);
 	//std::cout << "before test read" << std::endl;
 	_channel->testRead(_currTransaction);
 	//std::cout << "ReadCommand end prepare" << std::endl;
-	return true;
+	return this;
 }
 
 TMLTask* TMLReadCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLReadCommand.h b/simulators/c++2/src_simulator/TMLReadCommand.h
index 4102f2eaef779c1e072a3f73300e3af7472045d4..cdebd68a7452eaf5466a62a31077b462d3bc9d29 100644
--- a/simulators/c++2/src_simulator/TMLReadCommand.h
+++ b/simulators/c++2/src_simulator/TMLReadCommand.h
@@ -52,18 +52,10 @@ public:
 	///Constructor
     	/**
       	\param iTask Pointer to the task the command belongs to
-	\param iLength Constant virtual length of the command
+	\param iLengthFunc Pointer to the function returning the length of the command
 	\param iChannel Pointer to the channel which is read
 	*/
-	//TMLReadCommand(TMLTask* iTask, const TMLLength& iLength,TMLChannel* iChannel);
 	TMLReadCommand(TMLTask* iTask, LengthFuncPointer iLengthFunc, TMLChannel* iChannel);
-	/*///Constructor
-    	/**
-      	\param iTask Pointer to the task the command belongs to
-	\param iLength Virtual length of the command
-	\param iChannel Pointer to the channel which is read
-	*/
-	//TMLReadCommand(TMLTask* iTask, TMLLength& iLength,TMLChannel* iChannel);
 	void execute();
 	TMLTask* getDependentTask() const;
 	TMLChannel* getChannel() const;
@@ -71,10 +63,11 @@ public:
 	std::string toShortString();
 	std::string getCommandStr();
 protected:
+	///Pointer to the function returning the length of the command
 	LengthFuncPointer _lengthFunc;
 	///Channel which is read
 	TMLChannel* _channel;
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLRequestCommand.cpp b/simulators/c++2/src_simulator/TMLRequestCommand.cpp
index ec3f9cb74caebfb8d5e1f7fb7c31cb213e5c74c8..e67094d3e7ffc6a3eca498be2e0689357d6062ba 100644
--- a/simulators/c++2/src_simulator/TMLRequestCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLRequestCommand.cpp
@@ -52,24 +52,18 @@ void TMLRequestCommand::execute(){
 	//std::cout << "Dependent Task: " << _channel->getBlockedReadTask()->toString() << std::endl;
 	_progress+=_currTransaction->getVirtualLength();
 	//std::cout << "setEndLastTrans Virtual length " << std::endl;
-	_task->setEndLastTransaction(_currTransaction->getEndTime());
-	//_currTransaction=0;
-#if defined BUS_ENABLED && defined EVENTS_MAPPED_ON_BUS
-	//std::cout << "Bus OPS " << std::endl;
-	Bus* bus=_channel->getBus();
-	if (bus!=0) bus->addTransaction();
-#endif
-	//std::cout << "prepare " << std::endl;
-	if (!prepare()) _currTransaction->setTerminatedFlag();
-	if (_progress==0) _currTransaction=0;
+	//_task->setEndLastTransaction(_currTransaction->getEndTime());
+	_task->addTransaction(_currTransaction);
+	TMLCommand* aNextCommand = prepare();
+	if (aNextCommand==0) _currTransaction->setTerminatedFlag();
+	if (_progress==0 && aNextCommand!=this) _currTransaction=0;
 }
 
-bool TMLRequestCommand::prepareNextTransaction(){
+TMLCommand* TMLRequestCommand::prepareNextTransaction(){
 	//std::cout << "prepare bext transaction testWrite prg:" << _progress << " to execute:" << (*_pLength)-_progress << std::endl;
-	//_currTransaction=new TMLTransaction(this,_progress,(*_pLength)-_progress,_task->getEndLastTransaction());
-	_currTransaction=new TMLTransaction(this,_progress,_length-_progress,_task->getEndLastTransaction());
+	_currTransaction=new TMLTransaction(this, _length-_progress,_task->getEndLastTransaction(),_channel);
 	_channel->testWrite(_currTransaction);
-	return true;
+	return this;
 }
 
 TMLTask* TMLRequestCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLRequestCommand.h b/simulators/c++2/src_simulator/TMLRequestCommand.h
index cb7ddd79bb6e1c6a8ec408038f6b03aecc722aff..c2c7d0b27bafdbd7132e2de714425b038d798c59 100644
--- a/simulators/c++2/src_simulator/TMLRequestCommand.h
+++ b/simulators/c++2/src_simulator/TMLRequestCommand.h
@@ -46,7 +46,7 @@ Ludovic Apvrille, Renaud Pacalet
 
 class TMLEventBChannel;
 
-///This class models a send event operation within a TML task.
+///This class models a send request operation within a TML task.
 class TMLRequestCommand:public TMLCommand{
 public:
 	///Constructor
@@ -65,7 +65,7 @@ public:
 protected:
 	///Channel on which the event is conveyed
 	TMLEventBChannel* _channel;
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLSelectCommand.cpp b/simulators/c++2/src_simulator/TMLSelectCommand.cpp
index 8813c8976701b1bc04202cbf011f2c7782116250..85b3926bb0be0622d30a40e20b6f341be84d9dfd 100644
--- a/simulators/c++2/src_simulator/TMLSelectCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLSelectCommand.cpp
@@ -76,26 +76,21 @@ void TMLSelectCommand::execute(){
 	}
 	_currTransaction->setChannel(_channel[_indexNextCommand]);
 	_progress+=_currTransaction->getVirtualLength();
-	_task->setEndLastTransaction(_currTransaction->getEndTime());
+	//_task->setEndLastTransaction(_currTransaction->getEndTime());
+	_task->addTransaction(_currTransaction);
 #ifdef ADD_COMMENTS
-	//_task->addComment(new Comment(_task->getEndLastTransaction(), "SelectEvent result: " + _channel[_indexNextCommand]->toShortString()));
 	_task->addComment(new Comment(_task->getEndLastTransaction(), this, _indexNextCommand));
 #endif
-	//_currTransaction=0;
 	_maxChannelIndex=0;
-#if defined BUS_ENABLED && defined EVENTS_MAPPED_ON_BUS
-	Bus* bus=_channel[_indexNextCommand]->getBus();
-	if (bus!=0) bus->addTransaction();
-#endif
-	if (!prepare()) _currTransaction->setTerminatedFlag();
-	if (_progress==0) _currTransaction=0;
+	TMLCommand* aNextCommand = prepare();
+	if (aNextCommand==0) _currTransaction->setTerminatedFlag();
+	if (_progress==0 && aNextCommand!=this) _currTransaction=0;
 }
 
-bool TMLSelectCommand::prepareNextTransaction(){
+TMLCommand* TMLSelectCommand::prepareNextTransaction(){
 	unsigned int i;
 	//std::cout << "SC: New transaction."<< std::endl;
-	//_currTransaction=new TMLTransaction(this,_progress,(*_pLength)-_progress,_task->getEndLastTransaction());
-	_currTransaction=new TMLTransaction(this,_progress,_length-_progress,_task->getEndLastTransaction());
+	_currTransaction=new TMLTransaction(this, _length-_progress,_task->getEndLastTransaction());
 	//std::cout << "SC: loop."<< std::endl;
 	for (i=0;i<_numbChannels && _maxChannelIndex==0;i++){
 		//std::cout << "SC: inner."<< i<< std::endl;
@@ -104,7 +99,7 @@ bool TMLSelectCommand::prepareNextTransaction(){
 		if (_currTransaction->getVirtualLength()!=0) _maxChannelIndex=i+1;
 	}
 	//std::cout << "Max channel index:" << _maxChannelIndex << "  virtual length:" << _currTransaction->getVirtualLength()  << std::endl;
-	return true;
+	return this;
 }
 
 TMLTask* TMLSelectCommand::getDependentTask() const{
@@ -136,7 +131,9 @@ std::string TMLSelectCommand::toString(){
 }
 
 std::string TMLSelectCommand::toShortString(){
-	return "SelectEvent";
+	std::ostringstream outp;
+	outp << _task->toString() << ": SelectEvent";
+	return outp.str();
 }
 
 std::string TMLSelectCommand::getCommandStr(){
diff --git a/simulators/c++2/src_simulator/TMLSelectCommand.h b/simulators/c++2/src_simulator/TMLSelectCommand.h
index 92006cb1c0fdfe465119e3d3de2cc922e32f24ba..1ac4b5398d5926c9b0b28876444437fb14738d21 100644
--- a/simulators/c++2/src_simulator/TMLSelectCommand.h
+++ b/simulators/c++2/src_simulator/TMLSelectCommand.h
@@ -69,7 +69,7 @@ public:
 	std::string getCommandStr();
 	std::string getCommentString(Comment* iCom);
 protected:
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 	TMLCommand* getNextCommand() const;
 	///Pointer to an array of pointers to channels conveying the desired signals
 	TMLEventChannel** _channel;
diff --git a/simulators/c++2/src_simulator/TMLSendCommand.cpp b/simulators/c++2/src_simulator/TMLSendCommand.cpp
index 988bd41b285198c8c0d4165ddcb5f5febbaea386..36570c18f1154ce5e7df7a3eec96edfd9dc2cbc2 100644
--- a/simulators/c++2/src_simulator/TMLSendCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLSendCommand.cpp
@@ -51,22 +51,17 @@ void TMLSendCommand::execute(){
 	_channel->write();
 	//std::cout << "Dependent Task: " << _channel->getBlockedReadTask()->toString() << std::endl;
 	_progress+=_currTransaction->getVirtualLength();
-	_task->setEndLastTransaction(_currTransaction->getEndTime());
-	//_currTransaction=0;
-	//if (_param!=0) _param->print(); else std::cout << "no param\n";
-#if defined BUS_ENABLED && defined EVENTS_MAPPED_ON_BUS
-	Bus* bus=_channel->getBus();
-	if (bus!=0) bus->addTransaction();
-#endif
-	if (!prepare()) _currTransaction->setTerminatedFlag();
-	if (_progress==0) _currTransaction=0;
+	//_task->setEndLastTransaction(_currTransaction->getEndTime());
+	_task->addTransaction(_currTransaction);
+	TMLCommand* aNextCommand = prepare();
+	if (aNextCommand==0) _currTransaction->setTerminatedFlag();
+	if (_progress==0 && aNextCommand!=this) _currTransaction=0;
 }
 
-bool TMLSendCommand::prepareNextTransaction(){
-	//_currTransaction=new TMLTransaction(this, _progress,(*_pLength)-_progress, _task->getEndLastTransaction(), _channel);
-	_currTransaction=new TMLTransaction(this, _progress,_length-_progress, _task->getEndLastTransaction(), _channel);
+TMLCommand* TMLSendCommand::prepareNextTransaction(){
+	_currTransaction=new TMLTransaction(this, _length-_progress, _task->getEndLastTransaction(), _channel);
 	_channel->testWrite(_currTransaction);
-	return true;
+	return this;
 }
 
 TMLTask* TMLSendCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLSendCommand.h b/simulators/c++2/src_simulator/TMLSendCommand.h
index d0f7f65d12bb7feef1300a7f4ee70383325c9862..8948c31ccbae96dd04eb664388b4953b73d9533c 100644
--- a/simulators/c++2/src_simulator/TMLSendCommand.h
+++ b/simulators/c++2/src_simulator/TMLSendCommand.h
@@ -65,7 +65,7 @@ public:
 protected:
 	///Channel on which the event is conveyed
 	TMLEventChannel* _channel;
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLStateChannel.cpp b/simulators/c++2/src_simulator/TMLStateChannel.cpp
index d9e60eecb4c5cd25a757e1389ca78ac41d5defcb..5bcd1f1dd9f493d5ab78d5439ae93c4dfd19afa0 100644
--- a/simulators/c++2/src_simulator/TMLStateChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLStateChannel.cpp
@@ -40,7 +40,19 @@ Ludovic Apvrille, Renaud Pacalet
 
 #include <TMLStateChannel.h>
 
-TMLStateChannel::TMLStateChannel(std::string iName,Bus *iBus,TMLLength iContent):TMLChannel(iName,iBus),_content(iContent),_writeTrans(0),_readTrans(0),_nbToWrite(0),_nbToRead(0){
+TMLStateChannel::TMLStateChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iContent): TMLChannel(iName, iNumberOfHops, iBuses, iSlaves), _content(iContent), _nbToWrite(0), _nbToRead(0){
 }
 
 TMLStateChannel::~TMLStateChannel(){}
+
+std::ostream& TMLStateChannel::writeObject(std::ostream& s){
+	TMLChannel::writeObject(s);
+	WRITE_STREAM(s,_content);
+	return s;
+}
+
+std::istream& TMLStateChannel::readObject(std::istream& s){
+	TMLChannel::readObject(s);
+	READ_STREAM(s,_content);
+	return s;
+}
diff --git a/simulators/c++2/src_simulator/TMLStateChannel.h b/simulators/c++2/src_simulator/TMLStateChannel.h
index 9421f138c1486b353817bd521e75a32a9d03511e..0bf53afbc62fb71865137d34965905424a57fd1b 100644
--- a/simulators/c++2/src_simulator/TMLStateChannel.h
+++ b/simulators/c++2/src_simulator/TMLStateChannel.h
@@ -52,19 +52,19 @@ public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
 	\param iContent Initial content of the channel
     	*/
-	TMLStateChannel(std::string iName,Bus *iBus,TMLLength iContent);
+	TMLStateChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves ,TMLLength iContent);
 	///Destructor
 	virtual ~TMLStateChannel();
+	virtual std::ostream& writeObject(std::ostream& s);
+	virtual std::istream& readObject(std::istream& s);
 protected:
 	///Content of the channel
 	TMLLength _content;
-	///Pointer to the transaction which attempts to write in the channel
-	TMLTransaction* _writeTrans;
-	///Pointer to the transaction which attempts to read the channel
-	TMLTransaction* _readTrans;
 	///Number of samples the write transaction attempts to write
 	TMLLength _nbToWrite;
 	///Number of samples the read transaction attempts to read
diff --git a/simulators/c++2/src_simulator/TMLTask.cpp b/simulators/c++2/src_simulator/TMLTask.cpp
index fba8306a3f207e21e6f33e986818a7578ce468fd..f53419241074a7b71d9865db50f829e6aa53e3ec 100644
--- a/simulators/c++2/src_simulator/TMLTask.cpp
+++ b/simulators/c++2/src_simulator/TMLTask.cpp
@@ -42,7 +42,7 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLCommand.h>
 #include <CPU.h>
 
-TMLTask::TMLTask(unsigned int iPriority, std::string iName, CPU* iCPU):_name(iName), _priority(iPriority), _endLastTransaction(0), _currCommand(0), _cpu(iCPU), _previousTransEndTime(0), _comment(0) {
+TMLTask::TMLTask(unsigned int iPriority, std::string iName, CPU* iCPU):_name(iName), _priority(iPriority), _endLastTransaction(0), _currCommand(0), _cpu(iCPU), _previousTransEndTime(0), _comment(0), _busyCycles(0) {
 	_myid=++_id;
 	_cpu->registerTask(this);
 	_commentList.reserve(BLOCK_SIZE);
@@ -65,10 +65,6 @@ TMLTime TMLTask::getEndLastTransaction() const{
 	return _endLastTransaction;
 }
 
-void TMLTask::setEndLastTransaction(TMLTime iEndLastTransaction){
-	_endLastTransaction=iEndLastTransaction;
-}
-
 TMLCommand* TMLTask::getCurrCommand() const{
 	return _currCommand;
 }
@@ -114,19 +110,22 @@ std::string TMLTask::getNextComment(bool iInit, Comment*& oComment){
 }
 
 void TMLTask::addTransaction(TMLTransaction* iTrans){
-	//_endSchedule=_nextTransaction->getEndTime();
 	_transactList.push_back(iTrans);
+	_endLastTransaction=iTrans->getEndTime();
+	_busyCycles+=iTrans->getOperationLength();
 }
 
 TMLTime TMLTask::getNextSignalChange(bool iInit, std::string& oSigChange, bool& oNoMoreTrans){
 	std::ostringstream outp;
 	if (iInit){
-		 _posTrasactList=_transactList.begin();
+		//std::cout << "Init" << std::endl; 
+		_posTrasactList=_transactList.begin();
+		//std::cout << "Init2" << std::endl; 
 		_previousTransEndTime=0;
 		_vcdOutputState=END_TRANS;
 	}
 	if (_posTrasactList == _transactList.end()){
-		if (_transactList.back()->getTerminatedFlag()){
+		if (iInit || _transactList.back()->getTerminatedFlag()){
 			outp << "r" << TERMINATED << " ta" << _myid;
 		}else{
 			outp << "r" << SUSPENDED << " ta" << _myid;
@@ -135,6 +134,7 @@ TMLTime TMLTask::getNextSignalChange(bool iInit, std::string& oSigChange, bool&
 		oNoMoreTrans=true;
 		return _previousTransEndTime;
 	}else{
+		//std::cout << "VCD out trans: " << (*_posTrasactList)->toShortString() << std::endl;
 		TMLTransaction* aCurrTrans=*_posTrasactList;
 		oNoMoreTrans=false;
 		switch (_vcdOutputState){
@@ -172,3 +172,36 @@ TMLTime TMLTask::getNextSignalChange(bool iInit, std::string& oSigChange, bool&
 		}
 	}
 }
+
+/*unsigned int TMLTask::getBusyCycles(){
+	return 0;
+}*/
+
+std::ostream& TMLTask::writeObject(std::ostream& s){
+	unsigned int aCurrCmd;
+	WRITE_STREAM(s,_endLastTransaction);
+	if (_currCommand==0){
+		aCurrCmd=0;
+		WRITE_STREAM(s,aCurrCmd);
+	}else{
+		aCurrCmd=(unsigned int)_currCommand-(unsigned int)this;
+		WRITE_STREAM(s,aCurrCmd);
+		_currCommand->writeObject(s);
+	}
+	return s;
+}
+
+std::istream& TMLTask::readObject(std::istream& s){
+	unsigned int aCurrCmd;
+	READ_STREAM(s, _endLastTransaction);
+	READ_STREAM(s, aCurrCmd);
+	_currCommand=(aCurrCmd==0)?0:(TMLCommand*)(aCurrCmd+((unsigned int)this));
+	if (_currCommand!=0) _currCommand->readObject(s);
+	return s;
+}
+
+void TMLTask::streamBenchmarks(std::ostream& s){
+	s << "*** Task " << _name << " ***\n"; 
+	s << "Execution time: " << _busyCycles << std::endl;
+}
+
diff --git a/simulators/c++2/src_simulator/TMLTask.h b/simulators/c++2/src_simulator/TMLTask.h
index a482e66b1dfb63998c841caf32054728d4c87b9a..ba12590f64a1c47bce791d7cc0a98eb346041d88 100644
--- a/simulators/c++2/src_simulator/TMLTask.h
+++ b/simulators/c++2/src_simulator/TMLTask.h
@@ -44,6 +44,7 @@ Ludovic Apvrille, Renaud Pacalet
 #include <definitions.h>
 #include <TMLTransaction.h>
 #include <TraceableDevice.h>
+#include <Serializable.h>
 
 class TMLCommand;
 class CPU;
@@ -55,7 +56,7 @@ enum vcdTaskVisState
 	START_TRANS
 };
 
-class TMLTask: public TraceableDevice{
+class TMLTask: public TraceableDevice, public Serializable{
 public:	
 	///Constructor
     	/**
@@ -76,11 +77,6 @@ public:
       	\return End of transaction
     	*/
 	TMLTime getEndLastTransaction() const;
-	///Sets the end of the last scheduled transaction
-	/**
-      	\param iEndLastTransaction End of transaction
-    	*/
-	void setEndLastTransaction(TMLTime iEndLastTransaction);
 	///Returns a pointer to the current command of the task
 	/**
       	\return Pointer to the current command
@@ -119,12 +115,15 @@ public:
 	///Returns the next execution comment (pointed to by _posCommentList)
 	/**
       	\param iInit Indicates if the list iterator has to be reset to the beginning of the list
-	\return Pointer to the comment
+	\param oComment This pointer to the comment object is returned to the callee
+	\return String representation of the comment
     	*/ 
 	std::string getNextComment(bool iInit, Comment*& oComment);
 	///Returns the next signal change (for vcd output)
 	/**
       	\param iInit Indicates if the list iterator has to be reset to the beginning of the list
+	\param oSigChange This string representation of the signal change is returned to the callee
+	\param oNoMoreTrans This flag signals to the callee that no more signal changes are available
 	\return String representation of comment
     	*/ 
 	TMLTime getNextSignalChange(bool iInit, std::string& oSigChange, bool& oNoMoreTrans);
@@ -133,6 +132,9 @@ public:
       	\param iTrans Pointer to the transaction
     	*/ 
 	void addTransaction(TMLTransaction* iTrans);
+	virtual std::ostream& writeObject(std::ostream& s);
+	virtual std::istream& readObject(std::istream& s);
+	virtual void streamBenchmarks(std::ostream& s);
 protected:
 	///Name of the task
 	std::string _name;
@@ -160,7 +162,10 @@ protected:
 	TMLTime _previousTransEndTime;
 	///State variable for the VCD output
 	vcdTaskVisState _vcdOutputState;
+	///Array of static comments concerning the control flow of the task
 	std::string* _comment;
+	///Busy cycles since simulation start
+	unsigned long _busyCycles;
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLTransaction.cpp b/simulators/c++2/src_simulator/TMLTransaction.cpp
index bec8d0927bfe280e1d0a33a8f589f4b44fc2611c..52ae406d98e9a693074015cf08ddbcbf3ceea9da 100644
--- a/simulators/c++2/src_simulator/TMLTransaction.cpp
+++ b/simulators/c++2/src_simulator/TMLTransaction.cpp
@@ -45,7 +45,7 @@ Ludovic Apvrille, Renaud Pacalet
 
 Pool<TMLTransaction> TMLTransaction::memPool;
 
-TMLTransaction::TMLTransaction(TMLCommand* iCommand, TMLLength iVirtualStartTime, TMLLength iVirtualLength, TMLTime iRunnableTime, TMLChannel* iChannel):_runnableTime(iRunnableTime), _startTime(0), _virtualStartTime(iVirtualStartTime), _length(0), _virtualLength(iVirtualLength), _command(iCommand), _idlePenalty(0), _taskSwitchingPenalty(0), _branchingPenalty(0), _terminated(false), _channel(iChannel){
+TMLTransaction::TMLTransaction(TMLCommand* iCommand, TMLLength iVirtualLength, TMLTime iRunnableTime, TMLChannel* iChannel):_runnableTime(iRunnableTime), _startTime(0), _length(0), _virtualLength(iVirtualLength), _command(iCommand), _idlePenalty(0), _taskSwitchingPenalty(0), _branchingPenalty(0), _terminated(false), _channel(iChannel) {
 }
 
 TMLTime TMLTransaction::getRunnableTime() const{
@@ -58,7 +58,7 @@ void TMLTransaction::setRunnableTime(TMLTime iRunnableTime){
 	//	std::cout << "ERROR: runnable time set twice\n";
 	//}else{
 		//_runnableTimeSet=true;
-	_command->getTask()->getCPU()->registerTransaction(this);
+	_command->getTask()->getCPU()->registerTransaction(this,0);
 	//}
 }
 
@@ -74,10 +74,6 @@ void TMLTransaction::setStartTime(TMLTime iStartTime){
 	_startTime=iStartTime;
 }
 
-TMLLength TMLTransaction::getVirtualStartTime() const{
-	return _virtualStartTime;
-}
-
 TMLTime TMLTransaction::getOperationLength() const{
 	return _length;
 }
@@ -146,13 +142,13 @@ void TMLTransaction::setTerminatedFlag(){
 
 std::string TMLTransaction::toString(){
 	std::ostringstream outp;	
-	outp << _command->toString() << std::endl << "Transaction runnable:" << _runnableTime << " len:" << _length << " start:" << _startTime << " vLength:" << _virtualLength << " vStart:" << _virtualStartTime;
+	outp << _command->toString() << std::endl << "Transaction runnable:" << _runnableTime << " len:" << _length << " start:" << _startTime << " vLength:" << _virtualLength;
 	return outp.str();
 }
 
 std::string TMLTransaction::toShortString(){
 	std::ostringstream outp;	
-	outp << _command->toShortString() << " t:" << _startTime << " l:" << _length << " (vl:"<<  _virtualLength << " vs:" << _virtualStartTime << ")";
+	outp << _command->toShortString() << " t:" << _startTime << " l:" << _length << " (vl:"<<  _virtualLength << ")";
 	return outp.str();
 }
 
diff --git a/simulators/c++2/src_simulator/TMLTransaction.h b/simulators/c++2/src_simulator/TMLTransaction.h
index 0d0c67574c1628280b8b8ef36ea2556c70773076..5a6548b6e5640e2a9f3c34afbcb2b68e33e2d643 100644
--- a/simulators/c++2/src_simulator/TMLTransaction.h
+++ b/simulators/c++2/src_simulator/TMLTransaction.h
@@ -51,11 +51,11 @@ public:
 	///Constructor
     	/**
       	\param iCommand Pointer to the command the transaction belongs to
-	\param iVirtualStartTime Virtual start time of the transaction
 	\param iVirtualLength Virtual length of the transaction
 	\param iRunnableTime Time when the transaction became runnable
+	\param iChannel Channel on which data was conveyed
     	*/
-	TMLTransaction(TMLCommand* iCommand,TMLLength iVirtualStartTime, TMLLength iVirtualLength, TMLTime iRunnableTime, TMLChannel* iChannel=0);
+	TMLTransaction(TMLCommand* iCommand, TMLLength iVirtualLength, TMLTime iRunnableTime, TMLChannel* iChannel=0);
 	///Returns the time when the transaction became runnable
 	/**
       	\return Runnable time
@@ -81,11 +81,6 @@ public:
       	\param iStartTime Start time
     	*/
 	void setStartTime(TMLTime iStartTime);
-	///Returns the virtual start time of the transaction (number of execution units already carried out by previous transactions)
-	/**
-      	\return Virtual start time
-    	*/
-	TMLLength getVirtualStartTime() const;
 	///Returns the length of the operational part of the transaction
 	/**
       	\return Length of the operational part
@@ -170,28 +165,24 @@ public:
 	\return Short string representation
 	*/
 	std::string toShortString();
+	///Set channel on which data was conveyed
+	/**
+	\param iChannel Pointer to a channel
+	*/
 	void setChannel(TMLChannel* iChannel);
+	///Get channel on which data was conveyed
+	/**
+	\return Pointer to channel
+	*/
 	TMLChannel* getChannel();
 	
-	static void * operator new(unsigned int size);//{
-		//return memPool.pmalloc(size);
-	//}
-
-	static void operator delete(void *p, unsigned int size);//{
-		//memPool.pfree(p, size);
-	//}
-	//union{
-	//	TMLChannel* _channel;		//TMLSelectCommand
-	//	TMLLength _channelContent	//TMLNotifiedCommand
-	//	unsigned int randomValue	//random command
-	//}
+	static void * operator new(unsigned int size);
+	static void operator delete(void *p, unsigned int size);
 protected:
 	///Time when the transaction became runnable
 	TMLTime _runnableTime;
 	///Start time of the transaction
 	TMLTime _startTime;
-	///Virtual start time of the transaction (number of execution units already carried out by previous transactions)
-	TMLLength _virtualStartTime;
 	///Length of the transaction
 	TMLTime _length;
 	///Virtual length of the transaction (number of execution units of the transaction)
@@ -206,8 +197,9 @@ protected:
 	unsigned int _branchingPenalty;
 	///Task terminated flag
 	bool _terminated;
-	//bool _runnableTimeSet;
+	///Channel on which data was conveyed
 	TMLChannel* _channel;
+	///Memory pool for transactions
 	static Pool<TMLTransaction> memPool;
 };
 
diff --git a/simulators/c++2/src_simulator/TMLWaitCommand.cpp b/simulators/c++2/src_simulator/TMLWaitCommand.cpp
index 1bd448bc0c5a76c26a13f3ba8a1f233031bbde5c..485e870eb8a73e0a6923d8113226cd00c135ca66 100644
--- a/simulators/c++2/src_simulator/TMLWaitCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLWaitCommand.cpp
@@ -50,21 +50,18 @@ TMLWaitCommand::TMLWaitCommand(TMLTask* iTask, TMLEventChannel* iChannel, Parame
 void TMLWaitCommand::execute(){
 	_channel->read();
 	_progress+=_currTransaction->getVirtualLength();
-	_task->setEndLastTransaction(_currTransaction->getEndTime());
-	//_currTransaction=0;
-#if defined BUS_ENABLED && defined EVENTS_MAPPED_ON_BUS
-	Bus* bus=_channel->getBus();
-	if (bus!=0) bus->addTransaction();
-#endif
-	if (!prepare()) _currTransaction->setTerminatedFlag();
-	if (_progress==0) _currTransaction=0;
+	//_task->setEndLastTransaction(_currTransaction->getEndTime());
+	_task->addTransaction(_currTransaction);
+	TMLCommand* aNextCommand = prepare();
+	if (aNextCommand==0) _currTransaction->setTerminatedFlag();
+	if (_progress==0 && aNextCommand!=this) _currTransaction=0;
 }
 
-bool TMLWaitCommand::prepareNextTransaction(){
-	//_currTransaction=new TMLTransaction(this, _progress,(*_pLength)-_progress, _task->getEndLastTransaction(), _channel);
-	_currTransaction=new TMLTransaction(this, _progress,_length-_progress, _task->getEndLastTransaction(), _channel);
+TMLCommand* TMLWaitCommand::prepareNextTransaction(){
+	//std::cout << "wait command length: " << _length  << "  progress: " << _progress << std::endl; 
+	_currTransaction=new TMLTransaction(this, _length-_progress, _task->getEndLastTransaction(), _channel);
 	_channel->testRead(_currTransaction);
-	return true;
+	return this;
 }
 
 TMLTask* TMLWaitCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLWaitCommand.h b/simulators/c++2/src_simulator/TMLWaitCommand.h
index 8a0994b0a5da835a2e30498cc5cb9c90aaebc762..37af22c526884145b166e6acb196cae38216adf8 100644
--- a/simulators/c++2/src_simulator/TMLWaitCommand.h
+++ b/simulators/c++2/src_simulator/TMLWaitCommand.h
@@ -65,7 +65,7 @@ public:
 protected:
 	///Channel on which the event is conveyed
 	TMLEventChannel* _channel;
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLWriteCommand.cpp b/simulators/c++2/src_simulator/TMLWriteCommand.cpp
index 2ab6bc770065462d0734c8c6761e42b1334dddcc..758e74f3b55a9770661998273cc8f1327bce32c5 100644
--- a/simulators/c++2/src_simulator/TMLWriteCommand.cpp
+++ b/simulators/c++2/src_simulator/TMLWriteCommand.cpp
@@ -46,34 +46,37 @@ Ludovic Apvrille, Renaud Pacalet
 
 TMLWriteCommand::TMLWriteCommand(TMLTask* iTask, LengthFuncPointer iLengthFunc, TMLChannel* iChannel): TMLCommand(iTask,1,0), _lengthFunc(iLengthFunc), _channel(iChannel){
 }
-//TMLWriteCommand::TMLWriteCommand(TMLTask* iTask, const TMLLength& iLength, TMLChannel* iChannel):TMLCommand(iTask, iLength,0),_channel(iChannel){
-//}
-
-//TMLWriteCommand::TMLWriteCommand(TMLTask* iTask, TMLLength& iLength, TMLChannel* iChannel):TMLCommand(iTask, iLength,0),_channel(iChannel){
-//}
 
 void TMLWriteCommand::execute(){
 	_channel->write();
+	//std::cout << _currTransaction->getVirtualLength() << " samples written\n";
 	_progress+=_currTransaction->getVirtualLength();
-	_task->setEndLastTransaction(_currTransaction->getEndTime());
-	//_currTransaction=0;
-#ifdef BUS_ENABLED
-	Bus* bus=_channel->getBus();
-	if (bus!=0) bus->addTransaction();
-#endif
-	if (!prepare()) _currTransaction->setTerminatedFlag();
-	if (_progress==0) _currTransaction=0;
+	//_task->setEndLastTransaction(_currTransaction->getEndTime());
+	_task->addTransaction(_currTransaction);
+	TMLCommand* aNextCommand = prepare();
+	if (aNextCommand==0) _currTransaction->setTerminatedFlag();
+	if (_progress==0 && aNextCommand!=this) _currTransaction=0;
 }
 
-bool TMLWriteCommand::prepareNextTransaction(){
+TMLCommand* TMLWriteCommand::prepareNextTransaction(){
 	//std::cout << "WriteCommand prepare" << std::endl;
-	if (_progress==0) _length = (_task->*_lengthFunc)();
-	//_currTransaction=new TMLTransaction(this, _progress,(*_pLength)-_progress, _task->getEndLastTransaction(), _channel);
-	_currTransaction=new TMLTransaction(this, _progress,_length-_progress, _task->getEndLastTransaction(), _channel);
+	//if (_progress==0) _length = (_task->*_lengthFunc)();
+
+	//new test code
+	if (_progress==0){
+		 _length = (_task->*_lengthFunc)();
+		if (_length==0){
+			TMLCommand* aNextCommand=getNextCommand();
+			_task->setCurrCommand(aNextCommand);
+			if (aNextCommand!=0) return aNextCommand->prepare();
+		}
+	}
+
+	_currTransaction=new TMLTransaction(this, _length-_progress, _task->getEndLastTransaction(), _channel);
 	//std::cout << "before test write" << std::endl;
 	_channel->testWrite(_currTransaction);
 	//std::cout << "WriteCommand end prepare" << std::endl;
-	return true;
+	return this;
 }
 
 TMLTask* TMLWriteCommand::getDependentTask() const{
diff --git a/simulators/c++2/src_simulator/TMLWriteCommand.h b/simulators/c++2/src_simulator/TMLWriteCommand.h
index b3c11ffd8d7971a44a8ab921c78b07734cebb98f..075ab078a828233a91545ee491d055acaa8fe28d 100644
--- a/simulators/c++2/src_simulator/TMLWriteCommand.h
+++ b/simulators/c++2/src_simulator/TMLWriteCommand.h
@@ -52,18 +52,10 @@ public:
 	///Constructor
     	/**
       	\param iTask Pointer to the task the command belongs to
-	\param iLength Constant virtual length of the command
+	\param iLengthFunc Pointer to the function returning the length of the command
 	\param iChannel Pointer to the channel to which is written
 	*/
-	//TMLWriteCommand(TMLTask* iTask, const TMLLength& iLength,TMLChannel* iChannel);
 	TMLWriteCommand(TMLTask* iTask, LengthFuncPointer iLengthFunc, TMLChannel* iChannel);
-	/*///Constructor
-    	/**
-      	\param iTask Pointer to the task the command belongs to
-	\param iLength Virtual length of the command
-	\param iChannel Pointer to the channel to which is written
-	*/
-	//TMLWriteCommand(TMLTask* iTask, TMLLength& iLength,TMLChannel* iChannel);
 	void execute();
 	TMLTask* getDependentTask() const;
 	TMLChannel* getChannel() const;
@@ -71,10 +63,11 @@ public:
 	std::string toShortString();
 	std::string getCommandStr();
 protected:
+	///Pointer to the function returning the length of the command
 	LengthFuncPointer _lengthFunc;
 	///Channel to which is written
 	TMLChannel* _channel;
-	bool prepareNextTransaction();
+	TMLCommand* prepareNextTransaction();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLbrbwChannel.cpp b/simulators/c++2/src_simulator/TMLbrbwChannel.cpp
index dd3d075d3b868f913a88d4073ed16452d8515df9..ed3206a8e4cbd1a86365483155821c503db42e30 100644
--- a/simulators/c++2/src_simulator/TMLbrbwChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLbrbwChannel.cpp
@@ -40,16 +40,17 @@ Ludovic Apvrille, Renaud Pacalet
 
 #include <TMLbrbwChannel.h>
 #include <TMLTransaction.h>
+#include <TMLCommand.h>
 
-TMLbrbwChannel::TMLbrbwChannel(std::string iName, Bus* iBus, TMLLength iLength,TMLLength iContent):TMLStateChannel(iName,iBus,iContent),_length(iLength){
-//,_content(iContent),_writeTrans(0),_readTrans(0),_nbToWrite(0),_nbToRead(0){
+TMLbrbwChannel::TMLbrbwChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iLength,TMLLength iContent):TMLStateChannel(iName, iNumberOfHops, iBuses, iSlaves, iContent),_length(iLength){
 }
 
 void TMLbrbwChannel::testWrite(TMLTransaction* iTrans){
 	_nbToWrite=iTrans->getVirtualLength();
 	_writeTrans=iTrans;
+	//std::cout << "testWrite called by " << _writeTrans->getCommand()->toShortString() << std::endl;
 	setTransactionLength();
-	//std::cout << "TestWrite " << iLength<< " writeTrans: " << _writeTrans<< " transLen: "<< _writeTrans->getVirtualLength()<< std::endl;
+	//std::cout << "TestWrite " << iLength<< " writeTrans: " << _writeTrans<< " transLen: "<< _writeTrans->getVirtualLength()<< std::endl; 
 }
 
 void TMLbrbwChannel::testRead(TMLTransaction* iTrans){
@@ -80,37 +81,34 @@ bool TMLbrbwChannel::read(){
 	}
 }
 
-//void TMLbrbwChannel::cancelReadTransaction(){
-//	_nbToRead=0;
-//	_readTrans=0;
-//	setTransactionLength();
-//}
-
 void TMLbrbwChannel::setTransactionLength(){
 	if (_writeTrans!=0){	
 		if (_nbToRead==0){
-			_writeTrans->setVirtualLength(min(_length-_content,_nbToWrite,_burstSize));
+			_writeTrans->setVirtualLength(min(_length-_content,_nbToWrite));
 		}else{
 			if (_nbToRead<=_content){
 				//read could be executed right away			
-				_writeTrans->setVirtualLength(min(_length-_content,_nbToWrite,_burstSize));
+				_writeTrans->setVirtualLength(min(_length-_content,_nbToWrite));
 			}else{
 				//read could wake up because of write
-				_writeTrans->setVirtualLength(min(_length-_content,_nbToRead-_content,_nbToWrite,_burstSize));
+				_writeTrans->setVirtualLength(min(_length-_content,_nbToRead-_content,_nbToWrite));
 			}
 		}
 	}
 	if (_readTrans!=0){
 		if (_nbToWrite==0){
-			_readTrans->setVirtualLength(min(_content,_nbToRead,_burstSize));
+			_readTrans->setVirtualLength(min(_content,_nbToRead));
+			//std::cout << _name << ": set read trans len, no write trans, len = " << _readTrans->getVirtualLength() << std::endl;
 		}else{
 			if (_nbToWrite<=_length-_content){
 				//write could be executed right away
-				_readTrans->setVirtualLength(min(_content,_nbToRead,_burstSize));
+				_readTrans->setVirtualLength(min(_content,_nbToRead));
 			}else{
 				//write could wakeup because of read
-				_readTrans->setVirtualLength(min(_content,_nbToWrite-(_length-_content),_nbToRead,_burstSize));
+				_readTrans->setVirtualLength(min(_content,_nbToWrite-(_length-_content),_nbToRead));
 			}
+			//std::cout << _name << ": set read trans len, with write trans, len = " << _readTrans->getVirtualLength() << std::endl;
+
 		}
 	}
 }
diff --git a/simulators/c++2/src_simulator/TMLbrbwChannel.h b/simulators/c++2/src_simulator/TMLbrbwChannel.h
index 226467d4c08fd7761b165018f3698f1a61052934..dfe96f325c1662731816d7d1aa96c4f5e9b3337d 100644
--- a/simulators/c++2/src_simulator/TMLbrbwChannel.h
+++ b/simulators/c++2/src_simulator/TMLbrbwChannel.h
@@ -48,22 +48,22 @@ class TMLCommand;
 class Bus;
 
 ///This class models a blocking read blocking write channel (finite blocking FIFO).
-//class TMLbrbwChannel:public TMLChannel{
 class TMLbrbwChannel:public TMLStateChannel{
 public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
 	\param iLength Length of the channel
 	\param iContent Initial content of the channel
     	*/
-	TMLbrbwChannel(std::string iName,Bus* iBus,TMLLength iLength,TMLLength iContent);
+	TMLbrbwChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iLength, TMLLength iContent);
 	void testWrite(TMLTransaction* iTrans);
 	void testRead(TMLTransaction* iTrans);
 	void write();
 	bool read();
-	//void cancelReadTransaction();
 	TMLTask* getBlockedReadTask() const;
 	TMLTask* getBlockedWriteTask() const;
 	std::string toString();
@@ -72,16 +72,6 @@ protected:
 	void setTransactionLength();
 	///Length of the channel
 	TMLLength _length;
-	///Content of the channel
-	//TMLLength _content;
-	///Pointer to the transaction which attempts to write in the channel
-	//TMLTransaction* _writeTrans;
-	///Pointer to the transaction which attempts to read the channel
-	//TMLTransaction* _readTrans;
-	///Number of samples the write transaction attempts to write
-	//TMLLength _nbToWrite;
-	///Number of samples the read transaction attempts to read
-	//TMLLength _nbToRead;
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLbrnbwChannel.cpp b/simulators/c++2/src_simulator/TMLbrnbwChannel.cpp
index a7b008f666f8f7510dab3682e6ff95d03e7c7536..bead3e95898df947693e1a4c272945b196345bd8 100644
--- a/simulators/c++2/src_simulator/TMLbrnbwChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLbrnbwChannel.cpp
@@ -41,8 +41,7 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLbrnbwChannel.h>
 #include <TMLTransaction.h>
 
-//TMLbrnbwChannel::TMLbrnbwChannel(std::string iName,Bus *iBus,TMLLength iContent):TMLChannel(iName,iBus),_content(iContent),_writeTrans(0),_readTrans(0),_nbToWrite(0),_nbToRead(0){
-TMLbrnbwChannel::TMLbrnbwChannel(std::string iName,Bus *iBus,TMLLength iContent):TMLStateChannel(iName,iBus,iContent){
+TMLbrnbwChannel::TMLbrnbwChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iContent):TMLStateChannel(iName, iNumberOfHops, iBuses, iSlaves, iContent){
 }
 
 void TMLbrnbwChannel::testWrite(TMLTransaction* iTrans){
@@ -78,28 +77,26 @@ bool TMLbrnbwChannel::read(){
 	}
 }
 
-//void TMLbrnbwChannel::cancelReadTransaction(){
-//	_nbToRead=0;
-//	_readTrans=0;
-//	setTransactionLength();
-//}
-
 void TMLbrnbwChannel::setTransactionLength(){
 	if (_writeTrans!=0){	
 		if (_nbToRead==0){
-			_writeTrans->setVirtualLength(min(_nbToWrite,_burstSize));
+			//_writeTrans->setVirtualLength(min(_nbToWrite,_burstSize));
+			_writeTrans->setVirtualLength(_nbToWrite);
 		}else{
 			if (_nbToRead<=_content){
 				//read could be executed right away			
-				_writeTrans->setVirtualLength(min(_nbToWrite,_burstSize));
+				//_writeTrans->setVirtualLength(min(_nbToWrite,_burstSize));
+				_writeTrans->setVirtualLength(_nbToWrite);
 			}else{
 				//read could wake up because of write
-				_writeTrans->setVirtualLength(min(_nbToRead-_content,_nbToWrite,_burstSize));
+				//_writeTrans->setVirtualLength(min(_nbToRead-_content,_nbToWrite,_burstSize));
+				_writeTrans->setVirtualLength(min(_nbToRead-_content,_nbToWrite));
 			}
 		}
 	}
 	if (_readTrans!=0){
-		_readTrans->setVirtualLength(min(_content,_nbToRead,_burstSize));
+		//_readTrans->setVirtualLength(min(_content,_nbToRead,_burstSize));
+		_readTrans->setVirtualLength(min(_content,_nbToRead));
 	}
 }
 
diff --git a/simulators/c++2/src_simulator/TMLbrnbwChannel.h b/simulators/c++2/src_simulator/TMLbrnbwChannel.h
index 57dd09346d319715b290b8038ff343f04005736c..af77b49cdc4e3109d330f4dee2d0915b20124e11 100644
--- a/simulators/c++2/src_simulator/TMLbrnbwChannel.h
+++ b/simulators/c++2/src_simulator/TMLbrnbwChannel.h
@@ -53,31 +53,22 @@ public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
 	\param iContent Initial content of the channel
     	*/
-	TMLbrnbwChannel(std::string iName,Bus *iBus,TMLLength iContent);
+	TMLbrnbwChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves, TMLLength iContent);
 	void testWrite(TMLTransaction* iTrans);
 	void testRead(TMLTransaction* iTrans);
 	void write();
 	bool read();
-	//void cancelReadTransaction();
 	TMLTask* getBlockedReadTask() const;
 	TMLTask* getBlockedWriteTask() const;
 	std::string toString();
 protected:
 	///Determines the virtual length of read and write transactions based on the state of the channel
 	void setTransactionLength();
-	///Content of the channel
-	//TMLLength _content;
-	///Pointer to the transaction which attempts to write in the channel
-	//TMLTransaction* _writeTrans;
-	///Pointer to the transaction which attempts to read the channel
-	//TMLTransaction* _readTrans;
-	///Number of samples the write transaction attempts to write
-	//TMLLength _nbToWrite;
-	///Number of samples the read transaction attempts to read
-	//TMLLength _nbToRead;
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TMLnbrnbwChannel.cpp b/simulators/c++2/src_simulator/TMLnbrnbwChannel.cpp
index 4d8ccfbc625bde34d7f13d9f52c5ce9e4005b19f..69e3ee24bc03b0d01a0cd6d7e2b9b41d5f323b52 100644
--- a/simulators/c++2/src_simulator/TMLnbrnbwChannel.cpp
+++ b/simulators/c++2/src_simulator/TMLnbrnbwChannel.cpp
@@ -41,27 +41,28 @@ Ludovic Apvrille, Renaud Pacalet
 #include <TMLnbrnbwChannel.h>
 #include <TMLTransaction.h>
 
-TMLnbrnbwChannel::TMLnbrnbwChannel(std::string iName,Bus *iBus):TMLChannel(iName,iBus){
+TMLnbrnbwChannel::TMLnbrnbwChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves): TMLChannel(iName, iNumberOfHops, iBuses, iSlaves){
 }
 
 void TMLnbrnbwChannel::testWrite(TMLTransaction* iTrans){
-	iTrans->setVirtualLength(min(iTrans->getVirtualLength(),_burstSize));
+	_writeTrans=iTrans;
+	iTrans->setVirtualLength(iTrans->getVirtualLength());
 }
 
 void TMLnbrnbwChannel::testRead(TMLTransaction* iTrans){
-	iTrans->setVirtualLength(min(iTrans->getVirtualLength(),_burstSize));
+	_readTrans=iTrans;
+	iTrans->setVirtualLength(iTrans->getVirtualLength());
 }
 
 void TMLnbrnbwChannel::write(){
+	_writeTrans=0;
 }
 
 bool TMLnbrnbwChannel::read(){
+	_readTrans=0;
 	return true;
 }
 
-//void TMLnbrnbwChannel::cancelReadTransaction(){
-//}
-
 TMLTask* TMLnbrnbwChannel::getBlockedReadTask() const{
 	return 0;
 }
diff --git a/simulators/c++2/src_simulator/TMLnbrnbwChannel.h b/simulators/c++2/src_simulator/TMLnbrnbwChannel.h
index 688e6bf04c7aebbc59c745bc40470ad4402bcaf8..aa34c0919da357b67a13ba1ee52b6749fcbb8733 100644
--- a/simulators/c++2/src_simulator/TMLnbrnbwChannel.h
+++ b/simulators/c++2/src_simulator/TMLnbrnbwChannel.h
@@ -47,26 +47,25 @@ Ludovic Apvrille, Renaud Pacalet
 class TMLCommand;
 class Bus;
 
-///This class models a non blocking read non blocking write channel (memory).
+///This class models a non blocking read non blocking write channel.
 class TMLnbrnbwChannel:public TMLChannel{
 public:
 	///Constructor
     	/**
       	\param iName Name of the channel
-	\param iBus Pointer to the bus on which the channel is mapped
+	\param iNumberOfHops Number of buses on which the channel is mapped
+	\param iBuses Pointer to the buses on which the channel is mapped
+	\param iSlaves Pointer to the slaves on which the channel is mapped
     	*/
-	TMLnbrnbwChannel(std::string iName,Bus* iBus);
+	TMLnbrnbwChannel(std::string iName, unsigned int iNumberOfHops, SchedulableCommDevice** iBuses, Slave** iSlaves);
 	void testWrite(TMLTransaction* iCommand);
 	void testRead(TMLTransaction* iCommand);
 	void write();
 	bool read();
-	//void cancelReadTransaction();
 	TMLTask* getBlockedReadTask() const;
 	TMLTask* getBlockedWriteTask() const;
 	std::string toString();
 protected:
-	////Determines the virtual length of read and write transactions based on the state of the channel
-	//void setTransactionLength();
 };
 
 #endif
diff --git a/simulators/c++2/src_simulator/TraceableDevice.h b/simulators/c++2/src_simulator/TraceableDevice.h
index 9ca06fc3c0f5f35c225e58f57c3164a140f3a48d..e7a30bf5638deec26eca7b8338312c2e7a2e45a7 100644
--- a/simulators/c++2/src_simulator/TraceableDevice.h
+++ b/simulators/c++2/src_simulator/TraceableDevice.h
@@ -51,7 +51,7 @@ public:
 	\return Detailed string representation
 	*/
 	virtual std::string toString()=0;
-	////Returns a short string representation of the device
+	///Returns a short string representation of the device
 	/**
 	\return Short string representation
 	*/
@@ -64,6 +64,12 @@ public:
 	\return Point in time when the signal changes
     	*/ 
 	virtual TMLTime getNextSignalChange(bool iInit, std::string& oSigChange, bool& oNoMoreTrans)=0;
+	///Writes benchmarking data to a given stream
+	/**
+      	\param s Reference to an output stream
+	\param iSimulationTime Duration of the simulation in time units
+	*/
+	virtual void streamBenchmarks(std::ostream& s)=0;
 	///Destructor
 	virtual ~TraceableDevice(){}
 };
diff --git a/simulators/c++2/src_simulator/definitions.cpp b/simulators/c++2/src_simulator/definitions.cpp
index 4973cef3bf3ce5112e02a92173b8c7bf3e8b185f..1e37ae3f34232237af116b3c1e0f28de8ddd60d8 100644
--- a/simulators/c++2/src_simulator/definitions.cpp
+++ b/simulators/c++2/src_simulator/definitions.cpp
@@ -1,3 +1,43 @@
+/*Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Daniel Knorreck,
+Ludovic Apvrille, Renaud Pacalet
+ *
+ * ludovic.apvrille AT telecom-paristech.fr
+ *
+ * This software is a computer program whose purpose is to allow the
+ * edition of TURTLE analysis, design and deployment diagrams, to
+ * allow the generation of RT-LOTOS or Java code from this diagram,
+ * and at last to allow the analysis of formal validation traces
+ * obtained from external tools, e.g. RTL from LAAS-CNRS and CADP
+ * from INRIA Rhone-Alpes.
+ *
+ * This software is governed by the CeCILL  license under French law and
+ * abiding by the rules of distribution of free software.  You can  use,
+ * modify and/ or redistribute the software under the terms of the CeCILL
+ * license as circulated by CEA, CNRS and INRIA at the following URL
+ * "http://www.cecill.info".
+ *
+ * As a counterpart to the access to the source code and  rights to copy,
+ * modify and redistribute granted by the license, users are provided only
+ * with a limited warranty  and the software's author,  the holder of the
+ * economic rights,  and the successive licensors  have only  limited
+ * liability.
+ *
+ * In this respect, the user's attention is drawn to the risks associated
+ * with loading,  using,  modifying and/or developing or reproducing the
+ * software by the user in light of its specific status of free software,
+ * that may mean  that it is complicated to manipulate,  and  that  also
+ * therefore means  that it is reserved for developers  and  experienced
+ * professionals having in-depth computer knowledge. Users are therefore
+ * encouraged to load and test the software's suitability as regards their
+ * requirements in conditions enabling the security of their systems and/or
+ * data to be ensured and,  more generally, to use and operate it in the
+ * same conditions as regards security.
+ *
+ * The fact that you are presently reading this means that you have had
+ * knowledge of the CeCILL license and that you accept its terms.
+ *
+ */
+
 #include <definitions.h>
 #include <TMLTransaction.h>
 #include <TMLCommand.h>
@@ -13,7 +53,7 @@ int myrand(int n1, int n2){
 	}
 	n2++;
 	int r = (n1 + (int)(((float)(n2 - n1))*rand()/(RAND_MAX + 1.0)));
-	std::cout << "random number: " << r << std::endl;
+	//std::cout << "random number: " << r << std::endl;
 	//return (n1 + (int)(((float)(n2 - n1))*rand()/(RAND_MAX + 1.0)));
 	return r;
 	//return n1 + rand()/(RAND_MAX/(n2-n1+1));
@@ -38,46 +78,9 @@ bool greaterStartTime::operator()(TMLTransaction const* p1, TMLTransaction const
 	return p1->getStartTime() > p2->getStartTime();
 }
 
-/*template<class T> Pool<T>::Pool():_headFreeList(0){}
-
-template<class T> void* Pool<T>::pmalloc(unsigned int n){
-	if (n != sizeof(T)) return ::operator new(n);
-	T* aHead = _headFreeList;
-        if (aHead){
-		_headFreeList = *(reinterpret_cast<T**>(aHead));
-		//_headFreeList = (T*)((void*)(*aHead));
-        }else{
-		T** aAdr;
-		T* newBlock = static_cast<T*>(::operator new(BLOCK_SIZE * sizeof(T)));
-		for (int i = 1; i < BLOCK_SIZE-1; ++i){
-			aAdr = reinterpret_cast<T**>(&newBlock[i]);
-			*aAdr = &newBlock[i+1];
-			//newBlock[i] = &newBlock[i+1];
-		}
-		aAdr = reinterpret_cast<T**>(&newBlock[BLOCK_SIZE-1]);
-		*aAdr = 0;
-		//newBlock[BLOCK_SIZE-1].next = 0;
-		aHead = newBlock;
-		_headFreeList = &newBlock[1];
-		//_chunkList.push_back(p);
-        }
-	return aHead;
-}
-
-template<class T> void Pool<T>::pfree(void *p, unsigned int n){
-	if (p == 0) return;
-	if (n != sizeof(T)){
-		::operator delete(p);
-		return;
+void replaceAll(std::string& ioHTML, std::string iSearch, std::string iReplace){
+	unsigned int aPos=0;
+	while (aPos< ioHTML.length() && (aPos= ioHTML.find(iSearch,aPos))!=std::string::npos){
+		ioHTML.replace(aPos++,iSearch.length(),iReplace);
 	}
-	T* aDelObj = static_cast<T*>(p);
-	//delObj->next = _headFreeList;
-	T** aAdr = reinterpret_cast<T**>(aDelObj);
-	*aAdr = _headFreeList;
-	_headFreeList = aDelObj;
-}
-
-template<class T> Pool<T>::~Pool(){
-	//std::list<T*>::iterator i;
-	//for(i=_chunkList.begin(); i != _chunkList.end(); ++i) ::operator delete [] *i;
-}*/
+} 
diff --git a/simulators/c++2/src_simulator/definitions.h b/simulators/c++2/src_simulator/definitions.h
index 861d3e30bd483feefc6b43b05d8d795dc6461378..bd9c615e2553a539418d30f32044b2e0c9ca7787 100644
--- a/simulators/c++2/src_simulator/definitions.h
+++ b/simulators/c++2/src_simulator/definitions.h
@@ -56,18 +56,24 @@ Ludovic Apvrille, Renaud Pacalet
 #include <vector>
 #include <sys/time.h>
 
-#include <SchedulableDevice.h>
+#define WRITE_STREAM(s,v) s.write((char*) &v,sizeof(v))
+#define READ_STREAM(s,v) s.read((char*) &v,sizeof(v))
 
 using std::min;
 using std::max;
 
+#undef DEBUG_KERNEL
+#undef DEBUG_CPU
+#undef DEBUG_BUS
+
 #define BUS_ENABLED
-#define EVENTS_MAPPED_ON_BUS
+//#define EVENTS_MAPPED_ON_BUS
 #define WAIT_SEND_VLEN 1
 #define CPURRPB CPUPB
 #define CLOCK_INC 20
-#define BLOCK_SIZE 512
+#define BLOCK_SIZE 100000
 #define ADD_COMMENTS
+#define NO_EVENTS_TO_LOAD 10
 
 //Task VCD output
 #define TERMINATED 3
@@ -79,9 +85,19 @@ class TMLTask;
 class TMLTransaction;
 class TMLCommand;
 class CPU;
-class Bus;
+class SchedulableCommDevice;
+class SchedulableDevice;
 template <typename T> class Parameter;
 class TraceableDevice;
+class Master;
+
+enum vcdBusVisState
+    {
+	END_IDLE_BUS,
+	END_READ_BUS,
+	END_WRITE_BUS,
+	INIT_BUS
+};
 
 ///Datatype used for time measurements
 typedef unsigned int TMLTime;
@@ -93,12 +109,18 @@ typedef std::list<TMLTask*> TaskList;
 typedef std::vector<TMLTransaction*> TransactionList;
 ///Datatype holding pointer to CPUs, used by TMLMain and simulation kernel
 typedef std::list<CPU*> CPUList;
+///Datatype holding pointer to CPUs and Bridges, used by simulation kernel for scheduling
+typedef std::list<SchedulableDevice*> SchedulingList;
 ///Datatype holding references to buses, used by TMLMain and simulation kernel
-typedef std::list<Bus*> BusList;
-///Datatype used by the Bus to store pointers to all connected master devices
-typedef std::list<CPU*> MasterDeviceList;
+typedef std::list<SchedulableCommDevice*> BusList;
+/////Datatype used by the Bus to store pointers to all connected master devices
+//typedef std::list<Master*> MasterDeviceList;
 ///Datatype establishing an association between a CPU and a transaction, used by the bus
-typedef std::map<CPU*, TMLTransaction*> BusTransHashTab;
+typedef std::map<Master*, TMLTransaction*> BusTransHashTab;
+/////Datatype establishing an association between a transaction and its priority, used by buses
+//typedef std::multimap<unsigned int, Master*> BusMasterPrioTab;
+///Datatype establishing an association between a bus and a priority, used by Masters
+typedef std::map<SchedulableCommDevice*, unsigned int> MasterPriorityHashTab;
 ///Datatype for event parameters
 typedef int ParamType;
 ///Datatype used in EventChannels to store parameters of events
@@ -106,7 +128,6 @@ typedef std::deque<Parameter<ParamType>*> ParamQueue;
 ///Type of member function pointer used to indicate a function encapsulating a condition (for TMLChoiceCommand)
 typedef unsigned int (TMLTask::*CondFuncPointer) ();
 ///Type of member function pointer used to indicate a function encapsulating an action (for TMLActionCommand)
-//typedef void (TMLTask::*ActionFuncPointer) ();
 typedef unsigned int (TMLTask::*ActionFuncPointer) ();
 ///Type of member function pointer used to indicate a function encapsulating a condition (for TMLChoiceCommand)
 typedef unsigned int (TMLTask::*LengthFuncPointer) ();
@@ -114,81 +135,110 @@ typedef unsigned int (TMLTask::*LengthFuncPointer) ();
 typedef std::list<TraceableDevice*> TraceableDeviceList;
 
 
+///Generic Memory pool class
 template <typename T>
 class Pool {
 public:
+	///Constructor
 	Pool():_headFreeList(0){}
 
-void* pmalloc(unsigned int n){
-	if (n != sizeof(T)){
-		std::cout << "FAEAEAELA!";
-		return ::operator new(n);
-	}
-	T* aHead = _headFreeList;
-        if (aHead){
-		_headFreeList = *(reinterpret_cast<T**>(aHead));
-		//_headFreeList = (T*)((void*)(*aHead));
-        }else{
-		T** aAdr;
-		T* newBlock = static_cast<T*>(::operator new(BLOCK_SIZE * sizeof(T)));
-		for (int i = 1; i < BLOCK_SIZE-1; ++i){
-			aAdr = reinterpret_cast<T**>(&newBlock[i]);
-			*aAdr = &newBlock[i+1];
-			//newBlock[i] = &newBlock[i+1];
+	///Allocation method
+	/**
+	\param n Size of memory chunk to be allocated
+	\return Pointer to the allocated chunk of memory
+	*/
+	void* pmalloc(unsigned int n){
+		if (n != sizeof(T)){
+			std::cout << "FAEAEAELA!";
+			return ::operator new(n);
 		}
-		aAdr = reinterpret_cast<T**>(&newBlock[BLOCK_SIZE-1]);
-		*aAdr = 0;
-		//newBlock[BLOCK_SIZE-1].next = 0;
-		aHead = newBlock;
-		_headFreeList = &newBlock[1];
-		//_chunkList.push_back(p);
-        }
-	return aHead;
-}
+		T* aHead = _headFreeList;
+		if (aHead){
+			_headFreeList = *(reinterpret_cast<T**>(aHead));
+			//_headFreeList = (T*)((void*)(*aHead));
+		}else{
+			T** aAdr;
+			T* newBlock = static_cast<T*>(::operator new(BLOCK_SIZE * sizeof(T)));
+			for (int i = 1; i < BLOCK_SIZE-1; ++i){
+				aAdr = reinterpret_cast<T**>(&newBlock[i]);
+				*aAdr = &newBlock[i+1];
+				//newBlock[i] = &newBlock[i+1];
+			}
+			aAdr = reinterpret_cast<T**>(&newBlock[BLOCK_SIZE-1]);
+			*aAdr = 0;
+			//newBlock[BLOCK_SIZE-1].next = 0;
+			aHead = newBlock;
+			_headFreeList = &newBlock[1];
+			//_chunkList.push_back(p);
+		}
+		return aHead;
+	}
 
-void pfree(void *p, unsigned int n){
-	if (p == 0) return;
-	if (n != sizeof(T)){
-		::operator delete(p);
-		return;
+	///Deallocation method
+	/**
+	\param p Pointer to the memory chunk to be deallocated 
+	\return Size of memory chunk to be deallocated
+	*/
+	void pfree(void *p, unsigned int n){
+		if (p == 0) return;
+		if (n != sizeof(T)){
+			::operator delete(p);
+			return;
+		}
+		T* aDelObj = static_cast<T*>(p);
+		//delObj->next = _headFreeList;
+		T** aAdr = reinterpret_cast<T**>(aDelObj);
+		*aAdr = _headFreeList;
+		_headFreeList = aDelObj;
 	}
-	T* aDelObj = static_cast<T*>(p);
-	//delObj->next = _headFreeList;
-	T** aAdr = reinterpret_cast<T**>(aDelObj);
-	*aAdr = _headFreeList;
-	_headFreeList = aDelObj;
-}
 
+///Destructor
 ~Pool(){
 	//std::list<T*>::iterator i;
 	//for(i=_chunkList.begin(); i != _chunkList.end(); ++i) ::operator delete [] *i;
 }
 private:
+	///Head pointer of the free list
 	T* _headFreeList;
 	//std::list<T*> _chunkList;
 };
 
-
+///Class which encapsulates a comment concerning the control flow or task execution
 class Comment{
 public:	
 	///Constructor
 	/**
 	\param iTime Time when the message occurred
+	\param iCommand Pointer to the command which created the comment, 0 if comment was created by a task
+	\param iActionCode Code specifying the comment message
 	*/
 	Comment(TMLTime iTime, TMLCommand* iCommand, unsigned int iActionCode):_time(iTime), _command(iCommand), _actionCode(iActionCode){}
 	
-	void * operator new(unsigned int size){
+	///New operator
+	/**
+	\param size Size of memory chunk to be allocated
+	\return Pointer to the allocated chunk of memory
+	*/
+	inline void * operator new(unsigned int size){
 		return memPool.pmalloc(size);
 	}
-	void operator delete(void *p, unsigned int size){
+	///Delete operator
+	/**
+	\param p Pointer to the memory chunk to be deallocated 
+	\param size Size of memory chunk to be deallocated
+	*/
+	inline void operator delete(void *p, unsigned int size){
 		memPool.pfree(p, size);
 	}
 
 	///Time when the massage occurred
 	TMLTime _time;
+	///Pointer to the command which created the comment, 0 if comment was created by a task
 	TMLCommand* _command;
+	///Code specifying the comment message
 	unsigned int _actionCode;
 private:
+	///Memory pool for comments
 	static Pool<Comment> memPool;
 };
 
@@ -252,30 +302,55 @@ public:
 	/**
 	\param in Constant reference to value
 	*/
-	RefValUnion(const T& in):isValue(true){
+	RefValUnion(const T& in):isValue(true), value(in){
 		//std::cout << "const constructor executed" << std::endl;
-		value=in;
+		//value=in;
 	}
 	///Constructor called for variables
 	/**
 	\param in Reference to variable
 	*/
-	RefValUnion(T& in):isValue(false){
+	RefValUnion(T& in):isValue(false), pointer(&in){
 		//std::cout << "varible constructor executed" << std::endl;
-		pointer=&in;
+		//pointer=&in;
+	}
+	RefValUnion(std::istream& s, unsigned int iAdr){
+		READ_STREAM(s, isValue);
+		if (isValue){
+			READ_STREAM(s, value);
+		}else{
+			unsigned int aAddrOffs;
+			READ_STREAM(s, aAddrOffs);
+			pointer = (T*)(iAdr + aAddrOffs);
+		}			
 	}
 	///The parenthesis operator returns a reference to the stored value
 	/**
 	\return Reference to value 
 	*/
-	T& operator() (){if (isValue) return value; else return *pointer;}
+	inline T& operator() (){if (isValue) return value; else return *pointer;}
 	///The parenthesis operator returns a reference to the stored value
 	/**
 	\return Constant reference to value 
 	*/
-	const T& operator() () const {if (isValue) return value; else return *pointer;}
+	inline const T& operator() () const {if (isValue) return value; else return *pointer;}
 	
 	T print() const {return value;}
+	friend std::istream& operator >> (std::istream &is,RefValUnion<T> &obj){
+		is >> obj.value;
+		obj.isValue=true;
+		return is;
+	}
+	std::ostream& writeObject(std::ostream& s, unsigned int iAdr){
+		WRITE_STREAM(s,isValue);
+		if (isValue){
+			WRITE_STREAM(s,value);
+		}else{
+			unsigned int aAdr=((unsigned int)pointer)-iAdr;
+			WRITE_STREAM(s,aAdr);
+		}
+		return s;
+	}
 private:
 	///Indicates whether the class holds a value or a pointer to a value
 	bool isValue;
@@ -298,6 +373,7 @@ public:
 	\param ip3 Value 3
 	*/
 	Parameter(const RefValUnion<T>& ip1,const RefValUnion<T>& ip2,const RefValUnion<T>& ip3):_p1(ip1),_p2(ip2),_p3(ip3){}
+	Parameter(std::istream& s, unsigned int iAdr):_p1(s,iAdr), _p2(s,iAdr), _p3(s,iAdr){}
 	///Assignement operator, copies all parameters
 	const Parameter<T>& operator=(const Parameter<T>& rhs){
 		_p1()=rhs._p1();
@@ -309,6 +385,16 @@ public:
 	void print(){
 		std::cout << "p1:" << _p1.print() << " p2:" << _p2.print() << " p3:" << _p3.print() << std::endl;
 	}
+	inline std::ostream& writeObject(std::ostream& s, unsigned int iAdr){
+		_p1.writeObject(s,iAdr);
+		_p2.writeObject(s,iAdr);
+		_p3.writeObject(s,iAdr);
+		return s;
+	}
+	friend std::istream& operator >>(std::istream &is,Parameter<T> &obj){
+		is >>obj._p1 >> obj._p2 >> obj._p3;
+ 		return is;
+	}
 private:
 	///Three parameters
 	RefValUnion<T> _p1,_p2,_p3;
@@ -365,6 +451,7 @@ typedef std::priority_queue<TMLTransaction*, std::vector<TMLTransaction*>, great
 typedef std::priority_queue<TMLTransaction*, std::vector<TMLTransaction*>, greaterRunnableTime > FutureTransactionQueue;
 ///Priority queue holding Transactions for the graph output
 typedef std::priority_queue<TMLTransaction*, std::vector<TMLTransaction*>, greaterStartTime > GraphTransactionQueue;
+//typedef std::map<SchedulableCommDevice*, FutureTransactionQueue*> BridgeTransactionListHash;
 
 ///Calculates random numbers between n1 and n2 (both inclusive)
 /**
@@ -382,4 +469,11 @@ int myrand(int n1, int n2);
 */
 long getTimeDiff(struct timeval& begin, struct timeval& end);
 
+///Replaces all occurrences of iSearch in ioHTML by iReplace
+/**
+	\param ioHTML String in which the replacements shall be made
+	\param iSearch String to search for
+	\param iReplace String which is filled in
+*/
+void replaceAll(std::string& ioHTML, std::string iSearch, std::string iReplace);
 #endif
diff --git a/simulators/c++2/src_simulator/simkern.cpp b/simulators/c++2/src_simulator/simkern.cpp
index 5c8a9003f52c677c411d2c7424b67bc86ada8391..9d0920568b8c80a4c9305d8d895770da76a808f8 100644
--- a/simulators/c++2/src_simulator/simkern.cpp
+++ b/simulators/c++2/src_simulator/simkern.cpp
@@ -44,34 +44,34 @@ Ludovic Apvrille, Renaud Pacalet
 unsigned int TMLTask::_id=0;
 unsigned int Bus::_id=0;
 unsigned int CPU::_id=0;
+TMLTime SchedulableDevice::_simulatedTime=0;
 
-TMLTransaction* getTransLowestEndTime(CPUList& iCPUlist, CPU*& oCPU){
-	CPUList::iterator i;
+TMLTransaction* getTransLowestEndTime(SchedulingList& iSchedList, SchedulableDevice*& oResultDevice){
+	SchedulingList::iterator i;
 	TMLTransaction *aMarker=0, *aTempTrans;
 	TMLTime aLowestTime=-1;
-	CPU* tempCPU;
+	SchedulableDevice* aTempDevice;
 	//static unsigned int aTransitionNo=0;
-	for(i=iCPUlist.begin(); i != iCPUlist.end(); ++i){
-		tempCPU=*i;
-		aTempTrans=tempCPU->getNextTransaction();	
+#ifdef DEBUG_KERNEL
+	std::cout << "kernel:getTLET: before loop" << std::endl;
+#endif
+	for(i=iSchedList.begin(); i != iSchedList.end(); ++i){
+		aTempDevice=*i;
+		aTempTrans=aTempDevice->getNextTransaction();	
 		if (aTempTrans!=0 && aTempTrans->getVirtualLength()>0){	
-			//std::cout << tempCPU->toString() << " has trans\n";
+#ifdef DEBUG_KERNEL
+			std::cout << "kernel:getTLET: transaction found on " << aTempDevice->toString() << ": " << aTempTrans->toString() << std::endl;
+#endif
 			if (aTempTrans->getEndTime() < aLowestTime){		
 				aMarker=aTempTrans;
 				aLowestTime=aTempTrans->getEndTime();
-				oCPU=tempCPU;
+				oResultDevice=aTempDevice;
 			}
 		}
+#ifdef DEBUG_KERNEL
+		else std::cout << "kernel:getTLET: no transaction found on " << aTempDevice->toString() << std::endl;
+#endif
 	}
-	/*std::ostringstream outp;
-	if (aMarker!=0){
-		outp << "(" << aTransitionNo << ",\"i(" << oCPU->toString() << "__" << aMarker->getCommand()->getTask()->toString() << "__" << aMarker->getCommand()->getCommandStr();
-		if (aMarker->getChannel()!=0)
-			outp << "__" << aMarker->getChannel()->toShortString();
-		outp << ")\"," << ++aTransitionNo << ")";
-		//std::cout << "des (0, " << aTransitionNo << ", " << aTransitionNo+1 << ")" << std::endl << outp.str() << std::endl;
-		for (unsigned int i=0; i<aMarker->getVirtualLength(); i++) std::cout << outp.str() << std::endl;
-	}*/
 	return aMarker; 
 }
 
@@ -122,8 +122,27 @@ void schedule2Graph(CPUList& iCPUlist, int iLen, char** iArgs){
 
 }
 
-void schedule2HTML(CPUList& iCPUlist,BusList& iBusList, int iLen, char** iArgs){
-	CPUList::iterator i;
+void schedule2TXT(SchedulingList& iSchedList, int iLen, char** iArgs){
+	SchedulingList::iterator i;
+	struct timeval aBegin,aEnd;
+	gettimeofday(&aBegin,NULL);
+	std::string aFilename(getArgs(iLen, iArgs, "-otxt", "scheduling.txt"));
+	if (aFilename.empty()) return;
+	std::ofstream myfile (aFilename.c_str());
+	if (myfile.is_open()){
+		for(i=iSchedList.begin(); i != iSchedList.end(); ++i){
+			(*i)->schedule2TXT(myfile);
+		}
+		myfile.close();
+	}
+	else
+		std::cout << "Unable to open text output file" << std::endl;
+	gettimeofday(&aEnd,NULL);
+	std::cout << "The text output took " << getTimeDiff(aBegin,aEnd) << "usec. File: " << aFilename << std::endl;
+}
+
+void schedule2HTML(SchedulingList& iSchedList,BusList& iBusList, int iLen, char** iArgs){
+	SchedulingList::iterator i;
 	BusList::iterator j;
 	struct timeval aBegin,aEnd;
 	std::string helpNeeded(getArgs(iLen, iArgs, "-help", "help"));
@@ -134,8 +153,8 @@ void schedule2HTML(CPUList& iCPUlist,BusList& iBusList, int iLen, char** iArgs){
 	std::ofstream myfile (aFilename.c_str());
 	if (myfile.is_open()){
 		myfile << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
-		myfile << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"schedstyle.css\" />\n<title>Scheduling</title>\n</head>\n<body>\n";		
-		for(i=iCPUlist.begin(); i != iCPUlist.end(); ++i){
+		myfile << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"schedstyle.css\" />\n<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\" />\n<title>Scheduling</title>\n</head>\n<body>\n";		
+		for(i=iSchedList.begin(); i != iSchedList.end(); ++i){
 			(*i)->schedule2HTML(myfile);
 		}
 		for(j=iBusList.begin(); j != iBusList.end(); ++j){
@@ -173,6 +192,7 @@ void schedule2VCD(TraceableDeviceList& iVcdList, int iLen, char** iArgs){
 		myfile << "$date\n" << asctime(aTimeinfo) << "$end\n\n$version\nDaniels TML simulator\n$end\n\n";
 		myfile << "$timescale\n1 ns\n$end\n\n$scope module Simulation $end\n";
 		for (i=iVcdList.begin(); i!= iVcdList.end(); ++i){
+			//std::cout << "device: " << (*i)->toString() << std::endl;
 			myfile << "$var integer 3 " << (*i)->toShortString() << " " << (*i)->toString() << " $end\n";
 			aTime = (*i)->getNextSignalChange(true, aSigString, aNoMoreTrans);
 			aQueue.push(new SignalChangeData(aSigString, aTime, (aNoMoreTrans)?0:(*i)));
@@ -201,10 +221,12 @@ void schedule2VCD(TraceableDeviceList& iVcdList, int iLen, char** iArgs){
 			if (actDevice!=0) aQueue.push(new SignalChangeData(aSigString, aTime, (aNoMoreTrans)?0:actDevice));
     		}
 		myfile << "#" << aCurrTime+1 << "\n";
+		std::cout << "Simulated cycles: " << aCurrTime << std::endl;
 		for (i=iVcdList.begin(); i!= iVcdList.end(); ++i){
 			myfile << "r4 " << (*i)->toShortString() << "\n";
+			//std::cout << "Utilization of component " << (*i)->toString() << ": " << ((float)(*i)->getBusyCycles()) / ((float)aCurrTime) << std::endl;
 		}
-		std::cout << "Simulated cycles: " << aCurrTime << std::endl;
+
 		myfile.close();
 	}
 	else
@@ -214,65 +236,98 @@ void schedule2VCD(TraceableDeviceList& iVcdList, int iLen, char** iArgs){
 
 }
 
-inline void scheduleCPUBus(CPUList& iCPUlist,BusList& iBusList){
-	for_each(iCPUlist.begin(), iCPUlist.end(),std::mem_fun(&CPU::schedule));
-	for_each(iBusList.begin(), iBusList.end(),std::mem_fun(&Bus::schedule));
-}
+//inline void scheduleCPUBus(SchedulingList& iSchedList,BusList& iBusList){
+//	for_each(iSchedList.begin(), iSchedList.end(),std::mem_fun(&SchedulableDevice::schedule));
+//	for_each(iBusList.begin(), iBusList.end(),std::mem_fun(&SchedulableCommDevice::schedule));
+//}
 
-inline void scheduleCPUBus(CPU* iCPU,BusList& iBusList){
-	iCPU->schedule();
-	for_each(iBusList.begin(), iBusList.end(),std::mem_fun(&Bus::schedule));
-}
+//inline void scheduleCPUBus(SchedulableDevice* iDevice,BusList& iBusList){
+//	iDevice->schedule();
+//	for_each(iBusList.begin(), iBusList.end(),std::mem_fun(&SchedulableCommDevice::schedule));
+//}
 
-void simulate(CPUList& cpulist, BusList& buslist){
+void simulate(SchedulingList& iSchedList, BusList& buslist){
 	TMLTransaction* depTransaction,*depCPUnextTrans,*transLET;
 	TMLCommand* commandLET,*depCommand,*depCPUnextCommand;
 	TMLTask* depTask;
-	CPU* cpuLET,*depCPU;
+	SchedulableDevice* cpuLET;
+	CPU* depCPU;
 	struct timeval aBegin,aEnd;
 	gettimeofday(&aBegin,NULL);
-	scheduleCPUBus(cpulist,buslist);
-	transLET=getTransLowestEndTime(cpulist,cpuLET);
-	while (transLET!=0){	
+#ifdef DEBUG_KERNEL
+	std::cout << "kernel:simulate: first schedule" << std::endl;
+#endif
+	for_each(iSchedList.begin(), iSchedList.end(),std::mem_fun(&SchedulableDevice::schedule));
+	transLET=getTransLowestEndTime(iSchedList,cpuLET);
+	while (transLET!=0){
+#ifdef DEBUG_KERNEL
+		std::cout << "kernel:simulate: scheduling decision: " <<  transLET->toString() << std::endl;
+#endif
 		commandLET=transLET->getCommand();
-		//std::cout << "Execute " << commandLET->toString() << " next Trans:" << commandLET->getCurrTransaction() << " commandLET:" << commandLET << std::endl;
-		commandLET->execute();
-		//std::cout << "Add" << std::endl;
-		cpuLET->addTransaction();
-		commandLET->getTask()->addTransaction(transLET);
-		//std::cout << "Schedule" << std::endl;
-		scheduleCPUBus(cpuLET,buslist);	
-		//std::cout << "huge IF" << std::endl;
-		depTask=commandLET->getDependentTask();
-		if (depTask!=0){
-		 depCPU=depTask->getCPU();			
-		 if (depCPU!=cpuLET){								//tasks running on different CPUs
-		  depCommand=depTask->getCurrCommand();
-		  if (depCommand!=0 && (depCommand->getChannel()==commandLET->getChannel() || depCommand->channelUnknown())){ //commands accessing the same channel
-		   depTransaction=depCommand->getCurrTransaction();
-		   if (depTransaction!=0 && depTransaction->getVirtualLength()!=0){		//dependent task has a current transaction and is not blocked any more
-		    depCPUnextTrans=depCPU->getNextTransaction();
-		    if (depCPUnextTrans!=0){							//there is a transaction scheduled on depCPU
-		     depCPUnextCommand=depCPUnextTrans->getCommand();
-		     if (depCPUnextCommand->getTask()!=depTask){				//dependent task is not yet scheduled
-			//if (depCPUnextCommand->truncateTransactionAt(transLET->getEndTime())!=0){
+#ifdef DEBUG_KERNEL
+		std::cout << "kernel:simulate: add trans " << commandLET->toString() << std::endl;
+#endif
+		if (cpuLET->addTransaction()){
+#ifdef DEBUG_KERNEL
+		 std::cout << "kernel:simulate: invoke on executing CPU" << std::endl;
+#endif
+		 cpuLET->schedule();
+		 depTask=commandLET->getDependentTask();
+		 if (depTask!=0){
+#ifdef DEBUG_KERNEL
+		  std::cout << "kernel:simulate: dependent Task found" << std::endl;
+#endif
+		  depCPU=depTask->getCPU();			
+		  if (depCPU!=cpuLET){
+#ifdef DEBUG_KERNEL
+		   std::cout << "kernel:simulate: Tasks running on different CPUs" << std::endl;
+#endif
+		   depCommand=depTask->getCurrCommand();
+		   if (depCommand!=0 && (depCommand->getChannel()==commandLET->getChannel() || depCommand->channelUnknown())){
+#ifdef DEBUG_KERNEL
+		    std::cout << "kernel:simulate: commands are accessing the same channel" << std::endl;
+#endif
+		    depTransaction=depCommand->getCurrTransaction();
+		    if (depTransaction!=0 && depTransaction->getVirtualLength()!=0){
+#ifdef DEBUG_KERNEL
+		     std::cout << "kernel:simulate: dependent task has a current transaction and is not blocked any more" << std::endl;
+#endif
+		     depCPUnextTrans=depCPU->getNextTransaction();
+		      if (depCPUnextTrans!=0){
+#ifdef DEBUG_KERNEL
+		      std::cout << "kernel:simulate: transaction scheduled on dependent CPU" << std::endl;
+#endif
+		       depCPUnextCommand=depCPUnextTrans->getCommand();
+		       if (depCPUnextCommand->getTask()!=depTask){
+#ifdef DEBUG_KERNEL
+ 			std::cout << "kernel:simulate: dependent task not yet scheduled on dependent CPU" << std::endl;
+#endif
 			if (depCPU->truncateNextTransAt(transLET->getEndTime())!=0){
-				depCPUnextCommand->execute();
+#ifdef DEBUG_KERNEL
+				std::cout << "kernel:simulate: dependent transaction truncated" << std::endl;
+#endif
 				depCPU->addTransaction();
-				depCPUnextCommand->getTask()->addTransaction(depCPUnextTrans);
 			}
-			//std::cout << "Schedule within big IF" << std::endl;
-			scheduleCPUBus(depCPU,buslist);
+#ifdef DEBUG_KERNEL
+			std::cout << "kernel:simulate: schedule dependent CPU" << std::endl;
+#endif
+			depCPU->schedule();
+		      }
+		     }else{
+#ifdef DEBUG_KERNEL
+			std::cout << "kernel:simulate: schedule dependent CPU" << std::endl;
+#endif
+			depCPU->schedule();
 		     }
-		    }else{
-			//std::cout << "Schedule within small if" << std::endl;
-		     scheduleCPUBus(depCPU,buslist);
 		    }
 		   }
 		  }
 		 }
 		}
-		transLET=getTransLowestEndTime(cpulist,cpuLET);
+#ifdef DEBUG_KERNEL
+		else std::cout << "kernel:simulate: *** this should never happen ***" << std::endl;
+#endif
+		transLET=getTransLowestEndTime(iSchedList,cpuLET);
 	}
 	gettimeofday(&aEnd,NULL);
 	std::cout << "The simulation took " << getTimeDiff(aBegin,aEnd) << "usec.\n";
@@ -283,7 +338,6 @@ const std::string getArgs(int iLen, char** iArgs, const std::string& iComp, cons
 	while (aPosition < iLen){
 		if (iComp.compare(iArgs[aPosition])==0){
 			if (aPosition+1 < iLen && iArgs[aPosition+1][0]!='-'){
-				//std::cout << "next argument: " << std::string(iArgs[aPosition+1]) << std::endl;
 				return std::string(iArgs[aPosition+1]);
 			}else
 				return iDefault;
@@ -296,3 +350,10 @@ const std::string getArgs(int iLen, char** iArgs, const std::string& iComp, cons
 void printHelp(){
 	std::cout << "*****\nCommand line usage: run.x -ohtml myfile.htm -ovcd myfile.vcd\nParameters can be omitted if output is not needed, if file name is omitted the following default values will be taken instead: scheduling.htm, scheduling.vcd.\n*****\n";
 }
+
+void streamBenchmarks(std::ostream& s, TraceableDeviceList& iVcdList){
+	TraceableDeviceList::iterator i;
+	for (i=iVcdList.begin(); i!= iVcdList.end(); ++i){
+		(*i)->streamBenchmarks(s);
+	}
+}
diff --git a/simulators/c++2/src_simulator/simkern.h b/simulators/c++2/src_simulator/simkern.h
index 8a8edbf388fb9aa5521dc64202a77a5abb070fde..0c1b79eede142eadeb2c7c73da7901ec5897c1f1 100644
--- a/simulators/c++2/src_simulator/simkern.h
+++ b/simulators/c++2/src_simulator/simkern.h
@@ -47,6 +47,8 @@ Ludovic Apvrille, Renaud Pacalet
 #include <CPUPBL.h>
 #include <CPURR.h>
 #include <Bus.h>
+#include <Bridge.h>
+#include <Memory.h>
 #include <TMLbrbwChannel.h>
 #include <TMLnbrnbwChannel.h>
 #include <TMLbrnbwChannel.h>
@@ -67,36 +69,67 @@ Ludovic Apvrille, Renaud Pacalet
 TMLTransaction* getTransLowestEndTime(CPUList& iCPUlist, CPU*& oCPU);
 ///Writes a HTML representation of the schedule of CPUs and buses to an output file
 /**
-\param iCPUlist CPU list
+\param iSchedList List containing components to schedule
 \param iBusList Bus list
+\param iLen Number of command line arguments
+\param iArgs Pointer to command line arguments
 */
-void schedule2HTML(CPUList& iCPUlist,BusList& iBusList, int iLen, char** iArgs);
-///Invokes the schedule() method of all CPUs and buses
+void schedule2HTML(SchedulingList& iSchedList,BusList& iBusList, int iLen, char** iArgs);
+/////Invokes the schedule() method of all CPUs and buses
+/////**
+//\param iCPUlist CPU list
+//\param iBusList Bus list
+//*/
+//void scheduleCPUBus(CPUList& iCPUlist,BusList& iBusList);
+/////Invokes the schedule() method of one CPU and all buses
+/////**
+//\param iCPU CPU
+//\param iBusList Bus list
+//*/
+//void scheduleCPUBus(CPU* iCPU,BusList& iBusList);
+///Runs the simulation
 /**
-\param iCPUlist CPU list
+\param iSchedList List containing components to schedule
 \param iBusList Bus list
 */
-void scheduleCPUBus(CPUList& iCPUlist,BusList& iBusList);
-///Invokes the schedule() method of one CPU and all buses
+void simulate(SchedulingList& iSchedList, BusList& buslist);
+///Writes simulation traces in VCD format to an output file
 /**
-\param iCPU CPU
-\param iBusList Bus list
+\param iVcdList List of components whose traces are output
+\param iLen Number of command line arguments
+\param iArgs Pointer to command line arguments
 */
-void scheduleCPUBus(CPU* iCPU,BusList& iBusList);
-///Runs the simulation
+void schedule2VCD(TraceableDeviceList& iVcdList, int iLen, char** iArgs);
+///Writes the simulation graph to an output file
 /**
 \param iCPUlist CPU list
-\param iBusList Bus list
+\param iLen Number of command line arguments
+\param iArgs Pointer to command line arguments
 */
-void simulate(CPUList& cpulist, BusList& buslist);
-
-void schedule2VCD(TraceableDeviceList& iVcdList, int iLen, char** iArgs);
-
 void schedule2Graph(CPUList& iCPUlist, int iLen, char** iArgs);
-
+///Writes a HTML representation of the schedule of CPUs and buses to an output file
+/**
+\param iLen Number of command line arguments
+\param iArgs Pointer to command line arguments
+\param iComp Flag to search for in within the argument list
+\param iDefault Default name of an output file
+\return Output file name
+*/
 const std::string getArgs(int iLen, char** iArgs, const std::string& iComp, const std::string& iDefault);
-
+///Shows a help text explaining the usage of the simulator
 void printHelp();
-
+///Writes a plain text representation of the schedule of CPUs to an output file
+/**
+\param iSchedList List containing components to schedule
+\param iLen Number of command line arguments
+\param iArgs Pointer to command line arguments
+*/
+void schedule2TXT(SchedulingList& iSchedList, int iLen, char** iArgs);
+///Calls streamBenchmarks of all traceable devices contained in iVcdList
+/**
+\param s Reference to output stream object
+\param iVcdList List of devices which are able to stream their benchmark data
+*/
+void streamBenchmarks(std::ostream& s, TraceableDeviceList& iVcdList);
 #endif
 
diff --git a/src/nc/NCElement.java b/src/nc/NCElement.java
index 9e7284ff92b516dba761869f885b92df39bddf14..e0db13d65d3443ea6227c8b1bfb3f4af620df32f 100755
--- a/src/nc/NCElement.java
+++ b/src/nc/NCElement.java
@@ -46,7 +46,7 @@
 package nc;
 
 
-public class NCElement  {
+public class NCElement extends Object  {
     
 	protected String name;
 	
diff --git a/src/nc/NCLink.java b/src/nc/NCLink.java
index b0aad277f7045f780dded1e61bef0f5347090982..802d083a5e6e7d95565e857f3ae6ff3fd94335b1 100755
--- a/src/nc/NCLink.java
+++ b/src/nc/NCLink.java
@@ -86,5 +86,16 @@ public class NCLink extends NCElement  {
 		return capacityUnit;
 	}
 	
+	public Object clone() {
+		NCLink link = new NCLink();
+		NCCapacityUnit unit = new NCCapacityUnit();
+		unit.setUnit(getCapacityUnit().getStringUnit());
+		link.setCapacity(capacity);
+		link.setCapacityUnit(unit);
+		link.setLinkedElement1(le1);
+		link.setLinkedElement1(le2);
+		return link;
+	}
+	
 	
 }
\ No newline at end of file
diff --git a/src/nc/NCStructure.java b/src/nc/NCStructure.java
index 671db68fef49e8865e81e1dbb59ef4e5f71a4636..3d445eec9bb5ef6cc9adb76e865940ec74d413db 100755
--- a/src/nc/NCStructure.java
+++ b/src/nc/NCStructure.java
@@ -78,6 +78,16 @@ public class NCStructure extends NCElement {
 		return null;
 	}
 	
+	public NCLinkedElement getNCEquipmentByName(String _name) {
+		for(NCEquipment eq: equipments) {
+			if (eq.getName().equals(_name)) {
+				return eq;
+			}
+		}
+		
+		return null;
+	}
+	
 	public NCTraffic getTrafficByName(String name) {
 		for(NCTraffic tr: traffics) {
 			if (tr.getName().equals(name)) {
@@ -224,4 +234,14 @@ public class NCStructure extends NCElement {
 		return null;
 	}
 	
+	public NCLink getLinkWith(NCLinkedElement le) {
+		for(NCLink link: links) {
+			if ((link.le1 == le) || (link.le2 == le)) {
+				return link;
+			}
+		}
+		
+		return null;
+	}
+	
 }
\ No newline at end of file
diff --git a/src/nc/NCTraffic.java b/src/nc/NCTraffic.java
index ec6993ec8b3118d78a529802a7e113b6c1a5c92e..d9cea2d4ff28329633d09d81dadac2199ce2ea9e 100755
--- a/src/nc/NCTraffic.java
+++ b/src/nc/NCTraffic.java
@@ -113,4 +113,17 @@ public class NCTraffic extends NCElement  {
 	public int getPriority() {
         return priority;
     }
+	
+	public Object clone() {
+		NCTraffic traffic = new NCTraffic();
+		NCTimeUnit unit = new NCTimeUnit();
+		unit.setUnit(deadlineUnit.getStringUnit());
+		traffic.setDeadlineUnit(unit);
+		traffic.setPeriodicType(periodicType);
+		traffic.setDeadline(deadline);
+		traffic.setMinPacketSize(minPacketSize);
+		traffic.setMaxPacketSize(maxPacketSize);
+		traffic.setPriority(priority);
+		return traffic;
+	}
 }
\ No newline at end of file
diff --git a/src/tmltranslator/TMLArchitecture.java b/src/tmltranslator/TMLArchitecture.java
index 85279aebb03d8fe1a66b0605b15b8622bb8b90d8..bd1c5fa5ea18e7ae1da06441ea3371b078e86768 100755
--- a/src/tmltranslator/TMLArchitecture.java
+++ b/src/tmltranslator/TMLArchitecture.java
@@ -36,12 +36,12 @@ The fact that you are presently reading this means that you have had
 knowledge of the CeCILL license and that you accept its terms.
 
 /**
- * Class TMLArchitecture
- * Creation: 05/09/2007
- * @version 1.1 19/05/2008
- * @author Ludovic APVRILLE
- * @see
- */
+* Class TMLArchitecture
+* Creation: 05/09/2007
+* @version 1.1 19/05/2008
+* @author Ludovic APVRILLE
+* @see
+*/
 
 package tmltranslator;
 
@@ -51,13 +51,14 @@ import java.util.*;
 public class TMLArchitecture {
     private ArrayList<HwNode> hwnodes;
 	private ArrayList<HwLink> hwlinks; // Between buses and other component
+	
 	private int masterClockFrequency = 200; // in MHz
- 
+	
     
     public TMLArchitecture() {
         init();
     }
-
+	
     private void init() {
         hwnodes = new ArrayList<HwNode>();
 		hwlinks = new ArrayList<HwLink>();
@@ -70,6 +71,7 @@ public class TMLArchitecture {
 	public int getMasterClockFrequency() {
 		return masterClockFrequency;
 	}
+	
     
     public void addHwNode(HwNode _node) {
         hwnodes.add(_node);
@@ -133,5 +135,11 @@ public class TMLArchitecture {
 		return null;
 	}
 	
-  
+	public boolean isNodeConnectedToBus(HwNode node, HwBus bus){
+		for(HwLink link: hwlinks) {
+			if (node==link.hwnode && bus==link.bus) return true;
+		}
+		return false;
+	}
+	
 }
\ No newline at end of file
diff --git a/src/tmltranslator/TMLMapping.java b/src/tmltranslator/TMLMapping.java
index afc36265da8efa9ebaad4cd3f91122e855940830..1a120bf586f0c14285ac5e8503b5b38b5f4192d6 100755
--- a/src/tmltranslator/TMLMapping.java
+++ b/src/tmltranslator/TMLMapping.java
@@ -157,6 +157,13 @@ public class TMLMapping {
 		 }
 		 return false;
 	}
+
+	/*public boolean isChannelMappedOn(TMLElement _channel, HwCommunicationNode _node) {
+		 for(int i=0; i<oncommnodes.size(); i++) {
+			 if (oncommnodes.get(i) == _node && mappedcommelts.get(i) == _channel) return true;
+		 }
+		 return false;
+	}*/
 	
 	public boolean oneTaskMappedOn(TMLRequest _request, HwNode _node) {
 		TMLTask task;
@@ -212,6 +219,16 @@ public class TMLMapping {
 		return list;
 	}
 
+	public LinkedList<HwCommunicationNode> findNodesForElement(TMLElement _elementToFind){
+		LinkedList<HwCommunicationNode> list = new LinkedList<HwCommunicationNode>();
+		int index=0;
+		for(TMLElement tmlelem: mappedcommelts) {
+			if (tmlelem == _elementToFind) list.add(oncommnodes.get(index));
+			index++;
+		}
+		return list;
+	}
+
   
   
 }
\ No newline at end of file
diff --git a/src/tmltranslator/tomappingsystemc2/MappedSystemCTask.java b/src/tmltranslator/tomappingsystemc2/MappedSystemCTask.java
index 9b0ec47bbd34fd73b9f8cedf6288b13ee41777c8..b59897ff5007dd556691fa73872ef25f21eb7e85 100755
--- a/src/tmltranslator/tomappingsystemc2/MappedSystemCTask.java
+++ b/src/tmltranslator/tomappingsystemc2/MappedSystemCTask.java
@@ -1,772 +1,711 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
- *
- * ludovic.apvrille AT enst.fr
- *
- * This software is a computer program whose purpose is to allow the
- * edition of TURTLE analysis, design and deployment diagrams, to
- * allow the generation of RT-LOTOS or Java code from this diagram,
- * and at last to allow the analysis of formal validation traces
- * obtained from external tools, e.g. RTL from LAAS-CNRS and CADP
- * from INRIA Rhone-Alpes.
- *
- * This software is governed by the CeCILL  license under French law and
- * abiding by the rules of distribution of free software.  You can  use,
- * modify and/ or redistribute the software under the terms of the CeCILL
- * license as circulated by CEA, CNRS and INRIA at the following URL
- * "http://www.cecill.info".
- *
- * As a counterpart to the access to the source code and  rights to copy,
- * modify and redistribute granted by the license, users are provided only
- * with a limited warranty  and the software's author,  the holder of the
- * economic rights,  and the successive licensors  have only  limited
- * liability.
- *
- * In this respect, the user's attention is drawn to the risks associated
- * with loading,  using,  modifying and/or developing or reproducing the
- * software by the user in light of its specific status of free software,
- * that may mean  that it is complicated to manipulate,  and  that  also
- * therefore means  that it is reserved for developers  and  experienced
- * professionals having in-depth computer knowledge. Users are therefore
- * encouraged to load and test the software's suitability as regards their
- * requirements in conditions enabling the security of their systems and/or
- * data to be ensured and,  more generally, to use and operate it in the
- * same conditions as regards security.
- *
- * The fact that you are presently reading this means that you have had
- * knowledge of the CeCILL license and that you accept its terms.
- *
- * /**
- * Class MappedSystemCTask
- * Creation: 24/11/2005
- * @version 1.0 24/11/2005
- * @author Ludovic APVRILLE
- * @see
- */
-
-package tmltranslator.tomappingsystemc2;
-
-import java.util.*;
-
-import tmltranslator.*;
-import myutil.*;
-
-
-public class MappedSystemCTask {
-	//private TMLModeling tmlm;
-    private TMLTask task;
-    private String reference, cppcode, hcode, initCommand, functions, functionSig, chaining, firstCommand, commentText;
-	private ArrayList<TMLChannel> channels;
-	private ArrayList<TMLEvent> events;
-	private ArrayList<TMLRequest> requests;
-	private int commentNum;
-	
-    
-    private boolean debug;
-	
-	private final static String DOTH = ".h";
-	private final static String DOTCPP = ".cpp";
-	private final static String SYSTEM_INCLUDE = "#include \"systemc.h\"";
-	private final static String CR = "\n";
-	private final static String CR2 = "\n\n";
-	private final static String SCCR = ";\n";
-	private final static String EFCR = "}\n";
-	private final static String EFCR2 = "}\n\n";
-	private final static String EF = "}";
-	
-	
-    public MappedSystemCTask(TMLTask _task, ArrayList<TMLChannel> _channels, ArrayList<TMLEvent> _events, ArrayList<TMLRequest> _requests) {
-        task = _task;
-		channels = _channels;
-		events = _events;
-		requests = _requests;
-        	reference = task.getName();
-		cppcode = "";
-		hcode = "";
-		initCommand="";
-		functions="";
-		chaining="";
-		firstCommand="";
-		functionSig="";
-		commentText="";
-		commentNum=0;
-    }
-	
-	public void saveInFiles(String path) throws FileException {	
-		FileUtils.saveFile(path + reference + DOTH, getHCode());
-		FileUtils.saveFile(path + reference + DOTCPP, getCPPCode());
-	}
-	
-	public TMLTask getTMLTask() {
-		return task;
-	}
-    
-    
-    public void generateSystemC(boolean _debug) {
-        debug = _debug;
-		//basicHCode();
-		basicCPPCode();
-		makeClassCode();
-    }
-    
-    public void print() {
-		System.out.println("task: " + reference + DOTH + hcode);
-		System.out.println("task: " + reference + DOTCPP + cppcode);
-    }
-	
-	
-	public String getCPPCode() {
-		return cppcode;
-	}
-	
-	public String getHCode() {
-		return hcode;
-	}
-	
-	public String getReference() {
-		return reference;
-	}
-	
-	
-	// H Code
-	//
-	public String basicHCode() {
-		String code="";
-		code += "#ifndef " + reference.toUpperCase() + "__H" + CR;
-		code += "#define " + reference.toUpperCase() + "__H" + CR2;
-		code += "#include <TMLTask.h>\n#include <definitions.h>\n\n";
-		code += "#include <TMLbrbwChannel.h>\n#include <TMLbrnbwChannel.h>\n#include <TMLnbrnbwChannel.h>\n\n";
-		code += "#include <TMLEventBChannel.h>\n#include <TMLEventFChannel.h>\n#include <TMLEventFBChannel.h>\n\n";
-		code += "#include <TMLActionCommand.h>\n#include <TMLChoiceCommand.h>\n#include <TMLExeciCommand.h>\n";
-		code += "#include <TMLSelectCommand.h>\n#include <TMLReadCommand.h>\n#include <TMLNotifiedCommand.h>\n";
-		code += "#include <TMLRequestCommand.h>\n#include <TMLSendCommand.h>\n#include <TMLWaitCommand.h>\n";
-		code += "#include <TMLWriteCommand.h>\n\n";
-		return code;
-	}
-	
-
-	public void classHCode() {
-	}
-	
-	
-	// CPP Code
-	//
-	public void basicCPPCode() {
-		cppcode += "#include <" + reference + DOTH + ">" + CR2;
-	}
-	
-	public void makeClassCode(){
-		makeHeaderClassH();
-		makeEndClassH();
-		
-		cppcode+=reference+ "::" + makeConstructorSignature()+":TMLTask(iPriority,iName,iCPU)"+ CR + makeAttributesCode();
-		cppcode+=initCommand + CR2 + "{" + CR + "_comment = new std::string[" + commentNum + "]" + SCCR + commentText;
-		
-		cppcode+="//set blocked read task/set blocked write task"+ CR;
-		for(TMLChannel ch: channels) {
-			if (ch.getOriginTask()==task)
-				cppcode+=ch.getExtendedName() + "->setBlockedWriteTask(this)"+SCCR;
-			else
-				cppcode+=ch.getExtendedName() + "->setBlockedReadTask(this)"+SCCR;
-		}
-		for(TMLEvent evt: events) {
-			if (evt.getOriginTask()==task)
-				cppcode+=evt.getExtendedName() + "->setBlockedWriteTask(this)"+SCCR;
-			else
-				cppcode+=evt.getExtendedName() + "->setBlockedReadTask(this)"+SCCR;
-		}
-		if (task.isRequested()) cppcode+="requestChannel->setBlockedReadTask(this)" +SCCR;
-		for(TMLRequest req: requests) {
-			if (req.isAnOriginTask(task)) cppcode+=req.getExtendedName() + "->setBlockedWriteTask(this)" +SCCR;
-		}
-		cppcode+=CR + "//command chaining"+ CR;
-		cppcode+= chaining + "_currCommand=" + firstCommand + SCCR + "_currCommand->prepare()"+SCCR+"}";
-		cppcode+=CR2+functions;
-		hcode = Conversion.indentString(hcode, 4);
-		cppcode = Conversion.indentString(cppcode, 4);
-		//System.out.println(CR2+ "************HCODE************\n"+hcode);
-		//System.out.println(CR+ "************CPPCODE************\n" + cppcode);
-	}
-	
-	private String makeConstructorSignature(){
-		String constSig=reference+ "(unsigned int iPriority, std::string iName, CPU* iCPU"+CR;
-		for(TMLChannel ch: channels) {
-			constSig+=", TMLChannel* "+ ch.getExtendedName() + CR;
-		}
-		for(TMLEvent evt: events) {
-			constSig+=", TMLEventChannel* "+ evt.getExtendedName() +CR;
-		}
-		for(TMLRequest req: requests) {
-			if (req.isAnOriginTask(task)) constSig+=", TMLEventBChannel* " + req.getExtendedName() + CR;
-		}
-		if (task.isRequested()){
-			constSig+=", TMLEventBChannel* requestChannel"+CR;
-		}
-		return constSig+")";
-	}
-
-	public void makeHeaderClassH() {
-		String hcodeBegin="";
-		// Common dec
-		hcodeBegin = "class " + reference + ": public TMLTask {" + CR;
-		hcodeBegin += "private:" + CR;
-		
-		// Attributes
-		hcodeBegin += "// Attributes" + CR;
-		//hcodeBegin += makeAttributesDeclaration() + CR;
-		
-		if (task.isRequested()) {
-			int params = task.getRequest().getNbOfParams();
-			firstCommand="_waitOnRequest";
-			hcode+="TMLWaitCommand " + firstCommand + SCCR;
-			initCommand+= "," + firstCommand + "(this,requestChannel,"; 
-			if (params==0){
-				initCommand+= "0)" + CR;
-			}else{
-				initCommand+= "new Parameter<ParamType>(arg1__req,";
-				if (params>1) initCommand+= "arg2__req,"; else  initCommand+= "0,";
-				if (params>2) initCommand+= "arg3__req))\n"; else  initCommand+= "0))\n";
-			}	
-			//"arg2__req,arg3__req))" + CR;	
-			String xx = firstCommand + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(task.getActivityDiagram().getFirst(),false,"&"+firstCommand,null,null,null) + "))"+ SCCR;
-			firstCommand="&"+firstCommand;
-			chaining+=xx;
-		}else{
-			firstCommand=makeCommands(task.getActivityDiagram().getFirst(),false,"0",null,null,null);
-		}
-
-		hcode = basicHCode() + hcodeBegin + makeAttributesDeclaration() + CR + hcode;
-		// public dec
-		hcode += CR + functionSig + CR + "public:" + CR;
-		// Simulation
-		hcode += makeConstructorSignature() + SCCR;
-	}
-
-	public String makeCommands(TMLActivityElement currElem, boolean skip, String retElement, strwrap nextCommandCont, strwrap functionCont, TMLActivityElement lastSequence){
-		String nextCommand="",cmdName="";
-		//strwrap nextCommandCollection, functionCollection;
-
-		if (skip) return makeCommands(currElem.getNextElement(0), false,retElement,nextCommandCont,functionCont,lastSequence);
-
-		if (currElem==null){
-			System.out.println("Checking null\n");
-			//if (nextCommandCont!=null){
-				//nextCommandCont.str += ",(TMLCommand*)" + retElement;
-				//nextCommandCont.num++;
-			//}
-			//if (lastSequence!=null) return makeCommands(lastSequence, false,retElement,nextCommandCont,functionCont,null);
-			return retElement;
-		}
-		
-		//System.out.println("Checking " + currElem.getName() + CR);
-
-		if (currElem instanceof TMLStartState) {
-			System.out.println("Checking Start\n");
-			return makeCommands(currElem.getNextElement(0), false,retElement,nextCommandCont,functionCont,lastSequence);
-		
-		} else if (currElem instanceof TMLStopState){
-			System.out.println("Checking Stop\n");
-			//if (lastSequence!=null) return makeCommands(lastSequence, false,retElement,nextCommandCont,functionCont,null);
-			return retElement;
-		
-		} else if (currElem instanceof TMLActionState || currElem instanceof TMLRandom){
-			String action;
-			if (currElem instanceof TMLActionState){
-				action = ((TMLActionState)currElem).getAction();
-				System.out.println("Checking Action\n");
-			}else{
-				TMLRandom random = (TMLRandom)currElem;
-				action = random.getVariable() + "=myrand("+ random.getMinValue() + "," + random.getMaxValue() + ")";
-				System.out.println("Checking Random\n");
-			}
-			cmdName= "_action" + currElem.getID();
-			if (nextCommandCont==null){
-				System.out.println("nextCommandCont==null in ActionState "+ action +CR);
-				hcode+="TMLActionCommand " + cmdName + SCCR;
-				strwrap nextCommandCollection = new strwrap(""), functionCollection = new strwrap("");
-				//nextCommandCollection = new strwrap(""); functionCollection = new strwrap("");
-				initCommand+= "," + cmdName + "(this,(ActionFuncPointer)&" + reference + "::" + cmdName + "_func)"+CR;
-				String MKResult = makeCommands(currElem.getNextElement(0),false,retElement,nextCommandCollection,functionCollection,lastSequence);
-				if(nextCommandCollection.num==0){
-					nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + MKResult + "));\n";
-				}else{	
-					nextCommand= cmdName + ".setNextCommand(array(" + nextCommandCollection.num + nextCommandCollection.str + "));\n";
-				}
-				functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\n" + modifyString(addSemicolonIfNecessary(action)) + CR + functionCollection.str + "}" + CR2;
-				commentText+="_comment[" + commentNum + "]=std::string(\"Action " + action + "\");\n";
-				commentNum++;
-				functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
-			}else{
-				System.out.println("nextCommandCont!=null in ActionState "+ action +CR); 
-				functionCont.str += "addComment(new Comment(_endLastTransaction,0," + commentNum + "));\n" + modifyString(addSemicolonIfNecessary(action)) + CR;
-				commentText+="_comment[" + commentNum + "]=std::string(\"Action " + action + "\");\n";
-				commentNum++;
-				return makeCommands(currElem.getNextElement(0),false,retElement,nextCommandCont,functionCont,lastSequence);
-			}
-
-
-		} else if (currElem instanceof TMLExecI){
-			System.out.println("Checking Execi\n");
-			cmdName= "_execi" + currElem.getID();
-			hcode+="TMLExeciCommand " + cmdName + SCCR;
-			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecI)currElem).getAction() + ",0,0)"+CR;
-			initCommand+= "," + cmdName + "(this," + makeCommandLenFunc(cmdName, ((TMLExecI)currElem).getAction(), null) + ",0)" + CR;
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-
-		} else if (currElem instanceof TMLExecC){
-			System.out.println("Checking ExecC\n");
-			cmdName= "_execc" + currElem.getID();
-			hcode+="TMLExeciCommand " + cmdName + SCCR;
-			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecI)currElem).getAction() + ",1)"+CR;
-			initCommand+= "," + cmdName + "(this,"+ makeCommandLenFunc(cmdName, ((TMLExecI)currElem).getAction(), null) + ",1)"+CR;
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-		
-		} else if (currElem instanceof TMLExecIInterval){
-			System.out.println("Checking ExeciInterv\n");
-			cmdName= "_execi" + currElem.getID();
-			hcode+="TMLExeciCommand " + cmdName + SCCR;
-			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecIInterval)currElem).getMinDelay()+ "," + ((TMLExecIInterval)currElem).getMaxDelay() + ",0)"+CR;
-			initCommand+= "," + cmdName + "(this,"+ makeCommandLenFunc(cmdName, ((TMLExecIInterval)currElem).getMinDelay(), ((TMLExecIInterval)currElem).getMaxDelay()) + ",0)"+CR;
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-
-		} else if (currElem instanceof TMLExecCInterval){
-			System.out.println("Checking ExecCInterv\n");
-			cmdName= "_execc" + currElem.getID();
-			hcode+="TMLExeciCommand " + cmdName + SCCR;
-			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecIInterval)currElem).getMinDelay()+ "," + ((TMLExecIInterval)currElem).getMaxDelay() + ",1)"+CR;
-			initCommand+= "," + cmdName + "(this,"+ makeCommandLenFunc(cmdName, ((TMLExecIInterval)currElem).getMinDelay(), ((TMLExecIInterval)currElem).getMaxDelay()) + ",1)"+CR;
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-
-					
-		} else if (currElem instanceof TMLForLoop){
-			System.out.println("Checking Loop\n");
-			TMLForLoop fl = (TMLForLoop)currElem;
-			cmdName="_choice" + currElem.getID();
-			hcode+="TMLChoiceCommand " + cmdName + SCCR;
-			initCommand+= "," + cmdName + "(this,(CondFuncPointer)&" + reference + "::" + cmdName + "_func)"+CR;
-			functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\nstatic bool firstTime=true;\nif(firstTime){\nfirstTime=false;\n" + addSemicolonIfNecessary(((TMLForLoop)currElem).getInit()) + "\n}else{\n" + addSemicolonIfNecessary(((TMLForLoop)currElem).getIncrement()) + "\n}\nif(" + ((TMLForLoop)currElem).getCondition() + "){\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\nreturn 0;\n}else{\naddComment(new Comment(_endLastTransaction,0," + (commentNum+1) + "));\nfirstTime=true;\nreturn 1;\n}\n}\n\n";
-			commentText+="_comment[" + commentNum + "]=std::string(\"" + ((TMLForLoop)currElem).getCondition() + "=true\");\n";
-			commentNum++;
-			commentText+="_comment[" + commentNum + "]=std::string(\"Exit loop: " + ((TMLForLoop)currElem).getCondition() + "=false\");\n";
-			commentNum++;
-			functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
-			nextCommand= cmdName + ".setNextCommand(array(2,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,"&"+cmdName,null,null,null) + ",(TMLCommand*)" + makeCommands(currElem.getNextElement(1),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-		
-		} else if (currElem instanceof TMLReadChannel){
-			System.out.println("Checking Read\n");
-			cmdName= "_read" + currElem.getID();
-			hcode+="TMLReadCommand " + cmdName + SCCR;
-			TMLReadChannel rCommand=(TMLReadChannel)currElem;
-			//initCommand+= "," + cmdName + "(this," + rCommand.getNbOfSamples() + "*" + rCommand.getChannel().getSize() + "," + rCommand.getChannel().getExtendedName() + ")"+CR;
-			initCommand+= "," + cmdName + "(this," + makeCommandLenFunc(cmdName, rCommand.getChannel().getSize() + "*(" + rCommand.getNbOfSamples()+")",null) + "," + rCommand.getChannel().getExtendedName() + ")"+CR;
-			//initCommand+= "," + cmdName + "(this," + rCommand.getNbOfSamples() + "," + rCommand.getChannel().getExtendedName() + ")"+CR;
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-		
-		} else if (currElem instanceof TMLWriteChannel){
-			System.out.println("Checking Write\n");
-			cmdName= "_write" + currElem.getID();
-			hcode+="TMLWriteCommand " + cmdName + SCCR;
-			TMLWriteChannel wCommand=(TMLWriteChannel)currElem;
-			//initCommand+= "," + cmdName + "(this," + wCommand.getNbOfSamples() + "*" + wCommand.getChannel().getSize() + "," + wCommand.getChannel().getExtendedName() + ")"+CR;
-			initCommand+= "," + cmdName + "(this," + makeCommandLenFunc(cmdName, wCommand.getChannel().getSize() + "*(" + wCommand.getNbOfSamples() + ")", null) + "," + wCommand.getChannel().getExtendedName() + ")"+CR;
-			//initCommand+= "," + cmdName + "(this," + wCommand.getNbOfSamples() + "," + wCommand.getChannel().getExtendedName() + ")"+CR;
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-		
-		} else if (currElem instanceof TMLSendEvent){
-			System.out.println("Checking Send\n");
-			cmdName= "_send" + currElem.getID();
-			hcode+="TMLSendCommand " + cmdName + SCCR;
-			if (((TMLSendEvent)currElem).getNbOfParams()==0){
-				initCommand+= "," + cmdName + "(this," + ((TMLSendEvent)currElem).getEvent().getExtendedName() + ",0)"+CR;
-			}else{ 
-				initCommand+= "," + cmdName + "(this," + ((TMLSendEvent)currElem).getEvent().getExtendedName() + ",new Parameter<ParamType>(";
-				for(int i=0; i<3; i++) {
-					if (i!=0) initCommand += ",";
-					if (((TMLSendEvent)currElem).getParam(i) == null) {
-						initCommand += "0";
-					} else {
-						if (((TMLSendEvent)currElem).getParam(i).length() > 0) {
-							initCommand += ((TMLSendEvent)currElem).getParam(i);
-						} else {
-							initCommand += "0";
-						}
-					}
-            			}
-				initCommand+="))"+CR;
-			}
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-			
-		} else if (currElem instanceof TMLSendRequest){
-			System.out.println("Checking Request\n");
-			cmdName= "_request" + currElem.getID();
-			hcode+="TMLRequestCommand " + cmdName + SCCR;
-			if (((TMLSendRequest)currElem).getNbOfParams()==0){
-				initCommand+= "," + cmdName + "(this," + ((TMLSendRequest)currElem).getRequest().getExtendedName() + ",0)"+CR;
-			}else{ 
-				initCommand+= "," + cmdName + "(this," + ((TMLSendRequest)currElem).getRequest().getExtendedName() + ",new Parameter<ParamType>(";
-				for(int i=0; i<3; i++) {
-					if (i!=0) initCommand += ",";
-					if (((TMLSendRequest)currElem).getParam(i) == null) {
-						initCommand += "0";
-					} else {
-						if (((TMLSendRequest)currElem).getParam(i).length() > 0) {
-							initCommand += ((TMLSendRequest)currElem).getParam(i);
-						} else {
-							initCommand += "0";
-						}
-					}
-				}
-				initCommand+="))"+CR;
-			}
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;	
-	
-		} else if (currElem instanceof TMLWaitEvent){
-			System.out.println("Checking Wait\n");
-			cmdName= "_wait" + currElem.getID();
-			hcode+="TMLWaitCommand " + cmdName + SCCR;
-			if (((TMLWaitEvent)currElem).getNbOfParams()==0){
-				initCommand+= "," + cmdName + "(this," + ((TMLWaitEvent)currElem).getEvent().getExtendedName() + ",0)"+CR;
-			}else{ 
-				initCommand+= "," + cmdName + "(this," + ((TMLWaitEvent)currElem).getEvent().getExtendedName() + ",new Parameter<ParamType>(";
-				for(int i=0; i<3; i++) {
-					if (i!=0) initCommand += ",";
-					if (((TMLWaitEvent)currElem).getParam(i) == null) {
-						initCommand += "0";
-					} else {
-						if (((TMLWaitEvent)currElem).getParam(i).length() > 0) {
-							initCommand += ((TMLWaitEvent)currElem).getParam(i);
-						} else {
-							initCommand += "0";
-						}
-					}
-				}
-				initCommand+="))"+CR;
-			}
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
-		
-		} else if (currElem instanceof TMLNotifiedEvent){
-			System.out.println("Checking Notified\n");
-			cmdName= "_notified" + currElem.getID();
-			hcode+="TMLNotifiedCommand " + cmdName + SCCR;
-			initCommand+= "," + cmdName + "(this," + ((TMLNotifiedEvent)currElem).getEvent().getExtendedName() + ",(TMLLength*)&" + ((TMLNotifiedEvent)currElem).getVariable() +",\"" + ((TMLNotifiedEvent)currElem).getVariable() + "\")" + CR;
-			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR; 
-		
-		} else if (currElem instanceof TMLSequence){
-			TMLSequence tmlseq = (TMLSequence)currElem;
-			System.out.println("Checking Sequence with "+ tmlseq.getNbNext()+ " elements.");
-			if (tmlseq.getNbNext() == 0) {
-				//if (lastSequence!=null) return makeCommands(lastSequence, false,retElement,nextCommandCont,functionCont,null);
-                		return retElement;
-            		} else {
-                		if (tmlseq.getNbNext() == 1) {
-                    			return makeCommands(currElem.getNextElement(0), false,retElement,nextCommandCont,functionCont,lastSequence);
-                		} else {			
-					String nextBranch;
-					tmlseq.sortNexts();
-					System.out.println("Checking Sequence branch "+ (tmlseq.getNbNext()-1));
-					nextBranch= makeCommands(currElem.getNextElement(currElem.getNbNext() - 1),false,retElement,null,null,null);
-					for(int i=currElem.getNbNext() - 2; i>=0; i--) {
-						System.out.println("Checking Sequence branch "+ i);
-						nextBranch=makeCommands(currElem.getNextElement(i),false,nextBranch,null,null,null);
-					}
-					//nextBranch=makeCommands(currElem.getNextElement(0),false,nextBranch,nextCommandCont,functionCont,null);
-                    			return nextBranch;
-					//int index = tmlseq.getCurrIndex(lastSequence);
-					//if (index==tmlseq.getNbNext()-1) return makeCommands(currElem.getNextElement(index), false,retElement,nextCommandCont,functionCont,tmlseq.getLastSequence());
-					//return makeCommands(currElem.getNextElement(index), false,retElement,nextCommandCont,functionCont,currElem);
-                		}
-            		}
-		
-		} else if (currElem instanceof TMLChoice){
-			int returnIndex=0;
-			cmdName= "_choice" + currElem.getID();
-			TMLChoice choice = (TMLChoice)currElem;
-			String code = "", nextCommandTemp="", MCResult="";
-			System.out.println("Checking Choicet\n");
-			if (choice.getNbGuard() !=0 ) {
-				
-				String guardS = "",code2;
-				int index1 = choice.getElseGuard(), index2 = choice.getAfterGuard();
-				int nb = choice.nbOfNonDeterministicGuard();
-				int nbS = choice.nbOfStochasticGuard();
-				if ((nb > 0) || (nbS > 0)){
-					code += "rnd__0 = myrand(0, 99)" + SCCR;
-				}
-				nb = 0;
-				for(int i=0; i<choice.getNbGuard(); i++) {
-					if (choice.isNonDeterministicGuard(i)) {
-						code2 = "(rnd__0 < " + Math.floor(100/choice.getNbGuard())*(nb+1) + ")";
-						nb ++;
-					} else if (choice.isStochasticGuard(i)) {
-						if (guardS.length() == 0) {
-							guardS = choice.getStochasticGuard(i);
-						} else {
-							guardS = "(" + guardS + ")+(" + choice.getStochasticGuard(i) + ")";
-						}
-						code2 = "(rnd__0 < (" + guardS + "))";
-								nbS ++;
-					} else {
-						code2 = choice.getGuard(i);
-						code2 = Conversion.replaceAllChar(code2, '[', "(");
-						code2 = Conversion.replaceAllChar(code2, ']', ")");
-					}
-					//System.out.println("guard = " + code1 + " i=" + i);
-					if (i != index2) {
-						if (i==0) {
-							code += "if " + code2;
-						} else {
-							code += " else ";
-							if (i != index1) {
-								code += "if " + code2;
-							}
-						}
-						if (nextCommandCont==null){
-							strwrap nextCommandCollection = new strwrap("",returnIndex), functionCollection = new strwrap("");
-							//nextCommandCollection = new strwrap("",returnIndex); functionCollection = new strwrap("");
-							//System.out.println("Call makeCommands, task: "+reference);
-							if (nextCommandCollection==null) System.out.println("Choice: nextCommandCollection==0");
-							MCResult = makeCommands(currElem.getNextElement(i), false, retElement,nextCommandCollection,functionCollection,lastSequence);
-							if (functionCollection.str.isEmpty()){
-								System.out.println("NO content has been added to "+ code2);
-								code += "{\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\nreturn " + returnIndex + SCCR +"}" + CR;
-								commentText+="_comment[" + commentNum + "]=std::string(\"Branch taken: " + code2 + "\");\n";
-								commentNum++;
-								System.out.println("RETURN, aaINC NUM "+ returnIndex);
-								returnIndex++;
-								nextCommandTemp+= ",(TMLCommand*)" + MCResult;
-							}else{
-								System.out.println("OLD RETURN INDEX "+ returnIndex);
-								returnIndex = nextCommandCollection.num;
-								//System.out.println("Returned index: "+ returnIndex);
-								System.out.println("Choice: Content has been added to "+ code2);
-								code += "{\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\n" + functionCollection.str + "return " + returnIndex + ";\n}" + CR;
-								commentText+="_comment[" + commentNum + "]=std::string(\"Branch taken: " + code2 + "\");\n";
-								commentNum++;
-								//returnIndex = nextCommandCollection.num;
-								System.out.println("RETURN, bbINC NUM "+ returnIndex);
-								returnIndex++;
-								nextCommandTemp+= nextCommandCollection.str+ ",(TMLCommand*)" + MCResult;
-							}
-						}else{
-							System.out.println("Choice: Next command!=0 "+ code2);
-							int oldReturnIndex=nextCommandCont.num;
-							functionCont.str += code + "{\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\n";
-							commentText+="_comment[" + commentNum + "]=std::string(\"Branch taken: " + code2 + "\");\n";
-							commentNum++;
-							MCResult = makeCommands(currElem.getNextElement(i), false, retElement, nextCommandCont,functionCont,lastSequence);
-							if (oldReturnIndex==nextCommandCont.num){
-								System.out.println("RETURN, ccINC NUM "+ nextCommandCont.num);
-								functionCont.str+= "return " + nextCommandCont.num + SCCR;
-								nextCommandCont.num++;
-								nextCommandCont.str += ",(TMLCommand*)" + MCResult;
-							}
-							functionCont.str+= "}\n";
-							code="";
-						}
-					} 
-				}
-				// If there was no else, do a terminate
-				if (nextCommandCont==null){
-					System.out.println("Choice: finalization, add new command\n");
-					if (index1 == -1){
-						code += "addComment(new Comment(_endLastTransaction,0," + commentNum + "));\nreturn " + returnIndex + SCCR;
-						commentText+="_comment[" + commentNum + "]=std::string(\"Exit branch taken\");\n";
-						commentNum++;
-						nextCommand= cmdName + ".setNextCommand(array(" + (returnIndex+1) + nextCommandTemp + ",(TMLCommand*)0))" + SCCR;
-					}else{
-						nextCommand= cmdName + ".setNextCommand(array(" + returnIndex + nextCommandTemp + "))" + SCCR;
-					}
-					hcode+="TMLChoiceCommand " + cmdName + SCCR;
-					initCommand+= "," + cmdName + "(this,(CondFuncPointer)&" + reference + "::" + cmdName + "_func)"+CR;
-					functions+="unsigned int "+ reference + "::" + cmdName + "_func(){" + CR + code +CR+ "}" + CR2;
-					functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
-				}else{
-					System.out.println("Choice: finalization, No new command\n");
-					if (index1 == -1){
-						functionCont.str += "addComment(new Comment(_endLastTransaction,0," + commentNum + "));\nreturn " + nextCommandCont.num + SCCR;
-						commentText+="_comment[" + commentNum + "]=std::string(\"Exit branch taken\");\n";
-						commentNum++;
-						nextCommandCont.str += ",(TMLCommand*)0";
-						System.out.println("RETURN, ddINC NUM "+ nextCommandCont.num);
-						nextCommandCont.num++;
-					}
-					cmdName=MCResult;
-				}
-			}
-					
-		} else if (currElem instanceof TMLSelectEvt){
-			TMLEvent evt;
-			Integer nbevt=0;
-			String evtList="",paramList="";
-			System.out.println("Checking SelectEvt\n");
-			cmdName= "_select" + currElem.getID();
-			for(int i=0; i<currElem.getNbNext(); i++) {
-				evt=((TMLSelectEvt)currElem).getEvent(i);
-				if (evt!=null){
-					nbevt++;	
-					evtList += ",(TMLEventChannel*)"+ evt.getExtendedName();
-					//paramList+=",0";
-					if (evt.getNbOfParams()==0) {
-						paramList+=",(Parameter<ParamType>*)0";
-					}else{
-						paramList+=",new Parameter<ParamType>(";
-						for(int j=0; j<3; j++) {
-							if (j!=0) paramList += ",";
-							if (((TMLSelectEvt)currElem).getParam(i,j) == null) {
-								paramList += "0";
-							} else {
-								if (((TMLSelectEvt)currElem).getParam(i,j).length() > 0) {
-									paramList += ((TMLSelectEvt)currElem).getParam(i,j);
-								} else {
-									paramList += "0";
-								}
-							}
-						}
-						paramList+=")";
-					}
-					nextCommand+= ",(TMLCommand*)" + makeCommands(currElem.getNextElement(i), true, retElement,null,null,lastSequence); 
-				}
-			}
-			hcode+="TMLSelectCommand " + cmdName + SCCR;
-			//initCommand+= "," + cmdName + "(this,array("+ nbevt + evtList + "),"+ nbevt + ",0)"+CR;
-			initCommand+= "," + cmdName + "(this,array("+ nbevt + evtList + "),"+ nbevt + ",array("+ nbevt + paramList + "))"+CR;
-			nextCommand=cmdName + ".setNextCommand(array(" + nbevt + nextCommand + "))" + SCCR;
-		
-		} else {
-			System.out.println("Operator: " + currElem + " is not managed in SystemC" + "))" + SCCR);
-		}
-		chaining+=nextCommand; 
-		return (cmdName.equals("0") || cmdName.charAt(0)=='&')? cmdName : "&"+cmdName;
-	}
-	
-	
-	public String makeCommandLenFunc(String cmdName, String lowerLimit, String upperLimit){
-		if (upperLimit==null)
-			functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\nreturn (unsigned int)(" + lowerLimit + ");\n}" + CR2;
-		else
-			functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\nreturn (unsigned int)myrand(" + lowerLimit + "," + upperLimit + ");\n}" + CR2;
-		functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
-		return "(LengthFuncPointer)&" + reference + "::" + cmdName + "_func";
-	}
-
-	
-/*public String makeChoice(TMLActivityElement currElem){
-		TMLChoice choice = (TMLChoice)currElem;
-		//System.out.println("nb of guards = " + choice.getNbGuard() + " nb of nexts =" + choice.getNbNext());
-		String code = "";
-		if (choice.getNbGuard() !=0 ) {
-			String code1 = "",guardS = "",code2;
-			int index1 = choice.getElseGuard(), index2 = choice.getAfterGuard();
-			int nb = choice.nbOfNonDeterministicGuard();
-			int nbS = choice.nbOfStochasticGuard();
-			if ((nb > 0) || (nbS > 0)){
-				code += "rnd__0 = myrand(0, 99)" + SCCR;
-			}
-			nb = 0;
-			for(int i=0; i<choice.getNbGuard(); i++) {
-				if (choice.isNonDeterministicGuard(i)) {
-					code2 = "(rnd__0 < " + Math.floor(100/choice.getNbGuard())*(nb+1) + ")";
-					nb ++;
-				} else if (choice.isStochasticGuard(i)) {
-					if (guardS.length() == 0) {
-						guardS = choice.getStochasticGuard(i);
-					} else {
-						guardS = "(" + guardS + ")+(" + choice.getStochasticGuard(i) + ")";
-					}
-					code2 = "(rnd__0 < (" + guardS + "))";
-							nbS ++;
-				} else {
-					code2 = choice.getGuard(i);
-					code2 = Conversion.replaceAllChar(code2, '[', "(");
-					code2 = Conversion.replaceAllChar(code2, ']', ")");
-				}
-				//System.out.println("guard = " + code1 + " i=" + i);
-				if (i != index2) {
-					if (i==0) {
-						code += "if " + code2;
-					} else {
-						code += " else ";
-						if (i != index1) {
-							code += "if " + code2;
-						}
-					}
-					code += "{\naddComment(new Comment(_endLastTransaction,\"Branch taken: " + code2 + "\"));\nreturn "+ i + SCCR +"}" + CR;
-				} 
-			}
-			// If there was no else, do a terminate
-			if (index1 == -1)  code += "addComment(new Comment(_endLastTransaction,\"Exit branch taken\"));\nreturn " + choice.getNbGuard() + SCCR;
-			code += code1;
-		}
-		return code;
-	}*/
-	
-	public void makeEndClassH() {
-		hcode += "};" + CR + "#endif" + CR;
-	}
-
-	
-	private String makeAttributesCode() {
-        String code = "";
-        TMLAttribute att;
-        int i;
-        
-        ListIterator iterator = task.getAttributes().listIterator();
-        
-        while(iterator.hasNext()) {
-            att = (TMLAttribute)(iterator.next());
-            if (att.hasInitialValue())
-                code += ","+ att.name + "(" + att.initialValue + ")"+CR;
-            else
-		code += ","+ att.name + "(0)"+CR;
-	}	
-        return code;
-    }
-	
-	private String makeAttributesDeclaration() {
-        String code = "";
-        TMLAttribute att;
-        int i;
-        
-        ListIterator iterator = task.getAttributes().listIterator();
-        
-        while(iterator.hasNext()) {
-            att = (TMLAttribute)(iterator.next());
-            //code += TMLType.getStringType(att.type.getType()) + " " + att.name;
-		code += "int " + att.name;
-            code += ";\n";
-        }
-        
-	// Attributes for events
-	//code += "unsigned int arg__evt0" + SCCR;
-	//code += "unsigned int arg__evt1" + SCCR;
-	//code += "unsigned int arg__evt2" + SCCR;	
-		
-	//Adding request arguments
-        //if (task.isRequested()) {
-	//		code += "unsigned int arg1__req" + SCCR;
-	//		code += "unsigned int arg2__req" + SCCR;
-	//		code += "unsigned int arg3__req" + SCCR;	
-        //}
-		
-	code += "int rnd__0" + SCCR;
-	//if (commentNum!=0) code+= "std::string _comment[" + commentNum + "]" + SCCR;	
-        return code;
-    }
-	
-
-    public String addSemicolonIfNecessary(String _input) {
-        String code1 = _input.trim();
-        if (!(code1.endsWith(";"))) {
-            code1 += ";";
-        }
-        return code1;
-    }
-
-    public String modifyString(String _input) {
-        //System.out.println("Modify string=" + _input);
-        _input = Conversion.changeBinaryOperatorWithUnary(_input, "div", "/");
-        _input = Conversion.changeBinaryOperatorWithUnary(_input, "mod", "%");
-        //System.out.println("Modified string=" + _input);
-        return _input;
-    }
-      
-}
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+ *
+ * ludovic.apvrille AT enst.fr
+ *
+ * This software is a computer program whose purpose is to allow the
+ * edition of TURTLE analysis, design and deployment diagrams, to
+ * allow the generation of RT-LOTOS or Java code from this diagram,
+ * and at last to allow the analysis of formal validation traces
+ * obtained from external tools, e.g. RTL from LAAS-CNRS and CADP
+ * from INRIA Rhone-Alpes.
+ *
+ * This software is governed by the CeCILL  license under French law and
+ * abiding by the rules of distribution of free software.  You can  use,
+ * modify and/ or redistribute the software under the terms of the CeCILL
+ * license as circulated by CEA, CNRS and INRIA at the following URL
+ * "http://www.cecill.info".
+ *
+ * As a counterpart to the access to the source code and  rights to copy,
+ * modify and redistribute granted by the license, users are provided only
+ * with a limited warranty  and the software's author,  the holder of the
+ * economic rights,  and the successive licensors  have only  limited
+ * liability.
+ *
+ * In this respect, the user's attention is drawn to the risks associated
+ * with loading,  using,  modifying and/or developing or reproducing the
+ * software by the user in light of its specific status of free software,
+ * that may mean  that it is complicated to manipulate,  and  that  also
+ * therefore means  that it is reserved for developers  and  experienced
+ * professionals having in-depth computer knowledge. Users are therefore
+ * encouraged to load and test the software's suitability as regards their
+ * requirements in conditions enabling the security of their systems and/or
+ * data to be ensured and,  more generally, to use and operate it in the
+ * same conditions as regards security.
+ *
+ * The fact that you are presently reading this means that you have had
+ * knowledge of the CeCILL license and that you accept its terms.
+ *
+ * /**
+ * Class MappedSystemCTask
+ * Creation: 24/11/2005
+ * @version 1.0 24/11/2005
+ * @author Ludovic APVRILLE
+ * @see
+ */
+
+package tmltranslator.tomappingsystemc2;
+
+import java.util.*;
+
+import tmltranslator.*;
+import myutil.*;
+
+
+public class MappedSystemCTask {
+	//private TMLModeling tmlm;
+	private TMLTask task;
+ 	private String reference, cppcode, hcode, initCommand, functions, functionSig, chaining, firstCommand, commentText;
+	private ArrayList<TMLChannel> channels;
+	private ArrayList<TMLEvent> events;
+	private ArrayList<TMLRequest> requests;
+	private int commentNum;
+	private boolean debug;
+	
+	private final static String DOTH = ".h";
+	private final static String DOTCPP = ".cpp";
+	private final static String SYSTEM_INCLUDE = "#include \"systemc.h\"";
+	private final static String CR = "\n";
+	private final static String CR2 = "\n\n";
+	private final static String SCCR = ";\n";
+	private final static String EFCR = "}\n";
+	private final static String EFCR2 = "}\n\n";
+	private final static String EF = "}";
+	
+	
+	public MappedSystemCTask(TMLTask _task, ArrayList<TMLChannel> _channels, ArrayList<TMLEvent> _events, ArrayList<TMLRequest> _requests) {
+        	task = _task;
+		channels = _channels;
+		events = _events;
+		requests = _requests;
+        	reference = task.getName();
+		cppcode = "";
+		hcode = "";
+		initCommand="";
+		functions="";
+		chaining="";
+		firstCommand="";
+		functionSig="";
+		commentText="";
+		commentNum=0;
+    	}
+	
+	public void saveInFiles(String path) throws FileException {	
+		FileUtils.saveFile(path + reference + DOTH, getHCode());
+		FileUtils.saveFile(path + reference + DOTCPP, getCPPCode());
+	}
+	
+	public TMLTask getTMLTask() {
+		return task;
+	}
+    
+	public void generateSystemC(boolean _debug) {
+        	debug = _debug;
+		//basicHCode();
+		basicCPPCode();
+		makeClassCode();
+    	}
+	
+	public void print() {
+		System.out.println("task: " + reference + DOTH + hcode);
+		System.out.println("task: " + reference + DOTCPP + cppcode);
+	}
+	
+	
+	public String getCPPCode() {
+		return cppcode;
+	}
+	
+	public String getHCode() {
+		return hcode;
+	}
+	
+	public String getReference() {
+		return reference;
+	}
+	
+	// H-Code
+	private String basicHCode() {
+		String code="";
+		code += "#ifndef " + reference.toUpperCase() + "__H" + CR;
+		code += "#define " + reference.toUpperCase() + "__H" + CR2;
+		code += "#include <TMLTask.h>\n#include <definitions.h>\n\n";
+		code += "#include <TMLbrbwChannel.h>\n#include <TMLbrnbwChannel.h>\n#include <TMLnbrnbwChannel.h>\n\n";
+		code += "#include <TMLEventBChannel.h>\n#include <TMLEventFChannel.h>\n#include <TMLEventFBChannel.h>\n\n";
+		code += "#include <TMLActionCommand.h>\n#include <TMLChoiceCommand.h>\n#include <TMLExeciCommand.h>\n";
+		code += "#include <TMLSelectCommand.h>\n#include <TMLReadCommand.h>\n#include <TMLNotifiedCommand.h>\n";
+		code += "#include <TMLRequestCommand.h>\n#include <TMLSendCommand.h>\n#include <TMLWaitCommand.h>\n";
+		code += "#include <TMLWriteCommand.h>\n\n";
+		return code;
+	}
+	
+	private void classHCode() {
+	}
+	
+	// CPP Code
+	private void basicCPPCode() {
+		cppcode += "#include <" + reference + DOTH + ">" + CR2;
+	}
+	
+	private void makeClassCode(){
+		makeHeaderClassH();
+		makeEndClassH();
+		
+		cppcode+=reference+ "::" + makeConstructorSignature()+":TMLTask(iPriority,iName,iCPU)"+ CR + makeAttributesCode();
+		cppcode+=initCommand + CR + "{" + CR; 
+		if (commentNum!=0) cppcode+= "_comment = new std::string[" + commentNum + "]" + SCCR + commentText + CR;
+		cppcode+= "//set blocked read task/set blocked write task"+ CR;
+		for(TMLChannel ch: channels) {
+			if (ch.getOriginTask()==task)
+				cppcode+=ch.getExtendedName() + "->setBlockedWriteTask(this)"+SCCR;
+			else
+				cppcode+=ch.getExtendedName() + "->setBlockedReadTask(this)"+SCCR;
+		}
+		for(TMLEvent evt: events) {
+			if (evt.getOriginTask()==task)
+				cppcode+=evt.getExtendedName() + "->setBlockedWriteTask(this)"+SCCR;
+			else
+				cppcode+=evt.getExtendedName() + "->setBlockedReadTask(this)"+SCCR;
+		}
+		if (task.isRequested()) cppcode+="requestChannel->setBlockedReadTask(this)" +SCCR;
+		for(TMLRequest req: requests) {
+			if (req.isAnOriginTask(task)) cppcode+=req.getExtendedName() + "->setBlockedWriteTask(this)" +SCCR;
+		}
+		cppcode+=CR + "//command chaining"+ CR;
+		cppcode+= chaining + "_currCommand=" + firstCommand + SCCR; 
+		if (!firstCommand.equals("0")) cppcode+= "_currCommand->prepare()"+SCCR;
+		cppcode+="}"+ CR2 + functions; // + makeDestructor();
+		hcode = Conversion.indentString(hcode, 4);
+		cppcode = Conversion.indentString(cppcode, 4);
+	}
+	
+	private String makeDestructor(){
+		String dest=reference + "::~" + reference + "(){" + CR;
+		if (commentNum!=0) dest+="delete[] _comment" + SCCR;
+		return dest+"}"+CR;
+	}
+
+	private String makeConstructorSignature(){
+		String constSig=reference+ "(unsigned int iPriority, std::string iName, CPU* iCPU"+CR;
+		for(TMLChannel ch: channels) {
+			constSig+=", TMLChannel* "+ ch.getExtendedName() + CR;
+		}
+		for(TMLEvent evt: events) {
+			constSig+=", TMLEventChannel* "+ evt.getExtendedName() +CR;
+		}
+		for(TMLRequest req: requests) {
+			if (req.isAnOriginTask(task)) constSig+=", TMLEventBChannel* " + req.getExtendedName() + CR;
+		}
+		if (task.isRequested()){
+			constSig+=", TMLEventBChannel* requestChannel"+CR;
+		}
+		return constSig+")";
+	}
+
+	private void makeHeaderClassH() {
+		String hcodeBegin="";
+		// Common dec
+		hcodeBegin = "class " + reference + ": public TMLTask {" + CR;
+		hcodeBegin += "private:" + CR;
+		
+		// Attributes
+		hcodeBegin += "// Attributes" + CR;
+		//hcodeBegin += makeAttributesDeclaration() + CR;
+		
+		if (task.isRequested()) {
+			int params = task.getRequest().getNbOfParams();
+			firstCommand="_waitOnRequest";
+			hcode+="TMLWaitCommand " + firstCommand + SCCR;
+			initCommand+= "," + firstCommand + "(this,requestChannel,"; 
+			if (params==0){
+				initCommand+= "0)" + CR;
+			}else{
+				initCommand+= "new Parameter<ParamType>(arg1__req,";
+				if (params>1) initCommand+= "arg2__req,"; else  initCommand+= "0,";
+				if (params>2) initCommand+= "arg3__req))\n"; else  initCommand+= "0))\n";
+			}	
+			//"arg2__req,arg3__req))" + CR;	
+			String xx = firstCommand + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(task.getActivityDiagram().getFirst(),false,"&"+firstCommand,null,null,null) + "))"+ SCCR;
+			firstCommand="&"+firstCommand;
+			chaining+=xx;
+		}else{
+			firstCommand=makeCommands(task.getActivityDiagram().getFirst(),false,"0",null,null,null);
+		}
+
+		hcode = basicHCode() + hcodeBegin + makeAttributesDeclaration() + CR + hcode;
+		// public dec
+		hcode += CR + functionSig + CR + "public:" + CR;
+		// Simulation
+		hcode += makeConstructorSignature() + SCCR; // + "~" + reference + "()" + SCCR;
+		makeSerializableFuncs();
+	}
+
+	private void makeSerializableFuncs(){
+		ListIterator iterator = task.getAttributes().listIterator();
+		TMLAttribute att;
+		hcode += "virtual std::istream& readObject(std::istream& s)" + SCCR;
+		hcode += "virtual std::ostream& writeObject(std::ostream& s)" + SCCR;
+		functions+= "std::istream& " + reference + "::" + "readObject(std::istream& s){\nTMLTask::readObject(s);\n";
+		while(iterator.hasNext()) {
+			att = (TMLAttribute)(iterator.next());
+			functions += "READ_STREAM(s," + att.name + ")" + SCCR;
+		}
+		functions+= "return s;\n}\n\n";
+		functions+= "std::ostream& " + reference + "::" + "writeObject(std::ostream& s){\nTMLTask::writeObject(s);\n";
+		iterator = task.getAttributes().listIterator();
+		while(iterator.hasNext()) {
+			att = (TMLAttribute)(iterator.next());
+			functions += "WRITE_STREAM(s," + att.name + ")" + SCCR;
+		}
+		functions+= "return s;\n}\n\n";
+	}
+
+	private String makeCommands(TMLActivityElement currElem, boolean skip, String retElement, strwrap nextCommandCont, strwrap functionCont, TMLActivityElement lastSequence){
+		String nextCommand="",cmdName="";
+
+		if (skip) return makeCommands(currElem.getNextElement(0), false,retElement,nextCommandCont,functionCont,lastSequence);
+
+		if (currElem==null){
+			if (debug) System.out.println("Checking null\n");
+			return retElement;
+		}
+		
+		if (debug) System.out.println("Checking " + currElem.getName() + CR);
+
+		if (currElem instanceof TMLStartState) {
+			if (debug) System.out.println("Checking Start\n");
+			return makeCommands(currElem.getNextElement(0), false,retElement,nextCommandCont,functionCont,lastSequence);
+		
+		} else if (currElem instanceof TMLStopState){
+			if (debug) System.out.println("Checking Stop\n");
+			return retElement;
+		
+		} else if (currElem instanceof TMLActionState || currElem instanceof TMLRandom){
+			String action;
+			if (currElem instanceof TMLActionState){				
+				if (debug) System.out.println("Checking Action\n");
+				action = ((TMLActionState)currElem).getAction();
+			}else{
+				if (debug) System.out.println("Checking Random\n");
+				TMLRandom random = (TMLRandom)currElem;
+				action = random.getVariable() + "=myrand("+ random.getMinValue() + "," + random.getMaxValue() + ")";
+			}
+			cmdName= "_action" + currElem.getID();
+			if (nextCommandCont==null){
+				//System.out.println("nextCommandCont==null in ActionState "+ action +CR);
+				hcode+="TMLActionCommand " + cmdName + SCCR;
+				strwrap nextCommandCollection = new strwrap(""), functionCollection = new strwrap("");
+				//nextCommandCollection = new strwrap(""); functionCollection = new strwrap("");
+				initCommand+= "," + cmdName + "(this,(ActionFuncPointer)&" + reference + "::" + cmdName + "_func)"+CR;
+				String MKResult = makeCommands(currElem.getNextElement(0),false,retElement,nextCommandCollection,functionCollection,lastSequence);
+				if(nextCommandCollection.num==0){
+					nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + MKResult + "));\n";
+				}else{	
+					nextCommand= cmdName + ".setNextCommand(array(" + nextCommandCollection.num + nextCommandCollection.str + "));\n";
+				}
+				functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\n" + modifyString(addSemicolonIfNecessary(action)) + CR + functionCollection.str + "}" + CR2;
+				commentText+="_comment[" + commentNum + "]=std::string(\"Action " + action + "\");\n";
+				commentNum++;
+				functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
+			}else{
+				//System.out.println("nextCommandCont!=null in ActionState "+ action +CR); 
+				functionCont.str += "addComment(new Comment(_endLastTransaction,0," + commentNum + "));\n" + modifyString(addSemicolonIfNecessary(action)) + CR;
+				commentText+="_comment[" + commentNum + "]=std::string(\"Action " + action + "\");\n";
+				commentNum++;
+				return makeCommands(currElem.getNextElement(0),false,retElement,nextCommandCont,functionCont,lastSequence);
+			}
+
+
+		} else if (currElem instanceof TMLExecI){
+			if (debug) System.out.println("Checking Execi\n");
+			cmdName= "_execi" + currElem.getID();
+			hcode+="TMLExeciCommand " + cmdName + SCCR;
+			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecI)currElem).getAction() + ",0,0)"+CR;
+			initCommand+= "," + cmdName + "(this," + makeCommandLenFunc(cmdName, ((TMLExecI)currElem).getAction(), null) + ",0)" + CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+
+		} else if (currElem instanceof TMLExecC){
+			if (debug) System.out.println("Checking ExecC\n");
+			cmdName= "_execc" + currElem.getID();
+			hcode+="TMLExeciCommand " + cmdName + SCCR;
+			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecI)currElem).getAction() + ",1)"+CR;
+			initCommand+= "," + cmdName + "(this,"+ makeCommandLenFunc(cmdName, ((TMLExecI)currElem).getAction(), null) + ",1)"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLExecIInterval){
+			if (debug) System.out.println("Checking ExeciInterv\n");
+			cmdName= "_execi" + currElem.getID();
+			hcode+="TMLExeciCommand " + cmdName + SCCR;
+			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecIInterval)currElem).getMinDelay()+ "," + ((TMLExecIInterval)currElem).getMaxDelay() + ",0)"+CR;
+			initCommand+= "," + cmdName + "(this,"+ makeCommandLenFunc(cmdName, ((TMLExecIInterval)currElem).getMinDelay(), ((TMLExecIInterval)currElem).getMaxDelay()) + ",0)"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+
+		} else if (currElem instanceof TMLExecCInterval){
+			if (debug) System.out.println("Checking ExecCInterv\n");
+			cmdName= "_execc" + currElem.getID();
+			hcode+="TMLExeciCommand " + cmdName + SCCR;
+			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecIInterval)currElem).getMinDelay()+ "," + ((TMLExecIInterval)currElem).getMaxDelay() + ",1)"+CR;
+			initCommand+= "," + cmdName + "(this,"+ makeCommandLenFunc(cmdName, ((TMLExecIInterval)currElem).getMinDelay(), ((TMLExecIInterval)currElem).getMaxDelay()) + ",1)"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+
+					
+		} else if (currElem instanceof TMLForLoop){
+			if (debug) System.out.println("Checking Loop\n");
+			TMLForLoop fl = (TMLForLoop)currElem;
+			cmdName="_choice" + currElem.getID();
+			hcode+="TMLChoiceCommand " + cmdName + SCCR;
+			initCommand+= "," + cmdName + "(this,(CondFuncPointer)&" + reference + "::" + cmdName + "_func)"+CR;
+			functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\nstatic bool firstTime=true;\nif(firstTime){\nfirstTime=false;\n" + addSemicolonIfNecessary(((TMLForLoop)currElem).getInit()) + "\n}else{\n" + addSemicolonIfNecessary(((TMLForLoop)currElem).getIncrement()) + "\n}\nif(" + ((TMLForLoop)currElem).getCondition() + "){\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\nreturn 0;\n}else{\naddComment(new Comment(_endLastTransaction,0," + (commentNum+1) + "));\nfirstTime=true;\nreturn 1;\n}\n}\n\n";
+			commentText+="_comment[" + commentNum + "]=std::string(\"" + ((TMLForLoop)currElem).getCondition() + "=true\");\n";
+			commentNum++;
+			commentText+="_comment[" + commentNum + "]=std::string(\"Exit loop: " + ((TMLForLoop)currElem).getCondition() + "=false\");\n";
+			commentNum++;
+			functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
+			nextCommand= cmdName + ".setNextCommand(array(2,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,"&"+cmdName,null,null,null) + ",(TMLCommand*)" + makeCommands(currElem.getNextElement(1),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLReadChannel){
+			if (debug) System.out.println("Checking Read\n");
+			cmdName= "_read" + currElem.getID();
+			hcode+="TMLReadCommand " + cmdName + SCCR;
+			TMLReadChannel rCommand=(TMLReadChannel)currElem;
+			//initCommand+= "," + cmdName + "(this," + rCommand.getNbOfSamples() + "*" + rCommand.getChannel().getSize() + "," + rCommand.getChannel().getExtendedName() + ")"+CR;
+			initCommand+= "," + cmdName + "(this," + makeCommandLenFunc(cmdName, rCommand.getChannel().getSize() + "*(" + rCommand.getNbOfSamples()+")",null) + "," + rCommand.getChannel().getExtendedName() + ")"+CR;
+			//initCommand+= "," + cmdName + "(this," + rCommand.getNbOfSamples() + "," + rCommand.getChannel().getExtendedName() + ")"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLWriteChannel){
+			if (debug) System.out.println("Checking Write\n");
+			cmdName= "_write" + currElem.getID();
+			hcode+="TMLWriteCommand " + cmdName + SCCR;
+			TMLWriteChannel wCommand=(TMLWriteChannel)currElem;
+			//initCommand+= "," + cmdName + "(this," + wCommand.getNbOfSamples() + "*" + wCommand.getChannel().getSize() + "," + wCommand.getChannel().getExtendedName() + ")"+CR;
+			initCommand+= "," + cmdName + "(this," + makeCommandLenFunc(cmdName, wCommand.getChannel().getSize() + "*(" + wCommand.getNbOfSamples() + ")", null) + "," + wCommand.getChannel().getExtendedName() + ")"+CR;
+			//initCommand+= "," + cmdName + "(this," + wCommand.getNbOfSamples() + "," + wCommand.getChannel().getExtendedName() + ")"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLSendEvent){
+			if (debug) System.out.println("Checking Send\n");
+			cmdName= "_send" + currElem.getID();
+			hcode+="TMLSendCommand " + cmdName + SCCR;
+			if (((TMLSendEvent)currElem).getNbOfParams()==0){
+				initCommand+= "," + cmdName + "(this," + ((TMLSendEvent)currElem).getEvent().getExtendedName() + ",0)"+CR;
+			}else{ 
+				initCommand+= "," + cmdName + "(this," + ((TMLSendEvent)currElem).getEvent().getExtendedName() + ",new Parameter<ParamType>(";
+				for(int i=0; i<3; i++) {
+					if (i!=0) initCommand += ",";
+					if (((TMLSendEvent)currElem).getParam(i) == null) {
+						initCommand += "0";
+					} else {
+						if (((TMLSendEvent)currElem).getParam(i).length() > 0) {
+							initCommand += ((TMLSendEvent)currElem).getParam(i);
+						} else {
+							initCommand += "0";
+						}
+					}
+            			}
+				initCommand+="))"+CR;
+			}
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+			
+		} else if (currElem instanceof TMLSendRequest){
+			if (debug) System.out.println("Checking Request\n");
+			cmdName= "_request" + currElem.getID();
+			hcode+="TMLRequestCommand " + cmdName + SCCR;
+			if (((TMLSendRequest)currElem).getNbOfParams()==0){
+				initCommand+= "," + cmdName + "(this," + ((TMLSendRequest)currElem).getRequest().getExtendedName() + ",0)"+CR;
+			}else{ 
+				initCommand+= "," + cmdName + "(this," + ((TMLSendRequest)currElem).getRequest().getExtendedName() + ",new Parameter<ParamType>(";
+				for(int i=0; i<3; i++) {
+					if (i!=0) initCommand += ",";
+					if (((TMLSendRequest)currElem).getParam(i) == null) {
+						initCommand += "0";
+					} else {
+						if (((TMLSendRequest)currElem).getParam(i).length() > 0) {
+							initCommand += ((TMLSendRequest)currElem).getParam(i);
+						} else {
+							initCommand += "0";
+						}
+					}
+				}
+				initCommand+="))"+CR;
+			}
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;	
+	
+		} else if (currElem instanceof TMLWaitEvent){
+			if (debug) System.out.println("Checking Wait\n");
+			cmdName= "_wait" + currElem.getID();
+			hcode+="TMLWaitCommand " + cmdName + SCCR;
+			if (((TMLWaitEvent)currElem).getNbOfParams()==0){
+				initCommand+= "," + cmdName + "(this," + ((TMLWaitEvent)currElem).getEvent().getExtendedName() + ",0)"+CR;
+			}else{ 
+				initCommand+= "," + cmdName + "(this," + ((TMLWaitEvent)currElem).getEvent().getExtendedName() + ",new Parameter<ParamType>(";
+				for(int i=0; i<3; i++) {
+					if (i!=0) initCommand += ",";
+					if (((TMLWaitEvent)currElem).getParam(i) == null) {
+						initCommand += "0";
+					} else {
+						if (((TMLWaitEvent)currElem).getParam(i).length() > 0) {
+							initCommand += ((TMLWaitEvent)currElem).getParam(i);
+						} else {
+							initCommand += "0";
+						}
+					}
+				}
+				initCommand+="))"+CR;
+			}
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLNotifiedEvent){
+			if (debug) System.out.println("Checking Notified\n");
+			cmdName= "_notified" + currElem.getID();
+			hcode+="TMLNotifiedCommand " + cmdName + SCCR;
+			initCommand+= "," + cmdName + "(this," + ((TMLNotifiedEvent)currElem).getEvent().getExtendedName() + ",(TMLLength*)&" + ((TMLNotifiedEvent)currElem).getVariable() +",\"" + ((TMLNotifiedEvent)currElem).getVariable() + "\")" + CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null,null,lastSequence) + "))"+ SCCR; 
+		
+		} else if (currElem instanceof TMLSequence){
+			TMLSequence tmlseq = (TMLSequence)currElem;
+			if (debug) System.out.println("Checking Sequence with "+ tmlseq.getNbNext()+ " elements.");
+			if (tmlseq.getNbNext() == 0) {
+				//if (lastSequence!=null) return makeCommands(lastSequence, false,retElement,nextCommandCont,functionCont,null);
+                		return retElement;
+            		} else {
+                		if (tmlseq.getNbNext() == 1) {
+                    			return makeCommands(currElem.getNextElement(0), false,retElement,nextCommandCont,functionCont,lastSequence);
+                		} else {			
+					String nextBranch;
+					tmlseq.sortNexts();
+					if (debug) System.out.println("Checking Sequence branch "+ (tmlseq.getNbNext()-1));
+					nextBranch= makeCommands(currElem.getNextElement(currElem.getNbNext() - 1),false,retElement,null,null,null);
+					for(int i=currElem.getNbNext() - 2; i>=0; i--) {
+						if (debug) System.out.println("Checking Sequence branch "+ i);
+						nextBranch=makeCommands(currElem.getNextElement(i),false,nextBranch,null,null,null);
+					}
+					//nextBranch=makeCommands(currElem.getNextElement(0),false,nextBranch,nextCommandCont,functionCont,null);
+                    			return nextBranch;
+					//int index = tmlseq.getCurrIndex(lastSequence);
+					//if (index==tmlseq.getNbNext()-1) return makeCommands(currElem.getNextElement(index), false,retElement,nextCommandCont,functionCont,tmlseq.getLastSequence());
+					//return makeCommands(currElem.getNextElement(index), false,retElement,nextCommandCont,functionCont,currElem);
+                		}
+            		}
+		
+		} else if (currElem instanceof TMLChoice){
+			int returnIndex=0;
+			cmdName= "_choice" + currElem.getID();
+			TMLChoice choice = (TMLChoice)currElem;
+			String code = "", nextCommandTemp="", MCResult="";
+			if (debug) System.out.println("Checking Choice\n");
+			if (choice.getNbGuard() !=0 ) {
+				
+				String guardS = "",code2;
+				int index1 = choice.getElseGuard(), index2 = choice.getAfterGuard();
+				int nb = choice.nbOfNonDeterministicGuard();
+				int nbS = choice.nbOfStochasticGuard();
+				if ((nb > 0) || (nbS > 0)){
+					code += "rnd__0 = myrand(0, 99)" + SCCR;
+				}
+				nb = 0;
+				for(int i=0; i<choice.getNbGuard(); i++) {
+					if (choice.isNonDeterministicGuard(i)) {
+						code2 = "(rnd__0 < " + Math.floor(100/choice.getNbGuard())*(nb+1) + ")";
+						nb ++;
+					} else if (choice.isStochasticGuard(i)) {
+						if (guardS.length() == 0) {
+							guardS = choice.getStochasticGuard(i);
+						} else {
+							guardS = "(" + guardS + ")+(" + choice.getStochasticGuard(i) + ")";
+						}
+						code2 = "(rnd__0 < (" + guardS + "))";
+								nbS ++;
+					} else {
+						code2 = choice.getGuard(i);
+						code2 = Conversion.replaceAllChar(code2, '[', "(");
+						code2 = Conversion.replaceAllChar(code2, ']', ")");
+					}
+					//System.out.println("guard = " + code1 + " i=" + i);
+					if (i != index2) {
+						if (i==0) {
+							code += "if " + code2;
+						} else {
+							code += " else ";
+							if (i != index1) {
+								code += "if " + code2;
+							}
+						}
+						if (nextCommandCont==null){
+							strwrap nextCommandCollection = new strwrap("",returnIndex), functionCollection = new strwrap("");
+							//System.out.println("Call makeCommands, task: "+reference);
+							//if (nextCommandCollection==null) System.out.println("Choice: nextCommandCollection==0");
+							MCResult = makeCommands(currElem.getNextElement(i), false, retElement,nextCommandCollection,functionCollection,lastSequence);
+							if (functionCollection.str.isEmpty()){
+								//System.out.println("NO content has been added to "+ code2);
+								code += "{\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\nreturn " + returnIndex + SCCR +"}" + CR;
+								commentText+="_comment[" + commentNum + "]=std::string(\"Branch taken: " + code2 + "\");\n";
+								commentNum++;
+								//System.out.println("RETURN, aaINC NUM "+ returnIndex);
+								returnIndex++;
+								nextCommandTemp+= ",(TMLCommand*)" + MCResult;
+							}else{
+								//System.out.println("OLD RETURN INDEX "+ returnIndex);
+								returnIndex = nextCommandCollection.num;
+								//System.out.println("Returned index: "+ returnIndex);
+								//System.out.println("Choice: Content has been added to "+ code2);
+								code += "{\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\n" + functionCollection.str + "return " + returnIndex + ";\n}" + CR;
+								commentText+="_comment[" + commentNum + "]=std::string(\"Branch taken: " + code2 + "\");\n";
+								commentNum++;
+								//returnIndex = nextCommandCollection.num;
+								//System.out.println("RETURN, bbINC NUM "+ returnIndex);
+								returnIndex++;
+								nextCommandTemp+= nextCommandCollection.str+ ",(TMLCommand*)" + MCResult;
+							}
+						}else{
+							//System.out.println("Choice: Next command!=0 "+ code2);
+							int oldReturnIndex=nextCommandCont.num;
+							functionCont.str += code + "{\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\n";
+							commentText+="_comment[" + commentNum + "]=std::string(\"Branch taken: " + code2 + "\");\n";
+							commentNum++;
+							MCResult = makeCommands(currElem.getNextElement(i), false, retElement, nextCommandCont,functionCont,lastSequence);
+							if (oldReturnIndex==nextCommandCont.num){
+								//System.out.println("RETURN, ccINC NUM "+ nextCommandCont.num);
+								functionCont.str+= "return " + nextCommandCont.num + SCCR;
+								nextCommandCont.num++;
+								nextCommandCont.str += ",(TMLCommand*)" + MCResult;
+							}
+							functionCont.str+= "}\n";
+							code="";
+						}
+					} 
+				}
+				// If there was no else, do a terminate
+				if (nextCommandCont==null){
+					//System.out.println("Choice: finalization, add new command\n");
+					if (index1 == -1){
+						code += "addComment(new Comment(_endLastTransaction,0," + commentNum + "));\nreturn " + returnIndex + SCCR;
+						commentText+="_comment[" + commentNum + "]=std::string(\"Exit branch taken\");\n";
+						commentNum++;
+						nextCommand= cmdName + ".setNextCommand(array(" + (returnIndex+1) + nextCommandTemp + ",(TMLCommand*)0))" + SCCR;
+					}else{
+						nextCommand= cmdName + ".setNextCommand(array(" + returnIndex + nextCommandTemp + "))" + SCCR;
+					}
+					hcode+="TMLChoiceCommand " + cmdName + SCCR;
+					initCommand+= "," + cmdName + "(this,(CondFuncPointer)&" + reference + "::" + cmdName + "_func)"+CR;
+					functions+="unsigned int "+ reference + "::" + cmdName + "_func(){" + CR + code +CR+ "}" + CR2;
+					functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
+				}else{
+					//System.out.println("Choice: finalization, No new command\n");
+					if (index1 == -1){
+						functionCont.str += "addComment(new Comment(_endLastTransaction,0," + commentNum + "));\nreturn " + nextCommandCont.num + SCCR;
+						commentText+="_comment[" + commentNum + "]=std::string(\"Exit branch taken\");\n";
+						commentNum++;
+						nextCommandCont.str += ",(TMLCommand*)0";
+						//System.out.println("RETURN, ddINC NUM "+ nextCommandCont.num);
+						nextCommandCont.num++;
+					}
+					cmdName=MCResult;
+				}
+			}
+					
+		} else if (currElem instanceof TMLSelectEvt){
+			TMLEvent evt;
+			Integer nbevt=0;
+			String evtList="",paramList="";
+			if (debug) System.out.println("Checking SelectEvt\n");
+			cmdName= "_select" + currElem.getID();
+			for(int i=0; i<currElem.getNbNext(); i++) {
+				evt=((TMLSelectEvt)currElem).getEvent(i);
+				if (evt!=null){
+					nbevt++;	
+					evtList += ",(TMLEventChannel*)"+ evt.getExtendedName();
+					//paramList+=",0";
+					if (evt.getNbOfParams()==0) {
+						paramList+=",(Parameter<ParamType>*)0";
+					}else{
+						paramList+=",new Parameter<ParamType>(";
+						for(int j=0; j<3; j++) {
+							if (j!=0) paramList += ",";
+							if (((TMLSelectEvt)currElem).getParam(i,j) == null) {
+								paramList += "0";
+							} else {
+								if (((TMLSelectEvt)currElem).getParam(i,j).length() > 0) {
+									paramList += ((TMLSelectEvt)currElem).getParam(i,j);
+								} else {
+									paramList += "0";
+								}
+							}
+						}
+						paramList+=")";
+					}
+					nextCommand+= ",(TMLCommand*)" + makeCommands(currElem.getNextElement(i), true, retElement,null,null,lastSequence); 
+				}
+			}
+			hcode+="TMLSelectCommand " + cmdName + SCCR;
+			//initCommand+= "," + cmdName + "(this,array("+ nbevt + evtList + "),"+ nbevt + ",0)"+CR;
+			initCommand+= "," + cmdName + "(this,array("+ nbevt + evtList + "),"+ nbevt + ",array("+ nbevt + paramList + "))"+CR;
+			nextCommand=cmdName + ".setNextCommand(array(" + nbevt + nextCommand + "))" + SCCR;
+		
+		} else {
+			System.out.println("Operator: " + currElem + " is not managed in the current version of this C++ code generator." + "))" + SCCR);
+		}
+		chaining+=nextCommand; 
+		return (cmdName.equals("0") || cmdName.charAt(0)=='&')? cmdName : "&"+cmdName;
+	}
+	
+	
+	private String makeCommandLenFunc(String cmdName, String lowerLimit, String upperLimit){
+		if (upperLimit==null)
+			functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\nreturn (unsigned int)(" + lowerLimit + ");\n}" + CR2;
+		else
+			functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\nreturn (unsigned int)myrand(" + lowerLimit + "," + upperLimit + ");\n}" + CR2;
+		functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
+		return "(LengthFuncPointer)&" + reference + "::" + cmdName + "_func";
+	}
+
+	private void makeEndClassH() {
+		hcode += "};" + CR + "#endif" + CR;
+	}
+
+	
+	private String makeAttributesCode() {
+		String code = "";
+		TMLAttribute att;
+		int i;
+		ListIterator iterator = task.getAttributes().listIterator();
+		while(iterator.hasNext()) {
+			att = (TMLAttribute)(iterator.next());
+			if (att.hasInitialValue())
+				code += ","+ att.name + "(" + att.initialValue + ")"+CR;
+			else
+				code += ","+ att.name + "(0)"+CR;
+		}	
+		return code;
+	}
+	
+	private String makeAttributesDeclaration() {
+		String code = "";
+		TMLAttribute att;
+		int i;
+		ListIterator iterator = task.getAttributes().listIterator();
+		while(iterator.hasNext()) {
+			att = (TMLAttribute)(iterator.next());
+			//code += TMLType.getStringType(att.type.getType()) + " " + att.name;
+			code += "int " + att.name;
+			code += ";\n";
+		}		
+		code += "int rnd__0" + SCCR;
+		return code;
+	}
+	
+
+	private String addSemicolonIfNecessary(String _input) {
+		String code1 = _input.trim();
+		if (!(code1.endsWith(";"))) {
+		code1 += ";";
+		}
+		return code1;
+	}
+
+	private String modifyString(String _input) {
+		_input = Conversion.changeBinaryOperatorWithUnary(_input, "div", "/");
+		_input = Conversion.changeBinaryOperatorWithUnary(_input, "mod", "%");
+        	return _input;
+	}
+
+}
diff --git a/src/tmltranslator/tomappingsystemc2/TML2MappingSystemC.java b/src/tmltranslator/tomappingsystemc2/TML2MappingSystemC.java
index 5631c66e0ecbef6e9fe84fbd21273f750e96b72f..d38f6a1591c125ce3f722269c56b595698ae1dd0 100755
--- a/src/tmltranslator/tomappingsystemc2/TML2MappingSystemC.java
+++ b/src/tmltranslator/tomappingsystemc2/TML2MappingSystemC.java
@@ -53,25 +53,19 @@ import myutil.*;
 
 public class TML2MappingSystemC {
     
-    //private static int gateId;
-	
 	private final static String CR = "\n";
 	private final static String CR2 = "\n\n";
 	private final static String SCCR = ";\n";
 	private final static String EFCR = "}\n";
 	private final static String EFCR2 = "}\n\n";
 	private final static String EF = "}";
-	
 	private final static int MAX_EVENT = 1024;
-
+	
 	private TMLModeling tmlmodeling;
 	private TMLMapping tmlmapping;
-    
-    private boolean debug;
-    
-    
-    private String header, declaration, mainFile, src;
 	
+	private boolean debug;
+	private String header, declaration, mainFile, src;
 	private ArrayList<MappedSystemCTask> tasks;
     
 	public TML2MappingSystemC(TMLModeling _tmlm) {
@@ -84,55 +78,50 @@ public class TML2MappingSystemC {
 		cpu.taskSwitchingTime = 1;
 		cpu.branchingPredictionPenalty = 0;
 		cpu.execiTime = 1;
-		tmla.addHwNode(cpu);
-		
+		tmla.addHwNode(cpu);	
 		tmlmapping = new TMLMapping(tmlmodeling, tmla);
-		
 		ListIterator iterator = _tmlm.getTasks().listIterator();
-        TMLTask t;
+        	TMLTask t;
 		while(iterator.hasNext()) {
 			t = (TMLTask)(iterator.next());
 			tmlmapping.addTaskToHwExecutionNode(t, cpu);
 		}
-    }
+	}
 	
-    public TML2MappingSystemC(TMLMapping _tmlmapping) {
-		//System.out.println("Coucou!");
-        tmlmapping = _tmlmapping;
-    }
+	public TML2MappingSystemC(TMLMapping _tmlmapping) {
+        	tmlmapping = _tmlmapping;
+ 	}
     
-    public void saveFile(String path, String filename) throws FileException {  
-		//System.out.println("Content should be saved to path: "+path+CR);
+	public void saveFile(String path, String filename) throws FileException {  
 		generateTaskFiles(path);
-        FileUtils.saveFile(path + filename + ".cpp", getFullCode());
+        	FileUtils.saveFile(path + filename + ".cpp", getFullCode());
 		src += filename + ".cpp";
 		FileUtils.saveFile(path + "Makefile.src", src);
-    }
+	}
 	
 	public String getFullCode() {
 		return mainFile;
 	}
     
-    public void generateSystemC(boolean _debug) {
-        debug = _debug;
+    	public void generateSystemC(boolean _debug) {
+        	debug = _debug;
         
 		tmlmodeling = tmlmapping.getTMLModeling();
 		tasks = new ArrayList<MappedSystemCTask>();
         
-        generateSystemCTasks();
+        	generateSystemCTasks();
 		generateMainFile();
 		generateMakefileSrc();
 	}
 	
-	public void generateMainFile() {
+	private void generateMainFile() {
 		makeHeader();
 		makeDeclarations();
 		mainFile = header + declaration;
 		mainFile = Conversion.indentString(mainFile, 4);
-		//System.out.println(CR2+ "************MAINFILE************\n"+mainFile);
 	}
 	
-	public void generateMakefileSrc() {
+	private void generateMakefileSrc() {
 		src = "";
 		src += "SRCS = ";
 		for(MappedSystemCTask mst: tasks) {
@@ -140,7 +129,7 @@ public class TML2MappingSystemC {
 		}
 	}
 	
-	public void makeHeader() {
+	private void makeHeader() {
 		// System headers
 		header = "#include <simkern.h>" + CR;
 		// Generate tasks header
@@ -150,11 +139,11 @@ public class TML2MappingSystemC {
 		header += CR;
 	}
 	
-	public void makeDeclarations() {
-		declaration = "//************************* MAIN NEW SIMULATOR*********************\n\nint main(int len, char ** args) {\nstruct timeval begin, end;\ngettimeofday(&begin,NULL);\nCPUList cpulist;\nBusList buslist;\nTraceableDeviceList vcdlist;\n\n";
+	private void makeDeclarations() {
+		declaration = "//************************* MAIN NEW SIMULATOR*********************\n\nint main(int len, char ** args) {\nstruct timeval begin, end;\ngettimeofday(&begin,NULL);\nSchedulingList cpulist;\nBusList buslist;\nTraceableDeviceList vcdlist;\n\n";
 		
-		// Hw nodes
-		declaration += "//Declaration of hardware nodes" + CR;
+		// Declaration of HW nodes
+		declaration += "//Declaration of CPUs" + CR;
 		for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()) {
 			if (node instanceof HwCPU) {
 				if (tmlmapping.isAUsedHwNode(node)) {
@@ -167,38 +156,47 @@ public class TML2MappingSystemC {
 		}
 		declaration += CR;
 		
-		//Buses
-		declaration+="Bus defaultBus(\"defaultBus\",100)" + SCCR;
+		// Declaration of Buses
+		declaration += "//Declaration of Buses" + CR;
+		declaration+="Bus defaultBus(\"defaultBus\",100,1,1)" + SCCR;
 		declaration += "buslist.push_back(&defaultBus)" + SCCR;
 		declaration += "vcdlist.push_back((TraceableDevice*)&defaultBus)" + SCCR;
 		for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()) {
 			if (node instanceof HwBus) {
 				//if (tmlmapping.isAUsedHwNode(node)) {
-					declaration += "Bus " + node.getName() + "(\"" + node.getName() + "\",100)" + SCCR;
-					declaration += "buslist.push_back(&"+ node.getName() + ")" + SCCR;
-					declaration += "vcdlist.push_back((TraceableDevice*)&"+ node.getName() + ")" + SCCR;
+				declaration += "Bus " + node.getName() + "(\"" + node.getName() + "\",100,"+ ((HwBus)node).byteDataSize + "," + node.clockRatio + ")" + SCCR;
+				declaration += "buslist.push_back(&"+ node.getName() + ")" + SCCR;
+				declaration += "vcdlist.push_back((TraceableDevice*)&"+ node.getName() + ")" + SCCR;
 				//}
 			}
 		}
 		declaration += CR;
 
-		// Channels, events, requests
-		ListIterator iterator;
+		// Declaration of Bridges
+		declaration += "//Declaration of Bridges" + CR;
+		for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()) {
+			if (node instanceof HwBridge) {
+				declaration+= "Bridge " + node.getName() + "(\"" + node.getName() + "\", " + node.clockRatio + ", " + ((HwBridge)node).bufferByteSize + ")" +SCCR;
+			}
+		}
+		declaration += CR;
+
+		// Declaration of Memories
+		declaration += "//Declaration of Memories\nMemory defaultMemory(\"defaultMemory\",1,4)" + SCCR;
+		for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()) {
+			if (node instanceof HwMemory) {
+				declaration+= "Memory " + node.getName() + "(\"" + node.getName() + "\", " + node.clockRatio + ", " + ((HwMemory)node).byteDataSize + ")" +SCCR;
+			}
+		}
+		declaration += CR;
+				
+		// Declaration of channels
 		TMLChannel channel;
-		HwCommunicationNode commNode;
-		int indexOfChannel;
 		String tmp,param;
-		
 		declaration += "//Declaration of channels" + CR;
-		//iterator=tmlmapping.getCommunicationNodes().listIterator();
-		//for(TMLElement elem: tmlmapping.getMappedCommunicationElement()) {
 		for(TMLElement elem: tmlmodeling.getChannels()){
-			//commNode=(HwCommunicationNode)iterator.next();
 			if (elem instanceof TMLChannel) {
 				channel = (TMLChannel)elem;
-				commNode=null;
-				indexOfChannel=tmlmapping.getMappedCommunicationElement().indexOf(channel);
-				if (indexOfChannel!=-1) commNode=tmlmapping.getCommunicationNodes().get(indexOfChannel);
 				switch(channel.getType()) {
 				case TMLChannel.BRBW:
 					tmp = "TMLbrbwChannel ";
@@ -213,14 +211,29 @@ public class TML2MappingSystemC {
 					tmp = "TMLnbrnbwChannel ";
 					param= "";
 				}
-				if (commNode==null)
-					declaration += tmp + " " + channel.getExtendedName() +"(\"" + channel.getName() + "\",&defaultBus" + param +")"+ SCCR;
-				else
-					declaration += tmp + " " + channel.getExtendedName() +"(\"" + channel.getName() + "\",&" + commNode.getName() + param +")"+ SCCR;
+				declaration += tmp + " " + channel.getExtendedName() +"(\"" + channel.getName() + "\",";
+				strwrap buses1=new strwrap(""), buses2=new strwrap(""), slaves1=new strwrap(""), slaves2=new strwrap("");
+				int hopNum = addRoutingInfoForChannel(elem, ((TMLChannel)elem).getOriginTask(), buses1, slaves1, true);
+				if (hopNum==-1){
+					buses2.str=buses1.str;
+					slaves2.str=slaves1.str;
+					hopNum=2;
+				}else{
+					int tempHop= addRoutingInfoForChannel(elem, ((TMLChannel)elem).getDestinationTask(), buses2, slaves2, false);
+					if (tempHop==-1){
+						buses1.str=buses2.str;
+						slaves1.str=slaves2.str;
+						hopNum=2;
+					}else{
+						hopNum+=tempHop;
+					}	
+				}
+				declaration+= hopNum + ",array(" + hopNum + buses1.str + buses2.str + "),array(" + hopNum + slaves1.str + slaves2.str + ")" + param +")"+ SCCR;
 			}
 		}
 		declaration += CR;
 		
+		// Declaration of events
 		declaration += "//Declaration of events" + CR;
 		for(TMLEvent evt: tmlmodeling.getEvents()) {		
 			if (evt.isInfinite()) {
@@ -235,66 +248,37 @@ public class TML2MappingSystemC {
 					param= "," + evt.getMaxSize() + ",0";
 				}
 			}
-			indexOfChannel=tmlmapping.getMappedCommunicationElement().indexOf(evt);
-			if (indexOfChannel!=-1) commNode=tmlmapping.getCommunicationNodes().get(indexOfChannel); else commNode=null; 
-			if (commNode==null || !(commNode instanceof HwBus))
-				declaration += tmp + evt.getExtendedName() + "(\"" + evt.getName() + "\",0" + param +")" + SCCR;
-			else
-				declaration += tmp + evt.getExtendedName() + "(\"" + evt.getName() + "\",&" + commNode.getName() + param +")" + SCCR;
+			
+			declaration += tmp + evt.getExtendedName() + "(\"" + evt.getName() + "\",0,0,0" + param +")" + SCCR;
 		}
 		declaration += CR;
 		
+		// Declaration of requests
 		declaration += "//Declaration of requests" + CR;
 		for(TMLTask task: tmlmodeling.getTasks()) {
-			if (task.isRequested()) declaration += "TMLEventBChannel reqChannel_"+ task.getName() + "(\"reqChannel"+ task.getName() + "\",0,0,true)" + SCCR;
+			if (task.isRequested()) declaration += "TMLEventBChannel reqChannel_"+ task.getName() + "(\"reqChannel"+ task.getName() + "\",0,0,0,0,true)" + SCCR;
 		}
 		declaration += CR;
 		
-		//Registration of CPUs
-		//HwLink link;
-		declaration += "//Registration of CPUs" + CR;
-		//iterator=tmlmapping.getTMLArchitecture().getHwNodes().listIterator();
-		//for(HwLink link: tmlmapping.getTMLArchitecture().getHwLinks()){
-		//	declaration+=link.bus.getName() + ".registerMasterDevice(&" + ((HwNode)iterator.next()).getName() + ")" + SCCR; 
-		//}
-		PriorityQueue<HwLink> pq=new PriorityQueue<HwLink>(20);
+		// Registration of Bus masters
+		declaration += "//Registration of Bus masters" + CR;
 		for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()){
-			if (node instanceof HwExecutionNode){
+			if (node instanceof HwExecutionNode || node instanceof HwBridge){
 				ArrayList<HwLink> nodeLinks= tmlmapping.getTMLArchitecture().getLinkByHwNode(node);
 				if (nodeLinks.isEmpty())
-					declaration+= "defaultBus.registerMasterDevice(&" + node.getName() + ")" + SCCR;
-				else
-					pq.addAll(nodeLinks);
-			//getPriority
-				//for(HwLink link: tmlmapping.getTMLArchitecture().getLinkByHwNode(node)){
-				//	if (link==null){
-				//		declaration+= "defaultBus.registerMasterDevice(&" + node.getName() + ")" + SCCR;
-				//	}else{
-				//		pq.add(link);
-				//		//declaration+=link.bus.getName() + ".registerMasterDevice(&" + node.getName() + ")" + SCCR;
-				//	}
-				//}
+					//declaration+= "defaultBus.registerMasterDevice(&" + node.getName() + ")" + SCCR;
+					declaration+= node.getName() + ".addBusPriority(&defaultBus,1)"+SCCR;
+				else{
+					for(HwLink link: nodeLinks){
+						declaration+= node.getName() + ".addBusPriority(&" + link.bus.getName() + "," + link.getPriority() + ")" + SCCR;
+					}
+				}
 			} 
 		}
-		//for(HwLink link: tmlmapping.getTMLArchitecture().getHwLinks()){
-			//if (node instanceof HwExecutionNode){
-				//link = tmlmapping.getTMLArchitecture().getLinkByHwNode(node);
-				//if (link==null){
-				//	declaration+= "defaultBus.registerMasterDevice(&" + node.getName() + ")" + SCCR;
-				//}else{
-					//pq.add(link);
-					//declaration+=link.bus.getName() + ".registerMasterDevice(&" + node.getName() + ")" + SCCR;
-				//}
-			//}
-		//}
-		HwLink link;
-		while (!pq.isEmpty()){
-			link = pq.remove();
-			declaration+=link.bus.getName() + ".registerMasterDevice(&" + link.hwnode.getName() + ")" + SCCR;
-		}
 		declaration += CR;
 	
-		// Tasks
+		//Declaration of Tasks
+		ListIterator iterator;
 		declaration += "//Declaration of tasks" + CR;
 		HwExecutionNode node;
 		iterator=tmlmapping.getNodes().listIterator();
@@ -318,32 +302,108 @@ public class TML2MappingSystemC {
 		}
 		declaration += CR;
 		
-		//Task registration
-		/*declaration += "//Tasks registration" + CR;
-		HwExecutionNode node;
-		iterator=tmlmapping.getNodes().listIterator();
-		for(TMLTask task: tmlmapping.getMappedTasks()){
-			node=(HwExecutionNode)iterator.next();
-			declaration += node.getName() + ".registerTask(&task__" + task.getName() + ")" + SCCR;
+		declaration+="gettimeofday(&end,NULL);\nstd::cout << \"The preparation took \" << getTimeDiff(begin,end) << \"usec.\\n\";\nsimulate(cpulist,buslist);\nschedule2HTML(cpulist,buslist,len,args);\nschedule2VCD(vcdlist,len,args);\n//schedule2Graph(cpulist, len, args);\nschedule2TXT(cpulist, len, args);\nstreamBenchmarks(std::cout, vcdlist);\nreturn 0;\n}\n";
+  	}
+
+	private int addRoutingInfoForChannel(TMLElement _tmle, TMLTask _task, strwrap buses, strwrap slaves, boolean dir){
+		LinkedList<HwCommunicationNode> commNodeList = tmlmapping.findNodesForElement(_tmle);
+		if (debug){
+			System.out.println("CommNodes for "+ _tmle.getName());
+			for(HwCommunicationNode commNode: commNodeList) {
+				System.out.println(commNode.getName());
+			}
+		}
+		int hopNumber=1;
+		int taskIndex = tmlmapping.getMappedTasks().indexOf(_task);
+		if (debug) System.out.println("Starting from Task: " + _task.getName());
+		if (taskIndex==-1){
+			buses.str=",(SchedulableCommDevice*)&defaultBus";
+			slaves.str= ",(Slave*)&defaultMemory";
+			return -1;
 		}
-		declaration += CR;*/
+		//HwLink cpuLink = tmlmapping.getTMLArchitecture().getHwLinkByHwNode(tmlmapping.getNodes().get(taskIndex)); //cpu of task as parameter
+		//if (cpuLink==null){
+		//	buses.str=",(SchedulableCommDevice*)&defaultBus";
+		//	slaves.str= ",(Slave*)&defaultMemory";
+		//	return -1;
+		//}
+		//HwBus bus=cpuLink.bus;
+		HwBus bus= getBusConnectedToNode(commNodeList, tmlmapping.getNodes().get(taskIndex));
+		if (bus==null){
+			buses.str=",(SchedulableCommDevice*)&defaultBus";
+			slaves.str= ",(Slave*)&defaultMemory";
+			return -1;
+		}
+		buses.str+= " ,(SchedulableCommDevice*)&"+ bus.getName();
+		if (debug) System.out.println("Chaining:\nFirst bus: " + bus.getName());
+		HwMemory mem = getMemConnectedToBus(commNodeList, bus);
+		commNodeList.remove(bus);
+		HwBridge bridge;
+		while(mem==null){
+			bridge = getBridgeConnectedToBus(commNodeList, bus);
+			if (bridge==null){
+				buses.str=",(SchedulableCommDevice*)&defaultBus";
+				slaves.str= ",(Slave*)&defaultMemory";
+				return -1;
+			}
+			if (debug) System.out.println("Bridge: " + bridge.getName());
+			commNodeList.remove(bridge);
+			if (dir) slaves.str+= " ,(Slave*)&"+ bridge.getName(); else slaves.str= " ,(Slave*)&"+ bridge.getName() + slaves.str;
+			bus = getBusConnectedToNode(commNodeList, bridge);
+			if (bus==null){
+				buses.str=",(SchedulableCommDevice*)&defaultBus";
+				slaves.str= ",(Slave*)&defaultMemory";
+				return -1;
+			}
+			if (debug) System.out.println("Bus: " + bus.getName());
+			commNodeList.remove(bus);
+			if (dir) buses.str+= " ,(SchedulableCommDevice*)&"+ bus.getName(); else buses.str= " ,(SchedulableCommDevice*)&"+ bus.getName() + buses.str;
+			mem = getMemConnectedToBus(commNodeList, bus);
+			hopNumber++;
+		}
+		if (dir) slaves.str+= " ,(Slave*)&"+ mem.getName(); else slaves.str= " ,(Slave*)&"+ mem.getName() + slaves.str;
+		return hopNumber;
+	}
 
-		declaration+="gettimeofday(&end,NULL);\nstd::cout << \"The preparation took \" << getTimeDiff(begin,end) << \"usec.\\n\";\nsimulate(cpulist,buslist);\nschedule2HTML(cpulist,buslist,len,args);\nschedule2VCD(vcdlist,len,args);\nschedule2Graph(cpulist, len, args);\nschedule2TXT(cpulist, len, args);\nreturn 0;\n}\n";
-  }
-  
+	private HwMemory getMemConnectedToBus(LinkedList<HwCommunicationNode> _commNodes, HwBus _bus){
+		for(HwCommunicationNode commNode: _commNodes){
+			if (commNode instanceof HwMemory){
+				if (tmlmapping.getTMLArchitecture().isNodeConnectedToBus(commNode, _bus)) return (HwMemory)commNode;
+			}
+		}
+		return null;
+	}
+	
+	private HwBridge getBridgeConnectedToBus(LinkedList<HwCommunicationNode> _commNodes, HwBus _bus){
+		for(HwCommunicationNode commNode: _commNodes){
+			if (commNode instanceof HwBridge){
+				if (tmlmapping.getTMLArchitecture().isNodeConnectedToBus(commNode, _bus)) return (HwBridge)commNode;
+			}
+		}
+		return null;
+	}
+	
+	private HwBus getBusConnectedToNode(LinkedList<HwCommunicationNode> _commNodes, HwNode _node){
+		for(HwCommunicationNode commNode: _commNodes){
+			if (commNode instanceof HwBus){
+				if (tmlmapping.getTMLArchitecture().isNodeConnectedToBus(_node, (HwBus)commNode)) return (HwBus)commNode;
+			}
+		}
+		return null;
+	}
 
-  // *************** Internal structure manipulation ******************************* /
-    
-    public void generateSystemCTasks() {
-        ListIterator iterator = tmlmodeling.getTasks().listIterator();
-        TMLTask t;
-        MappedSystemCTask mst;
+
+
+// *************** Internal structure manipulation ******************************* /
+	public void generateSystemCTasks() {
+		ListIterator iterator = tmlmodeling.getTasks().listIterator();
+		TMLTask t;
+		MappedSystemCTask mst;
 		ArrayList<TMLChannel> channels;
 		ArrayList<TMLEvent> events;
 		ArrayList<TMLRequest> requests;
-        
-        while(iterator.hasNext()) {
-            t = (TMLTask)(iterator.next());
+		while(iterator.hasNext()) {
+			t = (TMLTask)(iterator.next());
 			if (tmlmapping.isTaskMapped(t)) {
 				channels = tmlmodeling.getChannels(t);
 				events = tmlmodeling.getEvents(t);
@@ -352,15 +412,12 @@ public class TML2MappingSystemC {
 				mst.generateSystemC(debug);
 				tasks.add(mst);
 			}
-        }
-    }
+		}
+	}
 	
 	public void generateTaskFiles(String path) throws FileException {
 		for(MappedSystemCTask mst: tasks) {
 			mst.saveInFiles(path);
 		}
 	}
-        
-
-    
 }
\ No newline at end of file
diff --git a/src/ui/GNCModeling.java b/src/ui/GNCModeling.java
index bc10ebaa5513c9cbf5e66607886909ed5291d709..d809e525494250d5554928d2978c544ded546839 100755
--- a/src/ui/GNCModeling.java
+++ b/src/ui/GNCModeling.java
@@ -86,6 +86,7 @@ public class GNCModeling  {
 			addTraffics();
 			addLinks();
 			addPaths();
+			manageParameters();
 		}
 		
 		System.out.println("NC XML:\n" + ncs.toXML());
@@ -110,13 +111,48 @@ public class GNCModeling  {
 		ListIterator iterator = ncdp.getListOfEqNode().listIterator();
 		NCEqNode node;
 		NCEquipment eq;
+		NCConnectorNode con;
+		int cpt;
+		CheckingError ce;
+		
+		
 		
 		while(iterator.hasNext()) {
 			node = (NCEqNode)(iterator.next());
 			
-			eq = new NCEquipment();
-			eq.setName(node.getName());
-			ncs.equipments.add(eq);
+			// Find the only interface of that Equipment
+			// If more than one interface -> error
+			/*ArrayList<NCConnectorNode> cons = ncdp.getConnectorOfEq(node);
+			
+			if (cons.size() == 0) {
+				ce = new CheckingError(CheckingError.STRUCTURE_ERROR, "Equipment " + node.getName() + " has non interface ans so not traffic can be sent over the network");
+				ce.setTDiagramPanel(ncdp);
+				ce.setTGComponent(node);
+				warnings.add(ce);
+				return;
+			}
+			
+			if (cons.size() > 1) {
+				ce = new CheckingError(CheckingError.STRUCTURE_ERROR, "Equipment: " + node.getName() + " has more than one interface");
+				ce.setTDiagramPanel(ncdp);
+				ce.setTGComponent(node);
+				checkingErrors.add(ce);
+				return;
+			}
+			
+			con = cons.get(0);*/
+			
+			/*if ((con.hasParameter()) && (con.getParameter() >0)) {
+				for(int i=0; i<con.getParameter(); i++) {
+					eq = new NCEquipment();
+					eq.setName(node.getName()+ "__" +i);
+					ncs.equipments.add(eq);
+				}
+			} else {*/
+				eq = new NCEquipment();
+				eq.setName(node.getName());
+				ncs.equipments.add(eq);
+			/*}*/
 		}
 	}
 	
@@ -300,7 +336,7 @@ public class GNCModeling  {
 	}
 	
 	private void addPaths() {
-		 System.out.println("Adding paths");
+		System.out.println("Adding paths");
 		// Consider each traffic
 		// For each traffic, its builds a tree
 		// Then, its generates the corresponding paths
@@ -383,8 +419,8 @@ public class GNCModeling  {
 			path.setName("path" + PATH_INDEX);
 			PATH_INDEX++;
 			ncs.paths.add(path);
-		
-		// not a leaf
+			
+			// not a leaf
 		} else {
 			sw = (NCSwitchNode)(tree.getElement());
 			TreeCell next = new TreeCell();
@@ -463,9 +499,9 @@ public class GNCModeling  {
 				checkingErrors.add(ce);
 				return -1;
 			}
-	   }
-	   
-	   // Good tree!
+		}
+		
+		// Good tree!
 		return 1;
 	}
 	
@@ -601,7 +637,7 @@ public class GNCModeling  {
 									buildTreeFromSwitch(root, cell, ncsn, nextArriving, arti);
 									//System.out.println("Ending adding a switch: " + ncsn.getNodeName());
 								}
-							//}
+								//}
 						}
 					}
 				}
@@ -612,5 +648,115 @@ public class GNCModeling  {
 		
 		return 0;
 	}
-    
+	
+	public void manageParameters() {
+		ListIterator iterator;
+		NCEqNode node1, node2;
+		ArrayList<NCConnectorNode> cons1, cons2;
+		NCConnectorNode con1, con2;
+		int i;
+		int parameter1, parameter2;
+		NCEquipment nceq1, nceq2;
+		CheckingError ce;
+		NCTraffic tr1;
+		NCPath path1;
+		NCLink link1, link2, link11, link22;
+		
+		//ArrayList<NCEquipment> newEquipments = new ArrayList<NCEquipment>();
+		ArrayList<NCTraffic> newTraffics = new ArrayList<NCTraffic>();
+		ArrayList<NCLink> newLinks = new ArrayList<NCLink>();
+		ArrayList<NCPath> newPaths = new ArrayList<NCPath>();
+		
+		ArrayList<NCEquipment> oldEquipments = new ArrayList<NCEquipment>();
+		ArrayList<NCTraffic> oldTraffics = new ArrayList<NCTraffic>();
+		ArrayList<NCLink> oldLinks = new ArrayList<NCLink>();
+		ArrayList<NCPath> oldPaths = new ArrayList<NCPath>();
+		
+		// Are there any path to duplicate?
+		for(NCPath path: ncs.paths) {
+			node1 = ncdp.getNCENodeByName(path.origin.getName());
+			node2 = ncdp.getNCENodeByName(path.destination.getName());
+			if ((node1 != null) && (node2 != null)) {
+				cons1 = ncdp.getConnectorOfEq(node1);
+				cons2 = ncdp.getConnectorOfEq(node2);
+				if ((cons1.size() == 1) && (cons2.size() == 1)) {
+					con1 = cons1.get(0);
+					con2 = cons2.get(0);
+					
+					if (con1.hasParameter() != con1.hasParameter()) {
+						ce = new CheckingError(CheckingError.STRUCTURE_ERROR, "Network structure error: parameters of links starting from " + node1.getNodeName() + " and " + node2.getNodeName() + " are not compatible");
+						ce.setTDiagramPanel(ncdp);
+						ce.setTGComponent(node1);
+						checkingErrors.add(ce);	
+					} else {
+						parameter1 = con1.getParameter();
+						parameter2 = con2.getParameter();
+						if (con1.hasParameter()) {
+							if (parameter1 != parameter2) {
+								ce = new CheckingError(CheckingError.STRUCTURE_ERROR, "Network structure error: parameters of links starting from " + node1.getNodeName() + " and " + node2.getNodeName() + " are not compatible");
+								ce.setTDiagramPanel(ncdp);
+								ce.setTGComponent(node1);
+								checkingErrors.add(ce);	
+							} else {
+								if (parameter1 < 2) {
+									ce = new CheckingError(CheckingError.STRUCTURE_ERROR, "Network structure error: parameters of links starting from " + node1.getNodeName() + " and " + node2.getNodeName() + " are not correctly set -> ignoring");
+									ce.setTDiagramPanel(ncdp);
+									ce.setTGComponent(node1);
+									warnings.add(ce);	
+								} else {
+									if (!oldEquipments.contains(path.origin)) {
+										link1 = ncs.getLinkWith(path.origin);
+										for (i=0; i<parameter1; i++) {
+											nceq1 = new NCEquipment();
+											nceq1.setName(path.origin.getName() + "__" + i);
+											ncs.equipments.add(nceq1);
+											
+											link11 = (NCLink)(link1.clone());
+											if (link11.getLinkedElement1() == path.origin) {
+												link11.setLinkedElement1(nceq1);
+											} else {
+												link11.setLinkedElement2(nceq1);
+											}
+											ncs.links.add(link11);
+										}
+										oldEquipments.add(path.origin);
+										oldLinks.add(link1);
+									}
+									
+									if (!oldEquipments.contains(path.destination)) {
+										link2 = ncs.getLinkWith(path.destination);
+										for (i=0; i<con1.getParameter(); i++) {
+											nceq2 = new NCEquipment();
+											nceq2.setName(path.destination.getName() + "__" + i);
+											ncs.equipments.add(nceq2);
+											
+											link22 = (NCLink)(link2.clone());
+											if (link22.getLinkedElement1() == path.destination) {
+												link22.setLinkedElement1(nceq2);
+											} else {
+												link22.setLinkedElement2(nceq2);
+											}
+											ncs.links.add(link22);
+										}
+										oldEquipments.add(path.destination);
+										oldLinks.add(link2);
+									}
+									
+									// Paths and traffics are duplicated
+									oldPaths.add(path);
+									oldTraffics.add(path.traffic);
+									for(i=0; i<parameter1; i++) {
+										tr1 = (NCTraffic)(path.traffic.clone());
+										tr1.setName(path.traffic.getName() + "__" + i);
+										ncs.traffics.add(tr1);
+									}
+								}
+							}
+						}
+					}
+				}
+			}
+		}
+	}
+
 }
diff --git a/src/ui/MainGUI.java b/src/ui/MainGUI.java
index d06bc2191106a61bc8709a40fbabb051088c8018..b16d674ab843215d854185c77783fbaf39508b3e 100755
--- a/src/ui/MainGUI.java
+++ b/src/ui/MainGUI.java
@@ -1630,6 +1630,10 @@ public	class MainGUI implements ActionListener, WindowListener, KeyListener {
         //jfc.setApproveButtonText("Open");
         int returnVal = jfc.showOpenDialog(frame);
         
+		if (returnVal == JFileChooser.CANCEL_OPTION) {
+			return;
+		}
+		
         if (returnVal == JFileChooser.APPROVE_OPTION) {
             file = jfc.getSelectedFile();
         }
diff --git a/src/ui/ncdd/NCConnectorNode.java b/src/ui/ncdd/NCConnectorNode.java
index ec11ca8ce93a6e82e5fc4b89c864c17fafe6a0ea..0e4b34f2061c48dc65a7c118ce48333ed6e0f712 100755
--- a/src/ui/ncdd/NCConnectorNode.java
+++ b/src/ui/ncdd/NCConnectorNode.java
@@ -128,7 +128,7 @@ public  class NCConnectorNode extends TGConnector implements WithAttributes {
 		String interfaceNameTmp;
         
         JDialogLinkNCNode jdlncn = new JDialogLinkNCNode(frame, "Setting link parameters", hasCapacity, capacity, capacityUnit, hasParameter, parameter, interfaceName);
-        jdlncn.setSize(450, 350);
+        jdlncn.setSize(650, 650);
         GraphicLib.centerOnParent(jdlncn);
         jdlncn.show(); // Blocked until dialog has been closed
 		
diff --git a/src/ui/ncdd/NCDiagramPanel.java b/src/ui/ncdd/NCDiagramPanel.java
index bb0088d2a82aec275896195778d0ee9e5619c204..ac867300912319efb4e7d8f8475b04163881c053 100755
--- a/src/ui/ncdd/NCDiagramPanel.java
+++ b/src/ui/ncdd/NCDiagramPanel.java
@@ -210,6 +210,23 @@ public class NCDiagramPanel extends TDiagramPanel implements TDPWithAttributes {
         return ll;
     }
 	
+	public NCEqNode getNCENodeByName(String _name) {
+		LinkedList ll = new LinkedList();
+        TGComponent tgc;
+        Iterator iterator = componentList.listIterator();
+        
+        while(iterator.hasNext()) {
+            tgc = (TGComponent)(iterator.next());
+            if (tgc instanceof NCEqNode) {
+                if (((NCEqNode)tgc).getNodeName().equals(_name)) {
+					return ((NCEqNode)tgc);
+				}
+            }
+        }
+        
+        return null;
+	}
+	
 	public LinkedList getListOfSwitchNode() {
         LinkedList ll = new LinkedList();
         TGComponent tgc;
diff --git a/src/ui/window/JDialogLinkNCNode.java b/src/ui/window/JDialogLinkNCNode.java
index 9e5837e9321982bcf758deeffb99d4fe55f724e3..54c41f7b2646c5c7a2a52b9916b81688763f4671 100755
--- a/src/ui/window/JDialogLinkNCNode.java
+++ b/src/ui/window/JDialogLinkNCNode.java
@@ -93,7 +93,7 @@ public class JDialogLinkNCNode extends javax.swing.JDialog implements ActionList
         
         myInitComponents();
         initComponents();
-        pack();
+        //pack();
 		updateComponents();
     }
     
@@ -115,8 +115,8 @@ public class JDialogLinkNCNode extends javax.swing.JDialog implements ActionList
         
         panel1 = new JPanel();
         panel1.setLayout(gridbag1);
-        panel1.setBorder(new javax.swing.border.TitledBorder("Setting idenfier and capacity "));
-        panel1.setPreferredSize(new Dimension(350, 250));
+        panel1.setBorder(new javax.swing.border.TitledBorder("Id, capacity, parameter"));
+        panel1.setPreferredSize(new Dimension(450, 450));
         
         // first line panel1
         c1.gridwidth = 1;