diff --git a/Makefile b/Makefile
index fcc6db67c5ce3e09a3230e2c9032a09948dd633c..15a43fce2f0adf40868a0a04cb14a2e0ab1895e6 100755
--- a/Makefile
+++ b/Makefile
@@ -14,7 +14,7 @@ GZIP = gzip -9 -f
 DEBUG  = -g
 CLASSPATH = -classpath
 CLASSPATH = -sourcepath
-PACKAGE = avatartranslator avatartranslator/toexecutable avatartranslator/directsimulation avatartranslator/tocppsim avatartranslator/touppaal avatartranslator/toturtle avatartranslator/toproverif avatartranslator/totpn automata compiler/tmlparser vcd nc ddtranslator launcher myutil tpndescription sddescription sdtranslator tepe translator tmltranslator tmltranslator/toautomata tmltranslator/tosystemc  tmltranslator/tomappingsystemc tmltranslator/tomappingsystemc2 tmltranslator/touppaal tmltranslator/toturtle translator/tojava translator/tosimujava translator/totpn translator/touppaal  ui ui/avatarbd ui/avatarsmd ui/avatarrd ui/avatarpd ui/avatarcd ui/avatarad ui/ad ui/cd ui/oscd ui/osad ui/dd ui/ebrdd ui/file ui/graph ui/iod ui/ncdd ui/procsd ui/prosmdui/prosmd/util ui/tmlad ui/tmlcd ui/tmldd ui/tmlcomp ui/req ui/sd ui/tree ui/ucd ui/window tmltranslator tmltranslator/toturtle req/ebrdd tmltranslator/tosystemc tmatrix proverifspec uppaaldesc fr/inria/oasis/vercors/cttool/model remotesimulation
+PACKAGE = avatartranslator avatartranslator/toexecutable avatartranslator/directsimulation avatartranslator/tocppsim avatartranslator/touppaal avatartranslator/toturtle avatartranslator/toproverif avatartranslator/totpn automata compiler/tmlparser vcd nc ddtranslator launcher myutil tpndescription sddescription sdtranslator tepe translator tmltranslator tmltranslator/toautomata tmltranslator/tosystemc  tmltranslator/tomappingsystemc tmltranslator/tomappingsystemc3 tmltranslator/touppaal tmltranslator/toturtle translator/tojava translator/tosimujava translator/totpn translator/touppaal  ui ui/avatarbd ui/avatarsmd ui/avatarrd ui/avatarpd ui/avatarcd ui/avatarad ui/ad ui/cd ui/oscd ui/osad ui/dd ui/ebrdd ui/file ui/graph ui/iod ui/ncdd ui/procsd ui/prosmdui/prosmd/util ui/tmlad ui/tmlcd ui/tmldd ui/tmlcomp ui/req ui/sd ui/tree ui/ucd ui/window tmltranslator tmltranslator/toturtle req/ebrdd tmltranslator/tosystemc tmatrix proverifspec uppaaldesc fr/inria/oasis/vercors/cttool/model remotesimulation
 BUILDER = builder.jar
 BUILD_INFO = build.txt
 BUILD_TO_MODIFY = src/ui/DefaultText.java
@@ -100,7 +100,7 @@ basic:
 ttooljar:
 	rm -f $(TTOOL_BIN)/$(TTOOL_BINARY)
 	cp $(TTOOL_SRC)/ui/images/$(STD_LOGO) $(TTOOL_SRC)/ui/images/$(LOGO) 
-	cd $(TTOOL_SRC);  $(JAR) cmf $(TTOOL_JAR_TXT) $(TTOOL_BIN)/$(TTOOL_BINARY) Main.class vcd/*.class avatartranslator/*.class avatartranslator/toexecutable/*.class avatartranslator/directsimulation/*.class avatartranslator/touppaal/*.class avatartranslator/toproverif/*.class avatartranslator/totpn/* avatartranslator/*.class avatartranslator/toturtle/*.java automata/*.class compiler/tmlparser/*.class nc/*.class  tepe/*.class tmltranslator/*.class tmltranslator/toautomata/*.class tmatrix/*.class tmltranslator/toturtle/*.class tmltranslator/touppaal/*.class tmltranslator/tosystemc/*.class tmltranslator/tomappingsystemc/*.class tmltranslator/tomappingsystemc2/*.class  tpndescription/*.class ddtranslator/*.class launcher/*.class myutil/*.class sddescription/*.class sdtranslator/*.class translator/*.class translator/tojava/*.class  translator/tosimujava/*.class translator/touppaal/*.class translator/totpn/*.class req/ebrdd/*.java ui/*.class ui/*/*.class ui/*/*/*.class proverifspec/*.class uppaaldesc/*.class ui/images/*.* ui/images/toolbarButtonGraphics/general/*.gif ui/images/toolbarButtonGraphics/navigation/*.gif  ui/images/toolbarButtonGraphics/media/*.gif $(TTOOL_BIN)/$(LAUNCHER_BINARY) RTLLauncher.class launcher/*.class fr/inria/oasis/vercors/cttool/model/*.class remotesimulation/*.class
+	cd $(TTOOL_SRC);  $(JAR) cmf $(TTOOL_JAR_TXT) $(TTOOL_BIN)/$(TTOOL_BINARY) Main.class vcd/*.class avatartranslator/*.class avatartranslator/toexecutable/*.class avatartranslator/directsimulation/*.class avatartranslator/touppaal/*.class avatartranslator/toproverif/*.class avatartranslator/totpn/* avatartranslator/*.class avatartranslator/toturtle/*.java automata/*.class compiler/tmlparser/*.class nc/*.class  tepe/*.class tmltranslator/*.class tmltranslator/toautomata/*.class tmatrix/*.class tmltranslator/toturtle/*.class tmltranslator/touppaal/*.class tmltranslator/tosystemc/*.class tmltranslator/tomappingsystemc/*.class tmltranslator/tomappingsystemc3/*.class  tpndescription/*.class ddtranslator/*.class launcher/*.class myutil/*.class sddescription/*.class sdtranslator/*.class translator/*.class translator/tojava/*.class  translator/tosimujava/*.class translator/touppaal/*.class translator/totpn/*.class req/ebrdd/*.java ui/*.class ui/*/*.class ui/*/*/*.class proverifspec/*.class uppaaldesc/*.class ui/images/*.* ui/images/toolbarButtonGraphics/general/*.gif ui/images/toolbarButtonGraphics/navigation/*.gif  ui/images/toolbarButtonGraphics/media/*.gif $(TTOOL_BIN)/$(LAUNCHER_BINARY) RTLLauncher.class launcher/*.class fr/inria/oasis/vercors/cttool/model/*.class remotesimulation/*.class
 
 launcher:
 	rm -f $(TTOOL_BIN)/$(LAUNCHER_BINARY)
@@ -116,7 +116,7 @@ tmltranslator:
 
 rundse:
 	rm -f $(TTOOL_BIN)/$(RUNDSE_BINARY)
-	cd $(TTOOL_SRC);$(JAR) cmf $(RUNDSE_JAR_TXT) $(TTOOL_BIN)/$(RUNDSE_BINARY)  RunDSE.class dseengine/*.class tmltranslator/*.class myutil/*.class tmltranslator/tomappingsystemc2/*.class
+	cd $(TTOOL_SRC);$(JAR) cmf $(RUNDSE_JAR_TXT) $(TTOOL_BIN)/$(RUNDSE_BINARY)  RunDSE.class dseengine/*.class tmltranslator/*.class myutil/*.class tmltranslator/tomappingsystemc3/*.class
 
 
 remotesimulator:
@@ -153,32 +153,32 @@ stdrelease:
 	cp  $(TTOOL_SIMULATORS)/systemc1/Makefile.defs $(TTOOL_TARGET)/simulators/systemc1
 	cp  $(TTOOL_SIMULATORS)/systemc1/src_simulator/*.cpp $(TTOOL_TARGET)/simulators/systemc1/src_simulator
 	cp  $(TTOOL_SIMULATORS)/systemc1/src_simulator/*.h $(TTOOL_TARGET)/simulators/systemc1/src_simulator
-	mkdir -p $(TTOOL_TARGET)/simulators/c++2/src_simulator
-	mkdir -p $(TTOOL_TARGET)/simulators/c++2/src_simulator/app
-	mkdir -p $(TTOOL_TARGET)/simulators/c++2/src_simulator/arch
-	mkdir -p $(TTOOL_TARGET)/simulators/c++2/src_simulator/ebrdd
-	mkdir -p $(TTOOL_TARGET)/simulators/c++2/src_simulator/evt
-	mkdir -p $(TTOOL_TARGET)/simulators/c++2/src_simulator/sim
-	mkdir -p $(TTOOL_TARGET)/simulators/c++2/src_simulator/TEPE
-	mkdir -p $(TTOOL_TARGET)/simulators/c++2/lib
-	cp  $(TTOOL_SIMULATORS)/c++2/lib/README $(TTOOL_TARGET)/simulators/c++2/lib/
-	cp  $(TTOOL_SIMULATORS)/c++2/Makefile $(TTOOL_TARGET)/simulators/c++2
-	cp  $(TTOOL_SIMULATORS)/c++2/Makefile.defs $(TTOOL_TARGET)/simulators/c++2
-	cp  $(TTOOL_SIMULATORS)/c++2/schedstyle.css $(TTOOL_TARGET)/simulators/c++2
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/*.cpp $(TTOOL_TARGET)/simulators/c++2/src_simulator
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/*.h $(TTOOL_TARGET)/simulators/c++2/src_simulator
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/app/*.cpp $(TTOOL_TARGET)/simulators/c++2/src_simulator/app
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/app/*.h $(TTOOL_TARGET)/simulators/c++2/src_simulator/app
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/arch/*.cpp $(TTOOL_TARGET)/simulators/c++2/src_simulator/arch
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/arch/*.h $(TTOOL_TARGET)/simulators/c++2/src_simulator/arch
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/ebrdd/*.cpp $(TTOOL_TARGET)/simulators/c++2/src_simulator/ebrdd
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/ebrdd/*.h $(TTOOL_TARGET)/simulators/c++2/src_simulator/ebrdd
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/evt/*.cpp $(TTOOL_TARGET)/simulators/c++2/src_simulator/evt
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/evt/*.h $(TTOOL_TARGET)/simulators/c++2/src_simulator/evt
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/sim/*.cpp $(TTOOL_TARGET)/simulators/c++2/src_simulator/sim
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/sim/*.h $(TTOOL_TARGET)/simulators/c++2/src_simulator/sim
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/TEPE/*.cpp $(TTOOL_TARGET)/simulators/c++2/src_simulator/TEPE
-	cp  $(TTOOL_SIMULATORS)/c++2/src_simulator/TEPE/*.h $(TTOOL_TARGET)/simulators/c++2/src_simulator/TEPE
+	mkdir -p $(TTOOL_TARGET)/simulators/c++3/src_simulator
+	mkdir -p $(TTOOL_TARGET)/simulators/c++3/src_simulator/app
+	mkdir -p $(TTOOL_TARGET)/simulators/c++3/src_simulator/arch
+	mkdir -p $(TTOOL_TARGET)/simulators/c++3/src_simulator/ebrdd
+	mkdir -p $(TTOOL_TARGET)/simulators/c++3/src_simulator/evt
+	mkdir -p $(TTOOL_TARGET)/simulators/c++3/src_simulator/sim
+	mkdir -p $(TTOOL_TARGET)/simulators/c++3/src_simulator/TEPE
+	mkdir -p $(TTOOL_TARGET)/simulators/c++3/lib
+	cp  $(TTOOL_SIMULATORS)/c++3/lib/README $(TTOOL_TARGET)/simulators/c++3/lib/
+	cp  $(TTOOL_SIMULATORS)/c++3/Makefile $(TTOOL_TARGET)/simulators/c++3
+	cp  $(TTOOL_SIMULATORS)/c++3/Makefile.defs $(TTOOL_TARGET)/simulators/c++3
+	cp  $(TTOOL_SIMULATORS)/c++3/schedstyle.css $(TTOOL_TARGET)/simulators/c++3
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/*.cpp $(TTOOL_TARGET)/simulators/c++3/src_simulator
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/*.h $(TTOOL_TARGET)/simulators/c++3/src_simulator
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/app/*.cpp $(TTOOL_TARGET)/simulators/c++3/src_simulator/app
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/app/*.h $(TTOOL_TARGET)/simulators/c++3/src_simulator/app
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/arch/*.cpp $(TTOOL_TARGET)/simulators/c++3/src_simulator/arch
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/arch/*.h $(TTOOL_TARGET)/simulators/c++3/src_simulator/arch
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/ebrdd/*.cpp $(TTOOL_TARGET)/simulators/c++3/src_simulator/ebrdd
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/ebrdd/*.h $(TTOOL_TARGET)/simulators/c++3/src_simulator/ebrdd
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/evt/*.cpp $(TTOOL_TARGET)/simulators/c++3/src_simulator/evt
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/evt/*.h $(TTOOL_TARGET)/simulators/c++3/src_simulator/evt
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/sim/*.cpp $(TTOOL_TARGET)/simulators/c++3/src_simulator/sim
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/sim/*.h $(TTOOL_TARGET)/simulators/c++3/src_simulator/sim
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/TEPE/*.cpp $(TTOOL_TARGET)/simulators/c++3/src_simulator/TEPE
+	cp  $(TTOOL_SIMULATORS)/c++3/src_simulator/TEPE/*.h $(TTOOL_TARGET)/simulators/c++3/src_simulator/TEPE
 # Licenses
 	cd $(TTOOL_DOC); cp $(RELEASE_STD_FILES_LICENSES) $(TTOOL_TARGET)
 # Main readme
@@ -237,29 +237,29 @@ jttooljar:
 	cd $(JTTOOL);$(JAVAC) $(JTTOOL_DIR)/*.java;$(JAR) cmf $(TTOOL_SRC)/$(TTOOL_JAR_TXT) $(TTOOL_BIN)/$(JTTOOL_JAR) $(JTTOOL_DIR)/*.class 
 
 updatesimulator:
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/Doxyfile /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/Doxyfile /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/
 
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/app/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/app/
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/app/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/app/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/app/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/app/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/app/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/app/
 
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/arch/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/arch/
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/arch/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/arch/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/arch/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/arch/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/arch/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/arch/
 
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/ebrdd/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/ebrdd/
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/ebrdd/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/ebrdd/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/ebrdd/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/ebrdd/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/ebrdd/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/ebrdd/
 
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/evt/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/evt/
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/evt/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/evt/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/evt/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/evt/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/evt/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/evt/
 
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/sim/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/sim/
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/sim/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/sim/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/sim/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/sim/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/sim/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/sim/
 
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/TEPE/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/TEPE/
-	cp /homes/apvrille/TTool/simulators/c++2/src_simulator/TEPE/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/TEPE/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/TEPE/*.cpp /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/TEPE/
+	cp /homes/apvrille/TTool/simulators/c++3/src_simulator/TEPE/*.h /homes/apvrille/TechTTool/SystemCCode/generated/src_simulator/TEPE/
 
-	cp /homes/apvrille/TTool/simulators/c++2/Makefile /homes/apvrille/TechTTool/SystemCCode/generated/
+	cp /homes/apvrille/TTool/simulators/c++3/Makefile /homes/apvrille/TechTTool/SystemCCode/generated/
 
 	cd /homes/apvrille/TechTTool/SystemCCode/generated/; make ultraclean
 
diff --git a/bin/config.xml b/bin/config.xml
index c739bcdda67de4b36f259f6b4cc19c86a385f688..e8ab3cb1962e3c07400f5abfee5f425bf092ff6d 100755
--- a/bin/config.xml
+++ b/bin/config.xml
@@ -60,7 +60,7 @@
 <ExternalCommand2Host data="localhost"/>
 <ExternalCommand2 data="/packages/uppaal(4.0.11/uppaal /home/enrici/TURTLE/uppaal/spec.xml"/>
 
-<LastOpenFile data="/home/enrici/TURTLE/modeling/prova.xml"/>
+<LastOpenFile data="/home/enrici/TURTLE/modeling/prova2.xml"/>
 
 
 
diff --git a/simulators/c++3/DIPLODOCUS_C_Design__Alice.cpp b/simulators/c++3/DIPLODOCUS_C_Design__Alice.cpp
index 694b845458b75ba9c2823fe92b0275e5aa3aa996..69797f8fc1cfde78fb4d2e00b5823eb7a736d0f9 100644
--- a/simulators/c++3/DIPLODOCUS_C_Design__Alice.cpp
+++ b/simulators/c++3/DIPLODOCUS_C_Design__Alice.cpp
@@ -3,10 +3,11 @@
 DIPLODOCUS_C_Design__Alice::DIPLODOCUS_C_Design__Alice(ID iID, Priority iPriority, std::string iName, CPU** iCPUs, unsigned int iNumOfCPUs
 , TMLChannel* channel__DIPLODOCUS_C_Design__Phone
 , TMLEventChannel* event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call
+, TMLEventChannel* event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm
 ):TMLTask(iID, iPriority,iName,iCPUs,iNumOfCPUs)
-,_wait13(13,this,event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call,0,"\x0\x0\x0\x0",false)
-,_read12(12,this,0,channel__DIPLODOCUS_C_Design__Phone,"\x0\x0\x0\x0",false,1)
-,_stop14(14,this)
+,_wait15(15,this,event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call,0,"\x0\x0\x0\x0",false)
+,_read14(14,this,0,channel__DIPLODOCUS_C_Design__Phone,"\x0\x0\x0\x0",false,1)
+,_stop16(16,this)
 
 {
     //generate task variable look-up table
@@ -15,15 +16,17 @@ DIPLODOCUS_C_Design__Alice::DIPLODOCUS_C_Design__Alice(ID iID, Priority iPriorit
     //set blocked read task/set blocked write task
     channel__DIPLODOCUS_C_Design__Phone->setBlockedReadTask(this);
     event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call->setBlockedReadTask(this);
+    event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm->setBlockedReadTask(this);
     
     //command chaining
-    _read12.setNextCommand(array(1,(TMLCommand*)&_stop14));
-    _wait13.setNextCommand(array(1,(TMLCommand*)&_read12));
-    _currCommand=&_wait13;
-    _firstCommand=&_wait13;
+    _read14.setNextCommand(array(1,(TMLCommand*)&_stop16));
+    _wait15.setNextCommand(array(1,(TMLCommand*)&_read14));
+    _currCommand=&_wait15;
+    _firstCommand=&_wait15;
     
     _channels[0] = channel__DIPLODOCUS_C_Design__Phone;
     _channels[1] = event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call;
+    _channels[2] = event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm;
     refreshStateHash("\x2\x0\x0\x0");
 }
 
@@ -47,6 +50,7 @@ HashValueType DIPLODOCUS_C_Design__Alice::getStateHash(){
         _stateHash.init((HashValueType)_ID,30);
         if(_liveVarList!=0){
              _channels[1]->setSignificance(this, ((_liveVarList[0] & 2)!=0));
+             _channels[2]->setSignificance(this, ((_liveVarList[0] & 4)!=0));
         }
     }
     return _stateHash.getHash();
diff --git a/simulators/c++3/DIPLODOCUS_C_Design__Alice.h b/simulators/c++3/DIPLODOCUS_C_Design__Alice.h
index 75eeddf275589632db6aa1bc20b8489e38f7dd29..95c2e70cad74f43db551c4cb884738d95f504848 100644
--- a/simulators/c++3/DIPLODOCUS_C_Design__Alice.h
+++ b/simulators/c++3/DIPLODOCUS_C_Design__Alice.h
@@ -33,11 +33,11 @@ class DIPLODOCUS_C_Design__Alice: public TMLTask {
     private:
     // Attributes
     ParamType rnd__0;
-    TMLChannel* _channels[2];
+    TMLChannel* _channels[3];
     
-    TMLWaitCommand _wait13;
-    TMLReadCommand _read12;
-    TMLStopCommand _stop14;
+    TMLWaitCommand _wait15;
+    TMLReadCommand _read14;
+    TMLStopCommand _stop16;
     
     
     public:
@@ -46,6 +46,7 @@ class DIPLODOCUS_C_Design__Alice: public TMLTask {
     DIPLODOCUS_C_Design__Alice(ID iID, Priority iPriority, std::string iName, CPU** iCPUs, unsigned int iNumOfCPUs
     , TMLChannel* channel__DIPLODOCUS_C_Design__Phone
     , TMLEventChannel* event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call
+    , TMLEventChannel* event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm
     );
     std::istream& readObject(std::istream& i_stream_var);
     std::ostream& writeObject(std::ostream& i_stream_var);
diff --git a/simulators/c++3/DIPLODOCUS_C_Design__Bob.cpp b/simulators/c++3/DIPLODOCUS_C_Design__Bob.cpp
index 565fc1515a899d0ef1d9525792a2e90103dadb78..029b620bfe37f85d3b45111fb751e4d413fbc9cf 100644
--- a/simulators/c++3/DIPLODOCUS_C_Design__Bob.cpp
+++ b/simulators/c++3/DIPLODOCUS_C_Design__Bob.cpp
@@ -3,10 +3,11 @@
 DIPLODOCUS_C_Design__Bob::DIPLODOCUS_C_Design__Bob(ID iID, Priority iPriority, std::string iName, CPU** iCPUs, unsigned int iNumOfCPUs
 , TMLChannel* channel__DIPLODOCUS_C_Design__Phone
 , TMLEventChannel* event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call
+, TMLEventChannel* event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm
 ):TMLTask(iID, iPriority,iName,iCPUs,iNumOfCPUs)
-,_send17(17,this,event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call,0,"\x0\x0\x0\x0",false)
-,_write16(16,this,0,channel__DIPLODOCUS_C_Design__Phone,"\x0\x0\x0\x0",false,1)
-,_stop18(18,this)
+,_send19(19,this,event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call,0,"\x0\x0\x0\x0",false)
+,_write18(18,this,0,channel__DIPLODOCUS_C_Design__Phone,"\x0\x0\x0\x0",false,1)
+,_stop20(20,this)
 
 {
     //generate task variable look-up table
@@ -15,15 +16,17 @@ DIPLODOCUS_C_Design__Bob::DIPLODOCUS_C_Design__Bob(ID iID, Priority iPriority, s
     //set blocked read task/set blocked write task
     channel__DIPLODOCUS_C_Design__Phone->setBlockedWriteTask(this);
     event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call->setBlockedWriteTask(this);
+    event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm->setBlockedWriteTask(this);
     
     //command chaining
-    _write16.setNextCommand(array(1,(TMLCommand*)&_stop18));
-    _send17.setNextCommand(array(1,(TMLCommand*)&_write16));
-    _currCommand=&_send17;
-    _firstCommand=&_send17;
+    _write18.setNextCommand(array(1,(TMLCommand*)&_stop20));
+    _send19.setNextCommand(array(1,(TMLCommand*)&_write18));
+    _currCommand=&_send19;
+    _firstCommand=&_send19;
     
     _channels[0] = channel__DIPLODOCUS_C_Design__Phone;
     _channels[1] = event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call;
+    _channels[2] = event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm;
     refreshStateHash("\x2\x0\x0\x0");
 }
 
diff --git a/simulators/c++3/DIPLODOCUS_C_Design__Bob.h b/simulators/c++3/DIPLODOCUS_C_Design__Bob.h
index d4da5d2218ab0df73301a281a7a97408d05d4a07..7166854e296b5247842e73c974bc183517b0397b 100644
--- a/simulators/c++3/DIPLODOCUS_C_Design__Bob.h
+++ b/simulators/c++3/DIPLODOCUS_C_Design__Bob.h
@@ -33,11 +33,11 @@ class DIPLODOCUS_C_Design__Bob: public TMLTask {
     private:
     // Attributes
     ParamType rnd__0;
-    TMLChannel* _channels[2];
+    TMLChannel* _channels[3];
     
-    TMLSendCommand _send17;
-    TMLWriteCommand _write16;
-    TMLStopCommand _stop18;
+    TMLSendCommand _send19;
+    TMLWriteCommand _write18;
+    TMLStopCommand _stop20;
     
     
     public:
@@ -46,6 +46,7 @@ class DIPLODOCUS_C_Design__Bob: public TMLTask {
     DIPLODOCUS_C_Design__Bob(ID iID, Priority iPriority, std::string iName, CPU** iCPUs, unsigned int iNumOfCPUs
     , TMLChannel* channel__DIPLODOCUS_C_Design__Phone
     , TMLEventChannel* event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call
+    , TMLEventChannel* event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm
     );
     std::istream& readObject(std::istream& i_stream_var);
     std::ostream& writeObject(std::ostream& i_stream_var);
diff --git a/simulators/c++3/appmodel.cpp b/simulators/c++3/appmodel.cpp
index 072651c9eea751ec52e2be2dee5fe75811979bcf..defab86307dc0d81c757dde9fe632609797aedef 100644
--- a/simulators/c++3/appmodel.cpp
+++ b/simulators/c++3/appmodel.cpp
@@ -35,14 +35,12 @@
 
 class CurrentComponents: public SimComponents{
     public:
-    CurrentComponents():SimComponents(-1103520087){
+    CurrentComponents():SimComponents(1379091812){
         //Declaration of CPUs
         RRScheduler* CPU1_scheduler = new RRScheduler("CPU1_RRSched", 0, 2000000, 2 ) ;
         CPU* CPU10 = new SingleCoreCPU(1, "CPU1_0", CPU1_scheduler, 1, 1, 1, 5, 20, 2, 10, 10, 4);
-        addCPU(CPU10);
         RRScheduler* CPU0_scheduler = new RRScheduler("CPU0_RRSched", 0, 2000000, 2 ) ;
         CPU* CPU00 = new SingleCoreCPU(2, "CPU0_0", CPU0_scheduler, 1, 1, 1, 5, 20, 2, 10, 10, 4);
-        addCPU(CPU00);
         
         //Declaration of Buses
         Bus* BusNORD_0 = new Bus(3,"BusNORD_0",0, 100, 4, 1,false);
@@ -53,6 +51,8 @@ class CurrentComponents: public SimComponents{
         //Declaration of Bridges
         
         //Declaration of Memories
+        Memory* Memory0 = new Memory(5,"Memory0", 1, 4);
+        addMem(Memory0);
         
         //Declaration of Bus masters
         BusMaster* CPU10_BusNORD_Master = new BusMaster("CPU10_BusNORD_Master", 0, 1, array(1, (SchedulableCommDevice*)BusNORD_0));
@@ -65,12 +65,14 @@ class CurrentComponents: public SimComponents{
         CPU00->addBusMaster(CPU00_BusSUD_Master);
         
         //Declaration of channels
-        TMLnbrnbwChannel* channel__DIPLODOCUS_C_Design__Phone = new TMLnbrnbwChannel(9,"DIPLODOCUS_C_Design__Phone",4,2,array(2,CPU00_BusNORD_Master,CPU10_BusNORD_Master),array(2,static_cast<Slave*>(0),static_cast<Slave*>(0)),0);
+        TMLnbrnbwChannel* channel__DIPLODOCUS_C_Design__Phone = new TMLnbrnbwChannel(10,"DIPLODOCUS_C_Design__Phone",4,2, array(2,CPU00_BusSUD_Master,CPU10_BusSUD_Master), array(2,static_cast<Slave*>(Memory0),static_cast<Slave*>(Memory0)),0);
         addChannel(channel__DIPLODOCUS_C_Design__Phone);
         
         //Declaration of events
-        TMLEventBChannel<ParamType,0>* event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call = new TMLEventBChannel<ParamType,0>(10,"DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call",0,0,0,0,false,false);
+        TMLEventBChannel<ParamType,0>* event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call = new TMLEventBChannel<ParamType,0>(11,"DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call",0,0,0,0,false,false);
         addEvent(event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call);
+        TMLEventBChannel<ParamType,0>* event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm = new TMLEventBChannel<ParamType,0>(12,"DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm",0,0,0,0,false,false);
+        addEvent(event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm);
         
         //Declaration of requests
         
@@ -79,14 +81,16 @@ class CurrentComponents: public SimComponents{
         BusSUD_0->setScheduler((WorkloadSource*) new RRScheduler("BusSUD_RRSched", 0, 5, 1, array(2, (WorkloadSource*)CPU10_BusSUD_Master, (WorkloadSource*)CPU00_BusSUD_Master), 2));
         
         //Declaration of tasks
-        DIPLODOCUS_C_Design__Alice* task__DIPLODOCUS_C_Design__Alice = new DIPLODOCUS_C_Design__Alice(5,0,"DIPLODOCUS_C_Design__Alice", array(1,CPU10),1
+        DIPLODOCUS_C_Design__Alice* task__DIPLODOCUS_C_Design__Alice = new DIPLODOCUS_C_Design__Alice(6,0,"DIPLODOCUS_C_Design__Alice", array(1,CPU10),1
         ,channel__DIPLODOCUS_C_Design__Phone
         ,event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call
+        ,event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm
         );
         addTask(task__DIPLODOCUS_C_Design__Alice);
-        DIPLODOCUS_C_Design__Bob* task__DIPLODOCUS_C_Design__Bob = new DIPLODOCUS_C_Design__Bob(7,0,"DIPLODOCUS_C_Design__Bob", array(1,CPU00),1
+        DIPLODOCUS_C_Design__Bob* task__DIPLODOCUS_C_Design__Bob = new DIPLODOCUS_C_Design__Bob(8,0,"DIPLODOCUS_C_Design__Bob", array(1,CPU00),1
         ,channel__DIPLODOCUS_C_Design__Phone
         ,event__DIPLODOCUS_C_Design__Call__DIPLODOCUS_C_Design__Call
+        ,event__DIPLODOCUS_C_Design__comm__DIPLODOCUS_C_Design__comm
         );
         addTask(task__DIPLODOCUS_C_Design__Bob);
         
diff --git a/src/TMLTranslator.java b/src/TMLTranslator.java
index 3eced11b61c2e0ac086ce6018af80cb48ae85b22..3ca33cf18d8f06f307ce675a1839212954d79535 100755
--- a/src/TMLTranslator.java
+++ b/src/TMLTranslator.java
@@ -1,6 +1,7 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
 
-ludovic.apvrille AT enst.fr
+ludovic.apvrille AT telecom-paritech.fr
+andrea.enrici 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 
@@ -39,8 +40,8 @@ knowledge of the CeCILL license and that you accept its terms.
 * Class TIFTranslator
 * Linecommand application for translating TIF to other languages
 * Creation: 29/06/2007
-* @version 1.0 29/06/2007
-* @author Ludovic APVRILLE
+* @version 1.1 30/05/2014
+* @author Ludovic APVRILLE, Andrea ENRICI
 * @see
 */
 
@@ -63,8 +64,10 @@ public class TMLTranslator  {
 	// 1 -> UPPAAL
 	// 2 -> SystemC
 	// 3 -> SystemC2
+	// 4 -> TML
+	// 5 -> Systemc3
 	
-    public static int conversionType; 
+	public static int conversionType; 
 	public static File inputFile;
 	public static File outputFile;
 	public static String outputFileName;
@@ -77,7 +80,7 @@ public class TMLTranslator  {
 	
 	
 	public static void printCopyright() {
-		System.out.println("TMLTranslator: (C) GET/ENST, Ludovic Apvrille, Ludovic.Apvrille@enst.fr");
+		System.out.println("TMLTranslator: (C) GET/ENST, Ludovic APVRILLE, Andrea ENRICI\n{ludovic.apvrille, andrea.enrici}@telecom-paristech.fr");
 		System.out.println("TMLTranslator is released under a CECILL License. See http://www.cecill.info/index.en.html");
 		System.out.println("For more information on TURTLE related technologies, please consult http://ttool.telecom-paristech.fr/");
 		
@@ -357,6 +360,31 @@ public class TMLTranslator  {
 		//System.out.println("SystemC conversion not yet implemented");
 		return true;
 	}
+
+	public static boolean convertToSystemC3() {
+
+		tmltranslator.tomappingsystemc3.TML2MappingSystemC map;	
+
+		System.out.println("Converting to SystemC3...");
+		if( tmap == null )	{
+			System.out.println("Taking TMLModeling...");
+			map = new tmltranslator.tomappingsystemc3.TML2MappingSystemC( tmlm );
+		}
+		else	{
+			System.out.println("Taking TMLMapping...");
+			map = new tmltranslator.tomappingsystemc3.TML2MappingSystemC( tmap );
+		}
+		map.generateSystemC( debug, true );
+		try {
+			map.saveFile( outputFileName, "appmodel" );
+		}
+		catch( Exception e ) {
+			System.out.println( "SystemC generation failed: " + e.getMessage() );
+			return false;
+		}
+		System.out.println( "Sorry...SystemC3 conversion not yet implemented" );
+		return true;
+	}
 	
 	public static boolean convertToTML() {
 		
@@ -482,6 +510,8 @@ public class TMLTranslator  {
 		case 4:
 			convert = convertToTML();
 			break;
+		case 5:
+			convert = convertToSystemC3();
 		}
 		
 		if (!convert) {
diff --git a/src/tmltranslator/TMLCP.java b/src/tmltranslator/TMLCP.java
index 0024b391782a337e08a0422be3269d9326197746..804101fa1b44a38102aa890bd3787a8a8f7c0449 100755
--- a/src/tmltranslator/TMLCP.java
+++ b/src/tmltranslator/TMLCP.java
@@ -50,9 +50,9 @@ import tmltranslator.tmlcp.*;
 import myutil.*;
 
 public class TMLCP extends TMLElement {
-    private TMLCPSection mainCP;
-    private ArrayList<TMLCPSection> otherCPs; //Ref to other CPs
-    private ArrayList<TMLSDSection> sds; //Ref to SDs
+    private CPActivityDiagram mainCP;
+    private ArrayList<CPActivityDiagram> otherCPs; //Ref to other CPs
+    private ArrayList<CPSequenceDiagram> sds; //Ref to SDs
 	
 	
 	private int hashCode;
@@ -65,8 +65,8 @@ public class TMLCP extends TMLElement {
   }
 	
   private void init() {
-  	otherCPs = new ArrayList<TMLCPSection>();
-    sds = new ArrayList<TMLSDSection>();
+  	otherCPs = new ArrayList<CPActivityDiagram>();
+    sds = new ArrayList<CPSequenceDiagram>();
   }
 	
 	private void computeHashCode() {
@@ -76,10 +76,10 @@ public class TMLCP extends TMLElement {
 		//System.out.println("TARCHI hashcode = " + hashCode); 
 	}
 
-	private boolean checkDiagramDeclaration( TMLSDSection _tmlsdSection )	{
+	private boolean checkDiagramDeclaration( CPSequenceDiagram _tmlsdSection )	{
 		
 		int i;
-		TMLCPSection CPsection;
+		CPActivityDiagram CPsection;
 
 		//first check the main CP
 		if( mainCP.containsSDDiagram( _tmlsdSection.getName() ) )	{
@@ -97,10 +97,10 @@ public class TMLCP extends TMLElement {
 		}
 	}
 
-	private boolean checkDiagramDeclaration( TMLCPSection _tmlcpSection )	{
+	private boolean checkDiagramDeclaration( CPActivityDiagram _tmlcpSection )	{
 
 		int i;
-		TMLCPSection CPsection;
+		CPActivityDiagram CPsection;
 
 		if( mainCP.containsADDiagram( _tmlcpSection.getName() ) )	{ //first check in the main CP's list
 			return true;
@@ -116,11 +116,11 @@ public class TMLCP extends TMLElement {
 		}
 	}
 	
-	private boolean checkMultipleDiagramDeclaration( TMLSDSection _tmlsdSection )	{
+	private boolean checkMultipleDiagramDeclaration( CPSequenceDiagram _tmlsdSection )	{
 		
 		int i, counterSD = 0;
 		String tempString;
-		TMLSDSection tempSD;
+		CPSequenceDiagram tempSD;
 
 		for( i = 0; i < sds.size(); i++ )	{
 			tempSD = sds.get(i);
@@ -132,11 +132,11 @@ public class TMLCP extends TMLElement {
 		return ( counterSD > 0 );
 	}
 
-	private boolean checkMultipleDiagramDeclaration( TMLCPSection _tmlcpSection )	{
+	private boolean checkMultipleDiagramDeclaration( CPActivityDiagram _tmlcpSection )	{
 
 		int i, counterAD = 0;
 		String tempString;
-		TMLCPSection tempAD;
+		CPActivityDiagram tempAD;
 
 		for( i = 0; i < otherCPs.size(); i++ )	{
 			tempAD = otherCPs.get(i);
@@ -158,11 +158,11 @@ public class TMLCP extends TMLElement {
 	}
 	
 	
-	public void setMainCP(TMLCPSection _tmlcpSection) {
+	public void setMainCP(CPActivityDiagram _tmlcpSection) {
 		mainCP = _tmlcpSection;
 	}
 	
-	public void addTMLCPSection( TMLCPSection _tmlcpSection ) throws UndeclaredDiagramException, MultipleDiagDeclarationsException {
+	public void addCPActivityDiagram( CPActivityDiagram _tmlcpSection ) throws UndeclaredDiagramException, MultipleDiagDeclarationsException {
 
 		if( checkDiagramDeclaration( _tmlcpSection ) )	{
 			if( checkMultipleDiagramDeclaration( _tmlcpSection ) )	{
@@ -179,7 +179,7 @@ public class TMLCP extends TMLElement {
 		}
   }
     
-  public void addTMLSDSection( TMLSDSection _tmlsdSection ) throws UndeclaredDiagramException, MultipleDiagDeclarationsException	{
+  public void addCPSequenceDiagram( CPSequenceDiagram _tmlsdSection ) throws UndeclaredDiagramException, MultipleDiagDeclarationsException	{
 
 		if( checkDiagramDeclaration( _tmlsdSection ) )	{
 			if( checkMultipleDiagramDeclaration( _tmlsdSection ) )	{
@@ -205,15 +205,15 @@ public class TMLCP extends TMLElement {
 		return sds.size();
 	}
 
-	public ArrayList<TMLCPSection> getCPSections()	{
+	public ArrayList<CPActivityDiagram> getCPSections()	{
 		return otherCPs;
 	}
 
-	public ArrayList<TMLSDSection> getSDSections()	{
+	public ArrayList<CPSequenceDiagram> getSDSections()	{
 		return sds;
 	}
 
-	public TMLCPSection getMainCP()	{
+	public CPActivityDiagram getMainCP()	{
 		return mainCP;
 	}
 
@@ -222,7 +222,7 @@ public class TMLCP extends TMLElement {
 		ArrayList<String> undefinedSDs = new ArrayList<String>();
 		ArrayList<String> SDlist;
 		String declaredSD;
-		TMLSDSection definedSD;
+		CPSequenceDiagram definedSD;
 		boolean isSDdefined = false;
 		int i, j, k;
 		
@@ -245,7 +245,7 @@ public class TMLCP extends TMLElement {
 
 		//then check in all other CPs
 		isSDdefined = false;
-		TMLCPSection AD;
+		CPActivityDiagram AD;
 
 		for( k = 0; k < otherCPs.size(); k++ )	{
 			AD = otherCPs.get(k);
@@ -274,7 +274,7 @@ public class TMLCP extends TMLElement {
 		ArrayList<String> undefinedADs = new ArrayList<String>();
 		ArrayList<String> ADlist;
 		String declaredAD;
-		TMLCPSection definedAD;
+		CPActivityDiagram definedAD;
 		boolean isADdefined = false;
 		int i, j, k;
 		
@@ -297,7 +297,7 @@ public class TMLCP extends TMLElement {
 
 		//then check in all other CPs
 		isADdefined = false;
-		TMLCPSection AD;
+		CPActivityDiagram AD;
 
 		for( k = 0; k < otherCPs.size(); k++ )	{
 			AD = otherCPs.get(k);
@@ -322,7 +322,7 @@ public class TMLCP extends TMLElement {
 
 	public void correctReferences()	{
 		
-		TMLCPSection CPsection;
+		CPActivityDiagram CPsection;
 		int i;
 
 		mainCP.correctReferences( this );
@@ -334,11 +334,11 @@ public class TMLCP extends TMLElement {
 
 	public void printDataStructure()	{
 
-		ArrayList<TMLCPSection> CPlist = new ArrayList<TMLCPSection>();
-		ArrayList<TMLSDSection> SDlist = new ArrayList<TMLSDSection>();
+		ArrayList<CPActivityDiagram> CPlist = new ArrayList<CPActivityDiagram>();
+		ArrayList<CPSequenceDiagram> SDlist = new ArrayList<CPSequenceDiagram>();
 		ArrayList<TMLAttribute> listAttributes = new ArrayList<TMLAttribute>();
-		TMLCPSection tempCP;
-		TMLSDSection tempSD;
+		CPActivityDiagram tempCP;
+		CPSequenceDiagram tempSD;
 		TMLAttribute attr;
 		int i, j, k;
 
@@ -383,8 +383,8 @@ public class TMLCP extends TMLElement {
 			ElementsList = tempCP.getElements();
 			System.out.println( "\tDeclared elements:" );
 			for( j = 0; j < ElementsList.size(); j++ )	{
-				if( ElementsList.get(j) instanceof TMLCPRefCP )	{
-					TMLCPRefCP refCP = (TMLCPRefCP) ElementsList.get(j);
+				if( ElementsList.get(j) instanceof CPRefAD )	{
+					CPRefAD refCP = (CPRefAD) ElementsList.get(j);
 					tempCP = refCP.getReference();
 					ADList = tempCP.getADlist();
 					System.out.println( "\tPrinting from reference to " + tempCP.getName() );
@@ -394,7 +394,7 @@ public class TMLCP extends TMLElement {
 					System.out.println( "\tStop printing from reference" );
 				}
 				/*else	{
-					TMLSDSection tempSD = tempElem.getReference();
+					CPSequenceDiagram tempSD = tempElem.getReference();
 				}*/
 				System.out.println( "\t\t\t" + ElementsList.get(j) );
 			}
diff --git a/src/tmltranslator/TMLCPTextSpecification.java b/src/tmltranslator/TMLCPTextSpecification.java
new file mode 100755
index 0000000000000000000000000000000000000000..e408f41cee5c1298885d4ce8520090d12be91bc4
--- /dev/null
+++ b/src/tmltranslator/TMLCPTextSpecification.java
@@ -0,0 +1,2588 @@
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
+*
+* ludovic.apvrille AT telecom-paristech.fr
+* andrea.enrici 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.
+*
+* /**
+* Class TMLTextSpecification
+* Import and export of TML CP textual specifications
+* Creation: 02/06/2014
+* @version 1.0 02/06/2014
+* @author Ludovic APVRILLE, Andrea ENRICI
+* @see
+*/
+
+
+package tmltranslator;
+
+import java.util.*;
+import java.io.*;
+import myutil.*;
+
+public class TMLCPTextSpecification {
+	public final static String CR = "\n";
+	public final static String SP = " ";
+	public final static String CR2 = "\n\n";
+	public final static String SC = ";";
+	public final static String C = ",";
+    
+    private String spec;
+	private String title;
+	
+	private TMLModeling tmlm;
+	private ArrayList<TMLTXTError> errors;
+	private ArrayList<TMLTXTError> warnings;
+	
+	// For reading TMLTXT specifications
+	private boolean inDec = true;
+	private boolean inTask = false;
+	private boolean inTaskDec = false;
+	private boolean inTaskBehavior = false;
+	private TMLTask task;
+	private TMLActivityElement tmlae;
+	private ArrayList<TMLParserSaveElt> parses;
+	
+	private static String keywords[] = {"BOOL", "INT", "NAT", "CHANNEL", "EVENT", "REQUEST", "LOSSYCHANNEL", "LOSSYEVENT", "LOSSYREQUEST", "BRBW", "NBRNBW", 
+		"BRNBW", "INF", "NIB", "NINB", "TASK", "ENDTASK", "IF", "ELSE", "ORIF", "ENDIF", "FOR", "ENDFOR",
+	"SELECTEVT", "CASE", "ENDSELECTEVT", "ENDCASE", "WRITE", "READ", "WAIT", "NOTIFY", "NOTIFIED", "RAND", "CASERAND", "ENDRAND", "ENDCASERAND", "EXECI", "EXECC", "DELAY", "RANDOM",
+	"RANDOMSEQ", "ENDRANDOMSEQ", "SEQ", "ENDSEQ"};
+	
+	private String channeltypes[] = {"BRBW", "NBRNBW", "BRNBW"};
+	private String eventtypes[] = {"INF", "NIB", "NINB"};
+	
+	private String beginArray[] = {"TASK", "FOR", "IF", "ELSE", "ORIF", "SELECTEVT", "CASE", "RAND", "CASERAND", "RANDOMSEQ", "SEQ"};
+	private String endArray[] = {"ENDTASK", "ENDFOR", "ENDIF", "ELSE", "ORIF", "ENDSELECTEVT", "ENDCASE", "ENDRAND", "ENDCASERAND", "ENDRANDOMSEQ", "ENDSEQ"};	
+	
+	public TMLCPTextSpecification(String _title) {
+		title = _title;
+    }   
+	
+	public TMLCPTextSpecification(String _title, boolean reset) {
+		title = _title;
+		if (reset) {
+			DIPLOElement.resetID();
+		}
+    }
+	
+	public void saveFile(String path, String filename) throws FileException {
+		TraceManager.addUser("Saving TMLCP spec file in " + path + filename);
+        FileUtils.saveFile(path + filename, spec);
+    }
+	
+	public TMLModeling getTMLModeling() {
+		return tmlm;
+	}
+	
+	public ArrayList<TMLTXTError> getErrors() {
+		return errors;
+	}  
+	
+	public ArrayList<TMLTXTError> getWarnings() {
+		return warnings;
+	}
+	
+	
+	
+	public void indent() {
+		indent(4);
+	}
+	
+	public void indent(int _nbDec) {
+		int dec = 0;
+        int indexEnd;
+        String output = "";
+        String tmp;
+        int nbOpen = 0;
+        int nbClose = 0;
+		
+		while ( (indexEnd = spec.indexOf('\n')) > -1) {
+			tmp = spec.substring(0, indexEnd+1);
+			try {
+                spec = spec.substring(indexEnd+1, spec.length());
+            } catch (Exception e) {
+                spec = "";
+            }
+			nbOpen = nbOfOpen(tmp);
+            nbClose = nbOfClose(tmp);
+			dec -= nbClose * _nbDec;
+            tmp = Conversion.addHead(tmp.trim(), ' ', dec);
+            dec += nbOpen * _nbDec;
+			//TraceManager.addDev("dec=" + dec);
+            output += tmp + "\n";
+		}
+		spec = output;
+	}
+	
+	private int nbOfOpen(String tmp) {
+		return nbOf(tmp, beginArray);
+	}
+	
+	private int nbOfClose(String tmp) {
+		return nbOf(tmp, endArray);
+	}
+	
+	private int nbOf(String _tmp, String[] array) {
+		String tmp;
+		int size;
+		
+		for(int i=0; i<array.length; i++) {
+			if (_tmp.startsWith(array[i])) {
+				tmp = _tmp.substring(array[i].length(), _tmp.length());
+				//TraceManager.addDev("tmp=" + tmp + " _tmp" + _tmp + " array=" + array[i]);
+				if ((tmp.length() == 0) || (tmp.charAt(0) == ' ') || (tmp.charAt(0) == '(') || (tmp.charAt(0) == '\n')) {
+						//TraceManager.addDev("Returning 1!!");
+						return 1;
+				}
+			}
+		}
+		return 0;
+	}
+	
+	public String toString() {
+		return spec;
+	}
+	
+	public String toTextFormat( TMLModeling tmlm ) {
+		tmlm.sortByName();
+		spec = makeDeclarations(tmlm);
+		spec += makeTasks(tmlm);
+		indent();
+		return spec;
+	}
+
+	public String toTextFormat( TMLMapping tmap ) {
+
+		/*tmap.sortByName();
+		spec = makeDeclarations( tmap );
+		spec += makeTasks( tmap );
+		indent();
+		return spec;*/
+		return "FAKE";
+	}
+	
+	public String makeDeclarations(TMLModeling tmlm) {
+		int i;
+		String sb = "";
+		sb += "// TML Communication Pattern - FORMAT 0.1" + CR;
+		sb += "// Communication Pattern: " + title + CR;
+		sb += "// Generated: " + new Date().toString() + CR2; 
+		
+		sb += "// Channels" + CR;
+		for(TMLChannel ch:tmlm.getChannels()) {
+			sb += "CHANNEL" + SP + ch.getName() + SP + TMLChannel.getStringType(ch.getType()) + SP + ch.getSize();
+			if (!ch.isInfinite()) {
+				sb += SP + ch.getMax();
+			}
+			sb += SP + ch.getOriginTask().getName() + SP + ch.getDestinationTask().getName() + CR;
+			
+			if (ch.isLossy()) {
+				sb += "LOSSYCHANNEL" + SP + ch.getName() + SP + ch.getLossPercentage() + SP + ch.getMaxNbOfLoss() + CR;
+			}
+		}
+		sb+= CR;
+		
+		sb += "// Events" + CR;
+		for(TMLEvent evt:tmlm.getEvents()) {
+			sb += "EVENT" + SP + evt.getName() + "(";
+				for(i=0; i<evt.getNbOfParams(); i++) {
+					if (i != 0) {
+						sb+= ", ";
+					}
+					sb += TMLType.getStringType(evt.getType(i).getType());
+				}
+				sb += ")";
+			sb += SP + evt.getTypeTextFormat();
+			if (!evt.isInfinite()) {
+				sb += SP + evt.getMaxSize();
+			}
+			sb +=  SP + evt.getOriginTask().getName() + SP + evt.getDestinationTask().getName();
+			
+			sb+= CR;
+			
+			if (evt.isLossy()) {
+				sb += "LOSSYEVENT" + SP + evt.getName() + SP + evt.getLossPercentage() + SP + evt.getMaxNbOfLoss() + CR;
+			}
+		}
+		sb+= CR;
+		
+		sb += "// Requests" + CR;
+		for(TMLRequest request:tmlm.getRequests()) {
+			sb += "REQUEST" + SP + request.getName() + "(";
+				for(i=0; i<request.getNbOfParams(); i++) {
+					if (i != 0) {
+						sb+= ", ";
+					}
+					sb += TMLType.getStringType(request.getType(i).getType());
+				}
+				sb += ")";
+			for(TMLTask t: request.getOriginTasks()) {
+				sb+= SP + t.getName();
+			}
+			sb += SP + request.getDestinationTask().getName();
+			sb+= CR;
+			
+			if (request.isLossy()) {
+				sb += "LOSSYREQUEST" + SP + request.getName() + SP + request.getLossPercentage() + SP + request.getMaxNbOfLoss() + CR;
+			}
+		}
+		sb+= CR;
+		
+		return sb;
+		
+	}
+	
+	public String makeTasks(TMLModeling tmlm) {
+		String sb = "";
+		for(TMLTask task: tmlm.getTasks()) {
+			sb += "TASK" + SP + task.getName() + CR;
+			sb += makeActivity(task);
+			sb += "ENDTASK" + CR2;
+		}
+		return sb;
+	}
+	
+	public String makeActivity(TMLTask task) {
+		String sb = "";
+		sb += "//Local variables" + CR;
+		
+		for(TMLAttribute attr: task.getAttributes()) {
+			sb += TMLType.getStringType(attr.getType().getType()) + SP + attr.getName();
+			if ((attr.getInitialValue() != null) && (attr.getInitialValue().length() > 0)){
+				sb += " = " + attr.getInitialValue();
+			}
+			sb += CR;
+		}
+		
+		sb += CR;
+		sb += "//Behavior" + CR;
+		sb += makeBehavior(task, task.getActivityDiagram().getFirst());
+		
+		return sb;
+	}
+	
+	public String makeBehavior(TMLTask task, TMLActivityElement elt) {
+		String code, code1, code2;
+		TMLForLoop tmlfl;
+		TMLActivityElementChannel tmlch;
+		TMLActivityElementEvent tmlevt;
+		TMLSendRequest tmlreq;
+		TMLEvent evt;
+		TMLRandom random;
+		int i;
+		String tmp1, tmp2;
+		
+		if (elt instanceof TMLStartState) {
+			return makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLStopState) {
+			return "";
+			
+		} else if (elt instanceof TMLExecI) {
+			code = "EXECI" + SP + modifyString(((TMLExecI)elt).getAction()) + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLExecIInterval) {
+			code = "EXECI" + SP + modifyString(((TMLExecIInterval)elt).getMinDelay()) + SP + modifyString(((TMLExecIInterval)elt).getMaxDelay()) + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLExecC) {
+			code = "EXECC" + SP + modifyString(((TMLExecC)elt).getAction()) + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLExecCInterval) {
+			code = "EXECC" + SP + modifyString(((TMLExecCInterval)elt).getMinDelay()) + SP + modifyString(((TMLExecCInterval)elt).getMaxDelay()) + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLDelay) {
+			tmp1 = ((TMLDelay)elt).getMinDelay();
+			tmp2 = ((TMLDelay)elt).getMaxDelay();
+			if (tmp1.compareTo(tmp2) == 0) {
+				code = "DELAY" + SP + modifyString(((TMLDelay)elt).getMinDelay()) + SP + modifyString(((TMLDelay)elt).getUnit()) + CR;
+			} else {
+				code = "DELAY" + SP + modifyString(((TMLDelay)elt).getMinDelay()) + SP + modifyString(((TMLDelay)elt).getMaxDelay()) + SP + modifyString(((TMLDelay)elt).getUnit()) + CR;
+			}
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLForLoop) {
+			tmlfl = (TMLForLoop)elt;
+			code = "FOR(" + tmlfl.getInit() + SC + SP;
+				code += tmlfl.getCondition() + SC + SP;
+				code += tmlfl.getIncrement() + ")" + CR;
+			code += makeBehavior(task, elt.getNextElement(0));
+			return code + "ENDFOR" + CR + makeBehavior(task, elt.getNextElement(1));
+		
+		} else if (elt instanceof TMLRandom) {
+			random = (TMLRandom)elt;
+			code = "RANDOM" + SP + modifyString(""+random.getFunctionId()) + SP;
+			code += modifyString(random.getVariable()) + SP;
+			code += modifyString(random.getMinValue()) + SP;
+			code += modifyString(random.getMaxValue()) + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLActionState) {
+			code = modifyString(((TMLActivityElementWithAction)elt).getAction()) + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLWriteChannel) {
+			tmlch = (TMLActivityElementChannel)elt;
+			code = "WRITE ";
+			for(int k=0; k<tmlch.getNbOfChannels(); k++) {
+				code = code + tmlch.getChannel(k).getName() + SP;
+			}
+			code = code + modifyString(tmlch.getNbOfSamples()) + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLReadChannel) {
+			tmlch = (TMLActivityElementChannel)elt;
+			code = "READ " + tmlch.getChannel(0).getName() + SP + modifyString(tmlch.getNbOfSamples()) + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLSendEvent) {
+			tmlevt = (TMLActivityElementEvent)elt;
+			code = "NOTIFY " + tmlevt.getEvent().getName() + " " + tmlevt.getAllParams(" ") + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLWaitEvent) {
+			tmlevt = (TMLActivityElementEvent)elt;
+			code = "WAIT " + tmlevt.getEvent().getName() + " " + tmlevt.getAllParams(" ") + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLNotifiedEvent) {
+			tmlevt = (TMLActivityElementEvent)elt;
+			code = "NOTIFIED " + tmlevt.getEvent().getName() + " " + tmlevt.getVariable() + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		} else if (elt instanceof TMLSendRequest) {
+			tmlreq = (TMLSendRequest)elt;
+			code = "REQUEST " + tmlreq.getRequest().getName() + " " + tmlreq.getAllParams(" ") + CR;
+			return code + makeBehavior(task, elt.getNextElement(0));
+			
+		}  else if (elt instanceof TMLSequence) {
+			code = "";
+			for(i=0; i<elt.getNbNext(); i++) {
+				code += makeBehavior(task, elt.getNextElement(i));
+			}
+			
+			return code;
+			
+		} else if (elt instanceof TMLChoice) {
+			TMLChoice choice = (TMLChoice)elt;
+			code = "";
+			if (choice.getNbGuard() !=0 ) {
+				code1 = "";
+                int index1 = choice.getElseGuard(), index2 = choice.getAfterGuard();
+				int nb = Math.max(choice.nbOfNonDeterministicGuard(), choice.nbOfStochasticGuard());
+				if (nb > 0) {
+					// Assumed to be a non deterministic choice
+					code += "RAND" + CR;
+				}
+				nb = 0;
+                for(i=0; i<choice.getNbGuard(); i++) {
+					if (i != index2) {
+						if (choice.isNonDeterministicGuard(i)) {
+							code2 = "" + (int)(Math.floor(100/choice.getNbGuard()));
+							nb ++;
+						} else if (choice.isStochasticGuard(i)){
+							code2 = prepareString(choice.getStochasticGuard(i));
+							nb ++;
+						} else {
+							code2 = modifyString(choice.getGuard(i));
+							code2 = Conversion.replaceAllChar(code2, '[', "(");
+							code2 = Conversion.replaceAllChar(code2, ']', ")");
+						}
+						//TraceManager.addDev("guard = " + code1 + " i=" + i);
+						if (nb != 0) {
+							/*if (choice.isNonDeterministicGuard(i)) {
+								code = "CASERAND 50";
+							} else {
+								code = "CASERAND " + prepareString(choice.getStochasticGuard(i));
+								
+							}*/
+							//nb ++;
+							if (i != index1) {
+								code += "CASERAND " + code2 + CR;
+								code += makeBehavior(task, elt.getNextElement(i));
+								code += "ENDCASERAND" + CR;
+							}
+						} else {
+							if (i==0) {
+								code += "IF " + code2;
+							} else {
+								if (i != index1) {
+									code += "ORIF " + code2;
+								} else {
+									code += "ELSE";
+								}
+							}
+							code += CR + makeBehavior(task, elt.getNextElement(i));
+						}
+					}
+                }
+				if (nb > 0) {
+					// Assumed to be a non deterministic choice
+					code += "ENDRAND" + CR;
+				} else {
+					code += "ENDIF" + CR;
+				}
+				if (index2 != -1) {
+					code += makeBehavior(task, elt.getNextElement(index2));
+				}
+            }
+			return code;
+			
+		} else if (elt instanceof TMLSelectEvt) {
+			code = "SELECTEVT" + CR;
+			for(i=0; i<elt.getNbNext(); i++) {
+				try {
+				tmlevt = (TMLActivityElementEvent)(elt.getNextElement(i));
+				code += "CASE ";
+				code += tmlevt.getEvent().getName() + " " + tmlevt.getAllParams(" ") + CR;
+				code += makeBehavior(task, elt.getNextElement(i).getNextElement(0));
+				code += "ENDCASE" + CR;
+				} catch (Exception e) {
+					TraceManager.addError("Non-event receiving following a select event operator");
+				}
+			}
+			code += "ENDSELECTEVT" + CR;
+			return code;
+			
+		} else if (elt instanceof TMLRandomSequence) {
+			code = "RANDOMSEQ" + CR;
+			for(i=0; i<elt.getNbNext(); i++) {
+				code += "SEQ" + CR;
+				code += makeBehavior(task, elt.getNextElement(i));
+				code += "ENDSEQ" + CR;
+			}
+			code += "ENDRANDOMSEQ" + CR;
+			return code;
+			
+		} else {
+			if (elt == null) {
+				return "";
+			}
+			TraceManager.addDev("Unrecognized element: " + elt);
+			return makeBehavior(task, elt.getNextElement(0));
+		}
+	}
+	
+	public boolean makeTMLModeling(String _spec) {
+		spec = _spec;
+		tmlm = new TMLModeling();
+		errors = new ArrayList<TMLTXTError>();  
+		warnings = new ArrayList<TMLTXTError>();
+		
+		spec = Conversion.removeComments(spec);
+		//TraceManager.addDev(spec);
+		browseCode();
+		
+		return (errors.size() == 0);
+	}
+	
+	public String printErrors() {
+		String ret = "";
+		for(TMLTXTError error: errors) {
+			ret += "ERROR at line " + error.lineNb + ": " + error.message + CR;
+			try {
+				ret += "->" + spec.split("\n")[error.lineNb] + CR2;
+			} catch (Exception e) {
+				ret += "(Code line not accessible)" + CR;
+			}
+		}
+		return ret;
+	}
+	
+	public String printWarnings() {
+		String ret = "";
+		for(TMLTXTError error: warnings) {
+			ret += "WARNING at line " + error.lineNb + CR;
+			ret += error.message + CR; 
+		}
+		return ret;
+	}
+	
+	public String printSummary() {
+		String ret = "";
+		if (errors.size() == 0) {
+			ret += printWarnings();
+			ret += "Compilation successful" + CR;
+			ret += "No error, " + warnings.size() + " warning(s)" + CR;
+		} else {
+			ret += printErrors() + CR + printWarnings() + CR;
+			ret += "Compilation failed" + CR;
+			ret += errors.size() + " error(s), "+ warnings.size() + " warning(s)" + CR;	
+		}
+		
+		return ret;
+	}
+	
+	public void browseCode() {
+		// Browse lines of code one after the other
+		// Build accordinlgy the TMLModeling and updates errors and warnings
+		// In case of fatal error, immedialty quit code bowsing
+		
+		StringReader sr = new StringReader(spec);
+        BufferedReader br = new BufferedReader(sr);
+        String s;
+		String s1;
+		String [] split;
+		int lineNb = 0;
+		
+		inDec = true;
+		inTask = false;
+		inTaskDec = false;
+		inTaskBehavior = false;
+		
+		
+		String instruction;
+        
+		parses = new ArrayList<TMLParserSaveElt>();
+		
+        try {
+            while((s = br.readLine()) != null) {
+				if (s != null) {
+					s = s.trim();
+					//TraceManager.addDev("s=" + s);
+					s = removeUndesiredWhiteSpaces(s, lineNb);
+					s1 = Conversion.replaceAllString(s, "\t", " ");
+					s1 = Conversion.replaceRecursiveAllString(s1, "  ", " ");
+					//TraceManager.addDev("s1=" + s1);
+					if (s1 != null) {
+						split = s1.split("\\s");
+						if (split.length > 0) {
+							//TraceManager.addDev("analyse");
+							analyseInstruction(s, lineNb, split);
+							//TraceManager.addDev("end analyse");
+						}
+					}
+					
+					lineNb++;
+				}
+            }
+        } catch (Exception e) {
+            TraceManager.addError("Exception when reading specification: " + e.getMessage());
+			addError(0, lineNb, 0, "Exception when reading specification");
+        }
+	}
+	
+	public void addError(int _type, int _lineNb, int _charNb, String _msg) {
+		TMLTXTError error = new TMLTXTError(_type);
+		error.lineNb = _lineNb;
+		error.charNb = _charNb;
+		error.message = _msg;
+		errors.add(error);
+	}
+	
+	public int analyseInstruction(String _line, int _lineNb, String[] _split) {
+		String error;
+		String params;
+		String id;
+		TMLChannel ch;
+		TMLEvent evt;
+		TMLRequest request;
+		TMLTask t1, t2;
+		TMLAttribute attribute;
+		TMLType type;
+		TMLStopState stop;
+		TMLRandom random;
+		int tmp, tmp0, tmp1, i;
+		int dec = 0;
+		boolean blocking;
+		TMLParserSaveElt parseElt;
+		
+		//TraceManager.addDev("Analyzing instruction:" + _line);
+		
+		if (parses.size() > 0) {
+			parseElt = parses.get(0);
+			if ((parseElt.type == TMLParserSaveElt.SELECTEVT) && ((!isInstruction("CASE", _split[0]) && (!isInstruction("ENDSELECTEVT", _split[0]))))) {
+				error = "CASE or ENDSELECTEVT instruction expected";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			if ((parseElt.type == TMLParserSaveElt.RAND) && ((!isInstruction("CASERAND", _split[0]) && (!isInstruction("ENDRAND", _split[0]))))) {
+				error = "CASERAND or ENDRAND instruction expected";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+		}
+		
+		// CHANNEL
+		if(isInstruction("CHANNEL", _split[0])) {
+			if (!inDec) {
+				error = "A channel may not be declared in a non-declaration part of a TML specification";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!((_split.length > 5) && (_split.length < 8))) {
+				error = "A channel must be declared with only 5 or 6 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (_split.length == 7) {
+				dec = 1;
+			} else {
+				dec = 0;
+			}
+			
+			if (!checkParameter("CHANNEL", _split, 1, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("CHANNEL", _split, 2, 2, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("CHANNEL", _split, 3, 1, _lineNb)) {
+				return -1;
+			}
+			
+			if (_split.length == 7) {
+				if (!checkParameter("CHANNEL", _split, 4, 1, _lineNb)) {
+					return -1;
+				}
+			}
+			
+			
+			if (!checkParameter("CHANNEL", _split, 4 + dec, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("CHANNEL", _split, 5 + dec, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (tmlm.getChannelByName(_split[1]) != null) {
+				error = "Duplicate definition of channel " + _split[1];
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (_split[2].toUpperCase().compareTo("NIB") == 0) {
+				
+			}
+			
+			ch = new TMLChannel(_split[1], null);
+			ch.setTypeByName(_split[2]);
+			try {
+				tmp = Integer.decode(_split[3]).intValue();
+				} catch (Exception e) {tmp = 4;}
+				ch.setSize(tmp);
+				
+				if (_split.length == 7) {
+					try {
+						tmp = Integer.decode(_split[4]).intValue();
+					} catch (Exception e) {tmp = 8;}
+					//TraceManager.addDev("Setting max to" + tmp);
+					ch.setMax(tmp);
+				}
+				
+				t1 = tmlm.getTMLTaskByName(_split[4+dec]);
+				if (t1 == null) {
+					t1 = new TMLTask(_split[4+dec], null, null);
+					//TraceManager.addDev("New task:" + _split[4+dec]);
+					tmlm.addTask(t1);
+				}
+				t2 = tmlm.getTMLTaskByName(_split[5+dec]);
+				if (t2 == null) {
+					t2 = new TMLTask(_split[5+dec], null, null);
+					//TraceManager.addDev("New task:" + _split[5+dec]);
+					tmlm.addTask(t2);
+				}
+				ch.setTasks(t1, t2);
+				tmlm.addChannel(ch);
+		} // CHANNEL
+		
+		
+		// LOSSYCHANNEL
+		if(isInstruction("LOSSYCHANNEL", _split[0])) {
+			if (!inDec) {
+				error = "A lossychannel may not be declared in a non-declaration part of a TML specification";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!((_split.length > 3) && (_split.length < 5))) {
+				error = "A lossychannel must be declared with exactly 3 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			
+			if (!checkParameter("LOSSYCHANNEL", _split, 1, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("LOSSYCHANNEL", _split, 2, 1, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("LOSSYCHANNEL", _split, 3, 9, _lineNb)) {
+				return -1;
+			}
+			
+			
+			ch = tmlm.getChannelByName(_split[1]);
+			if (ch == null) {
+				error = "lossy channel not previsouly declared as a regular channel " + _split[1];
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			try {
+				tmp0 = Integer.decode(_split[2]).intValue();
+				} catch (Exception e) {tmp0 = 5;}
+			try {
+				tmp1 = Integer.decode(_split[3]).intValue();
+				} catch (Exception e) {tmp1 = -1;}
+				
+				ch.setLossy(true, tmp0, tmp1);
+		} // LOSSYCHANNEL
+		
+		// EVENT
+		if(isInstruction("EVENT", _split[0])) {
+			if (!inDec) {
+				error = "An event may not be declared in a non-declaration part of a TML specification";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!((_split.length > 4) && (_split.length < 7))) {
+				error = "An event must be declared with only 4 or 5 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (_split.length == 6) {
+				dec = 1;
+			} else {
+				dec = 0;
+			}
+			
+			id = getEvtId(_split[1]);
+			params = getParams(_split[1]);
+			
+			//TraceManager.addDev("Evt id=" + id +  "params=" + params);
+			
+			if (!checkParameter("EVENT", _split, 1, 4, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("EVENT", _split, 2, 3, _lineNb)) {
+				return -1;
+			}
+			
+			if (_split.length == 6) {
+				if (!checkParameter("EVENT", _split, 3, 1, _lineNb)) {
+					return -1;
+				}
+			}
+			
+			if (!checkParameter("EVENT", _split, 3 + dec, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("EVENT", _split, 4 + dec, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (tmlm.getEventByName(id) != null) {
+				error = "Duplicate definition of event " + id;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (_split[2].toUpperCase().compareTo("NIB") == 0) {
+				blocking = true;
+			} else {
+				blocking = false;
+			}
+			
+			if (_split[2].toUpperCase().compareTo("INF") == 0) {
+				tmp = -1;
+			} else {
+				try {
+					tmp = Integer.decode(_split[3]).intValue();
+				} catch (Exception e) {
+					error = "Unvalid parameter #3: should be a numeric value";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+			}
+			
+			evt = new TMLEvent(id, null, tmp, blocking);
+			evt.addParam(params);
+			
+			t1 = tmlm.getTMLTaskByName(_split[3+dec]);
+			if (t1 == null) {
+				t1 = new TMLTask(_split[3+dec], null, null);
+				//TraceManager.addDev("New task:" + _split[3+dec]);
+				tmlm.addTask(t1);
+			}
+			t2 = tmlm.getTMLTaskByName(_split[4+dec]);
+			if (t2 == null) {
+				t2 = new TMLTask(_split[4+dec], null, null);
+				//TraceManager.addDev("New task:" + _split[4+dec]);
+				tmlm.addTask(t2);
+			}
+			evt.setTasks(t1, t2);
+			tmlm.addEvent(evt);
+			
+			
+		} // EVENT
+		
+		// LOSSYEVENT
+		if(isInstruction("LOSSYEVENT", _split[0])) {
+			if (!inDec) {
+				error = "A lossyevent may not be declared in a non-declaration part of a TML specification";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!((_split.length > 3) && (_split.length < 5))) {
+				error = "A lossyevent must be declared with exactly 3 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			
+			if (!checkParameter("LOSSYEVENT", _split, 1, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("LOSSYEVENT", _split, 2, 1, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("LOSSYEVENT", _split, 3, 9, _lineNb)) {
+				return -1;
+			}
+			
+			
+			evt = tmlm.getEventByName(_split[1]);
+			if (evt == null) {
+				error = "lossyevent not previsouly declared as a regular event " + _split[1];
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			try {
+				tmp0 = Integer.decode(_split[2]).intValue();
+				} catch (Exception e) {tmp0 = 5;}
+			try {
+				tmp1 = Integer.decode(_split[3]).intValue();
+				} catch (Exception e) {tmp1 = -1;}
+				
+				evt.setLossy(true, tmp0, tmp1);
+		} // LOSSYEVENT
+		
+		// REQUEST
+		if((isInstruction("REQUEST", _split[0])) && (inDec)) {
+			if (!inDec) {
+				error = "A request may not be declared in a non-declaration part of a TML specification";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (_split.length < 4) {
+				error = "A request must be declared with at least 4 paremeters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			
+			id = getEvtId(_split[1]);
+			params = getParams(_split[1]);
+			
+			//TraceManager.addDev("Evt id=" + id +  "params=" + params);
+			
+			if (!checkParameter("REQUEST", _split, 1, 4, _lineNb)) {
+				return -1;
+			}
+			
+			for(i=2; i<_split.length; i++) {
+				if (!checkParameter("REQUEST", _split, i, 0, _lineNb)) {
+					return -1;
+				}
+			}
+			
+			if (tmlm.getRequestByName(id) != null) {
+				error = "Duplicate definition of request " + id;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			request = new TMLRequest(id, null);
+			request.addParam(params);
+			
+			for(i=2; i<_split.length; i++) {
+				t1 = tmlm.getTMLTaskByName(_split[i]);
+				if (t1 == null) {
+					t1 = new TMLTask(_split[i], null, null);
+					//TraceManager.addDev("New task:" + _split[i]);
+					tmlm.addTask(t1);
+				}
+				if ((i+1) == _split.length) {
+					request.setDestinationTask(t1);
+					t1.setRequested(true);
+					t1.setRequest(request);
+				} else {
+					request.addOriginTask(t1);
+				}
+			}
+			
+			tmlm.addRequest(request);
+		} // REQUEST
+		
+		// LOSSYREQUEST
+		if(isInstruction("LOSSYREQUEST", _split[0])) {
+			if (!inDec) {
+				error = "A lossyrequest may not be declared in a non-declaration part of a TML specification";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!((_split.length > 3) && (_split.length < 5))) {
+				error = "A lossyrequest must be declared with exactly 3 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			
+			if (!checkParameter("LOSSYREQUEST", _split, 1, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("LOSSYREQUEST", _split, 2, 1, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("LOSSYREQUEST", _split, 3, 9, _lineNb)) {
+				return -1;
+			}
+			
+			
+			request = tmlm.getRequestByName(_split[1]);
+			if (request == null) {
+				error = "lossyrequest not previsouly declared as a regular event " + _split[1];
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			try {
+				tmp0 = Integer.decode(_split[2]).intValue();
+				} catch (Exception e) {tmp0 = 5;}
+			try {
+				tmp1 = Integer.decode(_split[3]).intValue();
+				} catch (Exception e) {tmp1 = -1;}
+				
+				request.setLossy(true, tmp0, tmp1);
+		} // LOSSYREQUEST
+		
+		// TASK
+		if((isInstruction("TASK", _split[0]))) {
+			
+			//TraceManager.addDev("In task");
+			if (inTask) {
+				error = "A task may not be declared in the body of another task";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = true;
+			inTaskBehavior = false;
+			
+			if (_split.length != 2) {
+				error = "A request must be declared with exactly 2 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!checkParameter("TASK", _split, 1, 0, _lineNb)) {
+				return -1;
+			}
+			
+			//TraceManager.addDev("In task: 12");
+			task = tmlm.getTMLTaskByName(_split[1]);
+			if ((task != null)  && (task.getActivityDiagram() != null)) {
+				if (task.getActivityDiagram().getFirst() != null) {
+					error = "Duplicate definition for task "+ (_split[1]);
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+			}
+			//TraceManager.addDev("In task: 13");
+			if (task == null) {
+				task = new TMLTask(_split[1], null, null);
+				tmlm.addTask(task);
+				//TraceManager.addDev("New task:" + _split[1]);
+			}
+			
+			TMLStartState start = new TMLStartState("start", null);
+			task.getActivityDiagram().setFirst(start);
+			tmlae = start;
+			
+			
+		} // TASK
+		
+		
+		// ENDTASK
+		if((isInstruction("ENDTASK", _split[0]))) {
+			if (!inTask) {
+				error = "A endtask may not be used outside the body of a task";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			inDec = true;
+			inTask = false;
+			inTaskDec = false;
+			inTaskBehavior = false;
+			
+			stop = new TMLStopState("stop", null);
+			task.getActivityDiagram().addElement(stop);
+			tmlae.addNext(stop);
+			
+			task = null;
+		} // ENDTASK
+		
+		
+		// Attribute declaration
+		if ((isInstruction("INT", _split[0])) || (isInstruction("NAT", _split[0])) || (isInstruction("BOOL", _split[0]))){
+			if (!inTaskDec) {
+				error = "An attribute declaration must be done in a task right after its declaration, and before its bahavior";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			String inst = _split[0].toUpperCase();
+			
+			if (!((_split.length == 2) || (_split.length == 4))) {
+				error = "An attribute declaration must be done with either 1 or 3 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!checkParameter(inst, _split, 1, 0, _lineNb)) {
+				return -1;
+			}
+			
+			if (_split.length > 2) {
+				if (!checkParameter(inst, _split, 2, 5, _lineNb)) {
+					return -1;
+				}
+				if (!checkParameter(inst, _split, 3, 6, _lineNb)) {
+					return -1;
+				}
+			}
+			
+			//TraceManager.addDev("Adding attribute " + _split[0] + " " + _split[1]);
+			
+			TMLAttribute ta = new TMLAttribute(_split[1], new TMLType(TMLType.getType(_split[0])));
+			if (_split.length > 2) {
+				ta.initialValue = _split[3];
+			} else {
+				ta.initialValue = ta.getDefaultInitialValue();
+			}
+			task.addAttribute(ta);
+		} // Attribute declaration
+		
+		// RANDOM
+		if((isInstruction("RANDOM", _split[0]))) {
+			
+			if (!inTask) {
+				error = "A RANDOM operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if (_split.length != 5) {
+				error = "A RANDOM operation must be declared with exactly 4 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!checkParameter("RANDOM", _split, 1, 1, _lineNb)) {
+				return -1;
+			}
+			
+			if (!checkParameter("RANDOM", _split, 2, 0, _lineNb)) {
+				return -1;
+			}
+			
+			random = new TMLRandom("random", null);
+			try {
+			 random.setFunctionId(Integer.decode(_split[1]).intValue());
+			} catch (Exception e) {
+			}
+			
+			random.setVariable(_split[2]);
+			random.setMinValue(_split[3]);
+			random.setMaxValue(_split[4]);
+			
+			TraceManager.addDev("RANDOM min=" + random.getMinValue() + " max=" + random.getMaxValue());
+			
+			task.getActivityDiagram().addElement(random);
+			tmlae.addNext(random);
+			tmlae = random;
+			
+		} // RANDOM
+		
+		// READ
+		if((isInstruction("READ", _split[0]))) {
+			
+			if (!inTask) {
+				error = "A READ operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if (_split.length != 3) {
+				error = "A READ operation must be declared with exactly 3 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!checkParameter("READ", _split, 1, 0, _lineNb)) {
+				return -1;
+			}
+			
+			/*if (!checkParameter("READ", _split, 2, 7, _lineNb)) {
+				return -1;
+			}*/
+			
+			ch = tmlm.getChannelByName(_split[1]);
+			if (ch == null ){
+				error = "Undeclared channel: " +  _split[1];
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			if (ch.getDestinationTask() != task ){
+				error = "READ operations must be done only in destination task. Should be in task: " + ch.getDestinationTask().getName();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			
+			TMLReadChannel tmlrch = new TMLReadChannel(_split[1], null);
+			tmlrch.addChannel(ch);
+			tmlrch.setNbOfSamples(_split[2]);
+			task.getActivityDiagram().addElement(tmlrch);
+			tmlae.addNext(tmlrch);
+			tmlae = tmlrch;
+			
+		} // READ
+		
+		// WRITE
+		if((isInstruction("WRITE", _split[0]))) {
+			
+			if (!inTask) {
+				error = "A WRITE operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if (_split.length < 3) {
+				error = "A WRITE operation must be declared with at most 3 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!checkParameter("WRITE", _split, 1, 0, _lineNb)) {
+				return -1;
+			}
+			
+			TMLWriteChannel tmlwch = new TMLWriteChannel(_split[1], null);
+			for(int k=0; k<_split.length-2; k++) {
+				ch = tmlm.getChannelByName(_split[1+k]);
+				if (ch == null ){
+					error = "Undeclared channel: " +  _split[1+k];
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				if (ch.getOriginTask() != task ){
+					error = "WRITE operations must be done only in origin task. Should be in task: " + ch.getOriginTask().getName();
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				
+				tmlwch.addChannel(ch);
+			}
+			
+			tmlwch.setNbOfSamples(_split[2]);
+			task.getActivityDiagram().addElement(tmlwch);
+			tmlae.addNext(tmlwch);
+			tmlae = tmlwch;
+			
+		} // WRITE
+		
+		// NOTIFY
+		if((isInstruction("NOTIFY", _split[0]))) {
+			
+			if (!inTask) {
+				error = "A NOTIFY operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if (_split.length < 2) {
+				error = "A NOTIFY operation must be declared with at least 2 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			evt = tmlm.getEventByName(_split[1]);
+			if (evt == null) {
+				error = "Unknown event: " + _split[1] ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			dec = evt.getNbOfParams();
+			
+			if (_split.length != 2 + dec) {
+				error = "A NOTIFY operation on evt " + evt.getName() + " must be declared with exactly " + (1 + dec) + " parameters and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			TMLSendEvent sevt = new TMLSendEvent(evt.getName(), null);
+			sevt.setEvent(evt);
+			for(i=2; i<2 + dec; i++) {
+				sevt.addParam(_split[i]);
+			}
+			
+			task.getActivityDiagram().addElement(sevt);
+			tmlae.addNext(sevt);
+			tmlae = sevt;
+		} // NOTIFY
+		
+		// WAIT
+		if((isInstruction("WAIT", _split[0]))) {
+			
+			if (!inTask) {
+				error = "A WAIT operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if (_split.length < 2) {
+				error = "A WAIT operation must be declared with at least 2 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			evt = tmlm.getEventByName(_split[1]);
+			if (evt == null) {
+				error = "Unknown event: " + _split[1] ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			dec = evt.getNbOfParams();
+			
+			if (_split.length != 2 + dec) {
+				error = "A WAIT operation on evt " + evt.getName() + " must be declared with exactly " + (1 + dec) + " parameters and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			// Each param must be a declared attribute of the right type
+			for(i=2; i<2 + dec; i++) {	
+				attribute = task.getAttributeByName(_split[i]);
+				if (attribute == null) {
+					error = "Attribute: " + _split[i] + " is undeclared";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				if (attribute.type.getType() != evt.getType(i-2).getType()) {
+					error = "Attribute: " + _split[i] + " is not of the right type";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+			}
+			
+			
+			TMLWaitEvent wevt = new TMLWaitEvent(evt.getName(), null);
+			wevt.setEvent(evt);
+			for(i=2; i<2 + dec; i++) {	
+				wevt.addParam(_split[i]);
+			}
+			
+			task.getActivityDiagram().addElement(wevt);
+			tmlae.addNext(wevt);
+			tmlae = wevt;
+		} // WAIT
+		
+		// NOTIFIED
+		if((isInstruction("NOTIFIED", _split[0]))) {
+			
+			if (!inTask) {
+				error = "A NOTIFIED operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if (_split.length != 3) {
+				error = "A NOTIFIED operation must be declared with exactly 2 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			evt = tmlm.getEventByName(_split[1]);
+			if (evt == null) {
+				error = "Unknown event: " + _split[1] ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			attribute = task.getAttributeByName(_split[2]);
+			if (attribute == null) {
+				error = "Attribute: " + _split[2] + " is undeclared";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			if (attribute.type.getType() != TMLType.NATURAL) {
+				error = "Attribute: " + _split[2] + " should be of natural type";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			TMLNotifiedEvent nevt = new TMLNotifiedEvent(evt.getName(), null);
+			nevt.setEvent(evt);
+			nevt.setVariable(_split[2]);
+			
+			task.getActivityDiagram().addElement(nevt);
+			tmlae.addNext(nevt);
+			tmlae = nevt;
+		} // NOTIFIED
+		
+		// Send REQUEST
+		if((isInstruction("REQUEST", _split[0])) && (inTask)) {
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if (_split.length < 2) {
+				error = "A REQUEST operation must be declared with at least 1 parameter (request name), and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			request = tmlm.getRequestByName(_split[1]);
+			if (request == null) {
+				error = "Unknown request: " + _split[1] ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			dec = request.getNbOfParams();
+			
+			if (_split.length != 2 + dec) {
+				error = "A REQUEST operation on request " + request.getName() + " must be declared with exactly " + (1 + dec) + " parameters and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			TMLSendRequest sreq = new TMLSendRequest(request.getName(), null);
+			sreq.setRequest(request);
+			for(i=2; i<2 + dec; i++) {	
+				sreq.addParam(_split[i]);
+			}
+			
+			task.getActivityDiagram().addElement(sreq);
+			tmlae.addNext(sreq);
+			tmlae = sreq;
+		} // Send REQUEST
+		
+		// FOR
+		if((isInstruction("FOR", _split[0])) && (inTask)) {
+			//TraceManager.addDev("FOR encountered");
+			if (_split.length < 2) {
+				error = "FOR operation: missing parameters";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the three elements of FOR
+			String forp = _split[1];
+			String forps[];
+			tmp0 = forp.indexOf('(');
+				tmp1 = forp.lastIndexOf(')');
+				if ((tmp0 == -1) || (tmp1 == -1)) {
+					error = "FOR operation: badly formed parameters";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				forp = forp.substring(tmp0+1, tmp1);
+				forps = forp.split(";");
+				if (forps.length != 3) {
+					error = "FOR operation: badly formed parameters";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				
+				// All is ok: constructing the FOR
+				parseElt = new TMLParserSaveElt();
+				parseElt.type = TMLParserSaveElt.FOR;
+				parses.add(0, parseElt);
+				TMLForLoop loop = new TMLForLoop("loop", null);
+				loop.setInit(forps[0].trim());
+				loop.setCondition(forps[1].trim());
+				loop.setIncrement(forps[2].trim());
+				task.getActivityDiagram().addElement(loop);
+				parseElt.tmlae = loop;
+				tmlae.addNext(loop);
+				tmlae = loop;
+				
+		} // FOR
+		
+		// ENDFOR
+		if(isInstruction("ENDFOR", _split[0])) {
+			if (!inTask) {
+				error = "ENDFOR: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the first element of the stack
+			if (parses.size() == 0) {
+				error = "ENDFOR: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.FOR) {
+				error = "ENDFOR: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			// All is ok: constructing the FOR
+			parses.remove(0);
+			stop = new TMLStopState("stop loop", null);
+			task.getActivityDiagram().addElement(stop);
+			tmlae.addNext(stop);
+			tmlae = parseElt.tmlae;
+		} // ENDFOR
+		
+		// SELECTEVT
+		if((isInstruction("SELECTEVT", _split[0]))) {
+			if (!inTask) {
+				error = "SELECTEVT: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if(_split.length > 1) {
+				error = "A SELECTEVT cannot have any parameters";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			parseElt = new TMLParserSaveElt();
+			parseElt.type = TMLParserSaveElt.SELECTEVT;
+			parses.add(0, parseElt);
+			TMLSequence seq = new TMLSequence("sequence", null);
+			parseElt.top = seq;
+			tmlae.addNext(seq);
+			TMLSelectEvt sel = new TMLSelectEvt("select evt", null);
+			parseElt.tmlae = sel;
+			seq.addNext(sel);
+			task.getActivityDiagram().addElement(seq);
+			task.getActivityDiagram().addElement(sel);
+			tmlae = sel;
+		} // SELECTEVT 
+		
+		// ENDSELECTEVT
+		if((isInstruction("ENDSELECTEVT", _split[0]))) {
+			if (!inTask) {
+				error = "ENDSELECTEVT: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the first element of the stack
+			if (parses.size() == 0) {
+				error = "ENDSELECTEVT: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.SELECTEVT) {
+				error = "ENDSELECTEVT: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			parses.remove(0);
+			tmlae = parseElt.top;
+		} // ENDSELECTEVT
+		
+		// CASE
+		if((isInstruction("CASE", _split[0]))) {
+			if (!inTask) {
+			error = "CASE: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (parses.size() == 0) {
+			error = "CASE: corresponding SELECTEVT not found";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			} else {
+				parseElt = parses.get(0);
+				if (parseElt.type != TMLParserSaveElt.SELECTEVT) {
+				error = "CASE: corresponding SELECTEVT not found";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if(_split.length < 2) {
+				error = "A CASE must have at least two parameters";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			evt = tmlm.getEventByName(_split[1]);
+			if (evt == null) {
+				error = "Unknown event: " + _split[1] ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			dec = evt.getNbOfParams();
+			
+			if (_split.length != 2 + dec) {
+				error = "A CASE operation on evt " + evt.getName() + " must be declared with exactly " + (1 + dec) + " parameters and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			TMLWaitEvent wevt = new TMLWaitEvent(evt.getName(), null);
+			wevt.setEvent(evt);
+			for(i=2; i<2 + dec; i++) {
+				wevt.addParam(_split[i]);
+			}
+			
+			task.getActivityDiagram().addElement(wevt);
+			tmlae.addNext(wevt);
+			
+			parseElt = new TMLParserSaveElt();
+			parseElt.type = TMLParserSaveElt.CASE;
+			parseElt.tmlae = wevt;
+			parseElt.top = tmlae;
+			parses.add(0, parseElt);
+			
+			tmlae = wevt;
+		} // CASE
+		
+		
+		// ENDCASE
+		if((isInstruction("ENDCASE", _split[0]))) {
+			if (!inTask) {
+			error = "ENDCASE: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the first element of the stack
+			if (parses.size() == 0) {
+			error = "ENDCASE: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.CASE) {
+			error = "ENDCASE: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parses.remove(0);
+			stop = new TMLStopState("stop case", null);
+			task.getActivityDiagram().addElement(stop);
+			tmlae.addNext(stop);
+			tmlae = parseElt.top;
+		} // ENDCASE
+		
+		// RANDOMSEQ
+		if((isInstruction("RANDOMSEQ", _split[0]))) {
+			if (!inTask) {
+				error = "RANDOMSEQ: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if(_split.length > 1) {
+				error = "A RANDOMSEQ cannot have any parameters";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			parseElt = new TMLParserSaveElt();
+			parseElt.type = TMLParserSaveElt.RANDOMSEQ;
+			parses.add(0, parseElt);
+			TMLSequence seq = new TMLSequence("sequence", null);
+			parseElt.top = seq;
+			tmlae.addNext(seq);
+			TMLRandomSequence rseq = new TMLRandomSequence("random sequence", null);
+			parseElt.tmlae = rseq;
+			seq.addNext(rseq);
+			task.getActivityDiagram().addElement(seq);
+			task.getActivityDiagram().addElement(rseq);
+			tmlae = rseq;
+		} // RANDOMSEQ 
+		
+		// ENDRANDOMSEQ
+		if((isInstruction("ENDRANDOMSEQ", _split[0]))) {
+			if (!inTask) {
+				error = "ENDRANDOMSEQ: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the first element of the stack
+			if (parses.size() == 0) {
+				error = "ENDRANDOMSEQ: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.RANDOMSEQ) {
+				error = "ENDRANDOMSEQ: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			parses.remove(0);
+			tmlae = parseElt.top;
+		} // ENDRANDOMSEQ
+		
+		
+		// SEQ
+		if((isInstruction("SEQ", _split[0]))) {
+			if (!inTask) {
+			error = "SEQ: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (parses.size() == 0) {
+				error = "SEQ: corresponding RANDOMSEQ not found";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			} else {
+				parseElt = parses.get(0);
+				if (parseElt.type != TMLParserSaveElt.RANDOMSEQ) {
+				error = "SEQ: corresponding RANDOMSEQ not found";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if(_split.length >1 ) {
+				error = "A SEQ has no parameter";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!(parseElt.tmlae instanceof TMLRandomSequence)) {
+				error = "Malformed specification: unexpected SEQ";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			TMLRandomSequence rseq = (TMLRandomSequence)parseElt.tmlae;
+			TMLSequence seq = new TMLSequence("sequence", null);
+			rseq.addNext(seq);
+			
+			task.getActivityDiagram().addElement(seq);
+			
+			parseElt = new TMLParserSaveElt();
+			parseElt.type = TMLParserSaveElt.SEQ;
+			parseElt.tmlae = seq;
+			parseElt.top = rseq;
+			parses.add(0, parseElt);
+			
+			tmlae = seq;
+		} // SEQ
+		
+		// ENDSEQ
+		if((isInstruction("ENDSEQ", _split[0]))) {
+			if (!inTask) {
+			error = "ENDSEQ: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the first element of the stack
+			if (parses.size() == 0) {
+			error = "ENDSEQ: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.SEQ) {
+			error = "ENDSEQ: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parses.remove(0);
+			stop = new TMLStopState("stop case", null);
+			task.getActivityDiagram().addElement(stop);
+			tmlae.addNext(stop);
+			tmlae = parseElt.top;
+		} // ENDSEQ
+		
+		// RAND
+		if((isInstruction("RAND", _split[0]))) {
+			if (!inTask) {
+				error = "RAND: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if(_split.length > 1) {
+				error = "A RAND cannot have any parameters";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			parseElt = new TMLParserSaveElt();
+			parseElt.type = TMLParserSaveElt.RAND;
+			parses.add(0, parseElt);
+			TMLSequence seq = new TMLSequence("sequence", null);
+			parseElt.top = seq;
+			tmlae.addNext(seq);
+			TMLChoice choice = new TMLChoice("choice evt", null);
+			parseElt.tmlae = choice;
+			seq.addNext(choice);
+			task.getActivityDiagram().addElement(seq);
+			task.getActivityDiagram().addElement(choice);
+			tmlae = choice;
+		} // RAND
+		
+		// ENDRAND
+		if((isInstruction("ENDRAND", _split[0]))) {
+			if (!inTask) {
+				error = "ENDRAND: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the first element of the stack
+			if (parses.size() == 0) {
+				error = "ENDRAND: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.RAND) {
+				error = "ENDRAND: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			parses.remove(0);
+			tmlae = parseElt.top;
+		} // ENDRAND
+		
+		// CASERAND
+		if((isInstruction("CASERAND", _split[0]))) {
+			if (!inTask) {
+			error = "CASERAND: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (parses.size() == 0) {
+			error = "CASERAND: corresponding RAND not found";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			} else {
+				parseElt = parses.get(0);
+				if (parseElt.type != TMLParserSaveElt.RAND) {
+				error = "CASERAND: corresponding RAND not found";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if(_split.length != 2) {
+				error = "A CASERAND should have one parameter";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (!(parseElt.tmlae instanceof TMLChoice)) {
+				error = "Malformed specification";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			TMLChoice choice = (TMLChoice)parseElt.tmlae;
+			TMLSequence seq = new TMLSequence("sequence", null);
+			choice.addGuard("[" + _split[1] + "%]");
+			choice.addNext(seq);
+			
+			task.getActivityDiagram().addElement(seq);
+			
+			parseElt = new TMLParserSaveElt();
+			parseElt.type = TMLParserSaveElt.CASERAND;
+			parseElt.tmlae = seq;
+			parseElt.top = choice;
+			parses.add(0, parseElt);
+			
+			tmlae = seq;
+			
+		} // CASERAND
+		
+		
+		// ENDCASERAND
+		if((isInstruction("ENDCASERAND", _split[0]))) {
+			if (!inTask) {
+			error = "ENDCASERAND: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the first element of the stack
+			if (parses.size() == 0) {
+			error = "ENDCASERAND: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.CASERAND) {
+			error = "ENDCASERAND: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parses.remove(0);
+			stop = new TMLStopState("stop case", null);
+			task.getActivityDiagram().addElement(stop);
+			tmlae.addNext(stop);
+			tmlae = parseElt.top;
+		} // ENDCASERAND
+		
+		// IF
+		if((isInstruction("IF", _split[0]))) {
+			if (!inTask) {
+				error = "IF: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if(_split.length != 2) {
+				error = "IF should be followed by one condition";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			String cond = _split[1].trim();
+			tmp0 = cond.indexOf('(');
+				tmp1 = cond.lastIndexOf(')');
+				if ((tmp0 == -1) || (tmp1 == -1)) {
+					error = "IF operation: badly formed condition";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				cond = cond.substring(tmp0+1, tmp1);
+				
+				parseElt = new TMLParserSaveElt();
+				parseElt.type = TMLParserSaveElt.IF;
+				parses.add(0, parseElt);
+				TMLSequence seq = new TMLSequence("sequence", null);
+				parseElt.top = seq;
+				tmlae.addNext(seq);
+				TMLChoice choice = new TMLChoice("if", null);
+				parseElt.tmlae = choice;
+				seq.addNext(choice);
+				task.getActivityDiagram().addElement(seq);
+				task.getActivityDiagram().addElement(choice);
+				
+				seq = new TMLSequence("sequence", null);
+				task.getActivityDiagram().addElement(seq);
+				choice.addNext(seq);
+				choice.addGuard("[" + cond + "]");
+				
+				tmlae = seq;
+		} // IF
+		
+		// ORIF
+		if((isInstruction("ORIF", _split[0]))) {
+			if (!inTask) {
+				error = "ORIF: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if(_split.length != 2) {
+				error = "ORIF should be followed by one condition";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			
+			String cond = _split[1].trim();
+			//TraceManager.addDev("cond1=" + cond);
+			tmp0 = cond.indexOf('(');
+				tmp1 = cond.lastIndexOf(')');
+				if ((tmp0 == -1) || (tmp1 == -1)) {
+					error = "ORIF operation: badly formed condition";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				cond = cond.substring(tmp0+1, tmp1);
+				//TraceManager.addDev("cond2=" + cond);
+				
+				if (parses.size() == 0) {
+					error = "ORIF: badly placed instruction.";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				parseElt = parses.get(0);
+				if (parseElt.type != TMLParserSaveElt.IF) {
+					error = "ORIF: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				
+				if (parseElt.nbElse > 0) {
+					error = "ORIF: should not followed a else instruction";
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+				
+				stop = new TMLStopState("stop", null);
+				task.getActivityDiagram().addElement(stop);
+				tmlae.addNext(stop);
+				
+				TMLSequence seq = new TMLSequence("sequence", null);
+				TMLChoice choice = (TMLChoice)parseElt.tmlae;
+				task.getActivityDiagram().addElement(seq);
+				
+				choice.addNext(seq);
+				choice.addGuard("[" + cond + "]");
+				
+				tmlae = seq;
+		} // ORIF
+		
+		// ELSE
+		if((isInstruction("ELSE", _split[0]))) {
+			if (!inTask) {
+				error = "ELSE: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if(_split.length != 1) {
+				error = "ELSE should have no parameter";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if (parses.size() == 0) {
+				error = "ELSE: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.IF) {
+				error = "ELSE: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			stop = new TMLStopState("stop", null);
+			task.getActivityDiagram().addElement(stop);
+			tmlae.addNext(stop);
+			
+			parseElt.nbElse ++;
+			
+			TMLSequence seq = new TMLSequence("sequence", null);
+			TMLChoice choice = (TMLChoice)parseElt.tmlae;
+			task.getActivityDiagram().addElement(seq);
+			
+			choice.addNext(seq);
+			choice.addGuard("[else]");
+			
+			tmlae = seq;
+		} // ELSE
+		
+		// ENDIF
+		if((isInstruction("ENDIF", _split[0]))) {
+			if (!inTask) {
+				error = "ENDIF: must be used in a Task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			// Extract the first element of the stack
+			if (parses.size() == 0) {
+				error = "ENDIF: badly placed instruction.";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			parseElt = parses.get(0);
+			if (parseElt.type != TMLParserSaveElt.IF) {
+				error = "ENDIF: badly placed instruction. Was expecting: " + parseElt.getExpectedInstruction();
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			stop = new TMLStopState("stop", null);
+			task.getActivityDiagram().addElement(stop);
+			tmlae.addNext(stop);
+			
+			parses.remove(0);
+			tmlae = parseElt.top;
+		} // ENDIF
+		
+		// EXECI
+		if((isInstruction("EXECI", _split[0]))) {
+			
+			if (!inTask) {
+				error = "An EXECI operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if ((_split.length < 2) ||(_split.length > 4)) {
+				error = "An EXECI operation must be declared with 1 or 2 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (_split.length == 2) {
+				TMLExecI execi = new TMLExecI("execi", null);
+				execi.setAction(_split[1]);
+				tmlae.addNext(execi);
+				task.getActivityDiagram().addElement(execi);
+				tmlae = execi;
+			} else {
+				TMLExecIInterval execi = new TMLExecIInterval("execi", null);
+				execi.setMinDelay(_split[1]);
+				execi.setMaxDelay(_split[2]);
+				tmlae.addNext(execi);
+				task.getActivityDiagram().addElement(execi);
+				tmlae = execi;
+			}
+		} // EXECI
+		
+		// EXECC
+		if((isInstruction("EXECC", _split[0]))) {
+			
+			if (!inTask) {
+				error = "An EXECC operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if ((_split.length < 2) ||(_split.length > 4)) {
+				error = "An EXECC operation must be declared with 1 or 2 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (_split.length == 2) {
+				TMLExecC execc = new TMLExecC("execc", null);
+				execc.setAction(_split[1]);
+				tmlae.addNext(execc);
+				task.getActivityDiagram().addElement(execc);
+				tmlae = execc;
+			} else {
+				TMLExecCInterval execci = new TMLExecCInterval("execci", null);
+				execci.setMinDelay(_split[1]);
+				execci.setMaxDelay(_split[2]);
+				tmlae.addNext(execci);
+				task.getActivityDiagram().addElement(execci);
+				tmlae = execci;
+			}
+		} // EXECC
+		
+		// DELAY
+		if((isInstruction("DELAY", _split[0]))) {
+			
+			if (!inTask) {
+				error = "A DELAY operation may only be performed in a task body";
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			if ((_split.length < 3) ||(_split.length > 5)) {
+				error = "A DELAY operation must be declared with 2 or 3 parameters, and not " + (_split.length - 1) ;
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			if (_split.length == 3) {
+				if (!checkParameter("DELAY", _split, 2, 0, _lineNb)) {
+					error = "A DELAY operation must be specified with a valid time unit (ns, us, ms, s))" ;
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+			}
+			
+			if (_split.length == 4) {
+				if (!checkParameter("DELAY", _split, 3, 0, _lineNb)) {
+					error = "A DELAY operation must be specified with a valid time unit (ns, us, ms, s))" ;
+					addError(0, _lineNb, 0, error);
+					return -1;
+				}
+			}
+			
+			TMLDelay delay = new TMLDelay("delay", null);
+			delay.setMinDelay(_split[1]);
+			if (_split.length == 3) {
+				delay.setMaxDelay(_split[1]);
+				delay.setUnit(_split[2]);
+			} else {
+				delay.setMaxDelay(_split[2]);
+				delay.setUnit(_split[3]);
+			}
+			
+			
+			tmlae.addNext(delay);
+			task.getActivityDiagram().addElement(delay);
+			tmlae = delay;
+			
+		} // EXECC
+		
+		// Other command
+		if((_split[0].length() > 0) && (!(isInstruction(_split[0])))) {
+			if (!inTask) {
+				error = "Syntax error in TML modeling: unrecognized instruction:" + _split[0];
+				addError(0, _lineNb, 0, error);
+				return -1;
+			}
+			
+			inDec = false;
+			inTask = true;
+			inTaskDec = false;
+			inTaskBehavior = true;
+			
+			TMLActionState action = new TMLActionState(_split[0], null);
+			action.setAction(_line);
+			tmlae.addNext(action);
+			task.getActivityDiagram().addElement(action);
+			tmlae = action;
+			
+		} // Other command
+		
+		return 0;
+	}
+	
+	// Type 0: id
+	// Type 1: numeral
+	// Type 2: channel type 
+	// Type 3: event type
+	// Type 4: event name
+	// Type 5: '='
+	// Type 6: attribute value
+	// Type 7: id or numeral
+	// Type 8:unit
+	
+	public boolean checkParameter(String _inst, String[] _split, int _parameter, int _type, int _lineNb) {
+		boolean err = false;
+		String error;
+		
+		if(_parameter < _split.length) {
+			switch(_type) {
+			case 0:
+				if (!isAValidId(_split[_parameter])) {
+					err = true;
+				}
+				break;
+			case 1:
+				if (!isANumeral(_split[_parameter])) {
+					err = true;
+				}
+				break;
+			case 2:
+				if (!isIncluded(_split[_parameter], channeltypes)) {
+					err = true;
+				}
+				break;	
+			case 3:
+				if (!isIncluded(_split[_parameter], eventtypes)) {
+					err = true;
+				}
+				break;	
+			case 4:
+				if (!isAValidId(getEvtId(_split[_parameter]))) {
+					err = true;
+					//TraceManager.addDev("Unvalid id");
+				} else if (!TMLEvent.isAValidListOfParams(getParams(_split[_parameter]))) {
+					//TraceManager.addDev("Unvalid param");
+					err = true;
+				}
+				break;
+			case 5:
+				if (!(_split[_parameter].equals("="))) {
+					TraceManager.addDev("Error of =");
+					err = true;
+				}
+				break;
+			case 6:
+				if (_inst.equals("BOOL")) {
+					String tmp = _split[_parameter].toUpperCase();
+					if (!(tmp.equals("TRUE") || tmp.equals("FALSE"))) {
+						err = true;
+					}
+				} else {
+					if (!isANumeral(_split[_parameter])) {
+						err = true;
+					}
+				}
+				break;	 
+			case 7:
+				if (!isAValidId(_split[_parameter]) && !isANumeral(_split[_parameter])) {
+					err = true;
+				}
+				break;	
+			case 8:
+				if (!isAValidUnit(_split[_parameter])) {
+					err = true;
+				}
+				break;	
+			case 9:
+				if (!isANegativeOrPositiveNumeral(_split[_parameter])) {
+					err = true;
+				}
+				break;
+			}
+		} else {
+			err = true;
+		}
+		if (err) {
+			error = "Unvalid parameter #" + _parameter + "-> $" + _split[_parameter] + "$ <- in " + _inst + " instruction";
+			addError(0, _lineNb, 0, error);
+			return false;
+		}
+		return true;
+	}
+	
+	public boolean isInstruction(String instcode, String inst) {
+		return (inst.toUpperCase().compareTo(instcode) == 0);
+	}
+	
+	public boolean isInstruction(String instcode) {
+		return (!checkKeywords(instcode));
+	}
+	
+	public static boolean isAValidId(String _id) {
+		if ((_id == null) || (_id.length() == 0)) {
+			return false;
+		}
+		
+		boolean b1 = (_id.substring(0,1)).matches("[a-zA-Z]");
+        boolean b2 = _id.matches("\\w*");
+		boolean b3 = checkKeywords(_id);
+		
+		return (b1 && b2 && b3);
+	}
+	
+	public boolean isANumeral(String _num) {
+		return _num.matches("\\d*");
+	}
+	
+	public boolean isANegativeOrPositiveNumeral(String _num) {
+		if (_num.startsWith("-")) {
+			return isANumeral(_num.substring(1, _num.length()));
+		}
+		return isANumeral(_num);
+	}
+	
+	public boolean isAValidUnit(String s) {
+		if (s.compareTo("ns") == 0) {
+			return true;
+		} else if (s.compareTo("us") == 0) {
+			return true;
+		} else if (s.compareTo("ms") == 0) {
+			return true;
+		} else if (s.compareTo("s") == 0) {
+			return true;
+		}
+		
+		return false;
+	}
+	
+	public static boolean checkKeywords(String _id) {
+		String id = _id.toUpperCase();
+		for(int i=0; i<keywords.length; i++) {
+			if (id.compareTo(keywords[i]) == 0) {
+				return false;
+			}
+		}
+		return true;
+	}
+	
+	public boolean isIncluded(String _id, String[] _list) {
+		String id = _id.toUpperCase();
+		for(int i=0; i<_list.length; i++) {
+			if (id.compareTo(_list[i]) == 0) {
+				return true;
+			}
+		}
+		return false;
+	}
+	
+	public String removeUndesiredWhiteSpaces(String _input, int _lineNb) {
+		String error, tmp;
+		int index0, index1, index2;
+		
+		if (_input.startsWith("EVENT ")) {
+			index0 = _input.indexOf('(');
+				index1 = _input.indexOf(')');
+				if ((index0 == -1) || (index1 == -1)) {
+					error = "Syntax Error: should be of the form EVENT evtname(<list of max three types>) + other parameters";
+					addError(0, _lineNb, 0, error);
+					return null;
+				}
+				return Conversion.replaceBetweenIndex(_input, index0, index1, " ", "");
+		}
+		
+		if (_input.startsWith("REQUEST ") && (inDec)) {
+			index0 = _input.indexOf('(');
+				index1 = _input.indexOf(')');
+				if ((index0 == -1) || (index1 == -1)) {
+					error = "Syntax Error: should be of the form REQUEST requestname(<list of max three types>) + other parameters";
+					addError(0, _lineNb, 0, error);
+					return null;
+				}
+				return Conversion.replaceBetweenIndex(_input, index0, index1, " ", "");
+		}
+		
+		if (_input.startsWith("FOR(")) {
+				_input = "FOR (" + _input.substring(4, _input.length());
+		}
+		
+		if (_input.startsWith("FOR (")) {
+				tmp = _input.substring(5, _input.length());
+				tmp = Conversion.replaceAllString(tmp, " ", "");
+				return "FOR (" + tmp;
+		}
+		
+		if (_input.startsWith("IF(")) {
+				_input = "IF (" + _input.substring(3, _input.length());
+		}
+		
+		if (_input.startsWith("IF (")) {
+				tmp = _input.substring(4, _input.length());
+				tmp = Conversion.replaceAllString(tmp, " ", "");
+				return "IF (" + tmp;
+		}
+		
+		if (_input.startsWith("ORIF(")) {
+				_input = "ORIF (" + _input.substring(5, _input.length());
+		}
+		
+		if (_input.startsWith("ORIF (")) {
+				tmp = _input.substring(6, _input.length());
+				tmp = Conversion.replaceAllString(tmp, " ", "");
+				return "ORIF (" + tmp;
+		}	
+		
+		return _input;
+	}
+	
+	private String getEvtId(String _input) {
+		int index = _input.indexOf('(');
+			if (index == -1) {
+				return _input;
+			}
+			return _input.substring(0, index);
+	}
+	
+	private String getParams(String _input) {
+		//TraceManager.addDev("input=" + _input);
+		int index0 = _input.indexOf('(');
+			int index1 = _input.indexOf(')');
+			if ((index0 == -1) || (index1 == -1)) {
+				return _input;
+			}
+			return _input.substring(index0 + 1, index1);
+	}
+	
+	private static String prepareString(String s) {
+		return s.replaceAll("\\s", "");
+	}
+	
+	public static String modifyString(String s) {
+		return prepareString(s);
+	}
+}
diff --git a/src/tmltranslator/tmlcp/TMLCPSection.java b/src/tmltranslator/tmlcp/CPActivityDiagram.java
similarity index 90%
rename from src/tmltranslator/tmlcp/TMLCPSection.java
rename to src/tmltranslator/tmlcp/CPActivityDiagram.java
index 72f4fac2ead6157f4c78fc467558da89ee3d0953..9728bef1da460f31ed23d672e36c3ccd8d626f05 100755
--- a/src/tmltranslator/tmlcp/TMLCPSection.java
+++ b/src/tmltranslator/tmlcp/CPActivityDiagram.java
@@ -37,7 +37,7 @@ 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 TMLCPSection
+* Class CPActivityDiagram
 * Creation: 18/02/2014
 * @version 1.0 21/05/2014
 * @author Ludovic APVRILLE, Andrea ENRICI
@@ -51,7 +51,7 @@ import tmltranslator.*;
 import myutil.*;
 //import compiler.tmlCPparser.myexceptions.*;
 
-public class TMLCPSection  extends TMLElement {
+public class CPActivityDiagram  extends TMLElement {
 	
 	private TMLCPStart start;
   private ArrayList<TMLCPElement> elements; // Including the start element
@@ -87,7 +87,7 @@ public class TMLCPSection  extends TMLElement {
 		sds = new ArrayList<String>();
   }
     
-  public TMLCPSection(String _name, Object _referenceObject) {
+  public CPActivityDiagram(String _name, Object _referenceObject) {
   	super(_name, _referenceObject);
     init();
   }
@@ -247,31 +247,31 @@ public class TMLCPSection  extends TMLElement {
 	public void correctReferences( TMLCP _refTopCP )	{
 		
 		TMLCPElement tempElem;
-		TMLCPSection tempCP;
-		TMLSDSection tempSD;
+		CPActivityDiagram tempCP;
+		CPSequenceDiagram tempSD;
 		String tempString;
 		int i, j, k;
 
-		ArrayList<TMLCPSection> activityList = _refTopCP.getCPSections();
+		ArrayList<CPActivityDiagram> activityList = _refTopCP.getCPSections();
 		for( i = 0; i < elements.size(); i++ )	{
 			tempElem = elements.get(i);
 			tempString = tempElem.getName();
-			if( tempElem instanceof TMLCPRefCP )	{
+			if( tempElem instanceof CPRefAD )	{
 				for( j = 0; j < activityList.size(); j++ )	{
 					tempCP = activityList.get(j);
 					if( tempString.equals( tempCP.getName() ) )	{
-						TMLCPRefCP CPRef = new TMLCPRefCP( tempCP, tempElem.getName(), new Object() );
+						CPRefAD CPRef = new CPRefAD( tempCP, tempElem.getName(), new Object() );
 						elements.set( i, CPRef );
 						break;
 					}
 				}
 			}
 			else	{ //A reference to a sequence diagram must be inserted instead
-				ArrayList<TMLSDSection> sequenceList = _refTopCP.getSDSections();
+				ArrayList<CPSequenceDiagram> sequenceList = _refTopCP.getSDSections();
 				for( k = 0; k < sequenceList.size(); k++ )	{
 					tempSD = sequenceList.get(k);
 					if( tempString.equals( tempSD.getName() ) )	{
-						TMLCPRefSD SDRef = new TMLCPRefSD( tempSD, tempElem.getName(), new Object() );
+						CPRefSD SDRef = new CPRefSD( tempSD, tempElem.getName(), new Object() );
 						elements.set( i, SDRef );
 						break;
 					}
diff --git a/src/tmltranslator/tmlcp/TMLCPRefCP.java b/src/tmltranslator/tmlcp/CPRefAD.java
similarity index 77%
rename from src/tmltranslator/tmlcp/TMLCPRefCP.java
rename to src/tmltranslator/tmlcp/CPRefAD.java
index a4dcd5d3e5d9392587dfad8a2085aaf6c6b3073c..1bfb2a7492718576a3e315ecea5371ebd0f4174d 100755
--- a/src/tmltranslator/tmlcp/TMLCPRefCP.java
+++ b/src/tmltranslator/tmlcp/CPRefAD.java
@@ -1,6 +1,7 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
 
-ludovic.apvrille AT enst.fr
+ludovic.apvrille AT telecom-paristech.fr
+andrea.enrici 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 
@@ -36,10 +37,10 @@ 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 TMLCPRefCP
+* Class CPRefAD
 * Creation: 18/02/2014
-* @version 1.0 18/02/2014
-* @author Ludovic APVRILLE
+* @version 1.1 04/06/2014
+* @author Ludovic APVRILLE, Andrea ENRICI
 * @see
 */
 
@@ -47,19 +48,19 @@ package tmltranslator.tmlcp;;
 
 import java.util.*;
 
-
 import myutil.*;
 
-public class TMLCPRefCP extends TMLCPElement  {
-	private TMLCPSection reference;
+public class CPRefAD extends TMLCPElement  {
+	
+	private CPActivityDiagram reference;
 	
-    public TMLCPRefCP(TMLCPSection _ref, String _name, Object _referenceObject) {
-        super(_name, _referenceObject);
-        reference = _ref;
-    }
+ 	public CPRefAD( CPActivityDiagram _ref, String _name, Object _referenceObject ) {
+  	super( _name, _referenceObject );
+    reference = _ref;
+ 	}
     
-    public TMLCPSection getReference() {
-    	return reference;
-    }
+  public CPActivityDiagram getReference() {
+  	return reference;
+  }
 	
-}
\ No newline at end of file
+}
diff --git a/src/tmltranslator/tmlcp/TMLCPRefSD.java b/src/tmltranslator/tmlcp/CPRefSD.java
similarity index 83%
rename from src/tmltranslator/tmlcp/TMLCPRefSD.java
rename to src/tmltranslator/tmlcp/CPRefSD.java
index 2ef5d3e2d59c4ceeb7f6f111053233ba04af92aa..d2f9a1dd1622a6d1f62314daadf71740a5b65151 100755
--- a/src/tmltranslator/tmlcp/TMLCPRefSD.java
+++ b/src/tmltranslator/tmlcp/CPRefSD.java
@@ -37,9 +37,9 @@ 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 TMLCPRefSD
+* Class CPRefSD
 * Creation: 18/02/2014
-* @version 1.0 23/05/2014
+* @version 1.1 04/06/2014
 * @author Ludovic APVRILLE, Andrea ENRICI
 * @see
 */
@@ -48,19 +48,19 @@ package tmltranslator.tmlcp;;
 
 import java.util.*;
 
-
 import myutil.*;
 
-public class TMLCPRefSD extends TMLCPElement  {
-	private TMLSDSection reference;
+public class CPRefSD extends TMLCPElement  {
+
+	private CPSequenceDiagram reference;
 	
-    public TMLCPRefSD(TMLSDSection _ref, String _name, Object _referenceObject) {
-        super(_name, _referenceObject);
-        reference = _ref;
-    }
+	public CPRefSD( CPSequenceDiagram _ref, String _name, Object _referenceObject ) {
+  	super( _name, _referenceObject );
+		reference = _ref;
+	}
     
-    public TMLSDSection getReference() {
-    	return reference;
-    }
+	public CPSequenceDiagram getReference() {
+  	return reference;
+	}
 	
 }
diff --git a/src/tmltranslator/tmlcp/TMLSDSection.java b/src/tmltranslator/tmlcp/CPSequenceDiagram.java
similarity index 86%
rename from src/tmltranslator/tmlcp/TMLSDSection.java
rename to src/tmltranslator/tmlcp/CPSequenceDiagram.java
index 5cd72d6fbe859d53ec84de5435defcca738618e9..9045678a95f8f9d287faac9659f703a471f7893c 100755
--- a/src/tmltranslator/tmlcp/TMLSDSection.java
+++ b/src/tmltranslator/tmlcp/CPSequenceDiagram.java
@@ -1,6 +1,7 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
 
-ludovic.apvrille AT enst.fr
+ludovic.apvrille AT telecom-paristech.fr
+andrea.enrici 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 
@@ -36,10 +37,10 @@ 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 TMLSDSection
+* Class CPSequenceDiagram
 * Creation: 18/02/2014
 * @version 1.0 18/02/2014
-* @author Ludovic APVRILLE
+* @author Ludovic APVRILLE, Andrea ENRICI
 * @see
 */
 
@@ -50,26 +51,27 @@ import java.util.*;
 import tmltranslator.*;
 import myutil.*;
 
-public class TMLSDSection  extends TMLElement {
-    private ArrayList<TMLSDInstance> instances; 
-    private ArrayList<TMLSDInstance> mappingInstances; 
-    private ArrayList<TMLAttribute> globalVariables; 
-    private ArrayList<TMLSDMessage> messages; 
+public class CPSequenceDiagram  extends TMLElement {
+	
+	private ArrayList<TMLSDInstance> instances; 
+	private ArrayList<TMLSDInstance> mappingInstances;
+	private ArrayList<TMLAttribute> globalVariables;
+	private ArrayList<TMLSDMessage> messages; 
 	
 	private int hashCode;
 	private boolean hashCodeComputed = false;
 	
     
-    public TMLSDSection(String _name, Object _referenceObject) {
-        super(_name, _referenceObject);
-        init();
-    }
-	
-    private void init() {
-        globalVariables = new ArrayList<TMLAttribute>();
-        instances = new ArrayList<TMLSDInstance>();  
-        messages = new ArrayList<TMLSDMessage>();
-    }
+	public CPSequenceDiagram( String _name, Object _referenceObject )	{
+		super( _name, _referenceObject );
+		init();
+	}
+
+	private void init() {
+		globalVariables = new ArrayList<TMLAttribute>();
+		instances = new ArrayList<TMLSDInstance>();
+		messages = new ArrayList<TMLSDMessage>();
+	}
     
  	public void addVariable( TMLAttribute _attr ) throws MultipleVariableDeclarationException	{
 
diff --git a/src/tmltranslator/tomappingsystemc2/TML2MappingSystemC.java b/src/tmltranslator/tomappingsystemc2/TML2MappingSystemC.java
index e3844000aa4d0e31dd40830c5f90ae062ce4e343..1073121a1e763b9a29adca2d281d78b640422368 100755
--- a/src/tmltranslator/tomappingsystemc2/TML2MappingSystemC.java
+++ b/src/tmltranslator/tomappingsystemc2/TML2MappingSystemC.java
@@ -587,24 +587,24 @@ public class TML2MappingSystemC {
 	private boolean exploreBuses(int depth, LinkedList<HwCommunicationNode> commNodes, LinkedList<HwCommunicationNode> path, HwNode startNode, HwNode destNode, TMLElement commElemToRoute){
 		//first called with Maping:getCommunicationNodes
 		LinkedList<HwCommunicationNode> nodesToExplore;
-		//TraceManager.addDev("No of comm nodes " + commNodes.size());
+		TraceManager.addDev("No of comm nodes " + commNodes.size());
 		boolean busExploreMode = ((depth & 1) == 0);
 		//if (depth % 2 == 0){
 		if(busExploreMode){
-			//TraceManager.addDev("search for buses connected to " + startNode.getName());
+			TraceManager.addDev("search for buses connected to " + startNode.getName());
 			nodesToExplore=getBusesConnectedToNode(commNodes, startNode);
 		}else{
-			//TraceManager.addDev("search for bridges connected to: " + startNode.getName());
+			TraceManager.addDev("search for bridges connected to: " + startNode.getName());
 			nodesToExplore=getBridgesConnectedToBus(commNodes, (HwBus)startNode);
 		}
 		//HwMemory memory = null;
-		//TraceManager.addDev("no of elements found: " + nodesToExplore.size());
+		TraceManager.addDev("no of elements found: " + nodesToExplore.size());
 		for(HwCommunicationNode currNode:nodesToExplore){
 			//memory = null;
 			if (busExploreMode){
 				//memory = getMemConnectedToBusChannelMapped(commNodes, (HwBus)currNode, commElemToRoute);
 				if(isBusConnectedToNode(currNode, destNode)){
-					//TraceManager.addDev(currNode.getName() + " is last node");
+					TraceManager.addDev(currNode.getName() + " is last node");
 					path.add(currNode);
 					//if (memory!=null) path.add(memory);
 					commNodes.remove(currNode);
@@ -612,7 +612,7 @@ public class TML2MappingSystemC {
 				}
 			}
 			if(tmlmapping.isCommNodeMappedOn(commElemToRoute, currNode)){
-				//TraceManager.addDev(currNode.getName() + " mapping found for " + commElemToRoute.getName());
+				TraceManager.addDev(currNode.getName() + " mapping found for " + commElemToRoute.getName());
 				path.add(currNode);
 				//if (memory!=null) path.add(memory);
 				commNodes.remove(currNode);
@@ -628,7 +628,7 @@ public class TML2MappingSystemC {
 			//if (memory!=null) path.add(memory);
 			commNodes.remove(currNode);
 			//for (int i=0; i<path.size(); i++) System.out.print("  ");
-			//TraceManager.addDev(currNode.getName());
+			TraceManager.addDev(currNode.getName());
 			if (exploreBuses(depth+1, commNodes, path, currNode, destNode, commElemToRoute)) return true;
 			path.remove(currNode);
 			//if (memory!=null) path.remove(memory);
diff --git a/src/tmltranslator/tomappingsystemc3/CheckpointInfo.java b/src/tmltranslator/tomappingsystemc3/CheckpointInfo.java
new file mode 100644
index 0000000000000000000000000000000000000000..120e43604a8f501570d51703184aeba0ed779698
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/CheckpointInfo.java
@@ -0,0 +1,60 @@
+package tmltranslator.tomappingsystemc3;
+
+import java.util.*;
+import tmltranslator.*;
+
+public class CheckpointInfo{
+
+	public int[] _depChannels = null;
+	public int[] _ctrlFlowJoinDefs = null;
+	public int[] _killedDefs = null;
+	public int[] _varsOutOfScope = null;
+	public int[] _depSrcDef = null;
+	public int _reasonCode = 0;
+	private int _opMode = 0;
+
+	public final static int CHANNEL_DEP=1;
+	public final static int CTRL_FLOW_JOIN=2;
+	public final static int KILLED_DEF=4;
+	public final static int VAR_OUT_OF_SCOPE=8;
+	public final static int DEP_SRC=16;
+
+	public void setOperationMode(int iOpMode){
+		_opMode = iOpMode;
+	}
+
+	public void setDefinitions(int[] iDefs){
+		switch(_opMode){
+		case CTRL_FLOW_JOIN:
+			_ctrlFlowJoinDefs = iDefs; break;
+		case KILLED_DEF:
+			_killedDefs = iDefs; break;
+		default:
+		}
+	}
+
+	public void setVariableID(int iVarID, int iLength){
+		if(_opMode == VAR_OUT_OF_SCOPE){
+			_varsOutOfScope = new int[iLength];
+			_varsOutOfScope[iVarID >>> 5] |= 1 << (iVarID & 0x1F);
+		}
+	}
+
+	public void incorporate(CheckpointInfo i2ndPoint){
+		_depChannels = mergeArrays(_depChannels, i2ndPoint._depChannels);
+		_ctrlFlowJoinDefs = mergeArrays(_ctrlFlowJoinDefs, i2ndPoint._ctrlFlowJoinDefs);
+		_killedDefs = mergeArrays(_killedDefs, i2ndPoint._killedDefs);
+		_varsOutOfScope = mergeArrays(_varsOutOfScope, i2ndPoint._varsOutOfScope);
+		_depSrcDef = mergeArrays(_depSrcDef, i2ndPoint._depSrcDef);
+		_reasonCode |= i2ndPoint._reasonCode;
+	}
+
+	private int[] mergeArrays(int[] iArray1, int[] iArray2){
+		if (iArray1==null) return iArray2;
+		if (iArray2==null) return iArray1;
+		int[] aMergedArray = new int[iArray1.length];
+		for(int i=0; i< iArray1.length; i++)
+			aMergedArray[i] = iArray1[i] | iArray2[i];
+		return aMergedArray;
+	}
+}
diff --git a/src/tmltranslator/tomappingsystemc3/LiveVariableNode.java b/src/tmltranslator/tomappingsystemc3/LiveVariableNode.java
new file mode 100755
index 0000000000000000000000000000000000000000..2d945f95ea12bd293be04db7ab36451ddee2d3fd
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/LiveVariableNode.java
@@ -0,0 +1,762 @@
+package tmltranslator.tomappingsystemc3;
+
+import java.util.*;
+import tmltranslator.*;
+import javax.script.*;
+
+import myutil.*;
+
+public class LiveVariableNode{
+	private LinkedList<LiveVariableNode> _succList = new LinkedList<LiveVariableNode>(), _predList = new LinkedList<LiveVariableNode>();
+	private boolean _valid=false;
+	StaticAnalysis _analysis;
+	//** Live Variable Analysis
+	private int[] _useVars;
+	private int[] _defVars;
+	private int[] _initialDefVars;
+	private int[] _inVars;
+	private int[] _outVars;
+	//** Reachable Definition analysis
+	private int[] _killDefs;
+	private int[] _generateDefs;
+	private int[] _killCandidates;
+	private int[] _inDefs;
+	private int[] _outDefs;
+	//** others
+	private int _myDefID = -2;
+	private boolean _isConstant=false;
+	private boolean _constantStuckToFalse=false;
+	private boolean _infected=false;
+	//private int _checkpoint=0;
+	private CheckpointInfo _checkpoint=null;
+	private boolean _guard=false;
+	private TMLActivityElement _linkedElem = null;
+	private LiveVariableNode _superiorBranchNode = null;
+	//private int _exprValue = 0;
+	private String _exprValue = "";
+	private String _lhs = "";
+	private String _rhs = "";
+	private String _unrolledExpr = "";
+	private boolean _varDepSource = false;
+	private String _nodeInfo="";
+	
+
+	LiveVariableNode(StaticAnalysis iAnalysis, int[] iUseVars, int[] iDefVars, TMLActivityElement iLinkedElem, LiveVariableNode iSuperiorNode, boolean iConstantStuckToFalse, String iLhs, String iRhs){
+		this(iAnalysis, iUseVars, iDefVars, iLinkedElem, iSuperiorNode, iConstantStuckToFalse);
+		_lhs=iLhs;
+		_rhs= iRhs;
+		//TraceManager.addDev("lhs in init:*" + _lhs + "* rhs in init:*" + _rhs);
+	}
+	
+	LiveVariableNode(StaticAnalysis iAnalysis, int[] iUseVars, int[] iDefVars, TMLActivityElement iLinkedElem, LiveVariableNode iSuperiorNode, boolean iConstantStuckToFalse){
+		this(iAnalysis, iUseVars, iDefVars, iLinkedElem, iSuperiorNode);
+		_constantStuckToFalse=iConstantStuckToFalse;
+		
+	}
+
+	LiveVariableNode(StaticAnalysis iAnalysis, int[] iUseVars, int[] iDefVars, TMLActivityElement iLinkedElem, LiveVariableNode iSuperiorNode){
+		_useVars=iUseVars;
+		_defVars=iDefVars;
+		_initialDefVars = new int[_defVars.length];
+		for (int i=0; i<_defVars.length; i++)
+			_initialDefVars[i]=_defVars[i];
+		_superiorBranchNode = iSuperiorNode;
+		_linkedElem = iLinkedElem;
+		_analysis = iAnalysis;
+		//_succList = ;
+		//_predList = new LinkedList<LiveVariableNode>();
+	}
+	
+	public void liveVariableInit(){
+		boolean isADefinition=false;
+		_inVars = new int[_defVars.length];
+		_outVars = new int[_defVars.length];
+		for (int i=0; i<_defVars.length;i++){
+			//_defNegVars[i] =  ~_defVars[i];
+			//_inVars[i] = _useVars[i] & _defNegVars[i];
+			_inVars[i] = _useVars[i] & (~_defVars[i]);
+			isADefinition |= (_defVars[i]!=0);
+		}
+		if (isADefinition)
+			_myDefID = _analysis.getNextDefID();
+		else
+			_myDefID=-1;
+	}
+	
+	public int varStatistics(int[] ioStatistics){
+		if(_checkpoint!=null){	
+			for (int bytes=0; bytes < _outVars.length; bytes++){
+				for (int bits=0; bits<32;bits++){
+					//TraceManager.addDev("bytes: " + bytes + " stat index: " + (bytes << 5 |bits));
+					//if((_outVars[bytes] & (1 << bits))!=0)
+					if((_outVars[bytes] & (1 << bits))!=0 || (_useVars[bytes] & (1 << bits))!=0)
+					      ioStatistics[bytes << 5 |bits]++;
+				}
+			}
+			return 3;
+		}
+		return (_linkedElem!=null && (_linkedElem instanceof TMLReadChannel || _linkedElem instanceof TMLWriteChannel|| _linkedElem instanceof TMLSendEvent || _linkedElem instanceof TMLWaitEvent || _linkedElem instanceof TMLSendRequest))? 1:0;
+	}
+				
+	private boolean atLeast1DepDefForVars(int[] iConcernedVars, boolean iVarGoOutOfScope, int iMinNbOfDefs, CheckpointInfo iCheckInfo){
+		//following a command where a variable goes out of scope which is reached by at least two definitions, at least one of them being dependent
+		//following a command which kills more than one definition of a variable and at least one of these definitions is dependent
+		int[] aDefsForVar = new int[_analysis.getBytesForDefs()];
+		for (int bytes=0; bytes<iConcernedVars.length; bytes++){
+			for (int bits=0; bits<32;bits++){
+				if ((iConcernedVars[bytes] & (1<< bits))!=0 && (!iVarGoOutOfScope || (_outVars[bytes] & (1<< bits))==0)){
+					//for all variables which are used in this statement and go out of scope
+					//reached by dependent definition?
+					//find all definitions for var
+					for (int i=0; i<_analysis.getBytesForDefs();i++)
+						aDefsForVar[i] = _inDefs[i] & _analysis.getDefsForVar()[bytes << 5 |bits][i];
+					//if (defsInfected(aDefsForVar)<-1) return true;
+					//if (defsInfected(aDefsForVar)<0) return true; //NEW!!!!!!!!!
+					if (defsInfected(aDefsForVar) < 1 - iMinNbOfDefs){
+						  iCheckInfo.setDefinitions(aDefsForVar);
+						  iCheckInfo.setVariableID(bytes << 5 |bits, iConcernedVars.length);
+						  return true;
+					}
+				}
+			}
+		}
+		return false;
+	}
+	
+	private int isCheckpointCandidate(CheckpointInfo iCheckInfo){
+		//being dependent or having at least one dependent inverse operator in the task the communication is established with
+		int aReasonCode=0;
+		//if (_linkedElem!=null) TraceManager.addDev("--- " + _linkedElem.getID() + " start isCheckpointCandidate"); else
+		//TraceManager.addDev("--- start isCheckpointCandidate");
+		if(_linkedElem instanceof TMLReadChannel || _linkedElem instanceof TMLWriteChannel){
+			for (int i=0; i<((TMLActivityElementChannel)_linkedElem).getNbOfChannels(); i++){
+				TMLChannel aChannel = ((TMLActivityElementChannel)_linkedElem).getChannel(i);
+				//TraceManager.addDev("get Infected for channel " + aChannel.getName() + "=" + aChannel.getInfected());
+				//if (aChannel.getInfected()) aReasonCode = CheckpointInfo.CHANNEL_DEP;
+				if (_analysis.isChannelDep(aChannel.getID())) aReasonCode = CheckpointInfo.CHANNEL_DEP;
+			}
+		}else if(_linkedElem instanceof TMLSendEvent || _linkedElem instanceof TMLWaitEvent){
+			//if (((TMLActivityElementEvent)_linkedElem).getEvent().getInfected()) aReasonCode = CheckpointInfo.CHANNEL_DEP;
+			if (_analysis.isChannelDep(((TMLActivityElementEvent)_linkedElem).getEvent().getID())) aReasonCode = CheckpointInfo.CHANNEL_DEP;
+		}else if (_linkedElem instanceof TMLSendRequest){
+			//if (((TMLSendRequest)_linkedElem).getRequest().getInfected()) aReasonCode = CheckpointInfo.CHANNEL_DEP;
+			if (_analysis.isChannelDep(((TMLSendRequest)_linkedElem).getRequest().getID())) aReasonCode = CheckpointInfo.CHANNEL_DEP;
+		}
+		//consider receive event
+		if (_predList.size()>1){
+			//TraceManager.addDev("more than one pred found");
+			aReasonCode += CheckpointInfo.CTRL_FLOW_JOIN;
+		}
+		iCheckInfo.setOperationMode(CheckpointInfo.KILLED_DEF);
+		if (atLeast1DepDefForVars(_defVars, false, 1, iCheckInfo)){
+			//TraceManager.addDev(getStatementDescr() + "  kills dependent definitions!!!");
+			aReasonCode += CheckpointInfo.KILLED_DEF;
+		}
+		iCheckInfo.setOperationMode(CheckpointInfo.VAR_OUT_OF_SCOPE);
+		if (atLeast1DepDefForVars(_useVars, true, 1, iCheckInfo)){
+			//TraceManager.addDev(getStatementDescr()+ " variable went out of scope!!! ");
+			aReasonCode += CheckpointInfo.VAR_OUT_OF_SCOPE;
+		}
+		if(_varDepSource){
+			if (canBeRemoved())
+				_varDepSource=false;
+			else{
+				//_analysis.setLastVarDepSource(_generateDefs);
+				iCheckInfo._depSrcDef = _generateDefs;
+				//TraceManager.addDev("Stored defs: "); printDefList(_generateDefs);
+				aReasonCode += CheckpointInfo.DEP_SRC;
+			}
+		}
+		//TraceManager.addDev("--- end isCheckpointCandidate: " +  aReasonCode);
+		return aReasonCode;
+
+	}
+
+	//public static int evaluate(String string) throws IllegalArgumentException{
+	public String evaluate(String expression) throws IllegalArgumentException{
+		ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
+		try{
+			//Object object = engine.eval("eval("+string+")");
+			engine.eval(expression);
+			Object object = engine.get("xx_xx");
+			if (object != null){
+				String result="";
+				if(object instanceof Number){
+					result = Integer.toString(((Number)(object)).intValue());
+				}else if (object instanceof Boolean){
+					result = ((Boolean)(object)).toString();
+				}else{
+					throw new IllegalArgumentException("Input is neither Integer nor Boolean: '"+expression+"'");
+				}
+                		return result;
+			}else{
+				throw new IllegalArgumentException("Invalid expression: '"+expression+"'");
+			}
+		}catch (ScriptException e){
+			throw new IllegalArgumentException("Invalid input: '"+expression+"'", e);
+		}
+	}
+	
+	public void prepareReachingDefinitions(){
+		invalidate();
+		_generateDefs = new int[_analysis.getBytesForDefs()];
+		_killDefs= new int[_analysis.getBytesForDefs()];
+		_killCandidates = new int[_analysis.getBytesForDefs()];
+		_inDefs = new int[_analysis.getBytesForDefs()];
+		_outDefs = new int[_analysis.getBytesForDefs()];
+		//TraceManager.addDev("<> varToStatements asso: " + getStatementDescr());
+		if (_myDefID!=-1){
+		//if (_myDefID!=-1 && !canBeRemoved()){  //NEW!!!!!!!!!!!
+			for (int bytes=0; bytes<_defVars.length;bytes++){
+				for (int bits=0; bits<32;bits++){
+					//if ((_defVars[bytes] & (1 << bits))!=0){
+					//only consider live variables= defined + significant
+					if ((_defVars[bytes] & (1 << bits))!=0){ //NEW!!!!!!!!!!
+						  if((_outVars[bytes] & (1 << bits))==0){
+							_defVars[bytes] ^= (1 << bits);
+							//TraceManager.addDev("del");
+						  }else
+							_analysis.getDefsForVar()[(bytes << 5)|bits][_myDefID >>> 5] |= 1 << (_myDefID & 0x1F);
+						//TraceManager.addDev("var found:" + ((bytes << 5)|bits));
+					}
+				}
+			}
+			if (!canBeRemoved()){
+				_generateDefs[_myDefID >>> 5] =  1 << (_myDefID & 0x1F);
+				_analysis.getDefLookUp()[_myDefID]=this;
+			}
+		}
+		//TraceManager.addDev("<> END varToStatements asso: " + getStatementDescr());
+	}
+
+	public void printKillEntries(){
+		//TraceManager.addDev("++++++++++ Kill definitions list ++++++++++");
+		System.out.print(getStatementDescr() + "  kills definitions: " + printDefList(_killDefs));
+		TraceManager.addDev("");
+	}
+
+	public void printReachingEntries(){
+		//TraceManager.addDev("++++++++++ Reaching definitions list ++++++++++");
+		//if(_linkedElem!=null && (_linkedElem instanceof TMLReadChannel || _linkedElem instanceof TMLWriteChannel|| _linkedElem instanceof TMLSendEvent || _linkedElem instanceof TMLWaitEvent || _linkedElem instanceof TMLSendRequest)){
+		System.out.print(getStatementDescr());
+		/*printDefList(_inVars);
+		System.out.print("  outvars: ");
+		printDefList(_outVars);
+		System.out.print("  defVars: ");
+		printDefList(_defVars);
+		System.out.print("  useVars: ");
+		printDefList(_useVars);*/
+		//+ "  reached by definitions: ");
+		//printDefList(_inDefs);
+		TraceManager.addDev("");
+		//}
+	}
+
+	private String printDefList(int[] iList){
+		String aResult="";
+		for (int bytes=0; bytes<iList.length; bytes++){
+			for (int bits=0; bits<32;bits++){
+				if ((iList[bytes]& (1 << bits))!=0) aResult += ((bytes << 5)|bits) + ", "; 
+			}
+		}
+		return aResult;
+	}
+	
+	private String printDefCmdIDs(int[] iList){
+		String aResult="";
+		if (iList!=null){
+			for (int bytes=0; bytes<iList.length; bytes++){
+				for (int bits=0; bits<32;bits++){
+					if ((iList[bytes] & (1 << bits))!=0){
+						TMLActivityElement anElem = _analysis.getDefLookUp()[(bytes << 5)|bits]._linkedElem;
+						aResult += _analysis.getDefLookUp()[(bytes << 5)|bits].getNodeInfo();
+						if (anElem!=null) aResult += "(" + anElem.getID() + "),"; else aResult += ",";
+					}
+				}
+			}
+		}
+		return aResult;
+	}
+
+	private boolean allDefsConstantAndEqual(int[] iDefinitions){
+		boolean aIsConst=true, aFirstTime=true, aDefFound=false;
+		//int aLastExprVal=0;
+		String aLastExprVal="";  
+		//TraceManager.addDev("******* allDefsConstantAndEqual");
+		for (int bytes=0; bytes<iDefinitions.length && aIsConst; bytes++){
+			for (int bits=0; bits<32 && aIsConst; bits++){
+				int anIndex = (bytes << 5)|bits;
+				if ((iDefinitions[bytes] & (1<< bits))!=0){ //what if there are no definitions????
+					aDefFound=true;
+					if (_analysis.getDefLookUp()[anIndex].isConstant()){
+						//TraceManager.addDev(_analysis.getDefLookUp()[anIndex].getStatementDescr() + " said to be constant");
+						//if (aFirstTime || _analysis.getDefLookUp()[anIndex].getExpressionValue() == aLastExprVal){
+						if (aFirstTime || _analysis.getDefLookUp()[anIndex].getExpressionValue().equals(aLastExprVal)){
+							aLastExprVal = _analysis.getDefLookUp()[anIndex].getExpressionValue();
+							_unrolledExpr+= _analysis.getDefLookUp()[anIndex].getExpressionString() + ";";
+							aFirstTime=false;
+						}else
+							aIsConst=false;
+					}else{
+						//TraceManager.addDev(_analysis.getDefLookUp()[anIndex].getStatementDescr() + " said to be NOT constant");
+						aIsConst=false;
+					}
+				}//else
+					//if (_analysis.getDefLookUp()[anIndex]!=null) TraceManager.addDev(_analysis.getDefLookUp()[anIndex].getStatementDescr() + " not concerned"); 
+			}
+		}
+		//if (aIsConst)
+		//TraceManager.addDev(aIsConst + " lhs:" + _lhs + " rhs:" + _rhs);
+		return (aIsConst && aDefFound);
+	}
+
+	public int determineIfConstant(){
+		//not constant: random, notified event, receive event, select event
+		//if (_linkedElem!=null && (_linkedElem instanceof TMLRandom || _linkedElem instanceof TMLWaitEvent || _linkedElem instanceof TMLNotifiedEvent || _linkedElem instanceof TMLSelectEvt)) return false;
+		if (_isConstant) return 0;
+		_valid=false;
+		//boolean aIsConst=true;
+		int aResult=0;
+		if (!_constantStuckToFalse){
+			int[] aReachingDefForVar= new int[_analysis.getBytesForDefs()];
+			aResult=2;
+		//TraceManager.addDev("!!!!Checking if  " + getStatementDescr() + " is constant");
+			for (int bytes=0; bytes<_useVars.length; bytes++){
+				for (int bits=0; bits<32;bits++){
+					if ((_useVars[bytes] & (1<< bits))!=0){
+						//TraceManager.addDev("var " + ((bytes << 5)|bits) + " is used  usevars:" + _useVars[bytes]);
+						//TraceManager.addDev("Reached by definitions: ");
+						//printDefList(_inDefs);
+						for (int i=0; i<_analysis.getBytesForDefs();i++){
+							aReachingDefForVar[i] = _analysis.getDefsForVar()[(bytes << 5)|bits][i] & _inDefs[i];
+						}
+						//aIsConst &= allDefsConstant(aReachingDefForVar);
+						if(allDefsConstantAndEqual(aReachingDefForVar)){
+							//toggle bit no [bits] = set it to zero as it is one
+							_useVars[bytes]^= (1<< bits);
+							//TraceManager.addDev("*** " + getStatementDescr() + "toggle bit " + ((bytes << 5)|bits) + "***");
+							//_inVars[bytes] = _useVars[bytes] & _defNegVars[bytes];
+							//_inVars[bytes] = _useVars[bytes] & (~_defVars[bytes]);  NEW!!!!!!!
+							aResult |= 1;   //set bit 2^0
+						}else{
+							//TraceManager.addDev("not all defs constant for variable " + ((bytes << 5)|bits));
+							//aIsConst=false;
+							aResult &= 1;  //del bit 2^1
+						}
+					}
+				}
+			}
+			_isConstant = ((aResult & 2)!=0);
+			if (_isConstant && !(_lhs==null ||_lhs.isEmpty())){
+				_unrolledExpr+= "xx_xx=" + _rhs + ";";
+				//try{
+					_exprValue = evaluate(_unrolledExpr);
+					//TraceManager.addDev("Expr: *" + _unrolledExpr + "* evaluated to: " + _exprValue);
+				//}catch(IllegalArgumentException e){
+					//TraceManager.addDev("At lest one variable of the expression remains undefined: " + _rhs);
+				//}
+			}
+		}
+		//boolean aChangeInResult = (_constantStuckToFalse)? false : aIsConst!= _isConstant;
+		//boolean aChangeInResult = (_constantStuckToFalse)? false : aIsConst;
+		//_isConstant = aIsConst;
+		//return aChangeInResult;
+		return aResult;
+		//}
+	}
+
+	public boolean isConstant(){
+		return (_constantStuckToFalse)? false: _isConstant;
+	}
+	
+	public boolean isInfected(){
+		return _infected;
+	}
+	
+	public String getExpressionString(){
+		return _lhs + "=" + _exprValue;
+	}
+	
+	//public int getExpressionValue(){
+	public String getExpressionValue(){
+		return _exprValue;
+	}
+
+	public int[] getKillCandidates(){
+		return _killCandidates;
+	}
+	
+	public void setInfected(boolean iInfected){
+		_infected = iInfected;
+	}
+
+	public void setVarDepSource(boolean iVarDepSource){
+		_infected = iVarDepSource;
+		_varDepSource = iVarDepSource;
+	}
+	
+	public String getNodeInfo(){
+		return _nodeInfo;
+	}
+	
+	public void setNodeInfo(String iInfo){
+		_nodeInfo=iInfo;
+	}
+
+	public boolean determineKilledSets(){
+		boolean aChange=false;
+		int [] aKillOut = new int[_analysis.getBytesForDefs()];
+		int [] aKillIn = new int[_analysis.getBytesForDefs()];
+		if (!_valid){
+			_valid=true;
+			//TraceManager.addDev("determineKilledSets for " + getStatementDescr() ); 
+			for(LiveVariableNode aPred: _predList) {
+				int[] aKillCandidatesPred = aPred.getKillCandidates();
+				for (int i=0; i<_analysis.getBytesForDefs();i++){
+					aKillOut[i] |= aKillCandidatesPred[i];
+					aKillIn[i] |= aKillCandidatesPred[i];
+				}
+			}
+			//TraceManager.addDev( "aLocalKillCandidates[0] " + aLocalKillCandidates[0]); 
+			//TraceManager.addDev( "killDefs[0] before" + _killDefs[0]); 
+			if (_myDefID!=-1){
+				//TraceManager.addDev("Statement " + _myDefID + " (" + getStatementDescr() + ") defines: " + _generateDefs[0] + " could kill input: " + aLocalKillCandidates[0]);
+				for (int bytes=0; bytes<_defVars.length; bytes++){
+					for (int bits=0; bits<32;bits++){
+						if ((_defVars[bytes] & (1<< bits))!=0){   //for all variables which are defined in this statement
+							for (int i=0; i<_analysis.getBytesForDefs();i++){
+								//killDefs = definitions representing kill candidates in program flow & all statements affecting the current variable targeted in this definition
+								//all kill candidates -> for a specific variable -> variable determined by defVars  
+								//_killDefs[i] |= (aLocalKillCandidates[i] & _varToStatements[(bytes << 5)|bits][i]);
+								_killDefs[i] |= (aKillIn[i] & _analysis.getDefsForVar()[(bytes << 5)|bits][i]);
+								//TraceManager.addDev( "killDefs[i] " + _killDefs[i] + " i" + i); 
+								//int oldCandidates = aLocalKillCandidates[i];
+								//delete all kill candidates for the variable yielded by that definition
+								//aLocalKillCandidates[i] &= ~ _varToStatements[(bytes << 5)|bits][i];
+								aKillOut[i] &= ~ _analysis.getDefsForVar()[(bytes << 5)|bits][i];
+								//add this definition as killer for the variable
+								//aLocalKillCandidates[i] |= _generateDefs[i];
+								aKillOut[i] |= _generateDefs[i];
+								//aChange |= (oldCandidates!=aLocalKillCandidates[i]);
+							}
+						}
+					}
+				}
+			}
+			//TraceManager.addDev( "killDefs[0] " + _killDefs[0]); 
+			for (int i=0; i<_analysis.getBytesForDefs();i++){
+				//aChange |= (_killCandidates[i]!=aLocalKillCandidates[i]);
+				aChange |= (_killCandidates[i]!=aKillOut[i]);
+				//_killCandidates[i]=aLocalKillCandidates[i];
+				_killCandidates[i]=aKillOut[i];
+			}
+			if (aChange){
+				for(LiveVariableNode aSucc: _succList) aSucc.invalidate();
+			}
+		}
+		return aChange;
+	}
+	
+	public String getStatementDescr(){
+		//String aName = "| Live ID: " + _myDefID + " | ";
+		String aName = "| ";
+		if (_linkedElem==null)
+				aName += "cmd type: unknown | cmd ID: unknown";
+		else
+			aName += "cmd type: " + _linkedElem.getName() + " | cmd ID: " + _linkedElem.getID();
+		aName+= " | infected: " + _infected;
+		if (!(_lhs==null || _rhs==null || _lhs.isEmpty() || _rhs.isEmpty()))
+			aName += " | action: " + _lhs + "=" + _rhs;
+		aName += " | const: ";
+		if (_isConstant){
+			if (_lhs==null || _lhs.isEmpty())
+				aName+= "yes";
+			else
+				aName+= _exprValue;
+		}else 
+			aName += "no"; 
+		aName += " | to be removed: " + canBeRemoved() + " | checkp:";
+		if (_checkpoint==null)
+			aName += "0";
+		else{
+			if ((_checkpoint._reasonCode & CheckpointInfo.CHANNEL_DEP)!=0) aName += " CH_DEP";
+			if ((_checkpoint._reasonCode & CheckpointInfo.CTRL_FLOW_JOIN)!=0) aName += " CTRL(" + printDefCmdIDs(_checkpoint._ctrlFlowJoinDefs) + ")";
+			if ((_checkpoint._reasonCode & CheckpointInfo.KILLED_DEF)!=0) aName += " KILL(" + printDefCmdIDs(_checkpoint._killedDefs) + ")";
+			if ((_checkpoint._reasonCode & CheckpointInfo.VAR_OUT_OF_SCOPE)!=0) aName += " VAR_SCP(" + _analysis.printVariables(_checkpoint._varsOutOfScope) + ")";
+			if ((_checkpoint._reasonCode & CheckpointInfo.DEP_SRC)!=0) aName += " SRC(" + printDefCmdIDs(_checkpoint._depSrcDef) + ")";
+		}
+		aName += " | ";
+		return aName;
+	}
+
+	public void invalidate(){
+		_valid=false;
+	}
+	
+	private boolean chOfCmdAllNBRNBW(TMLActivityElementChannel iElem){
+		for (int i=0; i<iElem.getNbOfChannels(); i++)
+			if (iElem.getChannel(i).getType()!=TMLChannel.NBRNBW) return false;
+		return true;
+	}
+	
+	//public void determineCheckpoints(int iPropagate, CheckpointInfo iCheckInfo){
+	public void determineCheckpoints(CheckpointInfo iCheckInfo){
+		if (!_guard){
+			//if (_checkpoint==0){
+			if (_checkpoint==null){
+				//int aCandidate = iCheckInfo.__reasonCode | isCheckpointCandidate(iCheckInfo);
+				iCheckInfo._reasonCode |= isCheckpointCandidate(iCheckInfo);
+				//if (_linkedElem!=null) TraceManager.addDev(_linkedElem.getID() + "  aCandidate: " + aCandidate);
+				iCheckInfo.setOperationMode(CheckpointInfo.CTRL_FLOW_JOIN);
+				//if ((aCandidate & CheckpointInfo.CTRL_FLOW_JOIN)!=0 && !atLeast1DepDefForVars(_inVars, false, 2, iCheckInfo)){
+				if ((iCheckInfo._reasonCode & CheckpointInfo.CTRL_FLOW_JOIN)!=0 && !atLeast1DepDefForVars(_inVars, false, 2, iCheckInfo)){
+					//aCandidate ^= CheckpointInfo.CTRL_FLOW_JOIN;
+					iCheckInfo._reasonCode ^= CheckpointInfo.CTRL_FLOW_JOIN;
+					//TraceManager.addDev("aCandidate reset control flow join");
+				}
+				//if ((aCandidate & CheckpointInfo.DEP_SRC)!=0){
+				if ((iCheckInfo._reasonCode & CheckpointInfo.DEP_SRC)!=0){
+					boolean aDefReachable=false;
+					for (int i=0; i<_analysis.getBytesForDefs() && !aDefReachable; i++)
+						//aDefReachable |= ((_analysis.getLastVarDepSource()[i] & _outDefs[i]) !=0);
+						aDefReachable |= ((iCheckInfo._depSrcDef[i] & _outDefs[i]) !=0);
+					if (!aDefReachable){
+						//aCandidate ^= CheckpointInfo.DEP_SRC;
+						iCheckInfo._reasonCode ^= CheckpointInfo.DEP_SRC;
+						/*TraceManager.addDev("aCandidate reset dep src");
+						TraceManager.addDev("comp1 in defs: "); printDefList(_outDefs);
+						TraceManager.addDev("comp2 stored defs: "); printDefList(_analysis.getLastVarDepSource());*/
+					}
+				}
+				//if(aCandidate>0){
+				if(iCheckInfo._reasonCode > 0){
+					if(((_linkedElem instanceof TMLReadChannel || _linkedElem instanceof TMLWriteChannel) && !chOfCmdAllNBRNBW((TMLActivityElementChannel)_linkedElem)) || _linkedElem instanceof TMLSendEvent || _linkedElem instanceof TMLWaitEvent || _linkedElem instanceof TMLSendRequest){
+						//_checkpoint=aCandidate;
+						_checkpoint = iCheckInfo;
+					}else{
+						_guard=true;
+						for(LiveVariableNode aSucc: _succList)
+							aSucc.determineCheckpoints(iCheckInfo);
+						_guard = false;
+					}
+				}
+			}else
+				//_checkpoint |= iPropagate;
+				_checkpoint.incorporate(iCheckInfo);
+		}
+	}
+
+	public void reachingDefinitionsInit(){
+		invalidate();
+		for (int i=0; i<_analysis.getBytesForDefs();i++){
+			_outDefs[i] = _generateDefs[i] & (~_killDefs[i]);
+		}
+		//TraceManager.addDev("out Defs " + getStatementDescr() + " " + _outDefs[0] + " generate Defs: " + _generateDefs[0] + " kill Defs: " + _killDefs[0]);
+	}
+
+	public boolean reachingDefinitionAnalysis(){
+		boolean aSuccInvalidated=false;
+		if (!_valid){
+			_valid=true;
+			for(LiveVariableNode aPred: _predList) {
+				int[] aPredOutDefs = aPred.getOutDefs();
+				for (int i=0; i<_analysis.getBytesForDefs();i++){
+					_inDefs[i] |= aPredOutDefs[i];
+					int aOutDefsOld=_outDefs[i];
+					_outDefs[i] = _generateDefs[i] | _inDefs[i] & (~_killDefs[i]);
+					if (aOutDefsOld!=_outDefs[i]) aSuccInvalidated=true; 
+				} 
+			}
+			if(aSuccInvalidated){
+				for(LiveVariableNode aSucc: _succList)
+					aSucc.invalidate();
+			}
+		}
+		return aSuccInvalidated;
+	}
+
+	public boolean liveVariableAnalysis(){
+		boolean aPredInvalidated=false;
+		if (!_valid){
+			_valid=true;
+			/*if (_linkedElem==null)
+				System.out.print("recalculate waitRequest invalidate: ");
+			else 
+				System.out.print("recalculate " + _linkedElem.getName() + " " + _linkedElem.getID() + "invalidate: ");*/
+			for(LiveVariableNode aSucc: _succList) {
+				int[] aSuccInVars = aSucc.getInVars();
+				for (int i=0; i<aSuccInVars.length;i++){
+					_outVars[i] |= aSuccInVars[i];
+					int aInVarsOld=_inVars[i];
+					//_inVars[i] = _useVars[i] | _outVars[i] & _defNegVars[i];
+					_inVars[i] = _useVars[i] | _outVars[i] & (~_defVars[i]);
+					if (aInVarsOld!=_inVars[i]) aPredInvalidated=true; 
+				} 
+			}
+			if(aPredInvalidated){
+				for(LiveVariableNode aPred: _predList){
+					aPred.invalidate();
+					/*if (aPred.getLinkedElement()==null)
+						System.out.print("waitRequest, ");
+					else
+						System.out.print(aPred.getLinkedElement().getID() + ", ");*/
+				}
+			}
+			//TraceManager.addDev();
+		}
+		return aPredInvalidated;
+	}
+	
+	public boolean infectionAnalysis(){
+		//if (_linkedElem!=null) TraceManager.addDev("Infection Analysis: "+  _linkedElem.getID());
+		if (_infected){
+			//TraceManager.addDev("cancelled");
+			return false;
+		}else{
+			if (_superiorBranchNode!=null && _superiorBranchNode.isInfected()){
+				//control dependency
+				_infected=true;
+			}else{
+				//data dependency
+				int[] aRelevantDefs = new int[_analysis.getBytesForDefs()];
+				for (int bytes=0; bytes<_useVars.length; bytes++){
+					for (int bits=0; bits<32;bits++){
+						if ((_useVars[bytes] & (1<< bits))!=0){   //for all variables which are used in this statement
+							for (int i=0; i<_analysis.getBytesForDefs();i++){
+								 aRelevantDefs[i] |=_inDefs[i] & _analysis.getDefsForVar()[(bytes << 5)|bits][i];
+							}						
+						}
+					}
+				}
+				_infected |= (defsInfected(aRelevantDefs)<0);
+			}
+		}
+		//synchronization dependency
+		if (_infected && _linkedElem!=null){
+			//TraceManager.addDev("in if 1");
+			if(_linkedElem instanceof TMLReadChannel || _linkedElem instanceof TMLWriteChannel){
+				//TraceManager.addDev("in if 2");
+				for (int i=0; i<((TMLActivityElementChannel)_linkedElem).getNbOfChannels(); i++){
+					//TraceManager.addDev("in loop");
+					TMLChannel aChannel = ((TMLActivityElementChannel)_linkedElem).getChannel(i);
+					//TraceManager.addDev("Set Infected for channel " + aChannel.getName());
+					//if (aChannel.getType()!=TMLChannel.NBRNBW) aChannel.setInfected(true);
+					if (aChannel.getType()!=TMLChannel.NBRNBW) _analysis.addDepChannel(aChannel.getID());
+				}
+			}else if(_linkedElem instanceof TMLSendEvent || _linkedElem instanceof TMLWaitEvent){
+				//((TMLActivityElementEvent)_linkedElem).getEvent().setInfected(true);
+				_analysis.addDepChannel(((TMLActivityElementEvent)_linkedElem).getEvent().getID());
+			}else if (_linkedElem instanceof TMLSendRequest){
+				//((TMLSendRequest)_linkedElem).getRequest().setInfected(true);
+				_analysis.addDepChannel(((TMLSendRequest)_linkedElem).getRequest().getID());
+			}
+		}
+		return _infected;
+	}
+	
+	private int defsInfected(int[] iDefs){
+		boolean aInfected=false;
+		int aNbOfDefs=0;
+		for (int bytes=0; bytes<iDefs.length; bytes++){
+			for (int bits=0; bits<32;bits++){
+				if ((iDefs[bytes] & (1<< bits))!=0){ 
+					aNbOfDefs++;
+					aInfected |= _analysis.getDefLookUp()[(bytes << 5)|bits].isInfected();
+				}
+			}
+		}
+		return (aInfected)? -aNbOfDefs : aNbOfDefs;
+	}
+	
+
+	public TMLActivityElement getLinkedElement(){
+		return _linkedElem;
+	}
+
+	public boolean isEmptyNode(){
+		return false;
+		/*if (_succList.size()>1) return false;
+		for (int i=0; i<_defVars.length;i++)
+			if (_defVars[i]!=0) return false;
+		for (int i=0; i<_useVars.length;i++)
+			if (_useVars[i]!=0) return false;
+		return true;*/
+	}
+
+	public void setSuccessor(LiveVariableNode iSucc){
+		if(iSucc!=null){
+			_succList.add(iSucc);
+			iSucc.setPredecessor(this);
+		}
+	}
+
+	private void setPredecessor(LiveVariableNode iPred){
+		_predList.add(iPred);
+		//if (_linkedElem!=null) TraceManager.addDev(_linkedElem.getID() + " adds pred " + iPred._myDefID);
+	}
+
+	public int[] getInVars(){
+		return _inVars;
+	}
+
+	public int[] getOutVars(){
+		return _outVars;
+	}
+	
+	public int[] getInDefs(){
+		return _inDefs;
+	}
+
+	public int[] getOutDefs(){
+		return _outDefs;
+	}
+
+	public int[] getInitialDefVars(){
+		return _initialDefVars;
+	}
+
+	private boolean canBeRemoved(){
+		//if ((_lhs==null || _lhs.isEmpty()) && (_rhs==null || _rhs.isEmpty()) && !(_linkedElem==null || _linkedElem instanceof TMLNotifiedEvent || _linkedElem instanceof TMLRandom)) return false;
+		for (int i=0; i<_defVars.length;i++){
+			if ((_defVars[i] & _outVars[i]) !=0) return false;
+		}
+		return true;
+	}
+
+	public String getLiveVariableString(){
+		/*System.out.print("Numbers: ");
+		for (int aPos=0; aPos<_outVars.length; aPos++){
+			System.out.print(Integer.toHexString(_outVars[aPos]) + ", ");
+		}
+		TraceManager.addDev();*/
+		return intArrayToHexString(_outVars);
+	}
+	
+	public String getStartLiveVariableString(){
+		return intArrayToHexString(_inVars);
+	}
+
+	public String getStateModificationString(){
+		return intArrayToHexString(_defVars);
+	}
+
+	private String intArrayToHexString(int[] iArray){
+		String aResult = "\"";
+		//\\x" + Integer.toHexString(iArray.length); 	
+		for (int aPos=0; aPos<iArray.length; aPos++){
+			int anItem = iArray[aPos];
+			for (int bytes=0; bytes<4; bytes++){
+			//for (int bits=0; bits<32; bits+=8)
+				aResult+= "\\x" + Integer.toHexString(anItem & 0xFF);
+				anItem >>>= 8;
+			}
+		}
+		aResult+="\"";
+		//TraceManager.addDev("String: " + aResult);
+		return aResult;
+	}
+	
+	public boolean isCheckpoint(){
+		return (_checkpoint!=null);
+	}
+}
diff --git a/src/tmltranslator/tomappingsystemc3/MappedSystemCTask.java b/src/tmltranslator/tomappingsystemc3/MappedSystemCTask.java
new file mode 100755
index 0000000000000000000000000000000000000000..6356f3bbff2c4025bc2998d743125a9feaa560f8
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/MappedSystemCTask.java
@@ -0,0 +1,985 @@
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
+ *
+ * ludovic.apvrille AT telecom-paristech.fr
+ * andrea.enrici 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.
+ *
+ * /**
+ * Class MappedSystemCTask
+ * Creation: 30/05/2014
+ * @version 1.0 30/05/2014
+ * @author Andrea Enrici, Daniel Knorreck
+ * @see
+ */
+
+package tmltranslator.tomappingsystemc3;
+
+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 TMLMapping tmlmapping;
+	private int commentNum;
+	private boolean debug;
+	private boolean optimize;
+	private StaticAnalysis _analysis;
+	private LiveVariableNode _startAnaNode=null;
+	
+	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, TMLMapping _tmlmapping, Set<Integer> _depChannels) {
+        	task = _task;
+		channels = _channels;
+		events = _events;
+		requests = _requests;
+		tmlmapping=_tmlmapping;
+        	reference = task.getName();
+		cppcode = "";
+		hcode = "";
+		initCommand="";
+		functions="";
+		chaining="";
+		firstCommand="";
+		functionSig="";
+		commentText="";
+		commentNum=0;
+		optimize=false;
+		
+		//for(TMLAttribute att: task.getAttributes()) {
+		//	 TraceManager.addDev ("************ Attribute: " + att.name);
+		//}	
+		
+		_analysis = new StaticAnalysis(_task, _channels, _events, _requests, _depChannels);
+		_startAnaNode = _analysis.startAnalysis();
+    	}
+	
+	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, boolean _optimize) {
+		//_startAnaNode = _analysis.startAnalysis();
+		//_analysis.determineCheckpoints(aStatistics); //NEW
+        	debug = _debug;
+		optimize=_optimize;
+		basicCPPCode();
+		makeClassCode();
+    	}
+	
+	public void print() {
+		TraceManager.addDev("task: " + reference + DOTH + hcode);
+		TraceManager.addDev("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 <TMLRandomChoiceCommand.h>\n#include <TMLExeciCommand.h>\n";
+		code += "#include <TMLSelectCommand.h>\n#include <TMLReadCommand.h>\n#include <TMLNotifiedCommand.h>\n#include<TMLExeciRangeCommand.h>\n";
+		code += "#include <TMLRequestCommand.h>\n#include <TMLSendCommand.h>\n#include <TMLWaitCommand.h>\n";
+		code += "#include <TMLWriteCommand.h>\n#include <TMLStopCommand.h>\n#include<TMLWriteMultCommand.h>\n#include <TMLRandomCommand.h>\n\n";
+		code += "extern \"C\" bool condFunc(TMLTask* _ioTask_);\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(iID, iPriority,iName,iCPUs,iNumOfCPUs)"+ CR + makeAttributesCode();
+		cppcode+=initCommand + CR + "{" + CR; 
+		if (commentNum!=0) cppcode+= "_comment = new std::string[" + commentNum + "]" + SCCR + commentText + CR;
+		cppcode+= "//generate task variable look-up table"+ CR;
+		for(TMLAttribute att: task.getAttributes()) {
+			//att = (TMLAttribute)(iterator.next());
+			//code += TMLType.getStringType(att.type.getType()) + " " + att.name;
+			cppcode += "_varLookUpName[\"" + att.name + "\"]=&" + att.name +SCCR;
+			cppcode += "_varLookUpID[" + att.getID() + "]=&" + att.name +SCCR;
+		}		
+		cppcode += "_varLookUpName[\"rnd__0\"]=&rnd__0" + SCCR + 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 + "_firstCommand=" + firstCommand +SCCR + CR; 
+		int aSeq=0;
+		for(TMLChannel ch: channels) {
+			cppcode+= "_channels[" + aSeq + "] = " + ch.getExtendedName() + SCCR;
+			 aSeq++;
+		}
+		for(TMLEvent evt: events) {
+			cppcode+= "_channels[" + aSeq + "] = " + evt.getExtendedName() + SCCR;
+			aSeq++;
+		}
+		if (task.isRequested()){
+			cppcode+= "_channels[" + aSeq + "] = requestChannel" + SCCR;
+		}
+		TMLActivityElement currElem=task.getActivityDiagram().getFirst();
+		LiveVariableNode currNode;
+		do{
+			currNode = _analysis.getLiveVarNodeByCommand(currElem);
+			currElem = currElem.getNextElement(0);
+		}while (currNode==null && currElem!=null);
+		if (currNode!=null) cppcode+= "refreshStateHash(" + currNode.getStartLiveVariableString() + ")" +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+ "(ID iID, Priority iPriority, std::string iName, CPU** iCPUs, unsigned int iNumOfCPUs"+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 (req.isAnOriginTask(task)) constSig+=", TMLEventChannel* " + req.getExtendedName() + CR;
+		}
+		if (task.isRequested()){
+			//constSig+=", TMLEventBChannel* requestChannel"+CR;
+			constSig+=", TMLEventChannel* requestChannel"+CR;
+		}
+		return constSig+")";
+	}
+
+	private void makeHeaderClassH() {
+		String hcodeBegin="";
+		hcodeBegin = "class " + reference + ": public TMLTask {" + CR;
+		hcodeBegin += "private:" + CR;
+		
+		hcodeBegin += "// Attributes" + CR;
+		
+		if (task.isRequested()) {
+			int params = task.getRequest().getNbOfParams();
+			firstCommand="_waitOnRequest";
+			hcode+="TMLWaitCommand " + firstCommand + SCCR;
+			initCommand+= "," + firstCommand + "(" + task.getActivityDiagram().getFirst().getID() + ",this,requestChannel,"; 
+			if (params==0){
+				initCommand+= "0,"+ getFormattedLiveVarStr(_startAnaNode) + ")" + CR;
+			}else{
+				initCommand+= "(ParamFuncPointer)&" + reference + "::" + "waitOnRequest_func," + getFormattedLiveVarStr(_startAnaNode)  + ")" + CR;
+				//functionSig+="Parameter<ParamType>* waitOnRequest_func(Parameter<ParamType>* ioParam)" + SCCR;
+				//functions+="Parameter<ParamType>* " + reference + "::waitOnRequest_func(Parameter<ParamType>* ioParam){" + CR;
+
+				functionSig+="Parameter* waitOnRequest_func(Parameter* ioParam)" + SCCR;
+				functions+="Parameter* " + reference + "::waitOnRequest_func(Parameter* ioParam){" + CR;
+				functions+= "ioParam->getP(&arg1__req";
+				for (int i=1; i<params; i++){
+					functions+= ", &arg" + (i+1) + "__req";
+				}
+				functions+=")" + SCCR + "return 0" + SCCR;
+				functions+="}\n\n"; 
+			}	
+			String xx = firstCommand + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(task.getActivityDiagram().getFirst(),false,"&"+firstCommand,null) + "))"+ SCCR;
+			firstCommand="&"+firstCommand;
+			chaining+=xx;
+		}else{
+			firstCommand=makeCommands(task.getActivityDiagram().getFirst(),false,"0",null);
+		}
+
+		hcode = basicHCode() + hcodeBegin + makeAttributesDeclaration() + CR + hcode;
+		// public dec
+		hcode += CR + functionSig + CR + "public:" + CR;
+		hcode += "friend bool condFunc(TMLTask* _ioTask_);\n";
+		hcode += "friend class CurrentComponents;\n";
+		// Simulation
+		hcode += makeConstructorSignature() + SCCR; // + "~" + reference + "()" + SCCR;
+		makeSerializableFuncs();
+	}
+
+	private void makeSerializableFuncs(){
+		hcode += "std::istream& readObject(std::istream& i_stream_var)" + SCCR;
+		hcode += "std::ostream& writeObject(std::ostream& i_stream_var)" + SCCR;
+		//hcode += "unsigned long getStateHash() const" + SCCR;
+		functions+= "std::istream& " + reference + "::readObject(std::istream& i_stream_var){\n";
+		for (TMLAttribute att:task.getAttributes()){
+			//att = (TMLAttribute)(iterator.next());
+			functions += "READ_STREAM(i_stream_var," + att.name + ")" + SCCR;
+			functions += "#ifdef DEBUG_SERIALIZE\n";
+			functions += "std::cout << \"Read: Variable " + att.name + " \" << " + att.name +  " << std::endl" + SCCR;
+			functions += "#endif\n";
+		}
+		functions+= "TMLTask::readObject(i_stream_var);\nreturn i_stream_var;\n}\n\n";
+		functions+= "std::ostream& " + reference + "::writeObject(std::ostream& i_stream_var){\n";
+		for (TMLAttribute att:task.getAttributes()){
+			functions += "WRITE_STREAM(i_stream_var," + att.name + ")" + SCCR;
+			functions += "#ifdef DEBUG_SERIALIZE\n";
+			functions += "std::cout << \"Write: Variable " + att.name + " \" << " + att.name +  " << std::endl" + SCCR;
+			functions += "#endif\n";
+		}
+		functions+= "TMLTask::writeObject(i_stream_var);\nreturn i_stream_var;\n}\n\n";
+		hcode += "void reset()" + SCCR;
+		functions+= "void "+reference + "::reset(){\nTMLTask::reset();\n";
+		for (TMLAttribute att:task.getAttributes()){
+			functions += att.name + "=";
+			if (att.hasInitialValue())
+				functions += att.initialValue + SCCR;
+			else
+				functions += "0" + SCCR;
+		}
+		functions+= "}\n\n";
+		/*hcode += "void refreshStateHash(const char* iLiveVarList);\n";
+		functions+= "void " + reference + "::refreshStateHash(const char* iLiveVarList){\n";
+		int aSeq=0;
+		functions += "_stateHash.init((HashValueType)_ID,30);\nif(iLiveVarList!=0){\n";*/
+		hcode += "HashValueType getStateHash();\n";
+		functions+= "HashValueType " + reference + "::getStateHash(){\n";
+		int aSeq=0;
+		//functions += "if(_liveVarList!=0 && _hashInvalidated){\n";
+		functions += "if(_hashInvalidated){\n";
+		functions += "_hashInvalidated=false;\n_stateHash.init((HashValueType)_ID,30);\n";
+		functions += "if(_liveVarList!=0){\n";
+		for(TMLAttribute att: task.getAttributes()) {
+			functions += "if ((_liveVarList[" + (aSeq >>> 3) + "] & " + (1 << (aSeq & 0x7)) + ")!=0) _stateHash.addValue(" + att.getName() + ");\n";
+			//functions += "_stateHash.addValue(" + att.getName() + ");\n";
+			aSeq++;
+		}
+		int i=0;
+		//for channels: include hash only if performed action is blocking
+		//for events: include filling level for senders (notified possible), include parameters for readers (if parameters set)
+		for(TMLChannel ch: channels) {
+			if (ch.getType()==TMLChannel.BRBW || (ch.getType()==TMLChannel.BRNBW && ch.getDestinationTask()==task)) functions += "_channels[" + i +"]->setSignificance(this, " + "((_liveVarList[" + (aSeq >>> 3) + "] & " + (1 << (aSeq & 0x7)) + ")!=0));\n";
+			//if (ch.getType()==TMLChannel.BRBW || (ch.getType()==TMLChannel.BRNBW && ch.getDestinationTask()==task)) functions += "_channels[" + i +"]->setSignificance(this, true);\n";
+
+			aSeq++; i++;
+		}
+		for(TMLEvent evt: events) {
+			if (evt.isBlocking() || evt.getDestinationTask()==task) functions += " _channels[" + i +"]->setSignificance(this, " + "((_liveVarList[" + (aSeq >>> 3) + "] & " + (1 << (aSeq & 0x7)) + ")!=0));\n";
+			//if (evt.isBlocking() || evt.getDestinationTask()==task) functions += " _channels[" + i +"]->setSignificance(this, true);\n";
+			aSeq++; i++;
+		}
+		if (task.isRequested()){
+			functions += " _channels[" + i +"]->setSignificance(this, " + "((_liveVarList[" + (aSeq >>> 3) + "] & " + (1 << (aSeq & 0x7)) + ")!=0));\n";
+			//functions += " _channels[" + i +"]->setSignificance(this, true);\n";
+		}
+		/*for(i=0; i< channels.size() + events.size() + (task.isRequested()? 1:0) ; i++){
+			functions += "if ((iLiveVarList[" + (aSeq >>> 3) + "] & " + (1 << (aSeq & 0x7)) + ")!=0) _channels[" + i +"]->getStateHash(iHash);\n";
+			aSeq++;
+		}*/
+		//functions += "}\n}\n\n";
+		functions += "}\n}\nreturn _stateHash.getHash();\n}\n\n";
+	}
+
+	private String getFormattedLiveVarStr(TMLActivityElement currElem){
+		return getFormattedLiveVarStr(_analysis.getLiveVarNodeByCommand(currElem));
+		//return getFormattedLiveVarStr((LiveVariableNode)null);
+	}
+	
+	private String getFormattedLiveVarStr(LiveVariableNode currNode){
+		if (currNode==null){
+			return "0, false";
+		}else{
+			String checkpoint = (currNode.isCheckpoint())? "true":"false";
+			//String checkpoint = "true";
+			return currNode.getLiveVariableString() + "," + checkpoint;
+		}
+	}
+	
+	
+
+	private String makeCommands(TMLActivityElement currElem, boolean skip, String retElement, String retElseElement){
+		String nextCommand="",cmdName="";
+
+		if (skip) return makeCommands(currElem.getNextElement(0), false,retElement,null);
+
+		if (currElem==null){
+			if (debug) TraceManager.addDev("Checking null\n");
+			return retElement;
+		}
+		
+		if (debug) TraceManager.addDev("Checking " + currElem.getName() + CR);
+
+		if (currElem instanceof TMLStartState) {
+			if (debug) TraceManager.addDev("Checking Start\n");
+			return makeCommands(currElem.getNextElement(0), false,retElement,null);
+		
+		} else if (currElem instanceof TMLStopState){
+			//add stop state if (retElement.equals("0"))
+			if (debug) TraceManager.addDev("Checking Stop\n");
+			if (retElement.equals("0")){
+				cmdName= "_stop" + currElem.getID();
+				hcode+="TMLStopCommand " + cmdName + SCCR;
+				initCommand+= "," + cmdName + "(" + currElem.getID() + ",this)" + CR;
+			}else
+				return retElement;
+		
+		}else if (currElem instanceof TMLRandom){
+			if (debug) TraceManager.addDev("Checking Random\n");
+			cmdName= "_random" + currElem.getID();
+			TMLRandom random = (TMLRandom)currElem;
+			hcode+="TMLRandomCommand " + cmdName + SCCR;
+			initCommand+= "," + cmdName + "("+ currElem.getID() + ",this," + makeCommandRangeFunc(cmdName, random.getMinValue(), random.getMaxValue()) + ",&" + random.getVariable() + "," + getFormattedLiveVarStr(currElem) + ")"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "));\n";
+			//functions+="void "+ reference + "::" + cmdName + "_func(ParamType& oMin, ParamType& oMax){\n oMin=" + modifyString(random.getMinValue()) + ";\noMax=" + modifyString(random.getMaxValue()) + SCCR;
+			//functions+= "}" + CR2;
+			//functionSig+="void " + cmdName + "_func(ParamType & oMin, ParamType& oMax)" + SCCR;
+
+		} else if (currElem instanceof TMLActionState || currElem instanceof TMLDelay){
+			String action,comment;
+			if (currElem instanceof TMLActionState){				
+				if (debug) TraceManager.addDev("Checking Action\n");
+				action = formatAction(((TMLActionState)currElem).getAction());
+				comment=action;
+			}else{
+				if (debug) TraceManager.addDev("Checking Delay\n");
+				int masterClockFreq = tmlmapping.getTMLArchitecture().getMasterClockFrequency();
+				TMLDelay delay=(TMLDelay)currElem;
+				action = "TMLTime tmpDelayxy = " + delay.getMaxDelay() + "*" + masterClockFreq + delay.getMasterClockFactor() + ";";
+				comment=action;
+				action+= "\nif (tmpDelayxy==0) tmpDelayxy=1;\n";
+				if (delay.getMinDelay().equals(delay.getMaxDelay())){
+					action += "_endLastTransaction+=tmpDelayxy";
+				}else{
+					action += "TMLTime tmpDelayxx = " + delay.getMinDelay() + "*" + masterClockFreq + delay.getMasterClockFactor() + ";\nif (tmpDelayxx==0) tmpDelayxx=1;\n";
+					action += "_endLastTransaction+=myrand(tmpDelayxx,tmpDelayxy)";
+				}
+			}
+			//cmdName= "_action" + currElem.getID();
+			String elemName=currElem.getName(), idString;
+			if (elemName.charAt(0)=='#'){
+				int pos=elemName.indexOf('\\');
+				idString=elemName.substring(1,pos);
+				//TraceManager.addDev(elemName + "***" + pos + "***" + idString + "***"+ elemName.length());
+				cmdName="_" + elemName.substring(pos+1) + idString;
+			}else{
+				cmdName= "_action" + currElem.getID();
+				idString=String.valueOf(currElem.getID());
+			}
+			hcode+="TMLActionCommand " + cmdName + SCCR;
+			initCommand+= "," + cmdName + "("+ idString + ",this,(ActionFuncPointer)&" + reference + "::" + cmdName + "_func, " + getFormattedLiveVarStr(currElem) +  ")"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "));\n";
+			functions+="void "+ reference + "::" + cmdName + "_func(){\n#ifdef ADD_COMMENTS\naddComment(new Comment(_endLastTransaction,0," + commentNum + "));\n#endif\n" + modifyString(addSemicolonIfNecessary(action)) + CR;
+			//functions+="return 0"+ SCCR;
+			functions+= "}" + CR2;
+			commentText+="_comment[" + commentNum + "]=std::string(\"Action " + comment + "\");\n";
+			commentNum++;
+			functionSig+="void " + cmdName + "_func()" + SCCR;
+		
+		} else if (currElem instanceof TMLExecI){
+			if (debug) TraceManager.addDev("Checking Execi\n");
+			cmdName= "_execi" + currElem.getID();
+			hcode+="TMLExeciCommand " + cmdName + SCCR;
+			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecI)currElem).getAction() + ",0,0)"+CR;
+			if (isIntValue(((TMLExecI)currElem).getAction()))
+				initCommand+= "," + cmdName + "(" + currElem.getID() + ",this,0,0," + ((TMLExecI)currElem).getAction() + "," + getFormattedLiveVarStr(currElem) + ")" + CR;
+			else
+				initCommand+= "," + cmdName + "(" + currElem.getID() + ",this," + makeCommandLenFunc(cmdName, ((TMLExecI)currElem).getAction(), null) + ",0,1," + getFormattedLiveVarStr(currElem) + ")" + CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;
+
+		} else if (currElem instanceof TMLExecC){
+			if (debug) TraceManager.addDev("Checking ExecC\n");
+			cmdName= "_execc" + currElem.getID();
+			hcode+="TMLExeciCommand " + cmdName + SCCR;
+			if (isIntValue(((TMLExecC)currElem).getAction()))
+				initCommand+= "," + cmdName + "(" + currElem.getID() + ",this,0,1," + ((TMLExecC)currElem).getAction() + "," + getFormattedLiveVarStr(currElem) + ")" + CR;
+			else
+				initCommand+= "," + cmdName + "("+ currElem.getID() + ",this,"+ makeCommandLenFunc(cmdName, ((TMLExecC)currElem).getAction(), null) + ",1,1," + getFormattedLiveVarStr(currElem) + ")"+CR;
+				
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLExecIInterval){
+			/*if (debug) TraceManager.addDev("Checking ExeciInterv\n");
+			cmdName= "_execi" + currElem.getID();
+			hcode+="TMLExeciCommand " + cmdName + SCCR;
+			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecIInterval)currElem).getMinDelay()+ "," + ((TMLExecIInterval)currElem).getMaxDelay() + ",0)"+CR;
+			initCommand+= "," + cmdName + "("+currElem.getID()+",this,"+ makeCommandLenFunc(cmdName, ((TMLExecIInterval)currElem).getMinDelay(), ((TMLExecIInterval)currElem).getMaxDelay()) + ",0,1," + getFormattedLiveVarStr(currElem) + ")" +CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;*/
+			if (debug) TraceManager.addDev("Checking ExeciInterv\n");
+			cmdName= "_execi" + currElem.getID();
+			hcode+="TMLExeciRangeCommand " + cmdName + SCCR;
+			initCommand+= "," + cmdName + "("+currElem.getID()+",this,"+ makeCommandRangeFunc(cmdName, ((TMLExecIInterval)currElem).getMinDelay(), ((TMLExecIInterval)currElem).getMaxDelay()) + ",0," + getFormattedLiveVarStr(currElem) + ")" +CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;
+
+		} else if (currElem instanceof TMLExecCInterval){
+			if (debug) TraceManager.addDev("Checking ExecCInterv\n");
+			cmdName= "_execc" + currElem.getID();
+			hcode+="TMLExeciCommand " + cmdName + SCCR;
+			//initCommand+= "," + cmdName + "(this,"+ ((TMLExecIInterval)currElem).getMinDelay()+ "," + ((TMLExecIInterval)currElem).getMaxDelay() + ",1)"+CR;
+			initCommand+= "," + cmdName + "("+currElem.getID()+",this,"+ makeCommandLenFunc(cmdName, ((TMLExecCInterval)currElem).getMinDelay(), ((TMLExecCInterval)currElem).getMaxDelay()) + ",1,1," + getFormattedLiveVarStr(currElem) + ")"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;
+
+					
+		} else if (currElem instanceof TMLForLoop){
+			//makeCommands(TMLActivityElement currElem, boolean skip, String retElement, MergedCmdStr nextCommandCont, String retElseElement)
+			if (debug) TraceManager.addDev("Checking Loop\n");
+			TMLForLoop fl = (TMLForLoop)currElem;
+			if (fl.getCondition().isEmpty() || fl.getCondition().trim().toUpperCase().equals("TRUE")){
+				//initAction.addNext(fl.getNextElement(0)); //inside loop
+				TMLActionState incAction=new TMLActionState("#"+ fl.getID() + "\\lpIncAc",null);
+				incAction.setAction(fl.getIncrement());
+				String firstCmdInLoop= makeCommands(fl.getNextElement(0), false, "&_lpIncAc" + fl.getID(), null);
+				makeCommands(incAction, false, firstCmdInLoop, null);
+				if (fl.getInit().isEmpty()){
+					return firstCmdInLoop;
+				}else{
+					TMLActionState initAction=new TMLActionState("lpInitAc",null);
+					initAction.setAction(fl.getInit());
+					return makeCommands(initAction, false, firstCmdInLoop,null);
+				}
+				
+			}else{	
+				TMLChoice lpChoice=new TMLChoice("#"+ fl.getID() + "\\lpChoice",null);
+				//if (fl.getCondition().isEmpty())
+				//	lpChoice.addGuard("[ true ]");
+				//else
+				lpChoice.addGuard("[ " + fl.getCondition() + " ]");
+				lpChoice.addGuard("[ else ]");
+				lpChoice.addNext(fl.getNextElement(0));  //inside loop
+				lpChoice.addNext(fl.getNextElement(1));  //after loop           cmdName= "_choice" + currElem.getID();
+				if (fl.getIncrement().isEmpty()){
+					makeCommands(lpChoice, false, "&_lpChoice" + fl.getID(), retElement);
+				}else{
+					TMLActionState incAction=new TMLActionState("#"+ fl.getID() + "\\lpIncAc",null);
+					incAction.setAction(fl.getIncrement());
+					makeCommands(incAction, false, "&_lpChoice" + fl.getID(), null);
+					makeCommands(lpChoice, false, "&_lpIncAc" + fl.getID(), retElement);
+				}
+				if (fl.getInit().isEmpty()){
+					return "&_lpChoice" + fl.getID();
+				}else{
+					TMLActionState initAction=new TMLActionState("lpInitAc",null);
+					initAction.setAction(fl.getInit());
+					return makeCommands(initAction, false, "&_lpChoice" + fl.getID(), null);
+				}
+			}
+		
+		} else if (currElem instanceof TMLReadChannel){
+			if (debug) TraceManager.addDev("Checking Read\n");
+			cmdName= "_read" + currElem.getID();
+			hcode+="TMLReadCommand " + cmdName + SCCR;
+			TMLReadChannel rCommand=(TMLReadChannel)currElem;
+			if (isIntValue(rCommand.getNbOfSamples()))
+				//initCommand+= "," + cmdName + "("+currElem.getID()+",this,0," + rCommand.getChannel(0).getExtendedName() + "," + rCommand.getChannel(0).getSize() + "*" + rCommand.getNbOfSamples() + ")"+CR;
+				initCommand+= "," + cmdName + "("+currElem.getID()+",this,0," + rCommand.getChannel(0).getExtendedName() + "," + getFormattedLiveVarStr(currElem) + "," +  rCommand.getNbOfSamples() + ")"+CR;
+
+			else
+				//initCommand+= "," + cmdName + "("+currElem.getID()+",this," + makeCommandLenFunc(cmdName, rCommand.getChannel(0).getSize() + "*(" + rCommand.getNbOfSamples()+")",null) + "," + rCommand.getChannel(0).getExtendedName() + ")"+CR;
+				initCommand+= "," + cmdName + "("+currElem.getID()+",this," + makeCommandLenFunc(cmdName, rCommand.getNbOfSamples(),null) + "," + rCommand.getChannel(0).getExtendedName() + "," + getFormattedLiveVarStr(currElem) + ")"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLWriteChannel){
+			String channels;
+			TMLWriteChannel wCommand=(TMLWriteChannel)currElem;
+			if (wCommand.getNbOfChannels()>1){
+				if (ChannelMappedOnSameHW(wCommand)){
+					if (debug) TraceManager.addDev("Checking WriteMult with multicast\n");
+					cmdName= "_mwrite" + currElem.getID();
+					hcode+="TMLWriteMultCommand " + cmdName + SCCR;
+					channels="array("+wCommand.getNbOfChannels();
+					for(int i=0; i<wCommand.getNbOfChannels(); i++){
+						channels+="," + wCommand.getChannel(i).getExtendedName();
+					}
+					channels+=")," + wCommand.getNbOfChannels();
+				}else{
+					if (debug) TraceManager.addDev("Checking WriteMult with unicast\n");
+					TMLWriteChannel prevWrite = null, firstWrite=null;
+					for(int i=0; i<wCommand.getNbOfChannels(); i++){
+						TMLWriteChannel newWrite =  new TMLWriteChannel("WriteMult",null);
+						if(i==0) firstWrite=newWrite;
+						newWrite.addChannel(wCommand.getChannel(i));
+						newWrite.setNbOfSamples(wCommand.getNbOfSamples());
+						if (prevWrite!=null) prevWrite.addNext(newWrite);
+						prevWrite=newWrite;
+					}
+					prevWrite.addNext(wCommand.getNextElement(0));
+					return makeCommands(firstWrite, false, retElement,null);
+				}
+			}else{
+				cmdName= "_write" + currElem.getID();
+				hcode+="TMLWriteCommand " + cmdName + SCCR;
+				channels=wCommand.getChannel(0).getExtendedName();
+			}
+			if (isIntValue(wCommand.getNbOfSamples()))
+				initCommand+= "," + cmdName + "("+currElem.getID()+",this,0," + channels + "," +  getFormattedLiveVarStr(currElem) + "," + wCommand.getNbOfSamples() + ")" +CR;
+			else
+				initCommand+= "," + cmdName + "("+currElem.getID()+",this," + makeCommandLenFunc(cmdName, wCommand.getNbOfSamples(), null) + "," + channels + "," + getFormattedLiveVarStr(currElem) + ")"+CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLSendEvent){
+			if (debug) TraceManager.addDev("Checking Send\n");
+			TMLSendEvent sendEvt=(TMLSendEvent)currElem;
+			cmdName= "_send" + currElem.getID();
+			hcode+="TMLSendCommand " + cmdName + SCCR;
+			handleParameters(currElem, cmdName, false, getFormattedLiveVarStr(currElem));
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;
+			
+		} else if (currElem instanceof TMLSendRequest){
+			if (debug) TraceManager.addDev("Checking Request\n");
+			TMLSendRequest sendReq=(TMLSendRequest)currElem;
+			cmdName= "_request" + currElem.getID();
+			hcode+="TMLRequestCommand " + cmdName + SCCR;
+			handleParameters(currElem, cmdName, false, getFormattedLiveVarStr(currElem));
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;	
+	
+		} else if (currElem instanceof TMLWaitEvent){
+			if (debug) TraceManager.addDev("Checking Wait\n");
+			TMLWaitEvent waitEvt = (TMLWaitEvent)currElem;
+			cmdName= "_wait" + currElem.getID();
+			hcode+="TMLWaitCommand " + cmdName + SCCR;
+			handleParameters(currElem, cmdName, true, getFormattedLiveVarStr(currElem));
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR;
+		
+		} else if (currElem instanceof TMLNotifiedEvent){
+			if (debug) TraceManager.addDev("Checking Notified\n");
+			cmdName= "_notified" + currElem.getID();
+			hcode+="TMLNotifiedCommand " + cmdName + SCCR;
+			initCommand+= "," + cmdName + "("+currElem.getID()+",this," + ((TMLNotifiedEvent)currElem).getEvent().getExtendedName() + ",&" + ((TMLNotifiedEvent)currElem).getVariable() +",\"" + ((TMLNotifiedEvent)currElem).getVariable() + "\"," + getFormattedLiveVarStr(currElem) + ")" + CR;
+			nextCommand= cmdName + ".setNextCommand(array(1,(TMLCommand*)" + makeCommands(currElem.getNextElement(0),false,retElement,null) + "))"+ SCCR; 
+		
+		} else if (currElem instanceof TMLSequence){
+			TMLSequence tmlseq = (TMLSequence)currElem;
+			if (debug) TraceManager.addDev("Checking Sequence with "+ tmlseq.getNbNext()+ " elements.");
+			if (tmlseq.getNbNext() == 0) {
+                		return retElement;
+            		} else {
+                		if (tmlseq.getNbNext() == 1) {
+                    			return makeCommands(currElem.getNextElement(0), false,retElement,null);
+                		} else {			
+					String nextBranch;
+					tmlseq.sortNexts();
+					if (debug) TraceManager.addDev("Checking Sequence branch "+ (tmlseq.getNbNext()-1));
+					nextBranch= makeCommands(currElem.getNextElement(currElem.getNbNext() - 1),false,retElement,null);
+					for(int i=currElem.getNbNext() - 2; i>=0; i--) {
+						if (debug) TraceManager.addDev("Checking Sequence branch "+ i);
+						nextBranch=makeCommands(currElem.getNextElement(i),false,nextBranch,null);
+					}
+                    			return nextBranch;
+                		}
+            		}
+		
+		} else if (currElem instanceof TMLChoice){
+			String elemName=currElem.getName(), idString;
+			if (elemName.charAt(0)=='#'){
+				int pos=elemName.indexOf('\\');
+				idString=elemName.substring(1,pos);
+				//TraceManager.addDev(elemName + "***" + pos + "***" + idString + "***"+ elemName.length());
+				cmdName="_" + elemName.substring(pos+1) + idString;
+			}else{
+				cmdName= "_choice" + currElem.getID();
+				idString=String.valueOf(currElem.getID());
+			}
+			TMLChoice choice = (TMLChoice)currElem;
+			String code = "", nextCommandTemp="", stopCmdToAdd="";
+			int noOfGuards=0;
+			if (debug) TraceManager.addDev("Checking Choice\n");
+			if (choice.getNbGuard() !=0 ) {
+				//int indexElseG = choice.getElseGuard(), indexAfterG = choice.getAfterGuard();
+				int noNonDetGuards = choice.nbOfNonDeterministicGuard();
+				int noStochGuards = choice.nbOfStochasticGuard();
+				if (noNonDetGuards>0){ //Non-Deterministic choice
+					code+= "oMin=0;\n";
+					code+= "oMax=" + (noNonDetGuards-1) + SCCR;
+					//code += "rnd__0 = myrand(0, "+ noNonDetGuards + ")" + SCCR;
+					code += "return myrand(0, "+ (noNonDetGuards-1) + ")" + SCCR;
+					for(int i=0; i<noNonDetGuards; i++) {
+						//code += "if (rnd__0 < " + Math.floor(100/noNonDetGuards)*(i+1) + ") return " + i + SCCR;
+						nextCommandTemp+= ",(TMLCommand*)" + makeCommands(choice.getNextElement(i), false, retElement,null);
+					}
+					noOfGuards = noNonDetGuards;
+					//code+= "return " + (noNonDetGuards-1) + SCCR;
+				}else if(noStochGuards>0){ //Stochastic choice
+					code+= "oMin=0;\n";
+					code+= "oMax=" + (noStochGuards-1) + SCCR;
+					code += "rnd__0 = myrand(0, 99)" + SCCR;
+					String composedGuard="";
+					for(int i=0; i<choice.getNbGuard(); i++) {
+						if (choice.isStochasticGuard(i)) {
+							if (composedGuard.isEmpty()) {
+								composedGuard = formatGuard(choice.getStochasticGuard(i));
+							} else {
+								composedGuard = composedGuard + "+" + formatGuard(choice.getStochasticGuard(i));
+							}
+							code += "if (rnd__0 < (" + composedGuard + ")) return " + noOfGuards + SCCR;
+							nextCommandTemp+= ",(TMLCommand*)" + makeCommands(choice.getNextElement(i), false, retElement,null);
+							noOfGuards++;
+						}
+					}
+					
+				}else{
+					int indElseGuard = choice.getElseGuard(), newIndElseGuard=-1;
+					code+= "unsigned int oC=0;\n";
+					code+= "oMin=-1;\n";
+					code+= "oMax=0;\n";
+					for(int i=0; i<choice.getNbGuard(); i++) {
+						if (!(choice.isNonDeterministicGuard(i) || choice.isStochasticGuard(i))){
+							if (i==indElseGuard){
+								newIndElseGuard=noOfGuards;
+								if (retElseElement!=null)
+									nextCommandTemp+= ",(TMLCommand*)" +makeCommands(choice.getNextElement(indElseGuard), false, retElseElement,null);
+								else
+									nextCommandTemp+= ",(TMLCommand*)" + makeCommands(choice.getNextElement(indElseGuard), false, retElement,null);
+								
+							}else{
+								code += "if "+ formatAction(formatGuard(choice.getGuard(i))) + "{\noC++;\n";
+								code += "oMax += " + (1 << noOfGuards) + SCCR + "\n}\n";
+								nextCommandTemp += ",(TMLCommand*)" + makeCommands(choice.getNextElement(i), false, retElement,null);
+							}
+							noOfGuards++;
+						}
+					}
+					//if (newIndElseGuard!=-1){
+					if (newIndElseGuard==-1){
+						newIndElseGuard= noOfGuards;
+						stopCmdToAdd = ",(TMLCommand*)&_stop" + idString;
+						noOfGuards++;
+						hcode+="TMLStopCommand " + "_stop" + idString + SCCR;
+						initCommand+= ", _stop" + idString + "(" + idString + ",this)" + CR;
+					}
+					code += "if (oMax==0){\n oMax=" + (1 << newIndElseGuard) + SCCR;
+					//code += "oC=1;\n}\n";
+					code += "return " + newIndElseGuard + ";\n}\n";
+					//}
+					code += "return getEnabledBranchNo(myrand(1,oC), oMax);\n";
+				}	
+				//nextCommand= cmdName + ".setNextCommand(array(" + noOfGuards + nextCommandTemp + "))" + SCCR;
+				nextCommand= cmdName + ".setNextCommand(array(" + noOfGuards + nextCommandTemp + stopCmdToAdd+ "))" + SCCR;
+			}
+			//if (choice.nbOfNonDeterministicGuard()==0 &&  choice.nbOfStochasticGuard()==0) 
+			//	hcode+="TMLChoiceCommand " + cmdName + SCCR;
+			//else
+			hcode+="TMLRandomChoiceCommand " + cmdName + SCCR;
+			initCommand+= "," + cmdName + "("+ idString +",this,(RangeFuncPointer)&" + reference + "::" + cmdName + "_func," + noOfGuards + "," + getFormattedLiveVarStr(currElem) + ")"+CR;
+			functions+="unsigned int "+ reference + "::" + cmdName + "_func(ParamType& oMin, ParamType& oMax){" + CR + code +CR+ "}" + CR2;
+			functionSig+="unsigned int " + cmdName + "_func(ParamType& oMin, ParamType& oMax)" + SCCR;
+					
+		} else if (currElem instanceof TMLSelectEvt){
+			TMLEvent evt;
+			//Integer nbevt=0;
+			int nbevt=0;
+			String evtList="",paramList="";
+			if (debug) TraceManager.addDev("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();
+					if (evt.getNbOfParams()==0) {
+						paramList+=",(ParamFuncPointer)0";
+					}else{
+
+						//functionSig+="Parameter<ParamType>* " + cmdName + "_func_" + i + "(Parameter<ParamType>* ioParam)" + SCCR;
+						//functions+="Parameter<ParamType>* " + reference + "::" + cmdName +  "_func_" + i + "(Parameter<ParamType>* ioParam){" + CR;
+						functionSig+="Parameter* " + cmdName + "_func_" + i + "(Parameter* ioParam)" + SCCR;
+						functions+="Parameter* " + reference + "::" + cmdName +  "_func_" + i + "(Parameter* ioParam){" + CR;
+
+						paramList+=",(ParamFuncPointer)&" + reference + "::" + cmdName + "_func_" + i + CR;
+						functions += "ioParam->getP(&" + ((TMLSelectEvt)currElem).getParam(i,0);
+						for(int j=1; j<evt.getNbOfParams(); j++) {
+							functions+= ", &" + ((TMLSelectEvt)currElem).getParam(i,j);
+						}
+						functions+=");\nreturn 0;\n}\n\n"; 
+					}
+					nextCommand+= ",(TMLCommand*)" + makeCommands(currElem.getNextElement(i), true, retElement,null); 
+				}
+			}
+			hcode+="TMLSelectCommand " + cmdName + SCCR;
+			initCommand+= "," + cmdName + "("+currElem.getID()+",this,array("+ nbevt + evtList + "),"+ nbevt + "," + getFormattedLiveVarStr(currElem) + ",array("+ nbevt + paramList + "))"+CR;
+			nextCommand=cmdName + ".setNextCommand(array(" + nbevt + nextCommand + "))" + SCCR;
+		
+		} else {
+			TraceManager.addDev("Operator: " + currElem + " of class " + currElem.getClass().getName() +  " is not managed in the current version of this C++ code generator.");
+		}
+		chaining+=nextCommand; 
+		return (cmdName.equals("0") || cmdName.charAt(0)=='&')? cmdName : "&"+cmdName;
+	}
+	
+	private String formatGuard(String guard){
+		guard = Conversion.replaceAllChar(guard, '[', "(");
+		guard = Conversion.replaceAllChar(guard, ']', ")");
+		return guard;
+	}
+	
+	public static String formatAction(String action){
+		action = action.replaceAll("not\\s","!");
+		action = action.replaceAll("not\\(","!(");
+		action = action.replaceAll("\\sand\\s","&&");
+		action = action.replaceAll("\\sand\\(","&&(");
+		action = action.replaceAll("\\)and\\s",")&&");
+		action = action.replaceAll("\\)and\\(",")&&(");
+		action = action.replaceAll("\\sor\\s","||");
+		action = action.replaceAll("\\sor\\(","||(");
+		action = action.replaceAll("\\)or\\s",")||");
+		action = action.replaceAll("\\)or\\(",")||(");
+		//action = action.replaceAll("[\\s(]or[\\s)]","||");
+		return action;
+	}
+
+	private boolean ChannelMappedOnSameHW(TMLWriteChannel writeCmd){
+		LinkedList<HwCommunicationNode> commNodeRefList = tmlmapping.findNodesForElement(writeCmd.getChannel(0));
+		for(int i=1; i<writeCmd.getNbOfChannels(); i++){
+			LinkedList<HwCommunicationNode> commNodeCmpList = tmlmapping.findNodesForElement(writeCmd.getChannel(i));
+			if (commNodeCmpList.size()!=commNodeRefList.size()) return false;
+			Iterator it = commNodeCmpList.iterator(); 
+			for(HwCommunicationNode cmnode: commNodeRefList) {
+				if (it.next()!=cmnode) return false;
+			}			
+		}
+		return true;
+	}
+	
+	
+	private String makeCommandLenFunc(String cmdName, String lowerLimit, String upperLimit){
+		if (upperLimit==null)
+			functions+="TMLLength "+ reference + "::" + cmdName + "_func(){\nreturn (TMLLength)(" + modifyString(lowerLimit) + ");\n}" + CR2;
+		else
+			functions+="TMLLength "+ reference + "::" + cmdName + "_func(){\nreturn (TMLLength)myrand(" + lowerLimit + "," + modifyString(upperLimit) + ");\n}" + CR2;
+		functionSig+="TMLLength " + cmdName + "_func()" + SCCR;
+		return "(LengthFuncPointer)&" + reference + "::" + cmdName + "_func";
+	}
+
+	private String makeCommandRangeFunc(String cmdName, String lowerLimit, String upperLimit){
+		functions+="unsigned int "+ reference + "::" + cmdName + "_func(ParamType& oMin, ParamType& oMax){\n oMin=" + modifyString(lowerLimit) + ";\noMax=" + modifyString(upperLimit) + SCCR + "return myrand(oMin, oMax)" + SCCR;
+		functions+= "}" + CR2;
+		functionSig+="unsigned int " + cmdName + "_func(ParamType & oMin, ParamType& oMax)" + SCCR;
+		return "(RangeFuncPointer)&" + reference + "::" + cmdName + "_func";
+	}
+
+	private boolean isIntValue(String input){  
+		try{  
+			Integer.parseInt(input); 
+			return true;  
+		}catch(Exception e){  
+			return false;
+		}  
+	}
+
+	private void handleParameters(TMLActivityElement currElem, String cmdName, boolean wait, String liveVarString){
+		String concatParams="", channelName="";
+		String[] paramArray=null;
+		//boolean areStatic=true;
+		int nbOfParams=0;
+		String address=(wait)? "&":"";
+		if (currElem instanceof TMLActivityElementEvent){
+			nbOfParams=((TMLActivityElementEvent)currElem).getNbOfParams();
+			paramArray = new String[nbOfParams];
+			for (int i=0; i< nbOfParams; i++){
+				paramArray[i]=((TMLActivityElementEvent)currElem).getParam(i);
+			}
+			channelName = ((TMLActivityElementEvent)currElem).getEvent().getExtendedName();
+		}
+		else if (currElem instanceof TMLSendRequest){
+			nbOfParams=((TMLSendRequest)currElem).getNbOfParams();
+			paramArray = new String[nbOfParams];
+			for (int i=0; i< nbOfParams; i++){
+				paramArray[i]=((TMLSendRequest)currElem).getParam(i);
+			}
+			channelName = ((TMLSendRequest)currElem).getRequest().getExtendedName();
+		}
+		if (nbOfParams==0){
+			initCommand+= "," + cmdName + "("+ currElem.getID() +",this," + channelName + ",0," + liveVarString +")"+CR;
+		}else{
+			for(int i=0; i<nbOfParams; i++){
+				//if(areStatic && !isIntValue(paramArray[i])) areStatic=false;
+				if (i>0) concatParams+=",";
+				//concatParams+=",";
+				if (paramArray[i]==null || paramArray[i].isEmpty()) concatParams+="0"; else concatParams+= address + paramArray[i];
+			}
+			//if (areStatic){
+				//initCommand+= "," + cmdName + "("+ currElem.getID() +",this," + channelName + ",0," + liveVarString + ",Parameter<ParamType>(" + nbOfParams + "," + concatParams + "))"+CR;
+				//initCommand+= "," + cmdName + "("+ currElem.getID() +",this," + channelName + ",0," + liveVarString + ",new SizedParameter<ParamType," + nbOfParams + ">(" + concatParams + "))"+CR;
+			//}else{
+			initCommand+= "," + cmdName + "("+ currElem.getID() +",this," + channelName + ",(ParamFuncPointer)&" + reference + "::" + cmdName + "_func,"+ liveVarString + ")" + CR;
+			//functionSig+="Parameter<ParamType>* " + cmdName + "_func(Parameter<ParamType>* ioParam)" + SCCR;
+			//functions+="Parameter<ParamType>* " + reference + "::" + cmdName +  "_func(Parameter<ParamType>* ioParam){" + CR;
+			functionSig+="Parameter* " + cmdName + "_func(Parameter* ioParam)" + SCCR;
+			functions+="Parameter* " + reference + "::" + cmdName +  "_func(Parameter* ioParam){" + CR;
+			if (wait)
+				functions += "ioParam->getP(" + concatParams + ")" + SCCR + "return 0" + SCCR;
+			else
+				//functions += "return new Parameter<ParamType>(" + nbOfParams + "," + concatParams + ")" + SCCR;
+				functions += "return new SizedParameter<ParamType," + nbOfParams + ">(" + concatParams + ")" + SCCR;
+			functions+="}\n\n"; 
+			//}
+		}
+	}
+
+	private void makeEndClassH() {
+		hcode += "};" + CR + "#endif" + CR;
+	}
+
+	
+	private String makeAttributesCode() {
+		String code = "";
+		int i;
+		for(TMLAttribute att: task.getAttributes()) {
+			//if (!att.name.endsWith("__req")){ //NEW
+				if (att.hasInitialValue())
+					code += ","+ att.name + "(" + att.initialValue + ")"+CR;
+				else
+					code += ","+ att.name + "(0)"+CR;
+			//}
+		}
+		//code += ",arg1__req(0)"+CR;
+		//code += ",arg2__req(0)"+CR;
+		//code += ",arg3__req(0)"+CR;
+		return code;
+	}
+	
+	private String makeAttributesDeclaration() {
+		String code = "";
+		int i;
+		for(TMLAttribute att: task.getAttributes()) { 
+			//if (!att.name.endsWith("__req")){  //NEW
+				code += "ParamType " + att.name;
+				code += ";\n";
+			//}
+		}
+		//code += "ParamType arg1__req" + SCCR;
+		//code += "ParamType arg2__req" + SCCR;
+		//code += "ParamType arg3__req" + SCCR;
+		code += "ParamType rnd__0" + SCCR;
+		code += "TMLChannel* _channels[" + (channels.size() + events.size() + (task.isRequested()? 1: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;
+	}
+	
+	public String getIdentifierNameByID(int id){
+		//Channels, Events, Requests, Variables, Choice, Random
+		id=Math.abs(id);
+		for (TMLChannel channel: channels){
+			if (channel.getID()==id) return channel.getName();
+		}
+		for (TMLEvent event: events){
+			if (event.getID()==id) return event.getName();
+			/*int param = Integer.MAX_VALUE - 3 * event.getID() - id + 1;
+			if (param>0 && param<4)  return event.getName() + "_param" + param;*/
+		}
+		for (TMLRequest request: requests){
+			if (request.getID()==id) return request.getName();
+			/*int param = Integer.MAX_VALUE - 3 * request.getID() - id +1;
+			if (param>0 && param<4)  return request.getName() + "_param!" + param;*/
+		}
+		for(TMLAttribute att: task.getAttributes()){
+			if (att.getID()==id) return reference + ":" + att.getName();
+		}
+		for(int i=0; i<task.getActivityDiagram().nElements();i++)
+			if (task.getActivityDiagram().get(i).getID()==id) return reference + ":Command " + id;
+		return null;
+	}
+	
+	public void determineCheckpoints(int[] aStatistics){
+		_analysis.determineCheckpoints(aStatistics);
+	}
+	
+	public StaticAnalysis getAnalysis(){
+		return _analysis;
+	}
+}
diff --git a/src/tmltranslator/tomappingsystemc3/MergedCmdStr.java b/src/tmltranslator/tomappingsystemc3/MergedCmdStr.java
new file mode 100644
index 0000000000000000000000000000000000000000..da73b4465035bb436c40f1f87f385f243cfa4422
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/MergedCmdStr.java
@@ -0,0 +1,17 @@
+package tmltranslator.tomappingsystemc3;
+
+public class MergedCmdStr{
+	String nextCmd;
+	String funcs;
+	String srcCmd;
+	int num;
+	MergedCmdStr(String iNextCommand, String iSrcCmd, int iNum){
+		nextCmd=iNextCommand;
+		srcCmd=iSrcCmd;
+		num=iNum;
+		funcs="";
+	}
+	MergedCmdStr(String iNextCommand, String iSrcCmd){
+		this(iNextCommand, iSrcCmd, 0);
+	}
+}
diff --git a/src/tmltranslator/tomappingsystemc3/README.txt b/src/tmltranslator/tomappingsystemc3/README.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f756f9bacdbd28d1e15833bec086bfc65155fa73
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/README.txt
@@ -0,0 +1,5 @@
+Date:			30/05/2014
+Author:		Andrea ENRICI
+Contact:	andrea.enrici@telecom-paristech.fr
+
+Third version of the TML-to-C++ code generator. It adds Communication Patterns to the simulator version n.2
diff --git a/src/tmltranslator/tomappingsystemc3/StaticAnalysis.java b/src/tmltranslator/tomappingsystemc3/StaticAnalysis.java
new file mode 100644
index 0000000000000000000000000000000000000000..99d5746dbce1690ba6a1058c94c90e3f6ad9fce3
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/StaticAnalysis.java
@@ -0,0 +1,535 @@
+package tmltranslator.tomappingsystemc3;
+
+import java.util.*;
+import tmltranslator.*;
+import java.util.regex.*;
+
+import myutil.*;
+//import java.util.HashSet;
+
+public class StaticAnalysis{
+	private ArrayList<LiveVariableNode> liveNodes= new ArrayList<LiveVariableNode>();
+	private final static Pattern _varPattern = Pattern.compile("[\\w&&\\D]+[\\w]*");
+	private TMLTask _task;
+	private ArrayList<TMLChannel> _channels;
+	private ArrayList<TMLEvent> _events;
+	private ArrayList<TMLRequest> _requests;
+	
+	private int _nextDefID=0;
+	private int[][] _varToDefs=null;
+	private int _bytesForDefs;
+	private int _bytesForVars;
+	private LiveVariableNode[] _defLookup=null;
+	private Set<Integer> _depChannels;
+
+	public StaticAnalysis(TMLTask iTask, ArrayList<TMLChannel>iChannels, ArrayList<TMLEvent> iEvents, ArrayList<TMLRequest> iRequests, Set<Integer> iDepChannels){
+		_task = iTask;
+		_channels=iChannels;
+		_events=iEvents;
+		_requests=iRequests;
+		_depChannels = iDepChannels;
+	}
+	
+	public int getNextDefID(){
+		return _nextDefID++;
+	}
+	
+	/*public int getNbOfDefs(){
+		return _nextDefID;
+	}*/
+	
+	public int getBytesForDefs(){
+		return _bytesForDefs;
+	}
+	
+	public int[][] getDefsForVar(){
+		return _varToDefs;
+	}
+	
+	public LiveVariableNode[] getDefLookUp(){
+		return _defLookup;
+	}
+
+	public void addDepChannel(int iID){
+		//TraceManager.addDev("Add Dependent Channel: " + iID);
+		_depChannels.add(iID);
+	}
+
+	public boolean isChannelDep(int iID){
+		//TraceManager.addDev("Check if Channel dep: " + iID + " answer: "  + _depChannels.contains(iID));
+		return _depChannels.contains(iID);
+	}
+
+	private int getVarSeqNoByName(String attName){
+		attName=attName.trim();
+		int aSeq=0;
+		for(TMLAttribute att: _task.getAttributes()) {
+			if (att.name.equals(attName)) return aSeq;
+			aSeq++;
+		}
+		return -1;
+	}
+
+	private int[] parseExprToVariableMap(String iExpr, int[] iMap){
+		//byte[] aResMap;
+		int[] aResMap;
+		if(iMap==null)
+			aResMap=new int[_bytesForVars];
+		else
+			aResMap=iMap;
+		if(!(iExpr==null || iExpr.isEmpty())){
+			//TraceManager.addDev("Examine expression: " + iExpr);
+			Matcher matcher = _varPattern.matcher(iExpr);
+			//System.out.print("Found tokens: ");
+			while (matcher.find()){
+				String token = iExpr.substring(matcher.start(), matcher.end());
+				//System.out.print(token + ", ");
+				int aVarSeqNo = getVarSeqNoByName(token);
+				if (aVarSeqNo>=0) aResMap[aVarSeqNo >>> 5] |= 1 << (aVarSeqNo & 0x1F);
+			}
+			//TraceManager.addDev();
+			//TraceManager.addDev("Byte sequence: ");
+		}
+		/*for(int i=0; i<_bytesForVars; i++)
+			System.out.print(((int)aResMap[i]) + ", ");
+		TraceManager.addDev();*/
+		return aResMap;		
+	}
+
+	private int[] parseChannelToVariableMap(TMLChannel iChannel, int[] iMap){
+		int[] aResMap;
+		if(iMap==null)
+			aResMap=new int[_bytesForVars];
+		else
+			aResMap=iMap;
+		int anIndex = _task.getAttributes().size() + _channels.indexOf(iChannel);
+		aResMap[anIndex >>> 5] |= 1 << (anIndex & 0x1F);
+		return aResMap;	
+	}
+
+	private int[] parseEventToVariableMap(TMLEvent iEvent){
+		int[] aResMap = new int[_bytesForVars];
+		int anIndex = _task.getAttributes().size() + _channels.size() + _events.indexOf(iEvent);
+		aResMap[anIndex >>> 5] |= 1 << (anIndex & 0x1F);
+		return aResMap;
+	}
+	
+	/*public String makeLiveVarEvalFunc(){
+		String anEvalFunc="";
+		//= "unsigned long getStateHash(const char* iLiveVarList) const{\n";
+		int aSeq=0;
+		for(TMLAttribute att: _task.getAttributes()) {
+			anEvalFunc += "if (iLiveVarList[" + (aSeq >>> 3) + "] && " + (1 << (aSeq & 0x7)) + "!=0) iHash->addValue(" + att.getName() + ");\n";
+			aSeq++;
+		}
+		for(TMLChannel ch: _channels) {
+			anEvalFunc += "if (iLiveVarList[" + (aSeq >>> 3) + "] && " + (1 << (aSeq & 0x7)) + "!=0) " + ch.getExtendedName() + "->getStateHash(iHash);\n";
+			aSeq++;
+		}
+		for(TMLEvent evt: _events) {
+			anEvalFunc += "if (iLiveVarList[" + (aSeq >>> 3) + "] && " + (1 << (aSeq & 0x7)) + "!=0) " + evt.getExtendedName() + "->getStateHash(iHash);\n";
+			aSeq++;
+		}
+		if (_task.isRequested())
+			anEvalFunc += "if (iLiveVarList[" + (aSeq >>> 3) + "] && " + (1 << (aSeq & 0x7)) + "!=0) requestChannel->getStateHash(iHash);\n"; 
+		//anEvalFunc += "}\n\n";
+		return anEvalFunc;
+	}*/
+
+	private void printLiveVarNode(LiveVariableNode iNode){
+		int aSeq=0;
+		for(TMLAttribute att: _task.getAttributes()) {
+			if ((iNode.getOutVars()[aSeq >>> 5] & (1 << (aSeq & 0x1F)))!=0)
+				TraceManager.addDev(att.getName() + ": significant");
+			aSeq++;
+		}
+		for(TMLChannel ch: _channels) {
+			if ((iNode.getOutVars()[aSeq >>> 5] & (1 << (aSeq & 0x1F)))!=0)
+				TraceManager.addDev(ch.getName() + ": significant");
+			aSeq++;
+		}
+		for(TMLEvent evt: _events) {
+			if ((iNode.getOutVars()[aSeq >>> 5] & (1 << (aSeq & 0x1F)))!=0)
+				TraceManager.addDev(evt.getName() + ": significant");
+			aSeq++;
+		}
+		if (_task.isRequested() && (iNode.getOutVars()[aSeq >>> 5] & (1 << (aSeq & 0x1F)))!=0)
+			TraceManager.addDev("reqChannel: significant");
+	}
+
+	public String printVariables(int[] iVariables){
+		String aResult="";
+		int aSeq=0;
+		for(TMLAttribute att: _task.getAttributes()) {
+			if ((iVariables[aSeq >>> 5] & (1 << (aSeq & 0x1F)))!=0)
+				aResult+= att.getName() + ",";
+			aSeq++;
+		}
+		for(TMLChannel ch: _channels) {
+			if ((iVariables[aSeq >>> 5] & (1 << (aSeq & 0x1F)))!=0)
+				aResult+= ch.getName() + ",";
+			aSeq++;
+		}
+		for(TMLEvent evt: _events) {
+			if ((iVariables[aSeq >>> 5] & (1 << (aSeq & 0x1F)))!=0)
+				aResult+= evt.getName() + ",";
+			aSeq++;
+		}
+		if (_task.isRequested() && (iVariables[aSeq >>> 5] & (1 << (aSeq & 0x1F)))!=0)
+			aResult += "reqCh";
+		return aResult;
+	}
+
+	public LiveVariableNode startAnalysis(){
+		int aNbOfLiveElements = _task.getAttributes().size() + _channels.size() + _events.size();
+		//int aNumberOfBytes=0;
+		//LiveVariableNode.reset();
+		liveNodes = new ArrayList<LiveVariableNode>();
+		if (_task.isRequested()) aNbOfLiveElements++;		
+		_bytesForVars = aNbOfLiveElements >>> 5;
+		if ((aNbOfLiveElements & 0x1F)!=0) _bytesForVars++;
+		LiveVariableNode aStartNode=null, aLastNode=null;
+		//_depChannels.clear();
+		for(TMLAttribute att: _task.getAttributes()) {
+			if (att.hasInitialValue())
+				aStartNode = new LiveVariableNode(this, new int[_bytesForVars], parseExprToVariableMap(att.name, null), null, null,
+			false, att.name, att.initialValue);			
+			else
+				aStartNode = new LiveVariableNode(this, new int[_bytesForVars], parseExprToVariableMap(att.name, null), null, null,
+			false, att.name, "0");
+			liveNodes.add(aStartNode);
+			aStartNode.setNodeInfo("init " + att.getName());
+			if (aLastNode!=null) aLastNode.setSuccessor(aStartNode);
+			aLastNode=aStartNode;
+		}
+		if (_task.isRequested()){
+			int[] aReqVars = parseExprToVariableMap("arg1__req", null);
+			for (int i=2; i<=_task.getRequest().getNbOfParams(); i++){
+				parseExprToVariableMap("arg" + i + "__req", aReqVars);
+			}
+			//parseExprToVariableMap("arg2__req", aReqVars);
+			//parseExprToVariableMap("arg3__req", aReqVars);
+			int[] aReqChannelVar = new int[_bytesForVars];
+			aReqChannelVar[_bytesForVars-1] = 1 << ((aNbOfLiveElements-1) & 0x1F);
+			aStartNode = new LiveVariableNode(this, aReqChannelVar, aReqVars, null, null, true);
+			for(TMLRequest aReq: _requests)
+				if (aReq.getNbOfParams()>0){ aStartNode.setVarDepSource(true); break;}
+			liveNodes.add(aStartNode);
+			aStartNode.setNodeInfo("rec req");
+			aStartNode.setSuccessor(buildLiveAnalysisTree(_task.getActivityDiagram().getFirst(), aStartNode, null));
+		}else{
+			aStartNode = buildLiveAnalysisTree(_task.getActivityDiagram().getFirst(), null, null);
+		}
+		if (aLastNode!=null) aLastNode.setSuccessor(aStartNode);
+		boolean aChange;
+		int aConstChange;
+		do{
+			//TraceManager.addDev("******************* one analysis round");
+			_nextDefID=0;
+			for(LiveVariableNode aLiveNode: liveNodes)
+				aLiveNode.liveVariableInit();
+			do{
+				aChange=false;
+				for(LiveVariableNode aLiveNode: liveNodes)
+					aChange |= aLiveNode.liveVariableAnalysis();
+			}while(aChange);
+			_bytesForDefs = _nextDefID >>> 5;
+			if ((_nextDefID & 0x1F)!=0 || _nextDefID==0) _bytesForDefs++;
+			_varToDefs = new int[aNbOfLiveElements][_bytesForDefs];
+			_defLookup = new LiveVariableNode[_nextDefID];
+			for(LiveVariableNode aLiveNode: liveNodes){
+				aLiveNode.prepareReachingDefinitions();
+			}
+			do{
+				aChange=false;
+				for(LiveVariableNode aLiveNode: liveNodes)
+					aChange |= aLiveNode.determineKilledSets();
+			}while(aChange);
+			for(LiveVariableNode aLiveNode: liveNodes){
+				//aLiveNode.printKillEntries();
+				aLiveNode.reachingDefinitionsInit();
+			}
+			do{
+				aChange=false;
+				for(LiveVariableNode aLiveNode: liveNodes)
+					aChange |= aLiveNode.reachingDefinitionAnalysis();
+			}while(aChange);
+			aConstChange=0;
+			do{
+				aConstChange &= 1;
+				for(LiveVariableNode aLiveNode: liveNodes)
+					aConstChange |= aLiveNode.determineIfConstant();
+			}while(aConstChange>1);
+
+			/*TraceManager.addDev("-----------------new step------------");
+			for(LiveVariableNode aLiveNode: liveNodes){
+				aLiveNode.printReachingEntries();
+				printLiveVarNode(aLiveNode);
+			
+			}*/
+
+			 
+		}while(aConstChange>0);
+		
+		do{
+			aChange=false;
+			for(LiveVariableNode aLiveNode: liveNodes)
+				aChange |= aLiveNode.infectionAnalysis();
+		}while(aChange);
+		return aStartNode;
+	}
+
+	public void determineCheckpoints(int[] iStatistics){
+		TraceManager.addDev("*** Static Analysis for task " + _task.getName());
+		for(LiveVariableNode aLiveNode: liveNodes)
+			aLiveNode.determineCheckpoints(new CheckpointInfo());
+		//TraceManager.addDev("Create array size " + (_bytesForVars << 5));
+		int[] aStatistics = new int[_bytesForVars << 5];
+		int aNbOfCheckPoints=0, aNbOfCandidates=0;
+		for(LiveVariableNode aLiveNode: liveNodes){
+			int aStatResult = aLiveNode.varStatistics(aStatistics);
+			if((aStatResult & 1)!=0){
+				//aLiveNode.printReachingEntries();
+				//printLiveVarNode(aLiveNode);
+				aNbOfCandidates++;
+				if((aStatResult & 2)!=0) aNbOfCheckPoints++;
+			}
+		}
+		if (aNbOfCandidates==0)
+			TraceManager.addDev("No checkpoint candidates");
+		else{
+			TraceManager.addDev("a: " + _task.getAttributes().size() + " c: " + _channels.size() + " e: " + _events.size());
+			int aNbOfLiveElements = _task.getAttributes().size() + _channels.size() + _events.size();
+			int nbOfVars=0, nbOfChannels=0, nbOfEvents=0;
+			for(int i=0; i<_task.getAttributes().size(); i++)
+				nbOfVars += aStatistics[i];
+			TraceManager.addDev("Variables Checks: " + nbOfVars + "  Candidates: " + (_task.getAttributes().size() * aNbOfCandidates));
+			if (!_task.getAttributes().isEmpty()){
+				iStatistics[0] += _task.getAttributes().size() * aNbOfCandidates;
+				int aVarGain = (100 * (_task.getAttributes().size() * aNbOfCandidates - nbOfVars) / (_task.getAttributes().size() * aNbOfCandidates));
+				iStatistics[1] += _task.getAttributes().size() * aNbOfCandidates - nbOfVars;
+				TraceManager.addDev("Variables Gain: " + aVarGain);
+			}
+			for(int i=0; i<_channels.size(); i++)
+				nbOfChannels += aStatistics[i + _task.getAttributes().size()];
+			TraceManager.addDev("Channel Checks: " + nbOfChannels + "  Candidates: " + (_channels.size() * aNbOfCandidates));
+			if (!_channels.isEmpty()){
+				iStatistics[2] += _channels.size() * aNbOfCandidates;
+				int aChGain = (100 * (_channels.size() * aNbOfCandidates - nbOfChannels) / (_channels.size() * aNbOfCandidates));
+				iStatistics[3] += _channels.size() * aNbOfCandidates - nbOfChannels;
+				TraceManager.addDev("Channels Gain: " + aChGain);
+			}
+			for(int i=0; i<_events.size(); i++)
+				nbOfEvents += aStatistics[i + _task.getAttributes().size() + _channels.size()];
+			TraceManager.addDev("Event Checks: " + nbOfEvents + "  Candidates: " + (_events.size() * aNbOfCandidates));
+			if (!_events.isEmpty()){
+				iStatistics[4] += _events.size() * aNbOfCandidates;
+				int aEvtGain = (100 * (_events.size() * aNbOfCandidates - nbOfEvents) / (_events.size() * aNbOfCandidates));
+				iStatistics[5] += _events.size() * aNbOfCandidates - nbOfEvents;
+				TraceManager.addDev("Events Gain: " + aEvtGain);
+			}
+			//TraceManager.addDev("Request Checks: " + aStatistics[_task.getAttributes().size() + _channels.size() + _events.size()] + "  Candidates: " + aNbOfCandidates);
+			//if (_task.isRequested()) TraceManager.addDev("Saved Requests: " + (100* (aNbOfCandidates - aStatistics[_task.getAttributes().size() + _channels.size() + _events.size()]) / aNbOfCandidates));
+			//TraceManager.addDev("Checkpoints: " + aNbOfCheckPoints + "  Candidates: " + aNbOfCandidates);
+			iStatistics[6] += aNbOfCandidates;
+			iStatistics[7] += aNbOfCandidates - aNbOfCheckPoints;
+			TraceManager.addDev("Checkpoint Gain: " + (100 * (aNbOfCandidates - aNbOfCheckPoints) / aNbOfCandidates));
+		}	
+		TraceManager.addDev("*** End of Static Analysis for task " + _task.getName());
+	}
+
+	private LiveVariableNode buildLiveAnalysisTree(TMLActivityElement iCurrElem, LiveVariableNode iReturnNode, LiveVariableNode iSuperiorNode){
+		LiveVariableNode aResNode=null;
+		
+		if (iCurrElem instanceof TMLStartState) {
+			iCurrElem.getNextElement(0);
+		}
+
+		if (iCurrElem==null || iCurrElem instanceof TMLStopState){
+			return iReturnNode;
+
+		} else if (iCurrElem instanceof TMLActionState){
+			String[] aTokens=MappedSystemCTask.formatAction(((TMLActionState)iCurrElem).getAction()).split("=",2);
+			if (aTokens.length<2) aTokens=new String[2];
+			aResNode = new LiveVariableNode(this, parseExprToVariableMap(aTokens[1], null), parseExprToVariableMap(aTokens[0], null), iCurrElem, iSuperiorNode, 
+			false, aTokens[0], aTokens[1]);	
+
+ 		} else if (iCurrElem instanceof TMLRandom){
+			TMLRandom aRndCmd=(TMLRandom)iCurrElem;
+			int[] aRandomVars = parseExprToVariableMap(aRndCmd.getMinValue(), null);
+			parseExprToVariableMap(aRndCmd.getMaxValue(), aRandomVars);
+			aResNode = new LiveVariableNode(this, aRandomVars, parseExprToVariableMap(aRndCmd.getVariable(), null), iCurrElem, iSuperiorNode, true);
+			aResNode.setVarDepSource(true);
+
+		} else if (iCurrElem instanceof TMLDelay){
+			int[] aDelayVars = parseExprToVariableMap(((TMLDelay)iCurrElem).getMinDelay(), null);
+			parseExprToVariableMap(((TMLDelay)iCurrElem).getMaxDelay(), aDelayVars);
+			aResNode = new LiveVariableNode(this, aDelayVars, new int[_bytesForVars], iCurrElem, iSuperiorNode);
+
+		} else if (iCurrElem instanceof TMLExecI){
+			aResNode = new LiveVariableNode(this, parseExprToVariableMap(((TMLExecI)iCurrElem).getAction(), null), new int[_bytesForVars], iCurrElem, iSuperiorNode);
+
+		} else if (iCurrElem instanceof TMLExecC){
+			aResNode = new LiveVariableNode(this, parseExprToVariableMap(((TMLExecC)iCurrElem).getAction(), null), new int[_bytesForVars], iCurrElem, iSuperiorNode);
+
+		} else if (iCurrElem instanceof TMLExecIInterval){
+			int[] aExecVars = parseExprToVariableMap(((TMLExecIInterval)iCurrElem).getMinDelay(), null);
+			parseExprToVariableMap(((TMLExecIInterval)iCurrElem).getMaxDelay(), aExecVars);
+			aResNode = new LiveVariableNode(this, aExecVars, new int[_bytesForVars], iCurrElem, iSuperiorNode);
+
+		} else if (iCurrElem instanceof TMLExecCInterval){
+			int[] aExecVars = parseExprToVariableMap(((TMLExecCInterval)iCurrElem).getMinDelay(), null);
+			parseExprToVariableMap(((TMLExecCInterval)iCurrElem).getMaxDelay(), aExecVars);
+			aResNode = new LiveVariableNode(this, aExecVars, new int[_bytesForVars],iCurrElem, iSuperiorNode);
+
+		} else if (iCurrElem instanceof TMLForLoop){
+			TMLForLoop aLoop = (TMLForLoop) iCurrElem;
+			String[] aTokens=aLoop.getInit().split("=",2);
+			if (aTokens.length<2) aTokens=new String[2];
+			LiveVariableNode aInit = new LiveVariableNode(this, parseExprToVariableMap(aTokens[1], null), parseExprToVariableMap(aTokens[0], null), iCurrElem, iSuperiorNode, false, aTokens[0], aTokens[1]);
+			aInit.setNodeInfo("init");
+			LiveVariableNode aCondition = new LiveVariableNode(this, parseExprToVariableMap(aLoop.getCondition(), null), new int[_bytesForVars], iCurrElem, iSuperiorNode);
+			aCondition.setNodeInfo("cond");
+			aTokens=aLoop.getIncrement().split("=",2);
+			if (aTokens.length<2) aTokens=new String[2];
+			LiveVariableNode anIncrement = new LiveVariableNode(this, parseExprToVariableMap(aTokens[1], null), parseExprToVariableMap(aTokens[0],null), iCurrElem, aCondition, false, aTokens[0], aTokens[1]);
+			anIncrement.setNodeInfo("inc");
+			aInit.setSuccessor(aCondition);
+			anIncrement.setSuccessor(aCondition);
+			aCondition.setSuccessor(buildLiveAnalysisTree(iCurrElem.getNextElement(0), anIncrement, aCondition));   //in loop
+			aCondition.setSuccessor(buildLiveAnalysisTree(iCurrElem.getNextElement(1), iReturnNode, aCondition));   //outside loop
+			liveNodes.add(aInit);
+			liveNodes.add(aCondition);
+			liveNodes.add(anIncrement);
+			return aInit;
+
+		} else if (iCurrElem instanceof TMLReadChannel){
+			TMLReadChannel aReadCmd = (TMLReadChannel)iCurrElem;
+			int[] aReadVars=null;
+			if (aReadCmd.getChannel(0).getType()==TMLChannel.BRBW || aReadCmd.getChannel(0).getType()==TMLChannel.BRNBW)
+				aReadVars = parseChannelToVariableMap(aReadCmd.getChannel(0), null);
+			else
+				aReadVars = new int[_bytesForVars];
+			parseExprToVariableMap(aReadCmd.getNbOfSamples(), aReadVars);
+			aResNode = new LiveVariableNode(this, aReadVars, new int[_bytesForVars], iCurrElem, iSuperiorNode);
+
+		} else if (iCurrElem instanceof TMLWriteChannel){
+			TMLWriteChannel aWriteCmd=(TMLWriteChannel)iCurrElem;
+			int[] aWriteVars = new int[_bytesForVars];
+			for(int i=0; i< aWriteCmd.getNbOfChannels(); i++){
+				if (aWriteCmd.getChannel(i).getType()==TMLChannel.BRBW) parseChannelToVariableMap(aWriteCmd.getChannel(i), aWriteVars);
+			}
+			parseExprToVariableMap(aWriteCmd.getNbOfSamples(), aWriteVars);
+			aResNode = new LiveVariableNode(this, aWriteVars, new int[_bytesForVars], iCurrElem, iSuperiorNode);
+			
+		} else if (iCurrElem instanceof TMLSendEvent){
+			TMLSendEvent aSendCmd=(TMLSendEvent)iCurrElem;
+			int[] aSendVars=null;
+			//if (aSendCmd.getEvent().isBlocking())
+				aSendVars = parseEventToVariableMap(aSendCmd.getEvent());
+			//else
+				//aSendVars = new int[_bytesForVars];
+			//parseExprToVariableMap(aSendCmd.getParam(0), aSendVars);
+			//parseExprToVariableMap(aSendCmd.getParam(1), aSendVars);
+			//parseExprToVariableMap(aSendCmd.getParam(2), aSendVars);
+			for (int i=0; i<aSendCmd.getNbOfParams(); i++){	
+				parseExprToVariableMap(aSendCmd.getParam(i), aSendVars);
+			}
+			aResNode = new LiveVariableNode(this, aSendVars, new int[_bytesForVars], iCurrElem, iSuperiorNode);
+		
+		} else if (iCurrElem instanceof TMLSendRequest){
+			TMLSendRequest aSendReqCmd=(TMLSendRequest)iCurrElem;
+			int[] aSendReqVars = parseExprToVariableMap(aSendReqCmd.getParam(0), null);
+			//parseExprToVariableMap(aSendReqCmd.getParam(1), aSendReqVars);
+			//parseExprToVariableMap(aSendReqCmd.getParam(2), aSendReqVars);
+			for (int i=1; i<aSendReqCmd.getNbOfParams(); i++){
+				parseExprToVariableMap(aSendReqCmd.getParam(i), aSendReqVars);
+			}
+			aResNode = new LiveVariableNode(this, aSendReqVars, new int[_bytesForVars], iCurrElem, iSuperiorNode);
+
+		} else if (iCurrElem instanceof TMLWaitEvent){
+			TMLWaitEvent aWaitCmd=(TMLWaitEvent)iCurrElem;
+			int[] aWaitVars = parseExprToVariableMap(aWaitCmd.getParam(0), null);
+			//parseExprToVariableMap(aWaitCmd.getParam(1), aWaitVars);
+			//parseExprToVariableMap(aWaitCmd.getParam(2), aWaitVars);
+			for (int i=1; i<aWaitCmd.getNbOfParams(); i++){
+				parseExprToVariableMap(aWaitCmd.getParam(i), aWaitVars);
+			}
+			aResNode = new LiveVariableNode(this, parseEventToVariableMap(aWaitCmd.getEvent()), aWaitVars, iCurrElem, iSuperiorNode, true);
+			if (aWaitCmd.getEvent().getNbOfParams()>0) aResNode.setVarDepSource(true);
+			
+		} else if (iCurrElem instanceof TMLNotifiedEvent){
+			aResNode = new LiveVariableNode(this, parseEventToVariableMap(((TMLNotifiedEvent)iCurrElem).getEvent()), parseExprToVariableMap(((TMLNotifiedEvent)iCurrElem).getVariable(), null), iCurrElem, iSuperiorNode, true);
+			aResNode.setVarDepSource(true);
+
+		} else if (iCurrElem instanceof TMLSequence){
+			((TMLSequence)iCurrElem).sortNexts();
+			for(int i=((TMLSequence)iCurrElem).getNbNext()-1; i>=0; i--){
+				iReturnNode = buildLiveAnalysisTree(iCurrElem.getNextElement(i), iReturnNode, iSuperiorNode);
+			}
+			return iReturnNode;
+			 
+		} else if (iCurrElem instanceof TMLChoice){
+			int[] aChoiceVars = new int[_bytesForVars];
+			TMLChoice aChoiceCmd = (TMLChoice)iCurrElem;
+			for(int i=0; i<aChoiceCmd.getNbGuard(); i++)
+				if (!(aChoiceCmd.isNonDeterministicGuard(i) || aChoiceCmd.isStochasticGuard(i) || aChoiceCmd.getElseGuard()==i)) parseExprToVariableMap(aChoiceCmd.getGuard(i), aChoiceVars);
+			aResNode = new LiveVariableNode(this, aChoiceVars, new int[_bytesForVars], iCurrElem, iSuperiorNode);
+			if (aChoiceCmd.nbOfNonDeterministicGuard()>0 || aChoiceCmd.nbOfStochasticGuard()>0) aResNode.setInfected(true);
+			//TraceManager.addDev("checl:  " + aChoiceCmd.nbOfNonDeterministicGuard() + " ** "+ aChoiceCmd.nbOfStochasticGuard());
+			for(int i=0; i<aChoiceCmd.getNbNext(); i++)
+				aResNode.setSuccessor(buildLiveAnalysisTree(iCurrElem.getNextElement(i), iReturnNode, aResNode));
+			liveNodes.add(aResNode);
+			return aResNode;
+		
+		} else if (iCurrElem instanceof TMLSelectEvt){
+			aResNode = new LiveVariableNode(this, new int[_bytesForVars], new int[_bytesForVars], iCurrElem, iSuperiorNode);
+			if (iCurrElem.getNbNext()>1) aResNode.setInfected(true);
+			for(int i=0; i<iCurrElem.getNbNext(); i++){
+				aResNode.setSuccessor(buildLiveAnalysisTree(iCurrElem.getNextElement(i), iReturnNode, aResNode));
+			}
+			liveNodes.add(aResNode);
+			return aResNode;
+		}
+
+		LiveVariableNode aSucc = buildLiveAnalysisTree(iCurrElem.getNextElement(0), iReturnNode, iSuperiorNode);
+		if (aResNode==null || aResNode.isEmptyNode()){
+			aResNode=aSucc;
+		}else{
+			liveNodes.add(aResNode);
+			aResNode.setSuccessor(aSucc);
+		}
+		return aResNode;
+	}
+
+	public LiveVariableNode getLiveVarNodeByCommand(TMLActivityElement iCmd){
+		for(LiveVariableNode aLiveNode: liveNodes)
+			if (aLiveNode.getLinkedElement()==iCmd) return aLiveNode;
+		return null;
+	}
+	
+	public void getCommandsImpactingVar(String iVarName, HashSet<Integer> oList){
+		//int[] aVarMap=new int[_bytesForVars];
+		int aVarSeqNo = getVarSeqNoByName(iVarName);
+		if (aVarSeqNo>=0){
+			//aVarMap[aVarSeqNo >>> 5] |= 1 << (aVarSeqNo & 0x1F);
+			int intPos = aVarSeqNo >>> 5;
+			int bitMask = 1 << (aVarSeqNo & 0x1F);
+			for(LiveVariableNode aLiveNode: liveNodes){
+				/*int[] aDefVars = aLiveNode.getDefVars();
+				boolean aMatchFound=false;
+				for (int i=0; i<aDefVars.length && !aMatchFound;i++){
+					aMatchFound |= ((aDefVars[i] & aVarMap[i]) !=0);
+				}*/
+				
+				//if (aMatchFound && aLiveNode.getLinkedElement()!=null) oList.add(aLiveNode.getLinkedElement().getID());
+				if ((aLiveNode.getInitialDefVars()[intPos] & bitMask)!=0){
+					if (aLiveNode.getLinkedElement()!=null) oList.add(aLiveNode.getLinkedElement().getID());
+					else TraceManager.addDev("No linked elem");
+				}else
+					TraceManager.addDev("Bit for var not set");
+			}
+		}else
+			TraceManager.addDev("Variable " + iVarName + " not found in getCommandsImpactingVar");
+	}
+}
diff --git a/src/tmltranslator/tomappingsystemc3/SystemCEBRDD.java b/src/tmltranslator/tomappingsystemc3/SystemCEBRDD.java
new file mode 100644
index 0000000000000000000000000000000000000000..bdc0d9e410d2d28338266d0549ffbf9accf3f767
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/SystemCEBRDD.java
@@ -0,0 +1,719 @@
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
+ *
+ * ludovic.apvrille AT telecom-paristech.fr
+ * andrea.enrici 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.
+ *
+ * /**
+ * Class SystemCEBRDD
+ * Creation: 30/05/2014
+ * @version 1.0 30/05/2014
+ * @author Andrea Enrici, Daniel Knorreck
+ * @see
+ */
+
+package tmltranslator.tomappingsystemc3;
+
+import java.util.*;
+
+import tmltranslator.*;
+import myutil.*;
+import req.ebrdd.*;
+
+
+public class SystemCEBRDD {
+	private EBRDD ebrdd;
+ 	private String reference, cppcode, hcode, initCommand, functions, functionSig, chaining, firstCommand, idsMergedCmds;
+	private String ETclasses;
+	//, ETdeclare, ETInit;
+	private boolean debug;
+	TMLModeling tmlmodeling;
+	TMLMapping tmlmapping;
+	
+	private final static String [] events = {"transexecuted", "cmdentered", "cmdstarted", "cmdexecuted", "cmdfinished", "taskstarted", "taskfinished", "readtrans", "writetrans", "simstarted", "simfinished"};
+	private final static String DOTH = ".h";
+	private final static String DOTCPP = ".cpp";
+	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 SystemCEBRDD(EBRDD _ebrdd, TMLModeling _tmlmodeling, TMLMapping _tmlmapping) {
+        	ebrdd = _ebrdd;
+        	reference = ebrdd.getName();
+		cppcode = "";
+		hcode = "";
+		initCommand="";
+		functions="";
+		chaining="";
+		firstCommand="";
+		functionSig="";
+		idsMergedCmds="";
+		ETclasses="";
+		tmlmodeling=_tmlmodeling;
+		tmlmapping=_tmlmapping;
+    	}
+	
+	public void saveInFiles(String path) throws FileException {	
+		FileUtils.saveFile(path + reference + DOTH, getHCode());
+		FileUtils.saveFile(path + reference + DOTCPP, getCPPCode());
+	}
+	
+	public EBRDD getEBRDD() {
+		return ebrdd;
+	}
+    
+	public void generateSystemC(boolean _debug) {
+        	debug = _debug;
+		//basicHCode();
+		basicCPPCode();
+		makeClassCode();
+    	}
+	
+	public void print() {
+		TraceManager.addDev("EBRDD: " + reference + DOTH + hcode);
+		TraceManager.addDev("EBRDD: " + 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 <definitions.h>\n#include <EBRDD.h>\n#include <ERC.h>\n#include <ESO.h>\n#include <ERB.h>\n#include <EBRDDChoiceCommand.h>\n#include <EBRDDActionCommand.h>\n#include <EBRDDStopCommand.h>\n\n";
+		return code;
+	}
+	
+	// CPP Code
+	private void basicCPPCode() {
+		cppcode += "#include <" + reference + DOTH + ">" + CR2;
+	}
+	
+	private void makeClassCode(){
+		makeHeaderClassH();
+		makeEndClassH();
+		cppcode+=reference+ "::" + makeConstructorSignature()+":EBRDD(iID, iName)"+ CR + makeAttributesCode();
+		cppcode+=initCommand + CR + "{" + CR; 
+		cppcode+= "//generate EBRDD variable look-up table"+ CR;
+		for(int i=0; i< ebrdd.getNbOfAttributes(); i++) {
+			String attName = ebrdd.getAttributeByIndex(i).getName();
+			cppcode += "_varLookUpName[\"" + attName + "\"]=&" + attName +SCCR;
+			//cppcode += "_varLookUpID[" + ebrdd.getAttributeByIndex(i).getID() + "]=&" + attName +SCCR;
+		}		
+		cppcode+=CR + "//command chaining"+ CR;
+		cppcode+= chaining + "_currCommand=" + firstCommand + SCCR + "_firstCommand=" + firstCommand + SCCR + CR; 
+		cppcode+="//IDs of merged commands\n" + idsMergedCmds + CR;
+		cppcode+="}"+ CR2 + functions; // + makeDestructor();
+		hcode = Conversion.indentString(hcode, 4);
+		cppcode = Conversion.indentString(cppcode, 4);
+	}
+	
+	private String makeDestructor(){
+		String dest=reference + "::~" + reference + "(){" + CR;
+		return dest+"}"+CR;
+	}
+
+	private String makeConstructorSignature(){
+		return reference + "(unsigned int iID, std::string iName)";
+	}
+
+	private void makeHeaderClassH() {
+		String hcodeBegin="";
+		// Common dec
+		hcodeBegin = "class " + reference + ": public EBRDD {" + CR;
+		hcodeBegin += "private:" + CR;
+		// Attributes
+		hcodeBegin += "// Attributes" + CR;
+		firstCommand=makeCommands(ebrdd.getStartState(), "0", null, null);
+		hcode = basicHCode() + ETclasses + "\n\n" + hcodeBegin + makeAttributesDeclaration() + CR + hcode;
+		// public dec
+		hcode += CR + functionSig + CR + "public:" + CR;
+		// Simulation
+		hcode += makeConstructorSignature() + SCCR;
+		makeSerializableFuncs();
+	}
+
+	private void makeSerializableFuncs(){
+		hcode += "virtual std::istream& readObject(std::istream& i_stream_var)" + SCCR;
+		hcode += "virtual std::ostream& writeObject(std::ostream& i_stream_var)" + SCCR;
+		functions+= "std::istream& " + reference + "::readObject(std::istream& i_stream_var){\nEBRDD::readObject(i_stream_var);\n"; 
+		for(int i=0; i< ebrdd.getNbOfAttributes(); i++){
+			String attName = ebrdd.getAttributeByIndex(i).getName();
+			functions += "READ_STREAM(i_stream_var," + attName + ")" + SCCR;
+			functions += "std::cout << \"Read: Variable " + attName + " \" << " + attName +  " << std::endl" + SCCR;
+		}
+		functions+= "return i_stream_var;\n}\n\n";
+		functions+= "std::ostream& " + reference + "::writeObject(std::ostream& i_stream_var){\nEBRDD::writeObject(i_stream_var);\n";
+		for(int i=0; i< ebrdd.getNbOfAttributes(); i++){
+			String attName = ebrdd.getAttributeByIndex(i).getName();
+			functions += "WRITE_STREAM(i_stream_var," + attName + ")" + SCCR;
+			functions += "std::cout << \"Write: Variable " + attName + " \" << " + attName +  " << std::endl" + SCCR;
+		}
+		functions+= "return i_stream_var;\n}\n\n";
+		hcode += "void reset()" + SCCR;
+		functions+= "void "+reference + "::reset(){\nEBRDD::reset();\n";
+		for(int i=0; i< ebrdd.getNbOfAttributes(); i++){
+			EBRDDAttribute att = ebrdd.getAttributeByIndex(i);
+			functions += att.getName() + "=";
+			if (att.hasInitialValue())
+				functions += att.getInitialValue() + SCCR;
+			else
+				functions += "0" + SCCR;
+		}
+		functions+= "}\n\n";
+	}
+
+	private String makeCommands(EBRDDComponent currElem, String retElement, MergedCmdStr nextCommandCont, String retElseElement){
+		String nextCommand="",cmdName="";
+
+		if (currElem==null){
+			if (debug) TraceManager.addDev("Checking null\n");
+			return retElement;
+		}
+		
+		if (debug) TraceManager.addDev("Checking " + currElem.getName() + CR);
+
+		if (currElem instanceof EBRDDStart) {
+			if (debug) TraceManager.addDev("Checking Start\n");
+			return makeCommands(currElem.getNextElement(0), retElement,nextCommandCont,null);
+		
+		} else if (currElem instanceof EBRDDStop){
+			if (debug) TraceManager.addDev("Checking Stop\n");
+			if (retElement.equals("0")){
+				cmdName= "_stop" + currElem.getID();
+				hcode+="EBRDDStopCommand " + cmdName + SCCR;
+				initCommand+= "," + cmdName + "(" + currElem.getID() + ",this)" + CR;
+			}else
+				return retElement;
+		
+		} else if (currElem instanceof EBRDDActionState){
+			String action;
+			if (debug) TraceManager.addDev("Checking Action\n");
+			action = ((EBRDDActionState)currElem).getAction();
+			String elemName=currElem.getName(), idString;
+			if (elemName.charAt(0)=='#'){
+				int pos=elemName.indexOf('\\');
+				idString=elemName.substring(1,pos);
+				TraceManager.addDev(elemName + "***" + pos + "***" + idString + "***"+ elemName.length());
+				cmdName="_" + elemName.substring(pos+1) + idString;
+			}else{
+				cmdName= "_action" + currElem.getID();
+				idString=String.valueOf(currElem.getID());
+			}
+			if (nextCommandCont==null){
+				hcode+="EBRDDChoiceCommand " + cmdName + SCCR;
+				MergedCmdStr nextCommandCollection = new MergedCmdStr("", cmdName);
+				initCommand+= "," + cmdName + "("+ idString + ",this,(EBRDDFuncPointer)&" + reference + "::" + cmdName + "_func)"+CR;
+				String MKResult = makeCommands(currElem.getNextElement(0), retElement, nextCommandCollection, null);
+				if(nextCommandCollection.num==0){
+					nextCommand= cmdName + ".setNextCommand(array(1,(EBRDDCommand*)" + MKResult + "));\n";
+				}else{	
+					nextCommand= cmdName + ".setNextCommand(array(" + nextCommandCollection.num + nextCommandCollection.nextCmd + "));\n";
+				}
+				functions+="unsigned int "+ reference + "::" + cmdName + "_func(){\n" + modifyString(addSemicolonIfNecessary(action)) + CR + nextCommandCollection.funcs;
+				if (nextCommandCollection.num==0) functions+="return 0"+ SCCR;
+				functions+= "}" + CR2;
+				functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
+			}else{
+				idsMergedCmds += "_commandHash[" + idString + "]=&" + nextCommandCont.srcCmd + SCCR;
+				nextCommandCont.funcs += modifyString(addSemicolonIfNecessary(action)) + CR;
+				return makeCommands(currElem.getNextElement(0), retElement, nextCommandCont, null);
+			}
+		
+		} else if (currElem instanceof EBRDDLoop){
+			if (debug) TraceManager.addDev("Checking Loop\n");
+			EBRDDLoop fl = (EBRDDLoop)currElem;
+			//EBRDDActionState initAction=new EBRDDActionState("lpInitAc",null);
+			//initAction.setAction(fl.getInit());
+			EBRDDActionState initAction=null;
+			if (!fl.getInit().isEmpty()){
+				initAction = new EBRDDActionState("lpInitAc",null);
+				initAction.setAction(fl.getInit());
+			}
+			//EBRDDActionState incAction=new EBRDDActionState("#"+ fl.getID() + "\\lpIncAc",null);
+			//incAction.setAction(fl.getIncrement());
+			EBRDDActionState incAction=null;
+			if (!fl.getIncrement().isEmpty()){
+				incAction=new EBRDDActionState("#"+ fl.getID() + "\\lpIncAc",null);
+				incAction.setAction(fl.getIncrement());
+			}
+			EBRDDChoice lpChoice=new EBRDDChoice("#"+ fl.getID() + "\\lpChoice",null);
+			lpChoice.addGuard("[ " + fl.getCondition() + " ]");
+			lpChoice.addGuard("[ else ]");
+			//incAction.addNext(lpChoice);
+			lpChoice.addNext(fl.getNextElement(0));  //inside loop
+			lpChoice.addNext(fl.getNextElement(1));  //after loop           cmdName= "_choice" + currElem.getID();
+			if (incAction==null){
+				makeCommands(lpChoice, "&_lpChoice" + fl.getID(), null, retElement);
+			}else{
+				makeCommands(incAction, "&_lpChoice" + fl.getID(), null, null);
+				makeCommands(lpChoice, "&_lpIncAc" + fl.getID(), null, retElement);
+			}
+			return makeCommands(initAction, "&_lpChoice" + fl.getID(), nextCommandCont, null);
+	
+
+		} else if (currElem instanceof EBRDDSequence){
+			EBRDDSequence tmlseq = (EBRDDSequence)currElem;
+			if (debug) TraceManager.addDev("Checking Sequence with "+ tmlseq.getNbNext()+ " elements.");
+			if (tmlseq.getNbNext() == 0) {
+				//if (lastSequence!=null) return makeCommands(lastSequence, retElement,nextCommandCont,functionCont,null);
+                		return retElement;
+            		} else {
+                		if (tmlseq.getNbNext() == 1) {
+                    			return makeCommands(currElem.getNextElement(0), retElement, nextCommandCont, null);
+                		} else {			
+					String nextBranch;
+					tmlseq.sortNexts();
+					if (debug) TraceManager.addDev("Checking Sequence branch "+ (tmlseq.getNbNext()-1));
+					nextBranch= makeCommands(currElem.getNextElement(currElem.getNbNext() - 1), retElement, null, null);
+					for(int i=currElem.getNbNext() - 2; i>=0; i--) {
+						if (debug) TraceManager.addDev("Checking Sequence branch "+ i);
+						nextBranch=makeCommands(currElem.getNextElement(i), nextBranch, null, null);
+					}
+                    			return nextBranch;
+                		}
+            		}
+		} else if(currElem instanceof EBRDDERC){
+			cmdName= "_erc" + currElem.getID();
+			strwrap ETDeclare=new strwrap(), ETInit=new strwrap();
+			LinkedList<String> erbFuncs = new LinkedList<String>();
+			hcode+= cmdName + "_class " + cmdName + SCCR;
+			//ERC declaration!!!
+			buildET(((EBRDDERC)currElem).getRoot(), "this", 0, ETDeclare, ETInit, erbFuncs);
+			initCommand+= ", " + cmdName + "("+ currElem.getID() + ", this";
+			for (String erbFunc : erbFuncs){
+				initCommand+= ", (EBRDDFuncPointer)&" + reference + "::" + erbFunc;
+			}
+			initCommand+=")\n";
+			nextCommand= cmdName + ".setNextCommand(array(1,(EBRDDCommand*)" + makeCommands(currElem.getNextElement(0),retElement,null,null) + "))"+ SCCR;
+			ETclasses+="class " + cmdName + "_class: public ERC{\nprivate:\n" + ETDeclare.str;
+			ETclasses+="public:\n" + cmdName + "_class(unsigned int iID, EBRDD* iEBRDD";
+			for (String erbFunc : erbFuncs){
+			 	ETclasses+= ", EBRDDFuncPointer " + erbFunc;
+			} 
+			ETclasses+= "): ERC(iID, iEBRDD)\n";
+			ETclasses+=ETInit.str + "{}\n};\n\n";
+		
+		} else if (currElem instanceof EBRDDChoice){
+			int returnIndex=0;
+			String elemName=currElem.getName(), idString;
+			if (elemName.charAt(0)=='#'){
+				int pos=elemName.indexOf('\\');
+				idString=elemName.substring(1,pos);
+				TraceManager.addDev(elemName + "***" + pos + "***" + idString + "***"+ elemName.length());
+				cmdName="_" + elemName.substring(pos+1) + idString;
+			}else{
+				cmdName= "_choice" + currElem.getID();
+				idString=String.valueOf(currElem.getID());
+			}
+			EBRDDChoice choice = (EBRDDChoice)currElem;
+			String code = "", nextCommandTemp="", MCResult="";
+			if (debug) TraceManager.addDev("Checking Choice\n");
+			if (choice.getNbGuard() !=0 ) {
+				String guardS = "",code2;
+				int index1 = choice.getElseGuard();
+				for(int i=0; i<choice.getNbGuard(); i++) {
+					code2 = choice.getGuard(i);
+					code2 = Conversion.replaceAllChar(code2, '[', "(");
+					code2 = Conversion.replaceAllChar(code2, ']', ")");
+					if (i==0) {
+						code += "if " + code2;
+					} else {
+						code += " else ";
+						if (i != index1) {
+							code += "if " + code2;
+						}
+					}
+					if (nextCommandCont==null){
+						MergedCmdStr nextCommandCollection = new MergedCmdStr("",cmdName, returnIndex);
+						//TraceManager.addDev("Call makeCommands, task: "+reference);
+						//if (nextCommandCollection==null) TraceManager.addDev("Choice: nextCommandCollection==0");
+						if (retElseElement!=null && i==index1)
+							//else case
+							MCResult = makeCommands(currElem.getNextElement(i), retElseElement,nextCommandCollection,null);
+						else
+							MCResult = makeCommands(currElem.getNextElement(i), retElement,nextCommandCollection,null);
+						if (nextCommandCollection.funcs.length() == 0){
+							code += "{\nreturn " + returnIndex + SCCR +"}" + CR;
+							returnIndex++;
+							nextCommandTemp+= ",(EBRDDCommand*)" + MCResult;
+						}else{
+							returnIndex = nextCommandCollection.num;
+							code += "{\n" + nextCommandCollection.funcs + "return " + returnIndex + ";\n}" + CR;
+							returnIndex++;
+							nextCommandTemp+= nextCommandCollection.nextCmd+ ",(EBRDDCommand*)" + MCResult;
+						}
+					}else{
+						idsMergedCmds += "_commandHash[" + currElem.getID() + "]=&" + nextCommandCont.srcCmd + SCCR;
+						//TraceManager.addDev("Choice: Next command!=0 "+ code2);
+						int oldReturnIndex=nextCommandCont.num;
+						nextCommandCont.funcs += code + "{\n";
+						if (retElseElement!=null && i==index1)
+							MCResult = makeCommands(currElem.getNextElement(i), retElseElement, nextCommandCont,null);
+						else
+							MCResult = makeCommands(currElem.getNextElement(i), retElement, nextCommandCont,null);
+						if (oldReturnIndex==nextCommandCont.num){
+							//TraceManager.addDev("RETURN, ccINC NUM "+ nextCommandCont.num);
+							nextCommandCont.funcs+= "return " + nextCommandCont.num + SCCR;
+							nextCommandCont.num++;
+							nextCommandCont.nextCmd += ",(EBRDDCommand*)" + MCResult;
+						}
+						nextCommandCont.funcs+= "}\n";
+						code="";
+					}
+					 
+				}
+				// If there was no else, do a terminate
+				if (nextCommandCont==null){
+					//TraceManager.addDev("Choice: finalization, add new command\n");
+					if (index1 == -1){
+						code += "return " + returnIndex + SCCR;
+						nextCommand= cmdName + ".setNextCommand(array(" + (returnIndex+1) + nextCommandTemp + ",(EBRDDCommand*)0))" + SCCR;
+					}else{
+						nextCommand= cmdName + ".setNextCommand(array(" + returnIndex + nextCommandTemp + "))" + SCCR;
+					}
+					hcode+="EBRDDChoiceCommand " + cmdName + SCCR;
+					initCommand+= "," + cmdName + "("+ idString +",this,(EBRDDFuncPointer)&" + reference + "::" + cmdName + "_func)\n";
+					functions+="unsigned int "+ reference + "::" + cmdName + "_func(){" + CR + code +CR+ "}" + CR2;
+					functionSig+="unsigned int " + cmdName + "_func()" + SCCR;
+				}else{
+					//TraceManager.addDev("Choice: finalization, No new command\n");
+					if (index1 == -1){
+						nextCommandCont.funcs += "return " + nextCommandCont.num + SCCR;
+						nextCommandCont.nextCmd += ",(EBRDDCommand*)0";
+						//TraceManager.addDev("RETURN, ddINC NUM "+ nextCommandCont.num);
+						nextCommandCont.num++;
+					}
+					cmdName=MCResult;
+				}
+			}
+					
+		} else {
+			TraceManager.addDev("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 void makeEndClassH() {
+		hcode += "};" + CR + "#endif" + CR;
+	}
+
+	private int buildET(ERCElement currElem, String ancestor, int newID, strwrap ETDeclare, strwrap ETInit, LinkedList<String> erbFuncs){
+		if (currElem==null) return newID;
+		String negated = (currElem.isNegated())? "true":"false";
+		newID++;
+		if (currElem instanceof ESO){
+			ESO currESO = (ESO)currElem;
+			String oncePerEvent = (currESO.getOncePerEvent())? "true":"false";
+			String esoName="";
+			switch (currESO.getID()){
+			case 0://Conjunction
+				//(NotifyIF* iAncestorNode, bool iNegated, unsigned int iNbOfEvents, TMLTime iTimeOut, bool iOncePerEvent)
+				esoName= "_esoConj" + newID;
+				ETDeclare.str+= "ESOConjunction " + esoName + ";\n";
+				ETInit.str+= "," + esoName + "(" + ancestor + ","+ negated + "," + currESO.getNbOfSons() + "," + currESO.getTimeout() + "," + oncePerEvent + ")\n";
+			break;
+			case 1: //Disjunction
+				//ESODisjunction(NotifyIF* iAncestorNode, bool iNegated, unsigned int iNbOfEvents, TMLTime iTimeOut);
+				esoName= "_esoDisj" + newID;
+				ETDeclare.str+= "ESODisjunction " + esoName + ";\n";
+				ETInit.str+= "," + esoName + "(" + ancestor + ","+ negated + "," + currESO.getNbOfSons() + "," + currESO.getTimeout() + ")\n";
+			break;
+			case 2: //Sequence
+				//ESOSequence(NotifyIF* iAncestorNode, bool iNegated, unsigned int iNbOfEvents, TMLTime iTimeOut);
+				esoName= "_esoSeq" + newID;
+				ETDeclare.str+= "ESOSequence " + esoName + ";\n";
+				ETInit.str+= "," + esoName + "(" + ancestor + ","+ negated + "," + currESO.getNbOfSons() + "," + currESO.getTimeout() + ")\n";
+			break;
+			case 3: //Strict sequence
+			case 4: //Simultaneous
+				//ESOSSequence(NotifyIF* iAncestorNode, bool iNegated, unsigned int iNbOfEvents, TMLTime iTimeOut);
+				esoName= "_esoSSeq" + newID;
+				ETDeclare.str+= "ESOSSequence " + esoName + ";\n";
+				ETInit.str+= "," + esoName + "(" + ancestor + ","+ negated + "," + currESO.getNbOfSons() + "," + currESO.getTimeout() + ")\n";
+			break;
+			case 5: //At least/at most
+				if (currESO.getN()==0){
+					//ESOAtMost(NotifyIF* iAncestorNode, bool iNegated, unsigned int iNbOfEvents, TMLTime iTimeOut, bool iOncePerEvent, unsigned int iN);
+					esoName= "_esoAtMost" + newID;
+					ETDeclare.str+= "ESOAtMost " + esoName + ";\n";
+					ETInit.str+= "," + esoName + "(" + ancestor + ","+ negated + "," + currESO.getNbOfSons() + "," + currESO.getTimeout() + "," + oncePerEvent + ","+ currESO.getM() + ")\n";
+				}else{
+					//ESOAtLeast(NotifyIF* iAncestorNode, bool iNegated, unsigned int iNbOfEvents, TMLTime iTimeOut, bool iOncePerEvent, unsigned int iN);
+					esoName= "_esoAtLeast" + newID;
+					ETDeclare.str+= "ESOAtLeast " + esoName + ";\n";
+					ETInit.str+= "," + esoName + "(" + ancestor + ","+ negated + "," + currESO.getNbOfSons() + "," + currESO.getTimeout() + "," + oncePerEvent + ","+ currESO.getN() + ")\n";	
+				}
+				break;
+			default:
+				//can't handle element
+			}
+			for (int i=0; i<currESO.getNbOfSons(); i++){
+				newID = buildET(currESO.getSon(i), "&" + esoName, newID, ETDeclare, ETInit, erbFuncs);
+			} 
+		}else if(currElem instanceof ERB){
+			//getEvent, getCondition, getAction
+			//ERB(NotifyIF* iAncestorNode, bool iNegated, const std::string& iName, unsigned int iSourceClass, unsigned int iSourceID, unsigned int iEvtID);
+			//String message="myEvent(source1, source2, source3)";
+			ERB currERB = (ERB)currElem;
+			String[] tokens = currERB.getEvent().split("[ \\(\\),]+");
+			System.out.print("Tokens: ");
+			for (int i=0; i< tokens.length; i++){
+				System.out.print(tokens[i]+ ", ");
+			}
+			TraceManager.addDev("");
+			if (tokens.length>1){
+				//eventID, sourceClass, arrayOfSources, numberOfSources
+				String erbName= "_erb" + newID;
+				ETDeclare.str+= "ERB " + erbName + ";\n";
+				idtypewrap source=null;
+				ETInit.str+= ", " + erbName + "(this, " + ancestor + ", "+ negated + ", \"" + erbName + "\", ";
+				int paramIndex=1;
+				String sourceIDs="";
+				int nbOfIDs=0;
+				while(paramIndex<tokens.length){
+					source = getIDType(tokens[paramIndex]);
+					sourceIDs += source.id;
+					paramIndex++;
+					nbOfIDs+=source.nbOfIDs;
+				}
+				ETInit.str += getEventCode(tokens[0]) + ", " + source.type + ", array(" + nbOfIDs;
+				ETInit.str += sourceIDs + "), " + nbOfIDs + ", ";
+				if ((currERB.getCondition().isEmpty() || currERB.getCondition().trim().toLowerCase().equals("true")) && currERB.getAction().isEmpty()){
+					ETInit.str += "0, \"" + currERB.getCondition() + "\")\n";
+				}else{
+					if (ancestor.charAt(0)=='&') ancestor=ancestor.substring(1);
+					 ETInit.str += ancestor + erbName + "_func, \"" + currERB.getCondition() + "\")\n";
+					//ERBFunc.str += ", EBRDDFuncPointer " + ancestor + erbName + "_func";
+					erbFuncs.add(ancestor + erbName + "_func");
+					functionSig += "int " + ancestor + erbName + "_func()" + SCCR;
+					if (currERB.getCondition().trim().toLowerCase().equals("true")){
+						functions+= "int " + reference + "::" + ancestor + erbName + "_func(){\n" + currERB.getAction() + "\nreturn true;\n}\n\n";
+					}else{
+						functions+= "int " + reference + "::" + ancestor + erbName + "_func(){\nif(" + currERB.getCondition() + "){\n" + currERB.getAction();
+						functions+= "\nreturn true;\n}else{\nreturn false;\n}\n}\n\n";
+					}
+				}
+			} 
+		}else{
+			//can't handle element
+		}
+		return newID;
+	}
+
+
+	private idtypewrap getIDType(String nodeName){
+		String lnodeName = nodeName.trim().toLowerCase();
+		if (lnodeName.equals("kernel")) return new idtypewrap(7, ", (unsigned int)0", 1);
+		idtypewrap idtype = new idtypewrap(1,"", 0);
+		if (lnodeName.equals("allcpus")){
+			idtype.type = 0;
+			for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()){
+				if (node instanceof HwCPU){
+					idtype.id +=", (unsigned int)" + node.getID();
+					idtype.nbOfIDs++;
+				}
+			}
+			return idtype;
+		}
+		if (lnodeName.equals("allbuses")){
+			idtype.type = 1;
+			for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()){
+				if (node instanceof HwBus){
+					idtype.id +=", (unsigned int)" + node.getID();
+					idtype.nbOfIDs++;
+				}
+			}
+			return idtype;
+		}
+		if (lnodeName.equals("allbridges")){
+			idtype.type = 3;
+			for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()){
+				if (node instanceof HwBridge){
+					idtype.id +=", (unsigned int)" + node.getID();
+					idtype.nbOfIDs++;
+				}
+			}
+			return idtype;
+		}
+		if (lnodeName.equals("allmems")){
+			idtype.type = 2;
+			for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()){
+				if (node instanceof HwMemory){
+					idtype.id +=", (unsigned int)" + node.getID();
+					idtype.nbOfIDs++;
+				}
+			}
+			return idtype;
+		}
+		if (lnodeName.equals("allhwa")){
+			idtype.type = 6;
+			for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()){
+				if (node instanceof HwA){
+					idtype.id +=", (unsigned int)" + node.getID();
+					idtype.nbOfIDs++;
+				}
+			}
+			return idtype;
+		}
+		if (lnodeName.equals("allchannels")){
+			idtype.type = 4;
+			idtype.nbOfIDs = tmlmodeling.getChannels().size();
+			for(TMLElement elem: tmlmodeling.getChannels()){
+				idtype.id +=", (unsigned int)" + elem.getID();
+			}
+			return idtype;
+		}
+		if (lnodeName.equals("allevents")){
+			idtype.type = 4;
+			idtype.nbOfIDs = tmlmodeling.getEvents().size();
+			for(TMLElement elem: tmlmodeling.getEvents()){
+				idtype.id +=", (unsigned int)" + elem.getID();
+			}
+			return idtype;
+		}
+		if (lnodeName.equals("allrequests")){
+			idtype.type = 4;
+			idtype.nbOfIDs = tmlmodeling.getRequests().size();
+			for(TMLElement elem: tmlmodeling.getRequests()){
+				idtype.id +=", (unsigned int)" + elem.getID();
+			}
+			return idtype;
+		}
+		if (lnodeName.equals("alltasks")){
+			idtype.type = 5;
+			idtype.nbOfIDs = tmlmapping.getMappedTasks().size();
+			for(TMLElement elem: tmlmapping.getMappedTasks()){
+				idtype.id +=", (unsigned int)" + elem.getID();
+			}
+			return idtype;
+		}
+		//allCPUs, allBuses, allBridges, allMemories, allHWAs, allChannels, allEvents, allRequests, allTasks
+		for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()){
+			if (node.getName().equals(nodeName)){
+				if (node instanceof HwCPU){
+					return new idtypewrap(0, ", (unsigned int)" + node.getID(), 1);
+				}else if (node instanceof HwBus){
+					return new idtypewrap(1, ", (unsigned int)" + node.getID(), 1);
+				}else if (node instanceof HwBridge){
+					return new idtypewrap(3, ", (unsigned int)" + node.getID(), 1);
+				}else if (node instanceof HwMemory){
+					return new idtypewrap(2, ", (unsigned int)" + node.getID(), 1);
+				}else if (node instanceof HwA){
+					return new idtypewrap(6, ", (unsigned int)" + node.getID(), 1);
+				}
+			}
+		}
+		String nodeName2 = nodeName;
+		TraceManager.addDev("Name of Element: " + nodeName);
+		for(TMLElement elem: tmlmodeling.getChannels()){
+			if (elem.getName().equals(nodeName2)) return new idtypewrap(4, ", (unsigned int)" + elem.getID(), 1);
+			TraceManager.addDev("Compare to: " + elem.getName());
+		}
+		for(TMLElement elem: tmlmodeling.getEvents()){
+			if (elem.getName().equals(nodeName2)) return new idtypewrap(4, ", (unsigned int)" + elem.getID(), 1);
+		}
+		for(TMLElement elem: tmlmodeling.getRequests()){
+			if (elem.getName().equals(nodeName2)) return new idtypewrap(4, ", (unsigned int)" + elem.getID(), 1);
+		}
+		for(TMLElement elem: tmlmapping.getMappedTasks()){
+			if (elem.getName().equals(nodeName2)) return new idtypewrap(5, ", (unsigned int)" + elem.getID(), 1);
+		}
+		return new idtypewrap(-1,", (unsigned int)1", 1);
+	}
+
+	private int getEventCode(String eventText){
+		eventText = eventText.trim().toLowerCase();
+		for (int i= 0; i < events.length; i++){
+			if (eventText.equals(events[i])) return i;
+		}
+		return -1;
+	}
+
+	private String makeAttributesCode() {
+		String code = "";
+		for(int i=0; i< ebrdd.getNbOfAttributes(); i++){
+			EBRDDAttribute att = ebrdd.getAttributeByIndex(i);
+			if (att.hasInitialValue())
+				code += ","+ att.getName() + "(" + att.getInitialValue() + ")"+CR;
+			else
+				code += ","+ att.getName() + "(0)"+CR;
+		}	
+		return code;
+	}
+	
+	private String makeAttributesDeclaration() {
+		String code = "";
+		for(int i=0; i< ebrdd.getNbOfAttributes(); i++){
+			code += "int " + ebrdd.getAttributeByIndex(i).getName();
+			code += ";\n";
+		}
+		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/tomappingsystemc3/SystemCTEPE.java b/src/tmltranslator/tomappingsystemc3/SystemCTEPE.java
new file mode 100644
index 0000000000000000000000000000000000000000..40307ec5f57c88b57b95a1d358f4b024be77f331
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/SystemCTEPE.java
@@ -0,0 +1,455 @@
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
+
+ludovic.apvrille AT telecom-paristech.fr
+andrea.enrici 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.
+
+/**
+ * Class SystemCTEPE
+ * Creation: 30/05/2014
+ * @version 1.0 30/05/2014
+ * @author Andrea ENRICI, Daniel KNORRECK
+ * @see
+ */
+
+package tmltranslator.tomappingsystemc3;
+
+import java.util.*;
+import tmltranslator.*;
+import myutil.*;
+import tepe.*;
+import java.util.regex.*;
+
+
+public class SystemCTEPE {
+    
+	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 Pattern _varPattern = Pattern.compile("[\\w&&\\D]+[\\w]*");
+	private ArrayList<TEPE> _tepes;
+	private int _nbOfFloatingSig=0,_nbOfStartNodes=0;
+	private String _floatingSigProc="", _floatingSigComp="", _floatingEnaComp="", _connect="", _declare="", _evtRegister="", _code="", _listeners="", _eqFuncs="", _eqFuncDecl="";
+	TML2MappingSystemC _tmltranslator;
+
+	public SystemCTEPE(ArrayList<TEPE> tepes, TML2MappingSystemC tmltranslator){
+		_tepes=tepes;
+		_tmltranslator=tmltranslator;
+	}
+	
+	public void generateTEPEs(){
+		_nbOfFloatingSig=0; _nbOfStartNodes=0;
+		_floatingSigProc=""; _floatingSigComp=""; _floatingEnaComp=""; _connect=""; _declare=""; _evtRegister=""; _listeners=""; _eqFuncs=""; _eqFuncDecl="";	
+		if (!_tepes.isEmpty()){
+			TraceManager.addDev("And the TEPEs are...............");
+			for(TEPE tepe: _tepes) {
+				for(TEPEComponent comp: tepe) {
+					TraceManager.addDev("Component: " + comp.getName());
+					generateTEPEProp(comp,null,null,null);
+				}
+			}
+			_code = "bool aIsId;\n" + _declare;
+			//TEPEFloatingSigListener(ListenerSubject<GeneralListener>* iSimulator, unsigned int inbOfSignals, SignalConstraint** iNotifConstr, NtfSigFuncPointer* iNotifFunc);
+			_code += "TEPEFloatingSigListener* flListener = new TEPEFloatingSigListener(_simulator," + _nbOfFloatingSig + ",";
+			if (_nbOfFloatingSig==0)
+				_code += "0,0";
+			else
+				_code+= "array(" + _nbOfFloatingSig + _floatingSigComp + "),array(" + _nbOfFloatingSig + _floatingSigProc + ")";
+			_code += "," + _nbOfStartNodes + ",array(" + _nbOfStartNodes + _floatingEnaComp + "))" + SCCR;
+			_code += "setTEPEEntryPoint(flListener);\n";
+			//_code += "SignalConstraint* opMapping[] = {0" + _floatingSigComp + "}"+SCCR;
+			//_code += "NtfSigFuncPointer fnMapping[] = {0" + _floatingSigProc + "}" + SCCR;
+			//_code += "PropertyConstraint* startNodes[] ={0" + _floatingEnaComp + "}" + SCCR;
+			_code += _connect;
+			_code += _listeners;
+		}
+	}
+	
+	public void saveFile(String filename) throws FileException{
+		FileUtils.saveFile(filename, _code);
+	}
+	
+	public String getCode(){
+		return _code;
+	}
+	
+	public String getEqFuncs(){
+		return _eqFuncs;
+	}
+	
+	public String getEqFuncDeclaration(){
+		return _eqFuncDecl;
+	}
+	
+	private String getTEPECompName(TEPEComponent currComp){
+		return "_" + Conversion.replaceAllChar(currComp.getName(),' ',"") + currComp.getID();
+	}
+	
+	private String[] getExprIDTskvarStrings(TEPEComponent currComp, String initExpr){
+		String[] resultStr = new String[3];
+		for(int i=0; i<3; i++)
+			resultStr[i]="";
+		LinkedList<String> addTokenList = new LinkedList<String>();
+		ArrayList<String> addTskVarList = new ArrayList<String>();
+		HashSet<Integer> addCmdIDList = new HashSet<Integer>();
+		parseExprToTokenList(initExpr, addTokenList);
+		if (currComp instanceof TEPEAttributeComponent){
+			generateTEPEProp(currComp, addTokenList, addTskVarList, addCmdIDList);
+		}else{
+			for(TEPEComponent linkedComps: currComp.getInAttributes()){
+				generateTEPEProp(linkedComps, addTokenList, addTskVarList, addCmdIDList);
+			}
+		}
+		for(String anAddString: addTokenList){
+			resultStr[0] += anAddString;
+		}
+		resultStr[1] += "array(" + addCmdIDList.size();
+		for(Integer id: addCmdIDList){
+			resultStr[1]+= ",(ID)" + id.toString();
+		}
+		resultStr[1] += ")," + addCmdIDList.size() ;
+		resultStr[2] += "array(" + addTskVarList.size();
+		for(String anAddTskVar: addTskVarList)
+			resultStr[2] += "," + anAddTskVar;
+		resultStr[2] += ")";
+		return resultStr;
+	}
+	
+	private String connectOutSignals(TEPEComponent currComp, int maxNoOfInSig, int maxNoOfNegInSig){
+		String connect="";
+		if (currComp.hasOutSignalComponents()){	
+			for(TEPEComponent outCmp: currComp.getOutSignals()){
+				int index = outCmp.getInSignals().indexOf(currComp);
+				String suffix = (index==-1)? "f": ""+(index+1);
+				connect += getTEPECompName(currComp) + "->connectSigOut(" + getTEPECompName(outCmp) + ",&SignalConstraint::notifyS" + suffix + ")" + SCCR;
+			}
+		}else
+			TraceManager.addDev(getTEPECompName(currComp) + " has no out signal components");
+			
+		//connect floating in Signal Components
+		int noOfSig= (currComp.hasInSignalComponents())? currComp.getInSignals().size():0;
+		TraceManager.addDev(getTEPECompName(currComp) + " Number of sig: " + noOfSig);
+		for(int i=noOfSig+1; i<=maxNoOfInSig; i++){
+			_floatingSigProc += ",&SignalConstraint::notifyS" + i;
+			_floatingSigComp += ",(SignalConstraint*)" + getTEPECompName(currComp);
+			_nbOfFloatingSig++;
+		}
+		noOfSig= (currComp.hasInNegatedSignalComponents())? currComp.getInNegatedSignals().size():0;
+		TraceManager.addDev(getTEPECompName(currComp) + " Number of neg sig: " + noOfSig);
+		for(int i=noOfSig; i<maxNoOfNegInSig; i++){
+			_floatingSigProc += ",&SignalConstraint::notifySf";
+			_floatingSigComp += ",(SignalConstraint*)" + getTEPECompName(currComp);
+			_nbOfFloatingSig++;
+		}
+		return connect;
+	}
+	
+	private String connectOutProperties(TEPEComponent currComp){
+		String connect="";
+		if (currComp.hasInPropertyComponents()){
+			connect += getTEPECompName(currComp) + "->connectEnaOut(array(" + currComp.getInProperties().size();
+			for(TEPEComponent outCmp: currComp.getInProperties()){
+				//connect += getTEPECompName(currComp) + "->connectEnaOut(array(1,(PropertyConstraint*)" + getTEPECompName(outCmp) + "),1)" + SCCR;
+				connect += ",(PropertyConstraint*)" + getTEPECompName(outCmp);
+			}
+			connect += ")," + currComp.getInProperties().size() + ")" + SCCR;
+		}else
+			TraceManager.addDev(getTEPECompName(currComp) + " has no out properties.\n");
+		if (!currComp.hasOutPropertyComponents()){
+			_floatingEnaComp+= ",(PropertyConstraint*)" + getTEPECompName(currComp);
+			_nbOfStartNodes++;
+		}
+		return connect;
+	}
+	
+	private void parseExprToTokenList(String iAdd, LinkedList<String> iList){
+		//LinkedList<String> resultList = new LinkedList<String>();
+		Matcher matcher = _varPattern.matcher(iAdd);
+		//System.out.print("Found tokens: ");
+		int lastEnd=0;
+		while (matcher.find()){
+			String token = iAdd.substring(matcher.start(), matcher.end()).trim();
+			if (matcher.start()>lastEnd) iList.add(iAdd.substring(lastEnd,matcher.start()).trim());
+			iList.add(token);
+			lastEnd=matcher.end();
+		}
+		if (lastEnd<iAdd.length()) iList.add(iAdd.substring(lastEnd,iAdd.length()).trim());
+	}
+	
+	private void replaceTokenInList(LinkedList<String> iList, String iReplace, String iAdd){
+		iReplace = iReplace.trim();
+		ListIterator itr = iList.listIterator();
+		LinkedList<String> addTokenList= new LinkedList<String>();
+		parseExprToTokenList(iAdd,addTokenList);
+		boolean aFound;
+		TraceManager.addDev("Decomp in replaceTokenInList: ");
+		for(String aToken: addTokenList)
+			System.out.print(aToken + ", ");
+		TraceManager.addDev("");
+		do{
+			aFound=false;
+			while(!aFound && itr.hasNext()){
+				aFound = ((String)itr.next()).equals(iReplace);
+			}
+			if (aFound){
+				TraceManager.addDev("Pattern found\n");
+				itr.remove();
+				for(String anAddString: addTokenList){
+					itr.add(anAddString);
+				}
+			}
+		}while(itr.hasNext());
+	}
+	
+	private String getSignalsForListener(TEPEComponent currComp){
+		String result= currComp.getOutSignals().size() + ",array(" + currComp.getOutSignals().size();
+		String aDstFuncs="";
+		for (TEPEComponent aDstCmp: currComp.getOutSignals()){
+			int index = aDstCmp.getInSignals().indexOf(currComp);
+			String suffix = (index==-1)? "f": ""+(index+1);
+			result += ",(SignalConstraint*)" + getTEPECompName(aDstCmp);
+			aDstFuncs += ",(NtfSigFuncPointer)&SignalConstraint::notifyS" + suffix;
+		}
+		result += "),array(" + currComp.getOutSignals().size() + aDstFuncs + ")";
+		return result;
+	}
+	
+	private void generateTEPEProp(TEPEComponent currComp, LinkedList<String> iTokenList, ArrayList<String> iTskVarList, HashSet<Integer> iCmdIDList){
+		
+		if (!(currComp instanceof TEPEPropertyComponent || currComp.hasOutAttributeComponents() || currComp.hasOutSignalComponents() || currComp.hasOutPropertyComponents())) return;
+		
+		String cmpName =  getTEPECompName(currComp);
+		
+		if(currComp instanceof TEPEAttributeComponent){
+			if (iTokenList==null){
+				if (currComp.hasOutSignalComponents()){
+					String[] decomp = getExprIDTskvarStrings(currComp, currComp.getValue());
+					_eqFuncDecl+= "ParamType " + cmpName + "_func(ParamType** iVar);\n";
+					_eqFuncs += "ParamType " + cmpName + "_func(ParamType** iVar){\n return " + decomp[0];
+					_eqFuncs += ";\n}\n\n";
+					_listeners+= "TEPESettingListener* " + cmpName + "_listener = new TEPESettingListener(" + decomp[1] + "," + decomp[2];
+					_listeners+= ",&" + cmpName + "_func" + "," + getSignalsForListener(currComp);
+					_listeners+= ",this,_simulator)" + SCCR;
+					_listeners+= "addTEPEListener((GeneralListener*)" + cmpName + "_listener);\n";
+				}
+				
+			}else{
+				//replaceTokenInList(iTokenList, currComp.getValue(), ((TEPEAttributeComponent)currComp).getBlockName() + "x" + currComp.getValue());
+				replaceTokenInList(iTokenList, currComp.getValue(), "*iVar[" + iTskVarList.size() + "]");
+				//iTskVarList.add( "&task__" + ((TEPEAttributeComponent)currComp).getBlockName() + "->" + currComp.getValue());
+				iTskVarList.add("getTaskByName(\""+ ((TEPEAttributeComponent)currComp).getBlockName() + "\")-> getVariableByName(\"" + currComp.getValue() + "\", aIsId)");
+				//getCommandsImpactingVar(String iVarName, ArrayList<Integer> oList)
+				MappedSystemCTask srcTsk = _tmltranslator.getMappedTaskByName(((TEPEAttributeComponent)currComp).getBlockName());
+				if (srcTsk==null)
+					TraceManager.addDev("Task not found: " + ((TEPEAttributeComponent)currComp).getBlockName());
+				else{
+					TraceManager.addDev("Search for Var " + currComp.getValue() +" in Task " + ((TEPEAttributeComponent)currComp).getBlockName());
+					srcTsk.getAnalysis().getCommandsImpactingVar(currComp.getValue(), iCmdIDList);
+				}
+			}
+		
+		}else if (currComp instanceof TEPEAliasComponent){
+			//no param
+			_declare+= "AliasConstraint* " + cmpName + " = new AliasConstraint(" + currComp.getID() + ")" + SCCR;
+			_connect += connectOutSignals(currComp,2,0);
+		
+		}else if (currComp instanceof TEPEEquationComponent){
+			/*LinkedList<String> addTokenList = new LinkedList<String>();
+			ArrayList<String> addTskVarList = new ArrayList<String>();
+			HashSet<Integer> addCmdIDList = new HashSet<Integer>();
+			parseExprToTokenList(currComp.getValue(), addTokenList);
+			for(TEPEComponent linkedComps: currComp.getInAttributes()){
+				TraceManager.addDev("%%%%%%%%%%% in Attribute");
+				generateTEPEProp(linkedComps, addTokenList, addTskVarList, addCmdIDList);
+			}*/
+			String[] decomp = getExprIDTskvarStrings(currComp, currComp.getValue());
+			_declare+= "EqConstraint* " + cmpName + " = new EqConstraint(" + currComp.getID() + ",GENERAL,true)" + SCCR;
+			//System.out.print(cmpName + "transformed to: ");
+			_eqFuncDecl+= "bool " + cmpName + "_func(ParamType** iVar);\n";
+			_eqFuncs += "bool " + cmpName + "_func(ParamType** iVar){\n return " + decomp[0];
+			/*for(String anAddString: addTokenList){
+				System.out.print(anAddString);
+				_eqFuncs += anAddString;
+			}
+			TraceManager.addDev();*/
+			_eqFuncs += ";\n}\n\n";
+			_listeners+= "TEPEEquationListener* " + cmpName + "_listener = new TEPEEquationListener(" + decomp[1] + "," + decomp[2];
+			/*"array(" + addCmdIDList.size();
+			for(Integer id: addCmdIDList){
+				_listeners+= ",(ID)" + id.toString();
+			} _listeners+= ")," + addCmdIDList.size() + "," + "array(" + addTskVarList.size();
+			for(String anAddTskVar: addTskVarList)
+				_listeners+= "," + anAddTskVar;*/
+			_listeners+= ",&" + cmpName + "_func" + "," + cmpName + ",&SignalConstraint::notifyS1,this, _simulator)" + SCCR;
+			_connect += connectOutSignals(currComp,0,0);
+			_connect += connectOutProperties(currComp);
+			_listeners+= "addTEPEListener((GeneralListener*)" + cmpName + "_listener);\n";
+		
+		}else if (currComp instanceof TEPELogicalConstraintComponent){
+			//LogConstraint(PropType iType, bool iIncludeBounds)
+			//SeqConstraint(PropType iType, bool iIncludeBounds)
+			if (((TEPELogicalConstraintComponent)currComp).getType()==TEPELogicalConstraintComponent.SEQUENCE){
+				_declare += "SeqConstraint* " + cmpName + " = new SeqConstraint("+ currComp.getID() + ",GENERAL,true)" + SCCR;
+			}else{
+				_declare += "LogConstraint* " + cmpName + " = new LogConstraint("+ currComp.getID() + ",GENERAL,true)" + SCCR;
+			}
+			//_declare += "addTEPEConstraint(" + cmpName + ");\n";
+			_connect += connectOutSignals(currComp,2,1);
+			_connect += connectOutProperties(currComp);
+		
+		}else if (currComp instanceof TEPEPropertyComponent){
+			//PropLabConstraint(PropLabType iType)
+			_declare += "PropLabConstraint* " + cmpName + " = new PropLabConstraint(";
+			TEPEPropertyComponent propComp = (TEPEPropertyComponent)currComp;
+			if (propComp.getType()==TEPEPropertyComponent.LIVENESS){
+				_declare += "LIVENESS";
+			}else if (propComp.getType()==TEPEPropertyComponent.NON_LIVENESS){
+				_declare += "NLIVENESS";
+			}else if (propComp.getType()==TEPEPropertyComponent.REACHABILITY){
+				_declare += "REACHABILITY";
+			}else{
+				_declare += "NREACHABILITY";
+			}
+			_declare += ")" + SCCR;
+			//_declare += "addTEPEConstraint(" + cmpName + ");\n";
+			_connect += connectOutProperties(currComp);
+		
+		}else if (currComp instanceof TEPEPropertyOperatorComponent){
+			//PropRelConstraint(PropRelType iType)
+			_declare += "PropRelConstraint* " + cmpName + " = new PropRelConstraint(";
+			TEPEPropertyOperatorComponent propOpComp = (TEPEPropertyOperatorComponent)currComp;
+			if (propOpComp.getType()==TEPEPropertyOperatorComponent.OR){
+				_declare += "OR";
+			}else{
+				_declare += "AND";
+			}
+			_declare += ")" + SCCR;
+			//_connect += connectOutSignals(currComp);
+			//_declare += "addTEPEConstraint(" + cmpName + ");\n";
+			_connect += connectOutProperties(currComp);
+		
+		}else if (currComp instanceof TEPESettingComponent){
+			//Variable Setting
+			//TEPESettingListener::TEPESettingListener(ID* iSubjectIDs, unsigned int iNbOfSubjectIDs, ParamType** iVar, SettingFuncPointer iSetFunc, unsigned int inbOfSignals, SignalConstraint** iNotifConstr, NtfSigFuncPointer* iNotifFunc, SimComponents* iSimComp, ListenerSubject<GeneralListener>* iSimulator);
+			if (iTokenList==null){
+				if (currComp.hasOutSignalComponents()){
+					String[] decomp = getExprIDTskvarStrings(currComp, currComp.getValue().split("=",2)[1]);
+					_eqFuncDecl+= "ParamType " + cmpName + "_func(ParamType** iVar);\n";
+					_eqFuncs += "ParamType " + cmpName + "_func(ParamType** iVar){\n return " + decomp[0];
+					_eqFuncs += ";\n}\n\n";
+					_listeners+= "TEPESettingListener* " + cmpName + "_listener = new TEPESettingListener(" + decomp[1] + "," + decomp[2];
+					_listeners+= ",&" + cmpName + "_func" + "," + getSignalsForListener(currComp);
+					_listeners+= ",this,_simulator)" + SCCR;
+					_listeners+= "addTEPEListener((GeneralListener*)" + cmpName + "_listener);\n";
+				}
+			}else{
+				String[] lhsrhs = currComp.getValue().split("=",2);
+				//TraceManager.addDev("Replace " + lhsrhs[0] + " by " + lhsrhs[1] + " before: ");
+				for(String aToken: iTokenList)
+					System.out.print(aToken + ", ");
+				//TraceManager.addDev("\nafter:");
+				replaceTokenInList(iTokenList, lhsrhs[0], lhsrhs[1]);
+				/*for(String aToken: iTokenList)
+					System.out.print(aToken + ", ");
+				TraceManager.addDev("");*/
+				for(TEPEComponent linkedComps: currComp.getInAttributes())
+					generateTEPEProp(linkedComps, iTokenList, iTskVarList, iCmdIDList);
+			}
+		
+		}else if (currComp instanceof TEPESignalComponent){
+			//Declaration of Signal?
+			//TEPESigListener(ID* iSubjectIDs, unsigned int nbOfSubjectIDs, unsigned int iEvtBitmap, unsigned int iTransTypeBitmap, SignalConstraint* iNotifConstr, NtfSigFuncPointer iNotifFunc, SimComponents* iSimComp)
+			if (currComp.hasOutSignalComponents()){
+				String[] aTokens = currComp.getValue().split("__");
+				TraceManager.addDev("name of block: "  + currComp.getValue());
+				for(int i=0; i<aTokens.length; i++)
+					TraceManager.addDev("A tokens [" + i + "]: " + aTokens[i]);
+				TraceManager.addDev("A tokens lenght: " + aTokens.length);
+				String[] aSrcIDs = aTokens[0].split("_");
+				String[] aEvts = aTokens[1].split("_");
+				String[] aTransTypes = aTokens[2].split("_");
+				String[] aEvtDescriptor = {"SIMSTART", "SIMEND", "TIMEADV", "TASKSTART", "TASKEND", "CMDRUNNABLE", "CMDSTART", "CMDEND", "TRANSEXEC"};
+				String[] aTransDescriptor = {"NONE", "EXE", "RD", "WR", "SEL", "SND", "REQ", "WAIT", "NOTIF", "ACT", "CHO", "RND", "STP"};
+				_listeners+= "TEPESigListener* " + cmpName + "_listener= new TEPESigListener(array(" + (aSrcIDs.length-1);
+				for(int i=1; i<aSrcIDs.length; i++)
+					_listeners+= ",(ID)" + aSrcIDs[i];
+				_listeners+= ")," + (aSrcIDs.length-1) + ",";
+				int aEvtCode=0, aTransCode=0;
+				for(int aEvtsInSigCmp=0; aEvtsInSigCmp<aEvts.length; aEvtsInSigCmp++){
+					for(int aEvtDescr=0; aEvtDescr<aEvtDescriptor.length; aEvtDescr++ ){
+						if (aEvts[aEvtsInSigCmp].toUpperCase().equals(aEvtDescriptor[aEvtDescr])) aEvtCode += (1<<aEvtDescr);
+					}
+				}
+				for(int aTransInSigCmp=0; aTransInSigCmp<aTransTypes.length; aTransInSigCmp++){
+					for(int aTransDescr=0; aTransDescr<aTransDescriptor.length; aTransDescr++ ){
+						if (aTransTypes[aTransInSigCmp].toUpperCase().equals(aTransDescriptor[aTransDescr])) aTransCode += (1<<aTransDescr);
+					}
+				}
+				
+				_listeners+= aEvtCode + "," + aTransCode + "," + getSignalsForListener(currComp);
+				/*_listeners+= currComp.getOutSignals().size() + ",array(" + currComp.getOutSignals().size();
+				String aDstFuncs="";
+				for (TEPEComponent aDstCmp: currComp.getOutSignals()){
+					int index = aDstCmp.getInSignals().indexOf(currComp);
+					String suffix = (index==-1)? "f": ""+(index+1);
+					_listeners += ",(SignalConstraint*)" + getTEPECompName(aDstCmp);
+					aDstFuncs += ",(NtfSigFuncPointer)&SignalConstraint::notifyS" + suffix;
+				}
+				_listeners += "),array(" + currComp.getOutSignals().size() + aDstFuncs + ")*/
+				_listeners += ",this, _simulator)" + SCCR;
+				_listeners+= "addTEPEListener((GeneralListener*)" + cmpName + "_listener);\n";
+			}
+			
+		}else if (currComp instanceof TEPETimeConstraintComponent){
+			//TimeMMConstraint(PropType iType, TMLTime iTmin, TMLTime iTmax, bool iRetrigger, bool iIncludeBounds)
+			//TimeTConstraint(TMLTime iT, bool iRetrigger, bool iIncludeBounds)
+			TEPETimeConstraintComponent timeConstr = (TEPETimeConstraintComponent)currComp;
+			if (currComp.getInSignals().size()>1){
+				String[] minMaxValues = timeConstr.getValue().split(",",2);
+				_declare += "TimeMMConstraint* " + cmpName +  " = new TimeMMConstraint("+ currComp.getID() + ",GENERAL, " + minMaxValues[0] + "," + minMaxValues[1] + ",false,true)"  + SCCR;
+				_connect += connectOutSignals(currComp,2,0);
+			}else{
+				_declare += "TimeTConstraint* " + cmpName + " =  new TimeTConstraint(" + currComp.getID() + "," + timeConstr.getValue() + ",false,true)"  + SCCR;
+				_connect += connectOutSignals(currComp,1,0);
+			}
+			//_declare += "addTEPEConstraint(" + cmpName + ");\n";
+			_connect += connectOutProperties(currComp);
+		}
+	}
+
+}
diff --git a/src/tmltranslator/tomappingsystemc3/TML2MappingSystemC.java b/src/tmltranslator/tomappingsystemc3/TML2MappingSystemC.java
new file mode 100755
index 0000000000000000000000000000000000000000..2ff6bdc2e8a9852c9eca324d9909613c4ba2aa7d
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/TML2MappingSystemC.java
@@ -0,0 +1,833 @@
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
+
+ludovic.apvrille AT telecom-paristech.fr
+andrea.enrici 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.
+
+/**
+ * Class TML2MappingSystemC
+ * Creation: 30/05/2014
+ * @version 1.0 30/05/2014
+ * @author Andrea Enrici, Daniel Knorreck
+ * @see
+ */
+
+package tmltranslator.tomappingsystemc3;
+
+import java.util.*;
+
+import tmltranslator.*;
+import myutil.*;
+import req.ebrdd.*;
+import tepe.*;
+
+
+public class TML2MappingSystemC {
+    
+	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 boolean optimize;
+	private String header, declaration, mainFile, src;
+	private ArrayList<MappedSystemCTask> tasks;
+	
+	//private ArrayList<EBRDD> ebrdds;
+	//private ArrayList<TEPE> tepes;
+	SystemCTEPE tepeTranslator;
+	//private ArrayList<SystemCEBRDD> systemCebrdds = new ArrayList<SystemCEBRDD>();
+    
+	public TML2MappingSystemC( TMLModeling _tmlm ) {
+
+		tmlmodeling = _tmlm;
+		tmlmapping = tmlmodeling.getDefaultMapping();
+		tepeTranslator = new SystemCTEPE( new ArrayList<TEPE>(), this );
+	}
+	
+	public TML2MappingSystemC( TMLMapping _tmlmapping ) {
+
+		tmlmapping = _tmlmapping;
+		tmlmapping.makeMinimumMapping();
+		tepeTranslator = new SystemCTEPE( new ArrayList<TEPE>(), this );
+ 	}
+
+	public TML2MappingSystemC( TMLModeling _tmlm, ArrayList<EBRDD> _ebrdds, ArrayList<TEPE> _tepes ) {
+	
+		tmlmodeling = _tmlm;
+		//ebrdds = _ebrdds;
+		tmlmapping = tmlmodeling.getDefaultMapping();
+		tepeTranslator = new SystemCTEPE( _tepes, this );
+		//tepeTranslator.generateTEPEs();
+	}
+	
+	public TML2MappingSystemC( TMLMapping _tmlmapping, ArrayList<EBRDD> _ebrdds, ArrayList<TEPE> _tepes ) {
+
+		tmlmapping = _tmlmapping;
+		//ebrdds = _ebrdds;
+		tmlmapping.makeMinimumMapping();
+		tepeTranslator = new SystemCTEPE( _tepes, this );
+		//tepeTranslator.generateTEPEs();
+ 	}
+    
+	public void saveFile( String path, String filename ) throws FileException {  
+
+		generateTaskFiles( path );
+    FileUtils.saveFile( path + filename + ".cpp", getFullCode() );
+		src += filename + ".cpp";
+		FileUtils.saveFile( path + "Makefile.src", src );
+		//tepeTranslator.saveFile(path + "src_simulator/TEPE/test.h");
+	}
+	
+	public String getFullCode() {
+		return mainFile;
+	}
+
+	public void generateSystemC( boolean _debug, boolean _optimize ) {
+		
+		debug = _debug;
+		optimize = _optimize;
+		tmlmapping.removeAllRandomSequences();
+		tmlmodeling = tmlmapping.getTMLModeling();
+		tasks = new ArrayList<MappedSystemCTask>();
+   	//generateSystemCTasks();
+		//generateEBRDDs();
+		generateMainFile();
+		generateMakefileSrc();
+	}
+	
+	private void generateMainFile() {
+
+		makeHeader();
+		makeDeclarations();
+		header += tepeTranslator.getEqFuncDeclaration() + "\n";
+		mainFile = header + declaration;
+		mainFile = Conversion.indentString( mainFile, 4 );
+	}
+	
+	private void generateMakefileSrc() {
+
+		src = "SRCS = ";
+		for(TMLTask mst: tmlmapping.getMappedTasks()) {
+			src += mst.getName() + ".cpp ";
+		}
+		//for(EBRDD ebrdd: ebrdds){
+		//	src += ebrdd.getName() + ".cpp ";
+		//}
+	}
+	
+	private void makeHeader() {
+		// System headers
+		header = "#include <Simulator.h>" + CR;
+		header += "#include <AliasConstraint.h>\n#include <EqConstraint.h>\n#include <LogConstraint.h>\n#include <PropLabConstraint.h>\n";
+		header += "#include <PropRelConstraint.h>\n#include <SeqConstraint.h>\n#include <SignalConstraint.h>\n#include <TimeMMConstraint.h>\n";
+		header += "#include <TimeTConstraint.h>\n";
+		header += "#include <CPU.h>\n#include <SingleCoreCPU.h>\n#include <RRScheduler.h>\n#include <RRPrioScheduler.h>\n#include <PrioScheduler.h>\n#include <Bus.h>\n";
+		header += "#include <Bridge.h>\n#include <Memory.h>\n#include <TMLbrbwChannel.h>\n#include <TMLnbrnbwChannel.h>\n";
+		header += "#include <TMLbrnbwChannel.h>\n#include <TMLEventBChannel.h>\n#include <TMLEventFChannel.h>\n#include <TMLEventFBChannel.h>\n";
+		header += "#include <TMLTransaction.h>\n#include <TMLCommand.h>\n#include <TMLTask.h>\n";
+		header += "#include <SimComponents.h>\n#include <Server.h>\n#include <SimServSyncInfo.h>\n#include <ListenersSimCmd.h>\n";
+
+		// Generate tasks header
+		for(TMLTask mst: tmlmapping.getMappedTasks()) {
+			//header += "#include <" + mst.getReference() + ".h>" + CR;
+			header += "#include <" + mst.getName() + ".h>" + CR;
+		}
+		//for(EBRDD ebrdd: ebrdds){
+		//	header += "#include <" + ebrdd.getName() + ".h>" + CR;
+		//}
+		header += CR;
+	}
+	
+	private void makeDeclarations() {
+
+		declaration = "class CurrentComponents: public SimComponents{\npublic:\nCurrentComponents():SimComponents("
+										+ tmlmapping.getHashCode() + "){\n";
+		
+		// Declaration of HW nodes
+		declaration += "//Declaration of CPUs" + CR;
+		for( HwNode node: tmlmapping.getTMLArchitecture().getHwNodes() )	{
+			if( node instanceof HwCPU ) {
+				HwCPU exNode = (HwCPU)node;
+				if( exNode.getType().equals( "CPURRPB" ) )	{
+					declaration += "PrioScheduler* " + exNode.getName() + "_scheduler = new PrioScheduler(\"" + exNode.getName()
+													+ "_PrioSched\",0)" + SCCR;
+				}
+				else	{
+					//tmlmapping.getTMLArchitecture().getMasterClockFrequency() * exNode.sliceTime
+					 //declaration += "RRScheduler* " + exNode.getName() + "_scheduler = new RRScheduler(\"" + exNode.getName()
+					 //+ "_RRSched\", 0, 5, " + (int) Math.ceil(((float)exNode.execiTime)*(1+((float)exNode.branchingPredictionPenalty)/100))
+					 //+ " ) " + SCCR;
+					 declaration += "RRScheduler* " + exNode.getName() + "_scheduler = new RRScheduler(\"" + exNode.getName() + "_RRSched\", 0, "
+					 								+ (tmlmapping.getTMLArchitecture().getMasterClockFrequency() * exNode.sliceTime) + ", "
+													+ (int) Math.ceil((float)(exNode.clockRatio * Math.max(exNode.execiTime,exNode.execcTime)
+													* (exNode.branchingPredictionPenalty * exNode.pipelineSize +100 - exNode.branchingPredictionPenalty))/100)
+													+ " ) " + SCCR;
+				//for(int cores=0; cores<exNode.nbOfCores; cores++){
+				}
+				for( int cores = 0; cores < 1; cores++ )	{
+					//if(tmlmapping.isAUsedHwNode(node)) {	
+					declaration += "CPU* " + exNode.getName() + cores + " = new SingleCoreCPU(" + exNode.getID() + ", \""
+													+ exNode.getName() + "_" + cores + "\", " + exNode.getName() + "_scheduler" + ", ";
+					
+					declaration  += exNode.clockRatio + ", " + exNode.execiTime + ", " + exNode.execcTime + ", " + exNode.pipelineSize
+													+ ", " + exNode.taskSwitchingTime + ", " + exNode.branchingPredictionPenalty + ", " + exNode.goIdleTime
+													+ ", "  + exNode.maxConsecutiveIdleCycles + ", " + exNode.byteDataSize + ")" + SCCR;
+					if( cores != 0 )	{
+						declaration+= node.getName() + cores + "->setScheduler(" + exNode.getName() + "_scheduler,false)" + SCCR;
+						declaration += "addCPU("+ node.getName() + cores +")"+ SCCR;
+					}
+				}
+			}
+			if( node instanceof HwA )	{
+				HwA hwaNode = (HwA)node;
+				declaration += "RRScheduler* " + hwaNode.getName() + "_scheduler = new RRScheduler(\"" + hwaNode.getName()
+												+ "_RRSched\", 0, " + (tmlmapping.getTMLArchitecture().getMasterClockFrequency() * hwaNode.DEFAULT_SLICE_TIME)
+												+ ", " + (int) Math.ceil((float)(hwaNode.clockRatio * Math.max(hwaNode.execiTime,hwaNode.execcTime)
+												* (hwaNode.DEFAULT_BRANCHING_PREDICTION_PENALTY * hwaNode.DEFAULT_PIPELINE_SIZE + 100
+												* - hwaNode.DEFAULT_BRANCHING_PREDICTION_PENALTY))/100) + " ) " + SCCR;
+				for( int cores = 0; cores < 1; cores++ )	{
+					//if(tmlmapping.isAUsedHwNode(node)) {	
+					declaration += "CPU* " + hwaNode.getName() + cores + " = new SingleCoreCPU(" + hwaNode.getID() + ", \""
+													+ hwaNode.getName() + "_" + cores + "\", " + hwaNode.getName() + "_scheduler" + ", ";
+					
+					declaration  += hwaNode.clockRatio + ", " + hwaNode.execiTime + ", " + hwaNode.execcTime + ", " + hwaNode.DEFAULT_PIPELINE_SIZE
+													+ ", " + hwaNode.DEFAULT_TASK_SWITCHING_TIME + ", " + hwaNode.DEFAULT_BRANCHING_PREDICTION_PENALTY
+													+ ", " + hwaNode.DEFAULT_GO_IDLE_TIME + ", "  + hwaNode.DEFAULT_MAX_CONSECUTIVE_IDLE_CYCLES + ", "
+													+ hwaNode.byteDataSize + ")" + SCCR;
+					if( cores != 0 )	{
+						declaration+= node.getName() + cores + "->setScheduler(" + hwaNode.getName() + "_scheduler,false)" + SCCR;
+						declaration += "addCPU("+ node.getName() + cores +")"+ SCCR;
+					}
+				}
+				
+			}
+		}
+		declaration += CR;
+		
+		// Declaration of Buses
+		declaration += "//Declaration of Buses" + CR;
+		//declaration+="Bus* defaultBus = new Bus(-1,\"defaultBus\",100,1,1)" + SCCR;
+		//declaration += "addBus(defaultBus)"+ SCCR;
+		for(HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()) {
+			if(node instanceof HwBus) {
+				//if(tmlmapping.isAUsedHwNode(node)) {
+				HwBus thisBus = (HwBus)node;
+				for( int i = 0; i < thisBus.pipelineSize; i++ )	{
+					declaration += "Bus* " + node.getName() + "_" + i + " = new Bus("+ node.getID() + ",\"" + node.getName() + "_" + i
+													+ "\",0, 100, "+ thisBus.byteDataSize + ", " + node.clockRatio + ",";
+					if( thisBus.arbitration==HwBus.CAN )	{
+						declaration +="true";
+					}
+					else	{
+						declaration +="false"; 
+					}
+					declaration += ");\naddBus("+ node.getName() + "_" + i + ")"+ SCCR;
+				}
+				//}
+			}
+		}
+		declaration += CR;
+
+		// Declaration of Bridges
+		declaration += "//Declaration of Bridges" + CR;
+		for( HwNode node: tmlmapping.getTMLArchitecture().getHwNodes() ) {
+			if(node instanceof HwBridge) {
+				declaration+= "Bridge* " + node.getName() + " = new Bridge("+ node.getID() + ",\"" + node.getName() + "\", "
+											+ node.clockRatio + ", " + ((HwBridge)node).bufferByteSize + ")" +SCCR;
+				declaration += "addBridge("+ node.getName() +")"+ SCCR;
+			}
+		}
+		declaration += CR;
+
+		// Declaration of Memories
+		//declaration += "//Declaration of Memories\nMemory* defaultMemory = new Memory(-1,\"defaultMemory\",1,4)" + SCCR;
+		//declaration += "addMem(defaultMemory)"+ SCCR;
+		declaration += "//Declaration of Memories" + CR;
+		for( HwNode node: tmlmapping.getTMLArchitecture().getHwNodes()) {
+			if( node instanceof HwMemory	) {
+				declaration += "Memory* " + node.getName() + " = new Memory("+ node.getID() + ",\"" + node.getName() + "\", "
+												+ node.clockRatio + ", " + ((HwMemory)node).byteDataSize + ")" +SCCR;
+				declaration += "addMem("+ node.getName() +")"+ SCCR;
+			}
+		}
+		declaration += CR;
+
+		//Declaration of Bus masters
+		declaration += "//Declaration of Bus masters" + CR;
+		for( HwNode node: tmlmapping.getTMLArchitecture().getHwNodes() ){
+			if( node instanceof HwExecutionNode || node instanceof HwBridge ){
+				ArrayList<HwLink> nodeLinks = tmlmapping.getTMLArchitecture().getLinkByHwNode( node );
+				if( !nodeLinks.isEmpty() )	{
+					//declaration+= "BusMaster* " + node.getName() + "2defaultBus = new BusMaster(\"" + node.getName()
+					//+ "2defaultBus\", 0, defaultBus)" + SCCR;
+				//else{
+					for( HwLink link: nodeLinks )	{
+						//declaration+= "BusMaster* " + node.getName() + "_" + link.bus.getName() + "_Master = new BusMaster(\""
+						//+ node.getName() + "_" + link.bus.getName() + "_Master\", " + link.getPriority() + ", 1, array(1, (SchedulableCommDevice*)"
+						//+  link.bus.getName() + "))" + SCCR;
+						int noOfCores;
+						//if(node instanceof HwCPU) noOfCores= ((HwCPU)node).nbOfCores; else noOfCores=1;
+						noOfCores = 1;
+						for( int cores = 0; cores < noOfCores; cores++ )	{
+							String nodeName = node.getName();
+							if( ( node instanceof HwCPU ) || ( node instanceof HwA ) )	{
+								nodeName += cores;
+							}
+							declaration += "BusMaster* " + nodeName + "_" + link.bus.getName() + "_Master = new BusMaster(\"" + nodeName
+													+ "_" + link.bus.getName() + "_Master\", " + link.getPriority() + ", " + link.bus.pipelineSize
+													+ ", array(" + link.bus.pipelineSize;
+							for( int i = 0; i < link.bus.pipelineSize; i++ )	{
+								declaration += ", (SchedulableCommDevice*)" +  link.bus.getName() + "_" + i; 
+							}
+							declaration += "))" + SCCR;
+							declaration += nodeName + "->addBusMaster(" + nodeName + "_" + link.bus.getName() + "_Master)" + SCCR;
+						}
+					}
+				}
+			} 
+		}
+		declaration += CR;
+				
+		// Declaration of channels
+		TMLChannel channel;
+		String tmp,param;
+		declaration += "//Declaration of channels" + CR;
+		for( TMLElement elem: tmlmodeling.getChannels() )	{
+			if( elem instanceof TMLChannel ) {
+				channel = (TMLChannel)elem;
+				switch( channel.getType() )	{
+					case TMLChannel.BRBW:
+						tmp = "TMLbrbwChannel";
+						param= "," + channel.getMax() + ",0";
+						break;
+					case TMLChannel.BRNBW:
+						tmp = "TMLbrnbwChannel";
+						param= ",0";
+						break;
+					case TMLChannel.NBRNBW:
+					default:
+						tmp = "TMLnbrnbwChannel";
+						param= "";
+				}
+				declaration += tmp + "* " + channel.getExtendedName() + " = new " + tmp  +"(" + channel.getID() + ",\""
+												+ channel.getName() + "\"," + channel.getSize() + ",";
+				TraceManager.addDev( "Channel: " + channel.getName() );
+				declaration += determineRouting( tmlmapping.getHwNodeOf( channel.getOriginTask() ),
+																					tmlmapping.getHwNodeOf( channel.getDestinationTask() ), elem )
+											+ param + "," + channel.getPriority();
+				if( (channel.isLossy()) && (channel.getType() != TMLChannel.NBRNBW) )	{
+					declaration += "," + channel.getLossPercentage() + "," + channel.getMaxNbOfLoss();
+				}
+				declaration += ")"+ SCCR;
+				declaration += "addChannel("+ channel.getExtendedName() +")"+ SCCR;
+			}
+		}
+		declaration += CR;
+		
+		// Declaration of events
+		declaration += "//Declaration of events" + CR;
+		for( TMLEvent evt: tmlmodeling.getEvents() )	{
+			if( evt.isInfinite() ) {
+				tmp = "TMLEventBChannel<ParamType," + evt.getNbOfParams() + ">";
+				param= ",0,false,false";
+			}
+			else	{
+				if( evt.isBlocking() ) {
+					tmp = "TMLEventFBChannel<ParamType," + evt.getNbOfParams() + ">";
+					param= "," + evt.getMaxSize() + ",0";
+				}
+				else	{
+					tmp = "TMLEventFChannel<ParamType," + evt.getNbOfParams() + ">";
+					param= "," + evt.getMaxSize() + ",0";
+				}
+			}
+			//param += "," + evt.getNbOfParams();
+			if( tmlmapping.isCommNodeMappedOn(evt,null) )	{
+				TraceManager.addDev( "Evt: " + evt.getName() );
+				declaration += tmp + "* " + evt.getExtendedName() + " = new " + tmp + "(" + evt.getID() + ",\"" + evt.getName()
+										+ "\"," + determineRouting(tmlmapping.getHwNodeOf(evt.getOriginTask()),
+										tmlmapping.getHwNodeOf(evt.getDestinationTask()), evt) + param;
+				
+			}
+			else	{
+				declaration += tmp + "* " + evt.getExtendedName() + " = new " + tmp + "(" + evt.getID() + ",\"" + evt.getName()
+											+ "\",0,0,0" + param;   ///old command
+			}
+			if( evt.isLossy() )	{
+				declaration += "," + evt.getLossPercentage() + "," + evt.getMaxNbOfLoss();
+			}
+			declaration += ")" + SCCR;
+			declaration += "addEvent("+ evt.getExtendedName() +")"+ SCCR;
+		}
+		declaration += CR;
+		
+		// Declaration of requests
+		declaration += "//Declaration of requests" + CR;
+		for( TMLTask task: tmlmodeling.getTasks() )	{
+			if( task.isRequested() )	{
+				TMLRequest req = task.getRequest();
+				if( tmlmapping.isCommNodeMappedOn(req,null) )	{
+					//declaration += "TMLEventBChannel* reqChannel_"+ task.getName() + " = new TMLEventBChannel(" +
+					TraceManager.addDev( "Request: " + req.getName() );
+					declaration += "TMLEventBChannel<ParamType," + req.getNbOfParams() + ">* reqChannel_"+ task.getName()
+												+ " = new TMLEventBChannel<ParamType," + req.getNbOfParams() + ">(" +
+												req.getID() + ",\"reqChannel"+ task.getName() + "\"," +
+					determineRouting( tmlmapping.getHwNodeOf(req.getOriginTasks().get(0) ),
+					//tmlmapping.getHwNodeOf(req.getDestinationTask()), req) + ",0," + req.getNbOfParams() + ",true)" + SCCR;
+														tmlmapping.getHwNodeOf(req.getDestinationTask()), req ) + ",0,true,false";
+				}
+				else	{
+					declaration += "TMLEventBChannel<ParamType," + req.getNbOfParams() + ">* reqChannel_"+ task.getName()
+													+ " = new TMLEventBChannel<ParamType," + req.getNbOfParams() + ">(" +
+													//req.getID() + ",\"reqChannel"+ task.getName() + "\",0,0,0,0," + req.getNbOfParams() + ",true)" + SCCR;
+													req.getID() + ",\"reqChannel"+ task.getName() + "\",0,0,0,0,true,false";
+				}
+				if( req.isLossy() )	{
+					declaration += "," + req.getLossPercentage() + "," + req.getMaxNbOfLoss();
+				}
+				declaration += ")" + SCCR;
+				declaration += "addRequest(reqChannel_"+ task.getName() +")"+ SCCR;
+			}
+		}
+		declaration += CR;
+
+		///Set bus schedulers
+		declaration += "//Set bus schedulers" + CR;
+		for( HwNode node: tmlmapping.getTMLArchitecture().getHwNodes() ) {
+			if( node instanceof HwBus ) {
+				ArrayList<HwLink> busLinks = tmlmapping.getTMLArchitecture().getLinkByBus((HwBus)node );
+				String devices = "";
+				int numDevices = 0;
+				if( !busLinks.isEmpty() ){
+					for( HwLink link: busLinks ){
+						if( link.hwnode instanceof HwExecutionNode || link.hwnode instanceof HwBridge ){
+								if( ( link.hwnode instanceof HwCPU ) || ( link.hwnode instanceof HwA ) ){
+									//for (int cores=0; cores< ((HwCPU)link.hwnode).nbOfCores; cores++){
+									for ( int cores = 0; cores < 1; cores++ )	{
+										devices += ", (WorkloadSource*)" + link.hwnode.getName()+ cores + "_" + node.getName() + "_Master";
+										numDevices++;
+									}
+								}
+								else	{
+									devices += ", (WorkloadSource*)" + link.hwnode.getName()+ "_" + node.getName() + "_Master";
+									numDevices++;
+								}
+						}
+					}
+					declaration += node.getName() + "_0->setScheduler((WorkloadSource*) new ";
+					if( ( (HwBus)node ).arbitration == HwBus.BASIC_ROUND_ROBIN)	{
+						//declaration+="RRScheduler(\"" + node.getName() + "_RRSched\", 0, 5, "
+						//+ (int) Math.ceil(((float)node.clockRatio)/((float)((HwBus)node).byteDataSize)) + ", array(";
+						declaration += "RRScheduler(\"" + node.getName() + "_RRSched\", 0, 5, "
+														+ (int) Math.ceil(((float)node.clockRatio)/((float)((HwBus)node).byteDataSize)) + ", array(";
+					}
+					else	{
+						declaration += "PrioScheduler(\"" + node.getName() + "_PrioSched\", 0, array(";
+					}
+					declaration += numDevices + devices + "), " + numDevices + "))" + SCCR;
+				}
+				for( int i = 1; i < ((HwBus)node).pipelineSize; i++	)	{
+					declaration += node.getName() + "_" + i + "->setScheduler(" + node.getName() + "_0->getScheduler(),false)" +SCCR;
+				}
+			}
+		}
+		declaration += CR;
+		
+	
+		//Declaration of Tasks
+		ListIterator iterator = tmlmapping.getNodes().listIterator();
+		declaration += "//Declaration of tasks" + CR;
+		HwExecutionNode node;
+		//for(TMLTask task: tmlmodeling.getTasks()) {
+		ArrayList<TMLChannel> channels;
+		ArrayList<TMLEvent> events;
+		ArrayList<TMLRequest> requests;
+		int[] aStatistics = new int[8];
+		Set<Integer> mappedChannels = new HashSet<Integer>(); 
+		for( TMLTask task: tmlmapping.getMappedTasks() )	{
+			node = ( HwExecutionNode )iterator.next();
+			int noOfCores;
+			declaration += task.getName() + "* task__" + task.getName() + " = new " + task.getName() + "("+ task.getID() +","
+											+ task.getPriority() + ",\"" + task.getName() + "\", array(";
+			
+			if( node instanceof HwCPU )	{
+				//declaration+= ((HwCPU)node).nbOfCores;
+				declaration += 1;
+				//for (int cores=0; cores< ((HwCPU)node).nbOfCores; cores++){
+				for( int cores = 0; cores < 1; cores++ )	{
+					declaration += "," + node.getName()+cores;
+				}
+				//declaration+= ")," + ((HwCPU)node).nbOfCores + CR;
+				declaration += "),1" + CR;
+			}
+			else	{
+					if( node instanceof HwA )	{ 
+					//declaration+= ((HwCPU)node).nbOfCores;
+					declaration += 1;
+					//for (int cores=0; cores< ((HwCPU)node).nbOfCores; cores++){
+					for( int cores=0; cores< 1; cores++ )	{
+						declaration += "," + node.getName()+cores;
+					}
+					//declaration+= ")," + ((HwCPU)node).nbOfCores + CR;
+					declaration += "),1" + CR;
+				}
+				else {
+					declaration += "1," + node.getName() + "),1" + CR; 
+				}
+			}
+			
+			MappedSystemCTask mst;
+			channels = new ArrayList<TMLChannel>(tmlmodeling.getChannels(task));
+			events = new ArrayList<TMLEvent>(tmlmodeling.getEvents(task));
+			requests = new ArrayList<TMLRequest>(tmlmodeling.getRequests(task));
+
+			mst = new MappedSystemCTask(task, channels, events, requests, tmlmapping, mappedChannels);
+			//mst.generateSystemC(debug, optimize, dependencies);
+			//mst.generateSystemC(debug, optimize);
+			tasks.add(mst);
+			for( TMLChannel channelb: channels	)	{
+				declaration += "," + channelb.getExtendedName()+CR;
+			}
+			for( TMLEvent evt: events )	{
+				declaration += "," + evt.getExtendedName()+CR;
+			}
+			for( TMLRequest req: requests )	{
+				if(	req.isAnOriginTask(task) )	{
+					declaration +=",reqChannel_" + req.getDestinationTask().getName()+CR;
+				}
+			}
+			if( task.isRequested() )	{
+				declaration += ",reqChannel_"+task.getName()+CR;
+			}
+			declaration += ")" + SCCR;
+			declaration += "addTask(task__"+ task.getName() +")"+ SCCR;
+		}
+		//int[] aStatistics = new int[8];
+		declaration += "\n}\n\n";
+
+		//Declaration of CommunicationPatterns
+		declaration += "//Declaration of CPs" + CR;
+		declaration += "//Here I will produce code for the Communication Patterns" + CR;
+		
+		//Declaration of TEPEs
+		declaration += "void generateTEPEs(){" + CR;
+		declaration += "//Declaration of TEPEs" + CR;
+		tepeTranslator.generateTEPEs();
+		declaration += tepeTranslator.getCode();
+		
+		//Generation of tasks
+		for(MappedSystemCTask task: tasks){
+			task.determineCheckpoints(aStatistics);
+			task.generateSystemC(debug, optimize);
+		}
+		
+		//Declaration of TEPEs continued
+		declaration += CR;
+		declaration += "}\n};\n\n" + tepeTranslator.getEqFuncs();
+		declaration +="#include <main.h>\n";
+		
+		if( aStatistics[0] != 0 )	{
+			TraceManager.addDev("Global gain variables " + 100 * aStatistics[1] / aStatistics[0]);
+		}
+		if( aStatistics[2] != 0 )	{
+			TraceManager.addDev("Global gain Channels " + 100 * aStatistics[3] / aStatistics[2]);
+		}
+		if( aStatistics[4] != 0 )	{
+			TraceManager.addDev("Global gain events " + 100 * aStatistics[5] / aStatistics[4]);
+		}
+		if( aStatistics[6] != 0 )	{
+			TraceManager.addDev("Global gain checkpoints " + 100 * aStatistics[7] / aStatistics[6]);
+		}
+		
+		//Declaration of EBRDDs
+		/*declaration += "//Declaration of EBRDDs" + CR;
+		for(EBRDD ebrdd: ebrdds){
+			declaration += ebrdd.getName() + "* ebrdd__" + ebrdd.getName() + " = new " + ebrdd.getName() + "(0, \""+ ebrdd.getName() + "\");\n";
+			declaration += "addEBRDD(ebrdd__"+ ebrdd.getName() +")"+ SCCR;
+		}*/
+	}
+
+
+	private int extractPath( LinkedList<HwCommunicationNode> path, strwrap masters, strwrap slaves, HwNode startNode,
+														HwNode destNode, boolean reverseIn )	{
+
+		String firstPart=""; //lastBus="";
+		int masterCount=0;
+		boolean reverse=reverseIn;
+		if(reverseIn)
+			slaves.str+=",static_cast<Slave*>(0)";
+		else
+			firstPart=startNode.getName() + "0";
+		/*TraceManager.addDev("------------------------------------------------------");
+		for(HwCommunicationNode commElem:path){
+			TraceManager.addDev("CommELem to process: " + commElem.getName());
+		}
+		TraceManager.addDev("------------------------------------------------------");*/
+		for(HwCommunicationNode commElem:path){
+			//TraceManager.addDev("CommELem to process: " + commElem.getName());
+			//String commElemName = commElem.getName();
+			//if(commElem instanceof HwCPU) commElemName += "0";
+			//System.out.println("Next elem in path: " + commElem.getName());
+			if(commElem instanceof HwMemory){
+				reverse=true;
+				slaves.str+= ",static_cast<Slave*>(" + commElem.getName() + "),static_cast<Slave*>(" + commElem.getName() + ")";
+				//firstPart=lastBus;
+				firstPart="";
+			}else{
+				if(reverse){
+					if(firstPart.length()==0){
+						firstPart=commElem.getName();
+						//firstPart=commElemName;
+					}else{
+						masters.str+= "," + commElem.getName() + "_" + firstPart + "_Master";
+						//masters.str+= "," + commElemName + "_" + firstPart + "_Master";
+						masterCount++;
+						slaves.str+= ",static_cast<Slave*>(" + commElem.getName() + ")";
+						firstPart="";
+					}
+				}else{
+					if(firstPart.length()==0){
+						firstPart=commElem.getName();
+						slaves.str+= ",static_cast<Slave*>(" + firstPart + ")";
+					}else{
+						//lastBus=commElem.getName();
+						masters.str+= "," + firstPart + "_" + commElem.getName() + "_Master";
+						masterCount++;
+						firstPart="";
+					}
+				}
+			}
+		}
+		if(reverse){
+			//masters.str+= "," + destNode.getName() + "_" + firstPart + "_Master";
+			masters.str+= "," + destNode.getName() + "0_" + firstPart + "_Master";
+			return masterCount+1;
+		}else{
+			slaves.str+=",static_cast<Slave*>(0)";
+			return -masterCount;
+		}
+	}
+
+//Method used when writing the C++ code for channels, event and requests
+	private String determineRouting(	HwNode startNode, HwNode destNode, TMLElement commElemToRoute )	{
+
+		strwrap masters = new strwrap(), slaves = new strwrap();
+		LinkedList<HwCommunicationNode> path = new LinkedList<HwCommunicationNode>();
+		LinkedList<HwCommunicationNode> commNodes = new LinkedList<HwCommunicationNode>();
+
+		for( HwNode node: tmlmapping.getTMLArchitecture().getHwNodes() )	{
+			if( node instanceof HwCommunicationNode )	{
+				commNodes.add( (HwCommunicationNode) node );
+			}
+		}
+//		TraceManager.addDev( "Printing communication nodes" );
+//		TraceManager.addDev( commNodes.get(i).getName() );
+		HwMemory memory = getMemConnectedToBusChannelMapped( commNodes, null, commElemToRoute );
+		if( memory == null )	{
+			TraceManager.addDev( "no memories to map" );
+			exploreBuses( 0, commNodes, path, startNode, destNode, commElemToRoute );
+		}
+		else	{	//there is at least one memory
+			LinkedList<HwCommunicationNode> commNodes2 = new LinkedList<HwCommunicationNode>(commNodes);
+			//exploreBuses(0, commNodes, path, startNode, memory, commElemToRoute);
+			if( !exploreBuses( 0, commNodes, path, startNode, memory, commElemToRoute ) )	{
+				TraceManager.addDev("NO route to " + memory.getName() + "found!!!!!!!!!!!!!!!!!!!!!!!!!!");
+			}
+			path.add( memory );
+			exploreBuses( 0, commNodes2, path, memory, destNode, commElemToRoute );
+		}
+		int hopNum;
+		if( ( hopNum = extractPath( path, masters, slaves, startNode, destNode, false ) ) < 0	)	{
+			hopNum = extractPath( path, masters, slaves, destNode, destNode, true ) - hopNum;
+		}
+		/*TraceManager.addDev(commElemToRoute.getName() + " is mapped on:");
+		for(HwCommunicationNode commElem:path){
+			TraceManager.addDev(commElem.getName());
+		}
+		TraceManager.addDev("number of elements: " + hopNum);
+		TraceManager.addDev("masters: " + masters.str);
+		TraceManager.addDev("slaves: " + slaves.str);*/
+		return hopNum + ", array(" + hopNum + masters.str + "), array(" + hopNum + slaves.str + ")";
+	}
+
+	private boolean exploreBuses( int depth, LinkedList<HwCommunicationNode> commNodes, LinkedList<HwCommunicationNode> path,
+																HwNode startNode, HwNode destNode, TMLElement commElemToRoute )	{
+
+		//first called with Mapping:getCommunicationNodes
+		LinkedList<HwCommunicationNode> nodesToExplore;
+
+		TraceManager.addDev( "exploreBuses: No of comm nodes " + commNodes.size() );
+		boolean busExploreMode = ( ( depth & 1 ) == 0);	//if(depth == 0)	busExploreMode = 0
+		//if(depth % 2 == 0){
+		if( busExploreMode )	{
+			TraceManager.addDev( "exploreBuses: search for buses connected to " + startNode.getName() );
+			nodesToExplore = getBusesConnectedToNode( commNodes, startNode );
+			TraceManager.addDev( "Connected to " + startNode.getName() + " I have found:" );
+			for( HwCommunicationNode pippo: nodesToExplore )	{
+				TraceManager.addDev( pippo.getName() );
+			}
+		}
+		else	{
+			TraceManager.addDev( "search for bridges connected to: " + startNode.getName() );
+			nodesToExplore = getBridgesConnectedToBus( commNodes, (HwBus) startNode );
+		}
+		//HwMemory memory = null;
+		TraceManager.addDev( "no of elements found: " + nodesToExplore.size() );
+		for( HwCommunicationNode currNode:nodesToExplore )	{
+			//memory = null;
+			if( busExploreMode ){
+				//memory = getMemConnectedToBusChannelMapped(commNodes, (HwBus)currNode, commElemToRoute);
+				if( isBusConnectedToNode(currNode, destNode) ){
+					TraceManager.addDev( currNode.getName() + " is last node");
+					path.add( currNode );
+					//if(memory!=null) path.add(memory);
+					commNodes.remove( currNode );
+					return true;
+				}
+			}
+			if( tmlmapping.isCommNodeMappedOn(commElemToRoute, currNode) )	{
+				TraceManager.addDev( currNode.getName() + " mapping found for " + commElemToRoute.getName( ));
+				path.add( currNode );
+				//if(memory!=null) path.add(memory);
+				commNodes.remove( currNode );
+				if(exploreBuses( depth+1, commNodes, path, currNode, destNode, commElemToRoute ) )	{
+					return true;
+				}
+				path.remove( currNode );
+				//if(memory!=null) path.remove(memory);
+				commNodes.add( currNode );
+			}
+		}
+		for( HwCommunicationNode currNode:nodesToExplore )	{
+			//if(busExploreMode) memory = getMemConnectedToBusChannelMapped(commNodes, (HwBus)currNode, commElemToRoute); else memory=null;
+			path.add( currNode );
+			//if(memory!=null) path.add(memory);
+			commNodes.remove( currNode );
+			//for (int i=0; i<path.size(); i++) System.out.print("  ");
+			//TraceManager.addDev(currNode.getName());
+			if( exploreBuses( depth+1, commNodes, path, currNode, destNode, commElemToRoute ) )	{
+				return true;
+			}
+			path.remove( currNode );
+			//if(memory!=null) path.remove(memory);
+			commNodes.add( currNode );	
+		}
+		return false;
+	}
+
+	private HwMemory getMemConnectedToBusChannelMapped(LinkedList<HwCommunicationNode> _commNodes, HwBus _bus, TMLElement _channel){
+		for(HwCommunicationNode commNode: _commNodes){
+			if(commNode instanceof HwMemory){
+				if(_bus!=null) System.out.println(commNode.getName() + " connected to bus " + _bus.getName() + ": " + tmlmapping.getTMLArchitecture().isNodeConnectedToBus(commNode, _bus));
+				System.out.println(_channel.getName() + " is mapped onto " + commNode.getName() + ": " + tmlmapping.isCommNodeMappedOn(_channel,commNode));
+				if((_bus==null || tmlmapping.getTMLArchitecture().isNodeConnectedToBus(commNode, _bus)) && tmlmapping.isCommNodeMappedOn(_channel,commNode)) return (HwMemory)commNode;
+			}
+		}
+		return null;
+	}
+
+	//Return the list of all buses in _commNodes that are connected to _node
+	private LinkedList<HwCommunicationNode> getBusesConnectedToNode( LinkedList<HwCommunicationNode> _commNodes, HwNode _node )	{
+
+		LinkedList<HwCommunicationNode> resultList = new LinkedList<HwCommunicationNode>();
+		for( HwCommunicationNode commNode: _commNodes )	{
+			if( commNode instanceof HwBus ){
+				if( tmlmapping.getTMLArchitecture().isNodeConnectedToBus( _node, (HwBus)commNode ) )	{
+					resultList.add((HwBus)commNode);
+				}
+			}
+		}
+		return resultList;
+	}
+
+	private LinkedList<HwCommunicationNode> getBridgesConnectedToBus(LinkedList<HwCommunicationNode> _commNodes, HwBus _bus){
+		LinkedList<HwCommunicationNode> resultList = new LinkedList<HwCommunicationNode>();
+		for(HwCommunicationNode commNode: _commNodes){
+			if(commNode instanceof HwBridge){
+				if(tmlmapping.getTMLArchitecture().isNodeConnectedToBus(commNode, _bus)) resultList.add((HwBridge)commNode);
+			}
+		}
+		return resultList;
+	}
+	
+	private boolean isBusConnectedToNode(HwCommunicationNode commNode, HwNode node){
+		for(HwLink link: tmlmapping.getTMLArchitecture().getHwLinks()) {
+			if(link.bus==commNode &&  link.hwnode==node) return true;
+		}
+		return false;
+	}
+
+	private String getIdentifierNameByID(int id){
+		
+		for(MappedSystemCTask task: tasks){
+			String tmp = task.getIdentifierNameByID(id);
+			if(tmp!=null) return tmp; 
+		}
+		return null;
+	}
+
+	/*private void generateEBRDDs(){
+		for(EBRDD ebrdd: ebrdds){
+			SystemCEBRDD newEbrdd = new SystemCEBRDD(ebrdd, tmlmodeling, tmlmapping);
+			newEbrdd.generateSystemC(debug);
+			systemCebrdds.add(newEbrdd);
+		}
+	}*/
+	
+	private void generateTaskFiles(String path) throws FileException {
+		for(MappedSystemCTask mst: tasks) {
+			mst.saveInFiles(path);
+		}
+		//for(SystemCEBRDD ebrdd: systemCebrdds) {
+		//	ebrdd.saveInFiles(path);
+		//}
+	}
+	
+	
+	public MappedSystemCTask getMappedTaskByName(String iName){
+		for(MappedSystemCTask task: tasks){
+			if(task.getTMLTask().getName().equals(iName)) return task;
+		}
+		return null;
+	}
+}
diff --git a/src/tmltranslator/tomappingsystemc3/idtypewrap.java b/src/tmltranslator/tomappingsystemc3/idtypewrap.java
new file mode 100644
index 0000000000000000000000000000000000000000..65e3245d88cada771dbab507dd1f11dad486978e
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/idtypewrap.java
@@ -0,0 +1,12 @@
+package tmltranslator.tomappingsystemc3;
+
+public class idtypewrap{
+	String id;
+	int type;
+	int nbOfIDs;
+	idtypewrap(int _type, String _id, int _nbOfIDs){
+		id=_id;
+		type=_type;
+		nbOfIDs=_nbOfIDs;
+	}
+}
diff --git a/src/tmltranslator/tomappingsystemc3/strwrap.java b/src/tmltranslator/tomappingsystemc3/strwrap.java
new file mode 100755
index 0000000000000000000000000000000000000000..9ed9b0c611b2f264bf8cc70de90b9dcc4fbc0cba
--- /dev/null
+++ b/src/tmltranslator/tomappingsystemc3/strwrap.java
@@ -0,0 +1,60 @@
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
+
+ludovic.apvrille AT telecom-paristech.fr
+andrea.enrici 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.
+
+/**
+ * Class TML2SystemC
+ * Creation: 01/06/2014
+ * @version 1.0 01/06/2014
+ * @author Andrea Enrici, Daniel Knorreck
+ * @see
+ */
+
+package tmltranslator.tomappingsystemc3;
+
+public class strwrap	{
+
+	String str;
+
+	strwrap( String iStr )	{
+		str = iStr;
+	}
+
+	strwrap(){
+		str = "";
+	}
+}	//End of class
diff --git a/src/ui/GTMLModeling.java b/src/ui/GTMLModeling.java
index 0a212d002d6ab3b7d2e58f515678ca523f117af2..5b5c0519e84029135e854c9e9846bc417173792e 100755
--- a/src/ui/GTMLModeling.java
+++ b/src/ui/GTMLModeling.java
@@ -54,12 +54,16 @@ import ui.tmlad.*;
 import ui.tmlcd.*;
 import ui.tmlcompd.*;
 import ui.tmldd.*;
+import ui.tmlcp.*;
 import tmltranslator.*;
+import tmltranslator.tmlcp.*;
 import myutil.*;
 
 public class GTMLModeling  {
 	private TMLDesignPanel tmldp;
 	private TMLComponentDesignPanel tmlcdp;
+	private TMLArchiPanel tmlap;
+	private TMLCommunicationPatternPanel tmlcpp;
 	private TMLModeling tmlm;
 	private Vector checkingErrors, warnings;
 	private LinkedList tasksToTakeIntoAccount;
@@ -69,7 +73,7 @@ public class GTMLModeling  {
 	private static CorrespondanceTGElement listE;
 	private Hashtable<String, String> table;
 	
-	private TMLArchiPanel tmlap;
+	
 	//private ArrayList<HwNode> nodesToTakeIntoAccount;
 	private LinkedList nodesToTakeIntoAccount;
 	TMLMapping map;
@@ -100,6 +104,14 @@ public class GTMLModeling  {
 			listE = new CorrespondanceTGElement();
 		}
 	}
+
+	public GTMLModeling( TMLCommunicationPatternPanel _tmlcpp, boolean resetList ) {
+		tmlcpp = _tmlcpp;
+        table = new Hashtable<String, String>();
+		if (resetList) {
+			listE = new CorrespondanceTGElement();
+		}
+	}
 	
 	public TMLModeling translateToTMLModeling(boolean _resetID) {
 		return translateToTMLModeling(false, _resetID);
@@ -1870,6 +1882,34 @@ public class GTMLModeling  {
 		
 		return map;
 	}
+
+	public TMLMapping translateToTMLCP() {
+
+		tmlm = new TMLModeling( true );
+		archi = new TMLArchitecture();
+		map = new TMLMapping( tmlm, archi, false );
+		
+		checkingErrors = new Vector();
+		warnings = new Vector();
+		//listE = new CorrespondanceTGElement();
+		
+		TraceManager.addDev( "Making Communication Pattern" );
+		makeCommunicationPattern();
+		/*TraceManager.addDev( "Making TML modeling" );
+		if (!makeTMLModeling()) {	//Attention, this routine will provoke errors...
+			return null;
+		}
+		TraceManager.addDev("Making mapping");
+		makeMapping();*/	//Attention this routine will provoke errors...
+		
+		//TraceManager.addDev("<--- TML modeling:");
+		//TraceManager.addDev("TML: " + tmlm.toString());
+		//TraceManager.addDev("End of TML modeling --->");
+		
+		removeActionsWithRecords();
+		
+		return map;
+	}
 	
 	private boolean nameInUse(ArrayList<String> _names, String _name) {
 		for(String s: _names) {
@@ -2080,6 +2120,130 @@ public class GTMLModeling  {
 			}
 		}
 	}
+
+	private void makeCommunicationPattern() {
+
+		TGComponent tgc;
+		TMLCPRefSD refSDnode;
+		CPRefSD refSD;
+		TMLCPRefCP refCPnode;
+		CPRefAD refCP;
+		ArrayList<String> names = new ArrayList<String>();
+		CPSequenceDiagram SD;
+		CPActivityDiagram AD;
+
+		if( nodesToTakeIntoAccount == null ) {
+			components = tmlcpp.tmlcpp.getComponentList();
+		}
+		else {
+			components = nodesToTakeIntoAccount;
+		}
+
+		ListIterator iterator = components.listIterator();
+		Vector<TDiagramPanel> panelList = tmlcpp.getPanels();
+
+		//TO BE DONE: For the main CP
+
+		for( int i = 0; i < components.size(); i++ ) {
+			tgc = (TGComponent)( components.get(i) );
+			TraceManager.addDev("Iteration: " + i + " testing " + tgc.getName() );
+			if( tgc instanceof TMLCPRefSD ) {
+				refSDnode = (TMLCPRefSD) tgc;
+				if( nameInUse( names, refSDnode.getName() ) ) {
+					// Node with the same name
+					CheckingError ce = new CheckingError( CheckingError.STRUCTURE_ERROR, "Two nodes have the same name: " + refSDnode.getName() );
+					ce.setTDiagramPanel( tmlcpp.tmlcpp );
+					ce.setTGComponent( refSDnode );
+					checkingErrors.add( ce );
+				}
+				else {
+					names.add( refSDnode.getName() );
+					String SDname = refSDnode.getName();
+					for( TDiagramPanel panel: panelList )	{
+						TraceManager.addDev("Testing panel: " + panel.getName() + " against SD ref " + SDname );
+						if( SDname.equals( panel.getName() ) )	{
+							TraceManager.addDev("Found match: " + panel.getName() );
+							LinkedList elemList = panel.getComponentList();
+							TraceManager.addDev("Lenght of elements: " + elemList.size() );
+							for( int j = 0; j < elemList.size(); j++ )	{
+								TGComponent elem = (TGComponent) elemList.get(j);
+								TraceManager.addDev( elem.getName() );
+							}
+							break;
+						}
+					}
+				}
+			}
+			if( tgc instanceof TMLCPRefCP ) {
+				refCPnode = (TMLCPRefCP) tgc;
+				if( nameInUse( names, refCPnode.getName() ) ) {
+					// Node with the same name
+					CheckingError ce = new CheckingError(CheckingError.STRUCTURE_ERROR, "Two nodes have the same name: " + refCPnode.getName());
+					ce.setTDiagramPanel( tmlcpp.tmlcpp );
+					ce.setTGComponent( refCPnode );
+					checkingErrors.add( ce );
+				}
+				else {
+					names.add( refCPnode.getName() );
+					String CPname = refCPnode.getName();
+					for( TDiagramPanel panel: panelList )	{
+						TraceManager.addDev("Testing panel: " + panel.getName() + " against AD ref" + CPname );
+						if( CPname.equals( panel.getName() ) )	{
+							TraceManager.addDev("Found match: " + panel.getName() );
+							LinkedList elemList = panel.getComponentList();
+							TraceManager.addDev("Lenght of elements: " + elemList.size() );
+							for( int k = 0; k < elemList.size(); k++ )	{
+								TGComponent elem = (TGComponent) elemList.get(k);
+								TraceManager.addDev( elem.getName() );
+							}
+							break;
+						}
+					}
+				}
+			}
+		}
+	}
+		
+		// Links between nodes
+		/*TGComponent tgc1, tgc2;
+		TGConnectingPoint p1, p2;
+		TMLArchiConnectorNode connector;
+		HwLink hwlink;
+		HwNode originNode;
+		
+		iterator = tmlap.tmlap.getComponentList().listIterator();
+		while(iterator.hasNext()) {
+			tgc = (TGComponent)(iterator.next());
+			if (tgc instanceof TMLArchiConnectorNode) {
+				//TraceManager.addDev("Found link");
+				connector = (TMLArchiConnectorNode)tgc;
+				tgc1 = null; tgc2 = null;
+				p1 = connector.getTGConnectingPointP1();
+				p2 = connector.getTGConnectingPointP2();
+				tgc1 = tgc.getTDiagramPanel().getComponentToWhichBelongs(p1);
+				tgc2 = tgc.getTDiagramPanel().getComponentToWhichBelongs(p2);
+				if ((tgc1 != null) && (tgc2 != null)) {
+					//TraceManager.addDev("Not null");
+					if (components.contains(tgc1) && components.contains(tgc2)) {
+						//TraceManager.addDev("Getting closer");
+						if (tgc2 instanceof TMLArchiBUSNode) {
+							originNode = listE.getHwNode(tgc1);
+							bus  = (HwBus)(listE.getHwNode(tgc2));
+							if ((originNode != null) && (bus != null)) {
+								hwlink = new HwLink("link_" +originNode.getName() + "_to_" + bus.getName());
+								hwlink.setPriority(connector.getPriority());
+								hwlink.bus = bus;
+								hwlink.hwnode = originNode;
+								listE.addCor(hwlink, connector);
+								archi.addHwLink(hwlink);
+								//TraceManager.addDev("Link added");
+							}
+						}
+					}
+				}
+			}
+		}
+	}*/
 	
 	private boolean makeTMLModeling() {
 		// Determine all TML Design to be used -> TMLDesignPanels
diff --git a/src/ui/GTURTLEModeling.java b/src/ui/GTURTLEModeling.java
index fec964b8306e744ccee8d3bc4df1b139291d8001..0bb6dd46e6af650f2ff7dd54c1c8d43031fd4e50 100755
--- a/src/ui/GTURTLEModeling.java
+++ b/src/ui/GTURTLEModeling.java
@@ -1,6 +1,7 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
  *
- * ludovic.apvrille AT enst.fr
+ * ludovic.apvrille AT telecom-paristech.fr
+ * andrea.enrici 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
@@ -38,7 +39,8 @@
  * /**
  * Class GTURTLEModeling
  * Creation: 09/12/2003
- * @author Ludovic APVRILLE
+ * Version: 1.1 02/06/2014
+ * @author Ludovic APVRILLE, Andrea ENRICI
  * @see
  */
 
@@ -393,23 +395,37 @@ public class GTURTLEModeling {
 		}
 	}
 	
-	public boolean generateTMLTxt(String _title) {
-		if (tmap == null) {
-			TMLTextSpecification spec = new TMLTextSpecification(_title);
-			spec.toTextFormat(tmlm);
+	public boolean generateTMLTxt( String _title ) {
+
+		//TO DO: make a third branch for the syntax checking from the CP panel
+
+		//This branch is activated if doing the syntax check from the application panel
+		if( tmap == null ) {
+			TMLTextSpecification spec = new TMLTextSpecification( _title );
+			spec.toTextFormat( tmlm );	//TMLModeling
+			TMLCPTextSpecification specCP = new TMLCPTextSpecification( _title );
+			specCP.toTextFormat( tmlm );	//TMLCP
 			try {
-				spec.saveFile(ConfigurationTTool.TMLCodeDirectory + File.separator, "spec.tml");
-			} catch (Exception e) {
-				TraceManager.addError("File could not be saved: " + e.getMessage());
+				spec.saveFile( ConfigurationTTool.TMLCodeDirectory + File.separator, "spec.tml" );
+				specCP.saveFile( ConfigurationTTool.TMLCodeDirectory + File.separator, "spec.tmlcp" );
+			}
+			catch( Exception e ) {
+				TraceManager.addError( "File could not be saved: " + e.getMessage() );
 				return false;
 			}
-		} else {
-			TMLMappingTextSpecification spec = new TMLMappingTextSpecification(_title);
-			spec.toTextFormat(tmap);
+		}
+		//This branch is activated if doing the syntax check from the architecture panel, regardless the presence of mapping artifacts
+		else {
+			TMLMappingTextSpecification spec = new TMLMappingTextSpecification( _title );
+			spec.toTextFormat( tmap );	//TMLMapping
+			TMLCPTextSpecification specCP = new TMLCPTextSpecification( _title );
+			specCP.toTextFormat( tmap );	//TMLCP
 			try {
-				spec.saveFile(ConfigurationTTool.TMLCodeDirectory + File.separator, "spec");
-			} catch (Exception e) {
-				TraceManager.addError("Files could not be saved: " + e.getMessage());
+				spec.saveFile( ConfigurationTTool.TMLCodeDirectory + File.separator, "spec" );
+				specCP.saveFile( ConfigurationTTool.TMLCodeDirectory + File.separator, "spec.tmlcp" );
+			}
+			catch( Exception e ) {
+				TraceManager.addError( "Files could not be saved: " + e.getMessage() );
 				return false;
 			}
 		}
@@ -6117,7 +6133,7 @@ public class GTURTLEModeling {
 		GTMLModeling gtmlm = new GTMLModeling(tmlap, true);
 		
 		
-		gtmlm.setNodes(nodesToTakeIntoAccount);
+		gtmlm.setNodes(nodesToTakeIntoAccount);	//simply transforms the parameter from a Vector to LinkedList
 		tmlm = null;
 		tm = null;
 		tmState = 1;
@@ -6143,6 +6159,41 @@ public class GTURTLEModeling {
 			return true;
 		}
 	}
+
+	//Newly introduced to perform Syntax check of CP diagrams
+	public boolean checkSyntaxTMLMapping( Vector nodesToTakeIntoAccount, TMLCommunicationPatternPanel tmlcpp, boolean optimize ) {
+
+		ArrayList<TMLError> warningsOptimize = new ArrayList<TMLError>();		
+		warnings = new Vector();
+		mgui.setMode( MainGUI.VIEW_SUGG_DESIGN_KO );
+		//TraceManager.addDev("New TML Mapping");
+		GTMLModeling gtmlm = new GTMLModeling( tmlcpp, true );
+		
+		gtmlm.setNodes( nodesToTakeIntoAccount );	//simply transforms the parameter from a Vector to LinkedList
+		tmlm = null;
+		tm = null;
+		tmState = 1;
+		tmap = gtmlm.translateToTMLCP();
+		listE = gtmlm.getCorrespondanceTable();
+		checkingErrors = gtmlm.getCheckingErrors();
+		
+		if( (checkingErrors != null) && (checkingErrors.size() > 0) )	{
+			analyzeErrors();
+			warnings = gtmlm.getCheckingWarnings();
+			return false;
+		}
+		else {
+			//tmap.removeAllRandomSequences();
+			if( optimize )	{
+				warningsOptimize = tmap.optimize();
+			}
+			warnings.addAll( convertToCheckingErrorTMLErrors(warningsOptimize, tmlcpp.tmlcpp ) );
+			mgui.resetAllDIPLOIDs();
+			listE.useDIPLOIDs();
+			mgui.setMode( MainGUI.GEN_DESIGN_OK );
+			return true;
+		}
+	}
 	
 	public boolean translateTMLMapping(boolean _sample, boolean _channel, boolean _event, boolean _request, boolean _exec, boolean _busTransfers, boolean _scheduling, boolean _taskState, boolean _channelState, boolean _branching, boolean _terminateCPU, boolean _terminateCPUs, boolean _clocked, String _tickValue, boolean _endClocked, boolean _countTick, boolean _maxCountTick, String _maxCountTickValue, boolean _randomTask) {
 		//TraceManager.addDev("TML=" + tmap.toString());
diff --git a/src/ui/MainGUI.java b/src/ui/MainGUI.java
index a44dbcc0fc3173daa50292e66147056329ac48d7..a8b5082a85e89b9034dba355d5fd92b662d0da39 100755
--- a/src/ui/MainGUI.java
+++ b/src/ui/MainGUI.java
@@ -982,7 +982,7 @@ public	class MainGUI implements ActionListener, WindowListener, KeyListener, Per
             index = tabs.size();
         }
         TMLCommunicationPatternPanel tmlcpp = new TMLCommunicationPatternPanel(this);
-        tabs.add(index, tmlcpp); // should look for the first
+        tabs.add( index, tmlcpp ); // should look for the first
         //mainTabbedPane.addTab(name, IconManager.imgic17, ap.tabbedPane, "Opens analysis diagrams");
         mainTabbedPane.add(tmlcpp.tabbedPane, index);
         mainTabbedPane.setToolTipTextAt(index, "Open CP diagrams");
@@ -3167,7 +3167,48 @@ public	class MainGUI implements ActionListener, WindowListener, KeyListener, Per
 					}
 				}
             }
-        } else if (tp instanceof RequirementPanel) {
+        }
+				else if( tp instanceof TMLCommunicationPatternPanel ) {
+					TMLCommunicationPatternPanel tmlcpp = (TMLCommunicationPatternPanel) tp;
+          JDialogSelectCPDiagrams.validated =  tmlcpp.validated;
+          JDialogSelectCPDiagrams.ignored =  tmlcpp.ignored;
+          Vector tmlDiagramsToValidate = new Vector();
+          JDialogSelectCPDiagrams jdscpd = new JDialogSelectCPDiagrams( frame, tmlDiagramsToValidate, tmlcpp.tmlcpp.getComponentList(),
+																														"Choosing Diagrams to validate" );
+					if( !automatic ) {
+						GraphicLib.centerOnParent( jdscpd );
+						jdscpd.setVisible( true ); // Blocked until dialog has been closed
+					}
+					else {
+						jdscpd.closeDialog();
+					}
+					//tmlcpp.tmlcpp.setMasterClockFrequency(jdstmln.getClock());
+			    if( tmlDiagramsToValidate.size() > 0 ) {
+						tmlcpp.validated = JDialogSelectCPDiagrams.validated;
+						tmlcpp.ignored = JDialogSelectCPDiagrams.ignored;
+						TraceManager.addDev("Ready to generate TML mapping for Communication Patterns!");
+						b = gtm.checkSyntaxTMLMapping( tmlDiagramsToValidate, tmlcpp, jdscpd.getOptimize() );
+						if( b ) {
+							//setMode(MainGUI.MODEL_OK);
+							setMode( MainGUI.GEN_SYSTEMC_OK );
+							setMode( MainGUI.MODEL_OK );
+							ret = true;
+							if( !automatic ) {
+								JOptionPane.showMessageDialog( frame, "0 error, " + getCheckingWarnings().size() +
+								" warning(s). You can now generate a formal (LOTOS, RT-LOTOS) specification or executable code (systemC)",
+								"Syntax analysis successful on TML mapping",
+								JOptionPane.INFORMATION_MESSAGE );
+							}
+						}
+						else {
+							if( !automatic ) {
+								JOptionPane.showMessageDialog( frame, "The TML mapping contains several errors", "Syntax analysis failed",
+																								JOptionPane.INFORMATION_MESSAGE );
+							}
+						}
+          }
+        }
+				else if( tp instanceof RequirementPanel ) {
             TDiagramPanel tdp = getCurrentTDiagramPanel();
             if (!(tdp instanceof RequirementDiagramPanel)) {
 				if (tdp instanceof EBRDDPanel) {
@@ -6575,6 +6616,29 @@ public	class MainGUI implements ActionListener, WindowListener, KeyListener, Per
         }
         changeMade(null, -1);
     }
+
+/*    public void requestRenameTab( int index, String s )	{
+
+			String oldName = mainTabbedPane.getTitleAt(index);
+        if ((s != null) && (s.length() > 0)){
+            // name already in use?
+			if (s.compareTo(oldName) != 0) {
+				if (isAValidTabName(s)) {
+					mainTabbedPane.setTitleAt(index, s);
+					changeMade(getCurrentTDiagramPanel(), ((TURTLEPanel)(tabs.elementAt(index))).tdp.MOVE_COMPONENT);
+					
+					TURTLEPanel tp = (TURTLEPanel)(tabs.elementAt(index));
+					if ((tp instanceof TMLDesignPanel) || (tp instanceof TMLComponentDesignPanel)) {
+						renameMapping(oldName, s);
+					}
+				} else {
+					JOptionPane.showMessageDialog(frame, "Invalid name", "Error", JOptionPane.INFORMATION_MESSAGE);
+				}
+				
+			}
+        }
+        changeMade(null, -1);
+    }*/
 	
 	public void renameMapping(String oldName, String newName) {
 		TURTLEPanel tp;
diff --git a/src/ui/TGUIAction.java b/src/ui/TGUIAction.java
index 380db20d3dbfe76cecdff5e2795de3124ed8449f..b6cd6b92ad44b07260ffa44213f1085f4f72347c 100755
--- a/src/ui/TGUIAction.java
+++ b/src/ui/TGUIAction.java
@@ -879,7 +879,7 @@ public class TGUIAction extends AbstractAction {
         actions[TMLCP_JUNCTION] = new TAction("add-tmlcp-junction", "Add Junction", IconManager.imgic212, IconManager.imgic212, "Junction", "Add a junction with three inputs to the currently opened communication pattern diagram", 0);
         
         actions[TMLSD_EDIT] = new TAction("edit-tmlsd-diagram", "Edit CP-SD diagram", IconManager.imgic100, IconManager.imgic101, "Edit The sequence diagram of  communication patterns", "Make it possible to edit the currently opened communication pattern sequence diagram", 0);
-        actions[TMLSD_MESSAGE_ASYNC] = new TAction("add-tmlsd-messageasync", "Add async msg", IconManager.imgic202, IconManager.imgic202, "Asynchonous msg", "Add an asynchronous message between two components of the currently opened communication pattern sequence diagram", 0);
+        actions[TMLSD_MESSAGE_ASYNC] = new TAction("add-tmlsd-messageasync", "Add async msg", IconManager.imgic202, IconManager.imgic202, "Asynchronous msg", "Add an asynchronous message between two components of the currently opened communication pattern sequence diagram", 0);
         actions[TMLSD_INSTANCE] = new TAction("add-instance-tmlsd", "Instance", IconManager.imgic500, IconManager.imgic500, "Instance", "Add an instance to the currently opened communication pattern sequence diagram", 0);
         actions[TMLSD_ACTION_STATE] = new TAction("add-action-tmlsd", "Action state", IconManager.imgic512, IconManager.imgic512, "Action state", "Add an action state to the currently opened communication pattern sequence diagram", 0);
         
diff --git a/src/ui/TMLCommunicationPatternPanel.java b/src/ui/TMLCommunicationPatternPanel.java
index ffbc218e1a710fcdc39d94ed2cf07c7810df1d2a..22e3f804d80b40f09fe65090442a8a4805e1fd78 100755
--- a/src/ui/TMLCommunicationPatternPanel.java
+++ b/src/ui/TMLCommunicationPatternPanel.java
@@ -60,6 +60,7 @@ import myutil.*;
 
 public class TMLCommunicationPatternPanel extends TURTLEPanel {
     public TMLCPPanel tmlcpp;
+		public Vector validated, ignored;
     
     public TMLCommunicationPatternPanel(MainGUI _mgui) {
         super(_mgui);
@@ -99,31 +100,46 @@ public class TMLCommunicationPatternPanel extends TURTLEPanel {
         //jsp.setVisible(true);
     }
     
-    public boolean addCPSequenceDiagram(String s) {
-        JPanel toolBarPanel = new JPanel();
-        toolBarPanel.setLayout(new BorderLayout());
+    public boolean addCPSequenceDiagram( String s ) {
+
+    	JPanel toolBarPanel = new JPanel();
+      toolBarPanel.setLayout( new BorderLayout() );
         
-        TMLSDToolBar toolBarSequence	= new TMLSDToolBar(mgui);
-        toolbars.add(toolBarSequence);
+      TMLSDToolBar toolBarSequence	= new TMLSDToolBar( mgui );
+      toolbars.add( toolBarSequence );
         
-        TMLSDPanel sdp = new TMLSDPanel(mgui, toolBarSequence);
-        sdp.setName(s);
-        sdp.tp = this;
-        panels.add(sdp);
-        JScrollDiagramPanel jsp	= new JScrollDiagramPanel(sdp);
-        sdp.jsp = jsp;
-        jsp.setWheelScrollingEnabled(true);
-        jsp.getVerticalScrollBar().setUnitIncrement(mgui.INCREMENT);
-        toolBarPanel.add(toolBarSequence, BorderLayout.NORTH);
-        toolBarPanel.add(jsp, BorderLayout.CENTER);
-        tabbedPane.addTab(s, IconManager.imgic18, toolBarPanel, "Open the communication pattern sequence diagram of " + s);
-        //tabbedPane.setVisible(true);
-        //sdp.setVisible(true);
-        //jsp.setVisible(true);
-        //tabbedPane.setSelectedIndex(panels.size()-1);
-        
-        return true;
+      TMLSDPanel sdp = new TMLSDPanel( mgui, toolBarSequence );
+      sdp.setName( s );
+      sdp.tp = this;
+      panels.add( sdp );
+      JScrollDiagramPanel jsp	= new JScrollDiagramPanel( sdp );
+      sdp.jsp = jsp;
+      jsp.setWheelScrollingEnabled( true );
+      jsp.getVerticalScrollBar().setUnitIncrement( mgui.INCREMENT );
+      toolBarPanel.add(toolBarSequence, BorderLayout.NORTH );
+      toolBarPanel.add( jsp, BorderLayout.CENTER );
+      tabbedPane.addTab( s, IconManager.imgic18, toolBarPanel, "Open the communication pattern sequence diagram of " + s );
+
+//			Vector<TDiagramPanel> panelList = tmlcpp.getPanels();
+			/*TDiagramPanel mainCP = panels.get( 0 );	//get the Main CP
+			TraceManager.addDev( mainCP.getName() );
+			LinkedList mainCPelems = mainCP.getComponentList();
+			for( int i = 0; i < mainCPelems.size(); i++ )	{
+				TGComponent elem = (TGComponent) mainCPelems.get(i);
+				TraceManager.addDev( elem.getName() );
+				if( elem instanceof TMLCPRefSD && s.equals(elem.getName()) )	{
+					TMLCPRefSD cpRefSD = (TMLCPRefSD) mainCPelems.get(i);
+					cpRefSD.setReferenceToSD( sdp );
+					//cpRefSD.setIndex( i );
+					TraceManager.addDev( "Found and added the reference" );
+				}
+			}*/
+      //tabbedPane.setVisible(true);
+      //sdp.setVisible(true);
+      //jsp.setVisible(true);
+      //tabbedPane.setSelectedIndex(panels.size()-1);
         
+      return true;
     }
     
 	public boolean addCPDiagram(String s) {
@@ -137,7 +153,7 @@ public class TMLCommunicationPatternPanel extends TURTLEPanel {
         tmlcppNew.setName(s);
         tmlcppNew.tp = this;
         tdp = tmlcppNew;
-        panels.add(tmlcppNew);
+        panels.add( tmlcppNew );
         JScrollDiagramPanel jsp	= new JScrollDiagramPanel(tmlcppNew);
         tmlcppNew.jsp = jsp;
         jsp.setWheelScrollingEnabled(true);
@@ -150,9 +166,6 @@ public class TMLCommunicationPatternPanel extends TURTLEPanel {
 		
     }
     
-   
-    
-	
     public String saveHeaderInXml() {
         return "<Modeling type=\"TML CP\" nameTab=\"" + mgui.getTabName(this) + "\" >\n";
     }
@@ -184,4 +197,4 @@ public class TMLCommunicationPatternPanel extends TURTLEPanel {
         return true;
     }  
     
-}
\ No newline at end of file
+}
diff --git a/src/ui/TURTLEPanel.java b/src/ui/TURTLEPanel.java
index e5141e2d43f115f20c0039edb0c6a6bff5401cf8..ebd90b966bd857f132777b5043c626fda8943680 100755
--- a/src/ui/TURTLEPanel.java
+++ b/src/ui/TURTLEPanel.java
@@ -158,6 +158,10 @@ public abstract class TURTLEPanel implements GenericTree {
         }
         return panels.size();
     }
+
+	public Vector<TDiagramPanel> getPanels()	{
+		return panels;
+	}
     
     public boolean nameInUse(String s) {
         for(int i = 0; i<tabbedPane.getTabCount(); i++) {
@@ -355,10 +359,3 @@ public abstract class TURTLEPanel implements GenericTree {
 	
     
 }
-
-
-
-
-
-
-
diff --git a/src/ui/iod/IODRefSD.java b/src/ui/iod/IODRefSD.java
index 310705ef181aa17364f5096ed36eff8cdef7ff45..28d853ee2bc6e9a2e394c094d86ea94c07b1c909 100755
--- a/src/ui/iod/IODRefSD.java
+++ b/src/ui/iod/IODRefSD.java
@@ -1,6 +1,7 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
 
-ludovic.apvrille AT enst.fr
+ludovic.apvrille AT telecom-paristech.fr
+andrea.enrici 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 
@@ -59,7 +60,7 @@ public class IODRefSD extends TGCOneLineText {
     protected int textX =  5;
     protected int textY =  15;
     protected int arc = 5;
-    
+
     public IODRefSD(int _x, int _y, int _minX, int _maxX, int _minY, int _maxY, boolean _pos, TGComponent _father, TDiagramPanel _tdp)  {
         super(_x, _y, _minX, _maxX, _minY, _maxY, _pos, _father, _tdp);
         
@@ -159,4 +160,21 @@ public class IODRefSD extends TGCOneLineText {
 	public int getDefaultConnector() {
       return TGComponentManager.CONNECTOR_INTERACTION;
     }
-}
\ No newline at end of file
+
+	/*public boolean editOndoubleClick(JFrame frame) {
+		
+		//System.out.println("Double click");
+     String text = getName() + ": ";
+    if( hasFather() ) {
+			text = getTopLevelName() + " / " + text;
+    }
+    String s = (String) JOptionPane.showInputDialog(frame, text,
+		"Setting Name", JOptionPane.PLAIN_MESSAGE, IconManager.imgic100,
+			null, getName() );
+    if( (s != null) && (s.length() > 0) )	{
+			setName(s);
+			return true;
+		}
+    return false;
+    }*/
+}
diff --git a/src/ui/tmlcp/TMLCPPanel.java b/src/ui/tmlcp/TMLCPPanel.java
index a43223ea7c92c545a6404ece36131e49393a53bb..6010937cb9d4fb31f5dc0a9d4675a751edddacf2 100755
--- a/src/ui/tmlcp/TMLCPPanel.java
+++ b/src/ui/tmlcp/TMLCPPanel.java
@@ -277,10 +277,3 @@ public class TMLCPPanel extends TDiagramPanel {
 	}
    
 }
-
-
-
-
-
-
-
diff --git a/src/ui/tmlcp/TMLCPRefCP.java b/src/ui/tmlcp/TMLCPRefCP.java
index 730773d494b48c354d86eaba6447a6794fa1acc0..7010474be4de370031b82da3915c6396c601aeb5 100755
--- a/src/ui/tmlcp/TMLCPRefCP.java
+++ b/src/ui/tmlcp/TMLCPRefCP.java
@@ -1,6 +1,7 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
  *
- * ludovic.apvrille AT enst.fr
+ * ludovic.apvrille AT telecom-paristech.fr
+ * andrea.enrici 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
@@ -37,10 +38,10 @@
  *
  * /**
  * Class TMLCPRefCP
- * Reference to a communication pattern from another communication pattern
+ * Reference to an Activity Diagram from another Activity Diagram (including the main communication pattern)
  * Creation: 17/02/2014
  * @version 1.0 17/02/2014
- * @author Ludovic APVRILLE
+ * @author Ludovic APVRILLE, Andrea ENRICI
  * @see
  */
 
@@ -78,8 +79,8 @@ public class TMLCPRefCP extends TGCOneLineText {
         editable = true;
         removable = true;
         
-        value = "ref to a cp";
-        name = "Reference to a CP";
+        value = "Reference to a CP";
+        name = "ActivityDiagram";
         
         myImageIcon = IconManager.imgic400;
     }
@@ -105,7 +106,7 @@ public class TMLCPRefCP extends TGCOneLineText {
         g.drawLine(x+(width/2), y, x+(width/2), y - lineLength);
         g.drawLine(x+(width/2), y+height, x+(width/2), y + lineLength + height);
         
-        g.drawString(value, x + (width - w) / 2, y + textY + 15);
+        g.drawString(name, x + (width - w) / 2, y + textY + 15);
         g.drawString("iod", x+3, y+12);
         g.drawLine(x, y+15, x+15, y+15);
         g.drawLine(x+25, y, x+25, y+8);
@@ -135,32 +136,52 @@ public class TMLCPRefCP extends TGCOneLineText {
         return TGComponentManager.TMLCP_REF_CP;
     }
     
-    public void addActionToPopupMenu(JPopupMenu componentMenu, ActionListener menuAL, int x, int y) {
-        componentMenu.addSeparator();
-        boolean b = ((TMLCPPanel)tdp).isTMLCPCreated(value);
-        JMenuItem isCPCreated;
+    public void addActionToPopupMenu( JPopupMenu componentMenu, ActionListener menuAL, int x, int y ) {
+
+      componentMenu.addSeparator();
+      boolean b = ( (TMLCPPanel)tdp ).isTMLCPCreated( name );
+      JMenuItem isCPCreated;
         
-        if (b) {
-            isCPCreated = new JMenuItem("Open diagram");
-        } else {
-            isCPCreated = new JMenuItem("Create communication pattern");
-        }
+      if( b ) {
+				isCPCreated = new JMenuItem("Open diagram");
+      }
+			else {
+          isCPCreated = new JMenuItem("Create communication pattern");
+      }
         
-        isCPCreated.addActionListener(menuAL);
-        componentMenu.add(isCPCreated);
+			isCPCreated.addActionListener( menuAL );
+      componentMenu.add( isCPCreated );
     }
     
-    public boolean eventOnPopup(ActionEvent e) {
-        boolean b = ((TMLCPPanel)tdp).isTMLCPCreated(value);
-        if (b) {
-            ((TMLCPPanel)tdp).openTMLCPDiagram(value);
-        } else {
-            ((TMLCPPanel)tdp).createTMLCPDiagram(value);
-        }
-        return true;
+    public boolean eventOnPopup( ActionEvent e ) {
+
+			boolean b = ( (TMLCPPanel)tdp ).isTMLCPCreated( name );
+      if (b) {
+				( (TMLCPPanel)tdp ).openTMLCPDiagram( name );
+      }
+			else {
+				( (TMLCPPanel)tdp ).createTMLCPDiagram( name );
+      }
+      return true;
     }
 	
 	public int getDefaultConnector() {
       return TGComponentManager.CONNECTOR_TMLCP;
     }
-}
\ No newline at end of file
+
+	@Override public boolean editOndoubleClick( JFrame frame ) {
+		
+		//System.out.println("Double click");
+     String text = "Reference to AD: ";
+    if( hasFather() ) {
+			text = getTopLevelName() + " / " + text;
+    }
+    String s = (String) JOptionPane.showInputDialog(frame, text,
+		"Setting Name", JOptionPane.PLAIN_MESSAGE, IconManager.imgic100, null, getName() );
+    if( (s != null) && (s.length() > 0) )	{
+			setName(s);
+			return true;
+		}
+    return false;
+    }
+}
diff --git a/src/ui/tmlcp/TMLCPRefSD.java b/src/ui/tmlcp/TMLCPRefSD.java
index 047abfdb9f7adf24c0c7be18f190a51d29fac9e5..f84950b12d40dc931b42e61184d6a64311676607 100755
--- a/src/ui/tmlcp/TMLCPRefSD.java
+++ b/src/ui/tmlcp/TMLCPRefSD.java
@@ -54,12 +54,16 @@ import javax.swing.*;
 import myutil.*;
 import ui.*;
 
+import ui.tmlsd.*;
+
 public class TMLCPRefSD extends TGCOneLineText {
     protected int lineLength = 5;
     protected int textX =  5;
     protected int textY =  15;
     protected int arc = 5;
-    
+		private TMLSDPanel refToSD;
+		//private int index = 0;
+
     public TMLCPRefSD(int _x, int _y, int _minX, int _maxX, int _minY, int _maxY, boolean _pos, TGComponent _father, TDiagramPanel _tdp)  {
         super(_x, _y, _minX, _maxX, _minY, _maxY, _pos, _father, _tdp);
         
@@ -77,10 +81,10 @@ public class TMLCPRefSD extends TGCOneLineText {
         moveable = true;
         editable = true;
         removable = true;
-        
-        value = "Scenario";
-        name = "Reference to a SD";
-        
+        value = "Reference to a SD";
+        name = "SequenceDiagram";
+				refToSD = null;
+
         myImageIcon = IconManager.imgic400;
     }
     
@@ -103,7 +107,7 @@ public class TMLCPRefSD extends TGCOneLineText {
         g.drawLine(x+(width/2), y, x+(width/2), y - lineLength);
         g.drawLine(x+(width/2), y+height, x+(width/2), y + lineLength + height);
         
-        g.drawString(value, x + (width - w) / 2, y + textY + 15);
+        g.drawString(name, x + (width - w) / 2, y + textY + 15);
         g.drawString("sd", x+3, y+12);
         g.drawLine(x, y+15, x+15, y+15);
         g.drawLine(x+25, y, x+25, y+8);
@@ -131,32 +135,65 @@ public class TMLCPRefSD extends TGCOneLineText {
         return TGComponentManager.TMLCP_REF_SD;
     }
     
-    public void addActionToPopupMenu(JPopupMenu componentMenu, ActionListener menuAL, int x, int y) {
-        componentMenu.addSeparator();
-        boolean b = ((TMLCPPanel)tdp).isTMLCPSDCreated(value);
-        JMenuItem isSDCreated;
+    public void addActionToPopupMenu( JPopupMenu componentMenu, ActionListener menuAL, int x, int y ) {
+			
+			componentMenu.addSeparator();
+      boolean b = ((TMLCPPanel)tdp).isTMLCPSDCreated( name );
+      JMenuItem isSDCreated;
         
-        if (b) { 
-            isSDCreated = new JMenuItem("Open diagram");
-        } else {
-            isSDCreated = new JMenuItem("Create sequence diagram");
-        }
+      if( b )	{ 
+				isSDCreated = new JMenuItem("Open diagram");
+			}
+			else	{
+				isSDCreated = new JMenuItem( "Create sequence diagram" );
+      }
         
-        isSDCreated.addActionListener(menuAL);
-        componentMenu.add(isSDCreated);
+      isSDCreated.addActionListener( menuAL );
+      componentMenu.add( isSDCreated );
     }
     
     public boolean eventOnPopup(ActionEvent e) {
-        boolean b = ((TMLCPPanel)tdp).isTMLCPSDCreated(value);
-        if (b) {
-            ((TMLCPPanel)tdp).openTMLCPSequenceDiagram(value);
-        } else {
-            ((TMLCPPanel)tdp).createTMLCPSequenceDiagram(value);
-        }   
-        return true;
+
+			boolean b = ((TMLCPPanel)tdp).isTMLCPSDCreated( name );
+      if( b )	{
+				( (TMLCPPanel)tdp ).openTMLCPSequenceDiagram( name );
+      }
+			else {
+				( (TMLCPPanel)tdp ).createTMLCPSequenceDiagram( name );
+			}   
+      return true;
     }
 	
 	public int getDefaultConnector() {
       return TGComponentManager.CONNECTOR_TMLCP;
     }
-}
\ No newline at end of file
+
+	/*public void setReferenceToSD( TMLSDPanel _panel )	{
+		refToSD = _panel;
+	}*/
+
+	@Override public boolean editOndoubleClick(JFrame frame) {
+		
+		//System.out.println("Double click");
+     String text = "Reference to a SD: ";
+    if( hasFather() ) {
+			text = getTopLevelName() + " / " + text;
+    }
+    String s = (String) JOptionPane.showInputDialog(frame, text,
+		"Setting Name", JOptionPane.PLAIN_MESSAGE, IconManager.imgic100, null, getName() );
+    if( (s != null) && (s.length() > 0) )	{
+			setName(s);
+			/*if( refToSD != null )	{
+				TraceManager.addDev( "About to change the name of the Diag" );
+				refToSD.setName(s);
+				//refToSD.changeName( index, s );
+			}*/
+			return true;
+		}
+    return false;
+    }
+
+	/*public void setIndex( int i )	{
+		index = i;
+	}*/
+}	//End of Class
diff --git a/src/ui/tmlcp/TMLCPToolBar.java b/src/ui/tmlcp/TMLCPToolBar.java
index 9cec52192c00eb7572442a6ba76f0e9112f69f7b..a44cdb33a0cdae73e4b71fc735eb6a14e043a0e4 100755
--- a/src/ui/tmlcp/TMLCPToolBar.java
+++ b/src/ui/tmlcp/TMLCPToolBar.java
@@ -1,6 +1,7 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
 
-ludovic.apvrille AT enst.fr
+ludovic.apvrille AT telecom-paristech.fr
+andrea.enrici 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 
@@ -39,8 +40,8 @@ knowledge of the CeCILL license and that you accept its terms.
  * Class TMLCPToolBar
  * Implements the toolbar to be used in conjunction with the panel of an interaction overview diagram
  * Creation: 29/09/2004
- * @version 1.0 29/09/2004
- * @author Ludovic APVRILLE
+ * @version 1.1 02/06/2014
+ * @author Ludovic APVRILLE, Andrea ENRICI
  * @see TClassDiagramPanel
  */
 
@@ -77,6 +78,7 @@ public class TMLCPToolBar extends TToolBar {
 		mgui.actions[TGUIAction.ACT_ZOOM_MORE].setEnabled(false);
 		mgui.actions[TGUIAction.ACT_ZOOM_LESS].setEnabled(false);
 		mgui.actions[TGUIAction.ACT_SHOW_ZOOM].setEnabled(false);
+		mgui.actions[TGUIAction.ACT_MODEL_CHECKING].setEnabled(b);
 		mgui.updateZoomInfo();
         
     }
diff --git a/src/ui/tmldd/TMLArchiDiagramToolBar.java b/src/ui/tmldd/TMLArchiDiagramToolBar.java
index b95bdc2eb213691f59258d7aff215397979bba30..6062fd2a303519a52dbb04ea778c860600353172 100755
--- a/src/ui/tmldd/TMLArchiDiagramToolBar.java
+++ b/src/ui/tmldd/TMLArchiDiagramToolBar.java
@@ -150,8 +150,3 @@ public class TMLArchiDiagramToolBar extends TToolBar {
     }
     
 } // Class
-
-
-
-
-
diff --git a/src/ui/tmlsd/TGConnectorMessageTMLSD.java b/src/ui/tmlsd/TGConnectorMessageTMLSD.java
index 1a9c68ea16793cb4bfd500900c6b8c8de4f7f5af..bbce413c42edbb1b9bcf11bde50465cc97a2c49e 100755
--- a/src/ui/tmlsd/TGConnectorMessageTMLSD.java
+++ b/src/ui/tmlsd/TGConnectorMessageTMLSD.java
@@ -159,10 +159,3 @@ public  abstract class TGConnectorMessageTMLSD extends TGConnector {
         return null;
     }
 }
-
-
-
-
-
-
-
diff --git a/src/ui/tmlsd/TMLSDPanel.java b/src/ui/tmlsd/TMLSDPanel.java
index 331b029aa822857e5c48bd2d9290123b3b8d0458..6b7bb1c70901121d84b8f0e655846e8f93f9c5b3 100755
--- a/src/ui/tmlsd/TMLSDPanel.java
+++ b/src/ui/tmlsd/TMLSDPanel.java
@@ -310,4 +310,8 @@ public class TMLSDPanel extends TDiagramPanel {
         }
         
     }
-}
\ No newline at end of file
+
+	/*public void changeName( int i, String s ){
+		mgui.requestRenameTab( i, s);
+	}*/
+}
diff --git a/src/ui/window/JDialogSelectCPDiagrams.java b/src/ui/window/JDialogSelectCPDiagrams.java
new file mode 100755
index 0000000000000000000000000000000000000000..7ed3a19dfae0dfa3c0263ce4b4cfe8f075c1dbd1
--- /dev/null
+++ b/src/ui/window/JDialogSelectCPDiagrams.java
@@ -0,0 +1,440 @@
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
+
+ludovic.apvrille AT telecom-paristech.fr
+andrea.enrici 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.
+
+/**
+ * Class JDialogSelectCPDiagrams
+ * Dialog for managing diagrams to be validated
+ * Creation: 02/06/2014
+ * @version 1.0 02/06/2014
+ * @author Ludovic APVRILLE, Andrea ENRICI
+ * @see
+ */
+
+package ui.window;
+
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.util.*;
+
+import ui.*;
+import ui.tmldd.*;
+import ui.tmlcp.*;
+
+
+public class JDialogSelectCPDiagrams extends javax.swing.JDialog implements ActionListener, ListSelectionListener  {
+
+  public static Vector validated, ignored;
+	private static boolean optimized = true;
+	
+	private Vector val, ign, back;	//val for validated, ign for ignored
+    
+  //subpanels
+	private JPanel panel1, panel2, panel3, panel4, panel5, panel6;
+  private JList listIgnored;
+  private JList listValidated;
+  private JButton allValidated;
+  private JButton addOneValidated;
+  private JButton addOneIgnored;
+  private JButton allIgnored;
+	protected JCheckBox optimize;
+//	protected JTextField clockField;
+    
+    // Main Panel
+  private JButton closeButton;
+  private JButton cancelButton;
+    
+    /** Creates new form  */
+  public JDialogSelectCPDiagrams( Frame f, Vector _back, LinkedList componentList, String title ) {
+		
+		super(f, title, true);
+        
+    back = _back;
+    if( ( validated == null ) || ( ignored == null ) ) {
+			val = makeNewVal( componentList );	//componentList must already contain something. Val contains a list of all TMLArchiNodes
+																					//originally contained in componentList
+      ign = new Vector();	//empty
+			//val and ign are the lists that are printed in the Syntax Analysis window
+    }
+		else {
+    	val = validated;	//validated and ignored, the public vectors come from the instance of TMLArchiPanel
+      ign = ignored;
+      checkDiagram( val, componentList );
+      checkDiagram( ign, componentList );
+      addNewDiagram( val, componentList, ign );
+    }
+        
+    initComponents();
+    myInitComponents();
+    pack();
+	}
+    
+	//From componentList, filter out all the elements which are not TMLArchiNode
+  private Vector makeNewVal( LinkedList list ) {
+  	
+		Vector v = new Vector();
+    TGComponent tgc;
+        
+		for( int i = 0; i < list.size(); i++ ) {
+			tgc = (TGComponent)( list.get(i) );
+      //System.out.println(tgc);
+      if ( ( tgc instanceof TMLCPRefSD ) || ( tgc instanceof TMLCPRefCP ) ) {
+         v.addElement( tgc );
+      }
+    }
+    return v;
+	}
+    
+	private void checkDiagram( Vector tobeChecked, LinkedList source ) {
+  	
+		TMLCPRefSD sd;
+		TMLCPRefCP cp;
+        
+    for(int i = 0; i < tobeChecked.size(); i++ ) {
+//    	sd = (TMLCPRefSD)( tobeChecked.elementAt(i) );
+//    	cp = (TMLCPRefCP)( tobeChecked.elementAt(i) );
+    	if( tobeChecked.elementAt(i) instanceof TMLCPRefSD )	{
+				sd = (TMLCPRefSD) tobeChecked.elementAt(i);
+				if( !source.contains( sd) )	{
+      		tobeChecked.removeElementAt(i);
+        	i--;
+				}
+			}
+    	else	{
+				if( tobeChecked.elementAt(i) instanceof TMLCPRefCP )	{
+					cp = (TMLCPRefCP) tobeChecked.elementAt(i);
+	      	if( !source.contains( cp ) )	{
+  	    		tobeChecked.removeElementAt(i);
+    	    	i--;
+      		}
+				}
+			}
+    }
+	}
+    
+	/*public void setValidated( Vector _input )	{
+		validated = _input;
+	}
+
+	public void setIgnored( Vector _ignored )	{
+		ignored = _ignored;
+	}
+
+	public Vector getValidated()	{
+		return validated;
+	}
+
+	public Vector getIgnored()	{
+		return ignored;
+	}*/
+
+	public void addNewDiagram( Vector added, LinkedList source, Vector notSource ) {
+  
+		TGComponent tgc;
+        
+    for( int i = 0; i < source.size(); i++ ) {
+			tgc = (TGComponent)( source.get(i) );
+			if( ( tgc instanceof TMLCPRefSD ) && ( tgc instanceof TMLCPRefCP ) && ( !added.contains(tgc) ) && ( !notSource.contains(tgc) ) )	{
+				added.addElement( tgc );
+				//System.out.println("New element");
+      }
+   	}
+	}
+    
+    private void myInitComponents() {
+        setButtons();
+    }
+    
+	private void initComponents() {
+  	
+		Container c = getContentPane();
+    GridBagLayout gridbag1 = new GridBagLayout();
+    GridBagConstraints c1 = new GridBagConstraints();
+    setFont( new Font( "Helvetica", Font.PLAIN, 14) );
+    c.setLayout( new BorderLayout() );
+    setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
+    
+    // ignored list
+    panel1 = new JPanel();
+    panel1.setLayout( new BorderLayout() );
+    panel1.setBorder( new javax.swing.border.TitledBorder( "Diagrams ignored" ) );
+    listIgnored = new JList( ign );
+    //listIgnored.setPreferredSize(new Dimension(200, 250));
+    listIgnored.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
+    listIgnored.addListSelectionListener( this );
+    JScrollPane scrollPane1 = new JScrollPane( listIgnored );
+    panel1.add( scrollPane1, BorderLayout.CENTER );
+    panel1.setPreferredSize( new Dimension( 200, 250) );
+    c.add( panel1, BorderLayout.WEST );
+    
+    // validated list
+    panel2 = new JPanel();
+    panel2.setLayout( new BorderLayout() );
+    panel2.setBorder( new javax.swing.border.TitledBorder( "Diagrams taken into account" ) );
+    listValidated = new JList( val );
+    //listValidated.setPreferredSize(new Dimension(200, 250));
+    listValidated.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
+    listValidated.addListSelectionListener( this );
+    JScrollPane scrollPane2 = new JScrollPane( listValidated );
+    panel2.add( scrollPane2, BorderLayout.CENTER );
+    panel2.setPreferredSize( new Dimension(200, 250) );
+    c.add( panel2, BorderLayout.EAST );
+    
+    // central buttons
+    panel3 = new JPanel();
+    panel3.setLayout(gridbag1);
+    
+    c1.weighty = 1.0;
+    c1.weightx = 1.0;
+    c1.gridwidth = GridBagConstraints.REMAINDER; //end row
+    c1.fill = GridBagConstraints.HORIZONTAL;
+    c1.gridheight = 1;
+    
+    allValidated = new JButton(IconManager.imgic50);
+    allValidated.setPreferredSize(new Dimension(50, 25));
+    allValidated.addActionListener(this);
+    allValidated.setActionCommand("allValidated");
+    panel3.add(allValidated, c1);
+    
+    addOneValidated = new JButton(IconManager.imgic48);
+    addOneValidated.setPreferredSize(new Dimension(50, 25));
+    addOneValidated.addActionListener(this);
+    addOneValidated.setActionCommand("addOneValidated");
+    panel3.add(addOneValidated, c1);
+    
+    panel3.add(new JLabel(" "), c1);
+    
+    addOneIgnored = new JButton(IconManager.imgic46);
+    addOneIgnored.addActionListener(this);
+    addOneIgnored.setPreferredSize(new Dimension(50, 25));
+    addOneIgnored.setActionCommand("addOneIgnored");
+    panel3.add(addOneIgnored, c1);
+    
+    allIgnored = new JButton(IconManager.imgic44);
+    allIgnored.addActionListener(this);
+    allIgnored.setPreferredSize(new Dimension(50, 25));
+    allIgnored.setActionCommand("allIgnored");
+    panel3.add(allIgnored, c1);
+    
+    c.add(panel3, BorderLayout.CENTER);
+    
+    // main panel;
+    panel6 = new JPanel();
+    panel6.setLayout(new BorderLayout());
+		
+		panel5 = new JPanel();
+		GridBagLayout gridbag2 = new GridBagLayout();
+        GridBagConstraints c2 = new GridBagConstraints();
+        panel5.setLayout(gridbag2);
+		
+		c2.weighty = 1.0;
+        c2.weightx = 1.0;
+        c2.fill = GridBagConstraints.HORIZONTAL;
+        c2.gridheight = 1;
+		
+		c2.gridwidth = GridBagConstraints.REMAINDER; //end row
+//		optimize = new JCheckBox("Optimize TML specification");
+//		optimize.setSelected(optimized);
+//		panel5.add(optimize, c2);
+		
+		c2.gridwidth = 1; //end row
+//		panel5.add(new JLabel("Master clock (in MHz)"), c2);
+//		c2.gridwidth = GridBagConstraints.REMAINDER; //end row
+//		clockField = new JTextField("" + clock);
+//		panel5.add(clockField, c2);
+		
+    panel4 = new JPanel();
+    panel4.setLayout(new FlowLayout());
+    
+    closeButton = new JButton("Start Syntax Analysis", IconManager.imgic37);
+    //closeButton.setPreferredSize(new Dimension(600, 50));
+    closeButton.addActionListener(this);
+    closeButton.setPreferredSize(new Dimension(200, 30));
+    
+    cancelButton = new JButton("Cancel", IconManager.imgic27);
+    cancelButton.addActionListener(this);
+    cancelButton.setPreferredSize(new Dimension(200, 30));
+    panel4.add(cancelButton);
+		panel4.add(closeButton);
+		
+		panel6.add(panel5, BorderLayout.NORTH);
+		panel6.add(panel4, BorderLayout.SOUTH);
+        
+    c.add(panel6, BorderLayout.SOUTH);
+        
+    }
+    
+    public void	actionPerformed( ActionEvent evt )  {
+        String command = evt.getActionCommand();
+        
+        // Compare the action command to the known actions.
+        if (command.equals("Start Syntax Analysis"))  {
+            closeDialog();
+        } else if (command.equals("Cancel")) {
+            cancelDialog();
+        } else if (command.equals("addOneIgnored")) {
+            addOneIgnored();
+        } else if (command.equals("addOneValidated")) {
+            addOneValidated();
+        } else if (command.equals("allValidated")) {
+            allValidated();
+        } else if (command.equals("allIgnored")) {
+            allIgnored();
+        }
+    }
+    
+    
+    private void addOneIgnored() {
+        int [] list = listValidated.getSelectedIndices();
+        Vector v = new Vector();
+        Object o;
+        for (int i=0; i<list.length; i++){
+            o = val.elementAt(list[i]);
+            ign.addElement(o);
+            v.addElement(o);
+        }
+        
+        val.removeAll(v);
+        listIgnored.setListData(ign);
+        listValidated.setListData(val);
+        setButtons();
+    }
+    
+    private void addOneValidated() {
+        int [] list = listIgnored.getSelectedIndices();
+        Vector v = new Vector();
+        Object o;
+        for (int i=0; i<list.length; i++){
+            o = ign.elementAt(list[i]);
+            val.addElement(o);
+            v.addElement(o);
+        }
+        
+        ign.removeAll(v);
+        listIgnored.setListData(ign);
+        listValidated.setListData(val);
+        setButtons();
+    }
+    
+    private void allValidated() {
+        val.addAll(ign);
+        ign.removeAllElements();
+        listIgnored.setListData(ign);
+        listValidated.setListData(val);
+        setButtons();
+    }
+    
+    private void allIgnored() {
+        ign.addAll(val);
+        val.removeAllElements();
+        listIgnored.setListData(ign);
+        listValidated.setListData(val);
+        setButtons();
+    }
+    
+    
+    public void closeDialog() {
+
+    	back.removeAllElements();
+				
+      for( int i = 0; i < val.size(); i++ ) {
+       	back.addElement( val.elementAt(i) );
+      }
+      validated = val;
+      ignored = ign;
+      dispose();
+    }
+    
+    public void cancelDialog() {
+        dispose();
+    }
+    
+    private void setButtons() {
+        int i1 = listIgnored.getSelectedIndex();
+        int i2 = listValidated.getSelectedIndex();
+        
+        if (i1 == -1) {
+            addOneValidated.setEnabled(false);
+        } else {
+            addOneValidated.setEnabled(true);
+            //listValidated.clearSelection();
+        }
+        
+        if (i2 == -1) {
+            addOneIgnored.setEnabled(false);
+        } else {
+            addOneIgnored.setEnabled(true);
+            //listIgnored.clearSelection();
+        }
+        
+        if (ign.size() ==0) {
+            allValidated.setEnabled(false);
+        } else {
+            allValidated.setEnabled(true);
+        }
+        
+        if (val.size() ==0) {
+            allIgnored.setEnabled(false);
+            closeButton.setEnabled(false);
+        } else {
+            allIgnored.setEnabled(true);
+            closeButton.setEnabled(true);
+        }
+    }
+    
+/*	public int getClock() {
+		try {
+			int c = Integer.decode(clockField.getText()).intValue();
+			if (c > 0) {
+				return c;
+			}
+		} catch (Exception e) {
+		}
+		return clock;
+	}
+*/
+    
+    public void valueChanged(ListSelectionEvent e) {
+        setButtons();
+    }
+	
+	public boolean getOptimize() {
+		return optimized;
+	}
+}
diff --git a/src/ui/window/JDialogSystemCGeneration.java b/src/ui/window/JDialogSystemCGeneration.java
index dddf01c9bcc0d81fa7b3fc91411526c3a474bd49..450857cec51ca499e933bcc690db9c405bf64c0f 100755
--- a/src/ui/window/JDialogSystemCGeneration.java
+++ b/src/ui/window/JDialogSystemCGeneration.java
@@ -1,6 +1,7 @@
-/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
+/**Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille, Andrea Enrici
  *
- * ludovic.apvrille AT enst.fr
+ * ludovic.apvrille AT telecom-paristech.fr
+ * andrea.enrici AT telecom-paristech.f
  *
  * This software is a computer program whose purpose is to allow the
  * edition of TURTLE analysis, design and deployment diagrams, to
@@ -39,8 +40,8 @@
  * Class JDialogSystemCGeneration
  * Dialog for managing the generation and compilation of SystemC code
  * Creation: 01/12/2005
- * @version 1.1 03/09/2007
- * @author Ludovic APVRILLE
+ * @version 1.2 02/06/2014
+ * @author Ludovic APVRILLE, Andrea ENRICI
  * @see
  */
 
@@ -78,7 +79,9 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act
     
     private static String unitCycle = "1";
 	
-	private static String[] simus = {"SystemC Simulator - LabSoC version", "C++ Simulator - LabSoc version"};
+	private static String[] simus = { "SystemC Simulator - LabSoC version",
+																		"C++ Simulator - LabSoc version",
+																		"C++ Simulator with Communication Patterns" };
 	private static int selectedItem = 1;
     
     protected static String pathCode;
@@ -725,21 +728,88 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act
     	
     	selectedItem = versionSimulator.getSelectedIndex();
     	//System.out.println("Selected item=" + selectedItem);
-    	if (selectedItem == 0) {
-    		tmltranslator.tomappingsystemc.TML2MappingSystemC tml2systc;
+    	switch( selectedItem ) {	//Old SystemC generator
+				case 0:	{
+					tmltranslator.tomappingsystemc.TML2MappingSystemC tml2systc;
+	    		if (mgui.gtm.getTMLMapping() == null) {
+  	  			if (mgui.gtm.getArtificialTMLMapping() == null) {
+    					tml2systc = new tmltranslator.tomappingsystemc.TML2MappingSystemC(mgui.gtm.getTMLModeling());
+    				} else {
+    					TraceManager.addDev("Using artifical mapping");
+    					tml2systc = new tmltranslator.tomappingsystemc.TML2MappingSystemC(mgui.gtm.getArtificialTMLMapping());
+	    			}
+  	  		}
+					else {
+    				tml2systc = new tmltranslator.tomappingsystemc.TML2MappingSystemC(mgui.gtm.getTMLMapping());
+    			}
+    			tml2systc.generateSystemC(debugmode.isSelected(), optimizemode.isSelected());
+	    		testGo();
+  	  		jta.append("SystemC code generation done\n");
+    			//t2j.printJavaClasses();
+    			try {
+    				jta.append("Generating SystemC file\n");
+    				pathCode = code1.getText();
+	    			tml2systc.saveFile(pathCode, "appmodel");
+  	  			jta.append("SystemC files generated\n");
+    			}
+					catch( Exception e ) {
+    				jta.append("Could not generate SystemC file\n");
+    			}
+				break;
+			}
+			case 1:	{	//Simulator without CPs (Daniel's version)
+    		tmltranslator.tomappingsystemc2.TML2MappingSystemC tml2systc;
+    		// Making EBRDDs
+    		ArrayList<EBRDD> al = new ArrayList<EBRDD>();
+    		ArrayList<TEPE> alTepe = new ArrayList<TEPE>();
+    		TEPE tepe;
+    		AvatarRequirementPanelTranslator arpt = new AvatarRequirementPanelTranslator();
+    		for(int k=0; k<valTepe.size(); k++) {
+    			testGo();
+    			tepe = arpt.generateTEPESpecification((AvatarPDPanel)(valTepe.get(k)));
+    			jta.append("TEPE: " + tepe.getName() + "\n");
+    			jta.append("Checking syntax\n");
+    			// tepe.checkSyntax();
+    			alTepe.add(tepe);
+    			jta.append("Done.\n");
+    		}
+    		/*EBRDDTranslator ebrddt;
+    		EBRDDPanel ep;
+    		EBRDD ebrdd;
+    		
+    		for(int k=0; k<val.size(); k++) {
+    		testGo();
+    		ebrddt = new EBRDDTranslator();
+    		ep = (EBRDDPanel)(val.get(k));
+    		jta.append("EBRDD: " + ep.getName() + "\n");
+    		ebrdd = ebrddt.generateEBRDD(ep, ep.getName());
+    		jta.append("Checking syntax\n");
+    		if (ebrddt.getErrors().size() > 0) {
+    		jta.append("Syntax error: ignoring EBRDD\n\n");
+    		} else {
+    		jta.append("No Syntax error: EBRDD taken into account\n\n");
+    		al.add(ebrdd);
+    		}
+    		}*/
+    		
+    		// Generating code
     		if (mgui.gtm.getTMLMapping() == null) {
     			if (mgui.gtm.getArtificialTMLMapping() == null) {
-    				tml2systc = new tmltranslator.tomappingsystemc.TML2MappingSystemC(mgui.gtm.getTMLModeling());
+    				tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getTMLModeling(), al, alTepe);
     			} else {
     				TraceManager.addDev("Using artifical mapping");
-    				tml2systc = new tmltranslator.tomappingsystemc.TML2MappingSystemC(mgui.gtm.getArtificialTMLMapping());
+    				tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getArtificialTMLMapping(), al, alTepe);
     			}
     		} else {
-    			tml2systc = new tmltranslator.tomappingsystemc.TML2MappingSystemC(mgui.gtm.getTMLMapping());
+    			tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getTMLMapping(), al, alTepe);
     		}
     		tml2systc.generateSystemC(debugmode.isSelected(), optimizemode.isSelected());
     		testGo();
     		jta.append("SystemC code generation done\n");
+    		
+    		for(TEPE tep: alTepe) {
+    			TraceManager.addDev(tep.toString());
+    		}
     		//t2j.printJavaClasses();
     		try {
     			jta.append("Generating SystemC file\n");
@@ -749,9 +819,10 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act
     		} catch (Exception e) {
     			jta.append("Could not generate SystemC file\n");
     		}
-    	} else {
-    		tmltranslator.tomappingsystemc2.TML2MappingSystemC tml2systc;
-    		
+			break;
+    	}
+		case 2:	{	//Simulator version with CPs
+    		tmltranslator.tomappingsystemc3.TML2MappingSystemC tml2systc;
     		// Making EBRDDs
     		ArrayList<EBRDD> al = new ArrayList<EBRDD>();
     		ArrayList<TEPE> alTepe = new ArrayList<TEPE>();
@@ -788,15 +859,17 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act
     		// Generating code
     		if (mgui.gtm.getTMLMapping() == null) {
     			if (mgui.gtm.getArtificialTMLMapping() == null) {
-    				tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getTMLModeling(), al, alTepe);
+    				tml2systc = new tmltranslator.tomappingsystemc3.TML2MappingSystemC(mgui.gtm.getTMLModeling(), al, alTepe);
     			} else {
     				TraceManager.addDev("Using artifical mapping");
-    				tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getArtificialTMLMapping(), al, alTepe);
+    				tml2systc = new tmltranslator.tomappingsystemc3.TML2MappingSystemC(mgui.gtm.getArtificialTMLMapping(), al, alTepe);
     			}
-    		} else {
-    			tml2systc = new tmltranslator.tomappingsystemc2.TML2MappingSystemC(mgui.gtm.getTMLMapping(), al, alTepe);
     		}
-    		tml2systc.generateSystemC(debugmode.isSelected(), optimizemode.isSelected());
+				else {
+    			tml2systc = new tmltranslator.tomappingsystemc3.TML2MappingSystemC(mgui.gtm.getTMLMapping(), al, alTepe);
+    		}
+				TraceManager.addDev( "Before exception" );
+    		tml2systc.generateSystemC( debugmode.isSelected(), optimizemode.isSelected() );
     		testGo();
     		jta.append("SystemC code generation done\n");
     		
@@ -812,9 +885,10 @@ public class JDialogSystemCGeneration extends javax.swing.JDialog implements Act
     		} catch (Exception e) {
     			jta.append("Could not generate SystemC file\n");
     		}
-    	}
-    	
-    }
+			break;
+			}
+		}
+	}	//End of method generateCode()
     
     public void compileCode() throws InterruptedException {
     	String cmd = compiler1.getText();
diff --git a/ttool.exe b/ttool.exe
index d759a65d6dff5e591777617848c4e5eb420cc416..726dc9b337e8dc38e2b0b0dde7c587ade0ff633a 100755
--- a/ttool.exe
+++ b/ttool.exe
@@ -1,5 +1,7 @@
 #!/bin/sh
+
 java -version
-cd bin; java -Xmx1024m -jar ttool.jar -config config.xml -experimental #-avatar -uppaal -launcher
+cd bin;
+java -Xmx1024m -jar ttool.jar -config config.xml -experimental -debug #-avatar -uppaal -launcher