Revision: 201039 RCL_3
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Wed, 13 Oct 2010 16:17:58 +0300
branchRCL_3
changeset 59 8ad140f3dd41
parent 49 7fdc9a71d314
Revision: 201039 Kit: 201041
analyzetool/analyzetool_plat/analyzetool_api/analyzetool_api.metaxml
analyzetool/analyzetool_plat/analyzetool_api/group/bld.inf
analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/analyzetool.h
analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/analyzetool.inl
analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/analyzetoolcleaner.h
analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/analyzetooltraceconstants.h
analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/atcommon.h
analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/customuser.h
analyzetool/analyzetool_plat/group/bld.inf
analyzetool/analyzetoolcleaner/group/analyzetoolcleaner.mmp
analyzetool/analyzetoolcleaner/group/bld.inf
analyzetool/analyzetoolcleaner/inc/analyzetoolcleaner.h
analyzetool/commandlineengine/group/atool.vcproj
analyzetool/commandlineengine/inc/ATCommonDefines.h
analyzetool/commandlineengine/inc/CATBase.h
analyzetool/commandlineengine/inc/CATModule2.h
analyzetool/commandlineengine/inc/CATParseBinaryFile.h
analyzetool/commandlineengine/inc/CATParseTraceFile.h
analyzetool/commandlineengine/inc/CATProcessData.h
analyzetool/commandlineengine/inc/CATProject.h
analyzetool/commandlineengine/inc/catalloc.h
analyzetool/commandlineengine/inc/catallocs.h
analyzetool/commandlineengine/install/atool.exe
analyzetool/commandlineengine/src/CATBase.cpp
analyzetool/commandlineengine/src/CATDatParser.cpp
analyzetool/commandlineengine/src/CATModule2.cpp
analyzetool/commandlineengine/src/CATParseBinaryFile.cpp
analyzetool/commandlineengine/src/CATParseTraceFile.cpp
analyzetool/commandlineengine/src/CATProject.cpp
analyzetool/commandlineengine/src/arguments.cpp
analyzetool/commandlineengine/src/atool.cpp
analyzetool/commandlineengine/src/catallocs.cpp
analyzetool/commandlineengine/src/helps.cpp
analyzetool/dynamicmemoryhook/bwins/atoolmemoryhooku.def
analyzetool/dynamicmemoryhook/eabi/atoolmemoryhooku.def
analyzetool/dynamicmemoryhook/group/atoolmemoryhook.mmp
analyzetool/dynamicmemoryhook/inc/analyzetoolallocator.h
analyzetool/dynamicmemoryhook/inc/analyzetooleventhandler.h
analyzetool/dynamicmemoryhook/inc/analyzetoolfastlog.h
analyzetool/dynamicmemoryhook/inc/analyzetoolfilelog.h
analyzetool/dynamicmemoryhook/inc/analyzetoolmainallocator.h
analyzetool/dynamicmemoryhook/inc/analyzetoolmainallocator.inl
analyzetool/dynamicmemoryhook/inc/analyzetoolpanics.pan
analyzetool/dynamicmemoryhook/inc/atdriveinfo.h
analyzetool/dynamicmemoryhook/inc/customuser.h
analyzetool/dynamicmemoryhook/src/analyzetoolallocator.cpp
analyzetool/dynamicmemoryhook/src/analyzetooleventhandler.cpp
analyzetool/dynamicmemoryhook/src/analyzetoolfastlog.cpp
analyzetool/dynamicmemoryhook/src/analyzetoolfilelog.cpp
analyzetool/dynamicmemoryhook/src/analyzetoolmainallocator.cpp
analyzetool/dynamicmemoryhook/src/analyzetoolmemoryallocator.cpp
analyzetool/dynamicmemoryhook/src/atdriveinfo.cpp
analyzetool/dynamicmemoryhook/src/customuser.cpp
analyzetool/group/ReleaseNotes_AnalyzeTool.txt
analyzetool/group/bld.inf
analyzetool/kerneleventhandler/group/bld.inf
analyzetool/kerneleventhandler/inc/analyzetool.h
analyzetool/kerneleventhandler/inc/analyzetool.inl
analyzetool/kerneleventhandler/inc/analyzetooltraceconstants.h
analyzetool/kerneleventhandler/inc/atcommon.h
analyzetool/rom/analyzetool_rom.iby
analyzetool/sis/AnalyzeTool.pkg
analyzetool/sis/AnalyzeTool_udeb.pkg
analyzetool/sis/analyzeTool_stub.pkg
analyzetool/staticlib/group/bld.inf
analyzetool/staticlib/src/atoolstaticlib.cpp
analyzetool/storageserver/client/bwins/atoolstorageserverclntu.def
analyzetool/storageserver/client/eabi/atoolstorageserverclntu.def
analyzetool/storageserver/client/group/atoolstorageserverclnt.mmp
analyzetool/storageserver/client/inc/atstorageserverclnt.h
analyzetool/storageserver/client/src/atstorageserverclnt.cpp
analyzetool/storageserver/group/bld.inf
analyzetool/storageserver/inc/atstorageservercommon.h
analyzetool/storageserver/server/group/atoolstorageserver.mmp
analyzetool/storageserver/server/inc/atdllinfo.h
analyzetool/storageserver/server/inc/atdriveinfo.h
analyzetool/storageserver/server/inc/atdynprocessinfo.h
analyzetool/storageserver/server/inc/atmemoryentry.h
analyzetool/storageserver/server/inc/atstorageserver.h
analyzetool/storageserver/server/inc/atstorageserversession.h
analyzetool/storageserver/server/src/atdllinfo.cpp
analyzetool/storageserver/server/src/atdriveinfo.cpp
analyzetool/storageserver/server/src/atdynprocessinfo.cpp
analyzetool/storageserver/server/src/atmemoryentry.cpp
analyzetool/storageserver/server/src/atstorageserver.cpp
analyzetool/storageserver/server/src/atstorageserversession.cpp
analyzetool/storageserver/sis/atstorageserver.pkg
analyzetool/storageserver/sis/atstorageserver_udeb.pkg
group/bld.inf
hti/HtiAutoStart/data/10210CC4.rss
hti/HtiAutoStart/group/HtiAutoStart.mmp
hti/HtiAutoStart/group/bld.inf
hti/HtiAutoStart/inc/HtiAutoStart.h
hti/HtiAutoStart/src/HtiAutoStart.cpp
hti/HtiCfg/bwins/HtiCfgu.def
hti/HtiCfg/eabi/HtiCfgu.def
hti/HtiCfg/group/HtiCfg.mmp
hti/HtiCfg/group/bld.inf
hti/HtiCfg/src/HtiCfg.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/BWINS/HtiBtCommInterfaceu.def
hti/HtiCommPlugins/HtiBtCommPlugin/BWINS/HtiBtCommServeru.def
hti/HtiCommPlugins/HtiBtCommPlugin/BWINS/HtiBtSerialComHelperu.def
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/BtSerialClient.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/BtSerialEngine.pan
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/HtiBtEngineLogging.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/HtiBtPowerManager.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/SocketObserver.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/btservicesearcher.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/btservicesearcher.pan
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/messageprotocolconstants.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/messageservicesearcher.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/sdpattributenotifier.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/sdpattributeparser.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/sdpattributeparser.pan
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/socketsreader.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/socketswriter.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/staticarrayc.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/staticarrayc.inl
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/timeoutnotifier.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/timeouttimer.h
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/BtSerialClient.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/btservicesearcher.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/messageservicesearcher.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/sdpattributeparser.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/socketsreader.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/socketswriter.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/timeouttimer.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommEcomPlugin/data/200212CB.rss
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommEcomPlugin/inc/HtiBtCommEcomPlugin.h
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommEcomPlugin/src/HtiBtCommEcomPlugin.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommEcomPlugin/src/proxy.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/HtiBtClientServerCommon.h
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/HtiBtCommInterface.h
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/HtiBtCommServer.h
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/HtiBtCommServerSession.h
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/Logger.h
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/src/HtiBtCommInterface.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/src/HtiBtCommServer.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/src/HtiBtCommServerSession.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/src/Logger.cpp
hti/HtiCommPlugins/HtiBtCommPlugin/eabi/HtiBtCommInterfaceu.def
hti/HtiCommPlugins/HtiBtCommPlugin/eabi/HtiBtCommServeru.def
hti/HtiCommPlugins/HtiBtCommPlugin/eabi/HtiBtSerialComHelperu.def
hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtComm.cfg
hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtCommEcomPlugin.mmp
hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtCommInterface.mmp
hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtCommServer.mmp
hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtSerialComHelper.mmp
hti/HtiCommPlugins/HtiBtCommPlugin/group/bld.inf
hti/HtiCommPlugins/HtiIPCommPlugin/BWINS/HtiIPCommInterfaceU.def
hti/HtiCommPlugins/HtiIPCommPlugin/data/200212CD.rss
hti/HtiCommPlugins/HtiIPCommPlugin/eabi/HtiIPCommInterfaceu.def
hti/HtiCommPlugins/HtiIPCommPlugin/group/HTIIPComm.cfg
hti/HtiCommPlugins/HtiIPCommPlugin/group/HtiIPCommEcomPlugin.mmp
hti/HtiCommPlugins/HtiIPCommPlugin/group/HtiIPCommServer.mmp
hti/HtiCommPlugins/HtiIPCommPlugin/group/HtiIPCommServerClient.mmp
hti/HtiCommPlugins/HtiIPCommPlugin/group/bld.inf
hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiConnectionManager.h
hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommEcomPlugin.h
hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommLogging.h
hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommServer.h
hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommServerClient.h
hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommServerCommon.h
hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommServerSession.h
hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiSocketMonitor.h
hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiConnectionManager.cpp
hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiIPCommEcomPlugin.cpp
hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiIPCommServerClient.cpp
hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiIPCommserver.cpp
hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiIPCommserverSession.cpp
hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiSocketMonitor.cpp
hti/HtiCommPlugins/HtiIPCommPlugin/src/proxy.cpp
hti/HtiCommPlugins/HtiSerialCommPlugin/data/10210CC9.rss
hti/HtiCommPlugins/HtiSerialCommPlugin/group/HtiSerialComm.cfg
hti/HtiCommPlugins/HtiSerialCommPlugin/group/HtiSerialCommEcomPlugin.mmp
hti/HtiCommPlugins/HtiSerialCommPlugin/group/bld.inf
hti/HtiCommPlugins/HtiSerialCommPlugin/inc/HtiSerialCommEcomPlugin.h
hti/HtiCommPlugins/HtiSerialCommPlugin/src/HtiSerialCommEcomPlugin.cpp
hti/HtiCommPlugins/HtiSerialCommPlugin/src/proxy.cpp
hti/HtiCommPlugins/HtiUsbSerialCommPlugin/data/200212CF.rss
hti/HtiCommPlugins/HtiUsbSerialCommPlugin/group/HtiUsbSerialComm.cfg
hti/HtiCommPlugins/HtiUsbSerialCommPlugin/group/HtiUsbSerialCommEcomPlugin.mmp
hti/HtiCommPlugins/HtiUsbSerialCommPlugin/group/bld.inf
hti/HtiCommPlugins/HtiUsbSerialCommPlugin/inc/HtiUsbSerialCommEcomPlugin.h
hti/HtiCommPlugins/HtiUsbSerialCommPlugin/src/HtiUsbSerialCommEcomPlugin.cpp
hti/HtiCommPlugins/HtiUsbSerialCommPlugin/src/proxy.cpp
hti/HtiFileHlp/group/HtiFileHlp.mmp
hti/HtiFileHlp/group/bld.inf
hti/HtiFileHlp/src/HtiFileHlp.cpp
hti/HtiFramework/group/HtiFramework.mmp
hti/HtiFramework/group/bld.inf
hti/HtiFramework/group/hti.cfg
hti/HtiFramework/inc/HtiCommAdapter.h
hti/HtiFramework/inc/HtiDispatcher.h
hti/HtiFramework/inc/HtiFramework.h
hti/HtiFramework/inc/HtiMessage.h
hti/HtiFramework/inc/HtiMessageQueue.h
hti/HtiFramework/inc/HtiNotifier.h
hti/HtiFramework/inc/HtiSecurityManager.h
hti/HtiFramework/src/HtiCommAdapter.cpp
hti/HtiFramework/src/HtiDispatcher.cpp
hti/HtiFramework/src/HtiFramework.cpp
hti/HtiFramework/src/HtiMessage.cpp
hti/HtiFramework/src/HtiMessageQueue.cpp
hti/HtiFramework/src/HtiNotifier.cpp
hti/HtiFramework/src/HtiSecurityManager.cpp
hti/HtiRestart/group/HtiRestart.mmp
hti/HtiRestart/group/bld.inf
hti/HtiRestart/src/HtiRestart.cpp
hti/HtiServicePlugins/HtiAppServicePlugin/data/1020DEC6.rss
hti/HtiServicePlugins/HtiAppServicePlugin/group/HtiAppServicePlugin.mmp
hti/HtiServicePlugins/HtiAppServicePlugin/group/bld.inf
hti/HtiServicePlugins/HtiAppServicePlugin/inc/HtiAppServicePlugin.h
hti/HtiServicePlugins/HtiAppServicePlugin/src/HtiAppServicePlugin.cpp
hti/HtiServicePlugins/HtiAppServicePlugin/src/proxy.cpp
hti/HtiServicePlugins/HtiEchoServicePlugin/data/1020DEBE.rss
hti/HtiServicePlugins/HtiEchoServicePlugin/group/HtiEchoServicePlugin.mmp
hti/HtiServicePlugins/HtiEchoServicePlugin/group/bld.inf
hti/HtiServicePlugins/HtiEchoServicePlugin/inc/HtiEchoServicePlugin.h
hti/HtiServicePlugins/HtiEchoServicePlugin/src/HtiEchoServicePlugin.cpp
hti/HtiServicePlugins/HtiEchoServicePlugin/src/proxy.cpp
hti/HtiServicePlugins/HtiFtpServicePlugin/data/1020DEC4.rss
hti/HtiServicePlugins/HtiFtpServicePlugin/group/HtiFtpServicePlugin.mmp
hti/HtiServicePlugins/HtiFtpServicePlugin/group/bld.inf
hti/HtiServicePlugins/HtiFtpServicePlugin/inc/HtiFtpServicePlugin.h
hti/HtiServicePlugins/HtiFtpServicePlugin/src/HtiFtpServicePlugin.cpp
hti/HtiServicePlugins/HtiFtpServicePlugin/src/proxy.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/CIPProxyEngine.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/CommRouterDefinitions.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/IPProxyEnginefactory.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MAbstractConnection.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MHostConnection.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MIPProxyEngine.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MIPProxyEngineObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MLocalTCPConnectionObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MSocket.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MSocketObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MSocketRouterObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MSocketWriter.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MTCPPortListenerObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/Mhostconnectionobserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPClose.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPClose.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPCloseAll.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPCloseAll.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPLstn.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPLstn.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPMsg.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPMsg.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPOpen.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPOpen.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprUDPMsg.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprUDPMsg.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CIPProxyEngine.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CLocalHostConnection.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CLocalHostConnection.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CLocalTCPConnection.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CProtocolTCP.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CProtocolTCP.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CProtocolUDP.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CProtocolUDP.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CSocketReader.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CSocketWriter.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CUDPSender.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CUDPSender.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CWriteEvent.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CWriteEvent.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Clocaltcpconnection.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocket.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocket.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocketreader.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocketrouter.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocketrouter.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocketwriter.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Ctcpportlistener.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Ctcpportlistener.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/DebugPrint.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/IPProxyEngine.pan
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/IPProxyEngineFactory.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MBPExpression.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MBPProtocol.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MExpressionObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MExpressionObserverTCP.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MExpressionObserverUDP.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MProtocolObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MProtocolObserverTCP.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MProtocolObserverUDP.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MSocketReaderObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MSocketRouterTestObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MSocketWriterObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MUDPSenderObserver.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/data/200212C9.rss
hti/HtiServicePlugins/HtiIpProxyServicePlugin/group/HtiIpProxyServicePlugin.mmp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/group/bld.inf
hti/HtiServicePlugins/HtiIpProxyServicePlugin/inc/HtiIpProxyServicePlugin.h
hti/HtiServicePlugins/HtiIpProxyServicePlugin/src/HtiIpProxyServicePlugin.cpp
hti/HtiServicePlugins/HtiIpProxyServicePlugin/src/proxy.cpp
hti/HtiServicePlugins/HtiStifTfServicePlugin/data/10210CC2.rss
hti/HtiServicePlugins/HtiStifTfServicePlugin/group/HtiStifTfServicePlugin.mmp
hti/HtiServicePlugins/HtiStifTfServicePlugin/group/bld.inf
hti/HtiServicePlugins/HtiStifTfServicePlugin/inc/HtiStifTfIf.h
hti/HtiServicePlugins/HtiStifTfServicePlugin/inc/HtiStifTfServicePlugin.h
hti/HtiServicePlugins/HtiStifTfServicePlugin/src/HtiStifTfIf.cpp
hti/HtiServicePlugins/HtiStifTfServicePlugin/src/HtiStifTfServicePlugin.cpp
hti/HtiServicePlugins/HtiStifTfServicePlugin/src/proxy.cpp
hti/HtiWatchDog/group/HtiWatchDog.mmp
hti/HtiWatchDog/group/bld.inf
hti/HtiWatchDog/src/HtiWatchDog.cpp
hti/PC_Tools/DataGateway/BIN/DataGateway.exe
hti/PC_Tools/DataGateway/DataGateway.sln
hti/PC_Tools/DataGateway/DataGateway.vcproj
hti/PC_Tools/DataGateway/INC/IPCommPlugin.h
hti/PC_Tools/DataGateway/INC/SerialCommPlugin.h
hti/PC_Tools/DataGateway/INC/Socket.h
hti/PC_Tools/DataGateway/INC/common.h
hti/PC_Tools/DataGateway/INC/datagateway.h
hti/PC_Tools/DataGateway/INC/error.h
hti/PC_Tools/DataGateway/INC/plugin.h
hti/PC_Tools/DataGateway/INC/pluginmgr.h
hti/PC_Tools/DataGateway/INC/safequeue.h
hti/PC_Tools/DataGateway/INC/stdafx.h
hti/PC_Tools/DataGateway/INC/sync.h
hti/PC_Tools/DataGateway/INC/thread.h
hti/PC_Tools/DataGateway/INC/util.h
hti/PC_Tools/DataGateway/INI/datagateway.ini
hti/PC_Tools/DataGateway/INI/ipcommplugin.ini
hti/PC_Tools/DataGateway/INI/serialplugin.ini
hti/PC_Tools/DataGateway/SRC/IPComm.cpp
hti/PC_Tools/DataGateway/SRC/SerialComm.cpp
hti/PC_Tools/DataGateway/SRC/Socket.cpp
hti/PC_Tools/DataGateway/SRC/common.cpp
hti/PC_Tools/DataGateway/SRC/datagateway.cpp
hti/PC_Tools/DataGateway/SRC/main.cpp
hti/PC_Tools/DataGateway/SRC/plugin.cpp
hti/PC_Tools/DataGateway/SRC/safequeue.cpp
hti/PC_Tools/DataGateway/SRC/stdafx.cpp
hti/PC_Tools/DataGateway/SRC/sync.cpp
hti/PC_Tools/DataGateway/SRC/util.cpp
hti/PC_Tools/HTIGateway/Binaries/HTIGateway_binaries.zip
hti/PC_Tools/HTIGateway/HtiCommon/HtiCommon.cpp
hti/PC_Tools/HTIGateway/HtiCommon/HtiCommon.h
hti/PC_Tools/HTIGateway/HtiCommon/HtiCommon.vcproj
hti/PC_Tools/HTIGateway/HtiCommon/HtiSoapHandlerInterface.h
hti/PC_Tools/HTIGateway/HtiGateway.sln
hti/PC_Tools/HTIGateway/HtiGateway/HtiGateway.vcproj
hti/PC_Tools/HTIGateway/HtiGateway/inc/DllModule.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/HtiDispatcher.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/HtiMessage.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/HtiPluginDll.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/IPCommPlugin.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/SOAPHandler.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/SerialCommPlugin.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/Socket.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/common.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/crc16.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/datagateway.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/error.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/plugin.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/pluginmgr.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/safequeue.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/stdafx.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/sync.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/thread.h
hti/PC_Tools/HTIGateway/HtiGateway/inc/util.h
hti/PC_Tools/HTIGateway/HtiGateway/ini/HtiGateway.ini
hti/PC_Tools/HTIGateway/HtiGateway/ini/ipcommplugin.ini
hti/PC_Tools/HTIGateway/HtiGateway/ini/serialplugin.ini
hti/PC_Tools/HTIGateway/HtiGateway/src/HtiDispatcher.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/HtiMessage.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/IPComm.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/SOAPHandler.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/SerialComm.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/Socket.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/common.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/datagateway.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/main.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/plugin.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/safequeue.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/stdafx.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/sync.cpp
hti/PC_Tools/HTIGateway/HtiGateway/src/util.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiApplication.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiApplication.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiApplication.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiApplication.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiAudio.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiAudio.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiAudio.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiAudio.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiEcho.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiEcho.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiEcho.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiEcho.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiFtp.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiFtp.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiFtp.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiFtp.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiKeyEvent.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiKeyEvent.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiKeyEvent.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiKeyEvent.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiMessages.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiMessages.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiMessages.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiMessages.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPIM.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPIM.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPIM.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPIM.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiScreenshot.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiScreenshot.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiScreenshot.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiScreenshot.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStif.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStif.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStif.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStif.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStifSender.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStifSender.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStifSender.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiSysInfo.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiSysInfo.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiSysInfo.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiSysInfo.wsdl
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiPlugin.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiSystem.cpp
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiSystem.h
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiSystem.vcproj
hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiSystem.wsdl
hti/PC_Tools/HTIGateway/build.bat
hti/PC_Tools/HTIGateway/stdsoap/env.h
hti/PC_Tools/HTIGateway/stdsoap/envC.cpp
hti/PC_Tools/HTIGateway/stdsoap/envClient.cpp
hti/PC_Tools/HTIGateway/stdsoap/envClientLib.cpp
hti/PC_Tools/HTIGateway/stdsoap/envH.h
hti/PC_Tools/HTIGateway/stdsoap/envServer.cpp
hti/PC_Tools/HTIGateway/stdsoap/envServerLib.cpp
hti/PC_Tools/HTIGateway/stdsoap/envStub.h
hti/PC_Tools/HTIGateway/stdsoap/soapcpp2.exe
hti/PC_Tools/HTIGateway/stdsoap/soapdefs.h
hti/PC_Tools/HTIGateway/stdsoap/stdsoap.vcproj
hti/PC_Tools/HTIGateway/stdsoap/stdsoap2.cpp
hti/PC_Tools/HTIGateway/stdsoap/stdsoap2.h
hti/group/bld.inf
hti/hti_plat/group/bld.inf
hti/hti_plat/hti_api/group/bld.inf
hti/hti_plat/hti_api/hti_api.metaxml
hti/hti_plat/hti_api/inc/HtiCfg.h
hti/hti_plat/hti_api/inc/HtiCommPluginInterface.h
hti/hti_plat/hti_api/inc/HtiCommPluginInterface.inl
hti/hti_plat/hti_api/inc/HtiDispatcherInterface.h
hti/hti_plat/hti_api/inc/HtiFtpBackupFakeBase.h
hti/hti_plat/hti_api/inc/HtiLogging.h
hti/hti_plat/hti_api/inc/HtiServicePluginInterface.h
hti/hti_plat/hti_api/inc/HtiServicePluginInterface.inl
hti/hti_plat/hti_api/inc/HtiStartupWaitInterface.h
hti/hti_plat/hti_api/inc/HtiVersion.h
hti/rom/htios.iby
memspy/CommandLine/Include/MemSpyCommandLine.h
memspy/CommandLine/Include/MemSpyCommands.h
memspy/CommandLine/Source/MemSpyCommandLine.cpp
memspy/CommandLine/Source/MemSpyCommandLineMain.cpp
memspy/CommandLine/group/MemSpyCommandLine.mmp
memspy/Console/Include/ConsoleMenu.h
memspy/Console/Source/ConsoleDWOperation.cpp
memspy/Console/Source/ConsoleMain.cpp
memspy/Console/Source/ConsoleMenu.cpp
memspy/Console/group/MemSpyConsole.mmp
memspy/Console/group/bld.inf
memspy/Driver/BWINS/memspydriverclientu.def
memspy/Driver/Kernel/Include/MemSpyDriverHeap.h
memspy/Driver/Kernel/Include/MemSpyDriverHeapStatistics.h
memspy/Driver/Kernel/Include/MemSpyDriverHeapWalker.h
memspy/Driver/Kernel/Include/MemSpyDriverInspectedProcess.h
memspy/Driver/Kernel/Include/MemSpyDriverLog.h
memspy/Driver/Kernel/Include/MemSpyDriverOSAdaption.h
memspy/Driver/Kernel/Include/MemSpyDriverObjectIx.h
memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanContainerBase.h
memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapBase.h
memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapInfo.h
memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapWalk.h
memspy/Driver/Kernel/Source/MemSpyDriverEventMonitor.cpp
memspy/Driver/Kernel/Source/MemSpyDriverHeap.cpp
memspy/Driver/Kernel/Source/MemSpyDriverHeapWalker.cpp
memspy/Driver/Kernel/Source/MemSpyDriverInspectedProcess.cpp
memspy/Driver/Kernel/Source/MemSpyDriverLogicalChannel.cpp
memspy/Driver/Kernel/Source/MemSpyDriverOSAdaption.cpp
memspy/Driver/Kernel/Source/MemSpyDriverObjectIx.cpp
memspy/Driver/Kernel/Source/MemSpyDriverStreamWriter.cpp
memspy/Driver/Kernel/Source/MemSpyDriverSuspensionManager.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanBase.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanChunks.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanClientServer.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanContainerBase.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanContainers.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapBase.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapData.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapInfo.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapWalk.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanMisc.cpp
memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanStack.cpp
memspy/Driver/Shared/MemSpyDriverObjectsInternal.h
memspy/Driver/Shared/MemSpyDriverOpCodes.h
memspy/Driver/Shared/heaputils.cpp
memspy/Driver/Shared/heaputils.h
memspy/Driver/User/Include/RBuildQueryableHeap.h
memspy/Driver/User/Source/MemSpyDriverClient.cpp
memspy/Driver/User/Source/RBuildQueryableHeap.cpp
memspy/Driver/eabi/memspydriverclientu.def
memspy/Driver/group/MemSpyDriver.mmp
memspy/Driver/group/MemSpyDriverClient.mmp
memspy/Engine/BWINS/MemSpyEngineu.def
memspy/Engine/Include/ClientServer/MemSpyEngineServer.h
memspy/Engine/Include/Sink/MemSpyEngineOutputSinkFile.h
memspy/Engine/Source/ClientServer/MemSpyEngineServer.cpp
memspy/Engine/Source/DeviceWideOps/MemSpyDeviceWideOperations.cpp
memspy/Engine/Source/Helpers/MemSpyEngineHelperActiveObject.cpp
memspy/Engine/Source/Helpers/MemSpyEngineHelperFbServ.cpp
memspy/Engine/Source/Helpers/MemSpyEngineHelperHeap.cpp
memspy/Engine/Source/Helpers/MemSpyEngineHelperKernelContainers.cpp
memspy/Engine/Source/Helpers/MemSpyEngineHelperStack.cpp
memspy/Engine/Source/MemSpyEngine.cpp
memspy/Engine/Source/MemSpyEngineImp.cpp
memspy/Engine/Source/MemSpyEngineUtils.cpp
memspy/Engine/Source/Sink/MemSpyEngineOutputList.cpp
memspy/Engine/Source/Sink/MemSpyEngineOutputSink.cpp
memspy/Engine/Source/Sink/MemSpyEngineOutputSinkFile.cpp
memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTracker.cpp
memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTrackerEntryHeap.cpp
memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTrackerEntryManager.cpp
memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectContainer.cpp
memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectProcess.cpp
memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectThread.cpp
memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectThreadInfoObjects.cpp
memspy/Engine/eabi/MemSpyEngineu.def
memspy/Engine/group/MemSpyEngine.mmp
memspy/MemSpyClient/bwins/MemSpyClientu.def
memspy/MemSpyClient/eabi/MemSpyClientu.def
memspy/MemSpyClient/group/MemSpyClient.mmp
memspy/MemSpyClient/group/bld.inf
memspy/MemSpyClient/inc/memspyapiecom.h
memspy/MemSpyClient/inc/memspyapiheap.h
memspy/MemSpyClient/inc/memspyapikernelobject.h
memspy/MemSpyClient/inc/memspyapikernelobjectitem.h
memspy/MemSpyClient/inc/memspyapimemorytrackingcycle.h
memspy/MemSpyClient/inc/memspyapiprocess.h
memspy/MemSpyClient/inc/memspyapiserver.h
memspy/MemSpyClient/inc/memspyapithread.h
memspy/MemSpyClient/inc/memspyapithreadinfoitem.h
memspy/MemSpyClient/inc/memspyecomdata.h
memspy/MemSpyClient/inc/memspyheapdata.h
memspy/MemSpyClient/inc/memspykernelobjectdata.h
memspy/MemSpyClient/inc/memspymemorytrackingcycledata.h
memspy/MemSpyClient/inc/memspyprocessdata.h
memspy/MemSpyClient/inc/memspyserverdata.h
memspy/MemSpyClient/inc/memspysession.h
memspy/MemSpyClient/inc/memspythreaddata.h
memspy/MemSpyClient/inc/memspythreadinfoitemdata.h
memspy/MemSpyClient/src/memspyapiecom.cpp
memspy/MemSpyClient/src/memspyapiheap.cpp
memspy/MemSpyClient/src/memspyapikernelobject.cpp
memspy/MemSpyClient/src/memspyapikernelobjectitem.cpp
memspy/MemSpyClient/src/memspyapimemorytrackingcycle.cpp
memspy/MemSpyClient/src/memspyapiprocess.cpp
memspy/MemSpyClient/src/memspyapiserver.cpp
memspy/MemSpyClient/src/memspyapithread.cpp
memspy/MemSpyClient/src/memspyapithreadinfoitem.cpp
memspy/MemSpyClient/src/memspysession.cpp
memspy/MemSpyServer/Source/MemSpyServerMain.cpp
memspy/MemSpyServer/data/MemSpyEComInterfaceIds.xml
memspy/MemSpyServer/group/MemSpyServer.mmp
memspy/MemSpyServer/group/bld.inf
memspy/group/ReleaseNotes_MemSpy.txt
memspy/group/bld.inf
memspy/memspy_plat/memspy_api/include/MemSpyEngineClientInterface.h
memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverEnumerationsShared.h
memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverObjectsShared.h
memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverObjectsSharedRHeap.h
memspy/memspy_plat/memspy_api/include/memspy/driver/user/MemSpyDriverClient.h
memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperECom.h
memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperFbServ.h
memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperHeap.h
memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperKernelContainers.h
memspy/memspy_plat/memspy_api/include/memspy/engine/MemSpyEngine.h
memspy/memspy_plat/memspy_api/include/memspy/engine/MemSpyEngineImp.h
memspy/memspy_plat/memspy_api/include/memspy/engine/Sink/MemSpyEngineOutputSink.h
memspy/memspy_plat/memspy_api/include/memspy/engine/SysMemTracker/MemSpyEngineHelperSysMemTracker.h
memspy/memspy_plat/memspy_api/include/memspy/engine/SysMemTracker/MemSpyEngineHelperSysMemTrackerConfig.h
memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectProcess.h
memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectThread.h
memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectThreadInfoObjects.h
memspy/rom/memspy.iby
piprofiler/engine/inc/SamplerController.h
piprofiler/engine/src/ProfilerEshell.cpp
piprofiler/engine/src/SamplerController.cpp
piprofiler/group/ReleaseNotes_PIProfiler.txt
piprofiler/group/bld.inf
piprofiler/piprofiler_plat/inc/SamplerPluginInterface.h
piprofiler/plugins/BUPplugin/inc/BupPlugin.h
piprofiler/plugins/BUPplugin/src/BupPlugin.cpp
piprofiler/plugins/GeneralsPlugin/inc/GeneralsPlugin.h
piprofiler/plugins/GeneralsPlugin/src/GeneralsPlugin.cpp
piprofiler/plugins/GeneralsPlugin/src/GppSamplerImpl.cpp
piprofiler/plugins/GeneralsPlugin/src/MemSamplerImpl.cpp
piprofiler/plugins/PWRplugin/data/2001E5B9.rss
piprofiler/plugins/PWRplugin/group/PWRPlugin.mmp
piprofiler/plugins/PWRplugin/group/bld.inf
piprofiler/plugins/PWRplugin/inc/PwrPlugin.h
piprofiler/plugins/PWRplugin/sis/PWRPlugin.pkg
piprofiler/plugins/PWRplugin/src/PwrPlugin.cpp
piprofiler/plugins/PWRplugin/src/PwrPluginImplementationTable.cpp
piprofiler/rom/piprofiler.iby
piprofiler/rom/piprofiler_s2.iby
piprofiler/symbian_version.hrh
stif/ATSInterface/group/ATSInterface.mmp
stif/ATSInterface/group/bld.inf
stif/ATSInterface/inc/ATSInterface.h
stif/ATSInterface/inc/ATSInterfaceRunner.h
stif/ATSInterface/src/ATSInterface.cpp
stif/ATSInterface/src/ATSInterfaceRunner.cpp
stif/ATSLogger/Bmarm/ATSLOGGERU.DEF
stif/ATSLogger/Bwins/ATSLOGGERU.DEF
stif/ATSLogger/eabi/atsloggeru.def
stif/ATSLogger/group/atsloggerdll.mmp
stif/ATSLogger/group/bld.inf
stif/ATSLogger/src/atslogger.cpp
stif/ConsoleUI/group/ConsoleUI.mmp
stif/ConsoleUI/group/bld.inf
stif/ConsoleUI/inc/CallBack.h
stif/ConsoleUI/inc/ConsoleMenus.h
stif/ConsoleUI/inc/ConsoleUI.h
stif/ConsoleUI/src/ConsoleNotify.cpp
stif/ConsoleUI/src/ConsoleUI.cpp
stif/ConsoleUI/src/Consolemenus.cpp
stif/DemoModule/BMARM/Demomoduleu.def
stif/DemoModule/BWINS/Demomoduleu.def
stif/DemoModule/eabi/Demomoduleu.def
stif/DemoModule/group/Demomodule.mmp
stif/DemoModule/group/bld.inf
stif/DemoModule/inc/DemoModule.h
stif/DemoModule/src/DemoModule.cpp
stif/DemoModule/src/Demomodulecases.cpp
stif/Logger/inc/DataLogger.h
stif/Logger/inc/FileOutput.h
stif/Logger/inc/HtmlLogger.h
stif/Logger/inc/LoggerOverFlow.h
stif/Logger/inc/LoggerTracing.h
stif/Logger/inc/NullOutput.h
stif/Logger/inc/Output.h
stif/Logger/inc/RDebugOutput.h
stif/Logger/inc/TxtLogger.h
stif/Logger/src/DataLogger.cpp
stif/Logger/src/FileOutput.cpp
stif/Logger/src/HtmlLogger.cpp
stif/Logger/src/LoggerOverFlow.cpp
stif/Logger/src/NullOutput.cpp
stif/Logger/src/Output.cpp
stif/Logger/src/RDebugOutput.cpp
stif/Logger/src/StifLogger.cpp
stif/Logger/src/TxtLogger.cpp
stif/Parser/inc/ParserTracing.h
stif/Parser/inc/StifFileParser.h
stif/Parser/inc/cstackdeprecated.h
stif/Parser/inc/cstackdeprecated.inl
stif/Parser/src/StifFileParser.cpp
stif/Parser/src/StifItemParser.cpp
stif/Parser/src/StifParser.cpp
stif/Parser/src/StifSectionParser.cpp
stif/SUEvent/Bmarm/SUEventu.def
stif/SUEvent/Bwins/SUEventu.def
stif/SUEvent/eabi/SUEventu.def
stif/SUEvent/group/SUEvent.mmp
stif/SUEvent/group/bld.inf
stif/SUEvent/inc/SUEvent.h
stif/SUEvent/src/SUEvent.cpp
stif/SUEvent/src/SUEventCases.cpp
stif/StifKernelTestClassBase/Bwins/StifKernelTestClassBase_eka1u.def
stif/StifKernelTestClassBase/Bwins/StifKernelTestClassBaseu.def
stif/StifKernelTestClassBase/eabi/StifKernelTestClassBaseu.def
stif/StifKernelTestClassBase/group/StifKernelTestClassBase.mmp
stif/StifKernelTestClassBase/group/bld.inf
stif/StifKernelTestClassBase/src/StifKernelTestClassBase.cpp
stif/StifTFwIf/Bmarm/StifTFwIfu.def
stif/StifTFwIf/Bwins/StifTFwIfu.def
stif/StifTFwIf/eabi/StifTFwIfu.def
stif/StifTFwIf/group/StifTFwIf.mmp
stif/StifTFwIf/group/bld.inf
stif/StifTFwIf/inc/Logging.h
stif/StifTFwIf/inc/UIEngineError.h
stif/StifTFwIf/inc/UIEngineEvent.h
stif/StifTFwIf/inc/UIEnginePrinter.h
stif/StifTFwIf/inc/UIEngineRemote.h
stif/StifTFwIf/inc/UIEngineRunner.h
stif/StifTFwIf/inc/UIStorePopup.h
stif/StifTFwIf/src/StifTFwIf.cpp
stif/StifTFwIf/src/UIEngine.cpp
stif/StifTFwIf/src/UIEngineContainer.cpp
stif/StifTFwIf/src/UIEngineError.cpp
stif/StifTFwIf/src/UIEngineEvent.cpp
stif/StifTFwIf/src/UIEnginePrinter.cpp
stif/StifTFwIf/src/UIEngineRemote.cpp
stif/StifTFwIf/src/UIEngineRunner.cpp
stif/StifTFwIf/src/UIStore.cpp
stif/StifTFwIf/src/UIStoreContainer.cpp
stif/StifTFwIf/src/UIStorePopup.cpp
stif/TestCombiner/Bmarm/testcombineru.def
stif/TestCombiner/Bwins/testcombineru.def
stif/TestCombiner/eabi/testcombineru.def
stif/TestCombiner/group/TestCombiner.mmp
stif/TestCombiner/group/TestCombinerExample.cfg
stif/TestCombiner/group/bld.inf
stif/TestCombiner/inc/Logging.h
stif/TestCombiner/inc/StifPythonFunComb.h
stif/TestCombiner/inc/TestCase.h
stif/TestCombiner/inc/TestCaseNotify.h
stif/TestCombiner/inc/TestCombiner.h
stif/TestCombiner/inc/TestCombinerEvent.h
stif/TestCombiner/inc/TestCombinerUtils.h
stif/TestCombiner/inc/TestKeywords.h
stif/TestCombiner/src/StifPythonFunComb.cpp
stif/TestCombiner/src/TestCase.cpp
stif/TestCombiner/src/TestCaseNotify.cpp
stif/TestCombiner/src/TestCombiner.cpp
stif/TestCombiner/src/TestCombinerUtils.cpp
stif/TestCombiner/src/TestKeywords.cpp
stif/TestEngine/BMARM/StifTestEngineu.def
stif/TestEngine/BWINS/StifTestEngineu.def
stif/TestEngine/eabi/StifTestEngineu.def
stif/TestEngine/group/TestEngine.mmp
stif/TestEngine/group/bld.inf
stif/TestEngine/inc/Logging.h
stif/TestEngine/inc/STIFTestFrameworkSettings.h
stif/TestEngine/inc/SettingServer.h
stif/TestEngine/inc/StifPythonFunEng.h
stif/TestEngine/inc/TestCallBack.h
stif/TestEngine/inc/TestCaseController.h
stif/TestEngine/inc/TestEngine.h
stif/TestEngine/inc/TestEngineCommon.h
stif/TestEngine/inc/TestEngineEvent.h
stif/TestEngine/inc/TestModuleController.h
stif/TestEngine/inc/TestReport.h
stif/TestEngine/src/STIFTestFrameworkSettings.cpp
stif/TestEngine/src/SettingServer.cpp
stif/TestEngine/src/SettingServerClient.cpp
stif/TestEngine/src/SettingServerSession.cpp
stif/TestEngine/src/StifPythonFunEng.cpp
stif/TestEngine/src/TestCaseController.cpp
stif/TestEngine/src/TestEngine.cpp
stif/TestEngine/src/TestEngineClient.cpp
stif/TestEngine/src/TestModuleController.cpp
stif/TestEngine/src/TestModuleInfo.cpp
stif/TestEngine/src/TestReport.cpp
stif/TestEngine/src/Testcasetimeout.cpp
stif/TestInterface/BMARM/StifTestInterfaceu.def
stif/TestInterface/BWINS/StifTestInterfaceu.def
stif/TestInterface/eabi/StifTestInterfaceu.def
stif/TestInterface/group/TestInterface.mmp
stif/TestInterface/group/bld.inf
stif/TestInterface/src/StifTFwIfProt.cpp
stif/TestInterface/src/TestInterface.cpp
stif/TestInterface/src/TestModuleIf.cpp
stif/TestInterface/src/TestModuleParameters.cpp
stif/TestInterference/inc/TestInterferenceImplementation.h
stif/TestInterference/src/StifTestInterference.cpp
stif/TestModuleTemplates/CapsModifierXXX/CreateCapsModifier.bat
stif/TestModuleTemplates/CapsModifierXXX/group/CapsModifierXXX_exe.mmp
stif/TestModuleTemplates/CapsModifierXXX/group/CapsModifierXXX_exe.pkg
stif/TestModuleTemplates/CapsModifierXXX/group/CapsModifierXXX_exe_nrm.mmp
stif/TestModuleTemplates/CapsModifierXXX/group/bld.inf
stif/TestModuleTemplates/CapsModifierXXX/src/CapsModifierXXX_exe.cpp
stif/TestModuleTemplates/HardCodedTestModuleXXX/Bmarm/HARDCODEDTESTMODULEXXXU.DEF
stif/TestModuleTemplates/HardCodedTestModuleXXX/Bwins/HardCodedTestModuleXXXu.def
stif/TestModuleTemplates/HardCodedTestModuleXXX/createhardcodedmodule.bat
stif/TestModuleTemplates/HardCodedTestModuleXXX/eabi/HardCodedTestModuleXXXu.def
stif/TestModuleTemplates/HardCodedTestModuleXXX/group/HardCodedTestModuleXXX.mmp
stif/TestModuleTemplates/HardCodedTestModuleXXX/group/HardCodedTestModuleXXX.pkg
stif/TestModuleTemplates/HardCodedTestModuleXXX/group/HardCodedTestModuleXXX_DoxyFile.txt
stif/TestModuleTemplates/HardCodedTestModuleXXX/group/HardCodedTestModuleXXX_nrm.mmp
stif/TestModuleTemplates/HardCodedTestModuleXXX/group/bld.inf
stif/TestModuleTemplates/HardCodedTestModuleXXX/inc/HardCodedTestModuleXXX.h
stif/TestModuleTemplates/HardCodedTestModuleXXX/src/HardCodedTestModuleXXX.cpp
stif/TestModuleTemplates/HardCodedTestModuleXXX/src/HardCodedTestModuleXXXCases.cpp
stif/TestModuleTemplates/STIFUnitXXX/Bmarm/STIFUNITXXXU.DEF
stif/TestModuleTemplates/STIFUnitXXX/Bwins/STIFUnitXXXu.def
stif/TestModuleTemplates/STIFUnitXXX/CreateSTIFUnitModule.bat
stif/TestModuleTemplates/STIFUnitXXX/CreateSTIFUnitModuleVar2.bat
stif/TestModuleTemplates/STIFUnitXXX/eabi/STIFUNITXXXu.def
stif/TestModuleTemplates/STIFUnitXXX/group/STIFUnitXXX.mmp
stif/TestModuleTemplates/STIFUnitXXX/group/STIFUnitXXX.pkg
stif/TestModuleTemplates/STIFUnitXXX/group/STIFUnitXXX_nrm.mmp
stif/TestModuleTemplates/STIFUnitXXX/group/bld.inf
stif/TestModuleTemplates/STIFUnitXXX/src/STIFUnitXXX.cpp
stif/TestModuleTemplates/STIFUnitXXX/src/STIFUnitXXXCases.cpp
stif/TestModuleTemplates/TemplateKernelScriptXXX/CreateKernelTestClass.bat
stif/TestModuleTemplates/TemplateKernelScriptXXX/conf/TemplateKernelScriptXXX.cfg
stif/TestModuleTemplates/TemplateKernelScriptXXX/group/TemplateKernelScriptXXX.mmp
stif/TestModuleTemplates/TemplateKernelScriptXXX/group/TemplateKernelScriptXXX.pkg
stif/TestModuleTemplates/TemplateKernelScriptXXX/group/TemplateKernelScriptXXX_DoxyFile.txt
stif/TestModuleTemplates/TemplateKernelScriptXXX/group/TemplateKernelScriptXXX_nrm.mmp
stif/TestModuleTemplates/TemplateKernelScriptXXX/group/bld.inf
stif/TestModuleTemplates/TemplateKernelScriptXXX/inc/TemplateKernelScriptXXX.h
stif/TestModuleTemplates/TemplateKernelScriptXXX/src/TemplateKernelScriptXXX.cpp
stif/TestModuleTemplates/TemplateKernelScriptXXX/src/TemplateKernelScriptXXXBlocks.cpp
stif/TestModuleTemplates/TemplateScriptXXX/Bmarm/TEMPLATESCRIPTXXXU.DEF
stif/TestModuleTemplates/TemplateScriptXXX/Bwins/TemplateScriptXXXu.def
stif/TestModuleTemplates/TemplateScriptXXX/CreateTestClass.bat
stif/TestModuleTemplates/TemplateScriptXXX/conf/TemplateScriptXXX.cfg
stif/TestModuleTemplates/TemplateScriptXXX/eabi/TemplateScriptXXXu.def
stif/TestModuleTemplates/TemplateScriptXXX/group/TemplateScriptXXX.mmp
stif/TestModuleTemplates/TemplateScriptXXX/group/TemplateScriptXXX.pkg
stif/TestModuleTemplates/TemplateScriptXXX/group/TemplateScriptXXX_DoxyFile.txt
stif/TestModuleTemplates/TemplateScriptXXX/group/TemplateScriptXXX_nrm.mmp
stif/TestModuleTemplates/TemplateScriptXXX/group/bld.inf
stif/TestModuleTemplates/TemplateScriptXXX/inc/TemplateScriptXXX.h
stif/TestModuleTemplates/TemplateScriptXXX/src/TemplateScriptXXX.cpp
stif/TestModuleTemplates/TemplateScriptXXX/src/TemplateScriptXXXBlocks.cpp
stif/TestModuleTemplates/TestModuleTemplates.zip
stif/TestModuleTemplates/TestModuleXXX/Bmarm/TESTMODULEXXXU.DEF
stif/TestModuleTemplates/TestModuleXXX/Bwins/TestModuleXXXu.def
stif/TestModuleTemplates/TestModuleXXX/createmodule.bat
stif/TestModuleTemplates/TestModuleXXX/eabi/TestModuleXXXu.def
stif/TestModuleTemplates/TestModuleXXX/group/TestModuleXXX.mmp
stif/TestModuleTemplates/TestModuleXXX/group/TestModuleXXX.pkg
stif/TestModuleTemplates/TestModuleXXX/group/TestModuleXXX_DoxyFile.txt
stif/TestModuleTemplates/TestModuleXXX/group/TestModuleXXX_nrm.mmp
stif/TestModuleTemplates/TestModuleXXX/group/bld.inf
stif/TestModuleTemplates/TestModuleXXX/inc/TestModuleXXX.h
stif/TestModuleTemplates/TestModuleXXX/src/TestModuleXXX.cpp
stif/TestModuleTemplates/createtestmodule.bat
stif/TestScripter/Bmarm/testscripteru.def
stif/TestScripter/Bwins/testscripteru.def
stif/TestScripter/eabi/testscripteru.def
stif/TestScripter/group/TestScripter.mmp
stif/TestScripter/group/bld.inf
stif/TestScripter/inc/Logging.h
stif/TestScripter/inc/TestKeywords.h
stif/TestScripter/inc/TestScripter.h
stif/TestScripter/src/TestKeywords.cpp
stif/TestScripter/src/TestScripter.cpp
stif/TestScripter/src/TestScripterInternal.cpp
stif/TestServer/BMARM/StifTestServeru.def
stif/TestServer/BWINS/StifTestServeru.def
stif/TestServer/eabi/StifTestServeru.def
stif/TestServer/group/TestServer.mmp
stif/TestServer/group/bld.inf
stif/TestServer/inc/Logging.h
stif/TestServer/inc/PrintQueue.h
stif/TestServer/inc/TestServer.h
stif/TestServer/inc/TestServerCommon.h
stif/TestServer/inc/TestServerEvent.h
stif/TestServer/inc/TestThreadContainerRunner.h
stif/TestServer/inc/ThreadLogging.h
stif/TestServer/src/Printqueue.cpp
stif/TestServer/src/TestExecutionThread.cpp
stif/TestServer/src/TestModuleContainer.cpp
stif/TestServer/src/TestServer.cpp
stif/TestServer/src/TestServerClient.cpp
stif/TestServer/src/TestServerEvent.cpp
stif/TestServer/src/TestThreadContainerRunner.cpp
stif/TestServer/src/TestThreadContainerRunnerFactory.cpp
stif/TestServer/src/Testexecution.cpp
stif/TestServer/src/Testserversession.cpp
stif/TestServer/src/Testundertaker.cpp
stif/TestServerStarter/group/TestServerStarter.mmp
stif/TestServerStarter/group/bld.inf
stif/TestServerStarter/src/TestServerStarter.cpp
stif/TouchConsoleUI/group/TouchConsoleUI.mmp
stif/TouchConsoleUI/group/bld.inf
stif/TouchConsoleUI/inc/CallBack.h
stif/TouchConsoleUI/inc/ConsoleMenus.h
stif/TouchConsoleUI/inc/ConsoleUI.h
stif/TouchConsoleUI/src/ConsoleNotify.cpp
stif/TouchConsoleUI/src/ConsoleUI.cpp
stif/TouchConsoleUI/src/Consolemenus.cpp
stif/envpatcher/EnvPatcher.pl
stif/envpatcher/ReadMe.txt
stif/examples/STIFTestMeasurementStub/Bmarm/STIFTESTMEASUREMENTSTUBU.DEF
stif/examples/STIFTestMeasurementStub/Bwins/STIFTestMeasurementStubu.def
stif/examples/STIFTestMeasurementStub/eabi/STIFTestMeasurementStubu.def
stif/examples/STIFTestMeasurementStub/group/STIFTestMeasurementStub.mmp
stif/examples/STIFTestMeasurementStub/group/STIFTestMeasurementStub_DoxyFile.txt
stif/examples/STIFTestMeasurementStub/group/bld.inf
stif/examples/STIFTestMeasurementStub/inc/STIFTestMeasurementStub.h
stif/examples/STIFTestMeasurementStub/src/STIFTestMeasurementStub.cpp
stif/examples/StifHWResetStub/BMARM/STIFHWRESETSTUBU.DEF
stif/examples/StifHWResetStub/BWINS/StifHWResetStubu.def
stif/examples/StifHWResetStub/eabi/StifHWResetStubu.def
stif/examples/StifHWResetStub/group/StifHWResetStub.mmp
stif/examples/StifHWResetStub/group/bld.inf
stif/examples/StifHWResetStub/inc/StifHWResetStub.h
stif/examples/StifHWResetStub/src/StifHWResetStub.cpp
stif/group/ReleaseNote.txt
stif/group/TestFramework.ini
stif/group/bld.inf
stif/inc/STIFConfiguration.mmh
stif/inc/STIFMeasurement.h
stif/inc/StifKernelTestClass.h
stif/inc/StifKernelTestClass.inl
stif/inc/StifPython.h
stif/inc/StifTFw.h
stif/inc/TestModuleInfo.h
stif/inc/TestServerModuleIf.h
stif/inc/TestThreadContainer.h
stif/inc/version.h
stif/rom/STIFTestFramework.iby
stif/rom/Stif.iby
stif/rom/Stif_rom.iby
stif/sis/Stif.pkg
stif/sis/Stif_31.sis
stif/sis/Stif_31_Stub.SIS
stif/stif_plat/group/bld.inf
stif/stif_plat/inc/NormalHardcodedAssert.h
stif/stif_plat/inc/RRefArray.h
stif/stif_plat/inc/SettingServerClient.h
stif/stif_plat/inc/StifCommand.h
stif/stif_plat/inc/StifHWReset.h
stif/stif_plat/inc/StifItemParser.h
stif/stif_plat/inc/StifKernelTestClassBase.h
stif/stif_plat/inc/StifLogger.h
stif/stif_plat/inc/StifParser.h
stif/stif_plat/inc/StifSectionParser.h
stif/stif_plat/inc/StifTFwIf.h
stif/stif_plat/inc/StifTFwIfProt.h
stif/stif_plat/inc/StifTestEventInterface.h
stif/stif_plat/inc/StifTestInterface.h
stif/stif_plat/inc/StifTestInterference.h
stif/stif_plat/inc/StifTestModule.h
stif/stif_plat/inc/StifUnitGeneric.h
stif/stif_plat/inc/StifUnitMacros.h
stif/stif_plat/inc/StifUnitUtils.inl
stif/stif_plat/inc/TestEngineClient.h
stif/stif_plat/inc/TestEngineClient.inl
stif/stif_plat/inc/TestScripterInternal.h
stif/stif_plat/inc/TestServerClient.h
stif/stif_plat/inc/TestThreadContainerRunnerFactory.h
stif/stif_plat/inc/TestclassAssert.h
stif/stif_plat/inc/UIEngine.h
stif/stif_plat/inc/UIEngineContainer.h
stif/stif_plat/inc/UIStore.h
stif/stif_plat/inc/UIStoreContainer.h
stif/stif_plat/inc/UIStoreIf.h
stif/stif_plat/inc/UiEnvProxy.h
stif/stif_plat/inc/atslogger.h
--- a/analyzetool/analyzetool_plat/analyzetool_api/analyzetool_api.metaxml	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<api id="e7d1f55108565c675ad3ff377518344a" dataversion="2.0">
-  <name>AnalyzeTool API</name>
-  <description>Defines the API, which is used by application compiled with AnlayzeTool.</description>
-  <type>c++</type>
-  <collection>AnalyzeTool</collection>
-  <libs>
-    <lib name="atoolstaticlib.lib"/>
-    <lib name="atoolcleaner.lib"/>
-    <lib name="atoolmemoryhook.lib"/>
-  </libs>
-  <release category="platform" sinceversion=""/>
-  <attributes>
-    <htmldocprovided>no</htmldocprovided>
-    <adaptation>no</adaptation>
-  </attributes>
-</api>
--- a/analyzetool/analyzetool_plat/analyzetool_api/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <platform_paths.hrh>
-
-PRJ_EXPORTS
-// Analyzetool API
-../inc/analyzetool/analyzetool.h				            OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/analyzetool.h)
-../inc/analyzetool/analyzetool.inl				            OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/analyzetool.inl)
-../inc/analyzetool/analyzetoolcleaner.h				        OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/analyzetoolcleaner.h)
-../inc/analyzetool/analyzetooltraceconstants.h				OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/analyzetooltraceconstants.h)
-../inc/analyzetool/atcommon.h				                OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/atcommon.h)
-../inc/analyzetool/customuser.h				                OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/customuser.h)
-
--- a/analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/analyzetool.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,325 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Declaration of the class RAnalyzeTool.
-*
-*/
-
-
-#ifndef __ANALYZETOOL_H__
-#define __ANALYZETOOL_H__
-
-// INCLUDES
-#include <e32cmn.h>
-
-//Version information for command line engine.
-//Tells the version of AT core componenets.
-//ANALYZETOOL_CORE_VERSION_FOR_CLE 1.10.0
-
-// CONSTANTS
-inline TVersion KAnalyzeToolLddVersion() { return TVersion(1, 0, 1); }
-
-/* The name of the analyze tool device driver*/
-_LIT( KAnalyzeToolLddName, "AToolKernelEventHandler" );
-
-/* The priority of AnalyzeTool Dfc */
-const TInt KAnalyzeToolThreadPriority = 27;
-
-/* The name of the AnalyzeTool DFC */
-_LIT8( KAnalyzeToolThreadName, "AnalyzeToolThreadDfc" );
-
-/* The panic literal */
-_LIT( KClientPanic, "AnalyzeTool" );
-
-//const TInt KATMaxCallstackLength = 20;
-
-/* The device handler panic codes */
-enum TPanic
-	{
-	EPanicRequestPending,
-	EPanicNoRequestPending,
-	EPanicUnsupportedRequest
-	};
-
-// Size of following must be multiple of 4 bytes.
-
-class TMainThreadParams
-	{
-	public:
-		RAllocator* iAllocator;
-		TBool       iAlone;
-		TUint       iProcessId;
-	};
-typedef TPckgBuf<TMainThreadParams> TMainThreadParamsBuf;
-
-class TLibraryInfo
-	{
-	public:
-		TBuf8<KMaxLibraryName> iLibraryName;
-		TLinAddr  iRunAddress;
-		TUint32   iSize;
-		TInt      iIndex;
-		TUint     iProcessId;
-	};
-
-typedef TPckgBuf<TLibraryInfo> TLibraryInfoBuf;
-
-class TCodesegInfo
-	{
-	public:
-		TBuf8<KMaxLibraryName> iFullName;
-		TLinAddr iRunAddress;
-		TUint32  iSize;
-		TInt  iIndex;
-		TUint iProcessId;
-		TInt  iCodesegIndex; 
-		TLinAddr iFileEntryPoint;
-		TInt     iFuntionCount;
-		TLibraryFunction iFirstFunction;
-		TModuleMemoryInfo iMemoryInfo;
-	};
-
-typedef TPckgBuf<TCodesegInfo> TCodesegInfoBuf;
-
-class TThreadParams
-	{		
-	public:
-	    TLinAddr iStackAddress;
-	    TInt iStackSize;
-	    TUint iThreadId;
-	};
-
-typedef TPckgBuf<TThreadParams> TThreadParamsBuf;
-
-class TProcessIdentityParams
-	{		
-	public:
-		TBuf8<KMaxProcessName> iProcessName;
-		TInt iDynamicCount;
-		TInt iCodesegCount;
-		TUint iProcessId;
-		TUint iThreadId;
-	    TLinAddr iStackAddress;
-	    TInt iStackSize;
-	};
-
-typedef TPckgBuf<TProcessIdentityParams> TProcessIdentityParamsBuf;
-
-class TLibraryEventInfo
-	{
-	public:
-		enum TLibraryEvent
-			{ 
-			ELibraryAdded = 0, 
-			ELibraryRemoved,
-			EKillThread 
-			};
-					
-	public:
-		TUint iProcessId;
-		TBuf8<KMaxLibraryName> iLibraryName;
-		TLinAddr iRunAddress;
-		TUint32 iSize;
-		TLibraryEvent iEventType;
-		TUint iThreadId;
-	};
-
-typedef TPckgBuf<TLibraryEventInfo> TLibraryEventInfoBuf;
-
-class TProcessHandleInfo
-	{
-	public:
-		TInt     iProcessHandleCount;
-		TInt     iThreadHandleCount;
-		TInt     iIndex;
-		TInt     iThreadCount;
-		TLinAddr iUserStackRunAddress;
-		TInt     iUserStackSize;
-		TUint    iProcessId;
-	};
-
-typedef TPckgBuf<TProcessHandleInfo> TProcessHandleInfoBuf;
-
-/**
-*  A class for particular process's current handle count
-*/
-class TATProcessHandles
-    {
-    public:
-    
-        /** The ID of the process. */
-        TUint iProcessId;
-        
-        /** The number of current handles in the library. */
-        TInt iCurrentHandleCount;
-    };
-
-typedef TPckgBuf<TATProcessHandles> TATProcessHandlesBuf;
-
-class TClientCount
-    {
-    public:
-    
-        /** The count of clients */
-        TInt iClientCount;     
-    };
-
-typedef TPckgBuf<TClientCount> TClientCountBuf;
-
-class TATMemoryModel
-    {
-    public :
-        /* Memory model*/
-        TUint32 iMemoryModel;
-    };
-typedef TPckgBuf<TATMemoryModel> TATMemoryModelBuf;
-
-// CLASS DECLARATION
-
-/**
-*  The user-side handle to a logical channel which provides functions to 
-*  open a channel and to make requests to a analyze tool device driver. 
-*/
-
-class RAnalyzeTool : public RBusLogicalChannel
-	{
-	
-	public:
-		
-	/** Enumeration of supported functions */
-	enum TBasicAnalyzerControl
-		{
-		EGetProcessInfo = 0, /* The process information */
-		EGetCodesegInfo,	 /* The codesegment information */
-		EGetLibraryInfo,     /* The library information */
-		EGetDynamicInfo,	 /* The count of dynamic code in the process */
-		ELibraryEvent,       /* Subscribe events from library events */
-		ECancelLibraryEvent, /* Cancel subscribetion of library events */
-		ECurrentClientCount,  /* The count of clients in device driver */
-		EMainThreadAlloctor,
-		EThreadStack,
-		EGetProcessHandle,	/* Gets process global handles info*/
-		EGetCurrentHandles, /* Get a process's current handle count */
-		EGetMemoryModel
-		};
-			
-#ifndef __KERNEL_MODE__
-
-        /**
-        * Opens a handle to a logical channel.
-        * @return TInt Returns KErrNone, if successful or otherwise 
-        		  one of the other system-wide error codes
-        */
-		inline TInt Open();
-
-        /**
-        * Acquires process information.
-        * @param aProcessIdentityParams The process information which 
-        								is filled by the device driver
-        * @return TInt Returns KErrNone, if successful
-        			   otherwise one of the other system-wide error codes
-        */
-		inline TInt GetProcessInfo( 
-				TProcessIdentityParamsBuf& aProcessIdentityParams );
-
-        /**
-        * Acquires codeseg information.
-        * @param aCodesegInfo The codeseg information which 
-        					  is filled by the device driver
-        * @return TInt Returns KErrNone, if successful
-        			   otherwise one of the other system-wide error codes
-        */
-		inline TInt GetCodesegInfo( TCodesegInfoBuf& aCodesegInfo );
-		
-        /**
-        * Acquires library information.
-        * @param aLibraryInfo The library information which 
-        					  is filled by the device driver
-        * @return TInt Returns KErrNone, if successful
-        			   otherwise one of the other system-wide error codes
-        */
-		inline TInt GetLibraryInfo( TLibraryInfoBuf& aLibraryInfo );
-				
-        /**
-        * Subscribes library event.
-        * @param aStatus The request status object for this request. 
-        * @param aLibraryInfo The library information which 
-        					  is filled by the device driver
-        * @return TInt Returns KErrNone, if successful
-        			   otherwise one of the other system-wide error codes
-        */
-		inline void LibraryEvent( TRequestStatus& aStatus, 
-		                          TLibraryEventInfo& aLibraryInfo );
-		
-        /**
-        * Cancels subscribetion of the library event.
-        */
-		inline void CancelLibraryEvent();
-
-        /**
-        * Acquires device driver current client count.
-        * @param aClientCount A reference to TInt which is 
-        				      updated by the device driver.
-        * @return TInt Returns KErrNone, if successful
-        			   otherwise one of the other system-wide error codes
-        */
-		inline TInt ClientCount( TClientCountBuf& aClientCount );
-		
-        /**
-        * Acquires process main thread RAllocator
-        * @param aMainThreadParams The main thread information which 
-        					        is filled by the device driver
-        * @return TInt Returns KErrNone, if successful
-        			   otherwise one of the other system-wide error codes
-        */	
-		inline TInt MainThreadAlloctor( TMainThreadParamsBuf& aMainThreadParams );
-		
-		/**
-		* Acquires main thread stack address.
-		* @param aThreadStack Pointer to the TThreadParams object.
-		* @return TInt Returns KErrNone, if successful
-					   otherwise one of the other system-wide error codes
-		*/
-		inline TInt ThreadStack( TThreadParamsBuf& aThreadStack );
-
-        /**
-        * Acquires information about process global handles.
-        * @param aProcessHandleInfo Pointer to the TProcessHandleInfo object.
-        * @return TInt Returns KErrNone, if successful
-        			   otherwise one of the other system-wide error codes
-        */
-		inline TInt GetProcessHandleInfo( TProcessHandleInfoBuf& aProcessHandleInfo );
-
-        /**
-        * Acquires a process's current handle count.
-        * @param aProcessHandles Pointer to the TATProcessHandles object.
-        * @return TInt Returns KErrNone, if successful
-                       otherwise one of the other system-wide error codes
-        */
-        inline TInt GetCurrentHandleCount( TATProcessHandlesBuf& aProcessHandles );
-
-        /**
-         * Acquires memory model system uses.
-         * @param aMemoryModel pointer to the TATMemoryModelBuf object.
-         */
-        inline TInt GetMemoryModel( TATMemoryModelBuf& aMemoryModel );
-        
-#endif // #ifndef __KERNEL_MODE__
-	};
-
-// INLINES
-#include <analyzetool/analyzetool.inl>
-
-#endif // #ifndef __ANALYZETOOL_H__
-
-// End of File
--- a/analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/analyzetool.inl	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,159 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Definitions for inline methods of the class RAnalyzeTool.
-*
-*/
-
-
-#ifndef __ANALYZETOOL_INL
-#define __ANALYZETOOL_INL
-
-#ifndef __KERNEL_MODE__
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::Open()
-// Opens a handle to a analyze tool device driver
-// ----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::Open()
-	{
-	return DoCreate( KAnalyzeToolLddName, 
-					 KAnalyzeToolLddVersion(), 
-					 KNullUnit, 
-					 NULL, 
-					 NULL, 
-					 EOwnerProcess );
-	}
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::GetProcessInfo()
-// Acquires process information.
-// ----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::GetProcessInfo( 
-		TProcessIdentityParamsBuf& aProcessIdentityParams )
-	{
-	return DoControl( EGetProcessInfo, &aProcessIdentityParams, NULL );
-	}
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::GetCodesegInfo()
-// Acquires codeseg information.
-// ----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::GetCodesegInfo( TCodesegInfoBuf& aCodesegInfo )
-	{
-	return DoControl( EGetCodesegInfo, &aCodesegInfo, NULL );
-	}
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::GetLibraryInfo()
-// Symbian 2nd phase constructor can leave.
-// ----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::GetLibraryInfo( TLibraryInfoBuf& aLibraryinfo )
-	{
-	return DoControl( EGetLibraryInfo, &aLibraryinfo, NULL );
-	}
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::LibraryEvent()
-// Subscribes library event.
-// ----------------------------------------------------------------------------
-//
-inline void RAnalyzeTool::LibraryEvent( TRequestStatus& aStatus,
-	TLibraryEventInfo& aLibInfo )
-	{
-	return DoRequest( ELibraryEvent, aStatus, (TAny*)&aLibInfo );
-	}
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::CancelLibraryEvent()
-// Cancels subscribetion of the library event.
-// ----------------------------------------------------------------------------
-//
-inline void RAnalyzeTool::CancelLibraryEvent()
-	{
-	DoControl( ECancelLibraryEvent, NULL, NULL);
-	}
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::ClientCount()
-// Acquires the count of device driver current users
-// ----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::ClientCount( TClientCountBuf& aClientCount )
-	{
-	return DoControl( ECurrentClientCount, &aClientCount, NULL );
-	}
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::MainThreadAlloctor()
-// Acquires information about process main thread
-// ----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::MainThreadAlloctor( 
-	        TMainThreadParamsBuf& aMainThreadParams )
-    {
-    return DoControl( EMainThreadAlloctor, &aMainThreadParams, NULL );
-    }
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::ThreadStack()
-// Acquires main thread stack address.
-// ----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::ThreadStack( TThreadParamsBuf& aThreadStack )
-    {
-    return DoControl( EThreadStack, &aThreadStack, NULL );
-    }
-
-// ----------------------------------------------------------------------------
-// RAnalyzeTool::GetProcessHandleInfo()
-// Acquires information about process handles
-// ----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::GetProcessHandleInfo( 
-		    TProcessHandleInfoBuf& aProcessHandleInfo )
-    {
-    return DoControl( EGetProcessHandle, &aProcessHandleInfo, NULL );
-    }
-
-// -----------------------------------------------------------------------------
-// DAnalyzeToolChannel::GetCurrentHandleCount()
-// Acquires a process's current handle count
-// -----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::GetCurrentHandleCount( 
-		    TATProcessHandlesBuf& aProcessHandles )
-    {
-    return DoControl( EGetCurrentHandles, &aProcessHandles, NULL );
-    }
-
-// -----------------------------------------------------------------------------
-// DAnalyzeToolChannel::GetMemoryModel()
-// Acquires memory model system uses.
-// -----------------------------------------------------------------------------
-//
-inline TInt RAnalyzeTool::GetMemoryModel( 
-            TATMemoryModelBuf& aMemoryModel )
-    {
-    return DoControl( EGetMemoryModel, &aMemoryModel, NULL );
-    }
-
-#endif // #ifndef __KERNEL_MODE__
-
-#endif // __ANALYZETOOL_INL
-
-// End of file
--- a/analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/analyzetoolcleaner.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Definitions for the class TAnalyzeToolCleanerBase.
-*
-*/
-
-#ifndef __ANALYZETOOLCLEANER_H__
-#define __ANALYZETOOLCLEANER_H__
-
-// INCLUDES
-#include <e32std.h>
-
-// CONSTANTS
-#define ATCLEANERTABLESIZE 10
-#define ATCLEANERTABLE TFixedArray<TUint32, ATCLEANERTABLESIZE>
-_LIT( KATCleanerDllName, "atoolcleaner.dll" );
-
-// CLASS DECLARATION
-
-/**
-*  Cleaner base class
-*/
-class TAnalyzeToolCleanerBase
-    {
-public:
-    /**
-    * Cleanup function which uninstall allocator
-    */
-    virtual void Cleanup() = 0;
-    };
-
-// CLASS DECLARATION
-
-/**
-*  Cleaner class
-*/
-class THookCleaner
-    {
-public:
-    /**
-    * C++ default constructor.
-    */
-    THookCleaner();
-    
-    /**
-    * Destructor.
-    */
-    ~THookCleaner();
-    
-    ATCLEANERTABLE iTable;
-    };
-#endif // __ANALYZETOOLCLEANER_H__
--- a/analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/analyzetooltraceconstants.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,209 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Common declarations/definitions for Analyze Tool.
-*
-*/
-
-#ifndef __ANALYZETOOLTRACECONSTANTS_H__
-#define __ANALYZETOOLTRACECONSTANTS_H__
-
-#include <analyzetool/atcommon.h>
-
-// Trace version information.
-const TUint KATTraceVersion = 0x3;
-
-// The default logging mode 
-const TATLogOption KDefaultLoggingMode = EATLogToTraceFast;
-
-// When needed, update the data file's version number directly inside
-// the _LIT8 macro. Note, if you change this string, also remember to update
-// the constant "KVersionStringLength" below.
-
-_LIT8( KDataFileVersion, "ATOOL_BINARY_FILE_VERSION 1\n" );
-_LIT( KOpenSquareBracket, "[" );
-_LIT( KCloseSquareBracket, "]" );
-_LIT( KUnderLine, "_" );
-_LIT( KLeftBracket, "(" );
-_LIT( KRightBracket, ")" );
-
-_LIT8( KSpace, " " );
-_LIT8( KUdeb, "UDEB" );
-_LIT8( KUrel, "UREL" );
-    
-// Constants for logging through debug channel
-
-// remember to change length of KTagLength when length of constants changes
-
-_LIT8( KATIdentifier, "<AT> " );
-_LIT8( KProcessStart, "PCS " );
-_LIT8( KProcessEnd, "PCE " );
-_LIT8( KVersionsInfo, "DEVINFO ");
-_LIT8( KThreadStart, "TDS " );
-_LIT8( KThreadEnd, "TDE " );
-_LIT8( KDllLoad, "DLL " );
-_LIT8( KDllUnload, "DLU " );
-_LIT8( KTestStart, "TSS " );
-_LIT8( KTestEnd, "TSE " );
-_LIT8( KHandleLeak, "HDL " );
-_LIT8( KLoggingCancelled, "LGC " );
-_LIT8( KErrorOccured, "ERR " );
-_LIT8( KMemoryAllocHeader, "ALH " );
-_LIT8( KMemoryAllocFragment, "ALF " );
-_LIT8( KMemoryFreedHeader, "FRH " );
-_LIT8( KMemoryFreedFragment, "FRF " );
-_LIT8( KMemoryReallocHeader, "RAH " );
-_LIT8( KMemoryReallocFragment, "RAF " );
-
-//to be implemented on carbide side (was logged from storage server/ carbide extension)
-//_LIT( KSubtestStart, "TEST_START " );
-//_LIT( KSubtestEnd, "TEST_END " );
-
-// File name format
-_LIT( KFormat, "%S%S%02d%S%S");// pad char="0", field width=2
-
-// A string for setting time January 1st, 1970 AD nominal Gregorian
-_LIT( KJanuaryFirst1970, "19700000:000000.000000" );
-
-
-// todo
-// Module name when it cannot be defined
-// was used in "handle leak" message - always unknown
-//_LIT8( KUnknownModule, "Unknown" );
-
-// Constant time variable used to calculate timestamps for pc side.
-const TInt64  KMicroSecondsAt1970 = 62168256000000000;
-
-// The length of the string KDataFileVersion
-const TInt KVersionStringLength = 27;
-
-// The maximum length of one word (32 bits) represented in the hexadecimal text format
-// without "0x" prefix
-const TInt KHexa32Length = 8;
-
-// The maximum length of one word (32 bits) represented in the decimal text format
-const TInt KDec32Length = 10;
-
-// The maximum length of a TInt64 represented in the hexadecimal text format without
-// "0x" prefix
-const TInt KHexa64Length = 16;
-
-// The length of one space character in text
-const TInt KSpaceLength = 1;
-
-// The length of the AT message identifier with one space character ("<AT> ")
-const TInt KATIdentifierLength = 5;
-
-// The length of the tag with one space character (e.g. "FRH ")
-const TInt KTagLength = 4;
-
-// The length of atool version string (x.x.x)
-const TInt KAtoolVersionLength = 6;
-
-// The length of api version string (x.x.x)
-const TInt KApiVersionLength = 5;
-
-// The length of sw version version string
-const TInt KSwVersionLength = 64;
-
-// The length of the combination atId+processId+msgTag (<AT> NNN PCS )
-const TInt KTraceHeaderLength = KATIdentifierLength + KHexa32Length + KSpaceLength + KTagLength;
-
-// Max length of alloc, free, realloc last item (callstack adress)
-const TInt KLastItemLength = KHexa32Length + KSpaceLength;
-
-// The maximum length of the process start (PCS) buffer
-// <<AT>> <Process ID> PCS <Process name> <Time stamp> <Udeb> <Version>
-const TInt KProcessStartBufLength = KTraceHeaderLength + 
-									KMaxProcessName + KSpaceLength + 
-									KHexa32Length + KSpaceLength + 
-									KHexa64Length + KSpaceLength +
-									KHexa32Length;
-
-// The maximum length of the versions info (VER) buffer
-// <<AT>> <Process ID> VER <AT version> <API version> <S60 version> <ROM ID>
-const TInt KVersionsInfoBufLength = KTraceHeaderLength + 
-		                            KAtoolVersionLength + KSpaceLength +
-		                            KApiVersionLength + KSpaceLength +
-									KSwVersionLength + KSpaceLength + 
-									KHexa32Length;
-
-// The maximum length of the process end PCE buffer
-// <<AT>> <Process ID> PCE
-const TInt KProcessEndBufLength = KTraceHeaderLength;
-
-// The maximum length of the load dll (DLL) buffer
-// <<AT>> <Process ID> DLL <DLL name> <Memory start address> <Memory end address>
-const TInt KDllLoadBufLength = KTraceHeaderLength +
-		                       KMaxLibraryName + KSpaceLength +
-		                       KHexa32Length + KSpaceLength + 
-		                       KHexa32Length;
-
-// The maximum length of the unload dll (DLU) buffer
-// <<AT>> <Process ID> DLU <DLL name> <Memory start address> <Memory end address>
-const TInt KDllUnloadBufLength = KTraceHeaderLength + 
-		                         KMaxLibraryName + KSpaceLength +
-		                         KHexa32Length + KSpaceLength + 
-		                         KHexa32Length;
-        
-// The maximum length of the error (ERR) buffer
-// <<AT>> <Process ID> ERR <Thread ID> <Error code> <Error message> 
-const TInt KErrOccuredBufLength = KTraceHeaderLength +
-		                          KHexa64Length + KSpaceLength +
-		                          KHexa32Length + KSpaceLength +
-		                          200; //err message length
-                                        
-// The maximum length of the alloc "ALH /ALF" buffer. 
-const TInt KMemAllocBufLength = 255;
-
-// The maximum length of the free "FRH/FRF" buffer.
-const TInt KMemFreedBufLength = 255;
-
-// The maximum length of the realloc "REH/REF" buffer.
-const TInt KMemReallocBufLength = 255;
-
-// The maximum length of the handle leak "HDL" buffer
-// <<AT>> <Process ID> HDL <Handle count>
-const TInt KHandleLeakBufLength = KTraceHeaderLength +
-                                  KHexa32Length;
-                                        
-// The maximum length of the test satart "TSS" buffer
-// <<AT>> <Process ID> TSS <Sub test name> <Handle count>
-const TInt KTestStartBufLength = KTraceHeaderLength +
-                                 KATMaxSubtestIdLength + KSpaceLength +
-                                 KHexa64Length;
-
-// The maximum length of the test end (TSE) buffer
-// <<AT>> <Process ID> TSE <Sub test name> <Handle count>
-const TInt KTestEndBufLength = KTraceHeaderLength + 
-		                       KATMaxSubtestIdLength + KSpaceLength + 
-		                       KHexa64Length;
-
-// The maximum length of the thread start (TDS) buffer.
-// <<AT>> <Process ID> TDS <Thread ID>
-const TInt KThreadStartBufLength = KTraceHeaderLength +
-                                   KHexa64Length; 
-
-
-// The maximum length of the thread end (TDE) buffer.
-// <<AT>> <Process ID> TDE <Thread ID>
-const TInt KThreadEndBufLength = KTraceHeaderLength +
-                                 KHexa64Length; 
-
-// The maximun length of the file name extension buffer.
-const TInt KExtensionLength = 50;
-
-// The maximun length of the process UID3 buffer.
-const TInt KProcessUidLength = 20;
-
-#endif // __ANALYZETOOLTRACECONSTANTS_H__
--- a/analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/atcommon.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,108 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Common declarations/definitions for Analyze Tool.
-*
-*/
-
-
-#ifndef ATCOMMON_H_
-#define ATCOMMON_H_
-
-// CONSTANTS
-const TInt KATMaxCallstackLength = 256;
-const TInt KATMaxFreeCallstackLength = 256;
-const TInt KATMaxSubtestIdLength = 256;
-
-// The following constants only limit the configuration UI.
-// The bigger the number is, the more space will be allocated run-time
-// by the client. So, change with care.
-const TInt KATMaxProcesses = 20;
-const TInt KATMaxDlls = 30;
-
-// Constants defining call stack address range in multiple memory model.
-const TInt32 KATMultipleMemoryModelLowLimit = 0x70000000;
-const TInt32 KATMultipleMemoryModelHighLimit = 0x90000000;
-
-
-// CLASS DECLARATIONS
-
-/**
-*  A class for storing process information
-*/
-class TATProcessInfo
-    {
-    public:
-    
-        /** The ID of the process. */
-        TUint iProcessId;
-        
-        /** The name of the process. */
-        TBuf8<KMaxProcessName> iProcessName;
-        
-        /** The starting time of the process. */
-        TInt64 iStartTime;
-    };
-
-
-// ENUMERATIONS
-
-/**
-*  Enumeration for different logging modes of Analyze Tool 
-*/
-enum TATLogOption
-    {
-    /** Using the default. */
-    EATUseDefault = 0,
-    
-    /** Logging to a file in S60. */
-    EATLogToFile,
-    
-    /** Logging to debug channel. */
-    EATLogToTrace,
-    
-    /** Logging to debug channel bypassing storage server. */
-    EATLogToTraceFast,
-    
-    /** Logging switched off. */
-    EATLoggingOff
-    };
-
-/**
-*  Class which supports interfacing with AnalyzeTool exported
-*  functions. Mainly meant for STIF integration.
-*/
-class AnalyzeToolInterface
-    {
-    public:
-
-        /**
-        * This function starts subtest with a given name.
-        * @param aSubtestId The name identifying this particular sub test. The length
-        *   of this descriptor must not be greater than KATMaxSubtestIdLength, or
-        *   otherwise the method raises a STSEClient: 2 panic.
-        */
-        IMPORT_C static void StartSubTest( const TDesC8& aSubtestId );
-
-        /**
-        * This function stops a subtest with a given name.
-        * @param aSubtestId The name identifying this particular sub test. The length
-        *   of this descriptor must not be greater than KATMaxSubtestIdLength, or
-        *   otherwise the method raises a STSEClient: 2 panic. 
-        */   
-        IMPORT_C static void StopSubTest( const TDesC8& aSubtestId );
-
-    };
-    
-
-#endif /*ATCOMMON_H_*/
--- a/analyzetool/analyzetool_plat/analyzetool_api/inc/analyzetool/customuser.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,218 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Declaration of the class CustomUser containing overloaded User static functions.
-*
-*/
-
-
-#ifndef CUSTOMUSER_H
-#define CUSTOMUSER_H
-
-// INCLUDES
-#include <u32std.h>
-#include <e32svr.h>
-
-// CONSTANTS
-const TInt KATVersionLength = 20;
-const TInt KATDefaultLogOption = 0;
-const TInt KATDefaultDebug = 1;
-const TInt KATDefaultAllocCallStackSize = 40;
-const TInt KATDefaultFreeCallStackSize = 0;
-    
-// TYPEDEFS
-typedef TBuf<KATVersionLength> TATVersion;
-
-// Argument list for SetupThreadHeap function parameters. (currently not used)
-// When needed, update the argument type directly inside _LIT macro.
-_LIT( KATArgumentList, "%i%i" ); //etc. 
-
-// CLASS DECLARATION
-
-/**
-*  Class which overloads the User functions and provides access to 
-*  the overloaded functions  
-*/
-class CustomUser
-    {
-    public: // Enumerations
-        enum TATOptions
-            {
-            /** Acquiring the log filename */
-            ELogFileName = 1,   
-            /** Acquiring the version number */
-            EVersion,
-            /** Acquiring logging option */
-            ELogOption,
-            /** Acquiring UDEB/UREL information */  
-            EDebug,
-            /** Acquiring max allocation call stack size */
-            EAllocCallStackSize,
-            /** Acquiring max free call stack size */
-            EFreeCallStackSize,
-            /** Acquiring the path of logfile */
-            ELogFilePath
-            };
-        
-    public:
-
-        /**
-        * Overloaded version of User::Exit()
-        * Terminates the current thread, specifying a reason. All child 
-        * threads are terminated and all resources are cleaned up.If the 
-        * current thread is the main thread in a process, the process is
-        * also terminated.
-        * @param aReason The reason code.
-        */
-        IMPORT_C static void Exit( TInt aReason );
-
-        /**
-        * Overloaded version of User::Panic()
-        * Panics the current thread, specifying a category name and panic
-        * number. Keep the length of the category name small;
-        * a length of 16 is ideal.
-        * @param aCategory A reference to the descriptor containing the text 
-        * that defines the category for this panic.
-        * @param aReason The panic number. 
-        */   
-        IMPORT_C static void Panic( const TDesC& aCategory, TInt aReason );
-
-        /**
-        * Overloaded version of UserHeap::SetupThreadHeap()
-        * Setups the threads heap.
-        * @param aNotFirst Is this first thread using specified heap
-        * @param aInfo Specifies the thread heap properties
-        * @param aFileName The name of the log file
-        * @param aLogOption The logging option
-        * @param aIsDebug Determines whether a binary is UDEB or UREL
-        * @param aVersion Atool version number
-        * @param aAllocCallStackSize Max number of stored callstack items when memory allocated
-        * @param aFreeCallStackSize Max number of stored callstack items when memory freed
-        * @param aFmt A descriptor containing the format string
-        * @return TInt KErrNone, if the insertion is successful, otherwise 
-        * one of the system wide error codes.
-        */   
-        IMPORT_C static TInt SetupThreadHeap( 
-                             TBool aNotFirst, 
-                             SStdEpocThreadCreateInfo& aInfo,
-                             const TFileName& aFileName,
-                             const TPath& aFilePath,
-                             TUint32 aLogOption, TUint32 aIsDebug,
-                             const TATVersion& aVersion,
-                             TUint32 aAllocCallStackSize,
-                             TUint32 aFreeCallStackSize,
-                             TRefByValue<const TDesC> aFmt, ... );
-                             
-        /**
-        * Overloaded version of UserHeap::SetCritical()
-        * Sets up or changes the effect that termination of the current 
-        * thread has, either on its owning process, or on the whole system.
-        * The precise effect of thread termination is defined by the following
-        *  specific values of the TCritical enum:
-        * ENotCritical
-        * EProcessCritical
-        * EProcessPermanent
-        * ESystemCritical
-        * ESystemPermanent
-        * Notes: The enum value EAllThreadsCritical cannot be set using this
-        * function. It is associated with a process, not a thread, and, if 
-        * appropriate, should be set using User::SetProcessCritical().
-        * The states associated with ENotCritical, EProcessCritical, 
-        * EProcessPermanent, ESystemCritical and ESystemPermanent are all 
-        * mutually exclusive, i.e. the thread can only be in one of these 
-        * states at any one time.
-        * @param aCritical The state to be set.
-        * @return TInt KErrNone, if successful; KErrArgument, if 
-        * EAllThreadsCritical is passed - this is a state associated with a 
-        * process, and you use User::SetProcessCritical() to set it.
-        */ 
-        IMPORT_C static TInt SetCritical( User::TCritical aCritical );
-        
-        /**
-        * Overloaded version of UserHeap::SetCritical()
-        * Sets up or changes the effect that termination of subsequently 
-        * created threads will have, either on the owning process, 
-        * or on the whole system. It is important to note that we are not
-        * referring to threads that have already been created, but threads
-        * that will be created subsequent to a call to this function.
-        * The precise effect of thread termination is defined by the following
-        * specific values of the TCritical enum:
-        * ENotCritical
-        * EAllThreadsCritical
-        * ESystemCritical
-        * ESystemPermanent
-        * Notes:
-        * The enum values EProcessCritical and EProcessPermanent cannot be set
-        * using this function. They are states associated with a thread, not a
-        * process, and, if appropriate, should be set using 
-        * User::SetCritical(). The states associated with ENotCritical, 
-        * EAllThreadsCritical, ESystemCritical and ESystemPermanent are all 
-        * mutually exclusive, i.e. the process can only be in one of these 
-        * states at any one time.
-        * @param aCritical The state to be set.
-        * @return TInt KErrNone, if successful; KErrArgument, if either 
-        * EProcessCritical or EProcessPermanent is passed - these are states
-        * associated with a thread, and you use User::SetCritical() 
-        * to set them.
-        */ 
-        IMPORT_C static TInt SetProcessCritical( User::TCritical aCritical );
-                
-    private: // Private functions
-        
-        /**
-        * Factory function for creating RAllocator instances.
-        * @param aNotFirst Is this first thread using specified heap
-        * @param aLogOption The logging option
-        * @param aFileName The name of the logging file
-        * @param aIsDebug Determines whether a binary is UDEB or UREL
-        * @param aAllocCallStackSize Max number of stored callstack items when memory allocated
-        * @param aFreecallStackSize Max number of stored callstack items when memory freed
-        * @param aAtoolVersion Version of atool
-        * @param aApiVersion  Version of atool's api
-        * @return RAllocator& A reference to created allocator
-        */  
-        static RAllocator& InstallAllocator( TBool aNotFirst,
-                                             const TFileName& aFileName,
-                                             const TPath& aFilePath,
-                                             TUint32 aLogOption, TUint32 aIsDebug,
-                                             TUint32 aAllocCallStackSize,
-                                             TUint32 aFreeCallStackSize, 
-                                             const TDesC8& aAtoolVersion,
-                                             const TDesC8& aApiVersion );
-        
-		/**
-		* Check atool version
-		* @param aVersion - Atool version number.
-		* @param aToolVersion The atool version number
-		* @return KErrNone if correct version found, otherwise one of the system wide 
-		* error codes.
-		*/
-        static TInt CheckVersion( const TATVersion& aVersion, TDes& aToolVersion, TDes& aApiVersion ); 
-        
-
-        /**
-		* Function for showing incorrect version information (file or debug channel).
-		* @param aLogOption The logging option
-		* @param aFileName The name of the log file
-		* @param aToolVersion The atool version number
-		*/
-        static void ReportIncorrectVersion( const TUint32 aLogOption, 
-											const TFileName& aFileName,
-											const TPath& aFilePath,
-											const TDes& aToolVersion );
-        
-    };
-
-#endif // CUSTOMUSER_H
-
-// End of File
--- a/analyzetool/analyzetool_plat/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,19 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description: 
-*
-*/
-
-// Analyze Tool API
-#include "../analyzetool_api/group/bld.inf"
--- a/analyzetool/analyzetoolcleaner/group/analyzetoolcleaner.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/analyzetoolcleaner/group/analyzetoolcleaner.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -30,7 +30,6 @@
 
 USERINCLUDE   ../inc
 USERINCLUDE   ../../inc
-USERINCLUDE   ../../analyzetool_plat/analyzetool_api/inc/analyzetool
 
 OS_LAYER_SYSTEMINCLUDE
 
--- a/analyzetool/analyzetoolcleaner/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/analyzetoolcleaner/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -1,22 +1,8 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  
-*
-*/
-
 PRJ_PLATFORMS
 ARMV5 WINSCW
 
+PRJ_EXPORTS
+../inc/analyzetoolcleaner.h  OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/analyzetoolcleaner.h)
+
 PRJ_MMPFILES
 analyzetoolcleaner.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/analyzetoolcleaner/inc/analyzetoolcleaner.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,63 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for the class TAnalyzeToolCleanerBase.
+*
+*/
+
+#ifndef __ANALYZETOOLCLEANER_H__
+#define __ANALYZETOOLCLEANER_H__
+
+// INCLUDES
+#include <e32std.h>
+
+// CONSTANTS
+#define ATCLEANERTABLESIZE 10
+#define ATCLEANERTABLE TFixedArray<TUint32, ATCLEANERTABLESIZE>
+_LIT( KATCleanerDllName, "atoolcleaner.dll" );
+
+// CLASS DECLARATION
+
+/**
+*  Cleaner base class
+*/
+class TAnalyzeToolCleanerBase
+    {
+public:
+    /**
+    * Cleanup function which uninstall allocator
+    */
+    virtual void Cleanup() = 0;
+    };
+
+// CLASS DECLARATION
+
+/**
+*  Cleaner class
+*/
+class THookCleaner
+    {
+public:
+    /**
+    * C++ default constructor.
+    */
+    THookCleaner();
+    
+    /**
+    * Destructor.
+    */
+    ~THookCleaner();
+    
+    ATCLEANERTABLE iTable;
+    };
+#endif // __ANALYZETOOLCLEANER_H__
--- a/analyzetool/commandlineengine/group/atool.vcproj	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/group/atool.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -241,10 +241,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\src\CATParseBinaryFile.cpp"
-				>
-			</File>
-			<File
 				RelativePath="..\src\CATParseTraceFile.cpp"
 				>
 			</File>
@@ -339,10 +335,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\src\CATParseBinaryFile.h"
-				>
-			</File>
-			<File
 				RelativePath="..\inc\CATParseTraceFile.h"
 				>
 			</File>
@@ -351,10 +343,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\inc\CATProcessData.h"
-				>
-			</File>
-			<File
 				RelativePath="..\inc\CATProject.h"
 				>
 			</File>
--- a/analyzetool/commandlineengine/inc/ATCommonDefines.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/inc/ATCommonDefines.h	Wed Oct 13 16:17:58 2010 +0300
@@ -23,51 +23,6 @@
 
 using namespace std;
 
-#define MAIN_ID "<AT>"
-#define ALLOC_ID "ALLOC" // < V.1.6 allocation. // todo remove
-#define ALLOCH_ID "ALH" // Header of multi message allocation.
-#define ALLOCF_ID "ALF" // Fragment of multi message allocation.
-#define REALLOCH_ID "RAH" // Header of multi message reallocation.
-#define REALLOCF_ID "RAF" // Fragment of multi message reallocation.
-#define FREE_ID "FREE"
-#define FREEH_ID "FRH" // Header of multi message free.
-#define FREEF_ID "FRF" // Fragment of multi message free.
-#define HANDLE_LEAK_ID "HANDLE_LEAK"
-
-const string ERROR_OCCURED = "ERR"; // Error messages.
-const string INCORRECT_ATOOL_VERSION = "INCORRECT_ATOOL_VERSION";
-
-// if changed, change also in analyzetoolfilelog.h
-enum EMessageType{
-    EFileVersion = 0,
-	EProcessStart,
-    EProcessEnd,
-    EThreadStart,
-	EThreadEnd,
-	EDllLoad,
-	EDllUnload,
-	EAllocH,
-	EAllocF,
-	EFreeH,
-	EFreeF,
-	EReallocH,
-	EReallocF,
-	ETestStart,
-	ETestEnd,
-	EHandleLeak,
-	EDeviceInfo,
-	EError  
-    };
-
-/**
-* Invalid characters in trace file line content.
-* These will be filtered out before actuall parsing of line.
-10 = LF
-13 = CR
-124 = |
-*/
-const char cINVALID_TRACE_FILE_CHARS[] = { 10, 13, 124 };
-
 /**
 * Atool return code.
 */
@@ -126,12 +81,9 @@
 // makefile dir is used in atool.cpp to check will we use sbs2 (in analyze and clear)
 #define RAPTOR_MAKEFILE_DIR "atool_temp\\build"
 
-//part of user defined filename to be replaced by process name
-const string AT_PROCESSNAME_TAG = "%processname%";
-
 // Atool version number and date
-#define ATOOL_VERSION "1.10.0" // NOTE! This version number is written also to temporary cpp file.
-#define ATOOL_DATE "2nd July 2010"
+#define ATOOL_VERSION "1.9.1" // NOTE! This version number is written also to temporary cpp file.
+#define ATOOL_DATE "29th April 2010"
 
 // Default/min/max call stack sizes
 const int AT_ALLOC_CALL_STACK_SIZE_DEFAULT = 40;
@@ -144,10 +96,10 @@
 
 // Constant compatibility string in temporary cpp.
 // Api version ; current version.
-#define ATOOL_COMPATIBILITY_STRING "1.7.6;1.10.0"
+#define ATOOL_COMPATIBILITY_STRING "1.7.5;1.9.1"
 
 // Datafile version
-#define AT_DATA_FILE_VERSION "DATA_FILE_VERSION 12"
+#define AT_DATA_FILE_VERSION "DATA_FILE_VERSION 11"
 
 // Latest dbghelp.dll version
 const int DBGHELP_VERSION_MAJ = 6;
@@ -163,8 +115,7 @@
 const string AT_BUILD_SUMMARY_TARGET = "\tTarget: ";
 const string AT_BUILD_SUMMARY_FAILED = "Build failed: ";
 const string AT_BUILD_SUMMARY_ERRORS = "\tErrors: ";
-const string AT_BUILD_SUMMARY_DATA_FILE_NAME = "\tLog file name: ";
-const string AT_BUILD_SUMMARY_DATA_FILE_PATH = "\tLog file path: ";
+const string AT_BUILD_SUMMARY_DATA_FILE_NAME = "\tInternal data gathering filename: ";
 const string AT_BUILD_SUMMARY_NORMAL_BUILD_COMPLETE = "Normal build complete: ";
 const string AT_BUILD_SUMMARY_STATIC_LIBRARY = "\tModule is static library.";
 const string AT_BUILD_SUMMARY_UNSUPPORTED_TARGET_TYPE = "\tModule has unsupported target type.";
@@ -176,9 +127,9 @@
 const string AT_BUILD_SUMMARY_LOGGING_MODE = "Data gathering mode: ";
 const string AT_BUILD_SUMMARY_ALLOC_CALL_STACK_SIZE = "Allocation call stack size: ";
 const string AT_BUILD_SUMMARY_FREE_CALL_STACK_SIZE = "Free call stack size: ";
-const string AT_BUILD_SUMMARY_FILE = "log to file";
+const string AT_BUILD_SUMMARY_FILE = "monitored internal";
 const string AT_BUILD_SUMMARY_TRACE = "monitored external";
-const string AT_BUILD_SUMMARY_TRACE_FAST = "output to trace";
+const string AT_BUILD_SUMMARY_TRACE_FAST = "external";
 
 const string AT_UNSUPPORTED_TARGET_TYPE = "\tModule has unsupported target type.";
 const string AT_UNSUPPORTED_COMPILE_DEFINITION = "\tModule defined unsupported compile definition.";
@@ -353,21 +304,17 @@
 
 // Trace file constants definitions
 #define LABEL_DATA_FILE_VERSION "DATA_FILE_VERSION"
-#define LABEL_PROCESS_START     "PCS"
-#define LABEL_DLL_LOAD          "DLL"
-#define LABEL_DLL_UNLOAD		"DLU"
+#define LABEL_PROCESS_START     "PROCESS_START"
+#define LABEL_DLL_LOAD          "DLL_LOAD"
+#define LABEL_DLL_UNLOAD		"DLL_UNLOAD"
 #define LABEL_MEM_LEAK          "MEM_LEAK"
-#define LABEL_PROCESS_END       "PCE"
-#define LABEL_ERROR_OCCURED     "ERR"
-#define LABEL_HANDLE_LEAK       "HDL"
-#define LABEL_TEST_START        "TSS"
-#define LABEL_TEST_END          "TSE"
-#define LABEL_THREAD_START		"TDS"
-#define LABEL_THREAD_END		"TDE"
-#define LABEL_DEVICE_INFO		"DEVINFO"
+#define LABEL_PROCESS_END       "PROCESS_END"
+#define LABEL_ERROR_OCCURED     "ERROR_OCCURED"
+#define LABEL_HANDLE_LEAK       "HANDLE_LEAK"
+#define LABEL_TEST_START        "TEST_START"
+#define LABEL_TEST_END          "TEST_END"
 #define LABEL_LOGGING_CANCELLED "LOGGING_CANCELLED"
 
-
 // AddressToLine related constants
 
 #define LABEL_ABNORMAL "ABNORMAL"
@@ -524,10 +471,8 @@
 {
 	bool bNoBuild; /** Only intrument project? (no build) */ 
 	bool bDataFileName; /** Is internal data gathering filename defined */
-	bool bDataFilePath; /** Is internal data gathering file path defined */
 	bool bAbldTest; /** Is build only for test modules (abld test build.. */
 	string sDataFileName; /** Internal data gathering filename */
-	string sDataFilePath; /** Path to internal data gathering file */
 	int iBuildSystem; /** 1 = sbs, 2 = raptor */
 	int iLoggingMode; /** Just for old parameter parsing. 1=trace, 2=file, 0=? */
 	int iAllocCallStackSize; /** Call stack size when memory allocated */
@@ -546,9 +491,7 @@
 		bNoBuild = false;
 		bAbldTest = false;
 		bDataFileName = false;
-		bDataFilePath = false;
 		sDataFileName = "";
-		sDataFilePath = "";
 		iBuildSystem = 0;
 		iLoggingMode = 0;
 		iAllocCallStackSize = AT_ALLOC_CALL_STACK_SIZE_DEFAULT;
--- a/analyzetool/commandlineengine/inc/CATBase.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/inc/CATBase.h	Wed Oct 13 16:17:58 2010 +0300
@@ -170,13 +170,6 @@
 	static string RemovePathAndExt( string sFileName, bool bReverseFindExt = false );
 
 	/**
-	* Returns time  stamp in microseconds parsed from start of trace message
-	* @param sLineStart
-	* @return int
-	*/
-	unsigned __int64 ParseTimeStamp( string sLineStart );
-
-	/**
 	* Check if given file exists.
 	* @param pFilename Pointer to file name.
 	* @return False If file does not exists.
@@ -290,16 +283,6 @@
 	static string GetStringUntilNextSpace( string& sInput, bool bEraseFromInput = true );
 
 	/**
-	* Function returns string from begin of given string until next atool's main id <AT>,
-	* characters until next space are removed from sInput string.
-	*
-	* @param sInput Line which contains main id.
-	* @param bEraseFromInput If true characters before main id will be removed.
-	* @return string String until main id.
-	*/
-	static string GetStringUntilMainId( string& sInput, bool bEraseFromInput = true );
-
-	/**
 	* Convert unix path to windows
 	* @param sPath
 	*/
@@ -310,7 +293,6 @@
 	* @param sId unique id to add in file name
 	* @param sPath where to create
 	* @param sS60FileName of the logging file
-	* @param sS60FilePath of the logging file
 	* @param iLogOption logging mode
 	* @param iIsDebug build type
 	* @param iAllocCallStackSize
@@ -320,7 +302,6 @@
 	static bool CreateTemporaryCpp( const string& sId
 								 ,const string& sPath
 								 ,const string& sS60FileName
-								 ,const string& sS60FilePath
 								 ,int iLogOption
 								 ,int iIsDebug
 								 ,int iAllocCallStackSize
@@ -364,13 +345,6 @@
 	static bool IsDataFile( string sFile );
 
 	/**
-	* checks given file is it binary log file
-	* @param sFile
-	* @return true if it is binary logfile
-	*/
-	static bool IsBinaryLogFile( string sFile );
-
-	/**
 	* Parses a path string containing ".." to a valid
 	* path without relations. If given string does
 	* not contain relations it will not be changed
--- a/analyzetool/commandlineengine/inc/CATModule2.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/inc/CATModule2.h	Wed Oct 13 16:17:58 2010 +0300
@@ -74,7 +74,6 @@
 	/**
 	* Create AT temporary cpp file for module.
 	* @param sS60FileName.
-	* @param sS60FileName.
 	* @param eLoggingMode.
 	* @param eBuildType.
 	* @param iAllocCallStackSize.
@@ -82,19 +81,12 @@
 	* @return true if successful.
 	*/
 	bool CreateTempCpp(const string& sS60FileName
-		, const string& sS60FilePath
 		, int eLoggingMode
 		, int eBuildType
 		, int iAllocCallStackSize
 		, int iFreeCallStackSize );
 
 	/**
-	* returns default data file name without extension in format processName.targetType
-	* @return string with default file name
-	*/
-	string GetDefaultFileName();
-
-	/**
 	* Add AT changes to modules mmp file.
 	* @return true if successful.
 	*/
@@ -295,12 +287,6 @@
 	string GetS60FileName() const;
 
 	/**
-	* Set S60 logging file name.
-	* @param aFileName s60 logging file name.
-	*/
-	void SetS60FileName( const string& aFileName );
-
-	/**
 	* Set target binary name.
 	* @param sTarget binary file name.
 	*/
@@ -528,10 +514,6 @@
 	vector<MAP_FUNC_INFO> m_vMapFileFuncList;
 	// File logging mode filename.
 	string m_sS60FileName;
-	// true if file name not empty and %processname% string replaced
-	bool m_bS60FileNameResolved;
-	// File logging mode file path.
-	string m_sS60FilePath;
 	// Is all data loaded for address to code line functions.
 	bool m_bAddressToLineInitialized;
 	// Read listing files (armv5 platform).
--- a/analyzetool/commandlineengine/inc/CATParseBinaryFile.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,113 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Definitions for class CATParseTrace, CProcessData and
-*               CSubTestData.
-*
-*/
-
-
-#ifndef __CATPARSEBINARYFILE_H__
-#define __CATPARSEBINARYFILE_H__
-
-#include "../inc/ATCommonDefines.h"
-#include "../inc/CATDataSaver.h"
-#include "../inc/CATBase.h"
-#include "../inc/catallocs.h"
-
-/**
-* Parses raw trace data to AnalyzeTool specific data file.
-*/
-class CATParseBinaryFile : public CATBase
-{
-public:
-	/**
-	* Constructor
-	*/
-	CATParseBinaryFile();
-
-	/**
-	* Main function to start parse.
-	*
-	* @param pFileName A trace file name
-	* @param pOutputFileName Pointer to output file name
-	*/
-	bool StartParse( const char* pFileName, const char* pOutputFileName );
-
-	/**
-	* Get data saver
-	* @return CATDataSaver*
-	*/
-	CATDataSaver* GetDataSaver(void);
-	
-	/**
-	* Gets 64bit number from input string
-	* @param cVal Input data
-	* @return Acquired number
-	*/
-	unsigned __int64 StringToNum64( unsigned char* cVal );
-
-	/**
-	* Gets 32bit number from input string
-	* @param cVal Input data
-	* @return Acquired number
-	*/
-	unsigned long StringToNum32( unsigned char* cVal );
-
-	/**
-	* Get next string from file
-	* @param pData Acquired data
-	* @param pIn Input file stream
-	* @param pStreamPos Actuall position in file
-	* @param pStreamEnd End of file
-	* @return false if no error
-	*/
-	bool GetString( unsigned char* pData, ifstream &pIn, size_t &streamPos,  size_t streamEnd );
-
-	/**
-	* Get next 8bit number from file
-	* @param pData Acquired data
-	* @param pIn Input file stream
-	* @param pStreamPos Actuall position in file
-	* @param pStreamEnd End of file
-	* @return false if no error
-	*/
-	bool GetNum8( unsigned char* pData, ifstream &pIn, size_t &pStreamPos, size_t pStreamEnd );
-
-	/**
-	* Get next 32bit number from file
-	* @param pData Acquired data
-	* @param pIn Input file stream
-	* @param pStreamPos Actuall position in file
-	* @param pStreamEnd End of file
-	* @return false if no error
-	*/
-	bool GetNum32( unsigned char* pData, ifstream &pIn, size_t &pStreamPos, size_t pStreamEnd );
-
-	/**
-	* Get next 64bit number from file
-	* @param pData Acquired data
-	* @param pIn Input file stream
-	* @param pStreamPos Actuall position in file
-	* @param pStreamEnd End of file
-	* @return false if no error
-	*/
-	bool GetNum64( unsigned char* pData, ifstream &pIn, size_t &pStreamPos, size_t pStreamEnd );
-
-#ifndef MODULE_TEST
-private:
-#endif
-	CATDataSaver m_DataSaver; /** Data saver */
-};
-
-#endif
\ No newline at end of file
--- a/analyzetool/commandlineengine/inc/CATParseTraceFile.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/inc/CATParseTraceFile.h	Wed Oct 13 16:17:58 2010 +0300
@@ -42,21 +42,13 @@
 	* @param pFileName A trace file name
 	* @param pOutputFileName Pointer to output file name
 	*/
-	bool StartParse( const char* pFileName, const char* pOutputFileName, const char* pCleanedTraceFile = NULL );
+	bool StartParse( const char* pFileName, const char* pOutputFileName );
 
 	/**
 	* Get data saver
 	* @return CATDataSaver*
 	*/
-	CATDataSaver* GetDataSaver(void);
-	
-	/**
-	* Get time from timestamp in microseconds as string
-	* @param iTimeStamp Timestamp for current message
-	* @param iTimeSpan Timespan for current process
-	* @return string Acquired time in microseconds(as string)
-	*/
-	static string GetTimeFromTimeStamp( unsigned __int64 iTimeStamp, unsigned __int64 iTimeSpan );
+	CATDataSaver* GetDataSaver(void);	
 
 #ifndef MODULE_TEST
 private:
@@ -64,4 +56,36 @@
 	CATDataSaver m_DataSaver; /** Data saver */
 };
 
+/**
+* Represents data of a single subtest.
+*/
+class CSubTestData : public CATAllocs
+{
+public:
+	// Members
+
+	bool bRunning; /** Is sub test running */
+	vector<string> vData; /** data */
+	string sSubTestName; /** test name */
+	string sStartTime; /** start time */
+	string sEndTime; /** end time */
+	string sSubTestStartHandleCount; /** handle count at start */
+	string sSubTestEndHandleCount; /** handle count at end */
+};
+
+/**
+* Represents data of a single run.
+*/
+class CProcessData : public CATAllocs
+{
+public:
+	// Members
+
+	bool bProcessOnGoing; /** is process on going */
+	int iProcessID; /** process id (pid)*/
+	vector<string> vData; /** data */
+	vector<string> vHandleLeaks; /** handle leak(s) */
+	vector<CSubTestData> vSubTests; /** process sub test(s) */
+};
+
 #endif
--- a/analyzetool/commandlineengine/inc/CATProcessData.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,58 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Definitions for class CATParseTrace, CProcessData and
-*               CSubTestData.
-*
-*/
-
-#ifndef __CATPROCESSDATA_H__
-#define __CATPROCESSDATA_H__
-
-/**
-* Represents data of a single subtest.
-*/
-class CSubTestData : public CATAllocs
-{
-public:
-	// Members
-
-	bool bRunning; /** Is sub test running */
-	vector<string> vData; /** data */
-	string sSubTestName; /** test name */
-	string sStartTime; /** start time */
-	string sEndTime; /** end time */
-	string sSubTestStartHandleCount; /** handle count at start */
-	string sSubTestEndHandleCount; /** handle count at end */
-};
-
-/**
-* Represents data of a single run.
-*/
-class CProcessData : public CATAllocs
-{
-public:
-	// Members
-
-	bool bProcessOnGoing; /** is process on going */
-	int iProcessID; /** process id (pid)*/
-	vector<string> vData; /** data */
-	vector<string> vHandleLeaks; /** handle leak(s) */
-	vector<CSubTestData> vSubTests; /** process sub test(s) */
-
-	// time at the start of the process - time stamp at the start of process
-	// in microseconds
-	unsigned __int64 iTimeSpan;
-};
-
-#endif
\ No newline at end of file
--- a/analyzetool/commandlineengine/inc/CATProject.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/inc/CATProject.h	Wed Oct 13 16:17:58 2010 +0300
@@ -21,7 +21,6 @@
 
 #include "ATCommonDefines.h"
 #include "CATBase.h"
-#include "../inc/CATParseBinaryFile.h"
 
 class CATModule2;
 class CATDatParser;
@@ -128,8 +127,6 @@
 	*/
 	~CATProject();
 
-	CATParseBinaryFile Parser;
-
 	/**
 	* Set arguments.
 	* @param arguments.
@@ -194,12 +191,6 @@
 	void SetS60FileName( const string& sFileName);
 
 	/**
-	* Set S60 logging file path.
-	* @param sFilePath filename.
-	*/
-	void SetS60FilePath( const string& sFilePath );
-
-	/**
 	* Set target module.
 	* @param sTargetModule target module name.
 	*/
@@ -617,8 +608,6 @@
 	string m_sMakeFile;
 	// User given S60 log file name.
 	string m_sS60FileName;
-	// User given S60 log file path.
-	string m_sS60FilePath;
 	// Target module.
 	string m_sTargetModule;
 	// Target modules (used in carbide instrumenting).
@@ -631,8 +620,6 @@
 	vector<string> m_vRomSymbolFiles;
 	// Temporary data file name if user gave trace file.
 	string m_sDataFileTemp;
-	// Temporary data file name if user gave binary log file.
-	string m_sBinaryLogFileTemp;
 	// User given output file to store analyse results.
 	string m_sDataFileOutput;
 	// Analyser object.
--- a/analyzetool/commandlineengine/inc/catalloc.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/inc/catalloc.h	Wed Oct 13 16:17:58 2010 +0300
@@ -50,8 +50,6 @@
 
 	string m_sSize; /** Allocation size */
 
-	string m_iThreadId; /** Thread id*/
-
 	unsigned long m_iCSCount; /** Call stack address count */
 
 	map<unsigned long,string> m_vCallStack; /** Call stack where packet number is key */
--- a/analyzetool/commandlineengine/inc/catallocs.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/inc/catallocs.h	Wed Oct 13 16:17:58 2010 +0300
@@ -40,25 +40,13 @@
 	* Alloc header message (multimessage call stack).
 	* @param sAllocHString allocation string
 	*/
-	void AllocH( const string& sAllocHString, const string& aTimeString );
+	void AllocH( const string& sAllocHString );
 
 	/*
 	* Alloc fragment message (fragment of call stack in multimessage alloc).
 	* @param sAllocFString allocation string
 	*/
-	void AllocF( const string& sAllocFString, const string& aTimeString );
-
-    /*
-	* Realloc header message (multimessage call stack).
-	* @param sReallocHString allocation string
-	*/
-	void ReallocH( const string& sReallocHString, const string& aTimeString );
-
-	/*
-	* Relloc fragment message (fragment of call stack in multimessage alloc).
-	* @param sReallocFString allocation string
-	*/
-	void ReallocF( const string& sReallocFString, const string& aTimeString );
+	void AllocF( const string& sAllocFString );
 
 	/**
 	* Free message.
@@ -71,14 +59,14 @@
 	* (not implemented yeat.)
 	* @param sFreeHString string
 	*/
-	void FreeH( const string& sFreeHString, const string& aTimeString );
+	void FreeH( const string& sFreeHString );
 
 	/**
 	* Free fragment message.
 	* (not implemented yeat.)
 	* @param sFreeFString string
 	*/
-	void FreeF( const string& sFreeFString, const string& aTimeString );
+	void FreeF( const string& sFreeFString );
 
 	/**
 	* Get "leak" list ordered by allocation time.
Binary file analyzetool/commandlineengine/install/atool.exe has changed
--- a/analyzetool/commandlineengine/src/CATBase.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/CATBase.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -144,7 +144,7 @@
 {
 	LOG_LOW_FUNC_ENTRY("CATBase::GetPathOrFileName");
 	string sRet;
-	size_t iPos = sInput.size()-1;
+	size_t iPos = sInput.size();
 
 	sInput = ChangeSlashToBackSlash( sInput );
 
@@ -228,30 +228,6 @@
 }
 
 // -----------------------------------------------------------------------------
-// CATBase::GetStringUntilMainId
-// Function returns string from begin of given string until next atool's main id <AT>,
-// characters until next main id are removed from sInput string.
-// -----------------------------------------------------------------------------
-string CATBase::GetStringUntilMainId( string& sInput, bool bEraseFromInput )
-{
-	LOG_LOW_FUNC_ENTRY("CATBase::GetStringUntilMainId");
-	string sTemp( sInput );
-	size_t iSize = sTemp.find(MAIN_ID);
-	if( iSize != string::npos )
-	{
-		sTemp.resize( iSize );
-		if( bEraseFromInput )
-			sInput.erase( 0, (iSize) );
-	}
-	else
-	{
-		if ( bEraseFromInput )
-			sInput.clear();
-	}
-	return sTemp;
-}
-
-// -----------------------------------------------------------------------------
 // CATBase::ChangeSlashToBackSlash
 // Function changes all BackSlash characters to Slash character from
 // given string.
@@ -269,73 +245,6 @@
 	return sInput;
 }
 
-
-// -----------------------------------------------------------------------------
-// CATBase::ParseTimeStamp
-// Function returns time parsed from start of trace message
-// -----------------------------------------------------------------------------
-unsigned __int64 CATBase::ParseTimeStamp( string sLineStart )
-{
-	unsigned __int64 iTime(0);
-
-	int iHours(0), iMinutes(0), iSeconds(0), iMiliseconds(0), iMicroseconds(0);
-	int iErr(0), iRet(0);
-
-	TrimString( sLineStart );
-	string sTimeString = GetStringUntilNextSpace( sLineStart );
-
-	// Get time
-	int iPos = sTimeString.find( ":" );
-	if( iPos != string::npos ) // ':' found, this is timestamp from fastTrace/traceViewer 
-	{
-		// possible formats 
-		// hh:mm:ss - seconds (ft)
-        // hh:mm:ss:mmm - miliseconds (ft/tw)
-		// hh:mm:ss:mmmmmm - microseconds (ft/tw)
-		// hh:mm:ss:nnnnnnnnn - nanoseconds (ft) - ignore last 3digits
-
-		iRet = sscanf_s( sTimeString.c_str(), "%d:%d:%d.%3d%3d", &iHours, &iMinutes, &iSeconds, &iMiliseconds, &iMicroseconds );
-		if( iRet == 5 || iRet == 4 )
-		{
-			// get microseconds
-			iTime = ( ( ( iHours*60 + iMinutes )*60 + iSeconds )*1000 + iMiliseconds )*1000 + iMicroseconds;
-		}
-		else
-		{
-			iErr = true;
-		}
-	}
-	else if( sTimeString.find( "." ) != string::npos ) // epoc timestamp in format ssss.mmm
-	{
-		iRet = sscanf_s( sTimeString.c_str(), "%d.%d", &iSeconds, &iMiliseconds );
-		if( iRet == 2 )
-		{
-			// get microseconds
-			iTime = ( ( ( iHours*60 + iMinutes )*60 + iSeconds )*1000 + iMiliseconds )*1000 + iMicroseconds;
-		}
-		else
-		{
-			iErr = true;
-		}
-	}
-	else // timestamp in microseconds from binary log file or from ft
-	{
-		iRet = sscanf_s( sTimeString.c_str(), "%016I64x", &iTime);
-		if( iRet == 1 )
-		{
-		}
-		else
-		{
-			iErr = true;
-		}
-	}
-
-	if( iErr )
-		cout << "Error, can not read timestamp.\n";
-
-	return iTime;
-}
-
 // -----------------------------------------------------------------------------
 // CATBase::FileExists
 // Check if given file exists.
@@ -967,7 +876,6 @@
 bool CATBase::CreateTemporaryCpp( const string& sId,
 								 const string& sPath
 								 ,const string& sS60FileName
-								 ,const string& sS60FilePath
 								 ,int iLogOption
 								 ,int iIsDebug
 								 ,int iAllocCallStackSize
@@ -1003,8 +911,6 @@
 	out << "\nconst TInt ATTempFreeCallStackSize(" << iFreeCallStackSize << ");";
 	// Log file name
 	out << "\n_LIT( ATTempLogFileName, \"" << sS60FileName << "\" );";
-	// Log file path
-	out << "\n_LIT( ATTempLogFilePath, \"" << sS60FilePath << "\" );";
 	// Version number
 	out << "\n_LIT( ATTempVersion, \"" << ATOOL_COMPATIBILITY_STRING << "\" );";
 	// Variable functions use enumeration values that are defined in memoryhook (customuser.h)
@@ -1018,8 +924,7 @@
             ELogOption = 3,
             EDebug = 4,
             EAllocCallStackSize = 5,
-            EFreeCallStackSize = 6,
-			ELogFilePath = 7
+            EFreeCallStackSize = 6
             };
 */
 	out << "\nTInt GetInt( const TUint8 aType )";
@@ -1039,7 +944,6 @@
 	out << "\n{";
 	out << "\ncase 1: return ATTempLogFileName();";
 	out << "\ncase 2: return ATTempVersion();";
-	out << "\ncase 7: return ATTempLogFilePath();";
 	out << "\ndefault: return KNullDesC();";
 	out << "\n}";
 	out << "\n}";
@@ -1051,24 +955,15 @@
 	out << sS60FileName;
 	out << "\" );\n";
 
-	out << "\n_LIT( KFilePath, \"";
-	out << sS60FilePath;
-	out << "\" );\n";
-
 	// Hardcoded version number for support.
 	out << "\n/* The AnalyzeTool version number used. */";
-	out << "\n_LIT( KAtoolVersion, \"1.7.6;1.10.0\" );\n";
+	out << "\n_LIT( KAtoolVersion, \"1.7.5;1.9.1\" );\n";
 
 	out << "\nconst TFileName LogFileName()";
 	out << "\n    {";
 	out << "\n    return TFileName( KFileName() );";
 	out << "\n    }";
 
-	out << "\nconst TPath LogFilePath()";
-	out << "\n    {";
-	out << "\n    return TPath( KFilePath() );";
-	out << "\n    }";
-
 	out << "\nTUint32 AllocCallStackSize()";
 	out << "\n    {";
 	out << "\n    return TUint32( ";
@@ -1139,36 +1034,6 @@
 		return false;
 }
 
-// -----------------------------------------------------------------------------
-// CATBase::IsBinaryLogFile
-// -----------------------------------------------------------------------------
-bool CATBase::IsBinaryLogFile( string sFile )
-{
-	LOG_FUNC_ENTRY("CATBase::IsDataFile");
-	// Check that sFile not empty
-	if ( sFile.empty() || sFile.length() < 1 )
-		return false;
-
-	// Temporary line char array.
-	char cLineFromFile[MAX_LINE_LENGTH];
-	//Open file
-	ifstream in( sFile.c_str() );
-
-	//File open ok?
-	if( !in.good() )
-		return false;
-
-	//Read all lines
-	in.getline( cLineFromFile, MAX_LINE_LENGTH );
-
-	string sLineFromFile( cLineFromFile );
-	in.close();
-
-	if( sLineFromFile.find( "ATOOL_BINARY_FILE_VERSION" ) != string::npos )
-		return true;
-	else
-		return false;
-}
 
 // -----------------------------------------------------------------------------
 // CATBase::ParseStringToVector
--- a/analyzetool/commandlineengine/src/CATDatParser.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/CATDatParser.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -364,7 +364,7 @@
 	string sPid = GetStringUntilNextSpace( sLine );
 	m_iCurrentProcessId = _httoi( sPid.c_str() );
 
-	// Header for process start
+	// Header for process tart
 	m_DataSaver.AddString( "\n--------------------------------\n" );
 	m_DataSaver.AddString( "Test Run start (" );
 	m_DataSaver.AddString( m_sCurrentProcessName.c_str() );
@@ -515,13 +515,10 @@
 			for( size_t i = 0 ; i < m_vHandleLeaks.size() ; i++ )
 			{
 				string sTempHandleLeak( m_vHandleLeaks[i] );
+				// Name.
+				string sHandleLeakModule( GetStringUntilNextSpace( sTempHandleLeak ) );
 				// Count.
 				string sNrOfLeaks( GetStringUntilNextSpace(sTempHandleLeak) );
-
-				// Name.
-				//string sHandleLeakModule( GetStringUntilNextSpace( sTempHandleLeak ) );
-				string sHandleLeakModule( "Unknown" );
-
 				unsigned long iNrOfLeaks = _httoi( sNrOfLeaks.c_str() );
 				iTotalNrOfLeaks += iNrOfLeaks;
 				if( iNrOfLeaks )
@@ -601,6 +598,15 @@
 	if ( _stricmp( "winscw", m_sProjectPlatform.c_str() ) == 0 )
 		CreateWinscwModule( structDllInfo.sModuleName );
 
+	if ( m_iDataVersion >= AT_DLL_TIMESTAMP_DATA_VERSION )
+	{
+		// Pickup module loading time.
+		string sLoadTime = GetStringUntilNextSpace( sLine );
+		unsigned long long ull;
+		if ( hexToDec( sLoadTime, ull ) )
+			structDllInfo.iLoadTime = ull;
+	}
+
 	// Get dll start memory string address from line
 	// Convert string address to real memory address
 	structDllInfo.iStartAddress = 
@@ -612,15 +618,6 @@
 		_httoi( 
 		GetStringUntilNextSpace( sLine ).c_str() );
 
-	if ( m_iDataVersion >= AT_DLL_TIMESTAMP_DATA_VERSION )
-	{
-		// Pickup module loading time.
-		string sLoadTime = GetStringUntilNextSpace( sLine );
-		unsigned long long ull;
-		if ( hexToDec( sLoadTime, ull ) )
-			structDllInfo.iLoadTime = ull;
-	}
-
 	// Is module already loaded, if not add it to list.
 	bool bFound = false;
 	for( vector<DLL_LOAD_INFO>::iterator it = m_vDllLoadModList.begin();
@@ -672,10 +669,6 @@
 	string sModuleName = GetStringUntilNextSpace( sLine );
 	ChangeToLower( sModuleName );
 
-	// skip adresses - not currently used
-	GetStringUntilNextSpace( sLine );
-	GetStringUntilNextSpace( sLine );
-
 	// Unload time
 	unsigned long long ull;
 	string sUnload = GetStringUntilNextSpace( sLine );
--- a/analyzetool/commandlineengine/src/CATModule2.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/CATModule2.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -27,7 +27,6 @@
 {
 	LOG_FUNC_ENTRY("CATModule2::CATModule2");
 	m_bAddressToLineInitialized = false;
-	m_bS60FileNameResolved = false;
 	m_pAddressToLine = 0;
 	m_sErrors = "";
 	m_sMakeFile = "";
@@ -334,37 +333,25 @@
 	}
 }
 bool CATModule2::CreateTempCpp(const string& sS60FileName
-							        , const string& sS60FilePath
 									, int eLoggingMode
 									, int eBuildType
 									, int iAllocCallStackSize
 									, int iFreeCallStackSize )
 {
 	LOG_FUNC_ENTRY("CATModule2::CreateTemporaryCpp");
-
+	// S60 filename
+	m_sS60FileName = sS60FileName;
 	// Make s60 filename target.type.dat if its empty and logging mode is file
-	if ( eLoggingMode == CATProject::FILE )
+	if ( eLoggingMode == CATProject::FILE
+		&& m_sS60FileName.empty() )
 	{
-		// S60 filename
-		SetS60FileName( sS60FileName );
-		
-		// S60 filepath
-		// use double slashes in temp cpp file
-		m_sS60FilePath = sS60FilePath;
-		int iIgnore(0);
-		size_t iPos = m_sS60FilePath.find("\\", iIgnore );
-		while( iPos != string::npos )
-		{
-			m_sS60FilePath.replace( iPos, 1, "\\\\" );
-			// dont replace previously replaced slashes
-			iIgnore = iPos + 2;
-			iPos = m_sS60FilePath.find("\\", iIgnore );
-		}
-
-
+		m_sS60FileName = m_sTarget;
+		m_sS60FileName.append(".");
+		m_sS60FileName.append( m_sTargetType );
+		m_sS60FileName.append(".dat");
 	}
 	return CreateTemporaryCpp( GetUniqueId(), m_sTempPath,
-		m_sS60FileName, m_sS60FilePath, eLoggingMode, eBuildType, iAllocCallStackSize, iFreeCallStackSize );
+		m_sS60FileName, eLoggingMode, eBuildType, iAllocCallStackSize, iFreeCallStackSize );
 }
 
 bool CATModule2::ModifyMmp()
@@ -1299,46 +1286,15 @@
 string CATModule2::GetS60FileName() const
 {
 	LOG_LOW_FUNC_ENTRY("CATModule2::GetS60FileName");
-	return m_sS60FileName;
-}
-
-void CATModule2::SetS60FileName( const string& aFileName  )
-{
-	LOG_LOW_FUNC_ENTRY("CATModule2::SetS60FileName");
-
-	m_sS60FileName = aFileName;
-
-	//check new m_sS60FileName and change it if needed
-	string sProcessName = "";
-	sProcessName.append( m_sTarget );
-	sProcessName.append(".");
-	sProcessName.append( m_sTargetType );
-		
 	if ( m_sS60FileName.empty() )
 	{
-		m_sS60FileName = sProcessName;
-		m_sS60FileName.append(".dat");
+		string sGeneratedDatName = m_sTarget;
+		sGeneratedDatName.append(".");
+		sGeneratedDatName.append( m_sTargetType );
+		sGeneratedDatName.append(".dat");
+		return sGeneratedDatName;
 	}
-	else
-	{
-		// if data file name contains %processname% string, replace it with process name
-		string sProcessnameTemp = "[";
-		sProcessnameTemp.append( sProcessName );
-		sProcessnameTemp.append( "]" );
-		size_t iSpot;
-
-		//create temp name in lowercase
-		string sS60FileNameLower = m_sS60FileName;
-		ChangeToLower( sS60FileNameLower );
-
-		// find %processname% string in lowercase name, replace it with process name in in m_sS60FileName
-		// replace it also in temp string (matching indexes)
-		while( ( iSpot = sS60FileNameLower.find( AT_PROCESSNAME_TAG ) ) != string::npos )
-		{
-			m_sS60FileName.replace( iSpot, AT_PROCESSNAME_TAG.length(), sProcessnameTemp );
-			sS60FileNameLower.replace( iSpot, AT_PROCESSNAME_TAG.length(), sProcessnameTemp );
-		}
-    }
+	return m_sS60FileName;
 }
 
 string CATModule2::GetLstNameOfSource(string sSource) const
--- a/analyzetool/commandlineengine/src/CATParseBinaryFile.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,734 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Definitions for the class CATParseTraceFile.
-*
-*/
-
-
-#include "../inc/ATCommonDefines.h"
-#include "../inc/CATParseBinaryFile.h"
-#include "../inc/catdatasaver.h"
-#include "../inc/CATDatParser.h"
-#include "../inc/CATProcessData.h"
-
-#include <time.h>
-
-
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::CATParseTraceFile
-// Constructor.
-// -----------------------------------------------------------------------------
-CATParseBinaryFile::CATParseBinaryFile()
-{
-	LOG_FUNC_ENTRY("CATParseTraceFile::CATParseTraceFile");
-	m_DataSaver.SetPrintFlag( false );
-}
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::StartParse
-// Main function to start trace parsing.
-// -----------------------------------------------------------------------------
-bool CATParseBinaryFile::StartParse( const char* pFileName, const char* pOutputFileName )
-{
-	LOG_FUNC_ENTRY("CATParseTraceFile::StartParse");
-
-	// Return value, will be changed to true if process start found.
-	bool bRet = false;
-
-	// Check pointers
-	if ( pFileName == NULL  )
-		return bRet;
-
-
-	if ( ! FileExists( pFileName ) )
-	{
-		cout << AT_MSG << "Error, input file \""
-			<< pFileName
-			<< "\" does not exist." << endl;
-		return bRet;
-	}
-
-	// Open input and output file
-	ifstream in( pFileName, ios::binary );
-	ofstream sDataToParse( pOutputFileName );
-
-	// Check file opened ok
-	if ( !in.good() )
-		return false;
-
-	// Get stream size
-	size_t streamPos = in.tellg();
-	in.seekg( 0, ios::end);
-	size_t streamEnd = in.tellg();
-	in.seekg( 0, ios::beg );
-
-	//Origianl characters (not filtered).
-
-	unsigned char cDataFromFile[MAX_LINE_LENGTH];
-
-	bool bProcessEndReached = false;
-	bool bError = false;
-
-	char messageType = 0;
-	unsigned __int64 messageTime = 0;
-
-	unsigned long iProcessId(0);
-	int iAddressCount(0);
-	string sTemp;
-
-	//first parse version info
-	GetString( cDataFromFile, in, streamPos, streamEnd );
-	//todo check if version is correct	
-
-	while( !bError && !bProcessEndReached )
-	{
-		// get time
-		if( !GetNum64( cDataFromFile, in, streamPos, streamEnd ) )
-		{
-			bError = true;
-			break;
-		}
-		messageTime = StringToNum64( cDataFromFile );
-
-		// get message type
-		if( !GetNum8( cDataFromFile, in, streamPos, streamEnd ) )
-		{
-			bError = true;
-			break;
-		}
-		messageType = (int)cDataFromFile[0];
-
-		switch (messageType)
-		{
-			case EProcessStart:
-				{
-				//temp string to store data until we get to processID
-				sTemp.clear();
-
-                //PCS MemoryLeaker.exe[edf5a8b2]0001 17b 48939b0f5c04f 1 3 1.10.0 1.7.5
-				sTemp.append( LABEL_PROCESS_START );
-				sTemp.append( " " );
-
-				// get process name
-				if( !GetString( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-
-				sTemp.append( (char *)cDataFromFile );
-				sTemp.append( " " );
-
-				//get process id
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-			    {
-					bError = true;
-					break;
-				}
-				iProcessId = StringToNum32(cDataFromFile);
-
-				// write stored data
-				sDataToParse << std::hex << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << std::hex << iProcessId;
-				sDataToParse << " ";
-				sDataToParse << sTemp;
-				sDataToParse <<  std::hex << iProcessId;
-				sDataToParse << " ";
-
-				//write time
-				sDataToParse <<  std::hex << messageTime;
-				sDataToParse << " ";
-
-				//get udeb/urel
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::dec << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				//add trace version - TODO check
-				sDataToParse <<  std::dec << 3;
-				sDataToParse << " ";
-
-				// get atool version
-				if( !GetString( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse << (char *)cDataFromFile;
-				sDataToParse << " ";
-
-				// get api version
-				if( !GetString( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse << (char *)cDataFromFile;
-				sDataToParse << "\n";
-
-				//process start found
-				bRet = true;
-
-				}
-				break;
-
-			case EProcessEnd:
-				{
-				sDataToParse << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				//PCE
-				sDataToParse << LABEL_PROCESS_END ;
-				sDataToParse << "\n";
-				bProcessEndReached = true;
-				}
-				break;
-
-			case EDllLoad:
-				{
-				sDataToParse << std::hex << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				//DLL AToolMemoryLeakerDll3.dll 3ff80000 3ff92000
-				sDataToParse << LABEL_DLL_LOAD ;
-				sDataToParse << " ";
-
-				// get dll name
-				if( !GetString( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse << (char *)cDataFromFile;
-				sDataToParse << " ";
-
-				// get start address
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get end address
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << "\n";
-				}
-				break;
-			
-			case EDllUnload:
-				{
-				sDataToParse << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				//DLU AToolMemoryLeakerDll3.dll 3ff80000 3ff92000
-				sDataToParse << LABEL_DLL_UNLOAD ;
-				sDataToParse << " ";
-
-				// get dll name
-				if( !GetString( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse << (char *)cDataFromFile;
-				sDataToParse << " ";
-
-				// get start address
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get end address
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << "\n";
-				}
-				break;
-
-			case EAllocH:
-				{
-				sDataToParse << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				//ALH 5a7a6734 5c 17c 11 6003ded4 60010df2 40001bff 40001c39 ...
-				// no fragments in log file
-				sDataToParse << ALLOCH_ID ;
-				sDataToParse << " ";
-
-				// get mam address
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get size of allocation
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get thread id
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get address count
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				int iAddressCount = StringToNum32(cDataFromFile);
-				sDataToParse <<  std::hex << iAddressCount;
-
-				// get callstack
-				for(int i=0; i<iAddressCount; i++)
-				{
-					sDataToParse << " ";
-					if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-					{
-						bError = true;
-						break;
-					}
-				    sDataToParse <<  std::hex << StringToNum32(cDataFromFile); 
-				}
-				sDataToParse << "\n";
-				}
-				break;
-
-			case EFreeH:
-				{
-				sDataToParse << std::hex <<messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				//FRH 5a7a679c 17c 0 (6003ded4 60010df2 40001bff 40001c39 ...)
-				// no fragments in log file
-				sDataToParse << FREEH_ID ;
-				sDataToParse << " ";
-
-				// get mem address
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get thread id
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get address count
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				iAddressCount = StringToNum32(cDataFromFile);
-				sDataToParse <<  std::hex << iAddressCount;
-
-				// get callstack
-				for(int i=0; i<iAddressCount; i++)
-				{
-					sDataToParse << " ";
-					if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-					{
-						bError = true;
-						break;
-					}
-				    sDataToParse <<  std::hex << StringToNum32(cDataFromFile); 
-				}
-				sDataToParse << "\n";
-
-				break;
-
-			case EReallocH:
-				sDataToParse << std::hex << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				// RAH 0 5a7a6f30 30 17c 17 6003e02b 60010ef8 600083e5 ...
-				// no fragments in log file
-				sDataToParse << REALLOCH_ID ;
-				sDataToParse << " ";
-
-				// get freed mem address
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get allocated mem address
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get size of allocation
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get thread id
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << " ";
-
-				// get address count
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				iAddressCount = StringToNum32(cDataFromFile);
-				sDataToParse <<  std::hex << iAddressCount;
-
-				// get callstack
-				for(int i=0; i<iAddressCount; i++)
-				{
-					sDataToParse << " ";
-					if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-					{
-						bError = true;
-						break;
-					}
-				    sDataToParse <<  std::hex << StringToNum32(cDataFromFile); 
-				}
-				sDataToParse << "\n";
-				}
-				break;
-
-			case EHandleLeak:
-				{
-				sDataToParse << std::hex << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				//HDL handleLeakCount
-				sDataToParse << LABEL_HANDLE_LEAK ;
-				sDataToParse << " ";
-
-				//get handle leak count
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << "\n";
-				}
-				break;
-
-			case EThreadStart:
-				{
-				sDataToParse << std::hex << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				// TDS 17c
-				sDataToParse << LABEL_THREAD_START;
-				sDataToParse << " ";
-
-				// get thread ID
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << "\n";
-				}
-				break;
-
-			case EThreadEnd:
-				{
-				sDataToParse << std::hex << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-				sDataToParse << iProcessId;
-				sDataToParse << " ";
-				// TDE 17c
-				sDataToParse << LABEL_THREAD_END;
-				sDataToParse << " ";
-
-				// get thread ID
-				if( !GetNum32( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				sDataToParse <<  std::hex << StringToNum32(cDataFromFile);
-				sDataToParse << "\n";
-				}
-				break;
-
-			case EDeviceInfo:
-				{
-				// DEVINFO swVersion  romChecksum //both are descriptors
-				sDataToParse << std::hex << messageTime;
-				sDataToParse << " ";
-				sDataToParse << MAIN_ID;
-				sDataToParse << " ";
-
-				sDataToParse << LABEL_DEVICE_INFO;
-				sDataToParse << " ";
-
-				// get swVersion
-				if( !GetString( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}			
-				sDataToParse << (char *)cDataFromFile;
-				sDataToParse << " ";
-
-				// todo check
-				// get romChecksum
-				if( !GetString( cDataFromFile, in, streamPos, streamEnd ) )
-				{
-					bError = true;
-					break;
-				}
-				
-				sDataToParse << (char *)cDataFromFile;
-				sDataToParse << "\n";
-				}
-				break;
-
-			case EError:
-				//currently not used
-				break;
-			case ETestStart:
-			case ETestEnd:
-				// currently can not occure in bin log file, this is added from carbide in traces
-				break;
-			default:
-				bError = true;
-				break;				
-		}
-	}
-
-	// Close file.
-	in.close();
-
-	sDataToParse.close();
-	return !bError;
-}
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::GetDataSaver
-// Gets data saver object.
-// -----------------------------------------------------------------------------
-CATDataSaver* CATParseBinaryFile::GetDataSaver(void)	
-{
-	LOG_LOW_FUNC_ENTRY("CATParseTraceFile::GetDataSaver");
-	return &m_DataSaver;
-}
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::StringToNum64
-// Gets 64bit number from input string
-// -----------------------------------------------------------------------------
-unsigned __int64 CATParseBinaryFile::StringToNum64( unsigned char* cVal )
-{
-	unsigned __int64 iRetVal(0);
-
-	for(int i=7; i>=0; i--)
-		iRetVal = ( iRetVal << 8 ) + cVal[i];
-
-	return iRetVal;
-}
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::StringToNum32
-// Gets 32bit number from input string
-// -----------------------------------------------------------------------------
-unsigned long CATParseBinaryFile::StringToNum32( unsigned char* cVal )
-{
-	unsigned long iRetVal(0);
-
-	for(int i=4; i>=0; i--)
-		iRetVal = ( iRetVal << 8 ) + cVal[i];
-
-	return iRetVal;
-}
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::GetString
-// Get next string from file
-// -----------------------------------------------------------------------------
-bool CATParseBinaryFile::GetString( unsigned char* pData, ifstream &pIn, size_t &pStreamPos, size_t pStreamEnd )
-{
-	int	numOfRead = 1;
-	if(pStreamPos + numOfRead <= pStreamEnd)
-	{
-		pIn.read((char*)pData, numOfRead);
-		pStreamPos = pIn.tellg();
-	}
-	else
-	{
-		return false;
-	}
-
-	numOfRead = (int)pData[0] >> 2;
-	if(pStreamPos + numOfRead <= pStreamEnd)
-	{
-		pIn.read((char*)pData, numOfRead);
-		pStreamPos = pIn.tellg();
-		pData[numOfRead] = 0;
-	}
-	else
-	{
-		return false;
-	}
-
-	return true;
-}
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::GetNum8
-// Get next 8bit number from file
-// -----------------------------------------------------------------------------
-bool CATParseBinaryFile::GetNum8( unsigned char* pData, ifstream &pIn, size_t &pStreamPos, size_t pStreamEnd )
-{
-	int	numOfRead = 1;
-	if(pStreamPos + numOfRead <= pStreamEnd)
-	{
-		pIn.read((char*)pData, numOfRead);
-		pStreamPos = pIn.tellg();
-	}
-	else
-	{
-		return false;
-	}
-
-	return true;
-}
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::GetNum32
-// Get next 32bit number from file
-// -----------------------------------------------------------------------------
-bool CATParseBinaryFile::GetNum32( unsigned char* pData, ifstream &pIn, size_t &pStreamPos, size_t pStreamEnd )
-{
-	int	numOfRead = 4;
-	if(pStreamPos + numOfRead <= pStreamEnd)
-	{
-		pIn.read((char*)pData, numOfRead);
-		pStreamPos = pIn.tellg();
-	}
-	else
-	{
-		return false;
-	}
-
-	return true;
-}
-
-// -----------------------------------------------------------------------------
-// CATParseBinaryFile::GetNum64
-// Get next 64bit number from file
-// -----------------------------------------------------------------------------
-bool CATParseBinaryFile::GetNum64( unsigned char* pData, ifstream &pIn, size_t &pStreamPos, size_t pStreamEnd )
-{
-	int	numOfRead = 8;
-	if(pStreamPos + numOfRead <= pStreamEnd)
-	{
-		pIn.read((char*)pData, numOfRead);
-		pStreamPos = pIn.tellg();
-	}
-	else
-	{
-		return false;
-	}
-
-	return true;
-}
-
-//EOF
--- a/analyzetool/commandlineengine/src/CATParseTraceFile.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/CATParseTraceFile.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -20,11 +20,28 @@
 #include "../inc/CATParseTraceFile.h"
 #include "../inc/catdatasaver.h"
 #include "../inc/CATDatParser.h"
-#include "../inc/CATProcessData.h"
 
 #include <time.h>
 
+#define MAIN_ID "PCSS"
+#define ALLOC_ID "ALLOC" // < V.1.6 allocation.
+#define ALLOCH_ID "ALLOCH" // Header of multi message allocation.
+#define ALLOCF_ID "ALLOCF" // Fragment of multi message allocation.
+#define FREE_ID "FREE"
+#define FREEH_ID "FREEH" // Header of multi message free.
+#define FREEF_ID "FREEF" // Fragment of multi message free.
+#define HANDLE_LEAK_ID "HANDLE_LEAK"
 
+const string ERROR_OCCURED = "ERROR_OCCURED"; // Error messages.
+const string INCORRECT_ATOOL_VERSION = "INCORRECT_ATOOL_VERSION";
+/**
+* Invalid characters in trace file line content.
+* These will be filtered out before actuall parsing of line.
+10 = LF
+13 = CR
+124 = |
+*/
+const char cINVALID_TRACE_FILE_CHARS[] = { 10, 13, 124 };
 
 // -----------------------------------------------------------------------------
 // CATParseTraceFile::CATParseTraceFile
@@ -40,13 +57,12 @@
 // CATParseTraceFile::StartParse
 // Main function to start trace parsing.
 // -----------------------------------------------------------------------------
-bool CATParseTraceFile::StartParse( const char* pFileName, const char* pOutputFileName, const char* pCleanedTraceFile )
+bool CATParseTraceFile::StartParse( const char* pFileName, const char* pOutputFileName )
 {
 	LOG_FUNC_ENTRY("CATParseTraceFile::StartParse");
 
 	// Return value, will be changed to true if process start found.
 	bool bRet = false;
-	bool bCreateCleanedTraces = false;
 
 	// Check pointers
 	if ( pFileName == NULL  )
@@ -63,24 +79,6 @@
 		return bRet;
 	}
 
-	ofstream cleanedTraces;
-
-	// check is creation of file needed
-	if( pCleanedTraceFile != NULL )
-	{
-		// if yes open file for cleaned traces
-	    // (<AT> messages with cleaned timestamps)
-		bCreateCleanedTraces = true;
-
-		cleanedTraces.open(pCleanedTraceFile);
-
-		if( !cleanedTraces.good() )
-		{
-			printf( "Can not open file: %s\n", pCleanedTraceFile );
-			return bRet;
-		}
-	}
-
 	// Open data file
 	ifstream in( pFileName );
 
@@ -142,17 +140,10 @@
 		if( strstr( cLineFromFile, MAIN_ID ) != NULL )
 		{
 			string sRestOfLine( cLineFromFile );
-			string sTemp("");
-			unsigned __int64 iTimeStamp(0);
-			string sTime("");
-			string sLineStart("");
+			string sTemp;
 
-			// Get part of line before main id. This should contain time info
-			sLineStart = GetStringUntilMainId( sRestOfLine );
-			// Get message's time stamp in microseconds
-			iTimeStamp = ParseTimeStamp( sLineStart );
-			// store whole line from MAIN_ID - to be logged to cleaned traces file
-		    string sLineToCleanedFile( sRestOfLine );
+			// Delete all characters before main ID
+			sRestOfLine.erase( 0, sRestOfLine.find( MAIN_ID ) );
 
 			// Get main ID
 			sTemp = GetStringUntilNextSpace( sRestOfLine );
@@ -165,7 +156,7 @@
 
 			// Get next argument
 			sTemp = GetStringUntilNextSpace( sRestOfLine );
-			// This might be process id, device info message or error message
+			// This might be process id or error message
 			if ( sTemp.compare( ERROR_OCCURED ) == 0 )
 			{
 				// Api mismatch between s60 side and atool.exe
@@ -188,31 +179,7 @@
 					cout << sRestOfLine << endl;
 				continue;
 			}
-
-			if ( sTemp.compare( LABEL_DEVICE_INFO ) == 0 ) 
-			{
-
-				if( vProcessList[iProcessIDinList].bProcessOnGoing == false )
-				continue;
-
-				// get time string from timestamp
-			    sTime = GetTimeFromTimeStamp( iTimeStamp, vProcessList[iProcessIDinList].iTimeSpan );
-
-				// device info line, log it to cleaned file for carbide
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << LABEL_DEVICE_INFO << " "; //add Message type
-				cleanedTraces << sRestOfLine << "\n"; //add the rest of the line
-				}
-				continue;
-			}
-
 			unsigned long iProcessID = _httoi( sTemp.c_str() );
-			// todo to be removed when reallocations are implemented
-			string sProcessID = sTemp;
 
 			iProcessIDinList = -1;
 			// Find process from list
@@ -254,26 +221,6 @@
 				bRet = true; // Set return value true we found start.
 				vProcessList[iProcessIDinList].vData.push_back( sWholeTempLine );
 				vProcessList[iProcessIDinList].bProcessOnGoing = true;
-
-				// remove <processName> <processID> part
-				GetStringUntilNextSpace( sRestOfLine );
-				GetStringUntilNextSpace( sRestOfLine );
-				// get time
-				sTemp = GetStringUntilNextSpace( sRestOfLine );
-				unsigned __int64 iTemp(0);
-				sscanf_s( sTemp.c_str(), "%016I64x", &iTemp);
-				//calculate span between PCS time and PCS timestamp
-				vProcessList[iProcessIDinList].iTimeSpan = iTemp - iTimeStamp;
-
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTemp << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				continue;
 			}
 
@@ -281,13 +228,6 @@
 			if( vProcessList[iProcessIDinList].bProcessOnGoing == false )
 				continue;
 
-			// get time string from timestamp
-			sTime = GetTimeFromTimeStamp( iTimeStamp, vProcessList[iProcessIDinList].iTimeSpan );
-
-			// TODO version with reallocation
-			//cleanedTraces << sTime << " "; //add time
-			//cleanedTraces << sLineToCleanedFile << "\n"; //add the rest of the line
-
 			// "Old style" allocation (< v.1.6)
 			if( ! _stricmp( pCommand, ALLOC_ID ) )
 			{
@@ -308,17 +248,8 @@
 			}
 			else if ( ! _stricmp( pCommand, ALLOCH_ID ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				// Add alloc
-				vProcessList[iProcessIDinList].AllocH( sRestOfLine, sTime );
+				vProcessList[iProcessIDinList].AllocH( sRestOfLine );
 
 				// Subtests running?
 				vector<CSubTestData>::iterator viSubTestIter = vProcessList[iProcessIDinList].vSubTests.begin();
@@ -327,7 +258,7 @@
 					if( viSubTestIter->bRunning )
 					{
 						// Save alloc also to sub test
-						viSubTestIter->AllocH( sRestOfLine, sTime );
+						viSubTestIter->AllocH( sRestOfLine );
 					}
 					viSubTestIter++;
 				}
@@ -335,17 +266,8 @@
 			// Allocation fragment (call stack).
 			else if ( ! _stricmp( pCommand, ALLOCF_ID ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				// Add alloc fragment
-				vProcessList[iProcessIDinList].AllocF( sRestOfLine, sTime );
+				vProcessList[iProcessIDinList].AllocF( sRestOfLine );
 				
 				// Subtests running?
 				vector<CSubTestData>::iterator viSubTestIter = vProcessList[iProcessIDinList].vSubTests.begin();
@@ -354,164 +276,7 @@
 					if( viSubTestIter->bRunning )
 					{
 						// Save alloc fragment also to sub test
-						viSubTestIter->AllocF( sRestOfLine, sTime );
-					}
-					viSubTestIter++;
-				}
-			}
-			else if ( ! _stricmp( pCommand, REALLOCH_ID ) )
-			{
-				// Add free
-
-				// get 'free' line from realloc line
-				string sFreeRestOfLine = sRestOfLine;
-				string sFreeLine = "";
-				sFreeLine.append( GetStringUntilNextSpace( sFreeRestOfLine, true ) ); //append freed memory address
-				sFreeLine.append( " " );
-				// next two strings are for 'alloc' (address and size) - lets remove them
-				GetStringUntilNextSpace( sFreeRestOfLine, true );
-				GetStringUntilNextSpace( sFreeRestOfLine, true );
-				// add rest of line to 'free' line
-				sFreeLine.append( sFreeRestOfLine );
-				//add 'free' line
-				vProcessList[iProcessIDinList].FreeH( sFreeLine, sTime );
-
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				// construct 'free' header trace
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << FREEH_ID << " "; //add FRH
-				cleanedTraces << sFreeLine << "\n"; //add the rest of the line
-				}
-
-				// Add alloc
-
-				//get 'alloc' line from realloc line
-				// only first string is unnecessary, lets remove it
-				GetStringUntilNextSpace( sRestOfLine );
-     			// add 'alloc' line
-				vProcessList[iProcessIDinList].AllocH( sRestOfLine, sTime );
-
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				// construct 'alloc' header trace
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << ALLOCH_ID << " "; //add FRH
-				cleanedTraces << sRestOfLine << "\n"; //add the rest of the line
-				}
-
-				// Subtests running?
-				vector<CSubTestData>::iterator viSubTestIter = vProcessList[iProcessIDinList].vSubTests.begin();
-				while( viSubTestIter != vProcessList[iProcessIDinList].vSubTests.end() )
-				{
-					if( viSubTestIter->bRunning )
-					{
-						// Save realloc also to sub test
-						// Add free
-
-						// get 'free' line from realloc line
-						string sFreeRestOfLine = sRestOfLine;
-						string sFreeLine = "";
-						sFreeLine.append( GetStringUntilNextSpace( sFreeRestOfLine, true ) ); //append freed memory address
-						sFreeLine.append( " " );
-						// next two strings are for 'alloc' (address and size) - lets remove them
-						GetStringUntilNextSpace( sFreeRestOfLine, true );
-						GetStringUntilNextSpace( sFreeRestOfLine, true );
-						// add rest of line to 'free' line
-						sFreeLine.append( sFreeRestOfLine );
-						//add 'free' line
-						vProcessList[iProcessIDinList].FreeH( sFreeLine, sTime );
-
-						// Add alloc
-
-						//get 'alloc' line from realloc line
-						// only first string is unnecessary, lets remove it
-						GetStringUntilNextSpace( sRestOfLine );
-     					// add 'alloc' line
-						vProcessList[iProcessIDinList].AllocH( sRestOfLine, sTime );
-					}
-					viSubTestIter++;
-				}
-			}
-			// rellocation fragment (call stack).
-			else if ( ! _stricmp( pCommand, REALLOCF_ID ) )
-			{
-				// Add free fragment 
-
-				// get 'free' line from realloc line
-				string sFreeRestOfLine = sRestOfLine;
-				string sFreeLine = "";
-				sFreeLine.append( GetStringUntilNextSpace( sFreeRestOfLine, true ) ); //append freed memory address
-				sFreeLine.append( " " );
-				// next string is for 'alloc' (address) - lets remove it
-				GetStringUntilNextSpace( sFreeRestOfLine, true );
-				// add rest of line to 'free' line
-				sFreeLine.append( sFreeRestOfLine );
-				//add 'free' line
-				vProcessList[iProcessIDinList].FreeH( sFreeLine, sTime );
-
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				// construct 'free' fragment trace
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << FREEF_ID << " "; //add FRF
-				cleanedTraces << sFreeLine << "\n"; //add the rest of the line
-				}
-
-				// Add alloc fragment
-
-				// first string is for 'free' (address), lets remove it first
-				GetStringUntilNextSpace( sRestOfLine, true );
-				//add 'alloc' line
-				vProcessList[iProcessIDinList].AllocF( sRestOfLine, sTime );
-
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				// construct 'alloc' fragment trace
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << ALLOCF_ID << " "; //add FRF
-				cleanedTraces << sRestOfLine << "\n"; //add the rest of the line
-				}
-				
-				// Subtests running?
-				vector<CSubTestData>::iterator viSubTestIter = vProcessList[iProcessIDinList].vSubTests.begin();
-				while( viSubTestIter != vProcessList[iProcessIDinList].vSubTests.end() )
-				{
-					if( viSubTestIter->bRunning )
-					{
-						// Save alloc fragment also to sub test
-						// Add free fragment 
-
-						// get 'free' line from realloc line
-						string sFreeRestOfLine = sRestOfLine;
-						string sFreeLine = "";
-						sFreeLine.append( GetStringUntilNextSpace( sFreeRestOfLine, true ) ); //append freed memory address
-						sFreeLine.append( " " );
-						// next string is for 'alloc' (address) - lets remove it
-						GetStringUntilNextSpace( sFreeRestOfLine, true );
-						// add rest of line to 'free' line
-						sFreeLine.append( sFreeRestOfLine );
-						//add 'free' line
-						vProcessList[iProcessIDinList].FreeH( sFreeLine, sTime );
-
-						// Add alloc fragment
-
-						// first string is for 'free' (address), lets remove it first
-						GetStringUntilNextSpace( sRestOfLine, true );
-						//add 'alloc' line
-						vProcessList[iProcessIDinList].AllocF( sRestOfLine, sTime );
+						viSubTestIter->AllocF( sRestOfLine );
 					}
 					viSubTestIter++;
 				}
@@ -537,17 +302,8 @@
 			// Header free.
 			else if( ! _stricmp( pCommand, FREEH_ID ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				// Send free
-				vProcessList[iProcessIDinList].FreeH( sRestOfLine, sTime );
+				vProcessList[iProcessIDinList].FreeH( sRestOfLine );
 
 				// Subtests running?
 				vector<CSubTestData>::iterator viSubTestIter = vProcessList[iProcessIDinList].vSubTests.begin();
@@ -556,7 +312,7 @@
 					if( viSubTestIter->bRunning )
 					{
 						// Send free to subtest
-						viSubTestIter->FreeH( sRestOfLine, sTime );
+						viSubTestIter->FreeH( sRestOfLine );
 					}
 					viSubTestIter++;
 				}
@@ -564,34 +320,11 @@
 			}
 			else if( ! _stricmp( pCommand, FREEF_ID ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
 				// Not used currently.
 			}
 			// Command process end
 			else if( ! _stricmp( pCommand, LABEL_PROCESS_END ) )
 			{
-				// append processID and time
-				sWholeTempLine.append(" ");
-				sWholeTempLine.append( sProcessID );
-				sWholeTempLine.append(" ");
-				sWholeTempLine.append( sTime );
-
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				// Set process has ended.
 				vProcessList[iProcessIDinList].bProcessOnGoing = false;
 
@@ -672,15 +405,6 @@
 			}
 			else if( ! _stricmp( pCommand, LABEL_HANDLE_LEAK ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				// Make whole line
 				sTemp.append( " " );
 				sTemp.append( sRestOfLine );
@@ -688,19 +412,6 @@
 			}
 			else if( ! _stricmp( pCommand, LABEL_DLL_LOAD ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
-				// append time to the end of the line
-				sWholeTempLine.append( " " );
-				sWholeTempLine.append( sTime );
-
 				// Add module load to process data.
 				vProcessList[iProcessIDinList].vData.push_back( sWholeTempLine );
 				// Add module load to subtest data if test running.
@@ -714,19 +425,6 @@
 			}
 			else if( ! _stricmp( pCommand, LABEL_DLL_UNLOAD ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
-				// append time to the end of the line
-				sWholeTempLine.append( " " );
-				sWholeTempLine.append( sTime );
-
 				// Add module load to process data.
 				vProcessList[iProcessIDinList].vData.push_back( sWholeTempLine );
 				// Add module unload to subtest data if test running.
@@ -741,28 +439,10 @@
 				     sTemp.find( LABEL_PROCESS_END ) != string::npos || sTemp.find( LABEL_ERROR_OCCURED ) != string::npos ||
 					 sTemp.find( LABEL_HANDLE_LEAK ) != string::npos )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				vProcessList[iProcessIDinList].vData.push_back( sWholeTempLine );
 			}
 			else if( ! _stricmp( pCommand, LABEL_TEST_START ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				bRet = true; // Set return value true we found start.
 				// Get sub test time
 				string sSubTestTime = GetStringUntilNextSpace( sRestOfLine );
@@ -781,15 +461,6 @@
 			}
 			else if( ! _stricmp( pCommand, LABEL_TEST_END ) )
 			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
 				// Get sub test time
 				string sSubTestEnd = GetStringUntilNextSpace( sRestOfLine );
 				// Get sub test name
@@ -810,53 +481,9 @@
 					viSubTestIter++;
 				}
 			}
-			else if( ! _stricmp( pCommand, LABEL_THREAD_START ) )
-			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
-				//currently not used
-			}
-			else if( ! _stricmp( pCommand, LABEL_THREAD_END ) )
-			{
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-
-				//currently not used
-			}
-			else
-			{
-				// unknown tag, log it to cleaned file for carbide
-				if( bCreateCleanedTraces )
-				{
-				// add message to cleaned traces file
-				cleanedTraces << sTime << " "; //add time
-				cleanedTraces << MAIN_ID << " "; //add MAIN_ID
-				cleanedTraces << sProcessID << " "; //add process ID
-				cleanedTraces << sWholeTempLine << "\n"; //add the rest of the line
-				}
-			}
 		}
 	}
 
-	if( bCreateCleanedTraces )
-	{
-	// close stream
-	cleanedTraces.close();
-	}
-
 	// Print all saved data from processes
 	for( unsigned int i = 0 ; i < vProcessList.size() ; i++ )
 	{
@@ -955,19 +582,4 @@
 	LOG_LOW_FUNC_ENTRY("CATParseTraceFile::GetDataSaver");
 	return &m_DataSaver;
 }
-
-
-// -----------------------------------------------------------------------------
-// CATBase::GetTimeFromTimeStamp
-// Gets time from timestamp in microseconds as string
-// -----------------------------------------------------------------------------
-string CATParseTraceFile::GetTimeFromTimeStamp( unsigned __int64 iTimeStamp, unsigned __int64 iTimeSpan )
-{
-	unsigned __int64 iTime = iTimeStamp + iTimeSpan;
-	stringstream ss;
-	ss <<  std::hex << iTime;
-
-    return ss.str();
-}
-
 //EOF
--- a/analyzetool/commandlineengine/src/CATProject.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/CATProject.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -19,7 +19,6 @@
 #include "../inc/CATProject.h"
 #include "../inc/CATModule2.h"
 #include "../inc/CATParseTraceFile.h"
-#include "../inc/CATParseBinaryFile.h"
 #include "../inc/CATDatParser.h"
 
 //dbghelp.dll version function.
@@ -52,12 +51,10 @@
 	m_sDataFile = "";
 	m_sDataFileOutput = "";
 	m_sDataFileTemp = "";
-	m_sBinaryLogFileTemp = "";
 	m_sEpocRoot = "\\";
 	m_sMakeFile = "";
 	m_sPlatform = "";
 	m_sS60FileName = "";
-	m_sS60FilePath = "";
 	m_sTargetModule = "";
 	m_sVariant = "";
 
@@ -87,14 +84,6 @@
 		if ( FileExists( m_sDataFileTemp.c_str() ) )
 			FileDelete( m_sDataFileTemp, false );
 	}
-
-	// Temporary trace file
-	if ( !m_sBinaryLogFileTemp.empty() )
-	{
-		if ( FileExists( m_sBinaryLogFileTemp.c_str() ) )
-			FileDelete( m_sBinaryLogFileTemp, false );
-	}
-	
 }
 
 bool CATProject::SetArguments( ARGUMENTS& arguments )
@@ -191,14 +180,10 @@
 		bRet = false;
 	}
 
-	//Internal data file name.
+	//Internal data file.
 	if ( arguments.HOOK.bDataFileName )
 		SetS60FileName( arguments.HOOK.sDataFileName );
 
-	//Internal data file path.
-	if ( arguments.HOOK.bDataFilePath )
-		SetS60FilePath( arguments.HOOK.sDataFilePath );
-
 	//Build command.
 	if ( arguments.HOOK.sBuildCmd.empty() && ( 
 		GetMode() == CATProject::COMPILE ||
@@ -518,45 +503,15 @@
 {
 	LOG_FUNC_ENTRY("CATProject::RunAnalyze");
 
-	// Parse data file if it is not data file.
+	// Parse data file if it is trace.
 	if ( !IsDataFile( m_sDataFile ) )
 	{
 		m_sDataFileTemp.clear();
 		m_sDataFileTemp.append( m_sDataFile );
 		m_sDataFileTemp.append( ".atool" );
-
-		// make filename for file with cleaned timestamps
-		// <m_sDataFile>.cleaned in the same place as output file
-		string sTraceFileCleaned( GetPathOrFileName( false, m_sDataFileOutput ) );
-		sTraceFileCleaned.append( GetPathOrFileName( true, m_sDataFile ) );
-		sTraceFileCleaned.append( ".cleaned" );
-
-		//check if it is binary log file
-		if( IsBinaryLogFile( m_sDataFile ) )
-		{
-			// convert binary log file to ASCII trace format
-			m_sBinaryLogFileTemp.clear();
-		    m_sBinaryLogFileTemp.append( m_sDataFile );
-		    m_sBinaryLogFileTemp.append( ".totraces" );
-
-			cout << AT_MSG << "Parsing binary data file..." << endl;
-
-			CATParseBinaryFile Parser;
-			stringstream dataToParse;
-			if ( ! Parser.StartParse( m_sDataFile.c_str(), m_sBinaryLogFileTemp.c_str() ) )
-			{
-				return AT_RETURN_CODE::EMPTY_DATA_FILE;
-			}
-			m_sDataFile = m_sBinaryLogFileTemp;
-			
-		}
-		else
-		{
-			cout << AT_MSG << "Parsing trace file..." << endl;
-		}
-
+		cout << AT_MSG << "Parsing trace file..." << endl;
 		CATParseTraceFile Parser;
-		if ( ! Parser.StartParse( m_sDataFile.c_str(), m_sDataFileTemp.c_str(), sTraceFileCleaned.c_str() ) )
+		if ( ! Parser.StartParse( m_sDataFile.c_str(), m_sDataFileTemp.c_str() ) )
 		{
 			return AT_RETURN_CODE::EMPTY_DATA_FILE;
 		}
@@ -832,17 +787,14 @@
 			if ( m_eLoggingMode == CATProject::FILE 
 				&& m_vModules.at(i)->GetTargetType().compare("exe") == 0 )
 			{
-				cout << AT_BUILD_SUMMARY_DATA_FILE_NAME
+				if ( m_sS60FileName.empty() )
+					cout << AT_BUILD_SUMMARY_DATA_FILE_NAME
 						<< m_vModules.at(i)->GetS60FileName()
 						<< endl;
-
-				// if filePath not empty, use it for log file
-				if ( !m_sS60FilePath.empty() )
-				{
-					cout << AT_BUILD_SUMMARY_DATA_FILE_PATH
-					<< m_sS60FilePath
+				else
+					cout << AT_BUILD_SUMMARY_DATA_FILE_NAME
+					<< m_sS60FileName
 					<< endl;
-				}
 			}
 		}
 		else
@@ -1601,7 +1553,7 @@
 	for( size_t i = 0 ; i < m_vModules.size(); i++)
 	{
 		if( ! m_vModules.at(i)->CreateTempCpp(
-			m_sS60FileName, m_sS60FilePath, m_eLoggingMode, m_eBuildType, m_iAllocCallStackSize, m_iFreeCallStackSize ) )
+			m_sS60FileName, m_eLoggingMode, m_eBuildType, m_iAllocCallStackSize, m_iFreeCallStackSize ) )
 			bRet = false;
 	}
 	return bRet;
@@ -2003,7 +1955,6 @@
 		out << m_vTargetModules.at(i) << AT_PROJECT_ATTRIBUTES_SEPARATOR;
 	out << endl;
 	out << m_sBuildCommand << endl;
-	out << m_sS60FilePath << endl;
 	out.close();
 	return true;
 }
@@ -2059,7 +2010,6 @@
 		iSpot = sLine.find( AT_PROJECT_ATTRIBUTES_SEPARATOR );
 	}
 	in.getline( cLine, MAX_LINE_LENGTH ); m_sBuildCommand = cLine;
-	in.getline( cLine, MAX_LINE_LENGTH ); m_sS60FilePath = string( cLine );
 	in.close();
 	return true;
 }
@@ -2418,11 +2368,6 @@
 	LOG_FUNC_ENTRY("CATProject::SetS60FileName");
 	m_sS60FileName = sFileName;
 }
-void CATProject::SetS60FilePath( const string& sFilePath)
-{
-	LOG_FUNC_ENTRY("CATProject::SetS60FilePath");
-	m_sS60FilePath = sFilePath;
-}
 void CATProject::SetRomSymbolFiles(const vector<string>& vRomSymbolFiles)
 {
 	LOG_FUNC_ENTRY("CATProject::SetRomSymbolFiles");
--- a/analyzetool/commandlineengine/src/arguments.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/arguments.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -22,13 +22,11 @@
 bool parseAnalyzeArguments( vector<string>& vArgs, ARGUMENTS& args );
 bool parseParseArguments( vector<string>& vArgs, ARGUMENTS& args );
 bool checkDataFileName( string& sFileName );
-bool checkDataFilePath( string& sFilePath );
 bool parseSbsConfiguration( string& sConfiguration, ARGUMENTS& args );
 
 // Constants for old "hooking" parameter parsing.
 #define INVALID_PARAMETER "AnalyzeTool : Error, invalid parameter: "
-const char DATAFILENAME_INVALID_CHARS[] = " &^+-@$*()|\\/[]{}<>?;:,\"'";
-const char DATAFILEPATH_INVALID_CHARS[] = " &^+-@$%*()|/[]{}<>?;,\"'";
+const char DATAFILENAME_INVALID_CHARS[] = " &^+-@$%*()|\\/[]{}<>?;:,\"'";
 
 /**
 * Check datafile name for invalid characters.
@@ -46,40 +44,6 @@
 }
 
 /**
-* Check datafile path for invalid characters and correct format.
-* @return true if file path ok.
-*/
-bool checkDataFilePath( string& sFilePath )
-{
-	for ( size_t i = 0; i < sFilePath.length(); i++ )
-	{
-		char c = sFilePath.at( i );
-		if( strchr( DATAFILEPATH_INVALID_CHARS, c ) != 0 )
-			return false;
-		// first char must be drive letter a-z
-		if( i == 0 && ( c = tolower( c ) < 'a' || c > 'z' ) )
-			return false;
-		// if last char is not '\', add it
-		if( i == sFilePath.length()-1 &&  c != '\\' )
-			sFilePath.append( "\\" );
-	}
-
-	// ':\' after drive letter
-	if( sFilePath.find( ":\\" ) != 1 )
-		return false;
-
-	// there can be only one ':' on pos 1
-	if( sFilePath.find( ":", 2 ) != string::npos )
-		return false;
-
-	//check double slashes
-	if( sFilePath.find( "\\\\" ) != string::npos )
-		return false;
-
-	return true;
-}
-
-/**
 * Parse base arguments from given vector of strings.
 * Removes debug / help arguments from vector.
 */
@@ -214,19 +178,16 @@
 			args.eMainSwitch = SWITCH_HELP;
 		else if ( ! _stricmp( (*it).c_str(), "-me" ) )
 		{
-			cout << AT_MSG << "This feature is no longer supported. You can use -tr parameter for output to trace. \n" << endl;
+			args.eMainSwitch = SWITCH_HOOK;
+			args.eHookSwitch = HOOK_EXTERNAL;
 		}
-		else if ( ! _stricmp( (*it).c_str(), "-e" ) ||  ! _stricmp( (*it).c_str(), "-tr" ) )
+		else if ( ! _stricmp( (*it).c_str(), "-e" ) )
 		{
 			args.eMainSwitch = SWITCH_HOOK;
 			args.eHookSwitch = HOOK_EXTERNAL_FAST;
 		}
 		else if ( ! _stricmp( (*it).c_str(), "-mi" ) )
 		{
-			cout << AT_MSG << "This feature is no longer supported. You can use -lf parameter for logging to file. \n" << endl;
-		}
-		else if ( ! _stricmp( (*it).c_str(), "-lf" ) )
-		{
 			args.eMainSwitch = SWITCH_HOOK;
 			args.eHookSwitch = HOOK_INTERNAL;
 		}
@@ -394,8 +355,7 @@
 				}
 				else if ( ! _stricmp( it->c_str(), "sbs" ) 
 					|| ! _stricmp( it->c_str(), "abld" )
-					|| ! _stricmp( it->c_str(), "-f" )
-					|| ! _stricmp( it->c_str(), "-fp" ) )
+					|| ! _stricmp( it->c_str(), "-f" ) )
 				{
 					bRet = false;
 					cout << AT_MSG << "Error, missing call stack size parameter." << endl;
@@ -447,13 +407,13 @@
 				if ( it == vArgs.end() )
 				{
 					bRet = false;
-					cout << AT_MSG << "Error, missing log file name." << endl;
+					cout << AT_MSG << "Error, missing internal data gathering file name." << endl;
 					break;
 				}
 				else if ( ! _stricmp( it->c_str(), "sbs" ) || ! _stricmp( it->c_str(), "abld" ) )
 				{
 					bRet = false;
-					cout << AT_MSG << "Error, missing log file name." << endl;
+					cout << AT_MSG << "Error, missing internal data gathering file name." << endl;
 					break;
 				}
 				else
@@ -467,41 +427,7 @@
 					else
 					{
 						bRet = false;
-						cout << AT_MSG << "Error, specified log file name contains invalid character(s)." << endl;
-						break;
-					}
-				}
-			}
-			// Data file path.
-			else if ( _stricmp( it->c_str(), "-fp" ) == 0 )
-			{
-				it++;
-				if ( it == vArgs.end() )
-				{
-					bRet = false;
-					cout << AT_MSG << "Error, missing path for log file." << endl;
-					break;
-				}
-				else if ( ! _stricmp( it->c_str(), "sbs" ) || ! _stricmp( it->c_str(), "abld" ) )
-				{
-					bRet = false;
-					cout << AT_MSG << "Error, missing path for log file." << endl;
-					break;
-				}
-				else
-				{
-					string sFormattedPath = string(*it);
-					if ( checkDataFilePath( sFormattedPath ) )
-					{
-						// Pickup filename.
-						args.HOOK.bDataFilePath = true;
-						args.HOOK.sDataFilePath = sFormattedPath;
-					}
-					else
-					{
-						bRet = false;
-						cout << AT_MSG << "Error, specified log file path contains invalid character(s) "
-							<< "or is in wrong format. Please, check help for correct format," << endl;
+						cout << AT_MSG << "Error, specified internal data gathering file name contains invalid character(s)." << endl;
 						break;
 					}
 				}
--- a/analyzetool/commandlineengine/src/atool.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/atool.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -207,12 +207,6 @@
 				cout << AT_MSG << "Error, " << args.PARSE.sDataFile << " is already parsed." << endl;
 				return AT_RETURN_CODE::INVALID_ARGUMENT_ERROR;
 			}
-			else if( CATBase::IsBinaryLogFile( args.PARSE.sDataFile ) )
-			{
-				cout << AT_MSG << "Error, " << args.PARSE.sDataFile << " is binary log file." << endl;
-				return AT_RETURN_CODE::INVALID_ARGUMENT_ERROR;
-			}
-
 			if ( args.PARSE.bOutputFile )
 			{
 				//Save data with name in arguments[3]
--- a/analyzetool/commandlineengine/src/catallocs.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/catallocs.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -36,65 +36,14 @@
 	}
 }
 
-void CATAllocs::AllocH( const string& sAllocHString, const string& aTimeString )
+void CATAllocs::AllocH( const string& sAllocHString )
 {
 	LOG_LOW_FUNC_ENTRY("CATAllocs::AllocH");
 	string sAllocH( sAllocHString );
 	// Parse alloc & create new allocation.
 	CATAlloc alloc;
-	alloc.m_sTime = aTimeString;
 	string sAddress = GetStringUntilNextSpace( sAllocH, true );
-	alloc.m_sSize = GetStringUntilNextSpace( sAllocH, true );
-	alloc.m_iThreadId = GetStringUntilNextSpace ( sAllocH, true );
-	alloc.m_iCSCount = _httoi( string( GetStringUntilNextSpace( sAllocH, true ) ).c_str() );
-	// Insert call stack fragment as "first" 1 because we are header.
-	if ( alloc.m_iCSCount > 0 )
-		alloc.m_vCallStack.insert( pair<unsigned long,string>( 0, sAllocH ) );
-	// Add allocation
-	pair< map<string,CATAlloc>::iterator, bool> ret;
-	ret = m_vAllocs.insert( pair<string, CATAlloc>( sAddress, alloc ) );
-	if( ret.second == false )
-	{
-		// Allocation to this memory address was already added.
-		LOG_STRING( "CATAllocs: Allocating same address again, address: " << sAddress );
-	}
-}
-
-void CATAllocs::AllocF( const string& sAllocFString, const string& aTimeString )
-{
-	LOG_LOW_FUNC_ENTRY("CATAllocs::AllocF");
-	string sAllocF( sAllocFString );
-	string sAddress = GetStringUntilNextSpace( sAllocF, true );
-	string sTime = aTimeString;
-	unsigned long iNumber = _httoi( string( GetStringUntilNextSpace( sAllocF, true ) ).c_str() );
-	string sCallSstack = sAllocF;
-	// Find correct allocation into which add call stack fragment.
-	map<string, CATAlloc>::iterator it;
-	it = m_vAllocs.find( sAddress );
-	// TODO: If cannot find, create new in cache.
-	if ( it == m_vAllocs.end() )
-	{
-		LOG_STRING( "CATAllocs: Allocate fragment without header: " << sAddress );
-		return;
-	}
-	pair< map<unsigned long,string>::iterator, bool> ret;
-	// Add call stack to it.
-	ret = it->second.m_vCallStack.insert( pair<unsigned long,string>( iNumber, sCallSstack ) );
-	if( ret.second == false )
-	{
-		LOG_STRING( "CATAllocs: Same allocation fragment again: " << sAddress );
-	}
-}
-
-// ReallocH.
-void CATAllocs::ReallocH( const string& sReallocHString, const string& aTimeString )
-{
-	LOG_LOW_FUNC_ENTRY("CATAllocs::ReallocH");
-	string sAllocH( sReallocHString );
-	// Parse alloc & create new allocation.
-	CATAlloc alloc;
-	string sAddress = GetStringUntilNextSpace( sAllocH, true );
-	alloc.m_sTime = aTimeString;
+	alloc.m_sTime = GetStringUntilNextSpace( sAllocH, true );
 	alloc.m_sSize = GetStringUntilNextSpace( sAllocH, true );
 	alloc.m_iCSCount = _httoi( string( GetStringUntilNextSpace( sAllocH, true ) ).c_str() );
 	// Insert call stack fragment as "first" 1 because we are header.
@@ -110,13 +59,12 @@
 	}
 }
 
-// ReallocF.
-void CATAllocs::ReallocF( const string& sReallocFString, const string& aTimeString )
+void CATAllocs::AllocF( const string& sAllocFString )
 {
-	LOG_LOW_FUNC_ENTRY("CATAllocs::ReallocF");
-	string sAllocF( sReallocFString );
+	LOG_LOW_FUNC_ENTRY("CATAllocs::AllocF");
+	string sAllocF( sAllocFString );
 	string sAddress = GetStringUntilNextSpace( sAllocF, true );
-	string sTime = aTimeString;
+	string sTime = GetStringUntilNextSpace( sAllocF, true );
 	unsigned long iNumber = _httoi( string( GetStringUntilNextSpace( sAllocF, true ) ).c_str() );
 	string sCallSstack = sAllocF;
 	// Find correct allocation into which add call stack fragment.
@@ -156,7 +104,7 @@
 }
 
 // FreeH.
-void CATAllocs::FreeH( const string& sFreeH, const string& aTimeString )
+void CATAllocs::FreeH( const string& sFreeH )
 {
 	LOG_LOW_FUNC_ENTRY("CATAllocs::FreeH");
 	// Current implementation does not use call stack of
@@ -164,7 +112,6 @@
 	string sFree( sFreeH );
 	string sKey = GetStringUntilNextSpace( sFree );
 	// Time stamp. (not used currently)
-	// Thread ID. (not used currently)
 	// Call stack count. (not used currently)
 	// Call stack data. (not used currently)
 
@@ -181,7 +128,7 @@
 }
 
 // FreeF.
-void CATAllocs::FreeF( const string& /* sFreeF */, const string& /* aTimeString */ )
+void CATAllocs::FreeF( const string& /* sFreeF */ )
 {
 	LOG_LOW_FUNC_ENTRY("CATAllocs::FreeF");
 	// Fragments are currently ignored.
--- a/analyzetool/commandlineengine/src/helps.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/commandlineengine/src/helps.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -32,8 +32,9 @@
 	cout<< "\n";
 	cout<< "Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).\nAll rights reserved.\n\n";
 	cout<< "Usage:\n";
-	cout<< "atool -tr [optional parameters] abld [abld parameters]\n";
-	cout<< "      -lf [optional parameters] abld [abld parameters]\n";
+	cout<< "atool -e [optional parameters] abld [abld parameters]\n";
+	cout<< "      -me [optional parameters] abld [abld parameters]\n";
+	cout<< "      -mi [optional parameters] [-f data-file] sbs [sbs parameters]\n";
 	cout<< "      -a data-file [output-file] [-s symbol-file] [-l#]\n";
 	cout<< "      -p data-file output-file\n";
 	cout<< "      -c\n";
@@ -41,8 +42,11 @@
 	cout<< "      -help\n";
 	cout<< "\n";
 	cout<< "Mandatory parameter to choose:\n";
-	cout<< " -tr             Build project for analysis using output to trace.\n";
-	cout<< " -lf             Build project for analysis using logging to file.\n";
+	cout<< " -e              Build project for analysis using external data gathering.\n";
+	cout<< " -me             Build project for analysis using monitored external\n";
+	cout<< "                 data gathering.\n";
+	cout<< " -mi             Build project for analysis using monitored internal\n";
+	cout<< "                 data gathering.\n";
 	cout<< " abld...         Use SBS v.1 build system with defined build command,\n";
 	cout<< "                 which includes supported platform and build type.\n";
 	cout<< " sbs...          Use SBS v.2 (Raptor) build system with defined sbs build\n";
@@ -59,10 +63,8 @@
 	cout<< "                 is allocated. Size can be between 0-256.\n";
 	cout<< " -fcs size       Specifies the call stack size gathered when memory is freed.\n";
 	cout<< "                 Size can be between 0-256.\n";
-	cout<< " -f data file    Specifies the filename for logging to file.\n";
+	cout<< " -f data file    Specifies the filename for monitored internal data gathering\n";
 	cout<< "                 (50 chars max). Cannot contain path.\n";
-	cout<< " -fp file path   Specifies the path of log file.\n";
-	cout<< "                 (in format <driveLetter>:\\<dir1>\\<dir2>\\...\\<dirN>\\)\n";
 	cout<< " output-file     Specifies the results data file name.\n";
 	cout<< " -l              Logging level of analyze report(0,1,2,3), default 3.\n";
 	cout<< " -s symbol-file  Specifies rom/rofs symbol file(s) to be used in analyze.\n";
@@ -123,37 +125,37 @@
 	cout<< "Building syntax examples:" << endl;
 	cout<< "Cmd   Description" << endl;
 	
-	cout<< "atool -tr abld build armv5 udeb" << endl;
-	cout<< "      Hooks every component from bld.inf. Using output to trace," << endl;
+	cout<< "atool -e abld build armv5 udeb" << endl;
+	cout<< "      Hooks every component from bld.inf. Using external data gathering," << endl;
 	cout<< "      udeb build type and armv5 platform." << endl;
 
-	cout<< "atool -lf -acs 5 sbs -c winscw_udeb" << endl;
+	cout<< "atool -mi -acs 5 sbs -c winscw_udeb" << endl;
 	cout<< "      Hooks every component from bld.inf. Using Symbian Build System v.2" << endl;
-	cout<< "      Using loging to data file, call stack size of 5" << endl;
+	cout<< "      Using monitored internal data gathering, call stack size of 5" << endl;
 	cout<< "      in allocations, udeb build type and winscw platform." << endl;
 	
-	cout<< "atool -tr abld build armv5 udeb foobar" << endl;
-	cout<< "      Hooks only foobar.mmp component from bld.inf. Using " << endl;
-	cout<< "      output to trace, udeb build type and armv5 platform." << endl;
+	cout<< "atool -me abld build armv5 udeb foobar" << endl;
+	cout<< "      Hooks only foobar.mmp component from bld.inf. Using monitored" << endl;
+	cout<< "      external data gathering, udeb build type and armv5 platform." << endl;
 	
-	cout<< "atool -lf -acs 0 -fcs 0 abld build armv5.default udeb" << endl;
+	cout<< "atool -e -acs 0 -fcs 0 abld build armv5.default udeb" << endl;
 	cout<< "      Hooks every component from bld.inf. Using default binary variant," << endl;
-	cout<< "      output to trace, 0 sized callstacks in allocation(s)/free(s)," << endl;
+	cout<< "      external data gathering, 0 sized callstacks in allocation(s)/free(s)," << endl;
 	cout<< "      udeb build type and armv5 platform." << endl;
 	
-	cout<< "atool -tr sbs -b bld.inf -c armv5_udeb" << endl;
+	cout<< "atool -e sbs -b bld.inf -c armv5_udeb" << endl;
 	cout<< "      Hooks every component from bld.inf. Using Symbian Build System v.2" << endl;
-	cout<< "      , output to trace, udeb build type and armv5 platform." << endl;
+	cout<< "      , external data gathering, udeb build type and armv5 platform." << endl;
 	
-	cout<< "atool -tr sbs -s system.xml --config=winscw_udeb" << endl;
+	cout<< "atool -me sbs -s system.xml --config=winscw_udeb" << endl;
 	cout<< "      Hooks every layer defined in system.xml system model. Using Symbian Build" << endl;
-	cout<< "      System v.2, output to trace, udeb build type and winscw platform." << endl;
+	cout<< "      System v.2, external data gathering, udeb build type and winscw platform." << endl;
 
 	cout<< endl;
 	cout<< "Instrumenting syntax examples:" << endl;
 	cout<< "Cmd   Description" << endl;
-	cout<< "atool -tr -nobuild abld build winscw udeb" << endl;
-	cout<< "      Instruments every component from bld.inf. Using output to trace,"<<endl;
+	cout<< "atool -e -nobuild abld build winscw udeb" << endl;
+	cout<< "      Instruments every component from bld.inf. Using external data gathering,"<<endl;
 	cout<< "      udeb build target and winscw platform." << endl;
     cout<< "   After project is instrumented, it needs to compiled using same platform and" << endl;
 	cout<< "   build type as given to instrumenting. Use -c parameter to remove changes." << endl;
--- a/analyzetool/dynamicmemoryhook/bwins/atoolmemoryhooku.def	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/bwins/atoolmemoryhooku.def	Wed Oct 13 16:17:58 2010 +0300
@@ -1,10 +1,10 @@
 EXPORTS
 	?Alloc@RAnalyzeToolAllocator@@UAEPAXH@Z @ 1 NONAME ; void * RAnalyzeToolAllocator::Alloc(int)
-	?SetupThreadHeap@CustomUser@@SAHHAAUSStdEpocThreadCreateInfo@@ABV?$TBuf@$0BAA@@@1KKABV?$TBuf@$0BE@@@KKV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 2 NONAME ; int CustomUser::SetupThreadHeap(int, struct SStdEpocThreadCreateInfo &, class TBuf<256> const &, class TBuf<256> const &, unsigned long, unsigned long, class TBuf<20> const &, unsigned long, unsigned long, class TRefByValue<class TDesC16 const >, ...)
-	?SetCritical@CustomUser@@SAHW4TCritical@User@@@Z @ 3 NONAME ; int CustomUser::SetCritical(enum User::TCritical)
-	?Exit@CustomUser@@SAXH@Z @ 4 NONAME ; void CustomUser::Exit(int)
-	?SetProcessCritical@CustomUser@@SAHW4TCritical@User@@@Z @ 5 NONAME ; int CustomUser::SetProcessCritical(enum User::TCritical)
-	?InstallAllocator@CustomUser@@CAAAVRAllocator@@HABV?$TBuf@$0BAA@@@0KKKKABVTDesC8@@1@Z @ 6 NONAME ; class RAllocator & CustomUser::InstallAllocator(int, class TBuf<256> const &, class TBuf<256> const &, unsigned long, unsigned long, unsigned long, unsigned long, class TDesC8 const &, class TDesC8 const &)
-	?Panic@CustomUser@@SAXABVTDesC16@@H@Z @ 7 NONAME ; void CustomUser::Panic(class TDesC16 const &, int)
-	?Alloc@RAnalyzeToolMainAllocator@@UAEPAXH@Z @ 8 NONAME ; void * RAnalyzeToolMainAllocator::Alloc(int)
+	?Alloc@RAnalyzeToolMainAllocator@@UAEPAXH@Z @ 2 NONAME ; void * RAnalyzeToolMainAllocator::Alloc(int)
+	?Exit@CustomUser@@SAXH@Z @ 3 NONAME ; void CustomUser::Exit(int)
+	?InstallAllocator@CustomUser@@CAAAVRAllocator@@HABV?$TBuf@$0BAA@@@KKKK@Z @ 4 NONAME ; class RAllocator & CustomUser::InstallAllocator(int, class TBuf<256> const &, unsigned long, unsigned long, unsigned long, unsigned long)
+	?Panic@CustomUser@@SAXABVTDesC16@@H@Z @ 5 NONAME ; void CustomUser::Panic(class TDesC16 const &, int)
+	?SetCritical@CustomUser@@SAHW4TCritical@User@@@Z @ 6 NONAME ; int CustomUser::SetCritical(enum User::TCritical)
+	?SetProcessCritical@CustomUser@@SAHW4TCritical@User@@@Z @ 7 NONAME ; int CustomUser::SetProcessCritical(enum User::TCritical)
+	?SetupThreadHeap@CustomUser@@SAHHAAUSStdEpocThreadCreateInfo@@ABV?$TBuf@$0BAA@@@KKABV?$TBuf@$0BE@@@KKV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 8 NONAME ; int CustomUser::SetupThreadHeap(int, struct SStdEpocThreadCreateInfo &, class TBuf<256> const &, unsigned long, unsigned long, class TBuf<20> const &, unsigned long, unsigned long, class TRefByValue<class TDesC16 const >, ...)
 
--- a/analyzetool/dynamicmemoryhook/eabi/atoolmemoryhooku.def	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/eabi/atoolmemoryhooku.def	Wed Oct 13 16:17:58 2010 +0300
@@ -1,18 +1,16 @@
 EXPORTS
 	_ZN10CustomUser11SetCriticalEN4User9TCriticalE @ 1 NONAME
-	_ZN10CustomUser15SetupThreadHeapEiR24SStdEpocThreadCreateInfoRK4TBufILi256EES5_mmRKS2_ILi20EEmm11TRefByValueIK7TDesC16Ez @ 2 NONAME
-	_ZN10CustomUser16InstallAllocatorEiRK4TBufILi256EES3_mmmmRK6TDesC8S6_ @ 3 NONAME
+	_ZN10CustomUser15SetupThreadHeapEiR24SStdEpocThreadCreateInfoRK4TBufILi256EEmmRKS2_ILi20EEmm11TRefByValueIK7TDesC16Ez @ 2 NONAME
+	_ZN10CustomUser16InstallAllocatorEiRK4TBufILi256EEmmmm @ 3 NONAME
 	_ZN10CustomUser18SetProcessCriticalEN4User9TCriticalE @ 4 NONAME
 	_ZN10CustomUser4ExitEi @ 5 NONAME
 	_ZN10CustomUser5PanicERK7TDesC16i @ 6 NONAME
-	_ZTI10RATFileLog @ 7 NONAME
-	_ZTI20CLibraryEventHandler @ 8 NONAME
-	_ZTI21RAnalyzeToolAllocator @ 9 NONAME
-	_ZTI25RAnalyzeToolMainAllocator @ 10 NONAME
-	_ZTI27RAnalyzeToolMemoryAllocator @ 11 NONAME
-	_ZTV10RATFileLog @ 12 NONAME
-	_ZTV20CLibraryEventHandler @ 13 NONAME
-	_ZTV21RAnalyzeToolAllocator @ 14 NONAME
-	_ZTV25RAnalyzeToolMainAllocator @ 15 NONAME
-	_ZTV27RAnalyzeToolMemoryAllocator @ 16 NONAME
+	_ZTI20CLibraryEventHandler @ 7 NONAME ; #<TI>#
+	_ZTI21RAnalyzeToolAllocator @ 8 NONAME ; #<TI>#
+	_ZTI25RAnalyzeToolMainAllocator @ 9 NONAME ; #<TI>#
+	_ZTI27RAnalyzeToolMemoryAllocator @ 10 NONAME ; #<TI>#
+	_ZTV20CLibraryEventHandler @ 11 NONAME ; #<VT>#
+	_ZTV21RAnalyzeToolAllocator @ 12 NONAME ; #<VT>#
+	_ZTV25RAnalyzeToolMainAllocator @ 13 NONAME ; #<VT>#
+	_ZTV27RAnalyzeToolMemoryAllocator @ 14 NONAME ; #<VT>#
 
--- a/analyzetool/dynamicmemoryhook/group/atoolmemoryhook.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/group/atoolmemoryhook.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -39,12 +39,14 @@
 SOURCE        analyzetoolmainallocator.cpp
 SOURCE        analyzetoolallocator.cpp
 SOURCE        analyzetoolfastlog.cpp
+
+SOURCEPATH    ../../storageserver/server/src
 SOURCE        atdriveinfo.cpp
-SOURCE        analyzetoolfilelog.cpp
 
 USERINCLUDE   ../inc
 USERINCLUDE   ../../inc
-USERINCLUDE   ../../analyzetool_plat/analyzetool_api/inc/analyzetool
+USERINCLUDE   ../../storageserver/inc
+USERINCLUDE   ../../storageserver/server/inc
 
 #ifdef WINSCW
 APP_LAYER_SYSTEMINCLUDE
@@ -54,14 +56,10 @@
 
 LIBRARY       efsrv.lib 
 LIBRARY       euser.lib
+LIBRARY       atoolstorageserverclnt.lib
 LIBRARY       flogger.lib
 LIBRARY       charconv.lib 
-LIBRARY       platformenv.lib
-LIBRARY       sysutil.lib 
-LIBRARY       estor.lib 
-#ifdef WINSCW
-LIBRARY        cone.lib
-#endif
+LIBRARY       platformenv.lib 
 
 #if ( SYMBIAN_VERSION_SUPPORT >= SYMBIAN_3 )
 MACRO	USE_CLEANER_DLL
--- a/analyzetool/dynamicmemoryhook/inc/analyzetoolallocator.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/inc/analyzetoolallocator.h	Wed Oct 13 16:17:58 2010 +0300
@@ -24,9 +24,9 @@
 #include "codeblock.h"
 #include "threadstack.h"
 #include "analyzetoolmemoryallocator.h"
+#include <analyzetool/atstorageserverclnt.h>
 #include <analyzetool/analyzetool.h>
 #include <analyzetool/atcommon.h>
-#include "analyzetoolfilelog.h"
 
 // CLASS DECLARATION
 
@@ -42,24 +42,29 @@
         /**
         * C++ default constructor.
         * @param aNotFirst Is this first thread using this heap
+        * @param aStorageServer A reference to the 
+        *                       <code>RATStorageServer</code> which is 
+        *                       used to store kernel events
         * @param aCodeblocks A reference to array of code segments
         * @param aMutex A reference to mutex for schedule access to the 
         *                   shared resources
         * @param aProcessId A reference to the observed process id
         * @param aAnalyzeTool Reference to device driver
-        * @param aLogOption The logging option
+        * @param aStorageServerOpen Variable to check if Storage server is connected
+        * @param aLogOption The logging option for storage server
         * @param aAllocCallStackSize Max number of stored callstack items when memory allocated
         * @param aFreeCallStackSize Max number of stored callstack items when memory freed
         */
         RAnalyzeToolAllocator( TBool aNotFirst,
+                               RATStorageServer& aStorageServer, 
                                RArray<TCodeblock>& aCodeblocks, 
                                RMutex& aMutex, 
                                TUint aProcessId,
                                RAnalyzeTool& aAnalyzeTool,
+                               TBool aStorageServerOpen,
                                TUint32 aLogOption,
                                TUint32 aAllocCallStackSize,
-                               TUint32 aFreeCallStackSize,
-                               RATFileLog& iLogFile );
+                               TUint32 aFreeCallStackSize );
         /**
         * Destructor.
         */                     
@@ -197,6 +202,9 @@
 
     private: 
     
+        /* Handle to the storage server*/
+        RATStorageServer& iStorageServer;
+
         /* A reference to codeblocks of the observed process */            
         RArray<TCodeblock>& iCodeblocks;
 
@@ -220,6 +228,9 @@
 
         RAnalyzeTool& iAnalyzeTool;
 
+        /* A flag for indicating that the RATStorageServer is open */
+        TBool iStorageServerOpen;
+
         /* Log option */
         TUint32 iLogOption;
         
@@ -229,9 +240,6 @@
         /* Max items on stored call stack when memory freed */
         TUint32 iFreeMaxCallStack;
         
-        /* Binary log file */
-        RATFileLog& iLogFile;
-        
     };
 
 #endif // ANALYZETOOLALLOCATOR_H
--- a/analyzetool/dynamicmemoryhook/inc/analyzetooleventhandler.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/inc/analyzetooleventhandler.h	Wed Oct 13 16:17:58 2010 +0300
@@ -21,10 +21,9 @@
 
 // INCLUDES
 #include <e32cmn.h>
-#include <e32base.h>
 #include "codeblock.h"
+#include <analyzetool/atstorageserverclnt.h>
 #include <analyzetool/analyzetool.h>
-#include "analyzetoolfilelog.h"
 
 // FORWARD DECLARATIONS
 class MAnalyzeToolEventhandlerNotifier;
@@ -44,6 +43,9 @@
         * @param aAnalyzeTool A reference to the <code>RAnalyzeTool</code> 
                  which is used to observe kernel events 
         * @param aCodeblocks A reference to array of code segments
+        * @param aStorageServer A reference to the 
+        *                       <code>RATStorageServer</code> which is 
+        *                       used to store kernel events
         * @param aProcessId A reference to the observed process id
         * @param aMutex A reference to mutex to schedule access to the 
         *                   shared resources
@@ -52,12 +54,12 @@
         * @param aLogOption Current used log option on allocator.
         */
         CLibraryEventHandler( RAnalyzeTool& aAnalyzeTool, 
-                RArray<TCodeblock>& aCodeblocks,
+                RArray<TCodeblock>& aCodeblocks, 
+                RATStorageServer& aStorageServer, 
                 TUint aProcessId,
                 RMutex& aMutex,
                 MAnalyzeToolEventhandlerNotifier& aNotifier,
-                TUint32 aLogOption,
-                RATFileLog& iLogFile );
+                TUint32 aLogOption );
 
         /**
         * Destructor.
@@ -93,6 +95,9 @@
         /* A reference to codeblocks of the observed process */
         RArray<TCodeblock>& iCodeblocks;
 
+        /* Handle to the storage server*/
+        RATStorageServer& iStorageServer;
+
         /* The observered process id */ 
         TUint iProcessId;
 
@@ -110,10 +115,6 @@
 
         /* Current used log option */
         TUint32 iLogOption;
-        
-        // TODO comment
-		/* */
-		RATFileLog& iLogFile;
     };
 
 #endif // ANALYZETOOLEVENTHANDLER_H
--- a/analyzetool/dynamicmemoryhook/inc/analyzetoolfastlog.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/inc/analyzetoolfastlog.h	Wed Oct 13 16:17:58 2010 +0300
@@ -36,9 +36,7 @@
 */
 GLREF_C TInt ATFastLogProcessStarted( const TDesC8& aProcessName,
                                  TUint aProcessId,
-                                 TUint32 aIsDebug,
-                                 const TDesC8& aAtoolVersion,
-                                 const TDesC8& aApiVersion );
+                                 TUint32 aIsDebug );
 
 /**
  * TBD 
@@ -80,60 +78,19 @@
  * @param aMemAddress The memory location where memory has been allocated.
  * @param aCallstack An array including the current call stack.
  * @param aSize The size of the newly allocated memory chunk.
- * @param aThreadId ID of the thread
  * @return KErrNone.
 */
 GLREF_C TInt ATFastLogMemoryAllocated( TUint aProcessId, TUint32 aMemAddress,
                                   TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
-                                  TInt aSize,  TUint aThreadId  );
+                                  TInt aSize );
         
 /**
  * TBD
  * @param aProcessId The ID number of the process ended.
  * @param aMemAddress The memory location where memory has been deallocated.
  * @param aFreeCallstack An array including the current call stack.
- * @param aThreadId ID of the thread
  * @return KErrNone.
 */
 GLREF_C TInt ATFastLogMemoryFreed( TUint aProcessId, TUint32 aMemAddress, 
-                              TFixedArray<TUint32, KATMaxFreeCallstackLength>& aFreeCallstack,
-                              TUint aThreadId );
-
-/**
- * TBD
- * @param aProcessId The ID number of the process ended.
- * @param aMemAddressFree The memory location where memory has been deallocated.
- * @param aMemAddressAlloc The memory location where memory has been allocated.
- * @param aFreeCallstack An array including the current call stack.
- * @param aThreadId ID of the thread
- * @return KErrNone.
-*/
-GLREF_C TInt ATFastLogMemoryReallocated( TUint aProcessId, TUint32 aMemAddressFree,  TUint32 aMemAddressAlloc,
-                                  TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
-                                  TInt aSize,  TUint aThreadId  );
-
-/**
- * TBD
- * @param aProcessId The ID number of the process ended.
- * @param aThreadID An ID of the new thread started
- * @return KErrNone.
-*/
-GLREF_C TInt ATFastLogThreadStarted( TUint aProcessId, TUint aThreadId );
-
-/**
- * TBD
- * @param aProcessId The ID number of the process ended.
- * @param aThreadID An ID of the thread ended
- * @return KErrNone.
-*/
-GLREF_C TInt ATFastLogThreadEnded( TUint aProcessId, TUint64 aThreadId );
-
-/**
- * TBD
- * @param aS60Version S60 version
- * @aChecksum ROM checksum
- * @return KErrNone.
-*/
-TInt ATFastLogDeviceInfo( const TDesC8& aS60Version, const TDesC8& aChecksum);
-
+                              TFixedArray<TUint32, KATMaxFreeCallstackLength>& aFreeCallstack );
 #endif
--- a/analyzetool/dynamicmemoryhook/inc/analyzetoolfilelog.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,223 +0,0 @@
-/*
-* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Declaration of the class TATDriveInfo.
-*
-*/
-
-#ifndef ANALYZETOOLFILELOG_H_
-#define ANALYZETOOLFILELOG_H_
-
-#include <e32base.h>
-#include <s32file.h> //RFileWriteStream 
-#include <f32file.h> //RFs
-#include <analyzetool/atcommon.h>
-
-class RATFileLog : public CBase
-	{
-    enum EMessageType{
-        EFileVersion = 0,
-        		EProcessStart,
-                EProcessEnd,
-                EThreadStart,
-                EThreadEnd,
-                EDllLoad,
-                EDllUnload,
-                EAllocH,
-                EAllocF,
-                EFreeH,
-                EFreeF,
-                EReallocH,
-                EReallocF,
-                ETestStart,
-                ETestEnd,
-                EHandleLeak,
-                EDeviceInfo,
-                EError  
-	    };
-    
-public:
-    
-    RATFileLog();
-	virtual ~RATFileLog();
-
-/**
- * TBD
- * @return KErrNone.
-*/
-	
-TInt ATFileLogVersion();
-
-/**
- * TBD
- * @param aProcessName The name of the new process started. The length of this
- *   descriptor must not be greater than KMaxProcessName.
- * @param aIsDebug Determines whether a binary is UDEB or UREL
- * @return KErrNone.
-*/
-
-TInt ATFileLogProcessStarted( const TDesC8& aProcessName,
-                                      TUint aProcessId,
-                                      TUint32 aIsDebug,
-                                      const TDesC8& aAtoolVersion,
-                                      const TDesC8& aApiVersion );
-
-/**
- * TBD 
- * @param aProcessId The ID number of the process ended.
- * @param aHandleLeakCount Number of handles open.
- * @return KErrNone, if successful; otherwise one of the other
- *   system-wide error codes.
- */
-TInt ATFileLogProcessEnded( TUint aHandleLeakCount );
-
-/**
- * TBD
- * @param aDllName The name of the new DLL loaded. The length of this descriptor
- *   must not be greater than KMaxLibraryName.
- * @param aStartAddress The start address of the DLL loaded.
- * @param aEndAddress The end address of the DLL loaded.
- * @return KErrNone.
-*/
-TInt ATFileLogDllLoaded( const TDesC8& aDllName, TUint32 aStartAddress,
-                                TUint32 aEndAddress );
-
-/**
- * TBD
- * @param aDllName The name of the DLL to be unloaded. The length of this
- *   descriptor must not be greater than KMaxLibraryName.
- * @param aStartAddress The start address of the DLL to be unloaded.
- * @param aEndAddress The end address of the DLL to be unloaded.
- * @return KErrNone.
-*/
-TInt ATFileLogDllUnloaded( const TDesC8& aDllName, TUint32 aStartAddress,
-                                       TUint32 aEndAddress );
-
-/**
- * TBD
- * @param aMemAddress The memory location where memory has been allocated.
- * @param aCallstack An array including the current call stack.
- * @param aSize The size of the newly allocated memory chunk.
- * @param aThreadId ID of the thread
- * @return KErrNone.
-*/
-TInt ATFileLogMemoryAllocated( TUint32 aMemAddress,
-                                  TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
-                                  TInt aSize,  TUint aThreadId  );
-        
-/**
- * TBD
- * @param aMemAddress The memory location where memory has been deallocated.
- * @param aFreeCallstack An array including the current call stack.
- * @param aThreadId ID of the thread
- * @return KErrNone.
-*/
-TInt ATFileLogMemoryFreed( TUint32 aMemAddress, 
-		                      TFixedArray<TUint32, KATMaxFreeCallstackLength>& aFreeCallstack,
-                              TUint aThreadId );
-
-/**
- * TBD
- * @param aMemAddressFree The memory location where memory has been deallocated.
- * @param aMemAddressAlloc The memory location where memory has been allocated.
- * @param aFreeCallstack An array including the current call stack.
- * @param aThreadId ID of the thread
- * @return KErrNone.
-*/
-TInt ATFileLogMemoryReallocated( TUint32 aMemAddressFree,  TUint32 aMemAddressAlloc,
-                                  TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
-                                  TInt aSize,  TUint aThreadId  );
-
-/**
- * TBD
- * @param aThreadID An ID of the new thread started
- * @return KErrNone.
-*/
-TInt ATFileLogThreadStarted( TUint aThreadId );
-
-/**
- * TBD
- * @param aThreadID An ID of the thread ended
- * @return KErrNone.
-*/
-TInt ATFileLogThreadEnded( TUint64 aThreadId );
-
-/**
- * TBD
- * @param aS60Version S60 version
- * @aChecksum ROM checksum
- * @return KErrNone.
-*/
-TInt ATFileLogDeviceInfo( const TDesC8& aS60Version, const TDesC8& aChecksum);
-
-/**
-* Opens a file server session and a file with the name specified.
-* @param aFileName The name of the file into which to log.
-* @param aProcessName Current process name.
-* @return KErrNone, if successful; otherwise one of the other system wide
-*   error codes.
-*/
-TInt OpenFsAndFile( const TDesC& aFileName, const TDesC& aFilePath, const TDesC8& aProcessName );
-
-/**
-* Method is used to parse file name extension.
-* @param aFileName The name of the file into which to log.
-* @param aExtension Parsed file extension. 
-*/
-void ParseExtension( TDes& aFileName, TDes& aExtension );
-
-/**
-* Called internally when need generate new file name.
-* @param aFileName The name of the file into which to log.
-* @param aProcessName Current process name.
-*/
-void GenerateNewFileName( TDes& aFileName, const TDesC8& aProcessName );
-
-/**
-* Method is used to check that file exists and is valid.
-* @param aFileName The name of the file into which to log.
-*/
-void CheckIfFileAlreadyExist( const TDes& aFileName );
-
-/**
-* Closes the handles to the file server session and to the file (if currently open).
-*/
-void CloseFsAndFile();
-
-// Local time function.
-TInt64 CurrentTime();
-
-
-
-/**
-* A variable telling the number of microseconds from January 1st, 0 AD
-* nominal Gregorian to January 1st, 1970 AD nominal Gregorian. 
-*/
-TInt64 iMicroSecondsAt1970;
-
-/** A handle to a file server */
-RFs iFileServer;
-
-/** A handle to a file write stream */
-RFileWriteStream iFile;
-
-/** The logging file of this process */
-TBuf8<KMaxFileName> iLogFile;
-
-/** A member variable for storing results of server function calls. */ 
-TInt iError;
-
-
-};
-
-#endif /* ANALYZETOOLFILELOG_H_ */
--- a/analyzetool/dynamicmemoryhook/inc/analyzetoolmainallocator.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/inc/analyzetoolmainallocator.h	Wed Oct 13 16:17:58 2010 +0300
@@ -22,11 +22,11 @@
 // INCLUDES
 #include <u32std.h>
 #include "codeblock.h"
+#include <analyzetool/atstorageserverclnt.h>
 #include <analyzetool/analyzetool.h>
 #include <analyzetool/atcommon.h>
 #include "analyzetoolmemoryallocator.h"
 #include "analyzetooleventhandlernotifier.h"
-#include "analyzetoolfilelog.h"
 
 // FORWARD DECLARATIONS
 class CLibraryEventHandler;
@@ -47,21 +47,16 @@
         * C++ default constructor.
         * @param aNotFirst Is this first thread using this heap
         * @param aFileName The name of the log file
-        * @param aLogOption The logging option
+        * @param aLogOption The logging option for storage server
         * @param aIsDebug Determines whether a binary is UDEB or UREL
         * @param aAllocCallStackSize Max number of stored callstack items when memory allocated
         * @param aFreeCallStackSize Max number of stored callstack items when memory freed
-        * @param aAtoolVersion Version of atool
-        * @param aApiVersion Version of api
         */
         RAnalyzeToolMainAllocator( TBool aNotFirst,
-                const TFileName& aFileName,
-                const TPath& aFilePath,
+                const TFileName aFileName,
                 TUint32 aLogOption, TUint32 aIsDebug,
                 TUint32 aAllocCallStackSize,
-                TUint32 aFreeCallStackSize,
-                const TDesC8& aAtoolVersion,
-                const TDesC8& aApiVersion );
+                TUint32 aFreeCallStackSize );
 
         /**
         * Destructor.
@@ -196,7 +191,13 @@
         void ShareHeap();
 
     public: // inlines
-            
+    
+        /**
+        * Acquires the open RATStorageServer handle
+        * @return RATStorageServer& The open RATStorageServer handle
+        */
+        inline RATStorageServer& StorageServer();
+        
         /**
         * Acquires the codeblocks of the process
         * @return RArray<TCodeblock>& The process codeblocks
@@ -220,6 +221,12 @@
 		* @return RAnalyzeTool A reference to logical channel
 		*/
         inline RAnalyzeTool& AnalyzeTool();
+ 
+         /**
+        * Acquires information if storage server is open
+        * @return TBool iStorageServerOpen
+        */
+        inline TBool StorageServerOpen();
                 
         /**
         * Acquires the log option type 
@@ -238,23 +245,17 @@
          * @return TUint32 iFreeMaxCallStack
          */
         inline TUint32 FreeMaxCallStack();
-        
-        /**
-         * Acquires handle to lig file
-         * @return RATFileLog iLogFile
-         */
-        inline RATFileLog& LogFile();
 
     private: // private functions
 
         /**
         * Log the process initial information
         * @param aFileName The name of the log file
-        * @param aLogOption The logging option
+        * @param aLogOption The logging option for storage serve
         * @param aIsDebug Determines whether a binary is UDEB or UREL
         */
-        void LogProcessInformation( const TFileName& aFileName,  const TPath& aFilePath,  TUint32 aLogOption,
-        		TUint32 aIsDebug, const TDesC8& aAtoolVersion, const TDesC8& aApiVersion );
+        void LogProcessInformation( const TFileName aFileName, TUint32 aLogOption,
+                                                                TUint32 aIsDebug );
 
         /**
         * Find the current thread which is using the heap
@@ -267,14 +268,11 @@
         * Installs the eventhandler, if possible
         */
         void InstallEventHandler();
-        
-        /**
-        * Logs version of ATApp, ATApi, S60 version and ROM checksum 
-        * at the startup of hooked application
-        */
-        void LogDeviceInfo();
 
     private: // member variables
+            
+        /* Handle to the RATStorageServer */
+        RATStorageServer iStorageServer;
 
         /* Handle to the RAnalyzeTool */		
         RAnalyzeTool iAnalyzeTool;           
@@ -305,6 +303,9 @@
                 
         /* Array of threads using this heap */
         RArray<TThreadStack> iThreadArray;
+
+        /* A flag for indicating that the RATStorageServer is open */
+        TBool iStorageServerOpen;
         
         /* Log option */
         TUint32 iLogOption;
@@ -318,10 +319,6 @@
         /* Max items on stored call stack when memory freed */
         TUint32 iFreeMaxCallStack;
         
-        /* Binary log file */
-        RATFileLog iLogFile;
-       
-        
     };
 
 // INLINES
--- a/analyzetool/dynamicmemoryhook/inc/analyzetoolmainallocator.inl	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/inc/analyzetoolmainallocator.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -17,6 +17,16 @@
 
 
 #include "analyzetoolmemoryallocator.h"
+
+// -----------------------------------------------------------------------------
+// RAnalyzeToolMainAllocator::StorageServer()
+// Acquires reference to open RATStorageServer
+// -----------------------------------------------------------------------------
+//
+inline RATStorageServer& RAnalyzeToolMainAllocator::StorageServer()
+    {
+    return iStorageServer;
+    }
   
 // -----------------------------------------------------------------------------
 // RAnalyzeToolMainAllocator::Codeblocks()
@@ -59,6 +69,16 @@
     }
 
 // -----------------------------------------------------------------------------
+// RAnalyzeToolMainAllocator::StorageServerOpen()
+// Acquires the iStorageServerOpen variable
+// -----------------------------------------------------------------------------
+//
+inline TBool RAnalyzeToolMainAllocator::StorageServerOpen()
+    {
+    return iStorageServerOpen;
+    }
+
+// -----------------------------------------------------------------------------
 // RAnalyzeToolMainAllocator::LogOption()
 // Acquires the iLogOption variable
 // -----------------------------------------------------------------------------
@@ -86,14 +106,4 @@
     {
     return iFreeMaxCallStack;
     }
-
-// -----------------------------------------------------------------------------
-// RAnalyzeToolMainAllocator::LogFile()
-// Acquires the iLogFile variable
-// -----------------------------------------------------------------------------
-//
-inline RATFileLog& RAnalyzeToolMainAllocator::LogFile()
-	{
-	return iLogFile;
-	}
 // End of File
--- a/analyzetool/dynamicmemoryhook/inc/analyzetoolpanics.pan	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/inc/analyzetoolpanics.pan	Wed Oct 13 16:17:58 2010 +0300
@@ -30,6 +30,8 @@
     ECantLoadDevice,
     ECantAppendToTheArray,
     ECantFindRightThread,
+    ECantConnectStorageServer,
+    ECantShareStorageServer,
     ECantCreateMutex,
     ECantLoadDeviceDriver,
     ECantConnectDeviceDriver
--- a/analyzetool/dynamicmemoryhook/inc/atdriveinfo.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,75 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Declaration of the class TATDriveInfo.
-*
-*/
-
-
-
-#ifndef ATDRIVEINFO_H
-#define ATDRIVEINFO_H
-
-#include <f32file.h>
-
-// The path of the storage file
-#ifdef __WINS__
-_LIT( KATDataFilePath, ":\\logs\\analyzetool\\" );
-#else
-_LIT( KATDataFilePath, ":\\analyzetool\\" );
-_LIT( KATDataFilePath2, ":\\data\\analyzetool\\" );
-#endif
-
-/**
-*  Check what drives exists and creates file full path.
-*/
-class TATDriveInfo
-    {    
-    public: // Constructors
-        
-        /**
-        * C++ default constructor.
-        */
-        TATDriveInfo();
-
-    public: // New functions
-
-        /**
-        * Create the file full path.
-        * @param aPath Full path.
-        * @param aFileName Filename.
-        * @param aFs A handle to a file server.
-        * @return KErrNone or KErrAlreadyExists, if successful; 
-        *   Otherwise one of the other system wide error codes.
-        */
-        static TInt CreatePath( TDes& aPath, const TDesC& aFileName, const TDesC& aFilePath, RFs& aFs );   
-    
-    private: // New functions
-    
-        /**
-        * Get the available drive character.
-        * @param aDrive The drive letter.
-        * @param aDriveNumber The drive number.
-        * @param aFs A handle to a file server.
-        * @param aDriveType Drive type.
-        * @return KErrNone, if successful; otherwise KErrNotFound
-        */
-        static TInt GetDrive( TChar& aDrive, TInt& aDriveNumber, 
-                RFs& aFs, const TUint aDriveType );  
-        
-    };
-
-#endif // ATDRIVEINFO_H
-
-// End of File
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/dynamicmemoryhook/inc/customuser.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,207 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the class CustomUser containing overloaded User static functions.
+*
+*/
+
+
+#ifndef CUSTOMUSER_H
+#define CUSTOMUSER_H
+
+// INCLUDES
+#include <u32std.h>
+#include <e32svr.h>
+// CONSTANTS
+const TInt KATVersionLength = 20;
+const TInt KATDefaultLogOption = 0;
+const TInt KATDefaultDebug = 1;
+const TInt KATDefaultAllocCallStackSize = 40;
+const TInt KATDefaultFreeCallStackSize = 0;
+    
+// TYPEDEFS
+typedef TBuf<KATVersionLength> TATVersion;
+
+// Argument list for SetupThreadHeap function parameters. (currently not used)
+// When needed, update the argument type directly inside _LIT macro.
+_LIT( KATArgumentList, "%i%i" ); //etc. 
+
+// CLASS DECLARATION
+
+/**
+*  Class which overloads the User functions and provides access to 
+*  the overloaded functions  
+*/
+class CustomUser
+    {
+    public: // Enumerations
+        enum TATOptions
+            {
+            /** Acquiring the log filename */
+            ELogFileName = 1,   
+            /** Acquiring the version number */
+            EVersion,
+            /** Acquiring logging option */
+            ELogOption,
+            /** Acquiring UDEB/UREL information */  
+            EDebug,
+            /** Acquiring max allocation call stack size */
+            EAllocCallStackSize,
+            /** Acquiring max free call stack size */
+            EFreeCallStackSize
+            };
+        
+    public:
+
+        /**
+        * Overloaded version of User::Exit()
+        * Terminates the current thread, specifying a reason. All child 
+        * threads are terminated and all resources are cleaned up.If the 
+        * current thread is the main thread in a process, the process is
+        * also terminated.
+        * @param aReason The reason code.
+        */
+        IMPORT_C static void Exit( TInt aReason );
+
+        /**
+        * Overloaded version of User::Panic()
+        * Panics the current thread, specifying a category name and panic
+        * number. Keep the length of the category name small;
+        * a length of 16 is ideal.
+        * @param aCategory A reference to the descriptor containing the text 
+        * that defines the category for this panic.
+        * @param aReason The panic number. 
+        */   
+        IMPORT_C static void Panic( const TDesC& aCategory, TInt aReason );
+
+        /**
+        * Overloaded version of UserHeap::SetupThreadHeap()
+        * Setups the threads heap.
+        * @param aNotFirst Is this first thread using specified heap
+        * @param aInfo Specifies the thread heap properties
+        * @param aFileName The name of the log file
+        * @param aLogOption The logging option for storage server
+        * @param aIsDebug Determines whether a binary is UDEB or UREL
+        * @param aVersion Atool version number
+        * @param aAllocCallStackSize Max number of stored callstack items when memory allocated
+        * @param aFreeCallStackSize Max number of stored callstack items when memory freed
+        * @param aFmt A descriptor containing the format string
+        * @return TInt KErrNone, if the insertion is successful, otherwise 
+        * one of the system wide error codes.
+        */   
+        IMPORT_C static TInt SetupThreadHeap( 
+                             TBool aNotFirst, 
+                             SStdEpocThreadCreateInfo& aInfo,
+                             const TFileName& aFileName,
+                             TUint32 aLogOption, TUint32 aIsDebug,
+                             const TATVersion& aVersion,
+                             TUint32 aAllocCallStackSize,
+                             TUint32 aFreeCallStackSize,
+                             TRefByValue<const TDesC> aFmt, ... );
+                             
+        /**
+        * Overloaded version of UserHeap::SetCritical()
+        * Sets up or changes the effect that termination of the current 
+        * thread has, either on its owning process, or on the whole system.
+        * The precise effect of thread termination is defined by the following
+        *  specific values of the TCritical enum:
+        * ENotCritical
+        * EProcessCritical
+        * EProcessPermanent
+        * ESystemCritical
+        * ESystemPermanent
+        * Notes: The enum value EAllThreadsCritical cannot be set using this
+        * function. It is associated with a process, not a thread, and, if 
+        * appropriate, should be set using User::SetProcessCritical().
+        * The states associated with ENotCritical, EProcessCritical, 
+        * EProcessPermanent, ESystemCritical and ESystemPermanent are all 
+        * mutually exclusive, i.e. the thread can only be in one of these 
+        * states at any one time.
+        * @param aCritical The state to be set.
+        * @return TInt KErrNone, if successful; KErrArgument, if 
+        * EAllThreadsCritical is passed - this is a state associated with a 
+        * process, and you use User::SetProcessCritical() to set it.
+        */ 
+        IMPORT_C static TInt SetCritical( User::TCritical aCritical );
+        
+        /**
+        * Overloaded version of UserHeap::SetCritical()
+        * Sets up or changes the effect that termination of subsequently 
+        * created threads will have, either on the owning process, 
+        * or on the whole system. It is important to note that we are not
+        * referring to threads that have already been created, but threads
+        * that will be created subsequent to a call to this function.
+        * The precise effect of thread termination is defined by the following
+        * specific values of the TCritical enum:
+        * ENotCritical
+        * EAllThreadsCritical
+        * ESystemCritical
+        * ESystemPermanent
+        * Notes:
+        * The enum values EProcessCritical and EProcessPermanent cannot be set
+        * using this function. They are states associated with a thread, not a
+        * process, and, if appropriate, should be set using 
+        * User::SetCritical(). The states associated with ENotCritical, 
+        * EAllThreadsCritical, ESystemCritical and ESystemPermanent are all 
+        * mutually exclusive, i.e. the process can only be in one of these 
+        * states at any one time.
+        * @param aCritical The state to be set.
+        * @return TInt KErrNone, if successful; KErrArgument, if either 
+        * EProcessCritical or EProcessPermanent is passed - these are states
+        * associated with a thread, and you use User::SetCritical() 
+        * to set them.
+        */ 
+        IMPORT_C static TInt SetProcessCritical( User::TCritical aCritical );
+                
+    private: // Private functions
+        
+        /**
+        * Factory function for creating RAllocator instances.
+        * @param aNotFirst Is this first thread using specified heap
+        * @param aLogOption The logging option for storage server
+        * @param aFileName The name of the logging file
+        * @param aIsDebug Determines whether a binary is UDEB or UREL
+        * @param aAllocCallStackSize Max number of stored callstack items when memory allocated
+        * @param aFreecallStackSize Max number of stored callstack items when memory freed
+        * @return RAllocator& A reference to created allocator
+        */  
+        static RAllocator& InstallAllocator( TBool aNotFirst,
+                                             const TFileName& aFileName,
+                                             TUint32 aLogOption, TUint32 aIsDebug,
+                                             TUint32 aAllocCallStackSize,
+                                             TUint32 aFreeCallStackSize );
+        
+		/**
+		* Check atool version
+		* @param aVersion - Atool version number.
+		* @param aToolVersion The atool version number
+		* @return KErrNone if correct version found, otherwise one of the system wide 
+		* error codes.
+		*/
+        static TInt CheckVersion( const TATVersion& aVersion, TDes& aToolVersion ); 
+        
+		/**
+		* Function for showing incorrect version information (file or debug channel).
+		* @param aLogOption The logging option
+		* @param aFileName The name of the log file
+		* @param aToolVersion The atool version number
+		*/
+        static void ReportIncorrectVersion( const TUint32 aLogOption, 
+											const TFileName& aFileName,
+											const TDes& aToolVersion );
+        
+    };
+
+#endif // CUSTOMUSER_H
+
+// End of File
--- a/analyzetool/dynamicmemoryhook/src/analyzetoolallocator.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/src/analyzetoolallocator.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -37,25 +37,27 @@
 // might leave.
 // -----------------------------------------------------------------------------
 //
-RAnalyzeToolAllocator::RAnalyzeToolAllocator( TBool aNotFirst,
+RAnalyzeToolAllocator::RAnalyzeToolAllocator( TBool aNotFirst, 
+                                              RATStorageServer& aStorageServer, 
                                               RArray<TCodeblock>& aCodeblocks, 
                                               RMutex& aMutex,
                                               TUint aProcessId,
                                               RAnalyzeTool& aAnalyzeTool,
+                                              TBool aStorageServerOpen,
                                               TUint32 aLogOption,
                                               TUint32 aAllocCallStackSize,
-                                              TUint32 aFreeCallStackSize,
-                                              RATFileLog& aLogFile ) :
+                                              TUint32 aFreeCallStackSize ) :
     RAnalyzeToolMemoryAllocator( aNotFirst ),
+    iStorageServer( aStorageServer ), 
     iCodeblocks( aCodeblocks ), 
     iMutex( aMutex ),
     iProcessId( aProcessId ),
     iThreadArray( KATMaxCallstackLength ),
     iAnalyzeTool( aAnalyzeTool ),
+    iStorageServerOpen( aStorageServerOpen ),
     iLogOption( aLogOption ),
     iAllocMaxCallStack( aAllocCallStackSize ),
-    iFreeMaxCallStack( aFreeCallStackSize ),
-    iLogFile ( aLogFile )
+    iFreeMaxCallStack( aFreeCallStackSize )
     {
     LOGSTR1( "ATMH RAnalyzeToolAllocator::RAnalyzeToolAllocator()" );
     
@@ -69,16 +71,6 @@
         LOGSTR2( "ATMH Thread stack size:    %x", params().iStackSize );
         error = iThreadArray.Append( TThreadStack( RThread().Id(), 
                              params().iStackAddress + params().iStackSize ) );
-
-        if ( iLogOption == EATLogToTraceFast )
-        	{
-            // log thread added
-            ATFastLogThreadStarted( aProcessId, RThread().Id().operator TUint() ); 
-        	}
-        else if ( iLogOption == EATLogToFile )
-        	{
-            iLogFile.ATFileLogThreadStarted( RThread().Id().operator TUint() );
-        	}
         }
     
     __ASSERT_ALWAYS( KErrNone == error, AssertPanic( ECantAppendToTheArray ) ); 
@@ -93,20 +85,6 @@
     {
     LOGSTR1( "ATMH RAnalyzeToolAllocator::~RAnalyzeToolAllocator()" );
     
-    for( TInt i=0; i<iThreadArray.Count(); i++)
-    	{
-        // log thread removed
-        if ( iLogOption == EATLogToTraceFast )
-        	{
-            ATFastLogThreadEnded( RProcess().Id().operator TUint(), RThread().Id().operator TUint() ); 
-            }
-        else if ( iLogOption == EATLogToFile )
-        	{
-            iLogFile.ATFileLogThreadEnded( RThread().Id().operator TUint() );
-        	}
-         }
-    
-    
     // Close the thread array 
     iThreadArray.Close();
     }
@@ -156,67 +134,88 @@
     // Acquire the mutex
     iMutex.Wait();
     
-    // get thread ID
-    TUint threadId = RThread().Id();
     // Alloc memory from the original allocator
     TAny* p = iAllocator->Alloc( aSize );
     
     LOGSTR3( "ATMH RAnalyzeToolAllocator::Alloc() - aSize: %i, address: %x", 
              aSize,  (TUint32) p );
     
-	// Reset the callstack
-	iCallStack.Reset();
-
-	// Find the current thread callstack start address
-	TUint32 stackstart( 0 );
-	TBool found( FindCurrentThreadStack( stackstart ) );
-	LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
-	
-	TUint32 _sp;
-	__asm
-		{
-		mov [_sp], esp
-		}
-	
-	// Get codeblocks count
-	TInt blocksCount( iCodeblocks.Count() );
-	TInt error( KErrNone );
-	TUint arrayCounter = 0;
-	
-	for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-		{
-		TUint32 addr = (TUint32) *( (TUint32*) i );
-		if ( ! IsAddressLoadedCode( addr ) )
-			continue;
-		for ( TInt j = 0; j < blocksCount; j++ )
-			{
-			if ( iCodeblocks[j].CheckAddress( addr ) )
-				{
-				// To avoid recursive call to ReAlloc specifying granularity
-				// Add address to the callstack
-				iCallStack[arrayCounter] = ( addr );
-				arrayCounter++;
-				break;
-				}
-			}
-		if ( arrayCounter == KATMaxCallstackLength ||
-			 arrayCounter == iAllocMaxCallStack )
-			{
-			LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
-			break;
-			}
-		}
-	// Log the memory allocation information
-	if ( iLogOption == EATLogToTraceFast )
-		{
-		// Using fast mode.
-		ATFastLogMemoryAllocated( iProcessId, (TUint32) p, iCallStack, aSize, threadId );
-		}
-	else if ( iLogOption == EATLogToFile )
-		{
-		iLogFile.ATFileLogMemoryAllocated( (TUint32) p, iCallStack, aSize, threadId );
-		}
-   
+    // Don't collect call stack and log data
+    // if storage server not open or logging mode not fast.
+    if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+        {
+        // Reset the callstack
+        iCallStack.Reset();
+    
+        // Find the current thread callstack start address
+        TUint32 stackstart( 0 );
+        TBool found( FindCurrentThreadStack( stackstart ) );
+        LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
+        
+        TUint32 _sp;
+        __asm
+            {
+            mov [_sp], esp
+            }
+        
+        // Get codeblocks count
+        TInt blocksCount( iCodeblocks.Count() );
+        TInt error( KErrNone );
+        TUint arrayCounter = 0;
+        
+        for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+            {
+            TUint32 addr = (TUint32) *( (TUint32*) i );
+            if ( ! IsAddressLoadedCode( addr ) )
+                continue;
+            for ( TInt j = 0; j < blocksCount; j++ )
+                {
+                if ( iCodeblocks[j].CheckAddress( addr ) )
+                    {
+                    // To avoid recursive call to ReAlloc specifying granularity
+                    // Add address to the callstack
+                    iCallStack[arrayCounter] = ( addr );
+                    arrayCounter++;
+                    break;
+                    }
+                }
+            if ( arrayCounter == KATMaxCallstackLength ||
+                 arrayCounter == iAllocMaxCallStack )
+                {
+                LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
+                break;
+                }
+            }
+        // Log the memory allocation information
+        if ( iLogOption == EATLogToTraceFast )
+            {
+            // Using fast mode.
+            ATFastLogMemoryAllocated( iProcessId, (TUint32) p, iCallStack, aSize );
+            }
+        else
+            {
+            // Using storage server.
+            error = iStorageServer.LogMemoryAllocated( (TUint32) p,
+                                                       iCallStack,
+                                                       aSize );
+            if ( KErrNone != error )
+                {
+                LOGSTR2( "ATMH LogMemoryAllocated error %i", error );
+                switch ( error )
+                    {
+                    case KErrNoMemory:
+                    LOGSTR1( "ATMH RAnalyzeToolMainAllocator::Alloc() - KErrNoMemory case"  );
+                    if ( iStorageServerOpen )
+                        {
+                        iStorageServerOpen = EFalse;
+                        LOGSTR1( "ATMH RAnalyzeToolMainAllocator::Alloc() - close iStorageServer"  );
+                        iStorageServer.Close();
+                        }
+                    break;
+                    }
+                }
+            }
+        }
     // Release the mutex
     iMutex.Signal();
     
@@ -236,59 +235,79 @@
     // Acquire the mutex
     iMutex.Wait();
     
-    // get thread ID
-    TUint threadId = RThread().Id();
-        
     // Alloc memory from the original allocator
     TAny* p = iAllocator->Alloc( aSize );
+    
+    // Don't collect call stack and log data
+    // if storage server not open or logging mode not fast.
+    if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+        {
+        // Reset the callstack
+        iCallStack.Reset(); 
         
-
-	// Reset the callstack
-	iCallStack.Reset(); 
-	
-	// Find the current thread callstack start address
-	TUint32 stackstart( 0 );
-	TBool found( FindCurrentThreadStack( stackstart ) );
-	LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
-	
-	// Get codeblocks count
-	TInt blocksCount( iCodeblocks.Count() );
-	TUint arrayCounter = 0;
-	
-	for ( TUint32 i = __current_sp(); i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-		{
-		TUint32 addr = (TUint32) *( (TUint32*) i );
-		if ( ! IsAddressLoadedCode( addr ) )
-			continue;
-		for ( TInt j = 0; j < blocksCount; j++ )
-			{
-			if ( iCodeblocks[j].CheckAddress( addr ) )
-				{
-				// To avoid recursive call to ReAlloc specifying granularity
-				// Add address to the callstack
-				iCallStack[arrayCounter] = ( addr );
-				arrayCounter++;
-				break;
-				}
-			}
-		if ( arrayCounter == KATMaxCallstackLength ||
-			 arrayCounter == iAllocMaxCallStack )
-			{
-			LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
-			break;
-			}
-		}
-	// Log the memory allocation information
-	if ( iLogOption == EATLogToTraceFast )
-		{
-		// Fast mode.
-		ATFastLogMemoryAllocated( iProcessId, (TUint32) p, iCallStack, aSize, threadId );
-		} 
-	else if ( iLogOption == EATLogToFile )
-		{
-	    iLogFile.ATFileLogMemoryAllocated( (TUint32) p, iCallStack, aSize, threadId );
-		}
-
+        // Find the current thread callstack start address
+        TUint32 stackstart( 0 );
+        TBool found( FindCurrentThreadStack( stackstart ) );
+        LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
+        
+        // Get codeblocks count
+        TInt blocksCount( iCodeblocks.Count() );
+        TInt error( KErrNone );
+        TUint arrayCounter = 0;
+        
+        for ( TUint32 i = __current_sp(); i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+            {
+            TUint32 addr = (TUint32) *( (TUint32*) i );
+            if ( ! IsAddressLoadedCode( addr ) )
+                continue;
+            for ( TInt j = 0; j < blocksCount; j++ )
+                {
+                if ( iCodeblocks[j].CheckAddress( addr ) )
+                    {
+                    // To avoid recursive call to ReAlloc specifying granularity
+                    // Add address to the callstack
+                    iCallStack[arrayCounter] = ( addr );
+                    arrayCounter++;
+                    break;
+                    }
+                }
+            if ( arrayCounter == KATMaxCallstackLength ||
+                 arrayCounter == iAllocMaxCallStack )
+                {
+                LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
+                break;
+                }
+            }
+        // Log the memory allocation information
+        if ( iLogOption == EATLogToTraceFast )
+            {
+            // Fast mode.
+            ATFastLogMemoryAllocated( iProcessId, (TUint32) p, iCallStack, aSize );
+            }
+        else
+            {
+            // Using storage server.
+            error = iStorageServer.LogMemoryAllocated( (TUint32) p, 
+                                                        iCallStack, 
+                                                        aSize );
+            if ( KErrNone != error )
+                {
+                LOGSTR2( "ATMH LogMemoryAllocated error %i", error );
+                switch ( error )
+                    {
+                    case KErrNoMemory:
+                    LOGSTR1( "ATMH RAnalyzeToolAllocator::Alloc() - KErrNoMemory case"  );
+                    if ( iStorageServerOpen )
+                        {
+                        iStorageServerOpen = EFalse;
+                        LOGSTR1( "ATMH RAnalyzeToolAllocator::Alloc() - close iStorageServer"  );
+                        iStorageServer.Close();
+                        }
+                    break;
+                    }
+                }
+            }
+        }
  
     // Release the mutex
     iMutex.Signal(); 
@@ -310,68 +329,76 @@
     // Acquire the mutex
     iMutex.Wait();
     
-    // get thread ID
-    TUint threadId = RThread().Id();
-    
-	// Reset the callstack
-	iFreeCallStack.Reset();
-	
-	if ( iFreeMaxCallStack > 0 )
-		{
-		// Find the current thread callstack start address
-		TUint32 stackstart( 0 );
-		TBool found( FindCurrentThreadStack( stackstart ) );
-		LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
-		TUint32 _sp;
-		
-		#ifdef __WINS__
-			__asm
-				{
-				mov [_sp], esp
-				}
-		#else
-			_sp = __current_sp();
-		#endif
-		
-		// Get codeblocks count
-		TInt blocksCount( iCodeblocks.Count() );
-		TUint arrayCounter = 0;
-	
-		for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-			{
-			TUint32 addr = (TUint32) *( (TUint32*) i );
-			if ( ! IsAddressLoadedCode( addr ) )
-				continue;
-			for ( TInt j = 0; j < blocksCount; j++ )
-				{
-				if ( iCodeblocks[j].CheckAddress( addr ) )
-					{
-					// To avoid recursive call to ReAlloc specifying granularity
-					// Add address to the callstack
-					iFreeCallStack[arrayCounter] = addr;
-					arrayCounter++;
-					break;
-					}
-				}
-			if ( arrayCounter == KATMaxFreeCallstackLength ||
-				 arrayCounter == iFreeMaxCallStack )
-				{
-				break;
-				}
-			}
-		LOGSTR2( "ATMH > iFreeCallStack count ( %i )", arrayCounter );
-		}
-	
-	// Log freed memory.
-	if ( iLogOption == EATLogToTraceFast )
-		{
-		// Using fast mode.
-		ATFastLogMemoryFreed( iProcessId, (TUint32) aPtr, iFreeCallStack, threadId );
-		} 
-	else if ( iLogOption == EATLogToFile )
-		{
-		iLogFile.ATFileLogMemoryFreed( (TUint32) aPtr, iFreeCallStack, threadId );
-		}
+    // Don't collect or log data if storage server not open or logging mode not fast.
+    if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+        {
+        // Reset the callstack
+        iFreeCallStack.Reset();
+        
+        // Check if trace logging mode because free call stack is not used in other log options.
+        if ( (iLogOption == EATUseDefault || iLogOption == EATLogToTrace || iLogOption == EATLogToTraceFast )
+                && iFreeMaxCallStack > 0 )
+            {
+            // Find the current thread callstack start address
+            TUint32 stackstart( 0 );
+            TBool found( FindCurrentThreadStack( stackstart ) );
+            LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
+            TUint32 _sp;
+            
+            #ifdef __WINS__
+                __asm
+                    {
+                    mov [_sp], esp
+                    }
+            #else
+                _sp = __current_sp();
+            #endif
+            
+            // Get codeblocks count
+            TInt blocksCount( iCodeblocks.Count() );
+            TUint arrayCounter = 0;
+        
+            for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+                {
+                TUint32 addr = (TUint32) *( (TUint32*) i );
+                if ( ! IsAddressLoadedCode( addr ) )
+                    continue;
+                for ( TInt j = 0; j < blocksCount; j++ )
+                    {
+                    if ( iCodeblocks[j].CheckAddress( addr ) )
+                        {
+                        // To avoid recursive call to ReAlloc specifying granularity
+                        // Add address to the callstack
+                        iFreeCallStack[arrayCounter] = addr;
+                        arrayCounter++;
+                        break;
+                        }
+                    }
+                if ( arrayCounter == KATMaxFreeCallstackLength ||
+                     arrayCounter == iFreeMaxCallStack )
+                    {
+                    break;
+                    }
+                }
+            LOGSTR2( "ATMH > iFreeCallStack count ( %i )", arrayCounter );
+            }
+        
+        // Log freed memory.
+        if ( iLogOption == EATLogToTraceFast )
+            {
+            // Using fast mode.
+            ATFastLogMemoryFreed( iProcessId, (TUint32) aPtr, iFreeCallStack );
+            }
+        else
+            {
+            // Using storage server.
+            TInt err( iStorageServer.LogMemoryFreed( (TUint32) aPtr, iFreeCallStack ) );
+            if ( err != KErrNone )
+                {
+                LOGSTR2( "ATMH > LogMemoryFreed err( %i )", err );
+                }
+            }
+        }
     
     // Free the memory using original allocator
     iAllocator->Free( aPtr ); 
@@ -413,15 +440,6 @@
             LOGSTR2( "ATMH Thread stack size:    %x", params().iStackSize );
             iThreadArray.Append( TThreadStack( RThread().Id(), 
                     params().iStackAddress + params().iStackSize ) );
-            if ( iLogOption == EATLogToTraceFast )
-            	{
-                // log thread added
-                ATFastLogThreadStarted( RProcess().Id().operator TUint(), RThread().Id().operator TUint()); 
-            	}
-            else if ( iLogOption == EATLogToFile )
-				{
-				iLogFile.ATFileLogThreadStarted( RThread().Id().operator TUint() );
-				}
             }
         }
     
@@ -458,16 +476,6 @@
             {
             // Remove the thread
             iThreadArray.Remove( i );
-            if ( iLogOption == EATLogToTraceFast )
-            	{
-                // log thread removed
-                ATFastLogThreadEnded( RProcess().Id().operator TUint(), RThread().Id().operator TUint() ); 
-            	}
-            else if ( iLogOption == EATLogToFile )
-				{
-				iLogFile.ATFileLogThreadEnded( RThread().Id().operator TUint() );
-				}
-            
             break;
             }
         }
@@ -489,9 +497,6 @@
 
     // Acquire the mutex
     iMutex.Wait();
-    
-    // get thread ID
-    TUint threadId = RThread().Id();
 
     // Realloc the memory using original allocator
     TAny* ptr = iAllocator->ReAlloc( aPtr, aSize, aMode );
@@ -504,61 +509,117 @@
         LOGSTR3( "ATMH RAnalyzeToolAllocator::ReAlloc() - aSize: %i, aMode: %i", 
                 aSize, aMode );
 
-
-		// Reset the callstack
-		iReCallStack.Reset(); 
+        // Don't collect or log data if storage server not open or logging mode fast.
+        if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+            {
+            // Reset the callstack
+            iReCallStack.Reset(); 
 
-		// Find the current thread callstack start address
-		TUint32 stackstart( 0 ); 
-		TBool found( FindCurrentThreadStack( stackstart ) );
-		LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
-		
-		// Get current sp
-		TUint32 _sp( 0 );
-		__asm
-			{
-			mov [_sp], esp
-			}
-		
-		// Get codeblocks count
-		TInt blocksCount( iCodeblocks.Count() );
-		TInt error( KErrNone );
-		TUint arrayCounter = 0;
-		
-		for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-			{
-			TUint32 addr = (TUint32) *( (TUint32*) i );
-			if ( ! IsAddressLoadedCode( addr ) )
-				continue;
-			for ( TInt j = 0; j < blocksCount; j++ )
-				{
-				if ( iCodeblocks[j].CheckAddress( addr ) )
-					{
-					// To avoid recursive call to ReAlloc specifying granularity
-					// Add address to the callstack
-					iReCallStack[arrayCounter] = addr;
-					arrayCounter++;
-					break;
-					}
-				}
-			if ( arrayCounter == KATMaxCallstackLength || 
-				 arrayCounter == iAllocMaxCallStack )
-				{
-				LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
-				break;
-				}
-			}
-
-		if ( iLogOption == EATLogToTraceFast )
-			{
-			// Using fast logging mode.
-			ATFastLogMemoryReallocated( iProcessId, (TUint32) aPtr, (TUint32) ptr, iReCallStack, aSize, threadId );
-			}
-		else if ( iLogOption == EATLogToFile )
-			{
-			iLogFile.ATFileLogMemoryReallocated( (TUint32) aPtr, (TUint32) ptr, iReCallStack, aSize, threadId );
-			}	
-		}
+            // Find the current thread callstack start address
+            TUint32 stackstart( 0 ); 
+            TBool found( FindCurrentThreadStack( stackstart ) );
+            LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
+            
+            // Get current sp
+            TUint32 _sp( 0 );
+            __asm
+                {
+                mov [_sp], esp
+                }
+            
+            // Get codeblocks count
+            TInt blocksCount( iCodeblocks.Count() );
+            TInt error( KErrNone );
+            TUint arrayCounter = 0;
+            
+            for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+                {
+                TUint32 addr = (TUint32) *( (TUint32*) i );
+                if ( ! IsAddressLoadedCode( addr ) )
+                    continue;
+                for ( TInt j = 0; j < blocksCount; j++ )
+                    {
+                    if ( iCodeblocks[j].CheckAddress( addr ) )
+                        {
+                        // To avoid recursive call to ReAlloc specifying granularity
+                        // Add address to the callstack
+                        iReCallStack[arrayCounter] = addr;
+                        arrayCounter++;
+                        break;
+                        }
+                    }
+                if ( arrayCounter == KATMaxCallstackLength || 
+                     arrayCounter == iAllocMaxCallStack )
+                    {
+                    LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
+                    break;
+                    }
+                }
+            
+            // No need to report free if the aPtr was NULL
+            if ( aPtr != NULL )
+                {
+                // Reset the free callstack
+                iFreeCallStack.Reset();
+                
+                // if trace logging mode(s) we also log call stack in free.
+                if ( ( iLogOption == EATUseDefault || iLogOption == EATLogToTrace || iLogOption == EATLogToTraceFast )
+                        && iFreeMaxCallStack > 0 )
+                    {
+                    for ( TInt i = 0; i < arrayCounter; i++ )
+                        {
+                        if ( i == KATMaxFreeCallstackLength || i == iFreeMaxCallStack )
+                            {
+                            break;
+                            }
+                        iFreeCallStack[i] = iReCallStack[i];
+                        }
+                    }
+                
+                // Try to remove old address from the storage server's
+                // leak array. If found it's removed from the array because system frees
+                // old address directly in the RHeap in ReAlloc case.
+                if ( iLogOption == EATLogToTraceFast )
+                    {
+                    ATFastLogMemoryFreed( iProcessId, (TUint32) aPtr, iFreeCallStack );
+                    }
+                else
+                    {
+                    iStorageServer.LogMemoryFreed( (TUint32) aPtr, iFreeCallStack );
+                    }
+                }
+            
+            // Log the memory allocation information
+            if ( iLogOption == EATLogToTraceFast )
+                {
+                // Using fast mode.
+                ATFastLogMemoryAllocated( iProcessId, (TUint32) ptr, iFreeCallStack, aSize);
+                }
+            else
+                {
+                // Using storage server.
+                error = iStorageServer.LogMemoryAllocated( (TUint32) ptr, 
+                                                            iReCallStack, 
+                                                            aSize );
+                if ( KErrNone != error )
+                    {
+                    LOGSTR2( "ATMH LogMemoryAllocated ReAlloc error %i", error );
+                    switch ( error )
+                        {
+                        case KErrNoMemory:
+                        LOGSTR1( "ATMH RAnalyzeToolAllocator::ReAlloc() - KErrNoMemory case"  );
+                        if ( iStorageServerOpen )
+                            {
+                            iStorageServerOpen = EFalse;
+                            LOGSTR1( "ATMH RAnalyzeToolAllocator::ReAlloc() - close iStorageServer"  );
+                            iStorageServer.Close();
+                            }
+                        break;
+                        }
+                    }
+                }
+            }
+        }
     
     // Release the mutex
     iMutex.Signal();
@@ -580,9 +641,6 @@
 
     // Acquire the mutex
     iMutex.Wait();
-    
-    // get thread ID
-    TUint threadId = RThread().Id();
 
     // Realloc the memory using original allocator
     TAny* ptr = iAllocator->ReAlloc( aPtr, aSize, aMode );
@@ -595,55 +653,110 @@
         LOGSTR3( "ATMH RAnalyzeToolAllocator::ReAlloc() - aSize: %i, aMode: %i", 
                 aSize, aMode );
 
-		// Reset the callstack
-		iReCallStack.Reset(); 
-
-		// Find the current thread callstack start address
-		TUint32 stackstart( 0 ); 
-		TBool found( FindCurrentThreadStack( stackstart ) );
-		LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
-		
-		// Get codeblocks count
-		TInt blocksCount( iCodeblocks.Count() );
+        // Don't collect or log data if storage server not open or logging mode fast.
+        if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+            {
+            // Reset the callstack
+            iReCallStack.Reset(); 
 
-		TUint arrayCounter = 0;
-		
-		for ( TUint32 i = __current_sp(); i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-			{
-			TUint32 addr = (TUint32) *( (TUint32*) i );
-			if ( ! IsAddressLoadedCode( addr ) )
-				continue;
-			for ( TInt j = 0; j < blocksCount; j++ )
-				{
-				if ( iCodeblocks[j].CheckAddress( addr ) )
-					{
-					// To avoid recursive call to ReAlloc specifying granularity
-					// Add address to the callstack
-					iReCallStack[arrayCounter] = ( addr );
-					arrayCounter++;
-					break;
-					}
-				}
-			if ( arrayCounter == KATMaxCallstackLength || 
-				 arrayCounter == iAllocMaxCallStack )
-				{
-				LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
-				break;
-				}
-			}
-
-		if ( iLogOption == EATLogToTraceFast )
-			{
-			// Using fast logging mode.
-			ATFastLogMemoryReallocated( iProcessId, (TUint32) aPtr, (TUint32) ptr, iReCallStack, aSize, threadId );
-			}
-		else if ( iLogOption == EATLogToFile )
-			{
-			iLogFile.ATFileLogMemoryReallocated( (TUint32) aPtr, (TUint32) ptr, iReCallStack, aSize, threadId );
-			}
-		
-		
-		}
+            // Find the current thread callstack start address
+            TUint32 stackstart( 0 ); 
+            TBool found( FindCurrentThreadStack( stackstart ) );
+            LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
+            
+            // Get codeblocks count
+            TInt blocksCount( iCodeblocks.Count() );
+            TInt error( KErrNone );
+            TUint arrayCounter = 0;
+            
+            for ( TUint32 i = __current_sp(); i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+                {
+                TUint32 addr = (TUint32) *( (TUint32*) i );
+                if ( ! IsAddressLoadedCode( addr ) )
+                    continue;
+                for ( TInt j = 0; j < blocksCount; j++ )
+                    {
+                    if ( iCodeblocks[j].CheckAddress( addr ) )
+                        {
+                        // To avoid recursive call to ReAlloc specifying granularity
+                        // Add address to the callstack
+                        iReCallStack[arrayCounter] = ( addr );
+                        arrayCounter++;
+                        break;
+                        }
+                    }
+                if ( arrayCounter == KATMaxCallstackLength || 
+                     arrayCounter == iAllocMaxCallStack )
+                    {
+                    LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
+                    break;
+                    }
+                }
+            
+            // No need to report free if the aPtr was NULL
+            if ( aPtr != NULL )
+                {
+                // Reset the free callstack
+                iFreeCallStack.Reset();
+                
+                // if trace logging mode(s) we also log call stack with free.
+                if ( ( iLogOption == EATUseDefault || iLogOption == EATLogToTrace || iLogOption == EATLogToTraceFast )
+                        && iFreeMaxCallStack > 0 )
+                    {
+                    for ( TInt i = 0; i < arrayCounter; i++ )
+                        {
+                        if ( i == iFreeCallStack.Count() )
+                            {
+                            break;
+                            }
+                        iFreeCallStack[i] = iReCallStack[i];
+                        }
+                    }
+                
+                // Try to remove old address from the storage server's
+                // leak array. If found it's removed from the array because system frees
+                // old address directly in the RHeap in ReAlloc case.
+                if ( iLogOption == EATLogToTraceFast )
+                    {
+                    ATFastLogMemoryFreed( iProcessId, (TUint32) aPtr, iFreeCallStack );
+                    }
+                else
+                    {
+                    iStorageServer.LogMemoryFreed( (TUint32) aPtr, iFreeCallStack );
+                    }
+                }
+        
+            // Log the memory allocation information
+            if ( iLogOption == EATLogToTraceFast )
+                {
+                // Using fast mode.
+                ATFastLogMemoryAllocated( iProcessId, (TUint32) ptr, iReCallStack, aSize );
+                }
+            else
+                {
+                // Using storage server.
+                error = iStorageServer.LogMemoryAllocated( (TUint32) ptr, 
+                                                            iReCallStack, 
+                                                            aSize );
+                if ( KErrNone != error )
+                    {
+                    LOGSTR2( "ATMH LogMemoryAllocated ReAlloc error %i", error );
+                    switch ( error )
+                        {
+                        case KErrNoMemory:
+                        LOGSTR1( "ATMH RAnalyzeToolAllocator::ReAlloc() - KErrNoMemory case"  );
+                        if ( iStorageServerOpen )
+                            {
+                            iStorageServerOpen = EFalse;
+                            LOGSTR1( "ATMH RAnalyzeToolAllocator::ReAlloc() - close iStorageServer"  );
+                            iStorageServer.Close();
+                            }
+                        break;
+                        }
+                    }
+                }
+            }
+        }
 
     // Release the mutex
     iMutex.Signal();
--- a/analyzetool/dynamicmemoryhook/src/analyzetooleventhandler.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/src/analyzetooleventhandler.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -68,13 +68,15 @@
                         iLibraryInfo.iRunAddress,
                         iLibraryInfo.iRunAddress + iLibraryInfo.iSize );
                 }
-            else if( iLogOption == EATLogToFile )
-            	{
-				iLogFile.ATFileLogDllLoaded( iLibraryInfo.iLibraryName, 
-						iLibraryInfo.iRunAddress,
-						iLibraryInfo.iRunAddress + iLibraryInfo.iSize );
-            	}
-            
+            else
+                {
+                LOGSTR1( "ATMH CLibraryEventHandler::RunL() - iStorageServer.LogDllLoaded() " );
+                error = iStorageServer.LogDllLoaded( 
+                        iLibraryInfo.iLibraryName, 
+                        iLibraryInfo.iRunAddress,
+                        iLibraryInfo.iRunAddress + iLibraryInfo.iSize );
+                LOGSTR2( "ATMH StorageServer error: %i",  error );
+                }
             if ( KErrNone == error )
                 {
                 iCodeblocks.Append( TCodeblock( iLibraryInfo.iRunAddress, 
@@ -104,12 +106,23 @@
                             iLibraryInfo.iRunAddress, 
                             iLibraryInfo.iRunAddress + iLibraryInfo.iSize );
                     }
-                else if( iLogOption == EATLogToFile )
-					{
-					iLogFile.ATFileLogDllUnloaded( iLibraryInfo.iLibraryName, 
-							iLibraryInfo.iRunAddress,
-							iLibraryInfo.iRunAddress + iLibraryInfo.iSize );
-					}
+                else
+                    {
+                    LOGSTR1( "ATMH CLibraryEventHandler::RunL() - iStorageServer.LogDllUnloaded() " );
+                    #ifdef LOGGING_ENABLED
+                    TInt error = iStorageServer.LogDllUnloaded( 
+                            libraryName/*iLibraryInfo.iLibraryName*/, 
+                            iLibraryInfo.iRunAddress, 
+                            iLibraryInfo.iRunAddress + iLibraryInfo.iSize );
+    
+                    LOGSTR2( "ATMH StorageServer error: %i",  error );
+                    #else
+                    iStorageServer.LogDllUnloaded( 
+                                                libraryName/*iLibraryInfo.iLibraryName*/, 
+                                                iLibraryInfo.iRunAddress, 
+                                                iLibraryInfo.iRunAddress + iLibraryInfo.iSize );
+                    #endif
+                    }
                 iCodeblocks.Remove( i );
                 break;
                 }
@@ -185,20 +198,19 @@
 // -----------------------------------------------------------------------------
 //
 CLibraryEventHandler::CLibraryEventHandler( RAnalyzeTool& aAnalyzeTool, 
-	RArray<TCodeblock>& aCodeblocks,
+	RArray<TCodeblock>& aCodeblocks, RATStorageServer& aStorageServer, 
 	TUint aProcessId, RMutex& aMutex, 
 	MAnalyzeToolEventhandlerNotifier& aNotifier,
-	TUint32 aLogOption,
-	RATFileLog& aFileLog ) 
+	TUint32 aLogOption ) 
  :	CActive( EPriorityNormal ),
     iAnalyzeTool( aAnalyzeTool ),
     iCodeblocks( aCodeblocks ),
+    iStorageServer( aStorageServer ),
     iProcessId( aProcessId ),
     iMutex( aMutex ),
     iStarted( EFalse ),
     iNotifier( aNotifier ),
-    iLogOption( aLogOption ),
-    iLogFile( aFileLog )
+    iLogOption( aLogOption )
     {
     LOGSTR1( "ATMH CLibraryEventHandler::CLibraryEventHandler()" );
     }
--- a/analyzetool/dynamicmemoryhook/src/analyzetoolfastlog.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/src/analyzetoolfastlog.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -15,6 +15,7 @@
 *
 */
 
+
 #include <e32debug.h> // RDebug
 #include <analyzetool/analyzetooltraceconstants.h>
 #include "analyzetoolfastlog.h"
@@ -31,51 +32,26 @@
 
 TInt ATFastLogProcessStarted( const TDesC8& aProcessName,
                                  TUint aProcessId,
-                                 TUint32 aIsDebug,
-                                 const TDesC8& aAtoolVersion,
-                                 const TDesC8& aApiVersion )
+                                 TUint32 aIsDebug )
     {
     LOGSTR1( "ATFL ATFastLogProcessStarted()" );
-    
-    // PCS <Process name> <Process ID> <Time stamp> <Udeb> <Version>
-
-    //Buffer to trace
-    TBuf8<KProcessStartBufLength> buffer;
-    
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    // process id
-    buffer.AppendNum( aProcessId, EHex );
-    buffer.Append( KSpace );
-    
-    // PCS
-    buffer.Append( KProcessStart );
-    // process name
-    buffer.Append( aProcessName );
-    buffer.Append( KSpace );
-    // process id
-    buffer.AppendNum( aProcessId, EHex );
-    buffer.Append( KSpace );
-    // time stamp
+    // Convert process name to 16-bit descriptor.
+    TBuf<KMaxProcessName> processName;
+    processName.Copy( aProcessName );
+    // Buffer to trace.
+    TBuf<KProcessStartBufLength> buffer;
+    // Format process name and id.
+    buffer.Format( KProcessStart16, &processName, aProcessId );
+    // Timestamp.
     buffer.AppendNum( CurrentTime(), EHex ) ;
-    buffer.Append( KSpace );
-    // urel/udeb
+    // Append udeb/urel information to the process start.
+    buffer.Append( KSpaceTrace );  
     buffer.AppendNum( aIsDebug, EHex );
-    buffer.Append( KSpace );
-    // version
+    // Append version number.
+    buffer.Append( KSpaceTrace );  
     buffer.AppendNum( KATTraceVersion, EHex );
-    buffer.Append( KSpace );    
-    // atool version
-    buffer.Append( aAtoolVersion );
-    buffer.Append( KSpace );
-    // ATAPI version
-    buffer.Append( aApiVersion );
-
-
-
-
-    RDebug::RawPrint( buffer );
-       
+    // Log to trace.
+    RDebug::Print( KTraceMessage, aProcessId ,&buffer );
     return KErrNone;
     }
 
@@ -83,44 +59,21 @@
                             TUint aHandleLeakCount )
     {
     LOGSTR1( "ATFL ATFastLogProcessEnded()" );
-    
-    // PCE
-    
+    // Handle leaks.
     if ( aHandleLeakCount > 0 )
-    	{
-        // HDL <Handle count>
-    
+        {
         // Buffer to trace.
-        TBuf8<KHandleLeakBufLength> buffer2;
-        
-        // AT indentifier
-        buffer2.Append( KATIdentifier );
-        // process id
-        buffer2.AppendNum( aProcessId, EHex );
-        buffer2.Append( KSpace );
-        
-        // HDL
-        buffer2.Append( KHandleLeak );
-        // leak count
-        buffer2.AppendNum( aHandleLeakCount );
-
-        RDebug::RawPrint( buffer2 );
-    	}
-    
-    // Buffer to trace.
-    TBuf8<KProcessEndBufLength> buffer;
-    
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    // process id
-    buffer.AppendNum( aProcessId, EHex );
-    buffer.Append( KSpace );
-    
-    // PCE
-    buffer.Append( KProcessEnd );
-    RDebug::RawPrint( buffer );
-    
-        
+        TBuf<KHandleLeakBufLength> buffer2;
+        buffer2.Format( KHandleLeak16, &KUnknownModule16, aHandleLeakCount );
+        // Trace it.
+        RDebug::Print( KTraceMessage, aProcessId, &buffer2 );
+        }
+    // Process end trace.
+    TBuf<KProcessEndBufLength> buffer;
+    buffer.Format( KProcessEnd16, aProcessId );
+    buffer.AppendNum( CurrentTime(), EHex);
+    buffer.Append( KNewLineTrace );
+    RDebug::Print( KTraceMessage, aProcessId, &buffer );
     return KErrNone;
     }
 
@@ -130,31 +83,15 @@
                                         TUint32 aEndAddress )
     {
     LOGSTR1( "ATFL ATFastLogDllLoaded()" );
-    
-    // DLL <DLL name> <Memory start address> <Memory end address>
-    
+    // Timestamp.
+    TInt64 time = CurrentTime();
+    // Convert dll name to 16-bit descriptor.
+    TBuf<KMaxLibraryName> dll;
+    dll.Copy( aDllName );
     // Buffer to trace.
-    TBuf8<KDllLoadBufLength> buffer;
-    
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    // process id
-    buffer.AppendNum( aProcessId, EHex  );
-    buffer.Append( KSpace );
-    
-    // DLL
-    buffer.Append( KDllLoad );
-    // dll name
-    buffer.Append( aDllName );
-    buffer.Append( KSpace );
-    // start adress
-    buffer.AppendNum( aStartAddress, EHex );
-    buffer.Append( KSpace );   
-    //end adress
-    buffer.AppendNum( aEndAddress, EHex );
-    
-    RDebug::RawPrint( buffer );
-    
+    TBuf<KDllLoadBufLength> buffer;
+    buffer.Format( KDllLoad16, &dll, time, aStartAddress, aEndAddress );
+    RDebug::Print( KTraceMessage, aProcessId, &buffer );
     return KErrNone;
     }
 
@@ -162,77 +99,67 @@
                                        TUint32 aEndAddress )
     {
     LOGSTR1( "ATFL ATFastLogDllUnloaded()" );
-    
-    // DLU <DLL name> <Memory start address> <Memory end address>
-    
+    // Timestamp.
+    TInt64 time = CurrentTime();
+    // Convert dll name to 16-bit descriptor.
+    TBuf<KMaxLibraryName> dll;
+    dll.Copy( aDllName );
     // Buffer to trace.
-    TBuf8<KDllUnloadBufLength> buffer;
-    
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    // process id
-    buffer.AppendNum( aProcessId, EHex  );
-    buffer.Append( KSpace );
-    
-    // DLU
-    buffer.Append( KDllUnload );
-    // dll name
-    buffer.Append( aDllName );
-    buffer.Append( KSpace );
-    // start adress
-    buffer.AppendNum( aStartAddress, EHex );
-    buffer.Append( KSpace );   
-    //end adress
-    buffer.AppendNum( aEndAddress, EHex );
-    
-    RDebug::RawPrint( buffer );
-
+    TBuf<KDllLoadBufLength> buffer;
+    buffer.Format( KDllUnload16, &dll, time, aStartAddress, aEndAddress );
+    RDebug::Print( KTraceMessage, aProcessId, &buffer );   
     return KErrNone;
     }
 
 TInt ATFastLogMemoryAllocated( TUint aProcessId, TUint32 aMemAddress,
                                   TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
-                                  TInt aSize, TUint aThreadId )
+                                  TInt aSize )
     {
     LOGSTR1( "ATFL ATFastLogMemoryAllocated()" );
+    // ALLOCH <Memory address> <Time stamp> <Allocation size> <Call stack address count> 
+    // <Call stack address> <Call stack address> ...
     
-    // ALH <Memory address> <Allocation size> <Thread ID> 
-    // <Call stack address count> <Call stack address> <Call stack address> ...
-        
-    // Buffer to trace.
-    TBuf8<KMemAllocBufLength> buffer;
+    // Timestamp.
+    TInt64 time = CurrentTime();
+    
+    // Trace buffer and pointer to it.
+    TBufC<KMemAllocBufLength> buffer;
+    TPtr ptr( buffer.Des() );
+    // Append the tag implying a memory allocation line in the data file
+    ptr.Append( KMemoryAllocHeader );
     
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    // process id
-    buffer.AppendNum( aProcessId, EHex  );
-    buffer.Append( KSpace );
+    // Append the start address of this allocation in the 32-bit (max 8 characters)
+    // hexadecimal text format.
+    ptr.AppendNum( aMemAddress, EHex );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    ptr.Append( KSpaceTrace );
+    ptr.AppendNum( time, EHex );
     
-    // ALH
-    buffer.Append( KMemoryAllocHeader );
-    // memory adress
-    buffer.AppendNum( aMemAddress, EHex );
-    buffer.Append( KSpace );
-    // allocation size
-    buffer.AppendNum( aSize, EHex );
-    buffer.Append( KSpace ); 
-    // thread ID
-    buffer.AppendNum( aThreadId, EHex );
-    buffer.Append( KSpace );
-
+    // Append the size of the allocation in the 32-bit (max 8 characters) hexadecimal
+    // text format.
+    ptr.Append( KSpaceTrace );
+    ptr.AppendNum( aSize, EHex );
+    
     // Search call stack for address count.
-	TInt addrCount(0);
-	for ( TInt j = 0; j < aCallstack.Count() ; j++ )
-		{
-		if ( aCallstack.At(j) == 0 )
-			break;
-		addrCount++;
-		}
-	// Current position in call stack.
-	TInt addrPos( 0 );
+    TInt addrCount(0);
+    for ( TInt j = 0; j < aCallstack.Count() ; j++ )
+        {
+        if ( aCallstack.At(j) == 0 )
+            break;
+        addrCount++;
+        }
+    // Current position in call stack.
+    TInt addrPos( 0 );
     
-    // address count
-    buffer.AppendNum( addrCount, EHex );
+    // Append address count.
+    ptr.Append( KSpaceTrace );
+    ptr.AppendNum( addrCount, EHex );
+            
+    // Calculate last item length
+    TInt lastItemLength( KTraceMessage().Length() + KHexa32Length + 
+            KSpaceLength + KNewlineLength );
     
     TUint packetNumber( 1 );
     
@@ -240,310 +167,132 @@
     // this memory allocation 
     for ( TInt j = 0; j < addrCount; j++ )
         {
-        // ALF <Memory address> <Packet number> <Call stack address> <Call stack address> ...
-        if ( buffer.Length() <= 0 )
-            {
-            // AT indentifier
-            buffer.Append( KATIdentifier );
-            // process id
-            buffer.AppendNum( aProcessId, EHex  );
-            buffer.Append( KSpace ); 
-            
+        // ALLOCF <Memory address> <Time stamp> <Packet number> 
+        // <Call stack address> <Call stack address> ...
+        if ( ptr.Length() <= 0 )
+            {               
             // Create alloc fragment message header
-            buffer.Append( KMemoryAllocFragment );
-            buffer.AppendNum( aMemAddress, EHex );
-            buffer.Append( KSpace );     
-            buffer.AppendNum( packetNumber, EHex );
+            ptr.Append( KMemoryAllocFragment );
+            ptr.AppendNum( aMemAddress, EHex );
+            ptr.Append( KSpaceTrace );
+            ptr.AppendNum( time, EHex );
+            ptr.Append( KSpaceTrace );        
+            ptr.AppendNum( packetNumber, EHex );
             // Increase packet number
             packetNumber++;
             }
       
         // Append call stack address.
-        buffer.Append( KSpace );
-        buffer.AppendNum( aCallstack.At( addrPos ), EHex );
+        ptr.AppendFormat( KHexaNumberTrace, aCallstack.At( addrPos ) );
         
         // Move the call stack position.
         addrPos++;
         
         // Check if buffer max length exceed
-        if ( KLastItemLength + buffer.Length() >= KMemAllocBufLength )
+        if ( lastItemLength + ptr.Length() >= KMemAllocBufLength )
             {
+            ptr.Append( KNewLineTrace );
             // Log through debug channel 
-            RDebug::RawPrint( buffer );
+            RDebug::Print( KTraceMessage, aProcessId, &buffer );
             // Empty trace buffer
-            buffer.Delete( 0, buffer.MaxLength() );
+            ptr.Delete( 0, ptr.MaxLength() );
             }
         }
     // Send last message if exists.
-    if ( buffer.Length() > 0 )
+    if ( ptr.Length() > 0 )
         {
-        RDebug::RawPrint( buffer );
+        ptr.Append( KNewLineTrace );
+        RDebug::Print( KTraceMessage, aProcessId, &buffer);
         }
- 
     return KErrNone;
     }
 
 
 TInt ATFastLogMemoryFreed( TUint aProcessId, TUint32 aMemAddress, 
-                              TFixedArray<TUint32, KATMaxFreeCallstackLength>& aFreeCallstack,
-                              TUint aThreadId )
+                              TFixedArray<TUint32, KATMaxFreeCallstackLength>& aFreeCallstack )
     {
     LOGSTR1( "ATFL ATFastLogMemoryFreed()" );
-
-	// FRH <Memory address> <Thread ID> <Call stack address count> 
-	// <Call stack address> <Call stack address> ...
-	
-	// Buffer to trace.
-	TBuf8<KMemFreedBufLength> buffer;
-
-	// AT indentifier
-	buffer.Append( KATIdentifier );
-	// process id
-	buffer.AppendNum( aProcessId, EHex  );
-	buffer.Append( KSpace );
-	
-	// FRH
-	buffer.Append( KMemoryFreedHeader );
-	
-	// Append the start address of this allocation in the 32-bit (max 8 characters)
-	// hexadecimal text format.
-	buffer.AppendNum( aMemAddress, EHex );
-	buffer.Append( KSpace );
-	
-	// thread ID
-	buffer.AppendNum( aThreadId, EHex );
-	buffer.Append( KSpace );
-	
-	// Search call stack for address count.
-	TInt addrCount(0);
-	for ( TInt j = 0; j < aFreeCallstack.Count() ; j++ )
-		{
-		if ( aFreeCallstack.At(j) == 0 )
-			break;
-		addrCount++;
-		}
-	// Current position in call stack.
-	TInt addrPos( 0 );
-	
-	// address count.
-	buffer.AppendNum( addrCount, EHex );
-	
-	TUint packetNumber( 1 );
-	
-	// Go through all call stack's memory addresses associated with
-	// this memory allocation 
-	for ( TInt j = 0; j < addrCount; j++ )
-		{
-		// FRF <Memory address> <Packet number> 
-		// <Call stack address> <Call stack address> ...
-		if ( buffer.Length() <= 0 )
-			{               
-			// Create alloc fragment message header
-			buffer.Append( KMemoryFreedFragment );
-			buffer.AppendNum( aMemAddress, EHex );
-			buffer.Append( KSpace );
-			buffer.AppendNum( packetNumber, EHex );
-			// Increase packet number
-			packetNumber++;
-			}
-	  
-		// Append call stack address.
-		buffer.Append( KSpace );
-		buffer.AppendNum( aFreeCallstack.At( addrPos ), EHex );
-		
-		// Move the call stack position.
-		addrPos++;
-		
-		// Check if buffer max length exceed
-		if ( KLastItemLength + buffer.Length() >= KMemFreedBufLength )
-			{
-			// Log through debug channel 
-			RDebug::RawPrint( buffer );
-			// Empty trace buffer
-			buffer.Delete( 0, buffer.MaxLength() );
-			}
-		}
-	// Send last message if exists.
-	if ( buffer.Length() > 0 )
-		{
-		RDebug::RawPrint( buffer );
-		}
-		
-    return KErrNone;   
-    }
-
-TInt ATFastLogMemoryReallocated( TUint aProcessId, TUint32 aMemAddressFree,  TUint32 aMemAddressAlloc,
-                                  TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
-                                  TInt aSize, TUint aThreadId )
-    {
-    LOGSTR1( "ATFL ATFastLogMemoryReallocated()" );    
+    // FREEH <Memory address> <Time tamp> <Call stack address count> <Call stack address>
+    // <Call stack address> ...
+    
+    // Timestamp.
+    TInt64 time = CurrentTime();
+    
+    // Trace buffer and pointer to it.
+    TBufC<KMemFreedBufLength> buffer;
+    TPtr ptr( buffer.Des() );
+ 
+    // Append the tag implying a memory allocation line in the data file
+    ptr.Append( KMemoryFreedHeader );
+    
+    // Append the start address of this allocation in the 32-bit (max 8 characters)
+    // hexadecimal text format.
+    ptr.AppendNum( aMemAddress, EHex );
     
-    // RAH <Freed memory address> <Allocated memory address> <Allocation size> <Thread ID>
-    // <Call stack address count> <Call stack address> <Call stack address> ...
-        
-    // Buffer to trace.
-    TBuf8<KMemReallocBufLength> buffer;
-    
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    // process id
-    buffer.AppendNum( aProcessId, EHex  );
-    buffer.Append( KSpace );
+    // Append timestamp;
+    ptr.Append( KSpaceTrace );
+    ptr.AppendNum( time, EHex);
     
-    // RAH
-    buffer.Append( KMemoryReallocHeader );
-    // memory adress freed
-    buffer.AppendNum( aMemAddressFree, EHex );
-    buffer.Append( KSpace );
-    // memory adress allocated
-    buffer.AppendNum( aMemAddressAlloc, EHex );
-    buffer.Append( KSpace );
-    // allocation size
-    buffer.AppendNum( aSize, EHex );
-    buffer.Append( KSpace ); 
-    // thread ID
-    buffer.AppendNum( aThreadId, EHex );
-    buffer.Append( KSpace );
-
     // Search call stack for address count.
-	TInt addrCount(0);
-	for ( TInt j = 0; j < aCallstack.Count() ; j++ )
-		{
-		if ( aCallstack.At(j) == 0 )
-			break;
-		addrCount++;
-		}
-	// Current position in call stack.
-	TInt addrPos( 0 );
+    TInt addrCount(0);
+    for ( TInt j = 0; j < aFreeCallstack.Count() ; j++ )
+        {
+        if ( aFreeCallstack.At(j) == 0 )
+            break;
+        addrCount++;
+        }
+    // Current position in call stack.
+    TInt addrPos( 0 );
     
-    // address count
-    buffer.AppendNum( addrCount, EHex );
-        
+    // Append address count.
+    ptr.Append( KSpaceTrace );
+    ptr.AppendNum( addrCount, EHex );
+            
+    // Calculate last item length
+    TInt lastItemLength( KTraceMessage().Length() + KHexa32Length + 
+            KSpaceLength + KNewlineLength );
+    
     TUint packetNumber( 1 );
     
     // Go through all call stack's memory addresses associated with
     // this memory allocation 
     for ( TInt j = 0; j < addrCount; j++ )
         {
-        // RAF <Freed memory address> <Allocated memory address> <Packet number>
+        // ALLOCF <Memory address> <Time stamp> <Packet number> 
         // <Call stack address> <Call stack address> ...
-        if ( buffer.Length() <= 0 )
-            {
-            // AT indentifier
-            buffer.Append( KATIdentifier );
-            // process id
-            buffer.AppendNum( aProcessId, EHex  );
-            buffer.Append( KSpace ); 
-            
+        if ( ptr.Length() <= 0 )
+            {               
             // Create alloc fragment message header
-            buffer.Append( KMemoryReallocFragment );
-            // memory adress freed
-            buffer.AppendNum( aMemAddressFree, EHex );
-            buffer.Append( KSpace );
-            // memory adress allocated
-            buffer.AppendNum( aMemAddressAlloc, EHex );
-            buffer.Append( KSpace );
-            // packet number
-            buffer.AppendNum( packetNumber, EHex );
+            ptr.Append( KMemoryFreedFragment );
+            ptr.AppendNum( aMemAddress, EHex );
+            ptr.Append( KSpaceTrace );
+            ptr.AppendNum( packetNumber, EHex );
             // Increase packet number
             packetNumber++;
             }
       
         // Append call stack address.
-        buffer.Append( KSpace );
-        buffer.AppendNum( aCallstack.At( addrPos ), EHex );
+        ptr.AppendFormat( KHexaNumberTrace, aFreeCallstack.At( addrPos ) );
         
         // Move the call stack position.
         addrPos++;
         
         // Check if buffer max length exceed
-        if ( KLastItemLength + buffer.Length() >= KMemAllocBufLength )
+        if ( lastItemLength + ptr.Length() >= KMemFreedBufLength )
             {
+            ptr.Append( KNewLineTrace );
             // Log through debug channel 
-            RDebug::RawPrint( buffer );
+            RDebug::Print( KTraceMessage, aProcessId, &buffer );
             // Empty trace buffer
-            buffer.Delete( 0, buffer.MaxLength() );
+            ptr.Delete( 0, ptr.MaxLength() );
             }
         }
     // Send last message if exists.
-    if ( buffer.Length() > 0 )
+    if ( ptr.Length() > 0 )
         {
-        RDebug::RawPrint( buffer);
+        ptr.Append( KNewLineTrace );
+        RDebug::Print( KTraceMessage, aProcessId, &buffer);
         }
-      
-    return KErrNone;
-    }
-
-TInt ATFastLogThreadStarted( TUint aProcessId, TUint aThreadId )
-    {
-    LOGSTR1( "ATFL ATFastLogThreadStarted()" );
-    
-    // TDS <Thread ID>
-
-    //Buffer to trace
-    TBuf8<KThreadStartBufLength> buffer;
-    
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    // process id
-    buffer.AppendNum( aProcessId, EHex  );
-    buffer.Append( KSpace );
-    
-    // TDS
-    buffer.Append( KThreadStart );
-    // thread ID
-    buffer.AppendNum( aThreadId, EHex );
-
-    RDebug::RawPrint( buffer );
-       
-    return KErrNone;
+    return KErrNone;   
     }
 
-TInt ATFastLogThreadEnded( TUint aProcessId, TUint64 aThreadId )
-    {
-    LOGSTR1( "ATFL ATFastLogThreadEnded()" );
-    
-    // TDE <Thread ID>
-
-    //Buffer to trace
-    TBuf8<KThreadEndBufLength> buffer;
-    
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    // process id
-    buffer.AppendNum( aProcessId, EHex  );
-    buffer.Append( KSpace );
-    
-    // TDE
-    buffer.Append( KThreadEnd );
-    // thread ID
-    buffer.AppendNum( aThreadId, EHex );
-
-    RDebug::RawPrint( buffer );
-       
-    return KErrNone;
-    }
-
-TInt ATFastLogDeviceInfo( const TDesC8& aS60Version, const TDesC8& aChecksum)
-    {
-    LOGSTR1( "ATFL ATFastLogVersionsInfo()" );
-    
-    //Buffer to trace
-    TBuf8<KVersionsInfoBufLength> buffer;
-    
-    // AT indentifier
-    buffer.Append( KATIdentifier );
-    
-    // VER
-    buffer.Append( KVersionsInfo );
-    
-    // sw version
-    buffer.Append(aS60Version);
-    buffer.Append(KSpace);
-    // rom checksum
-    buffer.Append(aChecksum);
-
-    RDebug::RawPrint( buffer );
-    
-    return KErrNone;
-    }
--- a/analyzetool/dynamicmemoryhook/src/analyzetoolfilelog.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,603 +0,0 @@
-/*
-* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Declaration of the class TATDriveInfo.
-*
-*/
-
-#include "analyzetoolfilelog.h"
-#include "atdriveinfo.h"
-#include "atlog.h"
-#include <analyzetool/customuser.h>
-#include <analyzetool/analyzetooltraceconstants.h>
-#include <f32file.h> //RFs
-#include <utf.h>
-
-// New file name start and end index.
-const TInt KNameIndexStart = 1;
-const TInt KNameIndexEnd = 100;
-
-RATFileLog::RATFileLog()
-	{
-
-    // Initialize iMicroSecondsAt1970
-    TTime time( KJanuaryFirst1970 );
-    iMicroSecondsAt1970 = time.Int64();
-    iError = KErrNone;
-	}
-
-RATFileLog::~RATFileLog()
-	{
-	// Auto-generated destructor stub
-	}
-
-
-// Local time function.
-TInt64 RATFileLog::CurrentTime()
-    {
-    LOGSTR1( "ATFL void CATStorageServerSession::GetTime()" );
-    
-    // Get the current universal time
-    TTime time;
-    time.UniversalTime();
-        
-    // Change the time format that tells the number of microseconds from January First,
-    // 0 AD nominal Gregorian, into a format that tells the number of microseconds from
-    // January First, 1970 AD nominal Gregorian. This is a more generic format and
-    // can be directly exploited by the PC code parsing the data file that this
-    // server generates.        
-    return ( time.Int64() - iMicroSecondsAt1970 );        
-    }
-
-TInt RATFileLog::ATFileLogVersion()
-{
-    LOGSTR1( "ATFL CATFileLog::ATFileLogVersion()" );
-    
-    iFile << KDataFileVersion;
-
-    iFile.CommitL();   
-    return KErrNone;
-}
-
-TInt RATFileLog::ATFileLogProcessStarted( const TDesC8& aProcessName,
-                                          TUint aProcessId,
-                                          TUint32 aIsDebug,
-                                          const TDesC8& aAtoolVersion,
-                                          const TDesC8& aApiVersion )
-{
-    LOGSTR1( "ATFL CATFileLog::ATFileLogProcessStarted()" );
- 
-    // log the current time
-    iFile << this->CurrentTime();
-    
-    // <Time stamp> PCS <Process name> <Process ID> <Udeb> <Version>
-    iFile << (TUint8)EProcessStart;
-    iFile << aProcessName;
-    iFile << (TUint32)aProcessId;
-    iFile << aIsDebug;
-    iFile << aAtoolVersion;
-    iFile << aApiVersion;
-    
-    // ensure that any buffered data is written to the stream
-    iFile.CommitL();
-    
-    return KErrNone;
-}
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogProcessEnded
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogProcessEnded( TUint aHandleLeakCount )
-{
-	LOGSTR1( "ATFL CATFileLog::ATFileLogProcessEnded()" );
-	   
-	if ( aHandleLeakCount > 0 )
-	{
-		// HDL <Handle count>
-		iFile << this->CurrentTime();
-        iFile << (TUint8)EHandleLeak;
-        iFile << (TUint32)aHandleLeakCount;	
-	}
-
-	// log the current time
-    iFile << this->CurrentTime();
-	
-	// PCE
-	iFile << (TUint8)EProcessEnd;
-	
-    // ensure that any buffered data is written to the stream
-    iFile.CommitL();
-	
-	return KErrNone;	
-}
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogDllLoaded
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogDllLoaded( const TDesC8& aDllName, TUint32 aStartAddress,
-                                TUint32 aEndAddress )
-{
-	LOGSTR1( "ATFL CATFileLog::ATFileLogDllLoaded()" );
-	    
-	// log the current time
-	iFile << this->CurrentTime();
-	
-	// DLL <DLL name> <Memory start address> <Memory end address>
-
-	// DLL
-	iFile << (TUint8)EDllLoad;
-	// dll name
-	iFile << aDllName;
-	// start adress
-	iFile << aStartAddress;
-	//end adress
-	iFile << aEndAddress;
-	
-	// ensure that any buffered data is written to the stream
-	iFile.CommitL();
-	
-	return KErrNone;
-}
-
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogDllUnloaded
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogDllUnloaded( const TDesC8& aDllName, TUint32 aStartAddress,
-                                       TUint32 aEndAddress )
-{
-    LOGSTR1( "ATFL CATFileLog::ATFileLogDllUnloaded()" );
-
-    // log the current time
-    iFile << this->CurrentTime();
-    
-    // DLU <DLL name> <Memory start address> <Memory end address>
-    
-    // DLU
-    iFile << (TUint8)EDllUnload;
-    // dll name
-    iFile << aDllName;
-    // start adress
-    iFile << aStartAddress;
-    //end adress
-    iFile << aEndAddress;
-    
-    // ensure that any buffered data is written to the stream
-    iFile.CommitL();
-	
-	return KErrNone;
-		
-}
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogMemoryAllocated
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogMemoryAllocated( TUint32 aMemAddress,
-                                  TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
-                                  TInt aSize,  TUint aThreadId  )
-{
-	LOGSTR1( "ATFL CATFileLog::ATFileLogMemoryAllocated()" );
-	
-	// ALH <Memory address> <Allocation size> <Thread ID> 
-	// <Call stack address count> <Call stack address> <Call stack address> ...
-	
-	// log the current time
-	iFile << this->CurrentTime();
-
-	// ALH
-	iFile << (TUint8)EAllocH;
-	// memory adress
-	iFile << aMemAddress;
-	// allocation size
-	iFile << (TUint32)aSize;
-	// thread ID
-	iFile << (TUint32)aThreadId;
-
-	// Search call stack for address count.
-	TInt addrCount(0);
-	for ( TInt j = 0; j < aCallstack.Count() ; j++ )
-		{
-		if ( aCallstack.At(j) == 0 )
-			break;
-		addrCount++;
-		}
-	
-	// address count
-    iFile << (TUint32)addrCount;
-		
-	// Go through all call stack's memory addresses associated with
-	// this memory allocation 
-	for ( TInt addrPos = 0; addrPos < addrCount; addrPos++ )
-		{
-	    iFile <<  aCallstack.At( addrPos );
-		}
-
-	// ensure that any buffered data is written to the stream
-	iFile.CommitL();
-
-	return KErrNone;	
-}
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogMemoryFreed
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogMemoryFreed( TUint32 aMemAddress, 
-		                                  TFixedArray<TUint32, KATMaxFreeCallstackLength>& aFreeCallstack, 
-		                                  TUint aThreadId )
-{
-    LOGSTR1( "ATFL CATFileLog::ATFileLogMemoryFreed()" );
-	
-	// FRH <Memory address> <Thread ID> <Call stack address count> 
-	// <Call stack address> <Call stack address> ...
-
-	// log the current time
-	iFile << this->CurrentTime();
-
-	// FRH
-	iFile << (TUint8)EFreeH;
-	
-	// Append the start address of this allocation in the 32-bit (max 8 characters)
-	// hexadecimal text format.
-	iFile << aMemAddress;
-
-	// thread ID
-	iFile << (TUint32)aThreadId;
-	
-	// Search call stack for address count.
-	TInt addrCount(0);
-	for ( TInt j = 0; j < aFreeCallstack.Count() ; j++ )
-		{
-		if ( aFreeCallstack.At(j) == 0 )
-			break;
-		addrCount++;
-		}
-	
-	// address count.
-	iFile << (TUint32)addrCount;
-
-	// Go through all call stack's memory addresses associated with
-	// this memory allocation 
-	for ( TInt addrPos = 0; addrPos < addrCount; addrPos++ )
-		{
-		iFile << aFreeCallstack.At( addrPos );
-		}
-
-	// ensure that any buffered data is written to the stream
-	iFile.CommitL();
-
-	return KErrNone;		
-}
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogMemoryReallocated
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogMemoryReallocated( TUint32 aMemAddressFree,  TUint32 aMemAddressAlloc,
-                                  TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
-                                  TInt aSize,  TUint aThreadId  )
-{
-	LOGSTR1( "ATFL CATFileLog::ATFileLogMemoryReallocated()" );    
-	    
-	// RAH <Freed memory address> <Allocated memory address> <Allocation size> <Thread ID>
-	// <Call stack address count> <Call stack address> <Call stack address> ...
-	        
-    // log the current time
-    iFile << this->CurrentTime();
-	
-	// RAH
-    iFile <<  (TUint8)EReallocH;
-	// memory adress freed
-    iFile << aMemAddressFree;
-	// memory adress allocated
-    iFile << aMemAddressAlloc;
-	// allocation size
-    iFile << (TUint32)aSize;
-	// thread ID
-    iFile << (TUint32)aThreadId;
-
-	// Search call stack for address count.
-	TInt addrCount(0);
-	for ( TInt j = 0; j < aCallstack.Count() ; j++ )
-		{
-		if ( aCallstack.At(j) == 0 )
-			break;
-		addrCount++;
-		}
-	
-	// address count
-	iFile << (TUint32)addrCount;
-		
-	// Go through all call stack's memory addresses associated with
-	// this memory allocation 
-	for ( TInt addrPos = 0; addrPos < addrCount; addrPos++ )
-		{	  
-		// Append call stack address.
-		iFile << aCallstack.At( addrPos );
-		}
-
-	// ensure that any buffered data is written to the stream
-	iFile.CommitL();
-
-	return KErrNone;	
-}
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogThreadStarted
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogThreadStarted( TUint aThreadId )
-{
-	LOGSTR1( "ATFL CATFileLog::ATFileLogThreadStarted()" );
-
-	// log the current time
-	iFile << this->CurrentTime();
-	
-	// TDS <Thread ID>
-
-	// TDS
-	iFile << (TUint8)EThreadStart;
-	// thread ID
-	iFile << (TUint32)aThreadId;
-    
-    // ensure that any buffered data is written to the stream
-    iFile.CommitL();
-
-	return KErrNone;
-}
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogThreadEnded
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogThreadEnded( TUint64 aThreadId )
-{
-	  LOGSTR1( "ATFL CATFileLog::ATFileLogThreadEnded()" );
-
-		// log the current time
-		iFile << this->CurrentTime();
-		
-		// TDE <Thread ID>
-
-		// TDE
-		iFile << (TUint8)EThreadEnd;
-		// thread ID
-		iFile << (TUint32)aThreadId;
-	    
-	    // ensure that any buffered data is written to the stream
-	    iFile.CommitL();
-
-		return KErrNone;
-}
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ATFileLogDeviceInfo
-// 
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::ATFileLogDeviceInfo( const TDesC8& aS60Version, const TDesC8& aChecksum)
-
-{
-    LOGSTR1( "ATFL CATFileLog::ATFileLogVersionsInfo()" );
-
-    // log the current time
-    iFile << this->CurrentTime();
-
-    // VER
-    iFile << (TUint8)EDeviceInfo;
-    // sw version
-    iFile << aS60Version;
-    // rom checksum
-    iFile << aChecksum;
-
-    // ensure that any buffered data is written to the stream
-    iFile.CommitL();
-
-	return KErrNone;	
-}
-
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::OpenFsAndFile
-// Internally used for opening a handle to the file server and a file
-// -----------------------------------------------------------------------------
-// 
-TInt RATFileLog::OpenFsAndFile( const TDesC& aFileName, const TDesC& aFilePath, 
-    const TDesC8& aProcessName )
-    {
-    LOGSTR1( "ATFL TInt CATFileLog::OpenFsAndFile()" );
-    
-    // Connect file server, return if error occured
-    iError = iFileServer.Connect();
-    if ( iError )
-        {
-        iFileServer.Close();
-        return iError;
-        }
-    
-    iError = iFileServer.ShareAuto();
-    if( iError )
-    	{
-		iFileServer.Close();
-		return iError;
-    	}
-
-    // Open a file
-    TBuf<KMaxFileName> fileNameBuf;  
-    
-    iError = TATDriveInfo::CreatePath( fileNameBuf, aFileName, aFilePath, iFileServer );
-                        
-    // Return, if an error occured, and it
-    // is not KErrAlreadyExists
-    if ( iError && iError != KErrAlreadyExists )
-        {
-        iFileServer.Close();
-        return iError;
-        }
-
-    // if file already exist, generat new filename with index
-    GenerateNewFileName( fileNameBuf, aProcessName );
-    
-    // Save the file name for this session
-    CnvUtfConverter::ConvertFromUnicodeToUtf8( iLogFile, fileNameBuf );
-    
-    LOGSTR2( "ATFL > iError(%i)", iError );
-        
-    // If the file does not exist, create it. Write also the version number of
-    // the file at the beginning of the new file
-    if ( iError == KErrNotFound )
-        {
-        iError = iFile.Create( iFileServer, fileNameBuf, EFileWrite | EFileShareAny );
-        if ( !iError )
-            {
-        	// todo
-            }
-        }
-       
-    if ( iError )
-        {
-        iFile.Close();
-        iFileServer.Close();
-        return iError;
-        }
-
-    return iError;
-    }
-
-// -----------------------------------------------------------------------------
-// RATFileLog::GenerateNewFileName
-// Called internally when need generate new file name.
-// -----------------------------------------------------------------------------
-//                     
-void RATFileLog::GenerateNewFileName( TDes& aFileName,
-    const TDesC8& aProcessName )
-    {    
-    LOGSTR1( "ATFL void CATFileLog::GenerateNewFileName()" );
-        
-    // Extension
-    TBuf<KExtensionLength> extension;
-        
-	// Check if file already exist
-	CheckIfFileAlreadyExist( aFileName );
-	if ( iError == KErrNotFound )
-		{
-	    // If not we can use filename without indexing
-		return;
-		}
-	
-	// File with aFileName already exist, let's add index
-	
-	// Parse file extension if exists.
-	ParseExtension( aFileName, extension );
-	
-	// Temp file name
-	TBuf<KMaxFileName> tempName;
-	
-	for ( TInt i = KNameIndexStart; i < KNameIndexEnd; i++ )
-		{
-		tempName.Delete( 0, tempName.MaxLength() );
-		tempName.Format( KFormat, &aFileName, &KLeftBracket, i, &KRightBracket, &extension );
-		LOGSTR2( "ATFL > tempName(%S)", &tempName );
-		// Try to open file
-		CheckIfFileAlreadyExist( tempName );
-		// File does not exist, this index can be used
-		if ( iError == KErrNotFound )
-			{
-			aFileName.Copy( tempName );
-			break;
-			}
-		}
-    }
-
-// -----------------------------------------------------------------------------
-// RATFileLog::ParseExtension
-// Method is used to parse file name extension.
-// -----------------------------------------------------------------------------
-//                     
-void RATFileLog::ParseExtension( 
-    TDes& aFileName, TDes& aExtension )
-    {    
-    LOGSTR2( "ATFL void CATFileLog::ParseExtension(%S)", 
-            &aFileName );
-
-    // Parse current file name
-    TParse parse;
-    // Set up the TParse object 
-    parse.Set( aFileName, NULL, NULL );
-
-    // Tests whether an extension is present.
-    if ( parse.ExtPresent() )
-        {
-        // Gets the extension
-        aExtension.Copy( parse.Ext() );
-        // Remove extension from file name
-        TInt pos( aFileName.Find( aExtension ) );
-        aFileName.Delete( pos, aFileName.Length() );
-        LOGSTR3( "ATFL > aFileName(%S), aExtension(%S)", 
-                &aFileName, &aExtension );
-        }
-    }
-
-// -----------------------------------------------------------------------------
-// RATFileLog::CheckIfFileAlreadyExist
-// Method is used to check that file exists and is valid.
-// -----------------------------------------------------------------------------
-//                     
-void RATFileLog::CheckIfFileAlreadyExist( 
-    const TDes& aFileName )
-    {    
-    LOGSTR2( "ATFL void CATFileLog::CheckIfFileAlreadyExist(%S)", 
-            &aFileName );
-    
-    iError = iFile.Open( iFileServer, aFileName, EFileWrite );
-    LOGSTR2( "ATFL > iError(%i)", iError );
-    }
-
-
-// -----------------------------------------------------------------------------
-// RATFileLog::CloseFsAndFile
-// Internally used for closing a handle to the file server and a file
-// -----------------------------------------------------------------------------
-// 
-void RATFileLog::CloseFsAndFile()
-    {
-    LOGSTR1( "ATFL void CATFileLog::CloseFsAndFile()" );
-    
-    // Close the file    
-    iFile.Close();
-                 
-    // Close the server session and return the error code   
-    iFileServer.Close();
-    }
-
--- a/analyzetool/dynamicmemoryhook/src/analyzetoolmainallocator.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/src/analyzetoolmainallocator.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -22,12 +22,7 @@
 #include "analyzetoolmemoryallocator.h"
 #include "analyzetoolpanics.pan"
 #include "analyzetoolfastlog.h"
-#include "analyzetoolfilelog.h"
 #include <e32svr.h>
-#ifndef __WINSCW__ 
-#include <e32rom.h>
-#endif
-#include <sysutil.h>
 
 
 // CONSTANTS
@@ -35,19 +30,15 @@
 // The name of the memoryhook dll
 _LIT8( KMemoryHook, "AToolMemoryHook.dll" );
 
+// The name of the storage server dll
+_LIT8( KStorageServer, "AToolStorageServerClnt.dll" );
+
 // Length of the callstack address
 const TUint32 KAddressLength = 4;
 
 // Thread count
 const TInt KThreadCount = 1;
 
-// separator that replaces \n character in sw version
-_LIT( KSeparator, "@" );
-// new line character
-_LIT( KNewLine16, "\n" );
-_LIT( KSpace16, " " );
-
-
 // -----------------------------------------------------------------------------
 // RAnalyzeToolMainAllocator::RAnalyzeToolMainAllocator()
 // C++ default constructor can NOT contain any code, that
@@ -55,9 +46,8 @@
 // -----------------------------------------------------------------------------
 //
 RAnalyzeToolMainAllocator::RAnalyzeToolMainAllocator( TBool aNotFirst, 
-    const TFileName& aFileName, const TPath& aFilePath, TUint32 aLogOption, TUint32 aIsDebug,
-    TUint32 aAllocCallStackSize, TUint32 aFreeCallStackSize,
-    const TDesC8& aAtoolVersion, const TDesC8& aApiVersion ) :
+    const TFileName aFileName, TUint32 aLogOption, TUint32 aIsDebug,
+    TUint32 aAllocCallStackSize, TUint32 aFreeCallStackSize ) :
     RAnalyzeToolMemoryAllocator( aNotFirst ),
     iAnalyzeToolOpen( EFalse ),
     iDeviceDriverLoaded( EFalse ),
@@ -72,7 +62,32 @@
 
     // Basic error variable used in method.
     TInt error( KErrNone );
-        
+    
+    // Connect to the storage server if logging mode not fast trace.
+    if ( iLogOption != EATLogToTraceFast )
+        {
+        error = iStorageServer.Connect();
+
+        LOGSTR2( "ATMH Opening RATStorageServer error %i", error );
+    
+        if ( KErrNone == error )
+            {
+            iStorageServerOpen = ETrue;
+            }
+        else
+            {
+            iStorageServerOpen = EFalse;
+            }
+    
+        if ( KErrNone == error )
+            {
+            // Make the storage server handle shared between threads
+            error = iStorageServer.ShareAuto();
+            }
+    
+        LOGSTR2( "ATMH Sharing RATStorageServer error %i", error );
+        }
+    
     // Create mutex for schedule access to shared resources
     error = iMutex.CreateLocal();
 
@@ -120,19 +135,16 @@
         }
     
     // Retrieve the initial process information
-    LogProcessInformation( aFileName, aFilePath, aLogOption, aIsDebug, aAtoolVersion, aApiVersion );
-
-    // log version of ATApp, ATApi, S60 version and ROM checksum
-    LogDeviceInfo();
+    LogProcessInformation( aFileName, aLogOption, aIsDebug );
 
     // Create handler for receiving kernel events
     iEventHandler = new CLibraryEventHandler( iAnalyzeTool,
                                               iCodeblocks,
+                                              iStorageServer,
                                               iProcessId,
                                               iMutex, 
                                               *this,
-                                              aLogOption,
-                                              iLogFile );
+                                              aLogOption);
 
     __ASSERT_ALWAYS( iEventHandler != NULL, AssertPanic( ENoMemory ) );
     }
@@ -185,33 +197,28 @@
             LOGSTR2( "ATMH Unloading ldd error: %i", error );
             }
         }
-    for( TInt i=0; i<iThreadArray.Count(); i++)
-    	{
-        // log thread removed
-		if ( iLogOption == EATLogToTraceFast )
-			{
-			ATFastLogThreadEnded( RProcess().Id().operator TUint(), RThread().Id().operator TUint() ); 
-			}
-		else if ( iLogOption == EATLogToFile )
-			{
-		    iLogFile.ATFileLogThreadEnded( RThread().Id().operator TUint() );		
-			}
-    	}
-
+    
     // Close the thread array
     iThreadArray.Close();
 
-    if ( iLogOption == EATLogToTraceFast )
+    if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
         {
-        LOGSTR1( "ATMH ATFastLogProcessEnded()" );
-        ATFastLogProcessEnded( iProcessId, handleLeakCount );
+        if ( iLogOption == EATLogToTraceFast )
+            {
+            LOGSTR1( "ATMH ATFastLogProcessEnded()" );
+            ATFastLogProcessEnded( iProcessId, handleLeakCount );
+            }
+        else
+            {
+            iStorageServerOpen = EFalse;
+            // Inform that process has ended and close the handle
+            LOGSTR1( "ATMH iStorageServer.LogProcessEnded()" );
+            iStorageServer.LogProcessEnded( iProcessId, handleLeakCount );
+            // Close the handle
+            iStorageServer.Close();
+            }
         }
-    else if ( iLogOption == EATLogToFile )
-    	{
-        iLogFile.ATFileLogProcessEnded( handleLeakCount );
-    	}
     
-
     // Close the mutex
     iMutex.Close();
     }
@@ -280,9 +287,6 @@
 
     // Acquire the mutex
     iMutex.Wait();
-    
-    // get thread ID
-    TUint threadId = RThread().Id();
 
     // Alloc memory from the original allocator
     TAny* p = iAllocator->Alloc( aSize );
@@ -290,86 +294,120 @@
     LOGSTR3( "ATMH RAnalyzeToolMainAllocator::Alloc() - aSize: %i, address: %x", 
             aSize,  (TUint32) p );
 
-
-	TInt error( KErrNone );
-			
-	// Check if eventhandler is started already
-	if ( !iEventHandler->IsStarted() )
-		{
-		// Install the eventhandler if needed
-		InstallEventHandler();
-		}
-	
-	// Reset the callstack
-	iCallStack.Reset();
+    // Don't collect or log data if storage server not open or logging mode fast.
+    if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+        {
+        TInt error( KErrNone );
+        
+        // Check if eventhandler is started already
+        if ( !iEventHandler->IsStarted() )
+            {
+            // Install the eventhandler if needed
+            InstallEventHandler();
+            }
+        
+        // Reset the callstack
+        iCallStack.Reset();
 
-	// If we don't want any call stack to be saved skip the next part
-	if( iAllocMaxCallStack > 0 )
-		{
-		// Find the current thread callstack start address
-		TUint32 stackstart( 0 );
-		TBool found( FindCurrentThreadStack( stackstart ) );
-		LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
-					
-		// Returns the value of the stack pointer at the 
-		// current point in your program.
-		TUint32 _sp;
-		__asm
-			{
-			mov [_sp], esp
-			}
-		
-		// Get process loaded code segments count
-		TInt blocksCount( iCodeblocks.Count() );
-		TUint arrayCounter = 0;
-		
-		// Iterate through callstack to find wanted callstack addresses
-		// - Start: current stack address
-		// - Stop: stack start address(Run-address of user stack)
-		// - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)
-		for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-			{
-			TUint32 addr = (TUint32) *( (TUint32*) i );
-			
-			// Checks is the given address in loaded code memory area.
-			if ( !IsAddressLoadedCode( addr ) )
-				continue;
-			
-			// Iterate through array of code blocks to check if address is in code segment area 
-			for ( TInt j = 0; j < blocksCount; j++ )
-				{
-				// Checks if the given address is in this memory block area
-				if ( iCodeblocks[j].CheckAddress( addr ) )
-					{
-					// To avoid recursive call to ReAlloc specifying granularity
-					// Add address to the callstack
-					iCallStack[arrayCounter] = ( addr );
-					arrayCounter++;
-					break;
-					}
-				}
-			
-			// Checks if the wanted callstack items are gathered
-			if ( arrayCounter == KATMaxCallstackLength ||
-				 arrayCounter == iAllocMaxCallStack )
-				{
-				LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
-				break;
-				}
-			} 
-		}
+        // If we don't want any call stack to be saved skip the next part
+        if( iAllocMaxCallStack > 0 )
+            {
+            // Find the current thread callstack start address
+            TUint32 stackstart( 0 );
+            TBool found( FindCurrentThreadStack( stackstart ) );
+            LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
+            
+            // Returns the value of the stack pointer at the 
+            // current point in your program.
+            TUint32 _sp;
+            __asm
+                {
+                mov [_sp], esp
+                }
+            
+            // Get process loaded code segments count
+            TInt blocksCount( iCodeblocks.Count() );
+            TUint arrayCounter = 0;
+            
+            // Iterate through callstack to find wanted callstack addresses
+            // - Start: current stack address
+            // - Stop: stack start address(Run-address of user stack)
+            // - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)
+            for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+                {
+                TUint32 addr = (TUint32) *( (TUint32*) i );
+                
+                // Checks is the given address in loaded code memory area.
+                if ( !IsAddressLoadedCode( addr ) )
+                    continue;
+                
+                // Iterate through array of code blocks to check if address is in code segment area 
+                for ( TInt j = 0; j < blocksCount; j++ )
+                    {
+                    // Checks if the given address is in this memory block area
+                    if ( iCodeblocks[j].CheckAddress( addr ) )
+                        {
+                        // To avoid recursive call to ReAlloc specifying granularity
+                        // Add address to the callstack
+                        iCallStack[arrayCounter] = ( addr );
+                        arrayCounter++;
+                        break;
+                        }
+                    }
+                
+                // Checks if the wanted callstack items are gathered
+                if ( arrayCounter == KATMaxCallstackLength ||
+                     arrayCounter == iAllocMaxCallStack )
+                    {
+                    LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
+                    break;
+                    }
+                } 
+            }
 
-	// Log the memory allocation information
-	if ( iLogOption == EATLogToTraceFast )
-		{
-		// Using fast mode.
-		ATFastLogMemoryAllocated( iProcessId, (TUint32) p , iCallStack, aSize, threadId );
-		} 
-	else if ( iLogOption == EATLogToFile )
-		{
-		iLogFile.ATFileLogMemoryAllocated( (TUint32) p , iCallStack, aSize, threadId );
-		}
-	
+        // Log the memory allocation information
+        if ( iLogOption == EATLogToTraceFast )
+            {
+            // Using fast mode.
+            ATFastLogMemoryAllocated( iProcessId, (TUint32) p , iCallStack, aSize );
+            }
+        else
+            {
+            // Using storage server.
+            error = iStorageServer.LogMemoryAllocated( (TUint32) p,
+                                                       iCallStack,
+                                                       aSize );
+            if ( KErrNone != error )
+                {
+                switch ( error )
+                    {
+                    case KErrNoMemory:
+                        {
+                        LOGSTR1( "ATMH RAnalyzeToolMainAllocator::Alloc() - KErrNoMemory case"  );
+                        // Check if eventhandler is active
+                        if ( iEventHandler->IsActive() )
+                            {
+                            // Cancel iEventHandler because not needed anymore
+                            iEventHandler->Cancel();
+                            }
+                        if ( iStorageServerOpen )
+                            {
+                            // Close storage server
+                            iStorageServerOpen = EFalse;
+                            LOGSTR1( "ATMH RAnalyzeToolMainAllocator::Alloc() - close iStorageServer"  );
+                            iStorageServer.Close();
+                            }
+                        break;
+                        }
+                    default:
+                        {
+                        LOGSTR2( "ATMH LogMemoryAllocated error %i", error );
+                        break;
+                        }
+                    }
+                }
+            }
+        }
     // Release the mutex
     iMutex.Signal();
 
@@ -388,9 +426,6 @@
 
     // acquire the mutex
     iMutex.Wait();
-    
-    // get thread ID
-    TUint threadId = RThread().Id();
 
     // Alloc memory from the original allocator
     TAny* p = iAllocator->Alloc( aSize );
@@ -398,77 +433,113 @@
     LOGSTR3( "ATMH RAnalyzeToolMainAllocator::Alloc() - aSize: %i, address: %x", 
             aSize,  (TUint32) p );
 
-
-	// Check if eventhandler is active already
-	// IsActive might return false value if a tested software has created many
-	// threads which install own CActiveScheduler.
-	if ( !iEventHandler->IsStarted() )
-		{
-		// Install the eventhandler if needed
-		InstallEventHandler();
-		}
-	
-	// Reset the callstack
-	iCallStack.Reset();
-	
-	// If we don't want any call stack to be saved skip the next part
-	if( iAllocMaxCallStack > 0 )
-		{
-		// Find the current thread callstack start address
-		TUint32 stackstart( 0 );
-		TBool found( FindCurrentThreadStack( stackstart ) );
-		LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
-		
-		// Get process loaded code segments count
-		TInt blocksCount( iCodeblocks.Count() );            
-		TUint arrayCounter = 0;
-		
-		// Iterate through callstack to find wanted callstack addresses
-		// - Start: current stack address(__current_sp(): Returns the value of the 
-		//      stack pointer at the current point in your program.)
-		// - Stop: stack start address(Run-address of user stack)
-		// - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)
-		for ( TUint32 i = __current_sp(); i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-			{
-			TUint32 addr = (TUint32) *( (TUint32*) i );
-			
-			// Checks is the given address in loaded code memory area.
-			if ( !IsAddressLoadedCode( addr ) )
-				continue;
-			
-			// Iterate through array of code blocks to check if address is in code segment area 
-			for ( TInt j = 0; j < blocksCount; j++ )
-				{
-				// Checks if the given address is in this memory block area
-				if ( iCodeblocks[j].CheckAddress( addr ) )
-					{
-					// To avoid recursive call to ReAlloc specifying granularity
-					// Add address to the callstack
-					iCallStack[arrayCounter] = ( addr );
-					arrayCounter++;
-					break;
-					}
-				}
-			
-			// Checks if the wanted callstack items are gathered
-			if ( arrayCounter == KATMaxCallstackLength ||
-				 arrayCounter == iAllocMaxCallStack )
-				{
-				LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
-				break;
-				}
-			}
-		}
-	// Log the memory allocation information
-	if ( iLogOption == EATLogToTraceFast )
-		{
-		// Using fast mode.
-		ATFastLogMemoryAllocated( iProcessId, (TUint32) p, iCallStack, aSize, threadId );
-		}
-	else if ( iLogOption == EATLogToFile )
-		{
-		iLogFile.ATFileLogMemoryAllocated( (TUint32) p , iCallStack, aSize, threadId );
-		}
+    TInt error( KErrNone );
+    
+    if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+        {
+        // Check if eventhandler is active already
+        // IsActive might return false value if a tested software has created many
+        // threads which install own CActiveScheduler.
+        if ( !iEventHandler->IsStarted() )
+            {
+            // Install the eventhandler if needed
+            InstallEventHandler();
+            }
+        
+        // Reset the callstack
+        iCallStack.Reset();
+        
+        // If we don't want any call stack to be saved skip the next part
+        if( iAllocMaxCallStack > 0 )
+            {
+            // Find the current thread callstack start address
+            TUint32 stackstart( 0 );
+            TBool found( FindCurrentThreadStack( stackstart ) );
+            LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
+            
+            // Get process loaded code segments count
+            TInt blocksCount( iCodeblocks.Count() );            
+            TUint arrayCounter = 0;
+            
+            // Iterate through callstack to find wanted callstack addresses
+            // - Start: current stack address(__current_sp(): Returns the value of the 
+            //      stack pointer at the current point in your program.)
+            // - Stop: stack start address(Run-address of user stack)
+            // - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)
+            for ( TUint32 i = __current_sp(); i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+                {
+                TUint32 addr = (TUint32) *( (TUint32*) i );
+                
+                // Checks is the given address in loaded code memory area.
+                if ( !IsAddressLoadedCode( addr ) )
+                    continue;
+                
+                // Iterate through array of code blocks to check if address is in code segment area 
+                for ( TInt j = 0; j < blocksCount; j++ )
+                    {
+                    // Checks if the given address is in this memory block area
+                    if ( iCodeblocks[j].CheckAddress( addr ) )
+                        {
+                        // To avoid recursive call to ReAlloc specifying granularity
+                        // Add address to the callstack
+                        iCallStack[arrayCounter] = ( addr );
+                        arrayCounter++;
+                        break;
+                        }
+                    }
+                
+                // Checks if the wanted callstack items are gathered
+                if ( arrayCounter == KATMaxCallstackLength ||
+                     arrayCounter == iAllocMaxCallStack )
+                    {
+                    LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
+                    break;
+                    }
+                }
+            }
+        // Log the memory allocation information
+        if ( iLogOption == EATLogToTraceFast )
+            {
+            // Using fast mode.
+            ATFastLogMemoryAllocated( iProcessId, (TUint32) p, iCallStack, aSize );
+            }
+        else
+            {
+            // Using storage server.
+            error = iStorageServer.LogMemoryAllocated( (TUint32) p,
+                                                       iCallStack,
+                                                       aSize );
+            if ( KErrNone != error )
+                {
+                switch ( error )
+                    {
+                    case KErrNoMemory:
+                        {
+                        LOGSTR1( "ATMH RAnalyzeToolMainAllocator::Alloc() - KErrNoMemory case"  );
+                        // Check if eventhandler is active
+                        if ( iEventHandler->IsActive() )
+                            {
+                            // Cancel ieventhandler because not needed anymore
+                            iEventHandler->Cancel();
+                            }
+                        if ( iStorageServerOpen )
+                            {
+                            // Close storage server
+                            iStorageServerOpen = EFalse;
+                            LOGSTR1( "ATMH RAnalyzeToolMainAllocator::Alloc() - close iStorageServer"  );
+                            iStorageServer.Close();
+                            }
+                        break;
+                        }
+                    default:
+                        {
+                        LOGSTR2( "ATMH LogMemoryAllocated error %i", error );
+                        break;
+                        }
+                    }
+                }
+            }
+        }
     
     // Release the mutex
     iMutex.Signal();
@@ -490,81 +561,87 @@
     // Acquire the mutex
     iMutex.Wait();
     
-    // get thread ID
-    TUint threadId = RThread().Id();
-
-	// Reset the callstack
-	iFreeCallStack.Reset();
-	
-	// Check if trace logging mode
-	// Also if we don't want any call stack to be stored skip the next part
-	if ( iFreeMaxCallStack > 0 )
-		{
-		// Find the current thread callstack start address
-		TUint32 stackstart( 0 );
-		TBool found( FindCurrentThreadStack( stackstart ) );
-		LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
-		TUint32 _sp;
-		
-		// Returns the value of the stack pointer at the 
-		// current point in your program.
-		#ifdef __WINS__
-			__asm
-				{
-				mov [_sp], esp
-				}
-		#else
-			_sp = __current_sp();
-		#endif
-		
-		// Get process loaded code segments count
-		TInt blocksCount( iCodeblocks.Count() );
-		TUint arrayCounter = 0;
-		
-		// Iterate through callstack to find wanted callstack addresses
-		// - Start: current stack address
-		// - Stop: stack start address(Run-address of user stack)
-		// - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)            
-		for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-			{
-			TUint32 addr = (TUint32) *( (TUint32*) i );
-			// Checks is the given address in loaded code memory area.
-			if ( ! IsAddressLoadedCode( addr ) )
-				continue;
-			
-			// Iterate through array of code blocks to check if address is in code segment area 
-			for ( TInt j = 0; j < blocksCount; j++ )
-				{
-				// Checks if the given address is in this memory block area
-				if ( iCodeblocks[j].CheckAddress( addr ) )
-					{
-					// To avoid recursive call to ReAlloc specifying granularity
-					// Add address to the callstack
-					iFreeCallStack[arrayCounter] = addr;
-					arrayCounter++;
-					break;
-					}
-				}
-			// Checks if the wanted callstack items are gathered
-			if ( arrayCounter == KATMaxFreeCallstackLength ||
-				 arrayCounter == iFreeMaxCallStack )
-				{
-				break;
-				}
-			}
-		LOGSTR2( "ATMH > iFreeCallStack count ( %i )", arrayCounter );
-		}
-	// Log the memory free information.
-	if ( iLogOption == EATLogToTraceFast )
-		{
-		// Using fast mode.
-		ATFastLogMemoryFreed( iProcessId, (TUint32) aPtr, iFreeCallStack, threadId );
-		}
-    else if ( iLogOption == EATLogToFile )
-    	{
-        iLogFile.ATFileLogMemoryFreed( (TUint32) aPtr, iFreeCallStack, threadId );
-    	}
-     
+    if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+        {
+        // Reset the callstack
+        iFreeCallStack.Reset();
+        
+        // Check if trace logging mode
+        // Also if we don't want any call stack to be stored skip the next part
+        if ( (iLogOption == EATUseDefault || iLogOption == EATLogToTrace || iLogOption == EATLogToTraceFast )
+                && iFreeMaxCallStack > 0 )
+            {
+            // Find the current thread callstack start address
+            TUint32 stackstart( 0 );
+            TBool found( FindCurrentThreadStack( stackstart ) );
+            LOGSTR3( "ATMH > stackstart: %x , found = %i", stackstart, found );
+            TUint32 _sp;
+            
+            // Returns the value of the stack pointer at the 
+            // current point in your program.
+            #ifdef __WINS__
+                __asm
+                    {
+                    mov [_sp], esp
+                    }
+            #else
+                _sp = __current_sp();
+            #endif
+            
+            // Get process loaded code segments count
+            TInt blocksCount( iCodeblocks.Count() );
+            TUint arrayCounter = 0;
+            
+            // Iterate through callstack to find wanted callstack addresses
+            // - Start: current stack address
+            // - Stop: stack start address(Run-address of user stack)
+            // - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)            
+            for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+                {
+                TUint32 addr = (TUint32) *( (TUint32*) i );
+                // Checks is the given address in loaded code memory area.
+                if ( ! IsAddressLoadedCode( addr ) )
+                    continue;
+                
+                // Iterate through array of code blocks to check if address is in code segment area 
+                for ( TInt j = 0; j < blocksCount; j++ )
+                    {
+                    // Checks if the given address is in this memory block area
+                    if ( iCodeblocks[j].CheckAddress( addr ) )
+                        {
+                        // To avoid recursive call to ReAlloc specifying granularity
+                        // Add address to the callstack
+                        iFreeCallStack[arrayCounter] = addr;
+                        arrayCounter++;
+                        break;
+                        }
+                    }
+                // Checks if the wanted callstack items are gathered
+                if ( arrayCounter == KATMaxFreeCallstackLength ||
+                     arrayCounter == iFreeMaxCallStack )
+                    {
+                    break;
+                    }
+                }
+            LOGSTR2( "ATMH > iFreeCallStack count ( %i )", arrayCounter );
+            }
+        // Log the memory free information.
+        if ( iLogOption == EATLogToTraceFast )
+            {
+            // Using fast mode.
+            ATFastLogMemoryFreed( iProcessId, (TUint32) aPtr, iFreeCallStack );
+            }
+        else
+            {
+            // Using storage server.
+            TInt err( iStorageServer.LogMemoryFreed( (TUint32) aPtr, iFreeCallStack ) );
+            if ( err != KErrNone )
+                {
+                LOGSTR2( "ATMH > LogMemoryFreed err( %i )", err );
+                }
+            }
+        }
+    
     // Free the memory using original allocator
     iAllocator->Free( aPtr );
 
@@ -605,15 +682,6 @@
             LOGSTR2( "ATMH Thread stack size:    %x", params().iStackSize );
             iThreadArray.Append( TThreadStack( RThread().Id(),
                     params().iStackAddress + params().iStackSize ) );
-            if ( iLogOption == EATLogToTraceFast )
-            	{
-                // log thread added
-                ATFastLogThreadStarted( RProcess().Id().operator TUint() , RThread().Id().operator TUint() ); 
-            	}
-            else if ( iLogOption == EATLogToFile )
-            	{
-                iLogFile.ATFileLogThreadStarted( RThread().Id().operator TUint() );
-            	}
             }
         }
 
@@ -650,15 +718,6 @@
             {
             // Remove the thread
             iThreadArray.Remove( i );
-            if ( iLogOption == EATLogToTraceFast )
-            	{
-                // log thread removed
-                ATFastLogThreadEnded( RProcess().Id().operator TUint(), RThread().Id().operator TUint() ); 
-            	}
-            else if ( iLogOption == EATLogToFile )
-            	{
-                iLogFile.ATFileLogThreadEnded( RThread().Id().operator TUint() );
-            	}
             LOGSTR1( "ATMH RAnalyzeToolMainAllocator::Close() - thread removed" );
             break;
             }
@@ -681,9 +740,6 @@
 
     // Acquire the mutex
     iMutex.Wait();
-    
-    // get thread ID
-    TUint threadId = RThread().Id();
 
     // Realloc the memory using original allocator
     TAny* ptr = iAllocator->ReAlloc( aPtr, aSize, aMode );
@@ -696,78 +752,142 @@
         LOGSTR3( "ATMH RAnalyzeToolMainAllocator::ReAlloc() - aSize: %i, aMode: %i", 
                 aSize, aMode );
       
-
-	TInt error( KErrNone );
-	TUint arrayCounter = 0;
-	
-	// Reset the callstack
-	iReCallStack.Reset();
-	
-	// If we don't want any call stack to be saved skip the next part
-	if( iAllocMaxCallStack > 0 )
-		{
-		// Find the current thread callstack start address
-		TUint32 stackstart( 0 );
-		TBool found( FindCurrentThreadStack( stackstart ) );
-		LOGSTR3( "ATMH > stackstart: %x , find = %i", stackstart, found );
-
-		// Returns the value of the stack pointer at the 
-		// current point in your program.
-		TUint32 _sp( 0 );
-		__asm
-			{
-			mov [_sp], esp
-			}
-		
-		// Get process loaded code segments count
-		TInt blocksCount( iCodeblocks.Count() );
-		
-		// Iterate through callstack to find wanted callstack addresses
-		// - Start: current stack address
-		// - Stop: stack start address(Run-address of user stack)
-		// - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)                
-		for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-			{
-			TUint32 addr = (TUint32) *( (TUint32*) i );
-			// Checks is the given address in loaded code memory area.
-			if ( ! IsAddressLoadedCode( addr ) )
-				continue;
-			
-			// Iterate through array of code blocks to check if address is in code segment area 
-			for ( TInt j = 0; j < blocksCount; j++ )
-				{
-				// Checks if the given address is in this memory block area
-				if ( iCodeblocks[j].CheckAddress( addr ) )
-					{
-					// To avoid recursive call to ReAlloc specifying granularity
-					// Add address to the callstack
-					iReCallStack[arrayCounter] = addr;
-					arrayCounter++;
-					break;
-					}
-				}
-			// Checks if the wanted callstack items are gathered
-			if ( arrayCounter == KATMaxCallstackLength || 
-				 arrayCounter == iAllocMaxCallStack )
-				{
-				LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
-				break;
-				}
-			}
-		}
-	
-	
-	// Log the memory reallocation information
-	if ( iLogOption == EATLogToTraceFast )
-		{
-		// Using fast logging mode.
-		ATFastLogMemoryReallocated( iProcessId, (TUint32) aPtr, (TUint32) ptr, iReCallStack, aSize, threadId );
-		}
-	else if ( iLogOption == EATLogToFile )
-		{
-		iLogFile.ATFileLogMemoryReallocated( (TUint32) aPtr, (TUint32) ptr, iReCallStack, aSize, threadId );
-		}
-       
+        // Don't collect or log data if storage server not open or logging mode is not fast.
+        if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+            {
+            TInt error( KErrNone );
+            TUint arrayCounter = 0;
+            
+            // Reset the callstack
+            iReCallStack.Reset();
+            
+            // If we don't want any call stack to be saved skip the next part
+            if( iAllocMaxCallStack > 0 )
+                {
+                // Find the current thread callstack start address
+                TUint32 stackstart( 0 );
+                TBool found( FindCurrentThreadStack( stackstart ) );
+                LOGSTR3( "ATMH > stackstart: %x , find = %i", stackstart, found );
+    
+                // Returns the value of the stack pointer at the 
+                // current point in your program.
+                TUint32 _sp( 0 );
+                __asm
+                    {
+                    mov [_sp], esp
+                    }
+                
+                // Get process loaded code segments count
+                TInt blocksCount( iCodeblocks.Count() );
+                
+                // Iterate through callstack to find wanted callstack addresses
+                // - Start: current stack address
+                // - Stop: stack start address(Run-address of user stack)
+                // - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)                
+                for ( TUint32 i = _sp; i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+                    {
+                    TUint32 addr = (TUint32) *( (TUint32*) i );
+                    // Checks is the given address in loaded code memory area.
+                    if ( ! IsAddressLoadedCode( addr ) )
+                        continue;
+                    
+                    // Iterate through array of code blocks to check if address is in code segment area 
+                    for ( TInt j = 0; j < blocksCount; j++ )
+                        {
+                        // Checks if the given address is in this memory block area
+                        if ( iCodeblocks[j].CheckAddress( addr ) )
+                            {
+                            // To avoid recursive call to ReAlloc specifying granularity
+                            // Add address to the callstack
+                            iReCallStack[arrayCounter] = addr;
+                            arrayCounter++;
+                            break;
+                            }
+                        }
+                    // Checks if the wanted callstack items are gathered
+                    if ( arrayCounter == KATMaxCallstackLength || 
+                         arrayCounter == iAllocMaxCallStack )
+                        {
+                        LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
+                        break;
+                        }
+                    }
+                }
+            
+            // No need to report free if the aPtr was NULL
+            if ( aPtr != NULL )
+                {
+                // Reset the free callstack
+                iFreeCallStack.Reset();
+                
+                // Check that logging mode is trace/trace fast so we use free call stack 
+                // and call stack size bigger than zero
+                if ( ( iLogOption == EATUseDefault || iLogOption == EATLogToTrace || iLogOption == EATLogToTraceFast ) && iFreeMaxCallStack > 0 )
+                    {
+                    for ( TInt i = 0; i < arrayCounter; i++ )
+                        {
+                        if ( i == KATMaxFreeCallstackLength || i == iFreeMaxCallStack )
+                            {
+                            break;
+                            }
+                        iFreeCallStack[i] = iReCallStack[i];
+                        }
+                    }
+                // Try to remove old address from the storage server's
+                // leak array. If found. it's removed from the array because system frees
+                // old address directly in the RHeap in ReAlloc case.
+                if ( iLogOption == EATLogToTraceFast )
+                    {
+                    ATFastLogMemoryFreed( iProcessId, (TUint32) aPtr, iFreeCallStack );
+                    }
+                else
+                    {
+                    iStorageServer.LogMemoryFreed( (TUint32) aPtr, iFreeCallStack );
+                    }
+                }
+            // Log the memory allocation information
+            if ( iLogOption == EATLogToTraceFast )
+                {
+                // Using fast logging mode.
+                ATFastLogMemoryAllocated( iProcessId, (TUint32) ptr, iReCallStack, aSize );
+                }
+            else
+                {
+                // Using storage server.
+                error = iStorageServer.LogMemoryAllocated( (TUint32) ptr,
+                                                           iReCallStack,
+                                                           aSize );
+                if ( KErrNone != error )
+                    {
+                    switch ( error )
+                        {
+                        case KErrNoMemory:
+                            {
+                            LOGSTR1( "ATMH RAnalyzeToolMainAllocator::ReAlloc() - KErrNoMemory case"  );
+                            // Check if eventhandler is active
+                            if ( iEventHandler->IsActive() )
+                                {
+                                // Cancel iEventHandler because not needed anymore
+                                iEventHandler->Cancel();
+                                }
+                            if ( iStorageServerOpen )
+                                {
+                                // Close storage server
+                                iStorageServerOpen = EFalse;
+                                LOGSTR1( "ATMH RAnalyzeToolMainAllocator::ReAlloc() - close iStorageServer"  );
+                                iStorageServer.Close();
+                                }
+                            break;
+                            }
+                        default:
+                            {
+                            LOGSTR2( "ATMH LogMemoryAllocated error %i", error );
+                            break;
+                            }
+                        }
+                    }
+                }
+            }
         }
     
     // Release the mutex
@@ -791,12 +911,10 @@
     // Acquire the mutex
     iMutex.Wait();
 
-    // get thread ID
-    TUint threadId = RThread().Id();
-    
     // Realloc the memory using original allocator
     TAny* ptr = iAllocator->ReAlloc( aPtr, aSize, aMode );
     
+    TInt error( KErrNone );
     TUint arrayCounter = 0;
     
     // NULL addresses are not in a process under test
@@ -807,65 +925,136 @@
         LOGSTR3( "ATMH RAnalyzeToolMainAllocator::ReAlloc() - aSize: %i, aMode: %i", 
                 aSize, aMode );
  
-		// Reset the callstack
-		iReCallStack.Reset();
-		
-		// If we don't want any call stack to be saved skip the next part
-		if( iAllocMaxCallStack > 0 )
-			{
-			// Find the current thread callstack start address
-			TUint32 stackstart( 0 );
-			TBool found( FindCurrentThreadStack( stackstart ) );
-			LOGSTR3( "ATMH > stackstart: %x , find = %i", stackstart, found );
-			
-			// Get process loaded code segments count
-			TInt blocksCount( iCodeblocks.Count() );
-			
-			// Iterate through callstack to find wanted callstack addresses
-			// - Start: current stack address(__current_sp(): Returns the value of the 
-			//      stack pointer at the current point in your program.)
-			// - Stop: stack start address(Run-address of user stack)
-			// - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)
-			for ( TUint32 i = __current_sp(); i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
-				{
-				TUint32 addr = (TUint32) *( (TUint32*) i );
-				
-				// Checks is the given address in loaded code memory area.
-				if ( !IsAddressLoadedCode( addr ) )
-					continue;
-							
-				// Iterate through array of code blocks to check if address is in code segment area 
-				for ( TInt j = 0; j < blocksCount; j++ )
-					{
-					// Checks if the given address is in this memory block area
-					if ( iCodeblocks[j].CheckAddress( addr ) )
-						{
-						// To avoid recursive call to ReAlloc specifying granularity
-						// Add address to the callstack
-						iReCallStack[arrayCounter] = ( addr );
-						arrayCounter++;
-						break;
-						}
-					}
-				// Checks if the wanted callstack items are gathered
-				if ( arrayCounter == KATMaxCallstackLength || 
-					 arrayCounter == iAllocMaxCallStack )
-					{
-					LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
-					break;
-					}
-				}
-			}
-		
-		if ( iLogOption == EATLogToTraceFast )
-			{
-			// Using fast logging mode.
-			ATFastLogMemoryReallocated( iProcessId, (TUint32) aPtr, (TUint32) ptr, iReCallStack, aSize, threadId );
-			}
-		else if ( iLogOption == EATLogToFile )
-			{
-			iLogFile.ATFileLogMemoryReallocated( (TUint32) aPtr, (TUint32) ptr, iReCallStack, aSize, threadId );
-			} 
+        // Don't collect or log data if storage server not open or logging mode is not fast.
+        if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+            {
+            // Reset the callstack
+            iReCallStack.Reset();
+            
+            // If we don't want any call stack to be saved skip the next part
+            if( iAllocMaxCallStack > 0 )
+                {
+                // Find the current thread callstack start address
+                TUint32 stackstart( 0 );
+                TBool found( FindCurrentThreadStack( stackstart ) );
+                LOGSTR3( "ATMH > stackstart: %x , find = %i", stackstart, found );
+                
+                // Get process loaded code segments count
+                TInt blocksCount( iCodeblocks.Count() );
+                
+                // Iterate through callstack to find wanted callstack addresses
+                // - Start: current stack address(__current_sp(): Returns the value of the 
+                //      stack pointer at the current point in your program.)
+                // - Stop: stack start address(Run-address of user stack)
+                // - Add: address length(The word size in the current system is 32 bits, which is 4 bytes)
+                for ( TUint32 i = __current_sp(); i < stackstart; i = i + KAddressLength )//lint !e1055 !e526 !e628 !e348
+                    {
+                    TUint32 addr = (TUint32) *( (TUint32*) i );
+                    
+                    // Checks is the given address in loaded code memory area.
+                    if ( !IsAddressLoadedCode( addr ) )
+                        continue;
+                                
+                    // Iterate through array of code blocks to check if address is in code segment area 
+                    for ( TInt j = 0; j < blocksCount; j++ )
+                        {
+                        // Checks if the given address is in this memory block area
+                        if ( iCodeblocks[j].CheckAddress( addr ) )
+                            {
+                            // To avoid recursive call to ReAlloc specifying granularity
+                            // Add address to the callstack
+                            iReCallStack[arrayCounter] = ( addr );
+                            arrayCounter++;
+                            break;
+                            }
+                        }
+                    // Checks if the wanted callstack items are gathered
+                    if ( arrayCounter == KATMaxCallstackLength || 
+                         arrayCounter == iAllocMaxCallStack )
+                        {
+                        LOGSTR2( "ATMH > Wanted CallStack items ready( %i )", arrayCounter );
+                        break;
+                        }
+                    }
+                }
+            
+            // No need to report free if the aPtr was NULL
+            if ( aPtr != NULL )
+                {
+                // Reset the free callstack
+                iFreeCallStack.Reset();
+                
+                // Check that logging mode is trace/trace fast so we use free call stack 
+                // and call stack size bigger than zero
+                if ( (iLogOption == EATUseDefault || iLogOption == EATLogToTrace || iLogOption == EATLogToTraceFast )
+                        && iFreeMaxCallStack > 0 )
+                    {
+                    for ( TInt i = 0; i < arrayCounter; i++ )
+                        {
+                        if ( i == KATMaxFreeCallstackLength || i == iFreeMaxCallStack )
+                            {
+                            break;
+                            }
+                        iFreeCallStack[i] = ( iReCallStack[i] );
+                        }
+                    }
+                
+                // Try to remove old address from the storage server's
+                // leak array. If found. it's removed from the array because system frees
+                // old address directly in the RHeap in ReAlloc case.
+                if ( iLogOption == EATLogToTraceFast )
+                    {
+                    ATFastLogMemoryFreed( iProcessId, (TUint32) aPtr, iFreeCallStack );
+                    }
+                else
+                    {
+                    iStorageServer.LogMemoryFreed( (TUint32) aPtr, iFreeCallStack );
+                    }
+                }
+            
+            // Log the memory allocation information
+            if ( iLogOption == EATLogToTraceFast )
+                {
+                // Using fast logging mode.
+                ATFastLogMemoryAllocated( iProcessId, (TUint32) ptr, iReCallStack, aSize );
+                }
+            else
+                {
+                // Using storage server.
+                error = iStorageServer.LogMemoryAllocated( (TUint32) ptr,
+                                                        iReCallStack,
+                                                        aSize );
+                if ( KErrNone != error )
+                    {
+                    switch ( error )
+                        {
+                        case KErrNoMemory:
+                            {
+                            LOGSTR1( "ATMH RAnalyzeToolMainAllocator::ReAlloc() - KErrNoMemory case"  );
+                            // Check if eventhandler is active
+                            if ( iEventHandler->IsActive() )
+                                {
+                                // Cancel iEventHandler because not needed anymore
+                                iEventHandler->Cancel();
+                                }
+                            if ( iStorageServerOpen )
+                                {
+                                // Close storage server
+                                iStorageServerOpen = EFalse;
+                                LOGSTR1( "ATMH RAnalyzeToolMainAllocator::ReAlloc() - close iStorageServer"  );
+                                iStorageServer.Close();
+                                }
+                            break;
+                            }
+                        default:
+                            {
+                            LOGSTR2( "ATMH LogMemoryAllocated error %i", error );
+                            break;
+                            }
+                        }
+                    }
+                }
+            }
         }
 
     // Release the mutex
@@ -1060,15 +1249,6 @@
             {
             // Remove the thread
             iThreadArray.Remove( i );
-            if ( iLogOption == EATLogToTraceFast )
-            	{
-                // log thread removed
-                ATFastLogThreadEnded( RProcess().Id().operator TUint(), aThreadId ); 
-            	}
-            else if ( iLogOption == EATLogToFile )
-				{
-                iLogFile.ATFileLogThreadEnded( aThreadId );
-				}
             LOGSTR1( "ATMH > thread removed" );
             break;
             }
@@ -1105,8 +1285,8 @@
 // Retrieve and log the process initial information
 // -----------------------------------------------------------------------------
 //
-void RAnalyzeToolMainAllocator::LogProcessInformation( const TFileName& aFileName, const TPath& aFilePath,
-    TUint32 aLogOption, TUint32 aIsDebug, const TDesC8& aAtoolVersion, const TDesC8& aApiVersion )
+void RAnalyzeToolMainAllocator::LogProcessInformation( const TFileName aFileName,
+    TUint32 aLogOption, TUint32 aIsDebug )
     {
     LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation()" );
     
@@ -1129,38 +1309,31 @@
         // Append thread to array of the users of this allocator
         error = iThreadArray.Append(
         TThreadStack( RThread().Id(), params().iStackAddress + params().iStackSize) );
-        
 
         __ASSERT_ALWAYS( KErrNone == error, AssertPanic( ECantAppendToTheArray ) );
-        
-        // Using fast logging mode.
-        if ( iLogOption == EATLogToTraceFast )
-            {          
-            LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - ATFastLogProcessStarted() #1" );
-            // Log process information
-            ATFastLogProcessStarted( params().iProcessName, iProcessId, aIsDebug, aAtoolVersion, aApiVersion );    
-            // log thread added
-            ATFastLogThreadStarted( iProcessId, RThread().Id().operator TUint() );
-            }
-        else if ( iLogOption == EATLogToFile )
-            {
-            // Open a file server session and a file.
-            error = iLogFile.OpenFsAndFile( aFileName, aFilePath, params().iProcessName );
 
-            // Return without logging, if an error occured
-            if ( error != KErrNone )
+        // Log process information
+        if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
+            {
+            if ( iLogOption == EATLogToTraceFast )
                 {
-                // TODO
+                // Using fast logging mode.
+                LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - ATFastLogProcessStarted() #1" );
+                ATFastLogProcessStarted( params().iProcessName, iProcessId, aIsDebug );                
                 }
-            
-            //if everything is ok, add file version in the begining of file
-            iLogFile.ATFileLogVersion();
-            //log process start
-            iLogFile.ATFileLogProcessStarted( params().iProcessName, iProcessId, aIsDebug, aAtoolVersion, aApiVersion ); 
-            // log thread added
-            iLogFile.ATFileLogThreadStarted( RThread().Id().operator TUint() );
+            else
+                {
+                // Using storage server.
+                LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - iStorageServerOpen #1" );
+                error = iStorageServer.LogProcessStarted(
+                        aFileName,
+                        params().iProcessName,
+                        iProcessId, 
+                        aLogOption, 
+                        aIsDebug );
+                }
             }
-                      
+
         LOGSTR2( "ATMH LogProcessStarted error %i", error );
 
         // Iterate through process codesegments
@@ -1176,27 +1349,31 @@
             if ( KErrNone == error )
                 {
                 // Don't log AnalyzeTool libraries
-                if ( 0 != codeinfo().iFullName.CompareC( KMemoryHook ) )
+                if ( 0 != codeinfo().iFullName.CompareC( KMemoryHook ) &&
+                     0 != codeinfo().iFullName.CompareC( KStorageServer ) )
                     {
                     // Log the loaded codesegment(s)
-
-                    if ( iLogOption == EATLogToTraceFast )
+                    if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
                         {
-                        // Using fast logging mode.
-                        LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - ATFastLogDllLoaded() #2" );
-                        ATFastLogDllLoaded( iProcessId,
-                                codeinfo().iFullName,
-                                codeinfo().iRunAddress,
-                                codeinfo().iRunAddress + codeinfo().iSize );
+                        if ( iLogOption == EATLogToTraceFast )
+                            {
+                            // Using fast logging mode.
+                            LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - ATFastLogDllLoaded() #2" );
+                            ATFastLogDllLoaded( iProcessId,
+                                    codeinfo().iFullName,
+                                    codeinfo().iRunAddress,
+                                    codeinfo().iRunAddress + codeinfo().iSize );
+                            }
+                        else
+                            {
+                            // Using storage server.
+                            LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - iStorageServerOpen #2" );
+                            error = iStorageServer.LogDllLoaded(
+                                    codeinfo().iFullName,
+                                    codeinfo().iRunAddress,
+                                    codeinfo().iRunAddress + codeinfo().iSize );
+                            }
                         }
-                    else if ( iLogOption == EATLogToFile )
-						{
-                        iLogFile.ATFileLogDllLoaded( 
-								codeinfo().iFullName,
-                                codeinfo().iRunAddress,
-                                codeinfo().iRunAddress + codeinfo().iSize );
-						}
-                    
 
                     LOGSTR2( "ATMH LogDllLoaded error %i", error );
 
@@ -1226,24 +1403,29 @@
             if ( KErrNone == error )
                 {
                 // Log the loaded dynamic codesegment(s)
-
-                if ( iLogOption == EATLogToTraceFast )
+                if ( iStorageServerOpen || iLogOption == EATLogToTraceFast )
                     {
-                    // Using fast logging mode.
-                    LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - - ATFastLogDllLoaded()#3" );
-                    ATFastLogDllLoaded( iProcessId,
-                            info().iLibraryName,
-                            info().iRunAddress,
-                            info().iRunAddress + info().iSize );
+                    if ( iLogOption == EATLogToTraceFast )
+                        {
+                        // Using fast logging mode.
+                        LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - - ATFastLogDllLoaded()#3" );
+                        ATFastLogDllLoaded( iProcessId,
+                                info().iLibraryName,
+                                info().iRunAddress,
+                                info().iRunAddress + info().iSize );
+                        }
+                    else
+                        {
+                        // Using storage server.
+                        LOGSTR1( "ATMH RAnalyzeToolMainAllocator::LogProcessInformation() - iStorageServerOpen #3" );
+                        error = iStorageServer.LogDllLoaded(
+                                info().iLibraryName,
+                                info().iRunAddress,
+                                info().iRunAddress + info().iSize );
+                        }
                     }
-                else if ( iLogOption == EATLogToFile )
-                	{
-                	iLogFile.ATFileLogDllLoaded( 
-                			info().iLibraryName,
-                			info().iRunAddress,
-                			info().iRunAddress + info().iSize );
-                	}
-     
+
+
                 LOGSTR2( "ATMH LogDllLoaded error %i", error );
 
                 if ( KErrNone == error )
@@ -1259,7 +1441,6 @@
         }
     }
 
-
 // -----------------------------------------------------------------------------
 // RAnalyzeToolMainAllocator::FindCurrentThreadStack()
 // Find the current thread which is using the heap
@@ -1323,59 +1504,6 @@
         {
         iEventHandler->Start();
         }
-      }
-
-// -----------------------------------------------------------------------------
-// RAnalyzeToolMainAllocator::LogDeviceInfo()
-// Logs iversion of ATApp, ATApi, S60 version and ROM checksum 
-// at the startup of hooked application
-// -----------------------------------------------------------------------------
-//
-void RAnalyzeToolMainAllocator::LogDeviceInfo()
-    {
-    //get s60 version
-    TBuf<KSysUtilVersionTextLength> bufS60;
-    if (SysUtil::GetSWVersion(bufS60) == KErrNone)
-        {
-        TInt index(0);
-        //replace newlines in string with '@'
-        //while ((index = bufS60.Find(KNewLine)) != KSysUtilVersionTextLength && index != KErrNotFound)
-        while ( (index = bufS60.Find(KNewLine16)) != KErrNotFound)
-            {
-            bufS60.Replace(index, 1, KSeparator);
-            }
-        while ( (index = bufS60.Find(KSpace16)) != KErrNotFound)
-			{
-			bufS60.Replace(index, 1, KSeparator);
-			}
-        }
-
-    TBuf<KHexa32Length> bufChecksum;
-    
-#ifndef __WINSCW__
-    TRomHeader* romHeader = (TRomHeader*) UserSvr::RomHeaderAddress();
-    if (romHeader)
-        {
-        bufChecksum.Format(_L("%08x"), romHeader->iCheckSum);
-        }
-#endif
-    
-    TBuf8<KSysUtilVersionTextLength> s60Version;
-    s60Version.Copy(bufS60);
-    
-    TBuf8<KHexa32Length> romChecksum;
-    romChecksum.Copy(bufChecksum);
-    
-    //only fastlog implementation
-    if (iLogOption == EATLogToTraceFast)
-    	{  
-        ATFastLogDeviceInfo(s60Version, romChecksum);
-        }
-    else if ( iLogOption == EATLogToFile )
-    	{
-        iLogFile.ATFileLogDeviceInfo( s60Version, romChecksum );
-    	}
-    
     }
 
 // End of File
--- a/analyzetool/dynamicmemoryhook/src/analyzetoolmemoryallocator.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/src/analyzetoolmemoryallocator.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -27,7 +27,8 @@
 //
 RAnalyzeToolMemoryAllocator::RAnalyzeToolMemoryAllocator( TBool aNotFirst ) :
     RAllocator(),
-    iNotFirst( aNotFirst )
+    iNotFirst( aNotFirst )/*,
+    iStorageServerOpen( EFalse )*/
     {
     LOGSTR1( "ATMH RAnalyzeToolMemoryAllocator::RAnalyzeToolMemoryAllocator()" );
     
--- a/analyzetool/dynamicmemoryhook/src/atdriveinfo.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,216 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  Definitions for the class TATDriveInfo.
-*
-*/
-
-
-
-// INCLUDE FILES
-#include <f32file.h>
-#include <driveinfo.h>
-#include "atdriveinfo.h"
-#include "atlog.h"
-
-// -----------------------------------------------------------------------------
-// TATDriveInfo::TATDriveInfo
-// C++ default constructor.
-// -----------------------------------------------------------------------------
-//
-TATDriveInfo::TATDriveInfo()
-    {
-    LOGSTR1( "TATD TATDriveInfo::TATDriveInfo()" );
-    }
-
-// -----------------------------------------------------------------------------
-// TATDriveInfo::CreatePath()
-// -----------------------------------------------------------------------------
-//    
-TInt TATDriveInfo::CreatePath( TDes& aPath, 
-    const TDesC& aFileName, const TDesC& aFilePath, RFs& aFs )
-    {
-    LOGSTR1( "TATD TInt TATDriveInfo::CreatePath()" );
-    TInt err( KErrNotFound );
-    
-    // first try to create user defined directory
-    if( aFilePath.Length()>0 )
-    	{
-		err = aFs.MkDir( aFilePath );
-		LOGSTR2( "STSE > defined path aFs.MkDir err = %i", err );
-		
-		if ( !err || err == KErrAlreadyExists )
-			{
-			//directory was succesfully created or exists
-			aPath.Copy( aFilePath );
-			if ( aFileName.Length() != 0 && 
-				 ( ( aPath.MaxLength() - aPath.Length() ) > aFileName.Length() ) )
-				{
-				aPath.Append( aFileName );
-				}
-			return err;
-			}
-		else if( err == KErrBadName )
-			{
-			// TODO bad path, log error
-			// log default name in the end of function
-			}
-    	}
-	
-
-
-	//error when trying to create user defined directory, lets use default paths
-    
-    // Drive letter    
-    TChar driveLetter;
-    // Drive number
-    TInt dNumber( EDriveZ );     
-    TBool found( EFalse );
-    // Drive type
-    TUint driveType( KDriveAttRemovable );    
-    
-    
-    while ( !found )
-        {
-        // Get drive letter
-        if ( GetDrive( driveLetter, dNumber, aFs, driveType ) == KErrNotFound )
-        	{
-        	if ( driveType == KDriveAttInternal )
-        		{
-                return KErrNotFound;
-        		}       	
-            driveType = KDriveAttInternal;
-        	dNumber = EDriveZ;
-        	}       
-        else
-        	{
-			// Create path
-			aPath.Delete( 0, aPath.MaxLength() );
-			aPath.Append( driveLetter );
-		  
-		            
-		#ifdef __WINS__
-            // For emulator the data file is stored to different location
-            aPath.Append( KATDataFilePath );       
-		#else
-		    TDriveInfo driveInfo;
-		    aFs.Drive( driveInfo, dNumber );      
-            // The drive is removable( memory card ) so we can log inside of root folder
-            if ( driveInfo.iDriveAtt & KDriveAttRemovable )
-                {
-                aPath.Append( KATDataFilePath );       
-                }
-            // The drive is internal user can only access data folder so log into that
-            else
-                {
-                aPath.Append( KATDataFilePath2 );       
-                }
-		#endif
-						
-			// Make a directory for logging data file
-			err = aFs.MkDir( aPath );
-			LOGSTR2( "STSE > aFs.MkDir err = %i", err );
-			
-			if ( !err || err == KErrAlreadyExists )
-				{                
-                if ( aFileName.Length() != 0 && 
-                     ( ( aPath.MaxLength() - aPath.Length() ) > aFileName.Length() ) )
-                    {
-                    aPath.Append( aFileName );
-                    }
-				found = ETrue;
-				}
-        	}
-        }        
-    return err;        
-    }
-
-// -----------------------------------------------------------------------------
-// TATDriveInfo::GetDrive()
-// -----------------------------------------------------------------------------
-//    
-TInt TATDriveInfo::GetDrive( TChar& aDrive, TInt& aDriveNumber, RFs& aFs, 
-	const TUint aDriveType )
-    {
-    LOGSTR1( "TATD TInt TATDriveInfo::GetDrive()" );
-       
-    // Contains drive information.
-    TDriveInfo driveInfo; 
-    
-    for ( TInt i = aDriveNumber; i >= (TInt)EDriveA; i-- )
-        {
-        // Gets information about a drive and the medium mounted on it.
-        // If error occured then skip to next drive.
-        if ( aFs.Drive( driveInfo, i ) != KErrNone )
-            continue;
-                
-        // Test whether drive is available. If not, skip to next drive.
-        if ( driveInfo.iDriveAtt & KDriveAbsent || i == (TInt)EDriveD ||
-             driveInfo.iDriveAtt & KDriveAttRom || 
-             driveInfo.iMediaAtt & KMediaAttWriteProtected ||
-             driveInfo.iDriveAtt & KDriveFileSysROFS )
-            continue;
-        
-        // Maps a drive number to the corresponding character.
-        if ( aFs.DriveToChar( i, aDrive ) != KErrNone )
-            continue;                
-        
-        if ( driveInfo.iDriveAtt & aDriveType &&
-             driveInfo.iType != EMediaNotPresent &&
-             driveInfo.iType != EMediaCdRom )
-            {
-            TUint status( 0 );
-            
-            switch ( aDriveType )
-                {
-                case KDriveAttRemovable:
-                    {
-                    // Get the drive status of the default removable mass storage.                    
-                    if ( DriveInfo::GetDriveStatus( aFs, i, status ) == KErrNone )
-                        {
-                        // To indicate that the drive is physically removable.
-                        if ( status & DriveInfo::EDriveRemovable &&
-                             !( status & DriveInfo::EDriveCorrupt ) )
-                            {
-                            aDriveNumber = --i;
-                            return KErrNone;
-                            }
-                        }
-                    }
-                    break;
-                case KDriveAttInternal:
-                    {
-                    // Get the drive status of the default removable mass storage.
-                    if ( DriveInfo::GetDriveStatus( aFs, i, status ) == KErrNone )
-                        {
-                        // To indicate that the drive is internal and 
-                        // cannot be physically removed.
-                        if ( status & DriveInfo::EDriveInternal &&
-                             !( status & DriveInfo::EDriveExternallyMountable ) )
-                            {
-                            aDriveNumber = --i;
-                            return KErrNone;
-                            }
-                        }
-                    }
-                    break;
-                    
-                default:
-                    break;
-                }
-            }
-        }
-    return KErrNotFound;
-    }
- 
-// End of File
--- a/analyzetool/dynamicmemoryhook/src/customuser.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/dynamicmemoryhook/src/customuser.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -23,9 +23,9 @@
 #include "atlog.h"
 #include "analyzetoolmemoryallocator.h"
 #include "analyzetoolpanics.pan"
+#include "atstorageservercommon.h"
 #include "atdriveinfo.h"
 #include <analyzetool/analyzetooltraceconstants.h>
-#include "analyzetoolfastlog.h"
 
 #ifdef USE_CLEANER_DLL
 // Global variable to detect dll attach & detach in process.
@@ -121,7 +121,7 @@
 // CONSTANTS
 // When needed, update the version number directly inside _LIT macro.
 // Constant for the atool API(staticlib) version.
-_LIT( KAtoolApiVersion, "1.7.6" );
+_LIT( KAtoolApiVersion, "1.7.5" );
 
 // Version number buffer length
 const TInt KAtoolVersionNumberLength = 10;
@@ -133,8 +133,8 @@
 _LIT( KVersionSeparator, ";" );
 
 // Incorrect version error strings 
-_LIT( KIncorrectText, "ERR INCORRECT_ATOOL_VERSION [API v.%S][ATOOL v.%S]" );
-_LIT( KIncorrectTextTrace, "<AT> " );
+_LIT( KIncorrectText, "ERROR_OCCURED INCORRECT_ATOOL_VERSION [API v.%S][ATOOL v.%S]" );
+_LIT( KIncorrectTextTrace, "PCSS " );
 
 // -----------------------------------------------------------------------------
 // CustomUser::Panic()
@@ -240,7 +240,7 @@
 // -----------------------------------------------------------------------------
 //
 EXPORT_C TInt CustomUser::SetupThreadHeap( TBool aNotFirst, 
-    SStdEpocThreadCreateInfo& aInfo, const TFileName& aFileName, const TPath& aFilePath,
+    SStdEpocThreadCreateInfo& aInfo, const TFileName& aFileName,
     TUint32 aLogOption, TUint32 aIsDebug, const TATVersion& aVersion,
     TUint32 aAllocCallStackSize, TUint32 aFreeCallStackSize,
     TRefByValue<const TDesC> aFmt, ... )
@@ -250,18 +250,13 @@
     
     // Add handling of the argument list here.
         
-    TInt ret( KErrNone ); 
-    
+    TInt ret( KErrNone );    
     // Check version number
     TBuf<KAtoolVersionNumberLength> atoolVer;
-    TBuf<KApiVersionLength> apiVer;
-    TInt err( KErrNone );
-    err = CheckVersion( aVersion, atoolVer, apiVer );
-    
-    if ( err )
+    if ( CheckVersion( aVersion, atoolVer ) != KErrNone )
     	{
     	LOGSTR1( "ATMH > Wrong API version > Inform user and Exit." );
-    	ReportIncorrectVersion( aLogOption, aFileName, aFilePath, atoolVer );
+    	ReportIncorrectVersion( aLogOption, aFileName, atoolVer );
     	return KAtoolVersionError;
     	}
     
@@ -282,12 +277,8 @@
     #endif
 #endif
         // Install the RAllocator
-        TBuf8<KAtoolVersionLength> atoolVer8;
-        atoolVer8.Copy(atoolVer);
-        TBuf8<KApiVersionLength> apiVer8;
-        apiVer8.Copy(apiVer);
-        aInfo.iAllocator = &InstallAllocator( aNotFirst, aFileName, aFilePath, aLogOption, aIsDebug,
-                aAllocCallStackSize, aFreeCallStackSize, atoolVer8, apiVer8 );
+        aInfo.iAllocator = &InstallAllocator( aNotFirst, aFileName, aLogOption, aIsDebug,
+                aAllocCallStackSize, aFreeCallStackSize );
         }
     else
         {
@@ -300,8 +291,6 @@
         // Switch thread heap 
         User::SwitchAllocator( allocator );
         }
-    
-
     return ret;
     }
 
@@ -312,8 +301,8 @@
 //
 //lint -e{429} suppress "Custodial pointer 'allocator' has not been freed or returned"
 EXPORT_C RAllocator& CustomUser::InstallAllocator( TBool aNotFirst, 
-	const TFileName& aFileName,  const TPath& aFilePath, TUint32 aLogOption, TUint32 aIsDebug,
-	TUint32 aAllocCallStackSize, TUint32 aFreeCallStackSize, const TDesC8& aAtoolVersion, const TDesC8& aApiVersion )
+	const TFileName& aFileName, TUint32 aLogOption, TUint32 aIsDebug,
+	TUint32 aAllocCallStackSize, TUint32 aFreeCallStackSize )
     {
     LOGSTR1( "ATMH CustomUser::InstallAllocator()" );
     
@@ -342,9 +331,8 @@
             LOGSTR1( "ATMH CustomUser::InstallAllocator() - first thread of the program" );
             // Only one thread in the program. Must be main thread
             RAnalyzeToolMainAllocator* allocator = 
-				new RAnalyzeToolMainAllocator( aNotFirst, aFileName, aFilePath, aLogOption,
-				                               aIsDebug, aAllocCallStackSize, aFreeCallStackSize, 
-				                               aAtoolVersion, aApiVersion );
+				new RAnalyzeToolMainAllocator( aNotFirst, aFileName, aLogOption,
+				                               aIsDebug, aAllocCallStackSize, aFreeCallStackSize );
             
             __ASSERT_ALWAYS( allocator != NULL, AssertPanic( ENoMemory ) );
             
@@ -361,14 +349,15 @@
             // Create new RAllocator with handles from the main thread
             RAnalyzeToolAllocator* allocator = new RAnalyzeToolAllocator( 
                     aNotFirst,
+                    ((RAnalyzeToolMainAllocator*)params().iAllocator)->StorageServer(), 
                     ((RAnalyzeToolMainAllocator*)params().iAllocator)->Codeblocks(), 
                     ((RAnalyzeToolMainAllocator*)params().iAllocator)->Mutex(), 
                     ((RAnalyzeToolMainAllocator*)params().iAllocator)->ProcessId(), 
                     ((RAnalyzeToolMainAllocator*)params().iAllocator)->AnalyzeTool(),
+                    ((RAnalyzeToolMainAllocator*)params().iAllocator)->StorageServerOpen(),
                     ((RAnalyzeToolMainAllocator*)params().iAllocator)->LogOption(),
                     ((RAnalyzeToolMainAllocator*)params().iAllocator)->AllocMaxCallStack(),
-                    ((RAnalyzeToolMainAllocator*)params().iAllocator)->FreeMaxCallStack(),
-                    ((RAnalyzeToolMainAllocator*)params().iAllocator)->LogFile() );
+                    ((RAnalyzeToolMainAllocator*)params().iAllocator)->FreeMaxCallStack() );
 
             __ASSERT_ALWAYS( allocator != NULL, AssertPanic( ENoMemory ) );
             
@@ -384,8 +373,8 @@
         {
         LOGSTR1( "ATMH CustomUser::InstallAllocator() - analyzetool.Open() returned error, creating DD" );
         RAnalyzeToolMainAllocator* allocator = 
-			new RAnalyzeToolMainAllocator( aNotFirst, aFileName, aFilePath, aLogOption, aIsDebug,
-			        aAllocCallStackSize, aFreeCallStackSize, aAtoolVersion, aApiVersion );
+			new RAnalyzeToolMainAllocator( aNotFirst, aFileName, aLogOption, aIsDebug,
+			        aAllocCallStackSize, aFreeCallStackSize );
         
         __ASSERT_ALWAYS( allocator != NULL, AssertPanic( ENoMemory ) );
         
@@ -402,7 +391,7 @@
 // Check atool version
 // -----------------------------------------------------------------------------
 //
-TInt CustomUser::CheckVersion( const TATVersion& aVersion, TDes& aToolVersion, TDes& aApiVersion )
+TInt CustomUser::CheckVersion( const TATVersion& aVersion, TDes& aToolVersion )
     { 
     LOGSTR2( "ATMH CustomUser::CheckVersion(), aVersion( %S )", &aVersion );
     
@@ -413,9 +402,9 @@
     // Find separator place
     TInt findplace( version.Find( KVersionSeparator() ) );
     // Parse API version first [x.x.x;x.x.x]
-    if ( findplace >= 0 && findplace <= aApiVersion.MaxLength() )
+    if ( findplace >= 0 && findplace <= apiVer.MaxLength() )
 		{
-        aApiVersion.Copy( version.Mid( 0, findplace ) ); 
+		apiVer.Copy( version.Mid( 0, findplace ) ); 
 		version.Delete( 0, findplace + KVersionSeparator().Length() );
 		}
  
@@ -423,18 +412,18 @@
     	{
     	aToolVersion.Copy( version );
     	if ( aToolVersion.Compare( KAtoolApiVersion ) == KErrNone &&
-    	     aApiVersion.Length() == 0 )
+    		 apiVer.Length() == 0 )
     		{
     		// Support 1.5.0 version (Version info: [1.5.0])
-    	    aApiVersion.Copy( version );
+    		apiVer.Copy( version );
     		}
     	}
     
     LOGSTR3( "ATMH > API version( %S ), ATOOL version( %S )", 
-    		&aApiVersion, &aToolVersion );
+    		&apiVer, &aToolVersion );
         
     // Check version numbers 
-    if ( aApiVersion.Compare( KAtoolApiVersion ) == KErrNone )
+    if ( apiVer.Compare( KAtoolApiVersion ) == KErrNone )
     	{
     	return KErrNone;
     	}
@@ -447,11 +436,11 @@
 // -----------------------------------------------------------------------------
 //
 void CustomUser::ReportIncorrectVersion( const TUint32 aLogOption,
-	const TFileName& aFileName, const TPath& aFilePath, const TDes& aToolVersion )
+	const TFileName& aFileName, const TDes& aToolVersion )
 	{
 	LOGSTR2( "ATMH CustomUser::ReportIncorrectVersion(), aFileName( %S )", 
 			&aFileName );
-
+	
 	switch ( aLogOption )
 		{
 		case EATLogToFile:
@@ -470,7 +459,7 @@
 			
 			if ( !err )
 				{				
-                err = TATDriveInfo::CreatePath( logFileBuf, aFileName, aFilePath, fs );
+                err = TATDriveInfo::CreatePath( logFileBuf, aFileName, fs );
 			    
 				// Replace file if exists
 				if ( err && err != KErrAlreadyExists )
@@ -504,9 +493,9 @@
 			break;
 			
 		case EATUseDefault:
-		case EATLogToTraceFast:
+		case EATLogToTrace:
 			{
-			LOGSTR1( "ATMH > ReportIncorrectVersion > EATLogToTraceFast" );
+			LOGSTR1( "ATMH > ReportIncorrectVersion > EATLogToTrace" );
 			// Error msg buffer
 			TBuf<KMaxFileName> msg;	
 			msg.Copy( KIncorrectTextTrace );
--- a/analyzetool/group/ReleaseNotes_AnalyzeTool.txt	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/group/ReleaseNotes_AnalyzeTool.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -1,7 +1,7 @@
 ===============================================================================
 
-RELEASE NOTES - ANALYZETOOL v1.10.0
-RELEASED 2nd July 2010
+RELEASE NOTES - ANALYZETOOL v1.9.1
+RELEASED 29th April 2010
 
 SUPPORTS SYMBIAN^1+
 
@@ -20,14 +20,14 @@
 
 ===============================================================================
 
-
-What's New in v1.10.0
+What's New in v1.9.1
 ====================
-  
-- Change: Storage server was removed
-- Change: New trace format
-- Change: Logging to binary file added
-- Change: Capture of reallocations implemented
+- Change: Removed Avkon and Console UI's to simplify the maintenance of the
+  tool
+- Change: Middleware layer dependencies removed so AnalyzeTool can be now used
+  also in OS layer builds
+- Fix: Move all binaries to ROM instead of ROFS to avoid ROM build
+  dependencies issues in hooked components
 
 ===============================================================================
 
@@ -85,12 +85,18 @@
 =============
 - Kernel analysis are not supported.
 
+- When using monitored internal data gathering mode (-mi) and hooked
+  application contains huge amounts of allocations AnalyzeTool? storageserver
+  might run out of memory to store the data. This message "Symbian error code
+  -4" is seen when analyzing the data file with atool.exe. Solution is to use
+  external / monitored external data gathering mode. 
+
 - Switch allocator. AnalyzeTool change the application memory allocator to
   AnalyzeTool own memory allocator and using the User::SwitchAllocator function
   can lead to situation where the tested application does not work properly.
   
 - AnalyzeTool hooked QT applications becomes too slow to run. Use small size
-  call stack(s) and new logging mode (external -tr). 
+  call stack(s) and new logging mode (external -e). 
 
 - Stif test case with AnalyzeTool can inform wrong memory leak alert.
 
@@ -110,17 +116,6 @@
 Version History:
 ================
 
-Version 1.9.1 - 29th April 2010
-==============================
-- Change: Removed Avkon and Console UI's to simplify the maintenance of the
-  tool
-- Change: Middleware layer dependencies removed so AnalyzeTool can be now used
-  also in OS layer builds
-- Fix: Move all binaries to ROM instead of ROFS to avoid ROM build
-  dependencies issues in hooked components
-
-===============================================================================
-
 Version 1.9.0 - 8th April 2010
 ==============================
 - Feature: Remove false positive memory leaks with better handling of global
--- a/analyzetool/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -17,9 +17,10 @@
 
 #include <platform_paths.hrh>
 
-#include "../analyzetool_plat/group/bld.inf"
+
 #include "../commandlineengine/group/bld.inf"
 #include "../staticlib/group/bld.inf"
+#include "../storageserver/group/bld.inf"
 #include "../kerneleventhandler/group/bld.inf"
 #include "../analyzetoolcleaner/group/bld.inf"
 #include "../dynamicmemoryhook/group/bld.inf"
--- a/analyzetool/kerneleventhandler/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/kerneleventhandler/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -20,6 +20,12 @@
 PRJ_PLATFORMS
 ARMV5 WINSCW
 
+PRJ_EXPORTS
+../inc/analyzetool.h OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/analyzetool.h)
+../inc/atcommon.h OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/atcommon.h)
+../inc/analyzetool.inl OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/analyzetool.inl)
+../inc/analyzetooltraceconstants.h OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/analyzetooltraceconstants.h)
+
 PRJ_MMPFILES
 atoolkerneleventhandler.mmp
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/kerneleventhandler/inc/analyzetool.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,325 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the class RAnalyzeTool.
+*
+*/
+
+
+#ifndef __ANALYZETOOL_H__
+#define __ANALYZETOOL_H__
+
+// INCLUDES
+#include <e32cmn.h>
+
+//Version information for command line engine.
+//Tells the version of AT core componenets.
+//ANALYZETOOL_CORE_VERSION_FOR_CLE 1.9.1
+
+// CONSTANTS
+inline TVersion KAnalyzeToolLddVersion() { return TVersion(1, 0, 1); }
+
+/* The name of the analyze tool device driver*/
+_LIT( KAnalyzeToolLddName, "AToolKernelEventHandler" );
+
+/* The priority of AnalyzeTool Dfc */
+const TInt KAnalyzeToolThreadPriority = 27;
+
+/* The name of the AnalyzeTool DFC */
+_LIT8( KAnalyzeToolThreadName, "AnalyzeToolThreadDfc" );
+
+/* The panic literal */
+_LIT( KClientPanic, "AnalyzeTool" );
+
+//const TInt KATMaxCallstackLength = 20;
+
+/* The device handler panic codes */
+enum TPanic
+	{
+	EPanicRequestPending,
+	EPanicNoRequestPending,
+	EPanicUnsupportedRequest
+	};
+
+// Size of following must be multiple of 4 bytes.
+
+class TMainThreadParams
+	{
+	public:
+		RAllocator* iAllocator;
+		TBool       iAlone;
+		TUint       iProcessId;
+	};
+typedef TPckgBuf<TMainThreadParams> TMainThreadParamsBuf;
+
+class TLibraryInfo
+	{
+	public:
+		TBuf8<KMaxLibraryName> iLibraryName;
+		TLinAddr  iRunAddress;
+		TUint32   iSize;
+		TInt      iIndex;
+		TUint     iProcessId;
+	};
+
+typedef TPckgBuf<TLibraryInfo> TLibraryInfoBuf;
+
+class TCodesegInfo
+	{
+	public:
+		TBuf8<KMaxLibraryName> iFullName;
+		TLinAddr iRunAddress;
+		TUint32  iSize;
+		TInt  iIndex;
+		TUint iProcessId;
+		TInt  iCodesegIndex; 
+		TLinAddr iFileEntryPoint;
+		TInt     iFuntionCount;
+		TLibraryFunction iFirstFunction;
+		TModuleMemoryInfo iMemoryInfo;
+	};
+
+typedef TPckgBuf<TCodesegInfo> TCodesegInfoBuf;
+
+class TThreadParams
+	{		
+	public:
+	    TLinAddr iStackAddress;
+	    TInt iStackSize;
+	    TUint iThreadId;
+	};
+
+typedef TPckgBuf<TThreadParams> TThreadParamsBuf;
+
+class TProcessIdentityParams
+	{		
+	public:
+		TBuf8<KMaxProcessName> iProcessName;
+		TInt iDynamicCount;
+		TInt iCodesegCount;
+		TUint iProcessId;
+		TUint iThreadId;
+	    TLinAddr iStackAddress;
+	    TInt iStackSize;
+	};
+
+typedef TPckgBuf<TProcessIdentityParams> TProcessIdentityParamsBuf;
+
+class TLibraryEventInfo
+	{
+	public:
+		enum TLibraryEvent
+			{ 
+			ELibraryAdded = 0, 
+			ELibraryRemoved,
+			EKillThread 
+			};
+					
+	public:
+		TUint iProcessId;
+		TBuf8<KMaxLibraryName> iLibraryName;
+		TLinAddr iRunAddress;
+		TUint32 iSize;
+		TLibraryEvent iEventType;
+		TUint iThreadId;
+	};
+
+typedef TPckgBuf<TLibraryEventInfo> TLibraryEventInfoBuf;
+
+class TProcessHandleInfo
+	{
+	public:
+		TInt     iProcessHandleCount;
+		TInt     iThreadHandleCount;
+		TInt     iIndex;
+		TInt     iThreadCount;
+		TLinAddr iUserStackRunAddress;
+		TInt     iUserStackSize;
+		TUint    iProcessId;
+	};
+
+typedef TPckgBuf<TProcessHandleInfo> TProcessHandleInfoBuf;
+
+/**
+*  A class for particular process's current handle count
+*/
+class TATProcessHandles
+    {
+    public:
+    
+        /** The ID of the process. */
+        TUint iProcessId;
+        
+        /** The number of current handles in the library. */
+        TInt iCurrentHandleCount;
+    };
+
+typedef TPckgBuf<TATProcessHandles> TATProcessHandlesBuf;
+
+class TClientCount
+    {
+    public:
+    
+        /** The count of clients */
+        TInt iClientCount;     
+    };
+
+typedef TPckgBuf<TClientCount> TClientCountBuf;
+
+class TATMemoryModel
+    {
+    public :
+        /* Memory model*/
+        TUint32 iMemoryModel;
+    };
+typedef TPckgBuf<TATMemoryModel> TATMemoryModelBuf;
+
+// CLASS DECLARATION
+
+/**
+*  The user-side handle to a logical channel which provides functions to 
+*  open a channel and to make requests to a analyze tool device driver. 
+*/
+
+class RAnalyzeTool : public RBusLogicalChannel
+	{
+	
+	public:
+		
+	/** Enumeration of supported functions */
+	enum TBasicAnalyzerControl
+		{
+		EGetProcessInfo = 0, /* The process information */
+		EGetCodesegInfo,	 /* The codesegment information */
+		EGetLibraryInfo,     /* The library information */
+		EGetDynamicInfo,	 /* The count of dynamic code in the process */
+		ELibraryEvent,       /* Subscribe events from library events */
+		ECancelLibraryEvent, /* Cancel subscribetion of library events */
+		ECurrentClientCount,  /* The count of clients in device driver */
+		EMainThreadAlloctor,
+		EThreadStack,
+		EGetProcessHandle,	/* Gets process global handles info*/
+		EGetCurrentHandles, /* Get a process's current handle count */
+		EGetMemoryModel
+		};
+			
+#ifndef __KERNEL_MODE__
+
+        /**
+        * Opens a handle to a logical channel.
+        * @return TInt Returns KErrNone, if successful or otherwise 
+        		  one of the other system-wide error codes
+        */
+		inline TInt Open();
+
+        /**
+        * Acquires process information.
+        * @param aProcessIdentityParams The process information which 
+        								is filled by the device driver
+        * @return TInt Returns KErrNone, if successful
+        			   otherwise one of the other system-wide error codes
+        */
+		inline TInt GetProcessInfo( 
+				TProcessIdentityParamsBuf& aProcessIdentityParams );
+
+        /**
+        * Acquires codeseg information.
+        * @param aCodesegInfo The codeseg information which 
+        					  is filled by the device driver
+        * @return TInt Returns KErrNone, if successful
+        			   otherwise one of the other system-wide error codes
+        */
+		inline TInt GetCodesegInfo( TCodesegInfoBuf& aCodesegInfo );
+		
+        /**
+        * Acquires library information.
+        * @param aLibraryInfo The library information which 
+        					  is filled by the device driver
+        * @return TInt Returns KErrNone, if successful
+        			   otherwise one of the other system-wide error codes
+        */
+		inline TInt GetLibraryInfo( TLibraryInfoBuf& aLibraryInfo );
+				
+        /**
+        * Subscribes library event.
+        * @param aStatus The request status object for this request. 
+        * @param aLibraryInfo The library information which 
+        					  is filled by the device driver
+        * @return TInt Returns KErrNone, if successful
+        			   otherwise one of the other system-wide error codes
+        */
+		inline void LibraryEvent( TRequestStatus& aStatus, 
+		                          TLibraryEventInfo& aLibraryInfo );
+		
+        /**
+        * Cancels subscribetion of the library event.
+        */
+		inline void CancelLibraryEvent();
+
+        /**
+        * Acquires device driver current client count.
+        * @param aClientCount A reference to TInt which is 
+        				      updated by the device driver.
+        * @return TInt Returns KErrNone, if successful
+        			   otherwise one of the other system-wide error codes
+        */
+		inline TInt ClientCount( TClientCountBuf& aClientCount );
+		
+        /**
+        * Acquires process main thread RAllocator
+        * @param aMainThreadParams The main thread information which 
+        					        is filled by the device driver
+        * @return TInt Returns KErrNone, if successful
+        			   otherwise one of the other system-wide error codes
+        */	
+		inline TInt MainThreadAlloctor( TMainThreadParamsBuf& aMainThreadParams );
+		
+		/**
+		* Acquires main thread stack address.
+		* @param aThreadStack Pointer to the TThreadParams object.
+		* @return TInt Returns KErrNone, if successful
+					   otherwise one of the other system-wide error codes
+		*/
+		inline TInt ThreadStack( TThreadParamsBuf& aThreadStack );
+
+        /**
+        * Acquires information about process global handles.
+        * @param aProcessHandleInfo Pointer to the TProcessHandleInfo object.
+        * @return TInt Returns KErrNone, if successful
+        			   otherwise one of the other system-wide error codes
+        */
+		inline TInt GetProcessHandleInfo( TProcessHandleInfoBuf& aProcessHandleInfo );
+
+        /**
+        * Acquires a process's current handle count.
+        * @param aProcessHandles Pointer to the TATProcessHandles object.
+        * @return TInt Returns KErrNone, if successful
+                       otherwise one of the other system-wide error codes
+        */
+        inline TInt GetCurrentHandleCount( TATProcessHandlesBuf& aProcessHandles );
+
+        /**
+         * Acquires memory model system uses.
+         * @param aMemoryModel pointer to the TATMemoryModelBuf object.
+         */
+        inline TInt GetMemoryModel( TATMemoryModelBuf& aMemoryModel );
+        
+#endif // #ifndef __KERNEL_MODE__
+	};
+
+// INLINES
+#include <analyzetool/analyzetool.inl>
+
+#endif // #ifndef __ANALYZETOOL_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/kerneleventhandler/inc/analyzetool.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,159 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for inline methods of the class RAnalyzeTool.
+*
+*/
+
+
+#ifndef __ANALYZETOOL_INL
+#define __ANALYZETOOL_INL
+
+#ifndef __KERNEL_MODE__
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::Open()
+// Opens a handle to a analyze tool device driver
+// ----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::Open()
+	{
+	return DoCreate( KAnalyzeToolLddName, 
+					 KAnalyzeToolLddVersion(), 
+					 KNullUnit, 
+					 NULL, 
+					 NULL, 
+					 EOwnerProcess );
+	}
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::GetProcessInfo()
+// Acquires process information.
+// ----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::GetProcessInfo( 
+		TProcessIdentityParamsBuf& aProcessIdentityParams )
+	{
+	return DoControl( EGetProcessInfo, &aProcessIdentityParams, NULL );
+	}
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::GetCodesegInfo()
+// Acquires codeseg information.
+// ----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::GetCodesegInfo( TCodesegInfoBuf& aCodesegInfo )
+	{
+	return DoControl( EGetCodesegInfo, &aCodesegInfo, NULL );
+	}
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::GetLibraryInfo()
+// Symbian 2nd phase constructor can leave.
+// ----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::GetLibraryInfo( TLibraryInfoBuf& aLibraryinfo )
+	{
+	return DoControl( EGetLibraryInfo, &aLibraryinfo, NULL );
+	}
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::LibraryEvent()
+// Subscribes library event.
+// ----------------------------------------------------------------------------
+//
+inline void RAnalyzeTool::LibraryEvent( TRequestStatus& aStatus,
+	TLibraryEventInfo& aLibInfo )
+	{
+	return DoRequest( ELibraryEvent, aStatus, (TAny*)&aLibInfo );
+	}
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::CancelLibraryEvent()
+// Cancels subscribetion of the library event.
+// ----------------------------------------------------------------------------
+//
+inline void RAnalyzeTool::CancelLibraryEvent()
+	{
+	DoControl( ECancelLibraryEvent, NULL, NULL);
+	}
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::ClientCount()
+// Acquires the count of device driver current users
+// ----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::ClientCount( TClientCountBuf& aClientCount )
+	{
+	return DoControl( ECurrentClientCount, &aClientCount, NULL );
+	}
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::MainThreadAlloctor()
+// Acquires information about process main thread
+// ----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::MainThreadAlloctor( 
+	        TMainThreadParamsBuf& aMainThreadParams )
+    {
+    return DoControl( EMainThreadAlloctor, &aMainThreadParams, NULL );
+    }
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::ThreadStack()
+// Acquires main thread stack address.
+// ----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::ThreadStack( TThreadParamsBuf& aThreadStack )
+    {
+    return DoControl( EThreadStack, &aThreadStack, NULL );
+    }
+
+// ----------------------------------------------------------------------------
+// RAnalyzeTool::GetProcessHandleInfo()
+// Acquires information about process handles
+// ----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::GetProcessHandleInfo( 
+		    TProcessHandleInfoBuf& aProcessHandleInfo )
+    {
+    return DoControl( EGetProcessHandle, &aProcessHandleInfo, NULL );
+    }
+
+// -----------------------------------------------------------------------------
+// DAnalyzeToolChannel::GetCurrentHandleCount()
+// Acquires a process's current handle count
+// -----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::GetCurrentHandleCount( 
+		    TATProcessHandlesBuf& aProcessHandles )
+    {
+    return DoControl( EGetCurrentHandles, &aProcessHandles, NULL );
+    }
+
+// -----------------------------------------------------------------------------
+// DAnalyzeToolChannel::GetMemoryModel()
+// Acquires memory model system uses.
+// -----------------------------------------------------------------------------
+//
+inline TInt RAnalyzeTool::GetMemoryModel( 
+            TATMemoryModelBuf& aMemoryModel )
+    {
+    return DoControl( EGetMemoryModel, &aMemoryModel, NULL );
+    }
+
+#endif // #ifndef __KERNEL_MODE__
+
+#endif // __ANALYZETOOL_INL
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/kerneleventhandler/inc/analyzetooltraceconstants.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,171 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common declarations/definitions for Analyze Tool.
+*
+*/
+
+
+
+#ifndef __ANALYZETOOLTRACECONSTANTS_H__
+#define __ANALYZETOOLTRACECONSTANTS_H__
+
+#include <analyzetool/atcommon.h>
+
+// Trace version information.
+const TUint KATTraceVersion = 0x2;
+
+// The default logging mode 
+const TATLogOption KDefaultLoggingMode = EATLogToTrace;
+
+// When needed, update the storage data file's version number directly inside
+// the _LIT8 macro. Note, if you change this string, also remember to update
+// the constant "KVersionStringLength" below.
+
+_LIT8( KDataFileVersion, "DATA_FILE_VERSION 11\r\n" );
+_LIT8( KProcessStart, "PROCESS_START %S %x " );
+_LIT16( KProcessStart16, "PROCESS_START %S %x " );
+_LIT8( KDllLoad, "DLL_LOAD %S %Lx %x %x\r\n" );
+_LIT16( KDllLoad16, "DLL_LOAD %S %Lx %x %x\r\n" );
+_LIT8( KDllUnload, "DLL_UNLOAD %S %Lx %x %x\r\n" );
+_LIT16( KDllUnload16, "DLL_UNLOAD %S %Lx %x %x\r\n" );
+_LIT8( KProcessEnd, "PROCESS_END %x " );
+_LIT16( KProcessEnd16, "PROCESS_END %x " );
+_LIT8( KProcessEndAbnormal, "PROCESS_END %x ABNORMAL " );
+_LIT8( KMemoryLeak, "MEM_LEAK " ); // Remember to update value of KMemoryLeak when changing this.
+_LIT8( KHandleLeak, "HANDLE_LEAK %S %x\r\n" );
+_LIT16( KHandleLeak16, "HANDLE_LEAK %S %x\r\n" );
+_LIT8( KErrorOccured, "ERROR_OCCURED %d " );
+_LIT8( KLoggingCancelled, "LOGGING_CANCELLED %x\r\n" );
+_LIT8( KNewLine, "\r\n" );
+_LIT8( KHexaNumber, " %x" );
+_LIT8( KSpace, " " );
+_LIT8( KUdeb, "UDEB" );
+_LIT8( KUrel, "UREL" );
+    
+// Constants for logging through debug channel
+_LIT( KTraceMessage, "PCSS %x %S" );
+_LIT( KMemoryAllocHeader, "ALLOCH " );
+_LIT( KMemoryAllocFragment, "ALLOCF " );
+_LIT( KMemoryFreedHeader, "FREEH " );
+_LIT( KMemoryFreedFragment, "FREEF " );
+_LIT( KSpaceTrace, " " );
+_LIT( KNewLineTrace, "\r\n" );
+_LIT( KHexaNumberTrace, " %x" );
+_LIT( KProcessEndTrace, "PROCESS_END %x " );
+_LIT( KProcessEndAbnormalTrace, "PROCESS_END %x ABNORMAL " );
+_LIT( KErrorOccuredTrace, "ERROR_OCCURED %d " );
+_LIT( KSubtestStart, "TEST_START " );
+_LIT( KSubtestEnd, "TEST_END " );
+_LIT8( KEmpty, "" );
+_LIT( KOpenSquareBracket, "[" );
+_LIT( KCloseSquareBracket, "]" );
+_LIT( KUnderLine, "_" );
+// File name format
+_LIT( KFormat, "%S%S%02d%S");// pad char="0", field width=2
+
+// A string for setting time January 1st, 1970 AD nominal Gregorian
+_LIT( KJanuaryFirst1970, "19700000:000000.000000" );
+
+// Module name when it cannot be defined
+_LIT8( KUnknownModule, "Unknown" );
+_LIT16( KUnknownModule16, "Unknown" );
+
+// Constant time variable used to calculate timestamps for pc side.
+const TInt64  KMicroSecondsAt1970 = 62168256000000000;
+
+// The length of the string KDataFileVersion
+const TInt KVersionStringLength = 22;
+
+// The length of the string KMemoryLeak
+const TInt KMemleakLength = 9;
+
+// The maximum length of one word (32 bits) represented in the hexadecimal text format
+// without "0x" prefix
+const TInt KHexa32Length = 8;
+
+// The maximum length of one word (32 bits) represented in the decimal text format
+const TInt KDec32Length = 10;
+
+// The maximum length of a TInt64 represented in the hexadecimal text format without
+// "0x" prefix
+const TInt KHexa64Length = 16;
+
+// The length of one space character in text
+const TInt KSpaceLength = 1;
+
+// The length of the combination of carriage return and new line characters.
+const TInt KNewlineLength = 2;
+
+// The maximum length of the "PROCESS_START..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KProcessStartBufLength = 16 + KMaxProcessName + KSpaceLength + KHexa32Length +
+                                        KSpaceLength + KHexa64Length + KHexa32Length + KNewlineLength;
+
+// The maximum length of the "DLL_LOAD..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KDllLoadBufLength = 9 + KMaxLibraryName + KSpaceLength + KHexa64Length + KSpaceLength +
+                    KHexa32Length + KSpaceLength + KHexa32Length + KNewlineLength;
+
+// The maximum length of the "DLL_UNLOAD..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KDllUnloadBufLength = 11 + KMaxLibraryName + KHexa64Length + KSpaceLength + KSpaceLength + 
+                    KHexa32Length + KSpaceLength + KHexa32Length + KNewlineLength;
+
+// The maximum length of the "PROCESS_END..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KProcessEndBufLength = 12 + KHexa32Length + KSpaceLength +
+                                        KHexa64Length + KNewlineLength;
+                                        
+// The maximum length of the "ERROR_OCCURED..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KErrOccuredBufLength = 14 + KDec32Length + KSpaceLength +
+                                        KHexa64Length + KNewlineLength;
+                                        
+// The maximum length of the "ALLOCH / ALLOCF..." buffer. 
+const TInt KMemAllocBufLength = 255;
+
+// The maximum length of the "FREE..." buffer.
+const TInt KMemFreedBufLength = 255;
+
+// The maximum length of the "HANDLE_LEAK..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KHandleLeakBufLength = 12 + KMaxLibraryName + KSpaceLength +
+                                        KHexa32Length + KNewlineLength;
+                                        
+// The maximum length of the "TEST_START..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KTestStartBufLength = 11 + KHexa64Length + KSpaceLength +
+                                        KATMaxSubtestIdLength + KSpaceLength + KHexa64Length + KNewlineLength;
+
+// The maximum length of the "TEST_END..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KTestEndBufLength = 9 + KHexa64Length + KSpaceLength +
+                                        KATMaxSubtestIdLength + KSpaceLength + KHexa64Length + KNewlineLength;
+
+// The maximun length of the "LOGGING_CANCELLED..." buffer. The first number is the
+// length of the line tag and one space character (see the descriptor constants above).
+const TInt KCancelBufLength = 18 + KHexa64Length + KNewlineLength;
+
+// The maximun length of the "PROCESS_END %x ABNORMAL..." buffer. The first number is length of
+// the line tag and one space character (see the descriptor constants above).
+const TInt KEndAbnormalBufLength = 22 + KHexa32Length + KHexa64Length + 
+                                        KSpaceLength + KNewlineLength;
+
+// The maximun length of the file name extension buffer.
+const TInt KExtensionLength = 50;
+
+// The maximun length of the process UID3 buffer.
+const TInt KProcessUidLength = 20;
+
+#endif // __ANALYZETOOLTRACECONSTANTS_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/kerneleventhandler/inc/atcommon.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,108 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Common declarations/definitions for Analyze Tool.
+*
+*/
+
+
+#ifndef ATCOMMON_H_
+#define ATCOMMON_H_
+
+// CONSTANTS
+const TInt KATMaxCallstackLength = 256;
+const TInt KATMaxFreeCallstackLength = 256;
+const TInt KATMaxSubtestIdLength = 256;
+
+// The following constants only limit the configuration UI.
+// The bigger the number is, the more space will be allocated run-time
+// by the client. So, change with care.
+const TInt KATMaxProcesses = 20;
+const TInt KATMaxDlls = 30;
+
+// Constants defining call stack address range in multiple memory model.
+const TInt32 KATMultipleMemoryModelLowLimit = 0x70000000;
+const TInt32 KATMultipleMemoryModelHighLimit = 0x90000000;
+
+
+// CLASS DECLARATIONS
+
+/**
+*  A class for storing process information
+*/
+class TATProcessInfo
+    {
+    public:
+    
+        /** The ID of the process. */
+        TUint iProcessId;
+        
+        /** The name of the process. */
+        TBuf8<KMaxProcessName> iProcessName;
+        
+        /** The starting time of the process. */
+        TInt64 iStartTime;
+    };
+
+
+// ENUMERATIONS
+
+/**
+*  Enumeration for different logging modes of Analyze Tool 
+*/
+enum TATLogOption
+    {
+    /** Using the default. */
+    EATUseDefault = 0,
+    
+    /** Logging to a file in S60. */
+    EATLogToFile,
+    
+    /** Logging to debug channel. */
+    EATLogToTrace,
+    
+    /** Logging to debug channel bypassing storage server. */
+    EATLogToTraceFast,
+    
+    /** Logging switched off. */
+    EATLoggingOff
+    };
+
+/**
+*  Class which supports interfacing with AnalyzeTool exported
+*  functions. Mainly meant for STIF integration.
+*/
+class AnalyzeToolInterface
+    {
+    public:
+
+        /**
+        * This function starts subtest with a given name.
+        * @param aSubtestId The name identifying this particular sub test. The length
+        *   of this descriptor must not be greater than KATMaxSubtestIdLength, or
+        *   otherwise the method raises a STSEClient: 2 panic.
+        */
+        IMPORT_C static void StartSubTest( const TDesC8& aSubtestId );
+
+        /**
+        * This function stops a subtest with a given name.
+        * @param aSubtestId The name identifying this particular sub test. The length
+        *   of this descriptor must not be greater than KATMaxSubtestIdLength, or
+        *   otherwise the method raises a STSEClient: 2 panic. 
+        */   
+        IMPORT_C static void StopSubTest( const TDesC8& aSubtestId );
+
+    };
+    
+
+#endif /*ATCOMMON_H_*/
--- a/analyzetool/rom/analyzetool_rom.iby	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/rom/analyzetool_rom.iby	Wed Oct 13 16:17:58 2010 +0300
@@ -29,5 +29,9 @@
 // Cleaner
 file=ABI_DIR\BUILD_DIR\atoolcleaner.dll           	            SHARED_LIB_DIR\atoolcleaner.dll
 
+// Storage server
+file=ABI_DIR\BUILD_DIR\atoolstorageserver.exe                   PROGRAMS_DIR\atoolstorageserver.exe
+file=ABI_DIR\BUILD_DIR\atoolstorageserverclnt.dll               SHARED_LIB_DIR\atoolstorageserverclnt.dll
+
 
 #endif // __ANALYZETOOL_ROM_IBY__
--- a/analyzetool/sis/AnalyzeTool.pkg	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/sis/AnalyzeTool.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -18,7 +18,7 @@
 &EN
 
 ; standard SIS file header
-#{"AnalyzeTool"},(0x20012432),1,10,0,TYPE=SA, RU
+#{"AnalyzeTool"},(0x20012432),1,9,1,TYPE=SA, RU
 
 ;Localised Vendor name
 %{"Nokia Corporation"}
@@ -34,6 +34,8 @@
 
 "\epoc32\release\armv5\urel\atoolkerneleventhandler.ldd"            -"!:\sys\bin\atoolkerneleventhandler.ldd"
 "\epoc32\release\armv5\urel\atoolmemoryhook.dll"                    -"!:\sys\bin\atoolmemoryhook.dll"
+"\epoc32\release\armv5\urel\atoolstorageserver.exe"                 -"!:\sys\bin\atoolstorageserver.exe"
+"\epoc32\release\armv5\urel\atoolstorageserverclnt.dll"             -"!:\sys\bin\atoolstorageserverclnt.dll"
 "\epoc32\release\armv5\urel\atoolcleaner.dll"                 		-"!:\sys\bin\atoolcleaner.dll"
 
 ; Install console application
--- a/analyzetool/sis/AnalyzeTool_udeb.pkg	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/sis/AnalyzeTool_udeb.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -18,7 +18,7 @@
 &EN
 
 ; standard SIS file header
-#{"AnalyzeTool"},(0x20012432),1,10,0,TYPE=SA, RU
+#{"AnalyzeTool"},(0x20012432),1,9,1,TYPE=SA, RU
 
 ;Localised Vendor name
 %{"Nokia Corporation"}
@@ -34,6 +34,8 @@
 
 "\epoc32\release\armv5\udeb\atoolkerneleventhandler.ldd"            -"!:\sys\bin\atoolkerneleventhandler.ldd"
 "\epoc32\release\armv5\udeb\atoolmemoryhook.dll"                    -"!:\sys\bin\atoolmemoryhook.dll"
+"\epoc32\release\armv5\udeb\atoolstorageserver.exe"                 -"!:\sys\bin\atoolstorageserver.exe"
+"\epoc32\release\armv5\udeb\atoolstorageserverclnt.dll"             -"!:\sys\bin\atoolstorageserverclnt.dll"
 "\epoc32\release\armv5\urel\atoolcleaner.dll"                 		-"!:\sys\bin\atoolcleaner.dll"
 
 ; Install console application
--- a/analyzetool/sis/analyzeTool_stub.pkg	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/sis/analyzeTool_stub.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -18,7 +18,7 @@
 &EN
 
 ;Header
-#{"AnalyzeTool"}, (0x20012432), 1,10,0
+#{"AnalyzeTool"}, (0x20012432), 1,9,1
 
 ; Non-localised vendor name
 :"Nokia Corporation"
@@ -29,6 +29,8 @@
 ; AnalyzeTool binaries
 ""-"z:\sys\bin\atoolkerneleventhandler.ldd"
 ""-"z:\sys\bin\atoolmemoryhook.dll"
+""-"z:\sys\bin\atoolstorageserver.exe"
+""-"z:\sys\bin\atoolstorageserverclnt.dll"
 ""-"z:\sys\bin\atoolcleaner.dll"
 
 ""-"z:\sys\bin\atool.exe"
\ No newline at end of file
--- a/analyzetool/staticlib/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/staticlib/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -20,5 +20,8 @@
 PRJ_PLATFORMS
 ARMV5 WINSCW
 
+PRJ_EXPORTS
+../../dynamicmemoryhook/inc/customuser.h OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/customuser.h)
+
 PRJ_MMPFILES
 atoolstaticlib.mmp
--- a/analyzetool/staticlib/src/atoolstaticlib.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/analyzetool/staticlib/src/atoolstaticlib.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -113,7 +113,6 @@
         
     return CustomUser::SetupThreadHeap( aNotFirst, aInfo, 
             GetString( (TUint8) CustomUser::ELogFileName ),
-            GetString( (TUint8) CustomUser::ELogFilePath ),
             (TUint32) logOption, (TUint32) debug,
             GetString( (TUint8) CustomUser::EVersion ),
             (TUint32) allocCallStack, (TUint32) freeCallStack,
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/client/bwins/atoolstorageserverclntu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,26 @@
+EXPORTS
+	??0RATStorageServer@@QAE@XZ @ 1 NONAME ; RATStorageServer::RATStorageServer(void)
+	?CancelLogging@RATStorageServer@@QAEHI@Z @ 2 NONAME ; int RATStorageServer::CancelLogging(unsigned int)
+	?CheckMemoryAddress@RATStorageServer@@QBEHK@Z @ 3 NONAME ; int RATStorageServer::CheckMemoryAddress(unsigned long) const
+	?Close@RATStorageServer@@QAEXXZ @ 4 NONAME ; void RATStorageServer::Close(void)
+	?Connect@RATStorageServer@@QAEHXZ @ 5 NONAME ; int RATStorageServer::Connect(void)
+	?GetCurrentAllocsL@RATStorageServer@@QAEHIAAK0@Z @ 6 NONAME ; int RATStorageServer::GetCurrentAllocsL(unsigned int, unsigned long &, unsigned long &)
+	?GetLoadedDllsL@RATStorageServer@@QAEHIAAV?$RArray@V?$TBuf8@$0DM@@@@@@Z @ 7 NONAME ; int RATStorageServer::GetLoadedDllsL(unsigned int, class RArray<class TBuf8<60> > &)
+	?GetLoggingFileL@RATStorageServer@@QAEHIAAVTDes8@@@Z @ 8 NONAME ; int RATStorageServer::GetLoggingFileL(unsigned int, class TDes8 &)
+	?GetLoggingModeL@RATStorageServer@@QAEHIAAW4TATLogOption@@@Z @ 9 NONAME ; int RATStorageServer::GetLoggingModeL(unsigned int, enum TATLogOption &)
+	?GetMaxAllocsL@RATStorageServer@@QAEHIAAK0@Z @ 10 NONAME ; int RATStorageServer::GetMaxAllocsL(unsigned int, unsigned long &, unsigned long &)
+	?GetProcessesL@RATStorageServer@@QAEHAAV?$RArray@VTATProcessInfo@@@@@Z @ 11 NONAME ; int RATStorageServer::GetProcessesL(class RArray<class TATProcessInfo> &)
+	?GetUdebL@RATStorageServer@@QAEHIAAK@Z @ 12 NONAME ; int RATStorageServer::GetUdebL(unsigned int, unsigned long &)
+	?IsMemoryAdded@RATStorageServer@@QAEHK@Z @ 13 NONAME ; int RATStorageServer::IsMemoryAdded(unsigned long)
+	?LogDllLoaded@RATStorageServer@@QAEHABVTDesC8@@KK@Z @ 14 NONAME ; int RATStorageServer::LogDllLoaded(class TDesC8 const &, unsigned long, unsigned long)
+	?LogDllUnloaded@RATStorageServer@@QAEHABVTDesC8@@KK@Z @ 15 NONAME ; int RATStorageServer::LogDllUnloaded(class TDesC8 const &, unsigned long, unsigned long)
+	?LogMemoryAllocated@RATStorageServer@@QAEHKAAV?$TFixedArray@K$0BAA@@@H@Z @ 16 NONAME ; int RATStorageServer::LogMemoryAllocated(unsigned long, class TFixedArray<unsigned long, 256> &, int)
+	?LogMemoryFreed@RATStorageServer@@QAEHKAAV?$TFixedArray@K$0BAA@@@@Z @ 17 NONAME ; int RATStorageServer::LogMemoryFreed(unsigned long, class TFixedArray<unsigned long, 256> &)
+	?LogProcessEnded@RATStorageServer@@QAEHII@Z @ 18 NONAME ; int RATStorageServer::LogProcessEnded(unsigned int, unsigned int)
+	?LogProcessStarted@RATStorageServer@@QAEHABVTDesC16@@ABVTDesC8@@IKK@Z @ 19 NONAME ; int RATStorageServer::LogProcessStarted(class TDesC16 const &, class TDesC8 const &, unsigned int, unsigned long, unsigned long)
+	?StartSubTest@RATStorageServer@@QAEHABVTDesC8@@@Z @ 20 NONAME ; int RATStorageServer::StartSubTest(class TDesC8 const &)
+	?StartSubTest@RATStorageServer@@QAEHIABVTDesC8@@H@Z @ 21 NONAME ; int RATStorageServer::StartSubTest(unsigned int, class TDesC8 const &, int)
+	?StopSubTest@RATStorageServer@@QAEHABVTDesC8@@@Z @ 22 NONAME ; int RATStorageServer::StopSubTest(class TDesC8 const &)
+	?StopSubTest@RATStorageServer@@QAEHIABVTDesC8@@H@Z @ 23 NONAME ; int RATStorageServer::StopSubTest(unsigned int, class TDesC8 const &, int)
+	?Version@RATStorageServer@@QBE?AVTVersion@@XZ @ 24 NONAME ; class TVersion RATStorageServer::Version(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/client/eabi/atoolstorageserverclntu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,27 @@
+EXPORTS
+	_ZN16RATStorageServer11StopSubTestERK6TDesC8 @ 1 NONAME
+	_ZN16RATStorageServer11StopSubTestEjRK6TDesC8i @ 2 NONAME
+	_ZN16RATStorageServer12LogDllLoadedERK6TDesC8mm @ 3 NONAME
+	_ZN16RATStorageServer12StartSubTestERK6TDesC8 @ 4 NONAME
+	_ZN16RATStorageServer12StartSubTestEjRK6TDesC8i @ 5 NONAME
+	_ZN16RATStorageServer13CancelLoggingEj @ 6 NONAME
+	_ZN16RATStorageServer13GetMaxAllocsLEjRmS0_ @ 7 NONAME
+	_ZN16RATStorageServer13GetProcessesLER6RArrayI14TATProcessInfoE @ 8 NONAME
+	_ZN16RATStorageServer13IsMemoryAddedEm @ 9 NONAME
+	_ZN16RATStorageServer14GetLoadedDllsLEjR6RArrayI5TBuf8ILi60EEE @ 10 NONAME
+	_ZN16RATStorageServer14LogDllUnloadedERK6TDesC8mm @ 11 NONAME
+	_ZN16RATStorageServer14LogMemoryFreedEmR11TFixedArrayImLi256EE @ 12 NONAME
+	_ZN16RATStorageServer15GetLoggingFileLEjR5TDes8 @ 13 NONAME
+	_ZN16RATStorageServer15GetLoggingModeLEjR12TATLogOption @ 14 NONAME
+	_ZN16RATStorageServer15LogProcessEndedEjj @ 15 NONAME
+	_ZN16RATStorageServer17GetCurrentAllocsLEjRmS0_ @ 16 NONAME
+	_ZN16RATStorageServer17LogProcessStartedERK7TDesC16RK6TDesC8jmm @ 17 NONAME
+	_ZN16RATStorageServer18LogMemoryAllocatedEmR11TFixedArrayImLi256EEi @ 18 NONAME
+	_ZN16RATStorageServer5CloseEv @ 19 NONAME
+	_ZN16RATStorageServer7ConnectEv @ 20 NONAME
+	_ZN16RATStorageServer8GetUdebLEjRm @ 21 NONAME
+	_ZN16RATStorageServerC1Ev @ 22 NONAME
+	_ZN16RATStorageServerC2Ev @ 23 NONAME
+	_ZNK16RATStorageServer18CheckMemoryAddressEm @ 24 NONAME
+	_ZNK16RATStorageServer7VersionEv @ 25 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/client/group/atoolstorageserverclnt.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  The .mmp file for the client side of AToolStorageServer
+*
+*/
+
+#include <platform_paths.hrh>
+
+TARGET            atoolstorageserverclnt.dll
+TARGETTYPE        dll
+UID               0x1000008d 0x20012431
+CAPABILITY        ALL -TCB
+
+SMPSAFE
+
+SOURCEPATH        ../src
+
+SOURCE            atstorageserverclnt.cpp
+
+USERINCLUDE       ../inc
+USERINCLUDE       ../../inc
+USERINCLUDE       ../../server/inc
+USERINCLUDE       ../../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY           euser.lib
+LIBRARY           flogger.lib
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/client/inc/atstorageserverclnt.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,371 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the client side handle class RATStorageServer
+*
+*/
+
+
+
+#ifndef ATSTORAGESERVERCLNT_H
+#define ATSTORAGESERVERCLNT_H
+
+
+// INCLUDES
+#include    <e32base.h>
+#include    <analyzetool/atcommon.h>
+
+
+// CONSTANTS
+// Constants for the lowest version of the server with which the
+// client is compatible
+const TUint KLowestVersionNumberMaj = 0;
+const TUint KLowestVersionNumberMin = 1;
+const TUint KLowestVersionNumberBld = 1;
+
+
+// FORWARD DECLARATIONS
+class TATProcessInfo;
+
+
+// CLASS DECLARATION
+
+/**
+*  The main class of the Storage Server client. Objects of this class work as handles
+*  to the Storage Server's server side. Use Connect() to connect a client to the server,
+*  and Close() to end an opened session.
+*/
+class RATStorageServer: public RSessionBase
+    {
+    public:  // Constructor and destructor
+       
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C RATStorageServer();
+   
+    public: // New functions
+        
+        /**
+        * Creates a new process for the server, if that doesn't already exist, and
+        * connects a client to the server by creating a new session with it, and
+        * initializes the client for use. To end the server session, use Close().
+        * @return KErrNone, if successful; otherwise one of the other
+        *   system-wide error codes.
+        */
+        IMPORT_C TInt Connect();
+    
+        /**
+        * Closes a handle to a server session. This has also the effect of destroying
+        * the associated server side session object. Also, the server itself and the
+        * process where it is running are destroyed, if there are no other open sessions
+        * left.
+        */
+        IMPORT_C void Close();
+    
+        /**
+        * This method is called to initialize the server for logging and it is to be
+        * called as the first method after connecting to the server. The method informs
+        * the server that a new process has been started. The method cannot be called
+        * again without a call to the LogProcessEnded() first. Otherwise a STSEClient: 3
+        * panic is raised. A KERN-EXEC: 0 panic is raised if the client is not connected
+        * to the server.
+        * @param aFileName The name of the logging file used when the system is logging
+        *   to a file (the logging mode is EATLogToFile). The length of aFileName must not be
+        *   greater than KMaxFileName, otherwise the method raises a STSEClient: 2 panic.
+        * @param aProcessName The name of the new process started. The length of this
+        *   descriptor must not be greater than KMaxProcessName, otherwise the method
+        *   raises a STSEClient: 2 panic.
+        * @param aProcessId The ID of the process started.
+        * @param aLogOption An option telling the logging mode.
+        * @param aIsDebug Determines whether a binary is UDEB or UREL
+        * @return KErrNone, if successful; otherwise one of the other
+        *   system-wide error codes.
+        */
+        IMPORT_C TInt LogProcessStarted( const TDesC& aFileName,
+                                         const TDesC8& aProcessName,
+                                         TUint aProcessId,
+                                         TUint32 aLogOption, TUint32 aIsDebug );
+        
+        /**
+        * Asks the server to log that a new DLL has been loaded. Note, the method
+        * LogProcessStarted() has to be previously called. Otherwise a STSEClient: 3
+        * panic is raised. A KERN-EXEC: 0 panic is raised if the client is not connected
+        * to the server.
+        * @param aDllName The name of the new DLL loaded. The length of this descriptor
+        *   must not be greater than KMaxLibraryName, otherwise the method raises a
+        *   STSEClient: 2 panic.
+        * @param aStartAddress The start address of the DLL loaded.
+        * @param aEndAddress The end address of the DLL loaded.
+        * @return KErrNone, if successful; otherwise one of the other
+        *   system-wide error codes.
+        */
+        IMPORT_C TInt LogDllLoaded( const TDesC8& aDllName, TUint32 aStartAddress,
+                                              TUint32 aEndAddress );
+        
+        /**
+        * Asks the server to log that a new DLL has been unloaded. Note, the method
+        * LogProcessStarted() has to be previously called. Otherwise a STSEClient: 3
+        * panic is raised. A KERN-EXEC: 0 panic is raised if the client is not connected
+        * to the server. If the method is called with illegal parameter values, a
+        * STSEClient: 2 panic is raised.
+        * @param aDllName The name of the DLL to be unloaded. The length of this
+        *   descriptor must not be greater than KMaxLibraryName, otherwise the method
+        *   raises a STSEClient: 2 panic.
+        * @param aStartAddress The start address of the DLL to be unloaded.
+        * @param aEndAddress The end address of the DLL to be unloaded.
+        * @return KErrNone, if successful; otherwise one of the other
+        *   system-wide error codes.
+        */
+        IMPORT_C TInt LogDllUnloaded( const TDesC8& aDllName, TUint32 aStartAddress,
+                                               TUint32 aEndAddress );
+        
+        /**
+        * Informs the server that a memory allocation has occured at the specified
+        * address. Sends also the current call stack to the server. Note, the method
+        * LogProcessStarted() has to be previously called. Otherwise a STSEClient: 3 
+        * panic is raised. A KERN-EXEC: 0 panic is raised if the client is not connected
+        * to the server.
+        * @param aMemAddress The memory location where memory has been allocated.
+        * @param aCallstack An array including the current call stack.
+        * @param aSize The size of the newly allocated memory chunk.
+        * @return KErrNone, if successful; otherwise one of the other
+        *   system-wide error codes.
+        */
+        IMPORT_C TInt LogMemoryAllocated( TUint32 aMemAddress,
+                                          TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
+                                          TInt aSize );
+                
+        /**
+        * Informs the server that memory was released at the specified address. Note,
+        * the method LogProcessStarted() has to be previously called. Otherwise a 
+        * STSEClient: 3 panic is raised. A KERN-EXEC: 0 panic is raised if the client is
+        * not connected to the server.
+        * @param aMemAddress The memory location where memory has been deallocated.
+        * @param aFreeCallstack An array including the current call stack.
+        * @return KErrNone, if successful; otherwise one of the other
+        *   system-wide error codes.
+        */
+        IMPORT_C TInt LogMemoryFreed( TUint32 aMemAddress, 
+                                      TFixedArray<TUint32, KATMaxFreeCallstackLength>& aFreeCallstack );
+        
+        /**
+        * Tells the server that the process under test has been ended. Prints information
+        * related to process ending, such as possibly occured memory leaks (when file
+        * logging mode used), and possibly occured handle leaks. Note, the method 
+        * LogProcessStarted() has to be previously called. Otherwise a STSEClient:
+        * 3 panic is raised. A call to this method also closes the file opened for
+        * the current process. So, no further logging is possible without a new call
+        * to the method LogProcessStarted(). A KERN-EXEC: 0 panic is raised if the client
+        * is not connected to the server.
+        * @param aProcessId The ID number of the process ended.
+        * @param aHandleLeaks Amount of handle leaks.
+        * @return KErrNone, if successful; otherwise one of the other
+        *   system-wide error codes.
+        */
+        IMPORT_C TInt LogProcessEnded( TUint aProcessId, 
+                                       TUint aHandleLeaks );
+           
+        /**
+        * Gives the lowest version number of the server needed for this client.
+        * @return The lowest version of the server needed for this client.
+        */
+        IMPORT_C TVersion Version() const;  
+
+        /**
+        * Checks if the current process has allocated, but not freed, the given memory
+        * address. Note, the method LogProcessStarted() has to be previously called.
+        * Otherwise a STSEClient: 3 panic is raised. A KERN-EXEC: 0 panic is raised if
+        * the client is not connected to the server.
+        * @param aMemAddress The memory location to check.
+        * @return When the system is logging into a file: the index of a found 
+        *   memory address or KErrNotFound, if a matching memory address cannot
+        *   be found. When the system is not logging into a file: always KErrNone.
+        */
+        IMPORT_C TInt CheckMemoryAddress( TUint32 aMemAddress ) const;
+        
+        /**
+        * Gets all the processes with currently open logging sessions.
+        * @param aProcesses A reference to a process array to be filled by the server.
+        * @return KErrNone, if successful; otherwise one of the other
+        *   system wide error codes.
+        */
+        IMPORT_C TInt GetProcessesL( RArray<TATProcessInfo>& aProcesses );
+        
+        /**
+        * Gets all the DLLs loaded by the given process.
+        * @param aProcessId The ID of the process whose DLLs will be fetched.
+        * @param aDlls An array that after this function call includes names of
+        *   the given process's dlls
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt GetLoadedDllsL( TUint aProcessId,
+                                      RArray< TBuf8<KMaxLibraryName> >& aDlls );
+                
+        /**
+        * Gets the logging mode of the given process.
+        * @param aProcessId The ID of the process whose logging mode is being asked.
+        * @param aLoggingMode An enumeration telling the logging mode after a call
+        *   to this function.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt GetLoggingModeL( TUint aProcessId, TATLogOption& aLoggingMode );
+        
+        /**
+        * Starts a sub test for the given process.
+        * @param aProcessId The ID of the process for which to start a sub test.
+        * @param aSubtestId The name identifying this particular sub test. The length
+        *   of this descriptor must not be greater than KATMaxSubtestIdLength, or
+        *   otherwise the method raises a STSEClient: 2 panic.
+        * @param aHandleCount The current handle count of a particular process.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was not
+        *   found; KErrNotSupported, if the requested process does not have a logging
+        *   session ongoing or its logging mode is not EATLogToTrace; Otherwise one of the
+        *   other system wide error codes.
+        */
+        IMPORT_C TInt StartSubTest( TUint aProcessId, const TDesC8& aSubtestId, TInt aHandleCount = 0 );
+
+        /**
+        * Stops a sub test for the given process.
+        * @param aProcessId The ID of the process for which to stop a sub test.
+        * @param aSubtestId The name identifying this particular sub test. The length
+        *   of this descriptor must not be greater than KATMaxSubtestIdLength, or
+        *   otherwise the method raises a STSEClient: 2 panic.
+        * @param aHandleCount The current handle count of a particular process.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was not
+        *   found; KErrNotSupported, if the requested process does not have a logging
+        *   session ongoing or its logging mode is not EATLogToTrace; Otherwise one of the
+        *   other system wide error codes.
+        */
+        IMPORT_C TInt StopSubTest( TUint aProcessId, const TDesC8& aSubtestId, TInt aHandleCount = 0 );
+        
+        /**
+        * Gets the number and total size of the memory chunks currently allocated by the
+        * requested process. 
+        * @param aProcessId The ID of the process whose information is requested.
+        * @param aNumber On return contains the number of memory chunks currenlty
+        *   allocated by the requested process.
+        * @param aSize On return contains the amount of memory currently allocated
+        *   by the requested process.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was not
+        *   found; Otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt GetCurrentAllocsL( TUint aProcessId, TUint32& aNumber, TUint32& aSize );
+        
+        /**
+        * Gets the maximum number and total size of the memory chunks allocated by the
+        * requested process. 
+        * @param aProcessId The ID of the process whose information is requested.
+        * @param aNumber On return contains the maximum number of memory chunks
+        *   allocated by the requested process during the test run.
+        * @param aSize On return contains the maximum amount of memory allocated
+        *   by the requested process during the test run.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was not
+        *   found; Otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt GetMaxAllocsL( TUint aProcessId, TUint32& aNumber, TUint32& aSize );
+        
+        /**
+        * Starts a sub test for the calling process.
+        * @param aSubtestId The name identifying this particular sub test. The length
+        *   of this descriptor must not be greater than KATMaxSubtestIdLength, or
+        *   otherwise the method raises a STSEClient: 2 panic.
+        * @return KErrNone, if successful; KErrNotSupported, if the calling process
+        *   does not have a logging session ongoing or its logging mode is not
+        *   EATLogToTrace; Otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt StartSubTest( const TDesC8& aSubtestId );
+
+        /**
+        * Stops a sub test for the calling process
+        * @param aSubtestId The name identifying this particular sub test. The length
+        *   of this descriptor must not be greater than KATMaxSubtestIdLength, or
+        *   otherwise the method raises a STSEClient: 2 panic.
+        * @return KErrNone, if successful; KErrNotSupported, if the calling process
+        *   does not have a logging session ongoing or its logging mode is not
+        *   EATLogToTrace; Otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt StopSubTest( const TDesC8& aSubtestId );
+        
+        /**
+        * Cancels logging for the requested process. After logging of a given process
+        * has been cancelled, the session associated with that process will not be
+        * usable anymore. If a process wants to start logging again, it needs to close
+        * the handle and open it again in order to create a new session. Until then, most
+        * of the client's methods will return KErrCancel.
+        * @param aProcessId The process ID of the process whose logging is requested to
+        *   be cancelled.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt CancelLogging( TUint aProcessId );
+
+        /**
+        * Gets the number and total size of the memory chunks currently allocated by the
+        * requested process. 
+        * @param aProcessId The ID of the process whose information is requested.
+        * @param aIsUdeb On return contains an value greater than KErrNone if
+        *   mode is UDEB. Else the mode is UREL
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was not
+        *   found; Otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt GetUdebL( TUint aProcessId, TUint32& aIsUdeb );
+
+        /**
+        * Gets the number and total size of the memory chunks currently allocated by the
+        * requested process. 
+        * @param aProcessId The ID of the process whose information is requested.
+        * @param aFileName On return contains logging filename for the process.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was not
+        *   found; Otherwise one of the other system wide error codes.
+        */
+        IMPORT_C TInt GetLoggingFileL( TUint aProcessId, TDes8& aFileName );
+     
+        /**
+		* Check a memory allocation (memory address) from an internal array.
+		* @param aMemAddress The memory address to be check
+		* @return KErrNone, if memory address found in array; 
+		* 	KErrNotFound, if the requested memory address was not found.
+		*/
+        IMPORT_C TInt IsMemoryAdded( TUint32 aMemAddress );
+               
+    protected: // New functions
+    
+        /**
+        * Creates a new process for the server, if it does not already exist.
+        * @return KErrNone, if successful; otherwise one of the other
+        * system-wide error codes. 
+        */
+        TInt CreateProcess();
+        
+    private: // Internal functions
+    
+        /**
+        * Creates two buffers: one for storing call stack memory addresses and one for
+        * handle leaks. Internally used by this class. May leave, if there is 
+        * insufficient memory.
+        */
+        void ConstructBuffersL();
+        
+    private: // Data
+    
+        /** A pointer to a buffer of call stack's memory addresses */
+        CBufFlat* iStackBuf;
+    };
+
+#endif      // ATSTORAGESERVERCLNT_H   
+
+            
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/client/src/atstorageserverclnt.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,930 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for the client side handle class RATStorageServer
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "atstorageserverclnt.h"
+#include    "atstorageserver.h"
+#include    "atlog.h"
+#include    "atstorageservercommon.h"
+
+
+// CONSTANTS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::RATStorageServer
+// C++ default constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C RATStorageServer::RATStorageServer() :
+    RSessionBase(), iStackBuf( NULL )
+    {
+    LOGSTR1( "STSE RATStorageServer::RATStorageServer()" );
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::Connect
+// A function for connecting to the server
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::Connect()
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::Connect()" );
+ 
+    TInt errorCode( KErrNone );
+    errorCode = CreateProcess();
+    
+    // If process's creation failed, return the error code
+    if ( errorCode != KErrNone )
+        {
+        return errorCode;
+        }
+        
+    // Otherwise create a new session    
+    errorCode = CreateSession( KStorageServerName, Version() );
+    
+    // If creation of a new session failed, return the error code
+    if ( errorCode != KErrNone )
+        {
+        return errorCode;
+        }
+    
+    // Construct a buffer for call stack's memory addresses. If the function leaves,
+    // the leave code is put in "errorCode". 
+    TRAP( errorCode, ConstructBuffersL() ); 
+    
+    return errorCode;
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::Close
+// Destroys all memory reserved by this class, and calls RSessionBase::Close()
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void RATStorageServer::Close()
+    {
+    LOGSTR1( "STSE void RATStorageServer::Close()" );
+    
+    // Delete iStackBuf
+    delete iStackBuf;
+    iStackBuf = NULL;
+    
+    // Call the base class' Close()
+    RSessionBase::Close(); 
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::LogProcessStarted
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::LogProcessStarted( const TDesC& aFileName,
+                                                   const TDesC8& aProcessName,
+                                                   TUint aProcessId,
+                                                   TUint32 aLogOption, TUint32 aIsDebug )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::LogProcessStarted()" );
+    
+    // Panic always if aFileName or aProcessName are longer than allowed.
+    __ASSERT_ALWAYS( aFileName.Length() <= KMaxFileName &&
+                     aProcessName.Length() <= KMaxProcessName,
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    // Panic (in debug builds) if aProcessId is KNullProcessId
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+
+    // This information is optional -> ignoring error
+    // Must be before EProcessStarted in order to append udeb/urel
+    // information to LogProcessStarted
+    TIpcArgs ipcArgs2( aIsDebug );
+    SendReceive( CATStorageServer::EProcessUdeb, ipcArgs2 );
+    
+    TIpcArgs ipcArgs( &aFileName, &aProcessName, aProcessId, aLogOption );
+    TInt error( 0 );
+    
+    error = SendReceive( CATStorageServer::EProcessStarted, ipcArgs );
+
+    // Return, if error is not KErrNone.
+    if ( error != KErrNone )
+        {
+        return error;
+        }
+    
+    return KErrNone;
+    }
+       
+// -----------------------------------------------------------------------------
+// RATStorageServer::LogDllLoaded
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::LogDllLoaded( const TDesC8& aDllName,
+                                              TUint32 aStartAddress,
+                                              TUint32 aEndAddress )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::LogDllLoaded()" );
+    
+    // Panic always if aDllName is longer than allowed.
+    __ASSERT_ALWAYS( aDllName.Length() <= KMaxLibraryName,
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    // Panic (in debug builds) if aStartAddress is greater than aEndAddress
+    __ASSERT_DEBUG( aStartAddress <= aEndAddress,
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TIpcArgs ipcArgs( &aDllName, aStartAddress, aEndAddress );
+    
+    return SendReceive( CATStorageServer::EDllLoaded, ipcArgs );
+    }
+    
+// -----------------------------------------------------------------------------
+// RATStorageServer::LogDllUnloaded
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::LogDllUnloaded( const TDesC8& aDllName,
+                                                TUint32 aStartAddress,
+                                                TUint32 aEndAddress )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::LogDllUnloaded()" );
+    
+    // Panic always if aDllName is longer than allowed.
+    __ASSERT_ALWAYS( aDllName.Length() <= KMaxLibraryName,
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    // Panic (in debug builds) if aStartAddress is greater than aEndAddress
+    __ASSERT_DEBUG( aStartAddress <= aEndAddress,
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+      
+    TIpcArgs ipcArgs( &aDllName, aStartAddress, aEndAddress );
+    
+    return SendReceive( CATStorageServer::EDllUnloaded, ipcArgs );
+    }    
+        
+// -----------------------------------------------------------------------------
+// RATStorageServer::LogMemoryAllocated
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::LogMemoryAllocated( TUint32 aMemAddress,
+                                                    TFixedArray<TUint32, KATMaxCallstackLength>& aCallstack,
+                                                    TInt aSize )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::LogMemoryAllocated()" );
+    
+    TInt count=0;
+    // The number of memory addresses in aCallstack
+    for ( TInt i = 0; i < KATMaxCallstackLength; i++ )
+        {
+        if( aCallstack[i] == 0 )
+            {
+            break;
+            }
+        count++;
+        }
+    
+    LOGSTR2( "STSE The number of memory addresses in the current call stack: %d", count );
+    
+    // The maximum number of call stack's memory addresses this server can handle
+    // is KMaxCallstackLength
+    if ( count > KATMaxCallstackLength )
+        {
+        count = KATMaxCallstackLength;
+        }
+        
+    // Panic (in debug builds) if the parameters are faulty
+    __ASSERT_DEBUG( aMemAddress != 0 && count >= 0 && aSize >= 0,
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+          
+    // Buffer position
+    TInt pos = 0;  
+    TUint32 callStackAddr;
+                 
+    // Write the number of memory addresses of aCallstack (one word) into
+    // the beginning of the call stack buffer
+    iStackBuf->Write( pos, &count, KWordSize );
+    
+    // Increase the position by one word
+    pos += KWordSize; 
+      
+    // Write all the memory addresses of aCallStack into the buffer 
+    for ( TInt i = 0; i < count; i++ )
+        {
+        callStackAddr = aCallstack[i];
+        
+        // Write the current memory address (the length of an address is one word)
+        iStackBuf->Write( pos, &callStackAddr, KWordSize ); 
+        
+        // Move the pos variable one word (4 bytes) onwards.
+        pos += KWordSize;        
+        }  
+    
+    TPtr8 bufPtr( iStackBuf->Ptr(0) );       
+     
+    TIpcArgs ipcArgs( aMemAddress, &bufPtr, aSize );
+     
+    return SendReceive( CATStorageServer::EMemoryAllocated, ipcArgs );  
+    }
+        
+// -----------------------------------------------------------------------------
+// RATStorageServer::LogMemoryFreed
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::LogMemoryFreed( TUint32 aMemAddress,
+        TFixedArray<TUint32, KATMaxFreeCallstackLength>& aFreeCallstack )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::LogMemoryFreed()" );
+    
+    TInt count=0;
+    // The number of memory addresses in aFreeCallstack
+    for ( TInt i = 0; i < KATMaxCallstackLength; i++ )
+        {
+        if( aFreeCallstack[i] == 0 )
+            {
+            break;
+            }
+        count++;
+        }
+    LOGSTR3( "STSE > aFreeCallstack.Count() ( %i ), address( %x )", 
+    		count, aMemAddress );
+    
+    // The maximum number of call stack's memory addresses this server can handle
+	// is KMaxCallstackLength
+	if ( count > KATMaxFreeCallstackLength )
+		{
+		count = KATMaxFreeCallstackLength;
+		}
+		  
+	// Buffer position
+	TInt pos = 0;	
+	TUint32 callStackAddr;
+				 
+	// Write the number of memory addresses of aFreeCallstack (one word) into
+	// the beginning of the call stack buffer
+	iStackBuf->Write( pos, &count, KWordSize );
+	
+	// Increase the position by one word
+	pos += KWordSize; 
+	  
+	// Write all the memory addresses of aFreeCallstack into the buffer 
+	for ( TInt i = 0; i < count; i++ )
+		{
+		callStackAddr = aFreeCallstack[i];
+		
+		// Write the current memory address (the length of an address is one word)
+		iStackBuf->Write( pos, &callStackAddr, KWordSize ); 
+		
+		// Move the pos variable one word (4 bytes) onwards.
+		pos += KWordSize;        
+		}  
+	
+	TPtr8 bufPtr( iStackBuf->Ptr( 0 ) );	 
+	TIpcArgs ipcArgs( aMemAddress, &bufPtr );
+    	
+    return SendReceive( CATStorageServer::EMemoryFreed, ipcArgs );
+    }        
+        
+// -----------------------------------------------------------------------------
+// RATStorageServer::LogProcessEnded
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::LogProcessEnded( TUint aProcessId,
+                                                 TUint aHandleLeaks )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::LogProcessEnded()" );
+    
+    // Panic (in debug builds) if the parameters are faulty
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TIpcArgs ipcArgs( aProcessId, aHandleLeaks );
+    
+    return SendReceive( CATStorageServer::EProcessEnded, ipcArgs );
+    }
+
+//-----------------------------------------------------------------------------
+// RATStorageServer::Version()
+// Returns the version number.
+//-----------------------------------------------------------------------------
+//
+EXPORT_C TVersion RATStorageServer::Version() const
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::Version()" );
+    
+    return TVersion(KLowestVersionNumberMaj, KLowestVersionNumberMin,
+                                                KLowestVersionNumberBld);
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::CheckMemoryAddress
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::CheckMemoryAddress( TUint32 aMemAddress ) const
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::CheckMemoryAddress()" );
+    
+    // Panic (in debug builds) if the parameters are faulty
+    __ASSERT_DEBUG( aMemAddress != 0, 
+            StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TIpcArgs ipcArgs( aMemAddress );
+    
+    return SendReceive( CATStorageServer::EMemoryCheck, ipcArgs ); 
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::GetProcessesL
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::GetProcessesL( RArray<TATProcessInfo>& aProcesses )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::GetProcessesL()" );
+    
+    TInt error( KErrNone );
+    TInt sizeOfProcessInfo = sizeof( TATProcessInfo );
+    
+    // Reset the sent array
+    aProcesses.Reset();
+    
+    // Calculate the length of the buffer to be constructed for processes.
+    // One word will be reserved for the length of the array.
+    TInt bufferLength = KWordSize + KATMaxProcesses * sizeOfProcessInfo; 
+    
+    CBufFlat* processBuf;
+    // Construct processBuf and expand it before the beginning (index 0)
+    processBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( processBuf );
+    processBuf->ExpandL( 0, bufferLength );
+    
+    TPtr8 bufPtr( processBuf->Ptr(0) );
+    
+    // Send the buffer to the server, which will fill it.
+    TIpcArgs ipcArgs( &bufPtr );  
+    error = SendReceive( CATStorageServer::EGetProcesses, ipcArgs ); 
+    // Return with the error code if the operation failed
+    if ( error != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( processBuf );
+        return error;
+        }
+    
+    // A variable for the number of TATProcessInfo objects
+    TInt count( 0 );
+     // A variable for the position
+    TInt pos( 0 );
+    
+    // Read the value for count 
+    processBuf->Read( pos, &count, KWordSize );
+    
+    // Return if we got an illegal value for count     
+    if ( count < 0 || count > KATMaxProcesses )
+        {
+        CleanupStack::PopAndDestroy( processBuf );
+        return KErrGeneral;
+        }    
+
+    // Move the position one word onwards.    
+    pos += KWordSize;
+
+    TATProcessInfo processInfo;
+
+    // Go through all TATProcessInfo objects sent to the server 
+    for ( TInt j = 0; j < count; j++ )
+        {
+        // Read one of the TATProcessInfo objects stored in the buffer.
+        processBuf->Read( pos, &processInfo, sizeOfProcessInfo );
+       
+        // Append this processInfo to the array
+        error = aProcesses.Append( processInfo );
+
+        if ( error != KErrNone )
+            {
+            CleanupStack::PopAndDestroy( processBuf );
+            return error;
+            }
+
+        // Move the pos variable one word onwards.
+        pos += sizeOfProcessInfo;
+        }  
+    
+    CleanupStack::PopAndDestroy( processBuf );
+    return error;
+    }
+        
+// -----------------------------------------------------------------------------
+// RATStorageServer::GetLoadedDllsL
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::GetLoadedDllsL( TUint aProcessId, 
+                                                RArray< TBuf8<KMaxLibraryName> >& aDlls )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::GetLoadedDllsL()" );
+    
+    // Panic (in debug builds) if aProcessId is faulty
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TInt error( KErrNone );
+    
+    // Size of a DLL descriptor
+    TInt sizeOfDllDesc = sizeof( TBuf8<KMaxLibraryName> );
+    
+    // Reset the sent array
+    aDlls.Reset();
+    
+    // Calculate the length of the buffer to be constructed for DLL names.
+    // One word will be reserved for the length of the array.
+    TInt bufferLength = KWordSize + KATMaxDlls * sizeOfDllDesc; 
+    
+    CBufFlat* dllBuf;
+    // Construct dllBuf and expand it before the beginning (index 0)
+    dllBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( dllBuf );
+    dllBuf->ExpandL( 0, bufferLength );
+    
+    TPtr8 bufPtr( dllBuf->Ptr(0) );
+    
+    // Call the server with the given arguments
+    TIpcArgs ipcArgs( aProcessId, &bufPtr );  
+    error = SendReceive( CATStorageServer::EGetDlls, ipcArgs );
+    
+    // Return, if error is not KErrNone.
+    if ( error != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( dllBuf );      
+        return error;
+        }
+    
+    // A variable for the number of objects in the buffer
+    TInt count( 0 );
+    
+     // A variable for the position
+    TInt pos( 0 );
+    
+    // Read the value for count 
+    dllBuf->Read( pos, &count, KWordSize );
+    
+    // Return if we got an illegal value for count
+    if ( count < 0 || count > KATMaxDlls )
+        {
+        CleanupStack::PopAndDestroy( dllBuf );
+        return KErrGeneral;
+        }
+
+    // Move the position one word onwards.    
+    pos += KWordSize;
+
+    TBuf8<KMaxLibraryName> dllName;
+
+    // Go through all DLL names objects sent to the server 
+    for ( TInt j = 0; j < count; j++ )
+        {
+        // Read one of the DLL names stored in the buffer.
+        dllBuf->Read( pos, &dllName, sizeOfDllDesc );
+       
+        // Append this DLL name to the array
+        error = aDlls.Append( dllName );
+
+        if ( error != KErrNone )
+            {
+            return error;
+            }
+
+        // Move the pos variable one word onwards.
+        pos += sizeOfDllDesc;
+        }  
+    
+    CleanupStack::PopAndDestroy( dllBuf );
+    return error;
+    }    
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::GetLoggingModeL
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::GetLoggingModeL( TUint aProcessId,
+                                                TATLogOption& aLoggingMode )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::GetLoggingModeL()" );
+    
+    // Panic (in debug builds) if aProcessId is illegal
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TInt error(0);
+    
+    // The length of the buffer to be constructed for logging mode
+    TInt bufferLength = KWordSize; 
+    
+    CBufFlat* loggingModeBuf;
+    // Construct allocInfoBuf and expand it before the beginning (index 0)
+    loggingModeBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( loggingModeBuf );
+    loggingModeBuf->ExpandL( 0, bufferLength );
+    
+    TPtr8 bufPtr( loggingModeBuf->Ptr(0) );
+    
+    // Call the server
+    TIpcArgs ipcArgs( aProcessId, &bufPtr );  
+    error = SendReceive( CATStorageServer::EGetLoggingMode, ipcArgs );
+    
+    // Return if an error occured.
+    if ( error )
+        {
+        CleanupStack::PopAndDestroy( loggingModeBuf );
+        return error;
+        }
+      
+    // A variable for the position
+    TInt pos( 0 );
+    
+    // Read the value for aNumber
+    loggingModeBuf->Read( pos, &aLoggingMode, KWordSize );
+    
+    CleanupStack::PopAndDestroy( loggingModeBuf );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::StartSubTest
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::StartSubTest( TUint aProcessId, 
+                                              const TDesC8& aSubtestId, TInt aHandleCount )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::StartSubTest()" );
+    
+    // Panic if the parameters are faulty
+    __ASSERT_ALWAYS( aSubtestId.Length() <= KATMaxSubtestIdLength,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+        
+    // Panic (in debug builds) if the parameters are faulty
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+        
+    TIpcArgs ipcArgs( aProcessId, &aSubtestId, aHandleCount );
+    
+    return SendReceive( CATStorageServer::ESubtestStart, ipcArgs );
+    }
+    
+// -----------------------------------------------------------------------------
+// RATStorageServer::StopSubTest
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::StopSubTest( TUint aProcessId, 
+                                             const TDesC8& aSubtestId, TInt aHandleCount )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::StopSubTest()" );
+    
+    // Panic if the parameters are faulty
+    __ASSERT_ALWAYS( aSubtestId.Length() <= KATMaxSubtestIdLength,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+        
+    // Panic (in debug builds) if the parameters are faulty
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+        
+    TIpcArgs ipcArgs( aProcessId, &aSubtestId, aHandleCount );
+    
+    return SendReceive( CATStorageServer::ESubtestStop, ipcArgs );
+    }
+    
+// -----------------------------------------------------------------------------
+// RATStorageServer::GetCurrentAllocsL
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::GetCurrentAllocsL( TUint aProcessId, 
+                                                  TUint32& aNumber,
+                                                  TUint32& aSize   )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::GetCurrentAllocsL()" );
+    
+    // Panic (in debug builds) if aProcessId is illegal
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TInt error(0);
+    
+    // The length of the buffer to be constructed for allocation number and size
+    TInt bufferLength = KWordSize + KWordSize; 
+    
+    CBufFlat* allocInfoBuf;
+    // Construct allocInfoBuf and expand it before the beginning (index 0)
+    allocInfoBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( allocInfoBuf );
+    allocInfoBuf->ExpandL( 0, bufferLength );
+    
+    TPtr8 bufPtr( allocInfoBuf->Ptr(0) );
+    
+    // Call the server
+    TIpcArgs ipcArgs( aProcessId, &bufPtr );  
+    error = SendReceive( CATStorageServer::EGetCurrentAllocs, ipcArgs );
+    
+    // Return if error is not KErrNone.
+    if ( error != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( allocInfoBuf );
+        return error;
+        }
+      
+    // A variable for the position
+    TInt pos( 0 );
+    
+    // Read the value for aNumber
+    allocInfoBuf->Read( pos, &aNumber, KWordSize );
+    
+    pos += KWordSize;
+    
+    // Read the value for aSize
+    allocInfoBuf->Read( pos, &aSize, KWordSize );
+    
+    CleanupStack::PopAndDestroy( allocInfoBuf );
+    
+    return KErrNone;
+    }
+                                                  
+// -----------------------------------------------------------------------------
+// RATStorageServer::GetMaxAllocsL
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::GetMaxAllocsL( TUint aProcessId, 
+                                              TUint32& aNumber,
+                                              TUint32& aSize   )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::GetMaxAllocsL()" );
+    
+    // Panic (in debug builds) if aProcessId is illegal
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+        
+    TInt error(0);
+     
+    // The length of the buffer to be constructed for allocation number and size
+    TInt bufferLength = KWordSize + KWordSize; 
+
+    CBufFlat* allocInfoBuf;
+    // Construct allocInfoBuf and expand it before the beginning (index 0)
+    allocInfoBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( allocInfoBuf );
+    allocInfoBuf->ExpandL( 0, bufferLength );
+
+    TPtr8 bufPtr( allocInfoBuf->Ptr(0) );
+
+    // Call the server
+    TIpcArgs ipcArgs( aProcessId, &bufPtr );
+    error = SendReceive( CATStorageServer::EGetMaxAllocs, ipcArgs );
+
+    // Return, if error is not KErrNone.
+    if ( error != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( allocInfoBuf );
+        return error;
+        }
+
+    // A variable for the position
+    TInt pos( 0 );
+
+    // Read the value for aNumber
+    allocInfoBuf->Read( pos, &aNumber, KWordSize );
+
+    pos += KWordSize;
+
+    // Read the value for aSize
+    allocInfoBuf->Read( pos, &aSize, KWordSize );
+
+    CleanupStack::PopAndDestroy( allocInfoBuf );
+
+    return KErrNone;
+    }
+    
+// -----------------------------------------------------------------------------
+// RATStorageServer::StartSubTest
+// An overloaded version without a PID parameter
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::StartSubTest( const TDesC8& aSubtestId )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::StartSubTest()" );
+    
+    // Panic if the parameters are faulty
+    __ASSERT_ALWAYS( aSubtestId.Length() <= KATMaxSubtestIdLength,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+        
+    TIpcArgs ipcArgs( &aSubtestId );
+    
+    return SendReceive( CATStorageServer::ESubtestStart2, ipcArgs );
+    }
+    
+// -----------------------------------------------------------------------------
+// RATStorageServer::StopSubTest
+// An overloaded version without a PID parameter
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::StopSubTest( const TDesC8& aSubtestId )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::StopSubTest()" );
+    
+    // Panic if the parameters are faulty
+    __ASSERT_ALWAYS( aSubtestId.Length() <= KATMaxSubtestIdLength,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+        
+    TIpcArgs ipcArgs( &aSubtestId );
+    
+    return SendReceive( CATStorageServer::ESubtestStop2, ipcArgs );
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::CancelLogging
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::CancelLogging( TUint aProcessId )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::CancelLogging()" );
+    
+    // Panic (in debug builds) if aProcessId is illegal
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TIpcArgs ipcArgs( aProcessId );
+    
+    return SendReceive( CATStorageServer::ECancelLogging, ipcArgs );
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::CreateProcess
+// Checks if the server already exists. If it doesn't, creates a new process
+// for it.
+// -----------------------------------------------------------------------------
+//
+TInt RATStorageServer::CreateProcess()
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::CreateProcess()" );
+    
+    TInt errorCode( KErrNone );
+ 
+    // Check if the server already exists
+    TFindServer findServer( KStorageServerName );
+    TFullName fullName;
+
+    errorCode = findServer.Next( fullName );
+    
+    // Return KErrNone if the server is already running
+    if ( errorCode == KErrNone )
+        {
+        return KErrNone;
+        }
+    
+    // Otherwise initiate starting the server by creating first a new process for it.
+    // The second argument of the Create() method call is an empty descriptor, because
+    // we don't need to pass any data to the thread function of the new process's main
+    // thread.
+    RProcess process;
+    errorCode = process.Create( KStorageServerFile, KNullDesC );
+    
+    // Return the error code if the creation of the process failed
+    if ( errorCode != KErrNone )
+        {
+        return errorCode;
+        }
+    
+    TRequestStatus status;
+    process.Rendezvous( status );
+    
+    // If the status is not KRequestPending, abort the project creation
+    // and return KErrGeneral
+    if ( status != KRequestPending )
+        {
+        process.RendezvousCancel( status );
+        process.Kill( KErrGeneral );
+        process.Close();
+        return KErrGeneral;
+        }
+    
+    // Otherwise make the first thread of the new process eligible for execution
+    process.Resume();
+    
+    // Wait for a signal from the server       
+    User::WaitForRequest( status );
+    
+    // Close the process handle    
+    process.Close();
+    
+    // Return the error code
+    return status.Int();
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::ConstructBuffersL
+// Allocates buffers from heap. Called when connecting to the server
+// -----------------------------------------------------------------------------
+//
+void RATStorageServer::ConstructBuffersL()
+    {
+    LOGSTR1( "STSE void RATStorageServer::ConstructBuffersL()" );
+    
+    // Calculate the length of the buffer to be constructed for call stack.
+    // One word will be reserved for the length of the array
+    TInt bufferLength = ( (1 + KATMaxCallstackLength) * KWordSize  );
+    
+    // Construct iStackBuf and expand it before the beginning (index 0)
+    iStackBuf = CBufFlat::NewL( bufferLength );
+    iStackBuf->ExpandL( 0, bufferLength );
+    }
+    
+// -----------------------------------------------------------------------------
+// RATStorageServer::GetLoggingFileL
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::GetLoggingFileL( TUint aProcessId,
+                                                    TDes8& aFileName )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::GetLoggingFileL()" );
+    
+    // Panic (in debug builds) if aProcessId is illegal
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TInt error(0);
+
+    TBuf8<KMaxFileName> fileBuf;
+    // Call the server
+    TIpcArgs ipcArgs( aProcessId, &fileBuf );  
+    error = SendReceive( CATStorageServer::EGetLoggingFile, ipcArgs );
+    
+    // Return, if an error occured.
+    if ( error )
+        {
+        return error;
+        }
+      
+    aFileName.Copy( fileBuf );
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::GetUdebL
+// -----------------------------------------------------------------------------
+//    
+EXPORT_C TInt RATStorageServer::GetUdebL( TUint aProcessId, TUint32& aIsUdeb )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::GetUdebL()" );
+    
+    // Panic (in debug builds) if aProcessId is illegal
+    __ASSERT_DEBUG( aProcessId != KNullProcessId,        
+        StorageServerPanic( KCategoryClient, EAToolBadArgument ) );
+    
+    TInt error(0);
+    TBuf8<KMaxVersionName> isUdeb;
+    _LIT8( KUdeb, "UDEB" );
+    // Call the server
+    TIpcArgs ipcArgs( aProcessId, &isUdeb );  
+    error = SendReceive( CATStorageServer::EGetUdeb, ipcArgs );
+    
+    // Return, if an error occured.
+    if ( error != KErrNone )
+        {
+        return error;
+        }
+    
+    if ( isUdeb.Compare( KUdeb() ) == 0 )
+        {
+        LOGSTR1( "STSE TInt RATStorageServer::GetUdebL() - Is UDEB" );    
+        aIsUdeb = 1;    
+        }
+    else
+        {
+        LOGSTR1( "STSE TInt RATStorageServer::GetUdebL() - Is UREL" );
+        aIsUdeb = 0;    
+        }
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// RATStorageServer::IsMemoryAdded
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt RATStorageServer::IsMemoryAdded( TUint32 aMemAddress )
+    {
+    LOGSTR1( "STSE TInt RATStorageServer::IsMemoryAdded()" );
+        
+    TIpcArgs ipcArgs( aMemAddress );    
+    return SendReceive( CATStorageServer::EIsMemoryAdded, ipcArgs );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+ARMV5 WINSCW
+
+PRJ_EXPORTS
+../client/inc/atstorageserverclnt.h         OS_LAYER_PLATFORM_EXPORT_PATH(analyzetool/atstorageserverclnt.h)
+
+PRJ_MMPFILES
+../server/group/atoolstorageserver.mmp
+../client/group/atoolstorageserverclnt.mmp
+
+PRJ_TESTMMPFILES
+../internal/tsrc/group/storageservertest.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/inc/atstorageservercommon.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Includes common constants and enums for the AnalyzeTool 
+*                StorageServer client and server.
+*
+*/
+
+
+
+#ifndef ATSTORAGESERVERCOMMON_H
+#define ATSTORAGESERVERCOMMON_H
+
+
+//  INCLUDES
+
+#include <e32base.h>
+
+
+// CONSTANTS
+
+// Server's file name
+_LIT(KStorageServerFile, "AToolStorageServer.exe");
+
+// server name
+_LIT(KStorageServerName,"AToolStorageServer");
+
+
+// The path of the storage file
+#ifdef __WINS__
+_LIT( KATDataFilePath, ":\\logs\\analyzetool\\" );
+#else
+_LIT( KATDataFilePath, ":\\analyzetool\\" );
+_LIT( KATDataFilePath2, ":\\data\\analyzetool\\" );
+#endif
+
+// The word size in the current system is 32 bits, which is 4 bytes.
+const TInt KWordSize = 4;
+
+// Leak array granularity value
+const TInt KLeakArrayGranularity = 100;
+
+// DATA TYPES
+
+/** Storage Server panic codes */
+enum TStorageServerPanics
+    {
+    EAToolBadRequest = 1, // An undefined operation request from the client
+    EAToolBadArgument,    // Illegal arguments / function parameters   
+    EAToolNotAllowed,     // An operation is not allowed in the current program state
+    EAToolInternalError,   // An internal error has occured
+    EAToolIllegalLogOption // An undefined log option has been requested 
+    };
+
+
+/** Panic categories */
+_LIT(KCategoryServer,"STSEServer");
+_LIT(KCategoryClient,"STSEClient");
+
+inline void StorageServerPanic( const TDesC &aCategory, TStorageServerPanics aReason )
+    {
+    User::Panic(aCategory, aReason);
+    }
+  
+#endif      // ATSTORAGESERVERCOMMON_H   
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/group/atoolstorageserver.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  The .mmp file for the server side of AToolStorageServer
+*
+*/
+
+#include <platform_paths.hrh>
+
+TARGET        atoolstorageserver.exe
+TARGETTYPE    exe
+UID           0x0 0x20012430   
+CAPABILITY    NONE
+
+SMPSAFE
+
+EPOCHEAPSIZE 0x10000 0x800000
+
+SOURCEPATH    ../src
+
+SOURCE        atstorageserver.cpp
+SOURCE        atstorageserversession.cpp
+SOURCE        atmemoryentry.cpp
+SOURCE        atdynprocessinfo.cpp
+SOURCE        atdriveinfo.cpp
+SOURCE        atdllinfo.cpp
+
+USERINCLUDE   ../inc
+USERINCLUDE   ../../inc
+USERINCLUDE   ../../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY     euser.lib
+LIBRARY     efsrv.lib
+LIBRARY     flogger.lib
+LIBRARY     charconv.lib
+LIBRARY     platformenv.lib 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/inc/atdllinfo.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,96 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the class TATDllInfo.
+*
+*/
+
+
+#ifndef ATDLLINFO_H
+#define ATDLLINFO_H
+
+// INCLUDES
+#include <u32std.h>
+
+/**
+*  Stores information of process loaded library
+*/
+class TATDllInfo
+    {
+    
+    public: // Constructors
+        
+        /**
+        * C++ default constructor.
+        * @param aStartAddress Start address of the library 
+        * @param aEndAddress The end address of the library 
+        * @param aLoadTime The current time in a 64-bit form.
+        * @param aDllName The name of the library
+        */
+        TATDllInfo( const TUint32 aStartAddress, const TUint32 aEndAddress, 
+        		const TInt64& aLoadTime, const TDesC8& aDllName );
+
+    public: // New functions
+
+        /**
+        * Returs library start address
+        * @return TUint32 start address of the library
+        */
+        TUint32 StartAddress();
+        
+        /**
+		* Returns library end address
+		* @return TUint32 end address of the library
+		*/
+		TUint32 EndAddress();
+                
+        /**
+        * Gets specific library name
+        * return TDes8 Name of the library
+        */
+        TDes8& Name();
+        
+        /**
+		* Returns library load time
+		* @return TInt64 library load time
+		*/
+        TInt64 LibraryLoadTime();
+        		
+        /**
+		* Checks if two objects of this class match based on the objects's
+        * saved library name.
+		* @param aFirst Library object
+		* @param aSecond Library object
+		* return TBool ETrue, if the two objects match. EFalse otherwise.
+		*/
+        static TBool Match( const TATDllInfo& aFirst, const TATDllInfo& aSecond );
+                
+    public: // Member variables
+
+        /* Start address of the loaded dll */
+    	const TUint32 iStartAddress;
+
+        /* End address of the loaded dll */
+        const TUint32 iEndAddress;
+
+        /* Loaded dll name */
+        TBuf8<KMaxLibraryName> iName;
+        
+        /** For storing the time when DLL has loaded. */
+        const TInt64 iLoadTime;
+    };
+
+#endif // ATDLLINFO_H
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/inc/atdriveinfo.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the class TATDriveInfo.
+*
+*/
+
+
+
+#ifndef ATDRIVEINFO_H
+#define ATDRIVEINFO_H
+
+#include <f32file.h>
+
+/**
+*  Check what drives exists and creates file full path.
+*/
+class TATDriveInfo
+    {    
+    public: // Constructors
+        
+        /**
+        * C++ default constructor.
+        */
+        TATDriveInfo();
+
+    public: // New functions
+
+        /**
+        * Create the file full path.
+        * @param aPath Full path.
+        * @param aFileName Filename.
+        * @param aFs A handle to a file server.
+        * @return KErrNone or KErrAlreadyExists, if successful; 
+        *   Otherwise one of the other system wide error codes.
+        */
+        static TInt CreatePath( TDes& aPath, const TDesC& aFileName, RFs& aFs );   
+    
+    private: // New functions
+    
+        /**
+        * Get the available drive character.
+        * @param aDrive The drive letter.
+        * @param aDriveNumber The drive number.
+        * @param aFs A handle to a file server.
+        * @param aDriveType Drive type.
+        * @return KErrNone, if successful; otherwise KErrNotFound
+        */
+        static TInt GetDrive( TChar& aDrive, TInt& aDriveNumber, 
+                RFs& aFs, const TUint aDriveType );  
+        
+    };
+
+#endif // ATDRIVEINFO_H
+
+// End of File
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/inc/atdynprocessinfo.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the class CATDynProcessInfo
+*
+*/
+
+
+#ifndef ATDYNPROCESSINFO_H
+#define ATDYNPROCESSINFO_H
+
+
+//  INCLUDES
+#include    <e32base.h>
+#include    <analyzetool/atcommon.h>
+#include	"atdllinfo.h"
+
+// FORWARD DECLARATIONS
+class CATStorageServerSession;
+
+// CLASS DECLARATION
+
+/**
+*  A class that can store different process related information. The information
+*  is associated to a particular process wiht a member telling a process ID.
+*  All the other information but the process ID and the pointer to this process's
+*  associated session object can be subject to change dynamically, run-time.
+*/
+class CATDynProcessInfo : public CBase
+    {
+    public: // Constructor
+
+        /**
+        * Constructor. 
+        */ 
+        CATDynProcessInfo();
+    
+        /**
+        * Constructor. 
+        * @param aProcessId A process ID.
+        * @param aSessionObject A pointer to this process's associated session object.
+        * @param aDlls The loaded DLLs of the associated process.
+        */
+        CATDynProcessInfo( TUint aProcessId,
+                           CATStorageServerSession* aSessionObject,
+                           const RArray<TATDllInfo>& aDlls );
+        
+        /**
+        * Constructor.
+        * @param aProcessId A process ID.
+        * @param aSessionObject A pointer to this process's associated session object.
+        */
+        CATDynProcessInfo( TUint aProcessId,
+                           CATStorageServerSession* aSessionObject );
+                           
+        /**
+        * Constructor.
+        * @param aProcessId A process ID.
+        */
+        CATDynProcessInfo( TUint aProcessId );
+
+        /**
+        * Destructor
+        */
+        virtual ~CATDynProcessInfo();
+        
+    public:
+        
+        /**
+        * Compares two objects of this class based on the process ID.
+        * @param aFirst The first object of this class to be compared.
+        * @param aSecond The second object of this class to be compared.
+        * @return  Zero, if the two objects are equal. A negative value,
+        *   if the first object is less than the second. A positive value,
+        *   if the first object is greater than the second.
+        */
+        static TInt Compare( const CATDynProcessInfo& aFirst,
+                             const CATDynProcessInfo& aSecond );
+        
+    public:
+
+        /** The ID of the process. */
+        const TUint iProcessId;
+        
+        /** A pointer to the session object associated with this process. */
+        CATStorageServerSession* const iSessionObject;
+        
+        /** The DLLs loaded by the associated process */
+        RArray<TATDllInfo> iDlls;
+    };
+  
+#endif      // ATDYNPROCESSINFO_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/inc/atmemoryentry.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,98 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the class CATMemoryEntry
+*
+*/
+
+
+#ifndef ATMEMORYENTRY_H
+#define ATMEMORYENTRY_H
+
+
+//  INCLUDES
+#include <e32base.h>
+
+
+// CLASS DECLARATION
+
+/**
+*  A class for storing memory entries when the server is informed that memory has been
+*  allocated. The class stores the memory address of a new allocation and a pointer to
+*  a buffer including the current call stack. It also stores a time stamp, and the size
+*  of the allocation. 
+*     The class has member methods for evaluating two different objects of this class
+*  with each other. In the construction the class takes a pointer to the call stack
+*  buffer, but it does not create the buffer itself. However, it is responsible for
+*  deleting the buffer in the destruction.
+*/
+class CATMemoryEntry : public CBase
+    {
+    public: // Constructor
+
+        /**
+        * Constructor.
+        * @param aMemAddress An address to allocated memory.
+        * @param aCallstackBuf A pointer to a buffer containing call stack's memory
+        *   addresses.
+        * @param aAllocTime The current time in a 64-bit form.
+        * @param aAllocSize The size of an allocated memory chunk.
+        */ 
+        CATMemoryEntry( TUint32 aMemAddress, const CBufFlat* aCallstackBuf,
+                        const TInt64& aAllocTime, TInt aAllocSize );
+
+        /**
+        * Destructor
+        */
+        virtual ~CATMemoryEntry();
+
+    public:
+        /**
+        * Compares two objects of this class based on the allocation time.
+        * @param aFirst The first object of this class to be compared.
+        * @param aSecond The second object of this class to be compared.
+        * @return  Zero, if the two objects are equal. A negative value,
+        *   if the first object is less than the second. A positive value,
+        *   if the first object is greater than the second.
+        */
+        static TInt Compare( const CATMemoryEntry& aFirst,
+                             const CATMemoryEntry& aSecond );
+
+        /**
+        * Checks if two objects of this class match based on the objects's
+        * saved memory allocation addresses.
+        * @param aFirst The first object of this class to be evaluated.
+        * @param aSecond The second object of this class to be evaluated.
+        * @return ETrue, if the two objects match. EFalse otherwise.
+        */
+        static TBool Match( const CATMemoryEntry& aFirst,
+                            const CATMemoryEntry& aSecond );
+
+    public:
+
+        /** For storing an address of a memory allocation. */
+        const TUint32 iMemAddress;
+
+        /** A pointer to an array for storing the current call stack. */
+        const CBufFlat* const iCallstackBuf;
+        
+        /** For storing the time when an allocation has occured. */
+        const TInt64 iAllocTime;
+        
+        /** For storing the size of an allocation. */
+        const TInt iAllocSize;
+        
+    };
+  
+  
+#endif      // ATMEMORYENTRY_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/inc/atstorageserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,218 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the server side main class CATStorageServer
+*
+*/
+
+
+#ifndef ATSTORAGESERVER_H
+#define ATSTORAGESERVER_H
+
+
+//  INCLUDES
+#include    <e32base.h>
+#include    <analyzetool/atcommon.h>
+#include 	"atdllinfo.h"
+
+// CONSTANTS
+// Constants for the server's version
+const TUint KVersionNumberMaj = 0;
+const TUint KVersionNumberMin = 1;
+const TUint KVersionNumberBld = 1;
+
+// DATA TYPES
+
+// FORWARD DECLARATIONS
+class TATProcessInfo;
+class CATDynProcessInfo;
+class CATStorageServerSession;
+
+// CLASS DECLARATION
+
+/**
+*  The main class of the Storage Server.
+*  When a client connects to the server, a new session object
+*  is created by an object of this class. If the server does not exist when
+*  connecting, a new process and an object of this class are created first.
+*/
+class CATStorageServer : public CPolicyServer
+    {
+    
+    public: // Enumerations
+    
+        // opcodes used in message passing between client and server
+        enum TStorageServerReq
+            {
+            EProcessStarted,
+            EDllLoaded,
+            EDllUnloaded,
+            EMemoryAllocated,
+            EMemoryFreed,
+            EProcessEnded,
+            EMemoryCheck,
+            EGetProcesses,
+            EGetDlls,
+            ESetLoggingMode,
+            EGetLoggingMode,
+            ESubtestStart,
+            ESubtestStop,
+            ESubtestStart2,
+            ESubtestStop2,
+            EGetCurrentAllocs,
+            EGetMaxAllocs,
+            ECancelLogging,
+            EGetUdeb,
+            EGetLoggingFile,
+            EProcessUdeb,
+            EIsMemoryAdded,
+            EOutOfBounds
+            };
+    
+    
+    public: // Constructors and destructor
+        
+        /**
+        * Two-phased constructor that can leave.
+        * @return A new instance of this class
+        */
+        static CATStorageServer* NewL();
+        
+        /**
+        * Two-phased constructor that can leave and leaves a pointer
+        * on the cleanup stack.
+        * @return A new instance of this class
+        */
+        static CATStorageServer* NewLC();
+        
+        /**
+        * Destructor
+        */
+        virtual ~CATStorageServer();
+
+    public: // New functions
+        
+  
+        /**
+        * Creates a new server object and starts the server.
+        */
+        static void RunServerL();
+        
+        /**
+        * Increments the count of active sessions for this server.
+        */
+        void IncSessionCount();
+
+        /**
+        * Decrements the count of active sessions for this server.
+        */
+        void DecSessionCount();
+        
+        /**
+        * Adds a new process into the server's arrays.
+        * @param aProcessName The name of the process to be added.
+        * @param aProcessId The ID of the process to be added.
+        * @param aSessionObject A pointer to the current process's associated session
+        *   object.
+        * @param aStartTime The starting time of the process to be added. It represents
+        *   time as a number of microseconds since midnight, January 1st, 0 AD nominal 
+        *   Gregorian. This is the representation used by, e.g., the TTime class.
+        * @return KErrNone, if the operation is successful; KErrAlreadyExists, if
+        *   an attempt is being made to insert a duplicate process; otherwise one of
+        *   the other system wide error codes.
+        */
+        TInt AddProcessL( const TDesC8& aProcessName, 
+                         TUint aProcessId,
+                         CATStorageServerSession* aSessionObject,
+                         const TInt64& aStartTime );
+        
+        /**
+        * Removes a process from the server's arrays.
+        * @param aProcessId The ID of the process to be removed.
+        * @return KErrNone, if successful; KErrNotFound, if a process with
+        *   the specified process ID could not be found in the array.
+        */
+        TInt RemoveProcessL( TUint aProcessId );
+        
+        /**
+        * Adds a DLL for a given process to the dynamic process info array of this class.
+        * @param aProcessId The ID of the process that has loaded the DLL to be added.
+        * @param aDllInfo Information of the DLL.
+        * @return KErrNone, if successful; KErrNotFound, if a process with the given
+        *   process ID could not be found; KErrAlreadyExists, if a DLL with the given
+        *   name was already stored; otherwise one of the other system wide error codes.
+        */
+        TInt AddDllL( TUint aProcessId, const TATDllInfo aDllInfo );
+        
+        /**
+        * Removes a DLL associated with the given process from the dynamic process
+        * info array of this class.
+        * @param aProcessId The ID of the process that has loaded the DLL to be removed.
+        * @param aDllName The name of the DLL to be removed.
+        * @return KErrNone, if successful; KErrNotFound, if a process with
+        *   the specified process ID could not be found, or if a DLL with the specified
+        *   name could not be found.
+        */
+        TInt RemoveDllL( TUint aProcessId, const TDesC8& aDllName );
+            
+        /**
+        * Gives a reference to the process info array of this class.
+        * @return A reference to iProcesses array
+        */
+        const RArray<TATProcessInfo>& ProcessInfoArray();
+        
+        /**
+        * Gives a reference to the dynamic process info array of this class.
+        * @return A reference to iProcessesDyn array
+        */
+        const RPointerArray<CATDynProcessInfo>& DynProcessInfoArray();
+                
+    public: // Functions from base classes
+        
+        /**
+        * From CPolicyServer.
+        * Creates a new server-side session object.
+        * @param aVersion The version of this server
+        * @param aMessage A message from the client
+        * @return A pointer to a new session object.
+        */
+        CSession2* NewSessionL( const TVersion& aVersion, const RMessage2& aMessage ) const;
+        
+    private:
+
+        /**
+        * C++ default constructor.
+        * @param aPriority A priority for this active object
+        */
+        CATStorageServer( TInt aPriority );
+
+        /**
+        *  Symbian 2nd phase constructor.
+        */
+        void ConstructL();
+   
+    private: // Data
+        
+        /** The number of active sessions */
+        TInt iSessionCount;
+        
+        /** An array for storing TATProcessInfo objects */
+        RArray<TATProcessInfo> iProcesses;
+        
+        /** An array for storing CATDynProcessInfo pointers */
+        RPointerArray<CATDynProcessInfo> iProcessesDyn;
+    };
+
+#endif      // ATSTORAGESERVER_H
+            
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/inc/atstorageserversession.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,588 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Declaration of the server side session class CATStorageServerSession
+*
+*/
+
+
+#ifndef ATSTORAGESERVERSESSION_H
+#define ATSTORAGESERVERSESSION_H
+
+
+//  INCLUDES
+#include    <e32base.h>
+#include    <f32file.h>
+#include    <analyzetool/atcommon.h>
+
+// FORWARD DECLARATIONS
+class CATStorageServer;
+class CATMemoryEntry;
+
+// CLASS DECLARATIONS
+
+/**
+*  A class for storing memory addresses and sizes of allocations.
+*  Needed for giving allocation information for the configuration UI.
+*/
+class TAllocInfo
+    {
+    public:
+    
+    // Constructor
+    TAllocInfo( TUint32 aMemAddress, TInt aAllocSize );
+    
+    /** Address of a memory allocation. */
+    const TUint32 iMemAddress;
+    
+    /** Size of the associated allocation. */
+    const TInt iAllocSize;
+    };
+
+
+/**
+*  The session class for Storage Server.
+*  When the Storage Server client connects to the server, a new object of this
+*  class is constructed. So, for every client there is an associated object
+*  of this class. CATStorageServer forwards all client messages to their associated
+*  session objects.
+*/
+class CATStorageServerSession : public CSession2
+    {
+    public: // Enumerations
+        
+    public:  // Constructors and destructor
+        
+        /**
+        * Two-phased constructor that can leave.
+        * @return A new instance of this class
+        */
+        static CATStorageServerSession* NewL( CATStorageServer& aStorageServer );
+        
+        /**
+        * Two-phased constructor that can leave and leaves a pointer
+        * on the cleanup stack.
+        * @return A new instance of this class
+        */
+        static CATStorageServerSession* NewLC( CATStorageServer& aStorageServer );
+        
+        /**
+        * Destructor
+        */
+        virtual ~CATStorageServerSession();
+        
+    public: // Functions from base classes 
+        
+        /**
+        * Receives messages sent by a client.
+        * @param aMessage A message from a client
+        */
+        virtual void ServiceL( const RMessage2& aMessage );
+        
+    protected: // new functions
+        
+        /**
+        * Initializes this session for logging. This includes opening a logging file
+        * with a requested name. The method is to be called as the first method after
+        * connecting to the server. The method logs information on process starting into
+        * the just opened logging file.
+        * If a logging session is already ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is already
+        * ongoing. Otherwise one of the other system wide error codes.
+        */
+        TInt LogProcessStartedL( const RMessage2& aMessage );
+        
+        /**
+        * Initializes this session for logging. The method is to be called as the first
+        * method after connecting to the server. The method logs information on process
+        * starting into debug channel.
+        * If a logging session is already ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is already
+        * ongoing. Otherwise one of the other system wide error codes.
+        */
+        TInt LogProcessStartTraceL( const RMessage2& aMessage );
+         
+        /**
+        * Logs information on a DLL load into the opened file.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; Otherwise one of the other system wide error codes.
+        */
+        TInt LogDllLoadedL( const RMessage2& aMessage );
+        
+        /**
+        * Logs information on a DLL load into debug channel.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; Otherwise one of the other system wide error codes.
+        */
+        TInt LogDllLoadTraceL( const RMessage2& aMessage );
+        
+        /**
+        * Logs information on a DLL unload into the opened file.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; Otherwise one of the other system wide error codes.
+        */
+        TInt LogDllUnloadedL( const RMessage2& aMessage );
+        
+        /**
+        * Logs information on a DLL unload into debug channel.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; Otherwise one of the other system wide error codes.
+        */
+        TInt LogDllUnloadTraceL( const RMessage2& aMessage );
+        
+        /**
+        * Stores a memory allocation (memory address, current call stack, allocation
+        * time and allocation size) in an internal array.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; KErrAlreadyExists, if an attempt is being made to allocate
+        *   again an already allocated memory area; Otherwise one of the other system
+        *   wide error codes.
+        */
+        TInt LogMemoryAllocatedL( const RMessage2& aMessage );
+        
+        /**
+        * Logs information on a memory allocation into debug channel.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; KErrAlreadyExists, if an attempt is being made to allocate
+        *   again an already allocated memory area; Otherwise one of the other system
+        *   wide error codes.
+        */
+        TInt LogMemoryAllocTraceL( const RMessage2& aMessage );
+                
+        /**
+        * Check a memory allocation (memory address) from an internal array.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @param aRemoveAlloc Boolean to enable removing the found address from allocations.
+        * @return KErrNone, if memory address found in array; 
+        *   KErrNotFound, if the requested memory address was not found.
+        */
+        TInt IsMemoryAdded( const RMessage2& aMessage, const TBool aRemoveAlloc = EFalse );
+        
+        /**
+        * Removes a memory allocation (memory address, current call stack, allocation
+        * time and allocation size) from an internal array.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; KErrNotFound, if the requested memory address was not
+        *   found; Otherwise one of the other system wide error codes.
+        */
+        TInt LogMemoryFreedL( const RMessage2& aMessage );
+        
+        /**
+        * Logs information on freeing of a memory allocatin into debug channel.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; KErrNotFound, if the requested memory address was not
+        *   found; Otherwise one of the other system wide error codes.
+        */
+        TInt LogMemoryFreedTraceL( const RMessage2& aMessage );
+        
+        /**
+        * Logs all non-released memory allocations into the opened file as memory leaks.
+        * Then the method logs a number of possibly occured handle leaks into the file.
+        * Next, the method logs information on process ending into the logging file.
+        * Finally, this method closes the logging file opened for the connected process,
+        * and ends the current logging session. However, this method does not end the 
+        * actual client-server session.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; KErrNotSupported if this method is called with a wrong
+        *   process id from the client. Otherwise one of the other system wide error
+        *   codes.
+        */
+        TInt LogProcessEndedL( const RMessage2& aMessage );
+        
+        /**
+        * Logs a number of possibly occured handle leaks into debug channel. Then, the method
+        * logs information on process ending into debug channel. The method also
+        * ends the current logging session. However, this method does not end the actual
+        * client-server session.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrCancel, if a logging session is not
+        *   currently ongoing; KErrNotSupported if this method is called with a wrong
+        *   process id from the client. Otherwise one of the other system wide error
+        *   codes.
+        */
+        TInt LogProcessEndTraceL( const RMessage2& aMessage );
+        
+        /**
+        * Checks if a given memory address can be found.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return When the system is logging into a file: the index of a found 
+        *   memory address, or KErrNotFound, if a matching memory address cannot
+        *   be found. KErrNone, when the system is not logging into a file.
+        *   KErrCancel, if a logging session is not currently ongoing.
+        */
+        TInt CheckMemoryAddressL( const RMessage2& aMessage );
+        
+        /**
+        * Checks if a given memory address can be found.
+        * If a logging session is not ongoing, the method makes the client raise an
+        * STSEClient: 3 panic, and returns KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return When the system is logging into a file: the index of a found 
+        *   memory address, or KErrNotFound, if a matching memory address cannot
+        *   be found. KErrNone, when the system is not logging into a file.
+        *   KErrCancel, if a logging session is not currently ongoing.
+        */
+        TInt CheckMemoryAddressTrace( const RMessage2& aMessage );
+        
+        /**
+        * Gets all the processes currently logging with AnalyzeTool
+        * @param aMessage A message that includes parameters sent by the client.
+        *   On return a buffer including all the currently logging processes is written
+        *   into this message.
+        * @return KErrNone, if successful; otherwise one of the other system wide error
+        *   codes.
+        */
+        TInt GetProcessesL( const RMessage2& aMessage );
+        
+        /**
+        * Gets all the DLLs loaded by the process determined by the parameters.
+        * @param aMessage A message that includes parameters sent by the client.
+        *   A buffer including all the DLLs loaded by the requested process is
+        *   written into this message.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        TInt GetDllsL( const RMessage2& aMessage );
+        
+        /**
+        * Gets the logging mode of the process determined by the parameters.
+        * @param aMessage A message that includes parameters sent by the client.
+        *   On return, the logging mode is written into this message.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        TInt GetLoggingModeL( const RMessage2& aMessage );
+        
+        /**
+        * Starts a sub test for the given process.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process is not
+        *   found; KErrNotSupported, if the requested process does not have a logging
+        *   session ongoing or its logging mode is not EATLogToTrace; Otherwise one of the
+        *   other system wide error codes.
+        */
+        TInt StartSubtestL( const RMessage2& aMessage );
+        
+        /**
+        * Stops a sub test for the given process.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process is not
+        *   found; KErrNotSupported, if the requested process does not have a logging
+        *   session ongoing or its logging mode is not EATLogToTrace; Otherwise one of the
+        *   other system wide error codes.
+        */
+        TInt StopSubtestL( const RMessage2& aMessage );
+        
+        /**
+        * Starts a sub test for the calling process. Does not need a PID from the client.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrNotSupported, if the calling process
+        *   does not have a logging session ongoing or its logging mode is not
+        *   EATLogToTrace; Otherwise one of the other system wide error codes.
+        */
+        TInt StartSubtest2L( const RMessage2& aMessage );
+        
+        /**
+        * Stops a sub test for the calling process. Does not need a PID from the client.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrNotSupported, if the calling process
+        *   does not have a logging session ongoing or its logging mode is not
+        *   EATLogToTrace; Otherwise one of the other system wide error codes.
+        */
+        TInt StopSubtest2( const RMessage2& aMessage );
+        
+        /**
+        * Gets the number and total size of the current memory chunks allocated by the
+        * requested process.
+        * @param aMessage A message that includes parameters sent by the client. The
+        *   requested information is written into this message.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        TInt GetCurrentAllocsL( const RMessage2& aMessage );
+        
+        /**
+        * Gets the maximum number of memory chunks and the maximum amount of memory 
+        * allocated by the requested process during the test run.
+        * @param aMessage A message that includes parameters sent by the client. The
+        *   requested information is written into this message.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        TInt GetMaxAllocsL( const RMessage2& aMessage );
+        
+        /**
+        * Cancels logging for the requested process. After logging of a given process
+        * has been cancelled, the session associated with that process will not be
+        * usable anymore. If a process wants to start logging again, it needs to close
+        * the handle and open it again in order to create a new session. Until then, any
+        * of the server's methods that can be called by the client will return
+        * KErrCancel.
+        * @param aMessage A message that includes parameters sent by the client.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        TInt CancelLoggingL( const RMessage2& aMessage );
+        
+        /**
+        * Gets the logging file of the process determined by the parameters.
+        * @param aMessage A message that includes parameters sent by the client.
+        *   On return, the logging file is written into this message.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        TInt GetLoggingFileL( const RMessage2& aMessage );
+        
+        /**
+        * Gets the mode of the process determined by the parameters.
+        * @param aMessage A message that includes parameters sent by the client.
+        *   On return, the logging file is written into this message.
+        * @return KErrNone, if successful; KErrNotFound, if the requested process was
+        *   not found; otherwise one of the other system wide error codes.
+        */
+        TInt GetUdebL( const RMessage2& aMessage );
+        
+        /**
+        * Sets the mode of the process determined by the parameters.
+        * @param aMessage A message that includes parameters sent by the client.
+        */
+        void SetUdeb( const RMessage2& aMessage );
+        
+    private:  // New functions for internal use  
+    
+        /**
+        * Releases the resources reserved by this object, and before closing the logging
+        * file and file server session, the method logs information on the occured error
+        * into the logging file.
+        * @param aError The error code to be logged.
+        */
+        void HandleError( TInt aError );
+        
+        /**
+        * Releases the resources reserved by this object, and logs information on the
+        * occured error into debug channel.
+        * @param aError The error code to be logged.
+        */
+        void HandleErrorTrace( TInt aError );
+        
+        /**
+        * Opens a file server session and a file with the name specified.
+        * @param aFileName The name of the file into which to log.
+        * @param aProcessName Current process name.
+        * @return KErrNone, if successful; otherwise one of the other system wide
+        *   error codes.
+        */
+        TInt OpenFsAndFile( const TDesC& aFileName, const TDesC8& aProcessName );
+        
+        /**
+        * Method is used to parse file name extension.
+        * @param aFileName The name of the file into which to log.
+        * @param aExtension Parsed file extension. 
+        */
+        void ParseExtension( TDes& aFileName, TDes& aExtension );
+        
+        /**
+        * Called internally when need generate new file name.
+        * @param aFileName The name of the file into which to log.
+        * @param aProcessName Current process name.
+        */
+        void GenerateNewFileName( TDes& aFileName, const TDesC8& aProcessName );
+        
+        /**
+        * Method is used to check that file exists and is valid.
+        * @param aFileName The name of the file into which to log.
+        */
+        void CheckIfFileAlreadyExist( const TDes& aFileName );
+        
+        /**
+        * Method is used to check file version.
+        * @param aFileName The name of the file into which to log.
+        */
+        void CheckFileVersion( const TDes& aFileName );
+        
+        /**
+        * Closes the handles to the file server session and to the file (if currently open).
+        */
+        void CloseFsAndFile();
+        
+        /**
+        * Writes the memory leaks stored in the iLeakArray member array into the
+        * logging file opened for the current logging session. If the method is
+        * called in a wrong program state (logging session is not ongoing, or the
+        * logging mode is not EATLogToFile), STSEClient: 4, and STSEServer: 4
+        * panics are raised.
+        * @param aMessage The current message from the client.
+        * @return KErrNone, if successful; otherwise one of the other system wide
+        *   error codes.
+        */
+        TInt PrintLeaksL( const RMessage2& aMessage );
+        
+        /**
+        * Sets the server's mode of operation. The operation mode is determined with
+        * an enumeration value, which is received from the client. If the method is
+        * called in a wrong program state (logging session is ongoing), STSEClient: 4,
+        * and STSEServer: 4 panics are raised.
+        * @param aMessage The current message from the client.
+        */
+        void SetLogOption( const RMessage2& aMessage );
+        
+        /**
+        * Logs the given descriptor through debug channel.
+        * @param aLogString The descriptor to be logged.
+        * @return KErrNone, if successful; KErrNotSupported, if a logging session is not
+        *   ongoing, or the logging mode is not EATLogToTrace;
+        */
+        TInt LogThroughTrace( const TDesC& aLogString ) const;
+        
+        /**
+        * Gives a reference to the allocation info array of this class.
+        * @return A reference to iAllocInfoArray array
+        */
+        RArray<TAllocInfo>& AllocInfoArray();
+               
+        /**
+        * Creates a panic in the associated client's code.
+        * @param aPanic The panic code
+        * @param aMessage The message associated with this panic.
+        */
+        void PanicClient( TInt aPanic, const RMessage2& aMessage );
+        
+        /**
+        * Logs the abnormal end to the debug channel (If logging mode is EATLogToTrace) 
+        * and to the file(If logging mode is EATLogToFile).
+        */
+        void LogAbnormalEnd();
+        
+        /**
+        * Get the current universal time.
+        * @return Time
+        */
+        TInt64 GetTime();
+        
+    private: // Constructors 
+        
+        /**
+        * C++ default constructor.
+        */
+        CATStorageServerSession( CATStorageServer& aStorageServer );
+        
+        /**
+        *  Symbian 2nd phase constructor.
+        */
+        void ConstructL();   
+        
+    private: // Data
+        
+        /** A reference to the CATStorageServer object that has created this session */    
+        CATStorageServer& iStorageServer;
+               
+        /** A handle to a file server */
+        RFs iFileServer;
+        
+        /** A handle to a file */
+        RFile iFile;
+        
+        /** A member variable for storing results of server function calls. */ 
+        TInt iError;
+        
+        /** An object for getting time stamps */ 
+        TTime iTime;
+        
+        /** 
+        * An array for storing CATMemoryEntry pointers. Used when logging
+        * to an S60 file.
+        */
+        RPointerArray<CATMemoryEntry> iLeakArray;
+        
+        /** 
+        * An array for storing TAllocInfo objects. Used for keeping records on memory
+        * allocations and their sizes.
+        */
+        RArray<TAllocInfo> iAllocInfoArray;
+        
+        /** The ID of the process associated with this session. */
+        TUint iProcessId;
+        
+        /**
+        * A boolean telling whether this session has been initialized for logging
+        * ( whether the client's LogProcessStarted() method has been called ) or not.
+        */
+        TBool iLoggingOngoing;
+        
+        /**
+        * A variable telling the number of microseconds from January 1st, 0 AD
+        * nominal Gregorian to January 1st, 1970 AD nominal Gregorian. 
+        */
+        TInt64 iMicroSecondsAt1970;
+        
+        /**
+        * An enumeration that tells the current operation mode of the Storage Server.
+        */
+        TATLogOption iLogOption;
+        
+        /** The total size of all the current allocations of this process */
+        TUint32 iCurAllocSize;
+        
+        /** The maximum number of allocations of this process */
+        TUint32 iMaxAllocs;
+        
+        /** The maximum total size of allocations of this process */
+        TUint32 iMaxAllocSize;
+        
+        /** The logging file of this process */
+        TBuf8<KMaxFileName> iLogFile;
+
+        /** The mode of the session. Default is 1 = UDEB */
+        TUint32 iIsUdeb;
+    };
+
+#endif      // ATSTORAGESERVERSESSION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/src/atdllinfo.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for the class TATDllInfo.
+*
+*/
+
+// INCLUDE FILES
+#include "atdllinfo.h"
+#include "atlog.h"
+
+// -----------------------------------------------------------------------------
+// TATDllInfo::TATDllInfo
+// C++ default constructor.
+// -----------------------------------------------------------------------------
+//
+TATDllInfo::TATDllInfo( const TUint32 aStartAddress, const TUint32 aEndAddress,
+	const TInt64& aLoadTime, const TDesC8& aDllName  )
+ :  iStartAddress( aStartAddress ), iEndAddress( aEndAddress ), 
+	iLoadTime( aLoadTime )
+    {
+    LOGSTR3( "STSE TATDllInfo::TATDllInfo() %x - %x", iStartAddress, iEndAddress );
+    
+    iName.Copy( aDllName );
+    }
+
+// -----------------------------------------------------------------------------
+// TATDllInfo::StartAddress
+// Returns library start address
+// -----------------------------------------------------------------------------
+//
+TUint32 TATDllInfo::StartAddress()
+    {
+    LOGSTR2( "STSE TATDllInfo::StartAddress( %x )", iStartAddress );
+    
+    return iStartAddress;
+    }
+
+// -----------------------------------------------------------------------------
+// TATDllInfo::EndAddress
+// Returns library end address
+// -----------------------------------------------------------------------------
+//
+TUint32 TATDllInfo::EndAddress()
+    {
+    LOGSTR2( "STSE TATDllInfo::EndAddress( %x )", iEndAddress );
+    
+    return iEndAddress;
+    }
+
+// -----------------------------------------------------------------------------
+// TATDllInfo::Name
+// Gets specific library name
+// -----------------------------------------------------------------------------
+//
+TDes8& TATDllInfo::Name()
+    {
+    LOGSTR1( "STSE TATDllInfo::Name()" );
+    
+    return iName;
+    }
+
+// -----------------------------------------------------------------------------
+// TATDllInfo::LibraryLoadTime
+// Returns library load time
+// -----------------------------------------------------------------------------
+//
+TInt64 TATDllInfo::LibraryLoadTime()
+    {
+    LOGSTR1( "STSE TATDllInfo::LibraryLoadTime()" );
+    
+    return iLoadTime;
+    }
+        
+// -----------------------------------------------------------------------------
+// TATDllInfo::Match
+// Checks if two objects of this class match based on the objects's
+// saved library name.
+// -----------------------------------------------------------------------------
+//
+TBool TATDllInfo::Match( const TATDllInfo& aFirst, const TATDllInfo& aSecond )
+    {
+    LOGSTR1( "STSE TATDllInfo::Match()" );
+    
+    if ( aFirst.iName.Compare( aSecond.iName ) == 0 )
+        {
+        return ETrue;
+        }
+    return EFalse;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/src/atdriveinfo.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,188 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for the class TATDriveInfo.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include <f32file.h>
+#include <driveinfo.h>
+#include "atdriveinfo.h"
+#include "atstorageservercommon.h"
+#include "atlog.h"
+
+// -----------------------------------------------------------------------------
+// TATDriveInfo::TATDriveInfo
+// C++ default constructor.
+// -----------------------------------------------------------------------------
+//
+TATDriveInfo::TATDriveInfo()
+    {
+    LOGSTR1( "TATD TATDriveInfo::TATDriveInfo()" );
+    }
+
+// -----------------------------------------------------------------------------
+// TATDriveInfo::CreatePath()
+// -----------------------------------------------------------------------------
+//    
+TInt TATDriveInfo::CreatePath( TDes& aPath, 
+    const TDesC& aFileName, RFs& aFs )
+    {
+    LOGSTR1( "TATD TInt TATDriveInfo::CreatePath()" );
+    
+    // Drive letter    
+    TChar driveLetter;
+    // Drive number
+    TInt dNumber( EDriveZ );     
+    TBool found( EFalse );
+    // Drive type
+    TUint driveType( KDriveAttRemovable );    
+    TInt err( KErrNotFound );
+    
+    while ( !found )
+        {
+        // Get drive letter
+        if ( GetDrive( driveLetter, dNumber, aFs, driveType ) == KErrNotFound )
+        	{
+        	if ( driveType == KDriveAttInternal )
+        		{
+                return KErrNotFound;
+        		}       	
+            driveType = KDriveAttInternal;
+        	dNumber = EDriveZ;
+        	}       
+        else
+        	{
+			// Create path
+			aPath.Delete( 0, aPath.MaxLength() );
+			aPath.Append( driveLetter );
+		  
+		            
+		#ifdef __WINS__
+            // For emulator the data file is stored to different location
+            aPath.Append( KATDataFilePath );       
+		#else
+		    TDriveInfo driveInfo;
+		    aFs.Drive( driveInfo, dNumber );      
+            // The drive is removable( memory card ) so we can log inside of root folder
+            if ( driveInfo.iDriveAtt & KDriveAttRemovable )
+                {
+                aPath.Append( KATDataFilePath );       
+                }
+            // The drive is internal user can only access data folder so log into that
+            else
+                {
+                aPath.Append( KATDataFilePath2 );       
+                }
+		#endif
+						
+			// Make a directory for AToolStorageServer's logging data file
+			err = aFs.MkDir( aPath );
+			LOGSTR2( "STSE > aFs.MkDir err = %i", err );
+			
+			if ( !err || err == KErrAlreadyExists )
+				{                
+                if ( aFileName.Length() != 0 && 
+                     ( ( aPath.MaxLength() - aPath.Length() ) > aFileName.Length() ) )
+                    {
+                    aPath.Append( aFileName );
+                    }
+				found = ETrue;
+				}
+        	}
+        }        
+    return err;        
+    }
+
+// -----------------------------------------------------------------------------
+// TATDriveInfo::GetDrive()
+// -----------------------------------------------------------------------------
+//    
+TInt TATDriveInfo::GetDrive( TChar& aDrive, TInt& aDriveNumber, RFs& aFs, 
+	const TUint aDriveType )
+    {
+    LOGSTR1( "TATD TInt TATDriveInfo::GetDrive()" );
+       
+    // Contains drive information.
+    TDriveInfo driveInfo; 
+    
+    for ( TInt i = aDriveNumber; i >= (TInt)EDriveA; i-- )
+        {
+        // Gets information about a drive and the medium mounted on it.
+        // If error occured then skip to next drive.
+        if ( aFs.Drive( driveInfo, i ) != KErrNone )
+            continue;
+                
+        // Test whether drive is available. If not, skip to next drive.
+        if ( driveInfo.iDriveAtt & KDriveAbsent || i == (TInt)EDriveD ||
+             driveInfo.iDriveAtt & KDriveAttRom || 
+             driveInfo.iMediaAtt & KMediaAttWriteProtected ||
+             driveInfo.iDriveAtt & KDriveFileSysROFS )
+            continue;
+        
+        // Maps a drive number to the corresponding character.
+        if ( aFs.DriveToChar( i, aDrive ) != KErrNone )
+            continue;                
+        
+        if ( driveInfo.iDriveAtt & aDriveType &&
+             driveInfo.iType != EMediaNotPresent &&
+             driveInfo.iType != EMediaCdRom )
+            {
+            TUint status( 0 );
+            
+            switch ( aDriveType )
+                {
+                case KDriveAttRemovable:
+                    {
+                    // Get the drive status of the default removable mass storage.                    
+                    if ( DriveInfo::GetDriveStatus( aFs, i, status ) == KErrNone )
+                        {
+                        // To indicate that the drive is physically removable.
+                        if ( status & DriveInfo::EDriveRemovable &&
+                             !( status & DriveInfo::EDriveCorrupt ) )
+                            {
+                            aDriveNumber = --i;
+                            return KErrNone;
+                            }
+                        }
+                    }
+                    break;
+                case KDriveAttInternal:
+                    {
+                    // Get the drive status of the default removable mass storage.
+                    if ( DriveInfo::GetDriveStatus( aFs, i, status ) == KErrNone )
+                        {
+                        // To indicate that the drive is internal and 
+                        // cannot be physically removed.
+                        if ( status & DriveInfo::EDriveInternal &&
+                             !( status & DriveInfo::EDriveExternallyMountable ) )
+                            {
+                            aDriveNumber = --i;
+                            return KErrNone;
+                            }
+                        }
+                    }
+                    break;
+                    
+                default:
+                    break;
+                }
+            }
+        }
+    return KErrNotFound;
+    }
+ 
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/src/atdynprocessinfo.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for the class CATDynProcessInfo
+*
+*/
+
+
+// INCLUDE FILES
+#include    "atdynprocessinfo.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+
+// -----------------------------------------------------------------------------
+// CATDynProcessInfo::CATDynProcessInfo
+// -----------------------------------------------------------------------------
+//  
+CATDynProcessInfo::CATDynProcessInfo() :
+    iProcessId( KNullProcessId ),
+    iSessionObject( NULL )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CATDynProcessInfo::CATDynProcessInfo
+// -----------------------------------------------------------------------------
+//  
+CATDynProcessInfo::CATDynProcessInfo( TUint aProcessId,
+                                      CATStorageServerSession* aSessionObject,
+                                      const RArray<TATDllInfo>& aDlls ) :
+    iProcessId( aProcessId ),
+    iSessionObject( aSessionObject ),
+    iDlls( aDlls )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CATDynProcessInfo::CATDynProcessInfo
+// -----------------------------------------------------------------------------
+//  
+CATDynProcessInfo::CATDynProcessInfo( TUint aProcessId,
+                                      CATStorageServerSession* aSessionObject ) :
+    iProcessId( aProcessId ), iSessionObject( aSessionObject )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CATDynProcessInfo::CATDynProcessInfo
+// -----------------------------------------------------------------------------
+//  
+CATDynProcessInfo::CATDynProcessInfo( TUint aProcessId ) :
+    iProcessId( aProcessId ), iSessionObject( NULL )
+    {
+    }
+
+// Destructor
+CATDynProcessInfo::~CATDynProcessInfo()
+    {
+    iDlls.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CATDynProcessInfo::Compare
+// -----------------------------------------------------------------------------
+//  
+TInt CATDynProcessInfo::Compare( const CATDynProcessInfo& aFirst, 
+	const CATDynProcessInfo& aSecond )
+    {
+    if ( aFirst.iProcessId < aSecond.iProcessId )
+        {
+        return -1;
+        }
+    
+    if ( aFirst.iProcessId > aSecond.iProcessId )
+        {
+        return 1;
+        }
+   
+    // else
+    return 0;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/src/atmemoryentry.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,84 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for the class CATMemoryEntry
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "atmemoryentry.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+
+// -----------------------------------------------------------------------------
+// CATMemoryEntry::CATMemoryEntry
+// C++ default constructor.
+// -----------------------------------------------------------------------------
+//  
+CATMemoryEntry::CATMemoryEntry( TUint32 aMemAddress,
+                                const CBufFlat* aCallstackBuf,
+                                const TInt64& aAllocTime,
+                                TInt aAllocSize ) :
+    iMemAddress( aMemAddress ),
+    iCallstackBuf( aCallstackBuf ),
+    iAllocTime( aAllocTime ),
+    iAllocSize( aAllocSize )
+    {
+    }
+
+// Destructor
+CATMemoryEntry::~CATMemoryEntry()
+    {
+    delete const_cast<CBufFlat*>( iCallstackBuf );
+    }
+
+// -----------------------------------------------------------------------------
+// CATMemoryEntry::Compare
+// -----------------------------------------------------------------------------
+//  
+TInt CATMemoryEntry::Compare( const CATMemoryEntry& aFirst, const CATMemoryEntry& aSecond )
+    {
+    if ( aFirst.iAllocTime < aSecond.iAllocTime )
+        {
+        return -1;
+        }
+    
+    if ( aFirst.iAllocTime > aSecond.iAllocTime )
+        {
+        return 1;
+        }
+   
+    // else
+    return 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CATMemoryEntry::Match
+// -----------------------------------------------------------------------------
+//
+TBool CATMemoryEntry::Match( const CATMemoryEntry& aFirst, const CATMemoryEntry& aSecond )
+    {
+    if ( aFirst.iMemAddress == aSecond.iMemAddress )
+        {
+        return ETrue;
+        }
+    
+    // else
+    return EFalse;
+    }
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/src/atstorageserver.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,452 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions for the class CATStorageServer. Includes also the
+*                entry point of the atoolstorageserver.exe executable.
+*
+*/
+
+
+
+
+// INCLUDE FILES
+
+#include    "atstorageserver.h"
+#include    "atstorageserversession.h"
+#include    "atstorageservercommon.h"
+#include    "atlog.h"
+#include    "atdynprocessinfo.h"
+
+
+// CONSTANTS
+
+
+// The amount of different ranges of requests specified for this policy server.
+// In a policy server, different actions can be determined for different ranges
+// of requests.
+const TUint8 KAmountOfRanges = 2;
+
+
+const TInt ranges[KAmountOfRanges] =
+    {
+    CATStorageServer::EProcessStarted,
+    CATStorageServer::EOutOfBounds
+    };
+
+
+const TUint8 actionForRange[ KAmountOfRanges ] = 
+    { 0, CPolicyServer::ENotSupported };
+
+
+const CPolicyServer::TPolicyElement elements[] =
+    {
+    
+    { _INIT_SECURITY_POLICY_C1( ECapability_None ),
+          CPolicyServer::EFailClient }
+    
+    };
+
+
+const CPolicyServer::TPolicy policy =
+    {
+    CPolicyServer::EAlwaysPass, // On connect
+    KAmountOfRanges, // Range count
+    ranges,
+    actionForRange,
+    elements,
+    };
+
+
+
+// ENTRY POINT
+
+TInt E32Main()
+    { 
+    LOGSTR1( "STSE TInt E32Main() in ATStorageServer.cpp" );
+    
+    __UHEAP_MARK;
+    
+    // Create a cleanup stack 
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    
+    TInt errorCode( KErrNoMemory );
+    
+    // If there was enough memory to create a cleanup stack, 
+    // create and start the server.
+    if( cleanup )
+        {
+        // If RunServerL() doesn't leave, errorCode will be set to KErrNone
+        TRAP( errorCode, CATStorageServer::RunServerL() );
+        delete cleanup;
+        }
+
+    // Signal the client that server creation failed, if a leave occured during
+    // the call to 'RunServerL()' function
+    if( errorCode != KErrNone )
+        {
+        RProcess::Rendezvous( errorCode );
+        }
+    
+    __UHEAP_MARKEND;
+       
+    return errorCode;
+    
+    }
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::CATStorageServer
+// C++ default constructor can NOT contain any code that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CATStorageServer::CATStorageServer( TInt aPriority ) :
+    CPolicyServer( aPriority, policy, ESharableSessions ),
+    iSessionCount( 0 )
+    {
+    LOGSTR1( "STSE CATStorageServer::CATStorageServer()" );
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CATStorageServer::ConstructL()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CATStorageServer* CATStorageServer::NewL()
+    {
+    CATStorageServer* self = NewLC();
+    CleanupStack::Pop( self );
+    
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CATStorageServer* CATStorageServer::NewLC()
+    {  
+    CATStorageServer* self = new ( ELeave ) CATStorageServer( EPriorityStandard );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    self->StartL( KStorageServerName );
+    return self;
+    }
+
+// Destructor
+CATStorageServer::~CATStorageServer()
+    {
+    LOGSTR1( "STSE CATStorageServer::~CATStorageServer()" );
+    
+    iProcesses.Close();
+    iProcessesDyn.ResetAndDestroy();
+    iProcessesDyn.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::NewSessionL
+// Create a new server session.
+// -----------------------------------------------------------------------------
+// 
+CSession2* CATStorageServer::NewSessionL(
+    const TVersion &aVersion,
+    const RMessage2& /*aMessage*/ ) const
+    {
+    LOGSTR1( "STSE CSession2* CATStorageServer::NewSessionL()" );
+    
+    // The server's version
+    TVersion version( KVersionNumberMaj, KVersionNumberMin,
+        KVersionNumberBld );
+
+    // Check this is a high enough version of the server
+    if ( !User::QueryVersionSupported(version, aVersion) )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    
+    // Construct and return a new session object
+    return CATStorageServerSession::NewL( const_cast<CATStorageServer&>(*this) );
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::RunServerL
+// Create active scheduler and a server object
+// -----------------------------------------------------------------------------
+//    
+void CATStorageServer::RunServerL()
+    {
+    LOGSTR1( "STSE void CATStorageServer::RunServerL()" );
+    
+    // Create and install an active scheduler
+    CActiveScheduler* activeSched = new (ELeave) CActiveScheduler;
+    CleanupStack::PushL( activeSched );
+    CActiveScheduler::Install( activeSched );
+
+    // Create server
+    CATStorageServer::NewLC();
+     
+    // The initialization performed alright, signal the client
+    RProcess::Rendezvous( KErrNone );
+
+    // Start the active scheduler
+    CActiveScheduler::Start();
+
+    // Remove the server and active scheduler from the cleanup stack
+    CleanupStack::PopAndDestroy( 2, activeSched );
+    }
+  
+// -----------------------------------------------------------------------------
+// CATStorageServer::IncSessionCount
+// Increments the count of active sessions for this server.
+// -----------------------------------------------------------------------------
+// 
+void CATStorageServer::IncSessionCount()
+    {
+    LOGSTR1( "STSE void CATStorageServer::IncSessionCount()" );
+    
+    iSessionCount++;
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServer::DecSessionCount
+// Decrements the count of active sessions for this server.
+// -----------------------------------------------------------------------------
+// 
+void CATStorageServer::DecSessionCount()
+    {
+    LOGSTR1( "STSE void CATStorageServer::DecSessionCount()" );
+       
+    iSessionCount--;
+    
+    // Cancels all outstanding messages and stops the active scheduler,
+    // if there are no other sessions open at the moment
+    if ( iSessionCount <= 0 )
+        {
+        this->Cancel();
+        CActiveScheduler::Stop();
+        }
+    }
+  
+// -----------------------------------------------------------------------------
+// CATStorageServer::AddProcessL
+// -----------------------------------------------------------------------------
+// 
+TInt CATStorageServer::AddProcessL( const TDesC8& aProcessName,
+                                   TUint aProcessId,
+                                   CATStorageServerSession* aSessionObject,
+                                   const TInt64& aStartTime )
+    {
+    LOGSTR1( "STSE TInt CATStorageServer::AddProcessL()" );
+
+    TInt error( KErrNone );
+    TATProcessInfo processInfo;
+    
+    processInfo.iProcessId = aProcessId;
+    processInfo.iProcessName.Copy( aProcessName );
+    processInfo.iStartTime = aStartTime;
+    
+    // Insert the static process info into the iProcesses array
+    error = iProcesses.InsertInUnsignedKeyOrder( processInfo );
+    
+    // Return if an error occured
+    if ( error != KErrNone)
+        {
+        return error;
+        }
+    
+    // Construct a CATDynProcessInfo object with the given process ID and logging mode
+    CATDynProcessInfo* dynProcessInfo = 
+                            new (ELeave) CATDynProcessInfo( aProcessId,
+                                                            aSessionObject );
+    
+    // Insert the dynamic process info into the iProcessesDyn array
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    error = iProcessesDyn.InsertInOrder( dynProcessInfo, order );
+    
+    return error;
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServer::RemoveProcessL
+// -----------------------------------------------------------------------------
+// 
+TInt CATStorageServer::RemoveProcessL( TUint aProcessId )
+    {
+    LOGSTR1( "STSE TInt CATStorageServer::RemoveProcessL()" );
+    
+    TATProcessInfo processInfo;
+    processInfo.iProcessId = aProcessId;
+    
+    TInt index = iProcesses.FindInUnsignedKeyOrder( processInfo );
+
+    // Return, if a process with the requested process ID was not found
+    if ( index == KErrNotFound )
+        {
+        return index; 
+        }
+     
+    // Remove the TATProcessInfo object at "index" from the array
+    iProcesses.Remove( index );
+     
+    // Now, start removing the associated dynamic process info object
+
+    // Construct a CATDynProcessInfo object with the given process ID
+    CATDynProcessInfo* dynProcessInfo = 
+                            new (ELeave) CATDynProcessInfo( aProcessId );
+    
+    // Find the index of a CATDynProcessInfo object with the given ID in the array
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    index = iProcessesDyn.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+     
+    // Return, if a process with the requested process ID was not found
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+     
+    // Otherwise, delete the object and remove the pointer at "index"
+    delete iProcessesDyn[index];
+    iProcessesDyn.Remove( index ); 
+     
+    return KErrNone;   
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::AddDllL
+// -----------------------------------------------------------------------------
+// 
+TInt CATStorageServer::AddDllL( TUint aProcessId, 
+    const TATDllInfo aDllInfo )
+    {
+    LOGSTR1( "STSE TInt CATStorageServer::AddDllL()" );
+ 
+    // Construct a CATDynProcessInfo object with the given process ID
+    CATDynProcessInfo* dynProcessInfo = 
+		new (ELeave) CATDynProcessInfo( aProcessId );
+  
+    // Find out if a process with this ID can be found in the dynamic process array
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = iProcessesDyn.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+     
+    // Return, if a process with the requested process ID was not found 
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+        
+    // If we are here, the wanted process was found at index => append a DLL for it
+    dynProcessInfo = iProcessesDyn[index];
+    
+    // Get the DLL array from this dynamic process info object
+    RArray<TATDllInfo>& dllArray = dynProcessInfo->iDlls;    
+    
+    // Let's see if the DLL to be added already exists
+    TIdentityRelation<TATDllInfo> matcher( TATDllInfo::Match );
+    index = dllArray.Find( aDllInfo, matcher );
+    
+    // If so, return KErrAlreadyExists
+    if ( index != KErrNotFound )
+        {
+        return KErrAlreadyExists;
+        }
+
+    // Otherwise append this DLL to the array and return 
+    return dynProcessInfo->iDlls.Append( aDllInfo );
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::RemoveDllL
+// -----------------------------------------------------------------------------
+// 
+TInt CATStorageServer::RemoveDllL( TUint aProcessId,
+                                  const TDesC8& aDllName )
+    {
+    LOGSTR1( "STSE TInt CATStorageServer::RemoveDllL()" );
+
+    // Construct a CATDynProcessInfo object with the given process ID
+    CATDynProcessInfo* dynProcessInfo = 
+		new (ELeave) CATDynProcessInfo( aProcessId );
+  
+    // Find out if a process with this ID can be found in the dynamic process array
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = iProcessesDyn.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+     
+    // Return, if a process with the requested process ID was not found 
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+        
+    // If we are here, the wanted process was found at index
+    dynProcessInfo = iProcessesDyn[index];
+
+    // Get the DLL array from this dynamic process info object
+    RArray<TATDllInfo>& dllArray = dynProcessInfo->iDlls;
+    
+    // Try to find wanted DLL
+    TIdentityRelation<TATDllInfo> matcher( TATDllInfo::Match );    
+    index = dllArray.Find( TATDllInfo( 0, 0, 0, aDllName  ), matcher );
+    
+    // Return, if a process with the requested process ID was not found 
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+        
+    // Otherwise remove the found DLL at "index"
+    dllArray.Remove( index );    
+        
+    return KErrNone;  
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServer::ProcessInfoArray
+// -----------------------------------------------------------------------------
+// 
+const RArray<TATProcessInfo>& CATStorageServer::ProcessInfoArray()
+    {
+    LOGSTR1( "STSE RArray<TATProcessInfo>& CATStorageServer::ProcessInfoArray()" );
+     
+    return iProcesses;   
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServer::DynProcessInfoArray
+// -----------------------------------------------------------------------------
+// 
+const RPointerArray<CATDynProcessInfo>& CATStorageServer::DynProcessInfoArray()
+    {
+    LOGSTR1( "STSE RPointerArray<CATDynProcessInfo>& CATStorageServer::DynProcessInfoArray()" );
+     
+    return iProcessesDyn;   
+    }    
+    
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/server/src/atstorageserversession.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3397 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definitions and constants for the class CATStorageServerSession
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    <utf.h>
+#include    <analyzetool/analyzetooltraceconstants.h>
+#include    "atstorageserversession.h"
+#include    "atstorageserver.h"
+#include    "atstorageservercommon.h"
+#include    "atmemoryentry.h"
+#include    "atlog.h"
+#include    "atdynprocessinfo.h"
+#include    "atdriveinfo.h"
+
+// CONSTANTS
+
+// New file name start and end index.
+const TInt KNameIndexStart = 1;
+const TInt KNameIndexEnd = 100;
+
+// ==================== MEMBER FUNCTIONS for TAllocInfo ========================
+
+// -----------------------------------------------------------------------------
+// TAllocInfo::TAllocInfo
+// Implementation for the constructor of the class TAllocInfo
+// -----------------------------------------------------------------------------
+//
+TAllocInfo::TAllocInfo( TUint32 aMemAddress, TInt aAllocSize ) :
+    iMemAddress( aMemAddress ),
+    iAllocSize( aAllocSize )
+    {
+    }
+
+
+// ============== MEMBER FUNCTIONS for CATStorageServerSession =================
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::CATStorageServerSession
+// C++ default constructor. It Does not contain any code that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CATStorageServerSession::CATStorageServerSession( CATStorageServer& aStorageServer ) :
+    iStorageServer( aStorageServer ),
+    iError( 0 ),
+    iLeakArray( KLeakArrayGranularity ),
+    iProcessId( KNullProcessId ),
+    iLoggingOngoing( EFalse ),
+    iLogOption( KDefaultLoggingMode ),
+    iCurAllocSize( 0 ),
+    iMaxAllocs( 0 ),
+    iMaxAllocSize( 0 ),
+    iLogFile( KEmpty() ),
+    iIsUdeb( 1 )
+    {
+    LOGSTR1( "STSE CATStorageServerSession::CATStorageServerSession()" );
+    
+    // Initialize iMicroSecondsAt1970
+    TTime time( KJanuaryFirst1970 );
+    iMicroSecondsAt1970 = time.Int64();
+    
+    // Increment the server's session count by one (1)
+    iStorageServer.IncSessionCount();
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CATStorageServerSession::ConstructL()
+    {
+    // Intentionally left empty
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CATStorageServerSession* CATStorageServerSession::NewL( CATStorageServer& aStorageServer )
+    { 
+    CATStorageServerSession* self = NewLC( aStorageServer );
+    CleanupStack::Pop( self );
+    
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CATStorageServerSession* CATStorageServerSession::NewLC( CATStorageServer& aStorageServer )
+    { 
+    CATStorageServerSession* self = new ( ELeave ) CATStorageServerSession( aStorageServer );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::~CATStorageServerSession
+// Destructor
+// -----------------------------------------------------------------------------
+CATStorageServerSession::~CATStorageServerSession()
+    {
+    LOGSTR1( "STSE CATStorageServerSession::~CATStorageServerSession()" );
+      
+    // Empty the array and delete the referenced objects
+    iLeakArray.ResetAndDestroy();
+  
+    // Close the leak array
+    iLeakArray.Close();
+    
+    // Close the allocation info array
+    iAllocInfoArray.Close();
+    
+    // Check if process closed abnormal
+    if ( iProcessId != KNullProcessId && 
+         iLoggingOngoing && iLogOption != EATLoggingOff && 
+         iError != KErrNoMemory )
+        {
+        LogAbnormalEnd();
+        }
+    
+    // Close the file and the handle to the file server
+    CloseFsAndFile();
+    
+    // Remove the process with the current PID from the server's array of processes
+    TRAP_IGNORE( iStorageServer.RemoveProcessL( iProcessId ) );
+    
+    // Decrement the server's session count by one (1)
+    iStorageServer.DecSessionCount();
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::ServiceL
+// This function is called by the client/server framework
+// -----------------------------------------------------------------------------
+//
+void CATStorageServerSession::ServiceL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::ServiceL()" );
+    
+    // If logging has been cancelled for this session, return immediately
+    if( iLogOption == EATLoggingOff )
+        {
+        aMessage.Complete( KErrCancel );
+        return;
+        }
+    
+    switch ( aMessage.Function() )
+        {
+        case CATStorageServer::EProcessStarted:
+            {
+            // If logging is not ongoing, set the log option
+            if( !iLoggingOngoing )
+                {
+                // Set the operation mode
+                SetLogOption( aMessage );
+                }
+
+            switch ( iLogOption )
+                {
+                case EATLogToTrace:
+                    {
+                    iError = LogProcessStartTraceL( aMessage );
+                    }
+                break;
+                
+                case EATLogToFile:
+                    {
+                    iError = LogProcessStartedL( aMessage );
+                    }
+                break;
+                
+                default:
+                    {
+                    // Panic the client and set iError KErrCancel, because being
+                    // here implies that an illegal log option has been given.
+                    PanicClient( EAToolIllegalLogOption, aMessage );
+                    iError = KErrCancel;
+                    }
+                break;
+                }
+            } 
+        break;
+        
+        
+        case CATStorageServer::EDllLoaded:
+            {
+            switch ( iLogOption )
+                {
+                case EATLogToTrace:
+                    {
+                    iError = LogDllLoadTraceL( aMessage );
+                    }
+                break;
+                
+                case EATLogToFile:
+                    {
+                    iError = LogDllLoadedL( aMessage );
+                    }
+                break;
+                
+                default:
+                    {
+                    // Panic the client and set iError KErrCancel, because being
+                    // here implies that an illegal log option has been given.
+                    PanicClient( EAToolIllegalLogOption, aMessage );
+                    iError = KErrCancel;
+                    }
+                break;
+                }
+            }
+        break;
+        
+        
+        case CATStorageServer::EDllUnloaded:
+            {
+            switch ( iLogOption )
+                {
+                case EATLogToTrace:
+                    {
+                    iError = LogDllUnloadTraceL( aMessage );
+                    }
+                break;
+                
+                case EATLogToFile:
+                    {
+                    iError = LogDllUnloadedL( aMessage );
+                    }
+                break;
+                
+                default:
+                    {
+                    // Panic the client and set iError KErrCancel, because being
+                    // here implies that an illegal log option has been given.
+                    PanicClient( EAToolIllegalLogOption, aMessage );
+                    iError = KErrCancel;
+                    }
+                break;
+                }
+            }
+        break;
+        
+        
+        case CATStorageServer::EMemoryAllocated:
+            {
+            switch ( iLogOption )
+                {
+                case EATLogToTrace:
+                    {
+                    iError = LogMemoryAllocTraceL( aMessage );
+                    }
+                break;
+                
+                case EATLogToFile:
+                    {
+                    iError = LogMemoryAllocatedL( aMessage );
+                    }
+                break;
+                
+                default:
+                    {
+                    // Panic the client and set iError KErrCancel, because being
+                    // here implies that an illegal log option has been given.
+                    PanicClient( EAToolIllegalLogOption, aMessage );
+                    iError = KErrCancel;
+                    }
+                break;
+                }
+            }
+        break;
+        
+        
+        case CATStorageServer::EMemoryFreed:
+            {
+            switch ( iLogOption )
+                {
+                case EATLogToTrace:
+                    {
+                    iError = LogMemoryFreedTraceL( aMessage );
+                    }
+                break;
+                
+                case EATLogToFile:
+                    {
+                    iError = LogMemoryFreedL( aMessage );
+                    }
+                break;
+                
+                default:
+                    {
+                    // Panic the client and set iError KErrCancel, because being
+                    // here implies that an illegal log option has been given.
+                    PanicClient( EAToolIllegalLogOption, aMessage );
+                    iError = KErrCancel;
+                    }
+                break;
+                }
+            }
+        break;
+        
+        
+        case CATStorageServer::EProcessEnded:
+            {
+            switch ( iLogOption )
+                {
+                case EATLogToTrace:
+                    {
+                    iError = LogProcessEndTraceL( aMessage );
+                    }
+                break;
+                
+                case EATLogToFile:
+                    {
+                    iError = LogProcessEndedL( aMessage );
+                    }
+                break;
+                
+                default:
+                    {
+                    // Panic the client and set iError KErrCancel, because being
+                    // here implies that an illegal log option has been given.
+                    PanicClient( EAToolIllegalLogOption, aMessage );
+                    iError = KErrCancel;
+                    }
+                break;
+                }
+            }
+        break;
+        
+        
+        case CATStorageServer::EMemoryCheck:
+            {
+            switch ( iLogOption )
+                {
+                case EATLogToTrace:
+                    {
+                    iError = CheckMemoryAddressTrace( aMessage );
+                    }
+                break;
+                
+                case EATLogToFile:
+                    {
+                    iError = CheckMemoryAddressL( aMessage );
+                    }
+                break;
+                
+                default:
+                    {
+                    // Panic the client and set iError KErrCancel, because being
+                    // here implies that an illegal log option has been given.
+                    PanicClient( EAToolIllegalLogOption, aMessage );
+                    iError = KErrCancel;
+                    }
+                break;
+                }
+            }
+        break;
+        
+        
+        case CATStorageServer::EGetProcesses:
+            {
+            iError = GetProcessesL( aMessage );
+            }
+        break;
+        
+        
+        case CATStorageServer::EGetDlls:
+            {
+            iError = GetDllsL( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::EGetLoggingMode:
+            {
+            iError = GetLoggingModeL( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::ESubtestStart:
+            {
+            iError = StartSubtestL( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::ESubtestStop:
+            {
+            iError = StopSubtestL( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::ESubtestStart2:
+            {
+            iError = StartSubtest2L( aMessage );
+            }
+        break;
+               
+        case CATStorageServer::ESubtestStop2:
+            {
+            iError = StopSubtest2( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::EGetCurrentAllocs:
+            {
+            iError = GetCurrentAllocsL( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::EGetMaxAllocs:
+            {
+            iError = GetMaxAllocsL( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::ECancelLogging:
+            {
+            iError = CancelLoggingL( aMessage );
+            }
+        break;
+
+        case CATStorageServer::EGetUdeb:
+            {
+            iError = GetUdebL( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::EGetLoggingFile:
+            {
+            iError = GetLoggingFileL( aMessage );
+            }
+        break;
+
+        case CATStorageServer::EProcessUdeb:
+            {
+            SetUdeb( aMessage );
+            }
+        break;
+        
+        case CATStorageServer::EIsMemoryAdded:
+            {
+            iError = IsMemoryAdded( aMessage );
+            LOGSTR2( "STSE > IsMemoryAdded err = %i", iError );
+            }
+        break;       
+        
+        default:
+            {
+            // Panic both the client and server, because being here implies
+            // that there is an internal error in the client/server.
+            PanicClient( EAToolBadRequest, aMessage );
+            StorageServerPanic( KCategoryServer, EAToolBadRequest );
+            }
+        break;
+            
+        }
+    
+    // Complete the message, if it has not been already cancelled.
+    if ( iError != KErrCancel )
+        {
+        // Log the error code. Only KErrNoMemory errors are logged.
+        if ( iLogOption == EATLogToFile && iError == KErrNoMemory  )
+            {
+            HandleError( iError );
+            }
+        else if ( iLogOption == EATLogToTrace && iError == KErrNoMemory )
+            {
+            HandleErrorTrace( iError );
+            }
+               
+        // Complete serving the message 
+        aMessage.Complete( iError );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogProcessStartedL()
+// Opens a logging file with the requested name and then writes information
+// on process start into the file.
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::LogProcessStartedL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogProcessStartedL()" );
+    
+    // Panic the client and return, if this method has already been called for this
+    // session object (and a logging file has been opened)
+    if ( iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    iError = KErrNone;
+    
+    LOGMEM;
+    
+    // READ THE FIRST ARGUMENT (descriptor)  
+    
+    // Length of the first argument (index 0)
+    TInt length = aMessage.GetDesLength( 0 );
+    
+    LOGSTR2( "STSE length of the fileName: %i", length );
+    
+    // Return if errors
+    if ( length == KErrArgument || length == KErrBadDescriptor )
+        {
+        return length;
+        }
+    
+    // Construct a buffer for file name, and leave the pointer on Cleanup Stack
+    HBufC* fileName = HBufC::NewLC( length );
+    TPtr fileNamePtr( fileName->Des() );
+     
+    // Read the client side's descriptor at index 0
+    iError = aMessage.Read( 0, fileNamePtr );
+    
+    if ( iError != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( fileName );
+        return iError;
+        }
+    
+    // READ THE SECOND ARGUMENT (descriptor)  
+    
+    // Length of the second argument (index 1)   
+    length = aMessage.GetDesLength( 1 );
+    
+    LOGSTR2( "STSE length of the processName: %i", length );
+    
+    // Return if errors
+    if ( length == KErrArgument || length == KErrBadDescriptor )
+        {
+        CleanupStack::PopAndDestroy( fileName );
+        return length;
+        }
+    
+    HBufC8* processName = HBufC8::NewL( length );
+    TPtr8 bufPtr( processName->Des() );
+
+    // Read the client side's descriptor at index 1 
+    iError = aMessage.Read( 1, bufPtr );
+  
+    if ( iError != KErrNone )
+        {
+        delete processName;
+        CleanupStack::PopAndDestroy( fileName );
+        return iError;
+        }
+    
+    // READ THE THIRD ARGUMENT (integer, a process ID)    
+    TInt processId = aMessage.Int2();
+    
+    // Open a file server session and a file. The file
+    // will be opened with the name received from the client
+    iError = OpenFsAndFile( *fileName, *processName );
+    CleanupStack::PopAndDestroy( fileName );
+    // Return without logging, if an error occured
+    if ( iError != KErrNone )
+        {
+        // Delete the local objects
+        delete processName;
+        return iError;
+        }
+    
+    // Get the home time for the configuration UI
+    iTime.HomeTime();
+    
+    // Add the process into the server's array of processes
+    iError = iStorageServer.AddProcessL( *processName,
+                                        processId,
+                                        this,
+                                        iTime.Int64() );
+
+    // Return without logging, if an error occured
+    if ( iError )
+        {
+        // Remove, if something was added regardless of the error
+        // However, we must not remove an existing process
+        if ( iError != KErrAlreadyExists )
+            {
+            iStorageServer.RemoveProcessL( processId );
+            }
+        return iError;
+        }
+      
+    // Make a buffer that will be logged into the opened logging file
+    TBuf8<KProcessStartBufLength> loggingBuf;
+    loggingBuf.Format( KProcessStart, processName, processId );
+    
+    delete processName;
+    
+    // Get the current universal time       
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    loggingBuf.AppendNum( timeFrom1970, EHex );
+    
+    // Append udeb/urel information to the process start
+    loggingBuf.Append( KSpace );  
+    loggingBuf.AppendNum( iIsUdeb, EHex );
+    
+    // Append trace version information
+    loggingBuf.Append( KSpace );
+    loggingBuf.AppendNum( KATTraceVersion, EHex );
+    
+    // Append a new line
+    loggingBuf.Append( KNewLine );
+    
+    // Write the buffer into the file  
+    iError = iFile.Write( loggingBuf );
+    
+    // Return, if an error occured
+    if ( iError )
+        {
+        iStorageServer.RemoveProcessL( processId );
+        return iError;
+        }
+    
+    LOGMEM;
+    
+    // Set the process ID value for this logging session
+    iProcessId = processId;
+    // Set logging session started
+    iLoggingOngoing = ETrue;
+    
+    return iError;
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogProcessStartTraceL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::LogProcessStartTraceL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogProcessStartTraceL()" );
+    
+    // Panic the client and return, if this method has already been called for this
+    // session object
+    if ( iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    iError = KErrNone;
+    
+    LOGMEM;
+    
+    // READ THE SECOND ARGUMENT (descriptor)
+    // The first argument, file name, is ignored when logging thru trace  
+    
+    // Length of the second argument (index 1)
+    TInt length = aMessage.GetDesLength( 1 );
+    
+    LOGSTR2( "STSE length of the processName: %i", length );
+
+    // Return if errors
+    if ( length == KErrArgument || length == KErrBadDescriptor )
+        {
+        return length;
+        }
+
+    HBufC8* processName = HBufC8::NewL( length );
+    TPtr8 bufPtr( processName->Des() );
+
+    // Read the client side's descriptor at index 1 
+    iError = aMessage.Read( 1, bufPtr );
+  
+    if ( iError != KErrNone )
+        {
+        // Delete local objects and return
+        delete processName;
+        return iError;
+        }
+    
+    // READ THE THIRD ARGUMENT (integer, a process ID)    
+    TInt processId = aMessage.Int2();
+
+    // Get the home time for the configuration UI
+    iTime.HomeTime();
+    
+    // Add the process into the server's array of processes
+    iError = iStorageServer.AddProcessL( *processName, processId, this,
+                                             iTime.Int64() );
+    
+    // Return without logging, if an error occured
+    if ( iError )
+        {
+        // Remove, if something was added regardless of the error
+        // However, we must not remove an existing process
+        if ( iError != KErrAlreadyExists )
+            {
+            iStorageServer.RemoveProcessL( processId );
+            }
+        return iError;
+        }
+
+    // Make a buffer that will be logged
+    TBuf8<KProcessStartBufLength> loggingBuf;
+    
+    loggingBuf.Format( KProcessStart, processName, processId );
+    
+    delete processName;
+    
+    // Get the current universal time      
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    loggingBuf.AppendNum( timeFrom1970, EHex );
+    
+    // Append udeb/urel information to the process start
+    loggingBuf.Append( KSpace );
+    loggingBuf.AppendNum( iIsUdeb, EHex );
+    
+    // Append version number
+    loggingBuf.Append( KSpace );  
+    loggingBuf.AppendNum( KATTraceVersion, EHex );
+    
+    // Append a new line
+    loggingBuf.Append( KNewLine );
+    
+    // Log to trace
+    TBuf<KProcessStartBufLength> traceBuf;
+    traceBuf.Copy( loggingBuf );
+    RDebug::Print( KTraceMessage, processId ,&traceBuf );
+    
+    LOGMEM;
+    
+    // Set the process ID value for this logging session
+    iProcessId = processId;
+    // Set logging session started
+    iLoggingOngoing = ETrue;
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogDllLoadedL()
+// Logs to the file opened by the function LogProcessStartedL()
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::LogDllLoadedL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogDllLoadedL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    iError = KErrNone;
+    
+    // Read the length of the first argument (index 0)   
+    TInt length = aMessage.GetDesLength( 0 );
+    
+    // Return if errors
+    if ( length == KErrArgument || length == KErrBadDescriptor )
+        {
+        return length;
+        }
+    
+    HBufC8* dllName = HBufC8::NewL( length );
+    TPtr8 bufPtr( dllName->Des() );
+
+    // Read the client side's descriptor (the argument 0) 
+    iError = aMessage.Read( 0, bufPtr );
+  
+    if ( iError != KErrNone )
+        {
+        delete dllName;
+        return iError;
+        }
+    
+    // Get the current universal time
+	TInt64 timeFrom1970( GetTime() );
+        
+    // Add this dll into the server's array
+    TUint32 startAddress( aMessage.Int1() );        
+    TUint32 endAddress( aMessage.Int2() );
+    iError = iStorageServer.AddDllL( iProcessId, 
+    		TATDllInfo( startAddress, endAddress, timeFrom1970, *dllName ) );
+    
+    // Return without logging, if an error occured
+    if ( iError )
+        {
+        delete dllName;
+        return iError;
+        }
+    
+    // Make a buffer that will be logged into the opened logging file
+    TBuf8<KDllLoadBufLength> loggingBuf;
+    loggingBuf.Format( KDllLoad, dllName, timeFrom1970, startAddress, endAddress );
+    
+    delete dllName;
+    
+    // Write the buffer into a file and return the error code   
+    return iFile.Write( loggingBuf );
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogDllLoadTraceL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::LogDllLoadTraceL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogDllLoadTraceL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    iError = KErrNone;
+    
+    // Read the length of the first argument (index 0)
+    TInt length = aMessage.GetDesLength( 0 );
+    
+    // Return if errors
+    if ( length == KErrArgument || length == KErrBadDescriptor )
+        {
+        return length;
+        }
+    
+    HBufC8* dllName = HBufC8::NewL( length );
+    TPtr8 bufPtr( dllName->Des() );
+
+    // Read the client side's descriptor (the argument 0) 
+    iError = aMessage.Read( 0, bufPtr );
+  
+    if ( iError != KErrNone )
+        {
+        delete dllName;
+        return iError;
+        }
+    // Get the current universal time
+	TInt64 timeFrom1970( GetTime() );
+    	
+    TUint32 startAddress( aMessage.Int1() );
+    TUint32 endAddress( aMessage.Int2() );
+        
+    // Add this dll into the server's array 
+    iError = iStorageServer.AddDllL( iProcessId, 
+    		TATDllInfo( startAddress, endAddress, timeFrom1970, *dllName ) );
+    
+    // Return without logging, if an error occured
+    if ( iError )
+        {
+        delete dllName;
+        return iError;
+        }
+    
+    // Make a buffer that will be logged
+    TBuf8<KDllLoadBufLength> loggingBuf;
+    loggingBuf.Format( KDllLoad, dllName, timeFrom1970, startAddress, endAddress );
+    
+    delete dllName;
+    
+    TBuf<KDllLoadBufLength> traceBuf;
+    traceBuf.Copy( loggingBuf );
+    RDebug::Print( KTraceMessage, iProcessId ,&traceBuf );
+    return iError;
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogDllUnloadedL()
+// Logs to the file opened by the function LogProcessStartedL()
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::LogDllUnloadedL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogDllUnloadedL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    iError = KErrNone;
+    
+    // Read the length of the first argument (index 0)   
+    TInt length = aMessage.GetDesLength( 0 );
+    
+    LOGSTR2( "STSE length %i", length );
+    
+    // Return if errors
+    if ( length == KErrArgument || length == KErrBadDescriptor )
+        {
+        return length;
+        }
+    
+    HBufC8* dllName = HBufC8::NewL( length );
+    TPtr8 bufPtr( dllName->Des() );
+
+    // Read the client side's descriptor (the argument 0) 
+    iError = aMessage.Read( 0, bufPtr );
+  
+    if ( iError != KErrNone )
+        {
+        delete dllName;
+        return iError;
+        }
+       
+    TUint32 startAddress = aMessage.Int1();
+    TUint32 endAddress = aMessage.Int2();
+    
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+        
+    // Make a buffer that will be logged into the opened logging file
+    TBuf8<KDllUnloadBufLength> loggingBuf;
+    loggingBuf.Format( KDllUnload, dllName, timeFrom1970, startAddress, endAddress );
+    
+    // Remove this dll from the server's array
+    iError = iStorageServer.RemoveDllL( iProcessId, bufPtr );
+    
+    delete dllName;
+    
+    // Return without logging, if an error occured
+    if ( iError )
+        {
+        return iError;
+        }
+     
+    // Write the buffer into a file and return the error code   
+    return iFile.Write( loggingBuf );
+    }
+ 
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogDllUnloadTraceL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::LogDllUnloadTraceL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogDllUnloadTraceL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+        
+    iError = KErrNone;
+    
+    // Read the length of the first argument (index 0)   
+    TInt length = aMessage.GetDesLength( 0 );
+    
+    LOGSTR2( "STSE length %i", length );
+    
+    // Return if errors
+    if ( length == KErrArgument || length == KErrBadDescriptor )
+        {
+        return length;
+        }
+    
+    HBufC8* dllName = HBufC8::NewL( length );
+    TPtr8 bufPtr( dllName->Des() );
+
+    // Read the client side's descriptor (the argument 0) 
+    iError = aMessage.Read( 0, bufPtr );
+  
+    if ( iError != KErrNone )
+        {
+        delete dllName;
+        return iError;
+        }
+    
+    TUint32 startAddress = aMessage.Int1();
+    TUint32 endAddress = aMessage.Int2();
+    
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+        
+    // Make a buffer that will be logged
+    TBuf8<KDllUnloadBufLength> loggingBuf;
+    loggingBuf.Format( KDllUnload, dllName, timeFrom1970, startAddress, endAddress );
+    
+    // Remove this dll from the server's array
+    iError = iStorageServer.RemoveDllL( iProcessId, bufPtr );
+    
+    delete dllName;
+    
+    // Return without logging, if an error occured
+    if ( iError )
+        {
+        return iError;
+        }
+    
+    TBuf<KDllLoadBufLength> traceBuf;
+    traceBuf.Copy( loggingBuf );
+    RDebug::Print( KTraceMessage, iProcessId ,&traceBuf );
+    return iError;
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogMemoryAllocatedL()
+// Constructs a CATMemoryEntry object and appends it into iLeakArray.
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::LogMemoryAllocatedL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogMemoryAllocatedL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }     
+    
+    // A pointer to a buffer of call stack's memory addresses
+    CBufFlat* stackBuf = NULL;
+    
+    iError = KErrNone;
+    
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Read the first argument (index 0)
+    TUint32 memAddress = aMessage.Int0();
+    if ( memAddress == 0 )
+        {
+        return KErrNotSupported;
+        }
+    
+    // Read the length of the descriptor argument (index 1) that should include
+    // call stack memory addresses associated with this memory allocation
+    TInt bufferLength = aMessage.GetDesLength( 1 );
+    
+    // Construct a buffer for aCallstack
+    stackBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( stackBuf );
+    
+    // Buffer position
+    TInt pos = 0;
+    
+    stackBuf->ExpandL( pos, bufferLength );
+
+    TPtr8 bufPtr = stackBuf->Ptr( pos );
+
+    // Read the descriptor argument into the buffer
+    aMessage.ReadL( 1, bufPtr );
+
+    // Read the third argument (index 2) that tells the size of this allocation
+    TInt size = aMessage.Int2();
+    
+    // Construct a new CATMemoryEntry object.   
+    // The ownership of the current stackBuf object is given to the "entry" object.
+    CATMemoryEntry* entry = 
+        new (ELeave) CATMemoryEntry( memAddress, stackBuf, timeFrom1970, size );
+    
+    // Pop stackBuf from CleanupStack and set it to NULL, because it is not used anymore.
+    CleanupStack::Pop( stackBuf );
+    stackBuf = NULL;
+    
+    // Make sure that the same memory area is not tryed to be allocated a second time
+    TIdentityRelation<CATMemoryEntry> matcher( CATMemoryEntry::Match );
+
+    TInt index = iLeakArray.Find( entry, matcher );
+    
+    if ( index == KErrNotFound )
+        {
+        TLinearOrder<CATMemoryEntry> order( CATMemoryEntry::Compare );
+        
+        // Insert the "entry" object into "iLeakArray". The ownership of
+        // the "entry" object is given to the array.
+        iError = iLeakArray.InsertInOrderAllowRepeats( entry, order );
+               
+        // If an insertion to the array was not successful, delete the created
+        // entry manually and return.
+        if ( iError )
+            {
+            delete entry;
+            return iError;
+            }
+        
+        // Make a TAllocInfo object, and give values for its members.
+        TAllocInfo allocInfo( memAddress, size );
+
+        // Insert the allocInfo object into iAllocInfoArray
+        iError = iAllocInfoArray.InsertInUnsignedKeyOrder( allocInfo );
+    
+        // If an insertion to the array was not successful, delete the created entry
+        // and remove its pointer from iLeakArray.
+        if ( iError )
+            {
+            index = iLeakArray.Find( entry, matcher );
+            // Delete the entry object and remove remove the pointer from the array
+            delete entry;
+            // The index should be in a legal range, because the earlier insertion of
+            // the entry was successful
+            iLeakArray.Remove( index );
+            }
+        
+        // Otherwise update the iCurAllocSize, iMaxAllocs and iMaxAllocSize variables
+        
+        iCurAllocSize += size;
+        
+        // The count can never be negative => associate it to an unsigned int
+        TUint allocCount = iAllocInfoArray.Count();
+        if ( allocCount > iMaxAllocs )
+            {
+            iMaxAllocs = allocCount;
+            }
+        
+        if ( iCurAllocSize > iMaxAllocSize )
+            {
+            iMaxAllocSize = iCurAllocSize;
+            }
+        
+        return iError;
+        }
+        
+    // This shouldn't happen, because the same memory area shouldn't be allocated
+    // more than once (without deallocating it first)
+    else
+        {
+        delete entry;
+        return KErrAlreadyExists;
+        }
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogMemoryAllocTraceL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::LogMemoryAllocTraceL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogMemoryAllocTraceL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    // Read the first argument (index 0)
+    TUint32 memAddress = aMessage.Int0();
+    if ( memAddress == 0 )
+        {
+        return KErrNotSupported;
+        }
+    
+    // Read the third argument (index 2) that tells the size of this allocation
+    TInt size = aMessage.Int2();
+    
+    // Append this allocation into the iAllocInfoArray array. This array is for
+    // providing the configuration UI with information on allocations
+    
+    // Make a TAllocInfo object, and give values for its members.
+    TAllocInfo allocInfo( memAddress, size );
+
+    // Insert the allocInfo object into iAllocInfoArray
+    iError = iAllocInfoArray.InsertInUnsignedKeyOrder( allocInfo );
+    
+    // Log debug message if duplicated allocation.
+    if ( iError == KErrAlreadyExists )
+        {
+        LOGSTR2( "STSE TInt CATStorageServerSession::LogMemoryAllocTraceL() Error, duplicate allocation :%i", memAddress );
+        }
+
+    // A pointer to a buffer of call stack's memory addresses
+    CBufFlat* stackBuf = NULL;
+    
+    // Get the current universal time           
+    TInt64 timeFrom1970( GetTime() );     
+    
+    // Read the length of the descriptor argument (index 1) that should include
+    // call stack memory addresses associated with this memory allocation
+    TInt bufferLength = aMessage.GetDesLength( 1 );
+    
+    // Construct a buffer for aCallstack
+    stackBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( stackBuf );
+    
+    // Buffer position
+    TInt pos( 0 );    
+    stackBuf->ExpandL( pos, bufferLength );
+    
+    TPtr8 bufPtr = stackBuf->Ptr( pos );
+    
+    // Read the descriptor argument (index 1) into the buffer
+    aMessage.ReadL( 1, bufPtr );
+    
+    // Variable for the number of memory addresses in the call stack
+    TInt addrCount( 0 );    
+    TUint32 callStackAddr;
+    
+    // Read the first word of the buffer. This includes the number of
+    // memory addresses stored in the current stackBuf   
+    stackBuf->Read( pos, &addrCount, KWordSize );
+    
+    // Move the position one word onwards.    
+    pos += KWordSize;
+    
+    // Create a 16-bit buffer, and a pointer descriptor for it    
+    // ALLOCH <Memory address> <Time stamp> <Allocation size> <Call stack address count> 
+    // <Call stack address> <Call stack address> ...
+    HBufC* traceBuf = HBufC::NewL( KMemAllocBufLength );
+    TPtr tracePtr( traceBuf->Des() );
+    
+    // Pop stackBuf from CleanupStack, since no leavable operations will be done
+    // anymore
+    CleanupStack::Pop( stackBuf );
+    
+    // Append the tag implying a memory allocation line in the data file
+    tracePtr.Append( KMemoryAllocHeader );
+    
+    // Append the start address of this allocation in the 32-bit (max 8 characters)
+    // hexadecimal text format.
+    tracePtr.AppendNum( memAddress, EHex );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    tracePtr.Append( KSpaceTrace );
+    tracePtr.AppendNum( timeFrom1970, EHex );
+    
+    // Append the size of the allocation in the 32-bit (max 8 characters) hexadecimal
+    // text format.
+    tracePtr.Append( KSpaceTrace );
+    tracePtr.AppendNum( size, EHex );
+    
+    // Append call stack address count
+    tracePtr.Append( KSpaceTrace );
+    tracePtr.AppendNum( addrCount, EHex );
+    
+    // Calculate last item length
+    TInt lastItemLength( KTraceMessage().Length() + KHexa32Length + 
+            KSpaceLength + KNewlineLength );
+    
+    TUint packetNumber( 1 );
+    
+    // Go through all call stack's memory addresses associated with
+    // this memory allocation 
+    for ( TInt j = 0; j < addrCount; j++ )
+        {
+        // ALLOCF <Memory address> <Time stamp> <Packet number> 
+        // <Call stack address> <Call stack address> ...
+        if ( tracePtr.Length() <= 0 )
+            {                
+            // Create alloc fragment message header
+            tracePtr.Append( KMemoryAllocFragment );
+            tracePtr.AppendNum( memAddress, EHex );
+            tracePtr.Append( KSpaceTrace );
+            tracePtr.AppendNum( timeFrom1970, EHex );
+            tracePtr.Append( KSpaceTrace );        
+            tracePtr.AppendNum( packetNumber, EHex );
+            // Increase packet number
+            packetNumber++;
+            }
+        
+        // Read the next call stack's memory address stored in the buffer.
+        stackBuf->Read( pos, &callStackAddr, KWordSize );
+        
+        // Append the read memory address as a hexadecimal number
+        tracePtr.AppendFormat( KHexaNumberTrace, callStackAddr );
+        
+        // Move the pos variable one word onwards.
+        pos += KWordSize;
+        
+        // Check if buffer max length exceed
+        if ( lastItemLength + tracePtr.Length() >= KMemAllocBufLength )
+            {
+            tracePtr.Append( KNewLineTrace );
+            // Log through debug channel 
+            RDebug::Print( KTraceMessage, iProcessId, traceBuf );
+            // Empty trace buffer
+            tracePtr.Delete( 0, tracePtr.MaxLength() );
+            }
+        }
+    
+    // Send the last message if exists
+    if ( tracePtr.Length() > 0 )
+        {
+        tracePtr.Append( KNewLineTrace );
+        
+        // Log through debug channel 
+        RDebug::Print( KTraceMessage, iProcessId, traceBuf );
+        }
+    
+    delete traceBuf;
+    delete stackBuf;
+    
+    // Update the iCurAllocSize, iMaxAllocs and iMaxAllocSize variables            
+    iCurAllocSize += size;
+    
+    // The count can never be negative => associate it to an unsigned int
+    TUint allocCount = iAllocInfoArray.Count();
+    if ( allocCount > iMaxAllocs )
+        {
+        iMaxAllocs = allocCount;
+        }
+    
+    if ( iCurAllocSize > iMaxAllocSize )
+        {
+        iMaxAllocSize = iCurAllocSize;
+        }
+    
+    return KErrNone;    
+    }    
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogMemoryFreedL()
+// Removes a TATMemoryEntry object with the specified memory address from 
+// iLeakArray, if found.
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::LogMemoryFreedL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogMemoryFreedL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    // Get the memory address
+    TUint32 memAddress = aMessage.Int0();
+    
+    // Remove this memory allocation from the leak array
+    TIdentityRelation<CATMemoryEntry> matcher( CATMemoryEntry::Match );
+    CATMemoryEntry* entry = new (ELeave) CATMemoryEntry( memAddress, NULL, 0, 0 );
+    TInt index = iLeakArray.Find( entry, matcher );
+    delete entry;
+    
+    // Return, if the requested memory address was not found
+    // (had not been allocated)
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Delete the CATMemoryEntry object at "index" and remove from the array
+    delete iLeakArray[index];
+    iLeakArray.Remove( index );
+    
+    // Remove this memory allocation also from the allocation info array
+    // Make a TAllocInfo object for a "find" operation
+    TAllocInfo allocInfo( memAddress, 0 );
+    index = iAllocInfoArray.FindInUnsignedKeyOrder( allocInfo );
+    
+    // The index should not be KErrNotFound, because an object with this memory address
+    // was found in the iLeakArray array. If the index is out of range, something is
+    // badly wrong, so it would be alright to panic in that case.
+    if ( index == KErrNotFound )
+        {
+        PanicClient( EAToolInternalError, aMessage );
+        return KErrCancel;
+        }
+    
+    // Decrease the current alloc size and remove the requested allocation
+    // from iAllocInfoArray
+    iCurAllocSize -= iAllocInfoArray[index].iAllocSize;
+    iAllocInfoArray.Remove( index );
+    
+    // If we are here, everything has gone alright
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::IsMemoryAdded()
+// Check a memory allocation (memory address) from an internal array.
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::IsMemoryAdded( const RMessage2& aMessage, 
+    const TBool aRemoveAlloc )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::IsMemoryAdded()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+        
+    // Read the first argument (index 0)
+    TUint32 memAddress = aMessage.Int0();
+    
+    // Try to find this memory allocation from the allocation info array
+    
+    // Make a TAllocInfo object for a "find" operation
+    TAllocInfo allocInfo( memAddress, 0 );
+    TInt index( iAllocInfoArray.FindInUnsignedKeyOrder( allocInfo ) );
+    
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    else if ( aRemoveAlloc )
+        {
+        // Otherwise decrease the current alloc size and remove the requested allocation
+        // from iAllocInfoArray
+        iCurAllocSize -= iAllocInfoArray[index].iAllocSize;
+        iAllocInfoArray.Remove( index );
+        }
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogMemoryFreedTraceL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::LogMemoryFreedTraceL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogMemoryFreedTraceL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    // A pointer to a buffer of call stack's memory addresses
+    CBufFlat* stackBuf = NULL;        
+    iError = KErrNone;    
+    
+    // Read the first argument (index 0)
+    TUint32 memAddress = aMessage.Int0();
+
+    // Remove address from allocation table and its size from alloc size,
+    // if found from table.
+    TAllocInfo allocInfo( memAddress, 0 ); // Dummy info for search.
+    TInt index( iAllocInfoArray.FindInUnsignedKeyOrder( allocInfo ) );
+    if ( index != KErrNotFound )
+        {
+        // Decrease the current alloc size and remove the requested allocation
+        // from table.
+        iCurAllocSize -= iAllocInfoArray[index].iAllocSize;
+        iAllocInfoArray.Remove( index );
+        }
+    else
+        {
+        LOGSTR2( "STSE TInt CATStorageServerSession::LogMemoryFreedTrace() Error, cannot find alloc for free: %i", memAddress );
+        }
+    
+    // Read the length of the descriptor argument (index 1) that should include
+    // call stack memory addresses associated with this memory allocation
+    TInt bufferLength = aMessage.GetDesLength( 1 );
+    
+    // Construct a buffer for aCallstack
+    stackBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( stackBuf );
+    
+    // Buffer position
+    TInt pos = 0;
+    
+    stackBuf->ExpandL( pos, bufferLength );
+
+    TPtr8 bufPtr = stackBuf->Ptr( pos );
+
+    // Read the descriptor argument (index 1) into the buffer
+    aMessage.ReadL( 1, bufPtr );
+    
+    // Variable for the number of memory addresses in the call stack
+    TInt addrCount( 0 );    
+    TUint32 callStackAddr( 0 );
+
+    // Read the first word of the buffer. This includes the number of
+    // memory addresses stored in the current stackBuf
+    stackBuf->Read( pos, &addrCount, KWordSize );
+
+    // Move the position one word onwards.
+    pos += KWordSize;
+    
+    // Create a 16-bit buffer, and a pointer descriptor for it
+    HBufC* traceBuf = HBufC::NewL( KMemFreedBufLength );
+    TPtr tracePtr( traceBuf->Des() );
+    
+    // Pop stackBuf from CleanupStack, since no leavable operations will be done
+    // anymore
+    CleanupStack::Pop( stackBuf );
+    
+	// Get the current universal time		
+	TInt64 timeFrom1970( GetTime() );
+			
+    // Memory deallocation header message.
+    // FREEH <Memory address> <Time stamp> <Call stack address count> <Call stack address>
+    // <Call stack address> ...
+
+    // Append the tag implying a memory free line in the data file
+    tracePtr.Append( KMemoryFreedHeader );
+    
+    // Append the start address of this allocation in the 32-bit (max 8 characters)
+    // hexadecimal text format.
+    tracePtr.AppendNum( memAddress, EHex );    
+    
+	// Append the current time in the 64-bit (max 16 characters) hexadecimal text
+	// format
+	tracePtr.Append( KSpaceTrace );
+	tracePtr.AppendNum( timeFrom1970, EHex );
+			
+    // Append call stack address count
+    tracePtr.Append( KSpaceTrace );
+    tracePtr.AppendNum( addrCount, EHex );
+    
+    // Packet number
+    TUint packetNumber( 1 );
+    
+    // Calculate last item length
+    TInt lastItemLength( KTraceMessage().Length() + KHexa32Length + 
+            KSpaceLength + KNewlineLength );
+    
+    // Go through all call stack's memory addresses associated with
+    // this memory allocation 
+    for ( TInt j = 0; j < addrCount; j++ )
+        {
+        if ( tracePtr.Length() <= 0 )
+            {
+            // Memory deallocation fragment message.
+            // FREEF <Memory address> <Time stamp> <Packet number> <Call stack address count>
+            // <Call stack address>...
+            // Create free fragment message header
+            tracePtr.Append( KMemoryFreedFragment );
+            tracePtr.AppendNum( memAddress, EHex );
+            tracePtr.Append( KSpaceTrace );    
+			tracePtr.AppendNum( timeFrom1970, EHex );
+			tracePtr.Append( KSpaceTrace );	
+            tracePtr.AppendNum( packetNumber, EHex );
+            // Increase packet number
+            packetNumber++;
+            }
+        
+        // Read the next call stack's memory address stored in the buffer.
+        stackBuf->Read( pos, &callStackAddr, KWordSize );
+        
+        // Append the read memory address as a hexadecimal number
+        tracePtr.AppendFormat( KHexaNumberTrace, callStackAddr );
+        
+        // Move the pos variable one word onwards.
+        pos += KWordSize;
+        
+        // Check if buffer max length exceed
+        if ( lastItemLength + tracePtr.Length() >= KMemFreedBufLength )
+            {
+            tracePtr.Append( KNewLineTrace );
+            // Log through debug channel 
+            RDebug::Print( KTraceMessage, iProcessId, traceBuf );
+            // Empty trace buffer
+            tracePtr.Delete( 0, tracePtr.MaxLength() );
+            }
+        }
+    
+    // Send the last message if exists
+    if ( tracePtr.Length() > 0 )
+        {
+        tracePtr.Append( KNewLineTrace );
+        
+        // Log through debug channel 
+        RDebug::Print( KTraceMessage, iProcessId, traceBuf );
+        }
+        
+    delete traceBuf;
+    delete stackBuf;
+    // If we are here, everything has gone alright
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogProcessEndedL()
+// Prints memory leaks and information on process end into a file opened by the
+// function LogProcessStartedL()
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::LogProcessEndedL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogProcessEndedL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    iError = KErrNone;
+    
+    // Read the sent process ID
+    TUint processId = aMessage.Int0();
+ 
+    // The process ID got from the client should equal iProcessId.
+    // If it does not, return KErrNotSupported
+    if ( processId != iProcessId )
+        {
+        return KErrNotSupported;
+        }
+    
+    //////////////////////////////////////////////
+    // Log memory leaks
+    //////////////////////////////////////////////  
+    
+    // Print the information on the memory allocations that were never freed
+    iError = PrintLeaksL( aMessage );
+    
+    if ( iError != KErrNone )
+        {
+        return iError;
+        }    
+    
+    //////////////////////////////////////////////
+    // Log handle leaks
+    ////////////////////////////////////////////// 
+
+    TUint handleLeakCount = aMessage.Int1();
+    
+    if( handleLeakCount == 0 )
+        {
+        LOGSTR1( "STSE TInt CATStorageServerSession::LogProcessEndedL() No handle leaks to report" );
+        }
+    else
+        {
+        // Make a buffer that will be logged
+        TBuf8<KHandleLeakBufLength> loggingBuf;
+        
+        // Set handle leak module name to unknown since it can not be defined.
+        // Write the handle leak count from aMessage.
+        loggingBuf.Format( KHandleLeak, &KUnknownModule, handleLeakCount );
+    
+        // Write the constructed string into the data file and return if error
+        iError = iFile.Write( loggingBuf );
+    
+        if ( iError != KErrNone )
+            {
+            return iError;
+            }
+        }
+    
+    //////////////////////////////////////////////
+    // Log process end
+    //////////////////////////////////////////////
+           
+    // Make a buffer that will be logged into the opened logging file
+    TBufC8<KProcessEndBufLength> processEndBuf;
+    
+    TPtr8 bufPtr = processEndBuf.Des();
+    
+    bufPtr.AppendFormat( KProcessEnd, iProcessId );
+    
+    // Get the current universal time       
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format         
+    bufPtr.AppendNum( timeFrom1970, EHex );
+    
+    // Append a new line
+    bufPtr.Append( KNewLine );
+    
+    // Write the buffer into a file and return the error code   
+    iError = iFile.Write( processEndBuf );
+    
+    // Close the file and the handle to the file server
+    CloseFsAndFile();
+    
+    // Remove the process from the server's array of processes
+    iError = iStorageServer.RemoveProcessL( processId );
+    
+    // Reset iProcesssId and set the logging flag false
+    iProcessId = KNullProcessId;
+    iLoggingOngoing = EFalse;
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogProcessEndTraceL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::LogProcessEndTraceL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogProcessEndTraceL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    iError = KErrNone;
+    
+    // Read the sent process ID
+    TUint processId = aMessage.Int0();
+ 
+    // The process ID got from the client should equal iProcessId.
+    // If it does not, return KErrNotSupported
+    if ( processId != iProcessId )
+        {
+        return KErrNotSupported;
+        }
+    
+    //////////////////////////////////////////////
+    // Log handle leaks
+    ////////////////////////////////////////////// 
+
+    TUint handleLeakCount = aMessage.Int1();
+
+    if( handleLeakCount == 0 )
+        {
+        LOGSTR1( "STSE TInt CATStorageServerSession::LogProcessEndTraceL() No handle leaks to report" );
+        }
+    else
+        {
+        // Make a buffer that will be logged
+        TBuf8<KHandleLeakBufLength> loggingBuf;
+        
+        // Make a 16-bit buffer that can be logged using RDebug
+        TBuf<KHandleLeakBufLength> traceBuf;
+        
+        // Set handle leak module name to unknown since it can not be defined.
+        // Write the handle leak count from aMessage.
+        loggingBuf.Format( KHandleLeak, &KUnknownModule, handleLeakCount );
+        
+        traceBuf.Copy( loggingBuf );
+    
+        // Log through debug channel 
+        RDebug::Print( KTraceMessage, iProcessId , &traceBuf );
+        }
+
+    //////////////////////////////////////////////
+    // Log process end
+    //////////////////////////////////////////////
+    
+    // Make a buffer that will be logged
+    TBuf<KProcessEndBufLength> processEndBuf;    
+    processEndBuf.AppendFormat( KProcessEndTrace, iProcessId );
+    
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    processEndBuf.AppendNum( timeFrom1970, EHex );
+    
+    // Append a new line
+    processEndBuf.Append( KNewLineTrace );
+    
+    // Log through debug channel
+    RDebug::Print( KTraceMessage, iProcessId, &processEndBuf );
+
+    // Remove the process from the server's array of processes
+    iError = iStorageServer.RemoveProcessL( iProcessId );
+
+    // Reset iProcesssId and set the logging flag false
+    iProcessId = KNullProcessId;
+    iLoggingOngoing = EFalse;
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::CheckMemoryAddressL()
+// Checks if given memory address can be found
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::CheckMemoryAddressL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::CheckMemoryAddressL()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    iError = KErrNone;
+    
+    // Check if memory address can be found in iLeakArray
+    TUint32 memAddress = aMessage.Int0();
+    TIdentityRelation<CATMemoryEntry> matcher( CATMemoryEntry::Match );
+    CATMemoryEntry* entry = new (ELeave) CATMemoryEntry( memAddress, NULL, 0, 0 );
+    
+    // Get the index or an error code
+    iError = iLeakArray.Find( entry, matcher );
+    delete entry;
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::CheckMemoryAddressTrace()
+// Checks if some memory address can be found
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::CheckMemoryAddressTrace( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::CheckMemoryAddressTrace()" );
+    
+    // Panic the client and return, if a logging session is not ongoing
+    // ( can be started by calling the client's LogProcessStarted() )
+    if ( !iLoggingOngoing )
+        {
+        PanicClient( EAToolNotAllowed, aMessage );
+        return KErrCancel;
+        }
+    
+    // Always return KErrNone in this mode
+    return KErrNone;
+    }
+ 
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GetProcessesL()
+// Checks if some memory address can be found
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::GetProcessesL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::GetProcessesL()" );
+    
+    iError = KErrNone;
+    
+    TInt processInfoSize = sizeof( TATProcessInfo );
+    
+    CBufFlat* processInfoBuf;
+    
+    // Buffer position
+    TInt pos( 0 );
+    
+    // Calculate the length of the buffer to be constructed for processes
+    // One word will be reserved for the length of the array.
+    TInt bufferLength = KWordSize + KATMaxProcesses * processInfoSize;
+    
+    // Construct processInfoBuf and expand it before the beginning (index 0)
+    processInfoBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( processInfoBuf );
+    processInfoBuf->ExpandL( pos, bufferLength );
+    
+    RArray<TATProcessInfo> processArray = iStorageServer.ProcessInfoArray();
+
+    // Variable for the number of TATProcessInfo objects in processArray
+    TInt count = processArray.Count();
+    
+    // The count cannot be greater than KATMaxProcesses, because the client
+    // has reserved a buffer of this size to be filled by the server
+    if ( count > KATMaxProcesses )
+        {
+        count = KATMaxProcesses;
+        }
+
+    // Write the count (4 bytes) into the beginning of processInfoBuf
+    processInfoBuf->Write( pos, &count, KWordSize );
+    
+    // Move the position one word onwards.    
+    pos += KWordSize;
+    
+    // Write all the process info objects into the buffer 
+    for ( TInt i = 0; i < count; i++ )
+        {
+        TATProcessInfo& processInfo = processArray[i];
+        
+        // Write the current process info into the buffer
+        processInfoBuf->Write( pos, &processInfo, processInfoSize );
+        
+        // Move the pos variable onwards.
+        pos += processInfoSize;
+        }
+    
+    // Make a pointer descriptor pointing to the start of processInfoBuf
+    TPtr8 bufPtr( processInfoBuf->Ptr(0) );
+    
+    // Write the buffer into aMessage at index 0 for the client
+    aMessage.WriteL( 0, bufPtr );
+    
+    CleanupStack::PopAndDestroy( processInfoBuf );
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GetDllsL()
+// Checks if some memory address can be found
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::GetDllsL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::GetDllsL()" );
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+    
+    // Size of a DLL descriptor
+    TInt sizeOfDllDesc = sizeof( TBuf8<KMaxLibraryName> );
+    
+    // Buffer position
+    TInt pos( 0 );
+    
+    // Calculate the length of the buffer to be constructed for DLL names.
+    // One word will be reserved for the length of the array.
+    TInt bufferLength = KWordSize + KATMaxDlls * sizeOfDllDesc;
+    
+    CBufFlat* dllBuf;
+    // Construct dllBuf and expand it before the beginning (index 0)
+    dllBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( dllBuf );
+    dllBuf->ExpandL( pos, bufferLength );
+
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+    
+    // Return, if a process with the requested process ID was not found 
+    if ( index == KErrNotFound )
+        {
+        CleanupStack::PopAndDestroy( dllBuf );
+        return index;
+        }
+    
+    // Get the wanted dynamic process info 
+    dynProcessInfo = dynProcessArray[index];
+ 
+    // Fetch a reference to the desired DLL array
+    RArray<TATDllInfo>& dllArray = dynProcessInfo->iDlls;
+    
+    // Take the count of names in the array 
+    TInt count = dllArray.Count();
+
+    // The count cannot be greater than KATMaxDlls, because the client
+    // has reserved a buffer of this size to be filled by the server
+    if ( count > KATMaxDlls )
+        {
+        count = KATMaxDlls;
+        }
+
+    // Write the count (4 bytes) into the beginning of dllBuf
+    dllBuf->Write( pos, &count, KWordSize );
+    
+    // Move the position one word onwards.
+    pos += KWordSize;
+
+    // Go through all DLL names objects sent to the server 
+    for ( TInt i = 0; i < count; i++ )
+        {
+        TBuf8<KMaxLibraryName>& dllName = dllArray[i].iName;
+        
+        // Write the current DLL name into the buffer
+        dllBuf->Write( pos, &dllName, sizeOfDllDesc );
+        
+        // Move the pos variable onwards.
+        pos += sizeOfDllDesc;
+        }  
+    
+    // Make a pointer descriptor pointing to the start of dllBuf
+    TPtr8 bufPtr( dllBuf->Ptr(0) );
+    
+    // Write the whole buffer into aMessage at index 1 for the client
+    aMessage.WriteL( 1, bufPtr );
+    
+    CleanupStack::PopAndDestroy( dllBuf );
+
+    // The dynProcessInfo object will not be deleted, because it is still owned by the
+    // server object's dynamic process info array.  
+    dynProcessInfo = NULL;
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GetLoggingModeL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::GetLoggingModeL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::GetLoggingModeL()" );
+    
+    iError = KErrNone;
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+    
+    // Buffer position
+    TInt pos( 0 );
+    
+    // The length of the buffer to be constructed for logging mode
+    TInt bufferLength = KWordSize;
+    
+    // Get the dynamic process info array
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+    
+    // Return, if a process with the requested process ID was not found 
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Otherwise get the wanted dynamic process info
+    dynProcessInfo = dynProcessArray[index];
+
+    // Get the desired process's associated session object
+    CATStorageServerSession* sessionObject = dynProcessInfo->iSessionObject;
+    CBufFlat* loggingModeBuf;
+    // Construct allocInfoBuf and expand it before the beginning (index 0)
+    loggingModeBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( loggingModeBuf );
+    loggingModeBuf->ExpandL( 0, bufferLength );
+    
+    // Write the current logging mode of the requested process into the buffer.
+    loggingModeBuf->Write( pos, &sessionObject->iLogOption, KWordSize );
+    
+    // Make a pointer descriptor that points to the data of allocInfoBuf
+    TPtr8 bufPtr( loggingModeBuf->Ptr(0) );
+    
+    // Write the whole buffer into aMessage at index 1 for the client
+    aMessage.WriteL( 1, bufPtr );
+    
+    CleanupStack::PopAndDestroy( loggingModeBuf );
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::StartSubtestL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::StartSubtestL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::StartSubtestL()" );
+    
+    iError = KErrNone;
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+    
+    // Read the sub test ID at index 1
+    TBuf8<KATMaxSubtestIdLength> subTestName;
+    iError = aMessage.Read( 1, subTestName );
+    
+    // Return if reading was not successful
+    if ( iError != KErrNone )
+        {
+        return iError;
+        }
+    
+    // Create another (non-8-bit) descriptor for logging to trace
+    // and copy the contents
+    TBuf<KATMaxSubtestIdLength> subTestNameTrace;
+    subTestNameTrace.Copy( subTestName );
+
+    // Read the handle count at index 2
+    TInt handleCount = aMessage.Int2();
+    
+    // FIND THE REQUESTED PROCESS
+    
+    // Get the dynamic process array
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+    
+    // Return, if a process with the requested process ID was not found
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Get the wanted dynamic process info
+    dynProcessInfo = dynProcessArray[index];
+    
+    // Get the desired process's associated session object
+    const CATStorageServerSession* sessionObject = dynProcessInfo->iSessionObject;
+  
+    // Make a buffer for logging thru trace
+    TBuf<KTestStartBufLength> loggingBuf;
+    
+    // Copy the line tag into the buffer  
+    loggingBuf.Copy( KSubtestStart );
+    
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    loggingBuf.AppendNum( timeFrom1970, EHex );
+    
+    // Append a space
+    loggingBuf.Append( KSpaceTrace );
+    
+    // Append the sub test ID
+    loggingBuf.Append( subTestNameTrace );
+
+    // Append a space
+    loggingBuf.Append( KSpaceTrace );
+    
+    // Append current handle leak count
+    loggingBuf.AppendNum( handleCount );
+    
+    // Append a new line
+    loggingBuf.Append( KNewLineTrace );
+    
+    // Log the string through trace
+    iError = sessionObject->LogThroughTrace( loggingBuf );
+        
+    // *******************
+    // Send loaded DLL's
+    // *******************
+    
+    // Fetch a reference to the desired DLL array
+	RArray<TATDllInfo>& dllArray = dynProcessInfo->iDlls;
+	
+	// Take the count of dll info items
+	TInt count( dllArray.Count() );
+	LOGSTR2( "STSE > dllArray.Count( %i )", count );
+	
+	// Create buffers
+	TBuf<KDllLoadBufLength> traceBuf;
+	TBuf8<KDllLoadBufLength> dllBuf;
+	
+	for ( TInt x = 0; x < count; x++ )
+		{
+		dllBuf.Format( KDllLoad, &dllArray[x].iName, dllArray[x].iLoadTime,
+				dllArray[x].iStartAddress, dllArray[x].iEndAddress );
+		traceBuf.Copy( dllBuf );
+		
+		// Log the string through trace
+		iError = sessionObject->LogThroughTrace( traceBuf );
+		if ( iError != KErrNone )
+			{
+			LOGSTR2( "STSE > LogThroughTrace() err( %i )", iError );
+			}
+		}
+    sessionObject = NULL;
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::StopSubtestL()
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::StopSubtestL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::StopSubtestL()" );
+    
+    iError = KErrNone;
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+    
+    // Read the sub test ID at index 1
+    TBuf8<KATMaxSubtestIdLength> subTestName;
+    iError = aMessage.Read( 1, subTestName );
+    
+    // Return if reading was not successful
+    if ( iError != KErrNone )
+        {
+        return iError;
+        }
+
+    // Create another (non-8-bit) descriptor for logging to trace,
+    // and copy the contents
+    TBuf<KATMaxSubtestIdLength> subTestNameTrace;
+    subTestNameTrace.Copy( subTestName );
+
+    // Read the handle count at index 2
+    TInt handleCount = aMessage.Int2();
+    
+    // FIND THE REQUESTED PROCESS
+    
+    // Get the dynamic process array
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+    
+    // Return, if a process with the requested process ID was not found
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Get the wanted dynamic process info
+    dynProcessInfo = dynProcessArray[index];
+    
+    // Get the desired process's associated session object
+    const CATStorageServerSession* sessionObject = dynProcessInfo->iSessionObject;
+  
+    // Make a buffer for logging thru trace
+    TBuf<KTestEndBufLength> loggingBuf;
+    
+    // Copy the line tag into the buffer  
+    loggingBuf.Copy( KSubtestEnd );
+    
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    loggingBuf.AppendNum( timeFrom1970, EHex );
+    
+    // Append a space
+    loggingBuf.Append( KSpaceTrace );
+    
+    // Append the sub test ID
+    loggingBuf.Append( subTestNameTrace );
+
+    // Append a space
+    loggingBuf.Append( KSpaceTrace );
+    
+    // Append current handle leak count
+    loggingBuf.AppendNum( handleCount );
+    
+    // Append a new line
+    loggingBuf.Append( KNewLineTrace );
+    
+    // Log the string through trace
+    iError = sessionObject->LogThroughTrace( loggingBuf );
+    
+    sessionObject = NULL;
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::StartSubtest2L()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::StartSubtest2L( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::StartSubtest2L()" );
+    
+    iError = KErrNone;
+    
+    // Read the sub test ID at index 0
+    TBuf8<KATMaxSubtestIdLength> subTestName;
+    iError = aMessage.Read( 0, subTestName );
+    
+    // Return if reading was not successful
+    if ( iError != KErrNone )
+        {
+        return iError;
+        }
+    
+    // Create another (non-8-bit) descriptor for logging to trace
+    // and copy the contents
+    TBuf<KATMaxSubtestIdLength> subTestNameTrace;
+    subTestNameTrace.Copy( subTestName );
+
+    // Make a buffer for logging thru trace
+    TBuf<KTestStartBufLength> loggingBuf;
+    
+    // Copy the line tag into the buffer  
+    loggingBuf.Copy( KSubtestStart );
+    
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    loggingBuf.AppendNum( timeFrom1970, EHex );
+    
+    // Append a space
+    loggingBuf.Append( KSpaceTrace );
+    
+    // Append the sub test ID
+    loggingBuf.Append( subTestNameTrace );
+    
+    // Append a new line
+    loggingBuf.Append( KNewLineTrace );
+    
+    // Log the string through trace
+    iError = LogThroughTrace( loggingBuf );
+    
+    // *******************
+	// Send loaded DLL's
+	// *******************
+	
+    // Get the dynamic process array
+	RPointerArray<CATDynProcessInfo> dynProcessArray =
+		iStorageServer.DynProcessInfoArray();
+	
+	// Construct a CATDynProcessInfo object with the given process ID for searching
+	CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( iProcessId );
+	
+	// Find the index of a CATDynProcessInfo object with the given process ID
+	TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+	TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+	delete dynProcessInfo;
+	dynProcessInfo = NULL;
+	 
+	// Return, if a process with the requested process ID was not found
+	if ( index == KErrNotFound )
+		{
+		return index;
+		}
+	
+	// Get the wanted dynamic process info
+	dynProcessInfo = dynProcessArray[index];
+        
+	// Fetch a reference to the desired DLL array
+	RArray<TATDllInfo>& dllArray = dynProcessInfo->iDlls;
+	
+	// Take the count of dll info items
+	TInt count( dllArray.Count() );
+	LOGSTR2( "STSE > dllArray.Count( %i )", count );
+	
+	// Create buffers
+	TBuf<KDllLoadBufLength> traceBuf;
+	TBuf8<KDllLoadBufLength> dllBuf;
+	
+	for ( TInt x = 0; x < count; x++ )
+		{
+		dllBuf.Format( KDllLoad, &dllArray[x].iName, dllArray[x].iLoadTime,
+				dllArray[x].iStartAddress, dllArray[x].iEndAddress );
+		traceBuf.Copy( dllBuf );
+		
+		// Log the string through trace
+		iError = LogThroughTrace( traceBuf );
+		if ( iError != KErrNone )
+			{
+			LOGSTR2( "STSE > LogThroughTrace() err( %i )", iError );
+			}
+		}
+    	
+    return iError;
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::StopSubtest2()
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::StopSubtest2( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::StopSubtest2()" );
+    
+    iError = KErrNone;
+    
+    // Read the sub test ID at index 0
+    TBuf8<KATMaxSubtestIdLength> subTestName;
+    iError = aMessage.Read( 0, subTestName );
+    
+    // Return if reading was not successful
+    if ( iError != KErrNone )
+        {
+        return iError;
+        }
+
+    // Create another (non-8-bit) descriptor for logging to trace,
+    // and copy the contents
+    TBuf<KATMaxSubtestIdLength> subTestNameTrace;
+    subTestNameTrace.Copy( subTestName );
+
+    // Make a buffer for logging thru trace
+    TBuf<KTestEndBufLength> loggingBuf;
+    
+    // Copy the line tag into the buffer  
+    loggingBuf.Copy( KSubtestEnd );
+    
+    // Get the current universal time    
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    loggingBuf.AppendNum( timeFrom1970, EHex );
+    
+    // Append a space
+    loggingBuf.Append( KSpaceTrace );
+    
+    // Append the sub test ID
+    loggingBuf.Append( subTestNameTrace );
+    
+    // Append a new line
+    loggingBuf.Append( KNewLineTrace );
+    
+    // Log the string through trace
+    iError = LogThroughTrace( loggingBuf );
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GetCurrentAllocsL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::GetCurrentAllocsL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::GetCurrentAllocsL()" );
+    
+    iError = KErrNone;
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+    TUint32 allocNumber( 0 );
+    TUint32 allocSize( 0 );
+    
+    // Buffer position
+    TInt pos( 0 );
+    
+    // The length of the buffer to be constructed for allocation number and size
+    TInt bufferLength = KWordSize + KWordSize;
+    
+    // Get the dynamic process info array
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+    
+    // Return, if a process with the requested process ID was not found
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Otherwise get the wanted dynamic process info
+    dynProcessInfo = dynProcessArray[index];
+
+    // Get the desired process's associated session object
+    CATStorageServerSession* sessionObject = dynProcessInfo->iSessionObject;
+    
+    // Get the alloc info array of that session object
+    RArray<TAllocInfo> allocInfo = sessionObject->AllocInfoArray();
+    
+    // Get the values for current allocations number and size
+    allocNumber = allocInfo.Count();
+    
+    // Calculate the total size of the current allocations
+    for ( TUint32 i = 0; i < allocNumber; i++ )
+        {
+        allocSize += allocInfo[i].iAllocSize;
+        }
+    
+    LOGSTR2( "STSE allocSize: %u", allocSize );
+    LOGSTR2( "STSE iCurAllocSize: %u", iCurAllocSize );
+    
+    CBufFlat* allocInfoBuf;
+    // Construct allocInfoBuf and expand it before the beginning (index 0)
+    allocInfoBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( allocInfoBuf );
+    allocInfoBuf->ExpandL( 0, bufferLength );
+    
+    // Write the current number of allocations of the requested process into the buffer.
+    allocInfoBuf->Write( pos, &allocNumber, KWordSize );
+    
+    // Move the position one word onwards
+    pos += KWordSize;
+    
+    // Write the current total size of the allocations of the requested process into the
+    // buffer.
+    allocInfoBuf->Write( pos, &allocSize, KWordSize );
+    
+    // Make a pointer descriptor that points to the data of allocInfoBuf
+    TPtr8 bufPtr( allocInfoBuf->Ptr(0) );
+    
+    // Write the whole buffer into aMessage at index 1 for the client
+    aMessage.WriteL( 1, bufPtr );
+    
+    CleanupStack::PopAndDestroy( allocInfoBuf );
+                    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GetMaxAllocsL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::GetMaxAllocsL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::GetMaxAllocsL()" );
+    
+    iError = KErrNone;
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+    TUint32 allocNumber( 0 );
+    TUint32 allocSize( 0 );
+    
+    // Buffer position
+    TInt pos( 0 );
+    
+    // The length of the buffer to be constructed for allocation number and size
+    TInt bufferLength = KWordSize + KWordSize;
+    
+    // Get the dynamic process info array
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+    
+    // Return, if a process with the requested process ID was not found 
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Otherwise get the wanted dynamic process info 
+    dynProcessInfo = dynProcessArray[index];
+
+    // Get the desired process's associated session object
+    CATStorageServerSession* sessionObject = dynProcessInfo->iSessionObject;
+    
+    // Get values for the maximum allocations number and size
+    allocNumber = sessionObject->iMaxAllocs;
+    allocSize = sessionObject->iMaxAllocSize;
+    
+    CBufFlat* allocInfoBuf;
+    // Construct allocInfoBuf and expand it before the beginning (index 0)
+    allocInfoBuf = CBufFlat::NewL( bufferLength );
+    CleanupStack::PushL( allocInfoBuf );
+    allocInfoBuf->ExpandL( 0, bufferLength );
+    
+    // Write the maximum number of allocations of the requested process into the buffer.
+    allocInfoBuf->Write( pos, &allocNumber, KWordSize );
+    
+    // Move the position one word onwards
+    pos += KWordSize;
+    
+    // Write the maximum total size of the allocations of the requested process into the
+    // buffer.
+    allocInfoBuf->Write( pos, &allocSize, KWordSize );
+    
+    // Make a pointer descriptor that points to the data of allocInfoBuf
+    TPtr8 bufPtr( allocInfoBuf->Ptr(0) );
+    
+    // Write the whole buffer into aMessage at index 1 for the client
+    aMessage.WriteL( 1, bufPtr );
+    
+    CleanupStack::PopAndDestroy( allocInfoBuf );
+                    
+    return iError;
+    }
+  
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::CancelLoggingL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::CancelLoggingL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::CancelLoggingL()" );
+    
+    iError = KErrNone;
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+        
+    // FIND THE REQUESTED PROCESS
+    
+    // Get the dynamic process array
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+     
+    // Return, if a process with the requested process ID was not found
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Otherwise get the wanted dynamic process info
+    dynProcessInfo = dynProcessArray[index];
+    
+    // Get the session object of the requested process
+    CATStorageServerSession* sessionObject = dynProcessInfo->iSessionObject;
+      
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+    
+    // Make a buffer for logging "logging cancelled"
+    TBuf8<KCancelBufLength> loggingBuf;
+    
+    // Copy the "logging cancelled" tag into the buffer with the current time 
+    loggingBuf.AppendFormat( KLoggingCancelled, timeFrom1970 );
+    
+    // Log the buffer eather to a file or to debug channel depending on the current
+    // logging mode
+    
+    if ( sessionObject->iLoggingOngoing && 
+         sessionObject->iLogOption == EATLogToFile )
+        {
+        // Write the buffer into the file  
+        sessionObject->iFile.Write( loggingBuf );
+        }
+    
+    else if ( sessionObject->iLoggingOngoing &&
+              sessionObject->iLogOption == EATLogToTrace )
+        {
+        // Make a buffer for logging to trace
+        TBuf<KCancelBufLength> traceBuf;
+        traceBuf.Copy( loggingBuf );
+        
+        // Write the buffer into the debug channel
+        RDebug::Print( KTraceMessage, processId ,&traceBuf );
+        }
+    
+    // Switch off logging of the requested process 
+    sessionObject->iLogOption = EATLoggingOff;
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::HandleError
+// Internally used for handling error situations.
+// -----------------------------------------------------------------------------
+// 
+void CATStorageServerSession::HandleError( TInt aError )
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::HandleError()" );
+      
+    // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+        
+    // Make a buffer that will be logged into the opened logging file
+    TBufC8<KErrOccuredBufLength> loggingBuf;
+    
+    TPtr8 bufPtr( loggingBuf.Des() );
+     
+    // Write the error code to the buffer  
+    bufPtr.Format( KErrorOccured, aError );
+       
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    bufPtr.AppendNum( timeFrom1970, EHex );
+    
+    // Append a new line
+    bufPtr.Append( KNewLine );
+            
+    // Write the buffer into a file (if possible in the current condition)
+    iFile.Write( loggingBuf );
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::HandleErrorTrace()
+// Internally used for handling error situations.
+// -----------------------------------------------------------------------------
+//    
+void CATStorageServerSession::HandleErrorTrace( TInt aError )
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::HandleErrorTrace()" );
+    
+     // Get the current universal time
+    TInt64 timeFrom1970( GetTime() );
+        
+    // Make a buffer that will be logged
+    TBuf<KErrOccuredBufLength> traceBuf;
+     
+    // Write the error code to the buffer  
+    traceBuf.Format( KErrorOccuredTrace, aError );
+       
+    // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+    // format
+    traceBuf.AppendNum( timeFrom1970, EHex );
+    
+    // Append a new line
+    traceBuf.Append( KNewLineTrace );
+                 
+    RDebug::Print( KTraceMessage, iProcessId , &traceBuf );
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::OpenFsAndFile
+// Internally used for opening a handle to the file server and a file
+// -----------------------------------------------------------------------------
+// 
+TInt CATStorageServerSession::OpenFsAndFile( const TDesC& aFileName, 
+    const TDesC8& aProcessName )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::OpenFsAndFile()" );
+    
+    // Connect file server, return if error occured
+    iError = iFileServer.Connect();
+    if ( iError )
+        {
+        iFileServer.Close();
+        return iError;
+        }
+
+    // Open a file
+    TBuf<KMaxFileName> fileNameBuf;    
+    iError = TATDriveInfo::CreatePath( fileNameBuf, aFileName, iFileServer );
+                        
+    // Return, if an error occured, and it
+    // is not KErrAlreadyExists
+    if ( iError && iError != KErrAlreadyExists )
+        {
+        iFileServer.Close();
+        return iError;
+        }
+    
+    // Save the file name for this session
+    CnvUtfConverter::ConvertFromUnicodeToUtf8( iLogFile, fileNameBuf );
+        
+    // Try to open file
+    CheckIfFileAlreadyExist( fileNameBuf );
+    
+    // If a data file with the requested name already existed, and was opened
+    // successfully, check the version of the file. If the line telling the version of
+    // the file is not the expected, replace the file
+    // If cannot open the file(error is KErrInUse), generate new filename and 
+    // then try to create new file.
+    if ( iError == KErrNone )
+        {
+        CheckFileVersion( fileNameBuf );
+        }    
+    else if ( iError == KErrInUse )
+        {
+        GenerateNewFileName( fileNameBuf, aProcessName );
+        
+        // Save the file name for this session
+        CnvUtfConverter::ConvertFromUnicodeToUtf8( iLogFile, fileNameBuf );
+        }
+    LOGSTR2( "STSE > iError(%i)", iError );
+        
+    // If the file does not exist, create it. Write also the version number of
+    // the file at the beginning of the new file
+    if ( iError == KErrNotFound )
+        {
+        iError = iFile.Create( iFileServer, fileNameBuf, EFileWrite );
+        
+        if ( !iError )
+            {
+            iError = iFile.Write( KDataFileVersion );
+            }
+        }   
+       
+    if ( iError )
+        {
+        iFile.Close();
+        iFileServer.Close();
+        return iError;
+        }
+        
+    // Seek the end of the file and set the current file position there
+    TInt offset = 0;
+    iError = iFile.Seek( ESeekEnd, offset );
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GenerateNewFileName
+// Called internally when need generate new file name.
+// -----------------------------------------------------------------------------
+//                     
+void CATStorageServerSession::GenerateNewFileName( TDes& aFileName,
+    const TDesC8& aProcessName )
+    {    
+    LOGSTR1( "STSE void CATStorageServerSession::GenerateNewFileName()" );
+        
+    // Extension
+    TBuf<KExtensionLength> extension;
+
+    // Parse file extension
+    ParseExtension( aFileName, extension );
+
+    // Try to find UID3 from current process name
+    TInt uidErr( KErrBadName );
+    TBuf<KMaxFileName> unicodeFile;
+
+    // Converts text encoded using the Unicode transformation format UTF-8 
+    // into the Unicode UCS-2 character set. 
+    CnvUtfConverter::ConvertToUnicodeFromUtf8( unicodeFile, aProcessName );
+    LOGSTR2( "STSE > unicodeFile(%S)", &unicodeFile );
+
+    // Find square brackets
+    TInt sPos( unicodeFile.Find( KOpenSquareBracket ) );
+    TInt ePos( unicodeFile.Find( KCloseSquareBracket ) );
+    LOGSTR3( "STSE > sPos(%i), ePos(%i)", sPos, ePos );
+            
+    if ( sPos != KErrNotFound && ePos != KErrNotFound )
+        {
+        TBuf<KProcessUidLength> processUid;
+        TInt pEnd( ePos - sPos - KOpenSquareBracket().Length() );
+        LOGSTR2( "STSE > pEnd(%i)", pEnd );
+        
+        // Copy UID value
+        if ( pEnd > 0 )
+            {
+            processUid.Copy( unicodeFile.Mid( 
+                    sPos + KOpenSquareBracket().Length(), pEnd ) );
+            LOGSTR2( "STSE > processUid(%S)", &processUid );
+            }
+        
+        if ( aFileName.Find( processUid ) == KErrNotFound )
+            {
+            // UID not exist, create new filename
+            // Append uid to filename (<file name>_<uid>.<extension>)
+            aFileName.Append( KUnderLine );
+            aFileName.Append( processUid );
+            aFileName.Append( extension );
+            // Try to open file
+            CheckIfFileAlreadyExist( aFileName );
+
+            if ( iError == KErrNone )
+                {
+                uidErr = KErrNone;
+                CheckFileVersion( aFileName );
+                }
+            }
+        }
+
+    if ( uidErr == KErrBadName && iError != KErrNotFound )
+        {
+        // Need re-create file name, add end off file _xx (xx=01, 02...)
+        LOGSTR2( "STSE > Re-create file name, aFileName(%S)", &aFileName );
+                
+        // Parse file extension if exists.
+        ParseExtension( aFileName, extension );
+        
+        // Temp file name
+        TBuf<KMaxFileName> tempName;
+        
+        for ( TInt i = KNameIndexStart; i < KNameIndexEnd; i++ )
+            {
+            tempName.Delete( 0, tempName.MaxLength() );
+            tempName.Format( KFormat, &aFileName, &KUnderLine, i, &extension );
+            LOGSTR2( "STSE > tempName(%S)", &tempName );
+            // Try to open file
+            CheckIfFileAlreadyExist( tempName );
+            
+            if ( iError == KErrNone || iError == KErrNotFound )
+                {
+                aFileName.Copy( tempName );
+                break;
+                }
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::ParseExtension
+// Method is used to parse file name extension.
+// -----------------------------------------------------------------------------
+//                     
+void CATStorageServerSession::ParseExtension( 
+    TDes& aFileName, TDes& aExtension )
+    {    
+    LOGSTR2( "STSE void CATStorageServerSession::ParseExtension(%S)", 
+            &aFileName );
+
+    // Parse current file name
+    TParse parse;
+    // Set up the TParse object 
+    parse.Set( aFileName, NULL, NULL );
+
+    // Tests whether an extension is present.
+    if ( parse.ExtPresent() )
+        {
+        // Gets the extension
+        aExtension.Copy( parse.Ext() );
+        // Remove extension from file name
+        TInt pos( aFileName.Find( aExtension ) );
+        aFileName.Delete( pos, aFileName.Length() );
+        LOGSTR3( "STSE > aFileName(%S), aExtension(%S)", 
+                &aFileName, &aExtension );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::CheckIfFileAlreadyExist
+// Method is used to check that file exists and is valid.
+// -----------------------------------------------------------------------------
+//                     
+void CATStorageServerSession::CheckIfFileAlreadyExist( 
+    const TDes& aFileName )
+    {    
+    LOGSTR2( "STSE void CATStorageServerSession::CheckIfFileAlreadyExist(%S)", 
+            &aFileName );
+    
+    iError = iFile.Open( iFileServer, aFileName, EFileWrite );
+    LOGSTR2( "STSE > iError(%i)", iError );
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::CheckFileVersion
+// Method is used to check file version.
+// -----------------------------------------------------------------------------
+//                     
+void CATStorageServerSession::CheckFileVersion( 
+    const TDes& aFileName )
+    {    
+    LOGSTR2( "STSE void CATStorageServerSession::CheckFileVersion(%S)", 
+            &aFileName );
+
+    TBuf8<KVersionStringLength> versionString;
+
+    // Read version information from the beginning of the file (offset 0)
+    iFile.Read( 0, versionString, KVersionStringLength );
+
+    // Delete the existing file, if the version string read from the file does not
+    // match with KDataFileVersion.
+    if ( versionString.Compare( KDataFileVersion ) != 0 )
+        {
+        // Close the existing, opened file, and delete it
+        iFile.Close();
+        iError = iFileServer.Delete( aFileName );
+        
+        // If the deletion was successful, set iError = KErrNotFound, so a new
+        // file will be created in the next few lines 
+        if ( iError == KErrNone )
+            {
+            iError = KErrNotFound;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::CloseFsAndFile
+// Internally used for closing a handle to the file server and a file
+// -----------------------------------------------------------------------------
+// 
+void CATStorageServerSession::CloseFsAndFile()
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::CloseFsAndFile()" );
+    
+    // Close the file    
+    iFile.Close();
+                 
+    // Close the server session and return the error code   
+    iFileServer.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::PrintLeaksL()
+// Called internally when a process is closed. Prints possible memory leaks
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::PrintLeaksL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::PrintLeaksL()" );
+    
+    // Panic both the client and the server, if this method is called in a wrong
+    // state (logging should be ongoing, and the system should be logging into a file,
+    // not into debug channel)
+    if ( !iLoggingOngoing || iLogOption != EATLogToFile )
+        {
+        PanicClient( EAToolInternalError, aMessage );
+        StorageServerPanic( KCategoryServer, EAToolInternalError );
+        }
+   
+    LOGMEM;
+
+    // A pointer to a buffer of call stack's memory addresses
+    CBufFlat* stackBuf = NULL;
+    
+    iError = KErrNone;
+    
+    TUint32 callStackAddr;
+    
+    // Number of leaks
+    TInt leakCount = iLeakArray.Count();
+    
+    // Variable for the number of memory addresses in the call stack
+    TInt addrCount( 0 );
+    
+    // Buffer position
+    TInt pos( 0 );
+                     
+    // Go through all the leaks 
+    for ( TInt i = 0; i < leakCount; i++ ) 
+        {   
+        pos = 0;
+        
+        // Get the call stack buffer of the the leak i.
+        stackBuf = const_cast<CBufFlat*>( iLeakArray[i]->iCallstackBuf );
+    
+        // Read the first word of the buffer. This includes the number of
+        // memory addresses stored in the current stackBuf
+        stackBuf->Read( pos, &addrCount, KWordSize );
+    
+        // Move the position one word onwards.
+        pos += KWordSize;
+         
+        // Construct a buffer for the string to be written into the logging file
+        // because of this memory leak. MEM_LEAK: <Memory address> <Time stamp>
+        // <Allocation size> <Call stack address> <Call stack address> ...
+        HBufC8* leakString = 
+            HBufC8::NewL( KMemleakLength +
+                          KHexa32Length +
+                          KSpaceLength + KHexa64Length +
+                          KSpaceLength + KHexa32Length +
+                          ( addrCount * (KSpaceLength + KHexa32Length) ) +
+                          KNewlineLength 
+                        );
+            
+        // Make a pointer descriptor that points to leakString
+        TPtr8 leakStringPtr( leakString->Des() );
+        
+        // Append the tag implying a memory leak line in the data file
+        leakStringPtr.Append( KMemoryLeak );
+        
+        // Append the address of the memory leak         
+        TUint32 memAddress = iLeakArray[i]->iMemAddress;
+        leakStringPtr.AppendNum( memAddress, EHex );
+        
+        // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+        // format
+        leakStringPtr.Append( KSpace );
+        TInt64 allocTime = iLeakArray[i]->iAllocTime;
+        leakStringPtr.AppendNum( allocTime, EHex );
+        
+        // Append the size of the allocation in the 32-bit (max 8 characters) hexadecimal
+        // text format.
+        leakStringPtr.Append( KSpace );
+        TInt allocSize = iLeakArray[i]->iAllocSize;
+        leakStringPtr.AppendNum( allocSize, EHex );
+        
+        // Go through all call stack's memory addresses associated with
+        // the current memory leak 
+        for ( TInt j = 0; j < addrCount; j++ )
+            {
+            // Read the next call stack's memory address stored in the buffer.
+            stackBuf->Read( pos, &callStackAddr, KWordSize );
+            
+            // Append the read memory address as a hexadecimal number
+            leakStringPtr.AppendFormat( KHexaNumber,  callStackAddr );
+    
+            // Move the pos variable one word onwards.
+            pos += KWordSize;
+            }
+        
+        leakStringPtr.Append( KNewLine );
+        
+        // Set stackBuf to NULL, because it is not used anymore.
+        stackBuf = NULL;
+        
+        // Write the constructed string into the data file and return if error
+        iError = iFile.Write( *leakString );
+        
+        delete leakString;
+          
+        if ( iError != KErrNone )
+            {
+            return iError;
+            }
+              
+        } // The outer for
+   
+    LOGSTR1( "STSE End of CATStorageServerSession::PrintLeaks()" );
+    LOGMEM;
+   
+    // Empty the leak array and delete the referenced objects
+    iLeakArray.ResetAndDestroy();
+   
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::SetLogOption()
+// For setting the logging mode.
+// -----------------------------------------------------------------------------
+//
+void CATStorageServerSession::SetLogOption( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::SetLogOption()" );
+        
+    // Panic both the client and the server, if this method is called in a wrong
+    // state (logging must not be ongoing when changing the mode of operation).
+    // So, the mode cannot be changed "on the fly".
+    if ( iLoggingOngoing )
+        {
+        PanicClient( EAToolInternalError, aMessage );
+        StorageServerPanic( KCategoryServer, EAToolInternalError );
+        }    
+
+    iLogOption = static_cast<TATLogOption>( aMessage.Int3() );
+    
+    // The default is EATLogToFile
+    if ( iLogOption == EATUseDefault )
+        {
+        iLogOption = KDefaultLoggingMode;
+        } 
+    }
+    
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogThroughTrace()
+// -----------------------------------------------------------------------------
+//
+TInt CATStorageServerSession::LogThroughTrace( const TDesC& aLogString ) const
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::LogThroughTrace()" );
+
+    // Return KErrNotSupported, if a logging session is not currently ongoing, or
+    // the logging mode is not EATLogToTrace
+    if ( !iLoggingOngoing || iLogOption != EATLogToTrace)
+        {
+        return KErrNotSupported;
+        }
+        
+    RDebug::Print( KTraceMessage, iProcessId, &aLogString );
+    
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::AllocInfoArray
+// -----------------------------------------------------------------------------
+// 
+RArray<TAllocInfo>& CATStorageServerSession::AllocInfoArray()
+    {
+    LOGSTR1( "STSE RArray<TAllocInfo>& CATStorageServerSession::AllocInfoArray()" );
+     
+    return iAllocInfoArray;
+    }    
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::PanicClient
+// Creates a panic in the associated client's code.
+// -----------------------------------------------------------------------------
+//
+void CATStorageServerSession::PanicClient( TInt aPanic, const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::PanicClient()" );
+    
+    aMessage.Panic( KCategoryClient, aPanic );
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GetLoggingFileL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::GetLoggingFileL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::GetLoggingFileL()" );
+    
+    iError = KErrNone;
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+    
+    // Get the dynamic process info array
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+    
+    // Return, if a process with the requested process ID was not found 
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Otherwise get the wanted dynamic process info
+    dynProcessInfo = dynProcessArray[index];
+
+    // Get the desired process's associated session object
+    CATStorageServerSession* sessionObject = dynProcessInfo->iSessionObject;
+            
+    // Write the whole buffer into aMessage at index 1 for the client
+    aMessage.WriteL( 1, sessionObject->iLogFile );
+                    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GetUdebL()
+// -----------------------------------------------------------------------------
+//    
+TInt CATStorageServerSession::GetUdebL( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE TInt CATStorageServerSession::GetUdebL()" );
+    
+    iError = KErrNone;
+    
+    // Read the process ID at index 0
+    TUint processId = aMessage.Int0();
+    
+    // Get the dynamic process info array
+    RPointerArray<CATDynProcessInfo> dynProcessArray =
+                                             iStorageServer.DynProcessInfoArray();
+    
+    // Construct a CATDynProcessInfo object with the given process ID for searching
+    CATDynProcessInfo* dynProcessInfo = new (ELeave) CATDynProcessInfo( processId );
+    
+    // Find the index of a CATDynProcessInfo object with the given process ID
+    TLinearOrder<CATDynProcessInfo> order( CATDynProcessInfo::Compare );
+    TInt index = dynProcessArray.FindInOrder( dynProcessInfo, order );
+    delete dynProcessInfo;
+    dynProcessInfo = NULL;
+    
+    // Return, if a process with the requested process ID was not found 
+    if ( index == KErrNotFound )
+        {
+        return index;
+        }
+    
+    // Otherwise get the wanted dynamic process info
+    dynProcessInfo = dynProcessArray[index];
+
+    // Get the desired process's associated session object
+    CATStorageServerSession* sessionObject = dynProcessInfo->iSessionObject;
+    
+    TBuf8<KMaxVersionName> isUdeb;
+    if ( sessionObject->iIsUdeb == 1 )
+        {
+        isUdeb.Copy( KUdeb() );
+        }
+    else if ( sessionObject->iIsUdeb == 0 )
+        {
+        isUdeb.Copy( KUrel() );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+    // Write the whole buffer into aMessage at index 1 for the client
+    aMessage.WriteL( 1, isUdeb );
+    
+    return iError;
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::SetUdeb()
+// -----------------------------------------------------------------------------
+//    
+void CATStorageServerSession::SetUdeb( const RMessage2& aMessage )
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::SetUdeb()" );
+ 
+    iIsUdeb = aMessage.Int0();
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::LogAbnormalEnd()
+// -----------------------------------------------------------------------------
+//    
+void CATStorageServerSession::LogAbnormalEnd()
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::LogAbnormalEnd()" );
+    
+    // Get the current universal time     
+    TInt64 timeFrom1970( GetTime() );
+        
+    switch ( iLogOption )
+        {
+        case EATLogToTrace:
+            {            
+            // Make a buffer that will be logged
+            TBuf<KEndAbnormalBufLength> traceBuf;
+            
+            // Write the process id to the buffer  
+            traceBuf.Format( KProcessEndAbnormalTrace, iProcessId );
+            
+            // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+            // format         
+            traceBuf.AppendNum( timeFrom1970, EHex );
+                
+            // Append a new line
+            traceBuf.Append( KNewLineTrace );
+            
+            // Write the buffer into the debug channel
+            RDebug::Print( KTraceMessage, iProcessId, &traceBuf );
+            }
+        break;
+        
+        case EATLogToFile:
+            {            
+            // Make a buffer that will be logged
+            TBuf8<KEndAbnormalBufLength> loggingBuf;
+            
+            // Write the process id to the buffer  
+            loggingBuf.Format( KProcessEndAbnormal, iProcessId );
+            
+            // Append the current time in the 64-bit (max 16 characters) hexadecimal text
+            // format         
+            loggingBuf.AppendNum( timeFrom1970, EHex );
+                
+            // Append a new line
+            loggingBuf.Append( KNewLine );
+            
+            // Write the buffer into a file (if possible in the current condition)
+            iFile.Write( loggingBuf );
+            }
+        break;
+              
+        default:
+            break;
+        }    
+    }
+
+// -----------------------------------------------------------------------------
+// CATStorageServerSession::GetTime()
+// Get the current universal time
+// -----------------------------------------------------------------------------
+//    
+TInt64 CATStorageServerSession::GetTime()
+    {
+    LOGSTR1( "STSE void CATStorageServerSession::GetTime()" );
+    
+    // Get the current universal time
+    iTime.UniversalTime();
+        
+    // Change the time format that tells the number of microseconds from January First,
+    // 0 AD nominal Gregorian, into a format that tells the number of microseconds from
+    // January First, 1970 AD nominal Gregorian. This is a more generic format and
+    // can be directly exploited by the PC code parsing the data file that this
+    // server generates.        
+    return ( iTime.Int64() - iMicroSecondsAt1970 );        
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/sis/atstorageserver.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;
+; An installation file for AnalyzeTool StorageServer
+;
+
+;Language - standard language definitions
+&EN
+
+; standard SIS file header
+#{"ATStorageServer"},(0xA22E6C80),1,8,1
+
+;Localised Vendor name
+%{"Vendor-EN"}
+
+;Unique Vendor name
+:"Vendor"
+
+;Supports Series 60 v 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; 4 Files to install
+"\epoc32\release\armv5\urel\atoolstorageserver.exe"-"!:\sys\bin\atoolstorageserver.exe"
+"\epoc32\release\armv5\urel\atoolstorageserverclnt.dll"-"!:\sys\bin\atoolstorageserverclnt.dll"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/analyzetool/storageserver/sis/atstorageserver_udeb.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+;
+; Description:
+;
+;
+; An installation file for AnalyzeTool StorageServer
+;
+
+;Language - standard language definitions
+&EN
+
+; standard SIS file header
+#{"ATStorageServer"},(0xA22E6C80),1,8,1
+
+;Localised Vendor name
+%{"Vendor-EN"}
+
+;Unique Vendor name
+:"Vendor"
+
+;Supports Series 60 v 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; 4 Files to install
+"\epoc32\release\armv5\udeb\atoolstorageserver.exe"-"!:\sys\bin\atoolstorageserver.exe"
+"\epoc32\release\armv5\udeb\atoolstorageserverclnt.dll"-"!:\sys\bin\atoolstorageserverclnt.dll"
--- a/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ b/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -19,8 +19,8 @@
 */
 
 #include "../osrndtools_plat/group/bld.inf"
-//#include "../stif/group/bld.inf"
+#include "../stif/group/bld.inf"
 #include "../memspy/group/bld.inf"
-//#include "../hti/group/bld.inf"
+#include "../hti/group/bld.inf"
 #include "../piprofiler/group/bld.inf"
 #include "../analyzetool/group/bld.inf"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiAutoStart/data/10210CC4.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for the HtiAutoStart.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x10210CC4;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x101F7D87;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x10210CC5;
+                    version_no         = 1;
+                    display_name       = "Hti autostart";
+                    default_data       = "";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiAutoStart/group/HtiAutoStart.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Recognizer for starting HTI automatically on device start-up.
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiAutoStart.dll
+TARGETTYPE      PLUGIN
+
+UID             0x10009D8D 0x10210CC4
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          HtiAutoStart.cpp
+
+LANG            SC
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/10210CC4.rss
+TARGET          HtiAutoStart.rsc
+END
+
+LIBRARY         euser.lib
+LIBRARY         apmime.lib
+LIBRARY         ecom.lib
+
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiAutoStart/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiAutoStart
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiAutoStart.mmp
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiAutoStart/inc/HtiAutoStart.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of recognizer that automatically starts HTI
+*               on device start-up if the device is configured to load
+*               data recognizers during start-up.
+*
+*/
+
+
+#ifndef __HTIAUTOSTART_H
+#define __HTIAUTOSTART_H
+
+
+//  INCLUDES
+#include <apmrec.h>
+#include <e32std.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+/**
+*  Implements CHtiAutostart
+*/
+class CHtiAutostart : public CApaDataRecognizerType
+    {
+    public: // new functions
+        static CApaDataRecognizerType* CreateRecognizerL();
+        CHtiAutostart();
+        static void StartThread();
+        static TInt StartAppThreadFunction( TAny* aParam );
+        static void StartAppThreadFunctionL();
+
+    public: // from CApaDataRecognizerType
+
+        TUint PreferredBufSize();
+        TDataType SupportedDataTypeL( TInt aIndex ) const;
+
+    private: // from CApaDataRecognizerType
+
+        void DoRecognizeL( const TDesC& aName, const TDesC8& aBuffer );
+    };
+
+#endif // __HTIAUTOSTART_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiAutoStart/src/HtiAutoStart.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,188 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiAutoStart implementation
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiAutoStart.h"
+#include <apmrec.h>
+#include <ecom/implementationproxy.h>
+
+// CONSTANTS
+const static TUint KHtiAutoStartImplUid = 0x10210CC5;
+const static TUid KHtiAutoStartUid = {0x10210CC4};
+_LIT( KHtiFrameworkExe, "HtiFramework.exe" );
+_LIT( KHtiMatchPattern, "HtiFramework*" );
+
+const TImplementationProxy ImplementationTable[] =
+    {
+    IMPLEMENTATION_PROXY_ENTRY( KHtiAutoStartImplUid,
+                                CHtiAutostart::CreateRecognizerL )
+    };
+
+// MACROS
+#ifdef __ENABLE_LOGGING__
+
+#include <flogger.h>
+_LIT( KLogFolder, "hti" );
+_LIT( KLogFile,   "htiautostart.txt" );
+
+#define HTI_LOG_TEXT(a1) {_LIT(temp, a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#define HTI_LOG_DES(a1) {RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, a1);}
+#define HTI_LOG_FORMAT(a1,a2) {_LIT(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, (a2));}
+
+#else   // !__ENABLE_LOGGING__
+
+#define HTI_LOG_TEXT(a1)
+#define HTI_LOG_DES(a1)
+#define HTI_LOG_FORMAT(a1,a2)
+
+#endif // __ENABLE_LOGGING__
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// ----------------------------------------------------------------------------
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+    {
+    HTI_LOG_TEXT( "ImplementationGroupProxy" );
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
+// ----------------------------------------------------------------------------
+CApaDataRecognizerType* CHtiAutostart::CreateRecognizerL()
+    {
+    HTI_LOG_TEXT( "CreateRecognizerL" );
+    CApaDataRecognizerType* recognizer = new CHtiAutostart();
+    CHtiAutostart::StartThread();
+    return recognizer;
+    }
+
+// ----------------------------------------------------------------------------
+CHtiAutostart::CHtiAutostart()
+    :CApaDataRecognizerType( KHtiAutoStartUid, CApaDataRecognizerType::ENormal )
+    {
+    HTI_LOG_TEXT( "CHtiAutostart constructor" );
+    iCountDataTypes = 1;
+    }
+
+// ----------------------------------------------------------------------------
+TUint CHtiAutostart::PreferredBufSize()
+    {
+    HTI_LOG_TEXT( "PreferredBufSize" );
+    return 0;
+    }
+
+// ----------------------------------------------------------------------------
+TDataType CHtiAutostart::SupportedDataTypeL( TInt /*aIndex*/ ) const
+    {
+    HTI_LOG_TEXT( "SupportedDataTypeL" );
+    return TDataType();
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiAutostart::DoRecognizeL( const TDesC& /*aName*/,
+                                  const TDesC8& /*aBuffer*/ )
+    {
+    HTI_LOG_TEXT( "DoRecognizeL" );
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiAutostart::StartThread()
+    {
+    HTI_LOG_TEXT( "StartThread" );
+    //create a new thread for starting our application
+    RThread* startAppThread = new RThread();
+
+    User::LeaveIfError( startAppThread->Create(
+        _L( "HtiAutostart" ),
+        CHtiAutostart::StartAppThreadFunction,
+        KDefaultStackSize,
+        KMinHeapSize,
+        KMinHeapSize,
+        NULL,
+        EOwnerThread ) );
+
+    startAppThread->SetPriority( EPriorityNormal );
+    startAppThread->Resume();
+    startAppThread->Close();
+    delete startAppThread;
+    }
+
+// ----------------------------------------------------------------------------
+TInt CHtiAutostart::StartAppThreadFunction( TAny* /*aParam*/ )
+    {
+    HTI_LOG_TEXT( "StartAppThreadFunction" );
+    // create a TRAP cleanup
+    CTrapCleanup * cleanup = CTrapCleanup::New();
+    TInt err;
+    if ( cleanup == NULL )
+        {
+        err = KErrNoMemory;
+        }
+    else
+        {
+        TRAP( err, StartAppThreadFunctionL() );
+        }
+    delete cleanup;
+
+    if ( err != KErrNone )
+        {
+        HTI_LOG_FORMAT( "StartAppThreadFunctionL leave %d", err );
+        User::Panic( _L( "HtiAutostart" ), err );
+        }
+
+    return err;
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiAutostart::StartAppThreadFunctionL()
+    {
+    HTI_LOG_TEXT( "StartAppThreadFunctionL" );
+    // Check if HtiFramework is already running
+    TFullName processName;
+    TFindProcess finder( KHtiMatchPattern );
+    TInt err = finder.Next( processName );
+    if ( err == KErrNone )
+        {
+        HTI_LOG_TEXT( "HtiFramework.exe already running, nothing to do" );
+        return;
+        }
+
+    RProcess prs;
+    err = prs.Create( KHtiFrameworkExe, KNullDesC );
+    if ( err == KErrNone )
+        {
+        prs.Resume();
+        prs.Close();
+        HTI_LOG_TEXT( "HtiFramework.exe process created" );
+        }
+    else
+        {
+        HTI_LOG_FORMAT( "HtiFramework.exe process creation failed %d", err );
+        User::Leave( err );
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCfg/bwins/HtiCfgu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,11 @@
+EXPORTS
+	?SetParameterL@CHtiCfg@@QAEHABVTDesC8@@0@Z @ 1 NONAME ; int CHtiCfg::SetParameterL(class TDesC8 const &, class TDesC8 const &)
+	?NewLC@CHtiCfg@@SAPAV1@XZ @ 2 NONAME ; class CHtiCfg * CHtiCfg::NewLC(void)
+	?LoadCfgL@CHtiCfg@@QAEXABVTDesC16@@0@Z @ 3 NONAME ; void CHtiCfg::LoadCfgL(class TDesC16 const &, class TDesC16 const &)
+	??1CHtiCfg@@UAE@XZ @ 4 NONAME ; CHtiCfg::~CHtiCfg(void)
+	?GetParameterL@CHtiCfg@@QAE?AVTPtrC8@@ABVTDesC8@@@Z @ 5 NONAME ; class TPtrC8 CHtiCfg::GetParameterL(class TDesC8 const &)
+	?GetParameterIntL@CHtiCfg@@QAEHABVTDesC8@@@Z @ 6 NONAME ; int CHtiCfg::GetParameterIntL(class TDesC8 const &)
+	?SaveCfgL@CHtiCfg@@QAEXABVTDesC16@@0@Z @ 7 NONAME ; void CHtiCfg::SaveCfgL(class TDesC16 const &, class TDesC16 const &)
+	?RemoveParameterL@CHtiCfg@@QAEHABVTDesC8@@@Z @ 8 NONAME ; int CHtiCfg::RemoveParameterL(class TDesC8 const &)
+	?NewL@CHtiCfg@@SAPAV1@XZ @ 9 NONAME ; class CHtiCfg * CHtiCfg::NewL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCfg/eabi/HtiCfgu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,15 @@
+EXPORTS
+	_ZN7CHtiCfg13GetParameterLERK6TDesC8 @ 1 NONAME
+	_ZN7CHtiCfg13SetParameterLERK6TDesC8S2_ @ 2 NONAME
+	_ZN7CHtiCfg16GetParameterIntLERK6TDesC8 @ 3 NONAME
+	_ZN7CHtiCfg16RemoveParameterLERK6TDesC8 @ 4 NONAME
+	_ZN7CHtiCfg4NewLEv @ 5 NONAME
+	_ZN7CHtiCfg5NewLCEv @ 6 NONAME
+	_ZN7CHtiCfg8LoadCfgLERK7TDesC16S2_ @ 7 NONAME
+	_ZN7CHtiCfg8SaveCfgLERK7TDesC16S2_ @ 8 NONAME
+	_ZN7CHtiCfgD0Ev @ 9 NONAME
+	_ZN7CHtiCfgD1Ev @ 10 NONAME
+	_ZN7CHtiCfgD2Ev @ 11 NONAME
+	_ZTI7CHtiCfg @ 12 NONAME ; #<TI>#
+	_ZTV7CHtiCfg @ 13 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCfg/group/HtiCfg.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiCfg project definition.
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiCfg.dll
+TARGETTYPE      DLL
+
+UID             0x1000008d 0x200212DD
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          HtiCfg.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY         bafl.lib
+LIBRARY         efsrv.lib
+LIBRARY         euser.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCfg/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiCfg build info
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiCfg.mmp
+
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCfg/src/HtiCfg.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,331 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CHtiCfg implementation
+*
+*/
+
+// INCLUDE FILES
+#include "HtiCfg.h"
+#include <badesca.h>
+#include <f32file.h>
+
+// CONSTANTS
+const static TInt KCfgArrayGranularity = 5;
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+EXPORT_C CHtiCfg* CHtiCfg::NewL()
+    {
+    CHtiCfg* self = NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::NewLC
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+EXPORT_C CHtiCfg* CHtiCfg::NewLC()
+    {
+    CHtiCfg* self = new ( ELeave ) CHtiCfg();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::CHtiCfg
+// Constructor
+// -----------------------------------------------------------------------------
+CHtiCfg::CHtiCfg():iCfgParameters( NULL )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::CHtiCfg
+// Destructor
+// -----------------------------------------------------------------------------
+EXPORT_C CHtiCfg::~CHtiCfg()
+    {
+    if ( iCfgParameters )
+        {
+        iCfgParameters->Reset();
+        delete iCfgParameters;
+        iCfgParameters = NULL;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::ConstructL
+// Second phase constructor. Private.
+// -----------------------------------------------------------------------------
+void CHtiCfg::ConstructL()
+    {
+    iCfgParameters = new ( ELeave ) CDesC8ArrayFlat( KCfgArrayGranularity );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::LoadCfgL
+// Searches the file in all drives and if found reads all parameter lines to the
+// iCfgParameters array.
+// -----------------------------------------------------------------------------
+EXPORT_C void CHtiCfg::LoadCfgL( const TDesC& aCfgFilePath,
+                                 const TDesC& aCfgFileName )
+    {
+    // Reset parameters
+    if ( iCfgParameters )
+        {
+        iCfgParameters->Reset();
+        delete iCfgParameters;
+        iCfgParameters = NULL;
+        }
+    iCfgParameters = new ( ELeave ) CDesC8ArrayFlat( KCfgArrayGranularity );
+
+    // Open & read file
+    RFs fsSession;
+    User::LeaveIfError( fsSession.Connect() );
+    CleanupClosePushL( fsSession );
+
+    TFindFile finder( fsSession );
+    TFileName path( aCfgFilePath );
+    TInt err = finder.FindByPath( aCfgFileName, &path );
+    if ( err != KErrNone )
+        {
+        User::Leave( err );
+        }
+
+    TFileName cfgFile = finder.File();
+
+    RFile file;
+    User::LeaveIfError( file.Open( fsSession, cfgFile, EFileRead ) );
+    CleanupClosePushL( file );
+
+    TInt fileLength;
+    User::LeaveIfError( file.Size( fileLength ) );
+
+    HBufC8* fileData = HBufC8::NewLC( fileLength );
+    TPtr8 fileDes = fileData->Des();
+    User::LeaveIfError( file.Read( fileDes ) );
+
+    // Get parameters
+    TBool eof = EFalse;
+    while ( !eof )
+        {
+        TInt strEndIndex = fileDes.Locate( KCfgNewLine );
+        if ( strEndIndex == KErrNotFound )
+            {
+                strEndIndex = fileDes.Length();
+                eof = ETrue;
+            }
+
+        TPtrC8 line = fileDes.Left( strEndIndex );
+
+        if ( line.Locate( KCfgComment ) != 0 )
+            {
+            if ( line.Locate( KCfgSeparator ) > 0 )
+                {
+                TBuf8<KMaxParameterLength> parameter;
+                parameter.Copy( line );
+                parameter.Trim();
+                iCfgParameters->AppendL( parameter );
+                }
+            }
+
+        if ( !eof )
+            fileDes = fileDes.Right( fileDes.Length() - ( strEndIndex + 1 ) );
+
+        }
+
+    CleanupStack::PopAndDestroy( 3 ); // fsSession, fileData, file
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::SaveCfgL
+// Writes all parameter lines from iCfgParameters array to the file.
+// Existing file is searched from all drives and if found file will be replaced.
+// If existing file is not found file will be created to c-drive.
+// -----------------------------------------------------------------------------
+EXPORT_C void CHtiCfg::SaveCfgL( const TDesC& aCfgFilePath,
+                                 const TDesC& aCfgFileName )
+    {
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+
+    RFile file;
+    CleanupClosePushL( file );
+
+    // Find the file
+    TFindFile finder( fs );
+    TFileName path( aCfgFilePath );
+    TFileName cfgFile;
+    TInt err = finder.FindByPath( aCfgFileName, &path );
+    if ( err != KErrNone )
+        {
+        cfgFile.Append( _L ( "c:" ) );
+        cfgFile.Append( path );
+        cfgFile.Append( aCfgFileName );
+        }
+    else
+        {
+        cfgFile = finder.File();
+        // If the file was found from ROM, we must save to C-drive.
+        if ( cfgFile[0] == 'z' || cfgFile[0] == 'Z' )
+            {
+            cfgFile[0] = 'c';
+            }
+        }
+
+    // Replace or create the file
+    User::LeaveIfError( file.Replace( fs, cfgFile, EFileWrite | EFileShareAny ) );
+
+    // Write the file
+    for ( TInt i = 0; i < iCfgParameters->Count(); i++ )
+        {
+        file.Write( iCfgParameters->MdcaPoint( i ) );
+        file.Write( _L8( "\n" ) );
+        }
+
+    // Close
+    CleanupStack::PopAndDestroy( 2 ); // fs, file
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::SetParameterL
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CHtiCfg::SetParameterL( const TDesC8& aName,
+                                      const TDesC8& aValue )
+    {
+    // Does the parameter exist?
+    for ( TInt i = 0; i < iCfgParameters->Count(); i++ )
+        {
+        TInt sepIndex =
+            ( iCfgParameters->MdcaPoint( i ) ).Locate( KCfgSeparator );
+        if ( sepIndex <= 0 )
+            User::Leave( KErrGeneral ); // should not happen
+
+        TPtrC8 name = ( iCfgParameters->MdcaPoint( i ) ).Left( sepIndex );
+        if ( name.Compare( aName ) == 0 )
+            {
+            iCfgParameters->Delete( i );
+            TBuf8<KMaxParameterLength> parameter;
+            parameter.Append( aName );
+            parameter.Append( KCfgSeparator );
+            parameter.Append( aValue );
+            iCfgParameters->AppendL( parameter );
+            return KErrNone;
+            }
+        }
+
+    // Apparently not.. add it
+    TBuf8<KMaxParameterLength> parameter;
+    parameter.Append( aName );
+    parameter.Append( KCfgSeparator );
+    parameter.Append( aValue );
+    iCfgParameters->AppendL( parameter );
+
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::RemoveParameterL
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CHtiCfg::RemoveParameterL( const TDesC8& aName )
+    {
+    for ( TInt i = 0; i < iCfgParameters->Count(); i++ )
+        {
+        TInt sepIndex =
+            ( iCfgParameters->MdcaPoint( i ) ).Locate( KCfgSeparator );
+        if ( sepIndex <= 0 )
+            User::Leave( KErrGeneral ); // should not happen
+
+        TPtrC8 name = ( iCfgParameters->MdcaPoint( i ) ).Left( sepIndex );
+        if ( name.Compare( aName ) == 0 )
+            {
+            iCfgParameters->Delete( i );
+            return KErrNone;
+            }
+        }
+
+    return KErrNotFound;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::GetParameterL
+// -----------------------------------------------------------------------------
+EXPORT_C TPtrC8 CHtiCfg::GetParameterL( const TDesC8& aName )
+    {
+    for ( TInt i = 0; i < iCfgParameters->Count(); i++ )
+        {
+        TInt sepIndex =
+            ( iCfgParameters->MdcaPoint( i ) ).Locate( KCfgSeparator );
+        if ( sepIndex <= 0 )
+            User::Leave( KErrGeneral ); // should not happen
+
+        TPtrC8 name = ( iCfgParameters->MdcaPoint( i ) ).Left( sepIndex );
+        if ( name.Compare( aName ) == 0 )
+            {
+            TPtrC8 value = ( iCfgParameters->MdcaPoint( i ) ).Right(
+                ( iCfgParameters->MdcaPoint( i ) ).Length() - ( sepIndex + 1 ) );
+            return value;
+            }
+        }
+    User::Leave( KErrNotFound );
+    return 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiCfg::GetParameterIntL
+// -----------------------------------------------------------------------------
+EXPORT_C TInt CHtiCfg::GetParameterIntL( const TDesC8& aName )
+    {
+    for ( TInt i = 0; i < iCfgParameters->Count(); i++ )
+        {
+        TInt sepIndex =
+            ( iCfgParameters->MdcaPoint( i ) ).Locate( KCfgSeparator );
+        if ( sepIndex <= 0 )
+            User::Leave( KErrGeneral ); // should not happen
+
+        TPtrC8 name = ( iCfgParameters->MdcaPoint( i ) ).Left( sepIndex );
+        if ( name.Compare( aName ) == 0 )
+            {
+            TPtrC8 value = ( iCfgParameters->MdcaPoint( i ) ).Right(
+                ( iCfgParameters->MdcaPoint( i ) ).Length() - ( sepIndex + 1 ) );
+
+            TLex8 lex( value );
+            TInt result;
+            User::LeaveIfError( lex.Val( result ) );
+            return result;
+            }
+        }
+    User::Leave( KErrNotFound );
+    return 0;
+    }
+
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BWINS/HtiBtCommInterfaceu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,13 @@
+EXPORTS
+	??0RHtiBtCommInterface@@QAE@XZ @ 1 NONAME ; RHtiBtCommInterface::RHtiBtCommInterface(void)
+	?CancelReceive@RHtiBtCommInterface@@QAEXXZ @ 2 NONAME ; void RHtiBtCommInterface::CancelReceive(void)
+	?CancelSend@RHtiBtCommInterface@@QAEXXZ @ 3 NONAME ; void RHtiBtCommInterface::CancelSend(void)
+	?Close@RHtiBtCommInterface@@QAEXXZ @ 4 NONAME ; void RHtiBtCommInterface::Close(void)
+	?Connect@RHtiBtCommInterface@@QAEHAAVTDesC8@@H@Z @ 5 NONAME ; int RHtiBtCommInterface::Connect(class TDesC8 &, int)
+	?GetPortNumber@RHtiBtCommInterface@@QBEHXZ @ 6 NONAME ; int RHtiBtCommInterface::GetPortNumber(void) const
+	?GetReceiveBufferSize@RHtiBtCommInterface@@QBEHXZ @ 7 NONAME ; int RHtiBtCommInterface::GetReceiveBufferSize(void) const
+	?GetSendBufferSize@RHtiBtCommInterface@@QBEHXZ @ 8 NONAME ; int RHtiBtCommInterface::GetSendBufferSize(void) const
+	?Receive@RHtiBtCommInterface@@QAEXAAVTDes8@@AAVTRequestStatus@@@Z @ 9 NONAME ; void RHtiBtCommInterface::Receive(class TDes8 &, class TRequestStatus &)
+	?Send@RHtiBtCommInterface@@QAEXABVTDesC8@@AAVTRequestStatus@@@Z @ 10 NONAME ; void RHtiBtCommInterface::Send(class TDesC8 const &, class TRequestStatus &)
+	?Version@RHtiBtCommInterface@@QBE?AVTVersion@@XZ @ 11 NONAME ; class TVersion RHtiBtCommInterface::Version(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BWINS/HtiBtCommServeru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	?StartThread@@YAHXZ @ 1 NONAME ; int StartThread(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BWINS/HtiBtSerialComHelperu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,16 @@
+EXPORTS
+	??1CBtSerialClient@@UAE@XZ @ 1 NONAME ; CBtSerialClient::~CBtSerialClient(void)
+	?ConnectL@CBtSerialClient@@QAEXABVTDesC16@@H@Z @ 2 NONAME ; void CBtSerialClient::ConnectL(class TDesC16 const &, int)
+	?ConnectL@CBtSerialClient@@QAEXVTBTDevAddr@@H@Z @ 3 NONAME ; void CBtSerialClient::ConnectL(class TBTDevAddr, int)
+	?ConnectL@CBtSerialClient@@QAEXXZ @ 4 NONAME ; void CBtSerialClient::ConnectL(void)
+	?Connected@CBtSerialClient@@QAEHXZ @ 5 NONAME ; int CBtSerialClient::Connected(void)
+	?Connecting@CBtSerialClient@@QAEHXZ @ 6 NONAME ; int CBtSerialClient::Connecting(void)
+	?Disconnect@CBtSerialClient@@QAEXXZ @ 7 NONAME ; void CBtSerialClient::Disconnect(void)
+	?FreeSpaceInSendBuffer@CBtSerialClient@@QAEHXZ @ 8 NONAME ; int CBtSerialClient::FreeSpaceInSendBuffer(void)
+	?NewL@CBtSerialClient@@SAPAV1@AAVMBtSerialClientObserver@@@Z @ 9 NONAME ; class CBtSerialClient * CBtSerialClient::NewL(class MBtSerialClientObserver &)
+	?ReadAsyncL@CBtSerialClient@@QAEXXZ @ 10 NONAME ; void CBtSerialClient::ReadAsyncL(void)
+	?SendBufferMaxSize@CBtSerialClient@@QAEHXZ @ 11 NONAME ; int CBtSerialClient::SendBufferMaxSize(void)
+	?SendL@CBtSerialClient@@QAEXABVTDesC8@@@Z @ 12 NONAME ; void CBtSerialClient::SendL(class TDesC8 const &)
+	?ServerAddressL@CBtSerialClient@@QAE?AVTBTDevAddr@@XZ @ 13 NONAME ; class TBTDevAddr CBtSerialClient::ServerAddressL(void)
+	?ServicePort@CBtSerialClient@@QAEHXZ @ 14 NONAME ; int CBtSerialClient::ServicePort(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/BtSerialClient.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,258 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Bluetooth serial client.
+*
+*/
+
+
+#ifndef __BTSERIALCLIENT_H__
+#define __BTSERIALCLIENT_H__
+
+// INCLUDES
+#include <e32base.h>
+#include <es_sock.h>
+#include <bluetooth/btpowercontrol.h>
+#include <bt_sock.h>
+#include <btextnotifiers.h>
+#include <btsdp.h>
+
+#include "SocketObserver.h"
+
+// FORWARD DECLARATIONS
+class CMessageServiceSearcher;
+class CSocketsReader;
+class CSocketsWriter;
+
+class MBtSerialClientObserver
+    {
+public:
+    virtual void ConnectedToServer(TInt aError) = 0;
+    virtual void DisconnectedFromServer() = 0;
+    virtual void DataFromServer(const TDesC8& aData) = 0;
+    virtual void AllBufferedDataSent() = 0;
+    };
+
+/**
+* CBtSerialClient
+* Connects and sends messages to a remote machine using bluetooth
+*/
+class CBtSerialClient : public CActive,
+                        public MSocketObserver
+    {
+    public: // Constructors and destructor
+
+        /**
+        * NewL()
+        * Construct a CBtSerialClient
+        * @param aObserver the observer for this BT serial client
+        * @return a pointer to the created instance of CBtSerialClient
+        */
+        IMPORT_C static CBtSerialClient* NewL( MBtSerialClientObserver& aObserver );
+
+        /**
+        * ~CBtSerialClient()
+        * Destroy the object and release all memory objects.
+        * Close any open sockets.
+        */
+        IMPORT_C virtual ~CBtSerialClient();
+
+    public:     // New functions
+
+        /**
+        * ConnectL()
+        * Connect to remote device. Query user for a device.
+        */
+        IMPORT_C void ConnectL();
+
+        /**
+        * ConnectL()
+        * Connect to remote device.
+        */
+        IMPORT_C void ConnectL(const TBTDevAddr aBTServerDevice, const TInt aPort );
+
+        /**
+        * ConnectL()
+        * Connect to remote device by device name.
+        */
+        IMPORT_C void ConnectL( const TDesC& aBTServerDeviceName, const TInt aPort );
+
+        /**
+        * DisconnectL()
+        * Disconnect from remote machine
+        */
+        IMPORT_C void Disconnect();
+
+        /**
+        * IsConnecting()
+        * @return ETrue if the client is establishing a
+        * connection to the server.
+        */
+        IMPORT_C TBool Connecting();
+
+        /**
+        * Connected()
+        * @return ETrue if the client is fully connected to the server.
+        */
+        IMPORT_C TBool Connected();
+
+        /**
+        * ServerAddressL()
+        * @return address of connected server. Leaves with KErrNotReady, if
+        * not connected.
+        */
+        TBTDevAddr ServerAddressL();
+
+        /**
+        * Add data to outgoing buffer and start sending it to client.
+        *
+        * Leaves with KErrOverflow, if the outgoing buffer cannot
+        * be added all of the aData.
+        * Leaves with KErrNotReady, if client is not connected.
+        * When all data in internal buffer has been sent, observer
+        * is notified (AllBufferedDataSent)
+        */
+        IMPORT_C void SendL(const TDesC8& aData);
+
+        /**
+        * Issue read operation. Will complete asyncronously.
+        *
+        * Leaves with KErrNotReady, if client is not connected.
+        * Notifies observer, when some data has been read. Caller
+        * is responsible for calling this method again to receive
+        * more data.
+        */
+        IMPORT_C void ReadAsyncL();
+
+        /**
+        * Query free size of outgoing buffer.
+        */
+        IMPORT_C TInt FreeSpaceInSendBuffer();
+
+        /**
+        * Query max size of outgoing buffer.
+        */
+        IMPORT_C TInt SendBufferMaxSize();
+
+        /**
+        * Query the port of the service we are connected with
+        * @return Port number or KErrDisconnected if not connected to a service
+        */
+        IMPORT_C TInt ServicePort();
+
+    protected:    // from CActive
+
+        /**
+        * DoCancel()
+        * Cancel any outstanding requests
+        */
+        void DoCancel();
+
+        /**
+        * RunL()
+        * Respond to an event
+        */
+        void RunL();
+
+    protected: // from MSocketObserver
+
+        void ReportError( TErrorType aErrorType, TInt aErrorCode );
+        void NewData( const TDesC8& aData );
+        void AllBufferedDataSent();
+
+    private:
+
+        /**
+        * ConnectToServerL
+        * Connects to the service
+        */
+        void ConnectToServerL();
+
+        /**
+        * DisconnectFromServer()
+        * Disconnects from the service
+        */
+        void DisconnectFromServer();
+
+        /**
+        * CBtSerialClient()
+        * Constructs this object
+        */
+        CBtSerialClient( MBtSerialClientObserver& aObserver );
+
+        /**
+        * ConstructL()
+        * Performs second phase construction of this object
+        */
+        void ConstructL();
+
+    private:    // data
+
+        /**
+        * TState
+        * The state of the active object, determines behaviour within
+        * the RunL method.
+        * EWaitingToGetDevice waiting for the user to select a device
+        * EGettingDevice searching for a device
+        * EGettingService searching for a service
+        * EGettingConnection connecting to a service on a remote machine
+        * EConnected connected to a service on a remote machine
+        */
+        enum TState
+            {
+            EWaitingToGetDevice,      // phase 1 of Connect
+            EGettingDevice,           // phase 2 of Connect
+            EGettingService,          // phase 3 of Connect
+            EGettingConnection,       // phase 4 of Connect
+            EConnected, // sending and receiving data
+            EDisconnecting
+            };
+
+        MBtSerialClientObserver& iObserver;
+
+        /** iState the current state of the client */
+        TState iState;
+
+        /**
+        * iServiceSearcher searches for service this
+        * client can connect to.
+        * Owned by CBtSerialClient
+        */
+        CMessageServiceSearcher* iServiceSearcher;
+
+        /**
+        * iCurrentServiceIndex the index number of the service we are
+        * currently connecting/connected to
+        */
+        TInt iCurrentServiceIndex;
+
+        /** iSocketServer a connection to the socket server */
+        RSocketServ iSocketServer;
+
+        /** iSocket a socket to connect with */
+        RSocket iSocket;
+
+        /** iServiceClass the service class UUID to search for */
+        TUUID iServiceClass;
+
+        TBTDevAddr iBTServerDevice;
+
+        CSocketsReader* iSocketReader;
+        CSocketsWriter* iSocketWriter;
+
+        RBTPowerControl iPowerControl;
+    };
+
+#endif // __BTSERIALCLIENT_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/BtSerialEngine.pan	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Bluetooth serial engine panic codes.
+*
+*/
+
+
+#ifndef __BTSERIALENGINE_PAN__
+#define __BTSERIALENGINE_PAN__
+
+#include <e32def.h>
+#include <e32std.h>
+
+/** Panic Categories */
+_LIT( KPanicSerialEngine, "BTSerialEngine" ); // All engine classes
+_LIT( KPanicBTServiceAdvertiser, "BTServiceAdvertiser" ); // only service advertiser
+
+
+enum TBTSerialEnginePanics
+    {
+    EBTPointToPointReceiverInvalidState = 1,
+    EBTPointToPointSenderExists = 2,
+    EBTPointToPointReceiverExists = 3,
+    EBTPointToPointSenderInvalidState = 4,
+    EBTPointToPointNoSender = 5,
+    EBTPointToPointAddMessage = 6,
+    EBTPointToPointNextRecordRequestComplete = 7,
+    EBTPointToPointAttributeRequestResult = 8,
+    EBTPointToPointAttributeRequestComplete = 9,
+    EBTPointToPointProtocolRead = 10,
+    EBTPointToPointAttributeRequest = 11,
+    EBTPointToPointSdpRecordDelete = 12,
+    EBTPointToPointServerStop = 13,
+    EBTPointToPointInvalidLogicState = 14,
+    EBTPointToPointUnableToDisconnect = 15,
+
+    EBTSerialEngineReadSocketBadState = 16,
+    EBTSerialEngineWriteSocketBadState = 17
+    };
+
+inline void Panic( TBTSerialEnginePanics aReason )
+    {
+    User::Panic( KPanicSerialEngine, aReason );
+    }
+
+
+#endif // __BTSERIALENGINE_PAN__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/HtiBtEngineLogging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,92 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logging for Bluetooth engine.
+*
+*/
+
+
+#ifndef __HTIBTENGINELOGGING_H__
+#define __HTIBTENGINELOGGING_H__
+
+// INCLUDES
+#include <flogger.h>
+
+/******************************************************/
+/**     LOG SETUP                                    **/
+/******************************************************/
+_LIT(KLogFolder, "Hti");
+_LIT(KLogFile, "BtSerialEngine.log");
+
+#ifdef __ENABLE_LOGGING__
+// Comment out the levels which are marked supported in the build
+// (and which are used runtime).
+//
+#define LOG_LEVEL_ERROR_SUPPORTED
+#define LOG_LEVEL_WARN_SUPPORTED
+#define LOG_LEVEL_INFO_SUPPORTED
+//#define LOG_LEVEL_DEBUG_SUPPORTED
+#endif
+
+/******************************************************/
+/**     MACRO DEFINITIONS                            **/
+/******************************************************/
+
+// Macros:                            Example:                                 Result:
+// LOGFMT_E(formatstring, parameter)  LOGFMT_E("Leave in RunL: %d", -6)        <TIME> ERROR: Leave in RunL: -6
+// LOG_E(string)                      LOG_E("There was an error")              <TIME> ERROR: There was an error
+// LOGFMT_W(formatstring, parameter)  LOGFMT_W("Buffer too small: %d", 12)     <TIME> WARNING: Buffer too small: 12
+// LOG_W(string)                      LOG_W("warmingtext")                     <TIME> WARNING: warningtext
+// LOGFMT_I(formatstring, parameter)  LOGFMT_I("plugin loaded: %S", &myDescr8) <TIME> INFO: plugin loaded: myplugin
+// LOG_I(string)                      LOG_I("abc")                             <TIME> INFO: abc
+// LOGFMT_D(formatstring, parameter)  LOGFMT_D("buffer length: %d", 56)        <TIME> DEBUG: buffer length: 56
+// LOG_D(string)                      LOG_D("abc")                             <TIME> DEBUG: abc
+
+#define ERRORSTR "ERROR: "
+#define WARNSTR  "WARNING: "
+#define INFOSTR  "INFO: "
+#define DEBUGSTR "DEBUG: "
+
+#ifdef LOG_LEVEL_ERROR_SUPPORTED
+    #define LOGFMT_E(a1, a2) {_LIT8(temp, ERRORSTR##a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, a2);}
+    #define LOG_E(a1) {_LIT8(temp, ERRORSTR##a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#else
+    #define LOGFMT_E(a1, a2) {}
+    #define LOG_E(a1) {}
+#endif
+
+#ifdef LOG_LEVEL_WARN_SUPPORTED
+    #define LOGFMT_W(a1, a2) {_LIT8(temp, WARNSTR##a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, a2);}
+    #define LOG_W(a1) {_LIT8(temp, WARNSTR##a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#else
+    #define LOGFMT_W(a1, a2) {}
+    #define LOG_W(a1) {}
+#endif
+
+#ifdef LOG_LEVEL_INFO_SUPPORTED
+    #define LOGFMT_I(a1, a2) {_LIT8(temp, INFOSTR##a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, a2);}
+    #define LOG_I(a1) {_LIT8(temp, INFOSTR##a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#else
+    #define LOGFMT_I(a1, a2) {}
+    #define LOG_I(a1) {}
+#endif
+
+#ifdef LOG_LEVEL_DEBUG_SUPPORTED
+    #define LOGFMT_D(a1, a2) {_LIT8(temp, DEBUGSTR##a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, a2);}
+    #define LOG_D(a1) {_LIT8(temp, DEBUGSTR##a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#else
+    #define LOGFMT_D(a1, a2) {}
+    #define LOG_D(a1) {}
+#endif
+
+#endif // __HTIBTENGINELOGGING_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/HtiBtPowerManager.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,84 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  BT power manager definition based on btpm.h.
+*                This is needed for accessing the blue tooth power management
+*                DLL directly to turn on the blue tooth in NCP environment,
+*                since the NCP releases do not contain the required headers.
+*
+*/
+
+
+#ifndef __HTIBTPOWERMANAGER_H
+#define __HTIBTPOWERMANAGER_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <es_sock.h>
+
+// CLASS DECLARATION
+
+/**
+* The observer class that is interested in power mode change
+*/
+class MBTPowerManagerObserver
+    {
+    public:
+        virtual void HandlePowerChange(TBool aNewState) = 0;
+    };
+
+// CLASS DECLARATION
+
+/**
+* This base class of BT power management
+*/
+class CBTPowerManagerBase : public CBase
+    {
+    public:
+
+        /**
+        * Get the current power state
+        * @param aState Reference where the current power state to be saved to
+        * @return KErrNone if successful otherwise one of the system wide error codes
+        */
+        virtual TInt GetPowerState(TBool& aState) = 0;
+
+        /**
+        * Set the current power state
+        * @param aState the current power state
+        * @return KErrNone if successful otherwise one of the system wide error codes
+        */
+        virtual TInt SetPowerState(TBool aState) = 0;
+
+        /**
+        * Notify observers that the power state has been changed
+        */
+        virtual void NotifyPowerChange() = 0;
+
+        /**
+        * Notify observers that the power change has been cancelled
+        */
+        virtual void NotifyPowerChangeCancel() = 0;
+
+        /**
+        * Set the device into test mode
+        * @return KErrNone if successful otherwise one of the system wide error codes
+        */
+        virtual TInt SetDUTMode() = 0;
+    };
+
+typedef CBTPowerManagerBase* (*TNewBTPowerManagerL)(MBTPowerManagerObserver* aObserver);
+
+#endif  // __HTIBTPOWERMANAGER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/SocketObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  The error notification interface.
+*
+*/
+
+
+#ifndef __SOCKETOBSERVER_H__
+#define __SOCKETOBSERVER_H__
+
+// CLASS DECLARATION
+
+/**
+* MEngineNotifier.
+* This class specifies the error notification interface.
+*/
+class MSocketObserver
+    {
+    public: // Enumerations
+
+        /**
+        * TErrorType.
+        * Error types encountered when reading/writing to a sockets.
+        *  - EDisconnected.      A disconnected error has been encountered.
+        *  - ETimeOutOnWrite.    A write operation has failed to complete
+        *                        within a predetermined period.
+        *  - EGeneralReadError.  A general error has been encountered
+        *                        during a read.
+        *  - EGeneralWriteError. A general error has been encountered
+        *                        during a write
+        */
+        enum TErrorType
+            {
+            EDisconnected,
+            ETimeOutOnWrite,
+            EGeneralReadError,
+            EGeneralWriteError
+            };
+
+    public: // New functions
+
+        /**
+        * ReportError.
+        * Reports a communication error.
+        * @param aErrorType Error type.
+        * @param aErrorCode Associated error code.
+        */
+        virtual void ReportError( TErrorType aErrorType, TInt aErrorCode ) = 0;
+
+        /**
+        * NewData.
+        * Data has been received on the socket and read into a buffer.
+        * @param aData The data buffer.
+        */
+        virtual void NewData(const TDesC8& aData) = 0;
+
+        virtual void AllBufferedDataSent() = 0;
+    };
+
+#endif // __SOCKETOBSERVER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/btservicesearcher.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,264 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Bluetooth service searcher.
+*
+*/
+
+
+#ifndef __BTSERVICESEARCHER_H__
+#define __BTSERVICESEARCHER_H__
+
+// INCLUDES
+#include <e32base.h>
+#include <bttypes.h>
+#include <btextnotifiers.h>
+
+#include "sdpattributeparser.h"
+#include "sdpattributenotifier.h"
+
+// CONSTANTS
+#include "messageprotocolconstants.h"
+
+// CLASS DECLARATIONS
+/**
+* CBTServiceSearcher
+* Searches for a service on a remote machine
+*/
+
+class CBTServiceSearcher : public CBase,
+                           public MSdpAgentNotifier,
+                           public MSdpAttributeNotifier
+    {
+    public: // Destructor
+
+        /**
+        * ~CBTServiceSearcher()
+        * Destroy the object and release all memory objects
+        */
+        virtual ~CBTServiceSearcher();
+
+    public: // New functions
+
+        /**
+        * SelectDeviceByDiscoveryL()
+        * Select a device
+        * @param aObserverRequestStatus the observer that is to
+        * be notified when the device selection is complete.
+        */
+        void SelectDeviceByDiscoveryL( TRequestStatus&
+                                       aObserverRequestStatus );
+
+       /**
+        * SelectDeviceByNameL()
+        * Select a device by BT device name.
+        * @param aDeviceName the name of the device to search and select.
+        * @param aObserverRequestStatus the observer that is to
+        * be notified when the device selection is complete.
+        */
+        void SelectDeviceByNameL( const TDesC& aDeviceName,
+                                  TRequestStatus& aObserverRequestStatus );
+
+        /**
+        * FindServiceL()
+        * Find a service on the specified device
+        * @param aDeviceAddress the BT address of the device to search for
+        * the service
+        * @param aObserverRequestStatus the observer that is to be notified
+        * when the service search is complete
+        */
+        void FindServiceL( const TBTDevAddr& aDeviceAddress,
+            TRequestStatus& aObserverRequestStatus );
+
+        /**
+        * BTDevAddr()
+        * @return the bluetooth device address
+        */
+        const TBTDevAddr& BTDevAddr();
+
+        /**
+        * ResponseParams()
+        * @return Information about the device selected by the user
+        */
+        const TBTDeviceResponseParams& ResponseParams();
+
+    protected:  // New functions
+
+        /**
+        * CBTServiceSearcher()
+        * Constructs this object
+        */
+        CBTServiceSearcher();
+
+        /**
+        * Finished()
+        * The search has finished. Notify the observer
+        * that the process is complete.
+        */
+        virtual void Finished( TInt aError = KErrNone );
+
+        /**
+        * HasFinishedSearching()
+        * Is the instance still wanting to search.
+        * @return EFalse if the instance wants searching to continue.
+        */
+        virtual TBool HasFinishedSearching() const;
+
+        /**
+        * HasFoundService()
+        * @return ETrue if a service has been found
+        */
+        TBool HasFoundService() const;
+
+    protected: // abstract methods
+
+        /**
+        * ProtocolList()
+        * The list of Protocols required by the service.
+        */
+        virtual const TSdpAttributeParser::TSdpAttributeList&
+                                           ProtocolList() const = 0;
+
+        /**
+        * ServiceClass()
+        * The service class to search for
+        * @return the service class UUID
+        */
+        virtual const TUUID& ServiceClass() const = 0;
+
+        /**
+        * FoundElementL()
+        * Read the data element
+        * @param aKey a key that identifies the element
+        * @param aValue the data element
+        */
+        virtual void FoundElementL( TInt aKey, CSdpAttrValue& aValue ) = 0;
+
+    public: // from MSdpAgentNotifier
+
+        /**
+        * NextRecordRequestComplete()
+        * Process the result of the next record request
+        * @param aError the error code
+        * @param aHandle the handle of the service record
+        * @param aTotalRecordsCount the total number of matching
+        * service records
+        */
+        void NextRecordRequestComplete( TInt aError,
+                                        TSdpServRecordHandle aHandle,
+                                        TInt aTotalRecordsCount );
+
+        /**
+        * AttributeRequestResult()
+        * Process the next attribute requested
+        * @param aHandle the handle of the service record
+        * @param aAttrID the id of the attribute
+        * @param aAttrValue the value of the attribute
+        */
+        void AttributeRequestResult( TSdpServRecordHandle aHandle,
+                                     TSdpAttributeID aAttrID,
+                                     CSdpAttrValue* aAttrValue );
+
+        /**
+        * AttributeRequestComplete()
+        * Process the arrtibute request completion
+        * @param aHandle the handle of the service record
+        * @param aError the error code
+        */
+        void AttributeRequestComplete( TSdpServRecordHandle aHandle,
+                                       TInt aError );
+
+    private:    // Functions from base classes
+
+        /**
+        * NextRecordRequestCompleteL()
+        * Process the result of the next record request
+        * @param aError the error code
+        * @param aHandle the handle of the service record
+        * @param aTotalRecordsCount the total number of
+        * matching service records
+        */
+        void NextRecordRequestCompleteL( TInt aError,
+                                         TSdpServRecordHandle aHandle,
+                                         TInt aTotalRecordsCount );
+
+        /**
+        * AttributeRequestResultL()
+        * Process the next attribute requested
+        * @param aHandle the handle of the service record
+        * @param aAttrID the id of the attribute
+        * @param aAttrValue the value of the attribute
+        */
+        void AttributeRequestResultL( TSdpServRecordHandle aHandle,
+                                      TSdpAttributeID aAttrID,
+                                      CSdpAttrValue* aAttrValue );
+
+        /**
+        * AttributeRequestCompleteL()
+        * Process the arrtibute request completion
+        * @param aHandle the handle of the service record
+        * @param aError the error code
+        */
+        void AttributeRequestCompleteL( TSdpServRecordHandle,
+                                        TInt aError );
+
+    private:    // data
+
+        /**
+        * iStatusObserver pointer to the request status observer
+        * Not owned by CBTServiceSearcher
+        */
+        TRequestStatus* iStatusObserver;
+
+        /**
+        * iIsDeviceSelectorConnected is the device
+        * selector connected?
+        */
+        TBool iIsDeviceSelectorConnected;
+
+        /**
+        * iDeviceSelector
+        * a handle to the bluetooth device selector notifier
+        */
+        RNotifier iDeviceSelector;
+
+        /**
+        * iResponse
+        * the response of the device selection.
+        */
+        TBTDeviceResponseParamsPckg iResponse;
+
+        /**
+        * iSelectionFilter
+        * Request a device selection
+        */
+        TBTDeviceSelectionParamsPckg iSelectionFilter;
+        /**
+        * iAgent a connetction to the SDP client
+        * Owned by CBTServiceSearcher
+        */
+        CSdpAgent* iAgent;
+
+        /**
+        * iSdpSearchPattern a search pattern
+        * Owned by CBTServiceSearcher
+        */
+        CSdpSearchPattern* iSdpSearchPattern;
+
+        /** iHasFoundService has the service been found ? */
+        TBool iHasFoundService;
+    };
+
+#endif // __BTSERVICESEARCHER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/btservicesearcher.pan	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Bluetooth service searcher panic codes.
+*
+*/
+
+
+#ifndef __BTSERVICE_SEARCHER_PAN__
+#define __BTSERVICE_SEARCHER_PAN__
+
+#include <e32std.h>
+
+/** BTServiceSearcher application panic codes */
+enum TBTServiceSearcherPanics
+    {
+    EBTServiceSearcherNextRecordRequestComplete = 1,
+    EBTServiceSearcherAttributeRequestResult,
+    EBTServiceSearcherAttributeRequestComplete,
+    EBTServiceSearcherInvalidControlIndex,
+    EBTServiceSearcherProtocolRead,
+    EBTServiceSearcherAttributeRequest,
+    EBTServiceSearcherSdpRecordDelete
+    };
+
+
+/** Panic Category */
+_LIT( KPanicServiceSearcher, "ServiceSearcher" );
+
+
+inline void Panic( TBTServiceSearcherPanics aReason )
+    {
+    User::Panic( KPanicServiceSearcher, aReason );
+    }
+
+#endif // __BTSERVICE_SEARCHER_PAN__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/messageprotocolconstants.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Constants for Bluetooth.
+*
+*/
+
+
+#ifndef __CMESSAGE_PROTOCOL_CONSTANTS__
+#define __CMESSAGE_PROTOCOL_CONSTANTS__
+
+// INCLUDES
+#include <bt_sock.h>
+
+const TInt KRfcommChannel = 1;
+const TInt KServiceClass = 0x1101;    //  SerialPort
+
+const TUid KUidBTPointToPointApp = { 0x10005B8B };
+
+_LIT( KStrRFCOMM,             "RFCOMM" );
+
+const TInt KListeningQueSize = 1;
+
+
+#endif //__CMESSAGE_PROTOCOL_CONSTANTS__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/messageservicesearcher.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,134 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Message service searcher.
+*
+*/
+
+
+#ifndef __MESSAGESERVICESEARCHER_H__
+#define __MESSAGESERVICESEARCHER_H__
+
+// INCLUDES
+#include <e32base.h>
+#include "btservicesearcher.h"
+
+// CLASS DECLARATIONS
+/**
+* CMessageServiceSearcher
+* Searches for a message service.
+*/
+class CMessageServiceSearcher : public CBTServiceSearcher
+    {
+    public:     // Constructors and destructor
+
+        /*
+        * NewL()
+        * Create a CMessageServiceSearcher object
+        * @return a pointer to the created instance of
+        * CMessageServiceSearcher
+        */
+        static CMessageServiceSearcher* NewL();
+
+        /**
+        * NewLC()
+        * Create a CMessageServiceSearcher object
+        * @return a pointer to the created instance of
+        * CMessageServiceSearcher
+        */
+        static CMessageServiceSearcher* NewLC();
+
+        /**
+        * ~CMessageServiceSearcher()
+        * Destroy the object and release all memory objects.
+        */
+        virtual ~CMessageServiceSearcher();
+
+    public: // New functions
+
+        /**
+        * Port()
+        * Retrieve the port on which the service is installed
+        * @param aIndex index number of the service whose port number to get
+        * @return the port number or KErrNotFound if aIndex negative or greater
+        * than returned by ServiceCount()
+        */
+        TInt Port( TInt aIndex = 0 );
+
+        /**
+        * AppendPort()
+        * Adds a new port number to the port number array. If the port number
+        * already exists in the array a duplicate is not added.
+        * @param aPort the port number to add
+        * */
+        void AppendPort( TInt aPort );
+
+        /**
+         * ServiceCount()
+         * Get the amount of requested services found from the remote machine
+         * @return the count of services (= ports)
+         */
+         TInt ServiceCount();
+
+    protected:  // New functions
+
+        /**
+        * ServiceClass()
+        * @return the service class uid.
+        */
+        const TUUID& ServiceClass() const;
+
+        /**
+        * ProtocolList()
+        * @return the attribute list.
+        */
+        const TSdpAttributeParser::TSdpAttributeList& ProtocolList() const;
+
+        /**
+        * FoundElementL()
+        * Read the data element
+        * @param aKey a key that identifies the element
+        * @param aValue the data element
+        */
+        virtual void FoundElementL( TInt aKey, CSdpAttrValue& aValue );
+
+    private:    // Constructors
+
+        /**
+        * CMessageServiceSearcher()
+        * Constructs this object
+        * @param aLog the log to send output to
+        */
+        CMessageServiceSearcher();
+
+        /**
+        * ConstructL()
+        * Performs second phase construction of this object
+        */
+        void ConstructL();
+
+    private:    // data
+
+        /** iServiceClass the service class UUID to search for */
+        TUUID iServiceClass;
+
+        /**
+        * iPortNumbers array of port numbers that has the remote
+        * service installed
+        */
+        RArray<TInt> iPortNumbers;
+    };
+
+#endif // __MESSAGESERVICESEARCHER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/sdpattributenotifier.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads SDP Attribute elements.
+*
+*/
+
+
+#ifndef __SDP_ATTRIBUTE_NOTIFIER_H__
+#define __SDP_ATTRIBUTE_NOTIFIER_H__
+
+// FORWARD DECLARATIONS
+class CSdpAttrValue;
+
+// CLASS DECLARATIONS
+/**
+* MSdpAttributeNotifier
+* An instance of MSdpAttributeNotifier is used to read selected SDP Attribute
+* elements from an attribute value.
+*/
+class MSdpAttributeNotifier
+    {
+    public: // New functions
+
+        /**
+        * FoundElementL
+        * Read the data element
+        * @param aKey a key that identifies the element
+        * @param aValue the data element
+        */
+        virtual void FoundElementL( TInt aKey, CSdpAttrValue& aValue ) = 0;
+    };
+
+#endif // __SDP_ATTRIBUTE_NOTIFIER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/sdpattributeparser.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,174 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads selected parts of SDP attribute values.
+*
+*/
+
+
+#ifndef __SDP_ATTRIBUTE_PARSER_H__
+#define __SDP_ATTRIBUTE_PARSER_H__
+
+// INCLUDES
+#include <btsdp.h>
+#include "staticarrayc.h"
+
+// FORWARD DECLARATIONS
+class MSdpAttributeNotifier;
+
+// CLASS DECLARATIONS
+/**
+* TSdpAttributeParser
+* An instance of TSdpAttributeParser is used to check an SDP
+* attribute value, and read selected parts
+*/
+class TSdpAttributeParser : public MSdpAttributeValueVisitor
+    {
+    public:     // Enumerations
+
+        /**
+        * TNodeCommand
+        * The command to be carried out at a node
+        * ECheckType. Check the type of the value
+        * ECheckValue. Check the type and the value
+        * ECheckEnd. Check that a list ends at this point
+        * ESkip. Do not check this value - can not match a list end
+        * EReadValue. Pass the value onto the observer
+        * EFinished. Marks the end of the node list
+        */
+        enum TNodeCommand
+            {
+                ECheckType,
+                ECheckValue,
+                ECheckEnd,
+                ESkip,
+                EReadValue,
+                EFinished
+            };
+
+        /**
+        * SSdpAttributeNode
+        * An instance of SSdpAttributeNode is used to determine how
+        * to parse an SDP attribute value data element
+        */
+        struct SSdpAttributeNode
+        {
+            /** iCommand the command for the node */
+            TNodeCommand iCommand;
+
+            /** iType the expected type */
+            TSdpElementType iType;
+
+            /** iValue the expected value for ECheckValue,the value of aKey
+            * passed to the observer for EReadValue
+            */
+            TInt iValue;
+        };
+
+        typedef const TStaticArrayC< SSdpAttributeNode > TSdpAttributeList;
+
+        /**
+        * TSdpAttributeParser
+        * Construct a TSdpAttributeParser
+        * @param aNodeList the list of expected nodes
+        * @param aObserver an observer to read specified node values
+        */
+        TSdpAttributeParser( TSdpAttributeList& aNodeList,
+                             MSdpAttributeNotifier& aObserver );
+
+        /**
+        * HasFinished
+        * Check if parsing processed the whole list
+        * @return true is the index refers to the EFinished node
+        */
+        TBool HasFinished() const;
+
+    public: // from MSdpAttributeValueVisitor
+
+        /**
+        * VisitAttributeValueL
+        * Process a data element
+        * @param aValue the data element
+        * @param aType the type of the data element
+        */
+        void VisitAttributeValueL( CSdpAttrValue& aValue,
+                                   TSdpElementType aType );
+
+        /**
+        * StartListL
+        * Process the start of a data element list
+        * @param aList the data element list
+        */
+        void StartListL( CSdpAttrValueList& aList );
+
+        /**
+        * EndListL
+        * Process the end of a data element list
+        */
+        void EndListL();
+
+    private:    // Functions from base classes
+
+        /**
+        * CheckTypeL
+        * Check the type of the current node is the same as
+        * the specified type.
+        * @param aElementType the type of the current data element
+        */
+        void CheckTypeL( TSdpElementType aElementType ) const;
+
+        /**
+        * CheckValueL
+        * Check the value of the current node is the same as the specified value
+        * @param aValue the value of the current data element.
+        */
+        void CheckValueL( CSdpAttrValue& aValue ) const;
+
+        /**
+        * ReadValueL
+        * Pass the data element value to the observer
+        * @param aValue the value of the current data element.
+        */
+        void ReadValueL( CSdpAttrValue& aValue ) const;
+
+        /**
+        * CurrentNode
+        * Get the current node
+        * @return the current node
+        */
+        const SSdpAttributeNode& CurrentNode() const;
+
+        /**
+        * AdvanceL
+        * Advance to the next node. Leaves with KErrEof
+        * if at the finished node.
+        */
+        void AdvanceL();
+
+    private:    // data
+
+        /** iObserver the observer to read values */
+        MSdpAttributeNotifier& iObserver;
+
+        /** iNodeList a list defining the expected
+        * structure of the value
+        */
+        TSdpAttributeList& iNodeList;
+
+        /** iCurrentNodeIndex the index of the current node in iNodeList */
+        TInt iCurrentNodeIndex;
+    };
+
+#endif // __SDP_ATTRIBUTE_PARSER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/sdpattributeparser.pan	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Bluetooth SDP attribute parser panic codes.
+*
+*/
+
+
+#ifndef __SDP_ATTRIBUTE_PARSER_PAN__
+#define __SDP_ATTRIBUTE_PARSER_PAN__
+
+/** Panic Category */
+_LIT( KPanicSAP, "SAP" );
+
+/** BTPointToPoint application panic codes */
+enum TSdpAttributeParserPanics
+    {
+    ESdpAttributeParserInvalidCommand = 1,
+    ESdpAttributeParserNoValue,
+    ESdpAttributeParserValueIsList,
+    ESdpAttributeParserValueTypeUnsupported
+    };
+
+inline void Panic( TSdpAttributeParserPanics aReason )
+    {
+    User::Panic( KPanicSAP, aReason );
+    }
+
+
+#endif // __SDP_ATTRIBUTE_PARSER_PAN__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/socketsreader.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,68 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads from socket.
+*
+*/
+
+
+#ifndef __SOCKETSREADER_H__
+#define __SOCKETSREADER_H__
+
+// INCLUDES
+#include <in_sock.h>
+
+// FORWARD DECLARATIONS
+class MSocketObserver;
+
+// CLASS DECLARATION
+
+const TInt KReadBufferMaxSize = 2 * 1024;
+
+class CSocketsReader : public CActive
+    {
+    public: // Constructors and destructors
+
+        static CSocketsReader* NewL( MSocketObserver& aObserver,
+                                     RSocket& aSocket );
+        virtual ~CSocketsReader();
+
+    public: // New functions
+
+        void ReadAsync(); // Use Cancel() to cancel
+
+    protected: // from CActive
+
+        void DoCancel();
+        void RunL();
+
+    private: // Constructors and destructors
+
+        CSocketsReader( MSocketObserver& aObserver, RSocket& aSocket );
+        void ConstructL();
+
+    private: // New functions
+
+        void IssueRead();
+
+    private: // Data
+
+        RSocket& iSocket;
+        MSocketObserver& iObserver;
+        TBuf8<KReadBufferMaxSize> iBuffer;
+        TSockXfrLength iLen;
+    };
+
+#endif // __SOCKETSREADER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/socketswriter.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,97 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Writes to socket.
+*
+*/
+
+
+#ifndef __SOCKETSWRITER_H__
+#define __SOCKETSWRITER_H__
+
+// INCLUDES
+#include <in_sock.h>
+#include "timeoutnotifier.h"
+
+// FORWARD DECLARATIONS
+class CTimeOutTimer;
+class MSocketObserver;
+
+const TInt KSocketWriteBufferSize = 1024;
+const TInt KTransferBufferSize = 8 * 1024;
+
+// CLASS DECLARATION
+class CSocketsWriter : public CActive, public MTimeOutNotifier
+    {
+    public:
+
+        static CSocketsWriter* NewL( MSocketObserver& aEngineNotifier,
+                                     RSocket& aSocket );
+        virtual ~CSocketsWriter();
+
+        /**
+         * Add data to iTransferBuffer and start sending if not already sending
+         * Leaves with KErrOverflow, if there is not enough free space.
+         * This can be called as long as there is space in buffer.
+         */
+        void SendL(const TDesC8& aData);
+
+        void CancelSending();
+
+        /**
+        * Return number of bytes that can be added to iTransferBuffer.
+        */
+        TInt FreeSpaceInSendBuffer();
+
+        TInt SendBufferMaxSize();
+
+    protected: // from CActive
+
+        void DoCancel();
+        void RunL();
+
+    protected: // from MTimeOutNotifier
+
+        void TimerExpired();
+
+    private: // Constructors and destructors
+
+        CSocketsWriter( MSocketObserver& aEngineNotifier, RSocket& aSocket );
+        void ConstructL();
+
+    private: // New functions
+
+        void SendNextPacket();
+
+    private: // Enumerations
+
+        enum TWriteState
+            {
+            ESending,
+            EIdle // nothing to be sent
+            };
+
+    private: // Data
+
+        RSocket& iSocket;
+        MSocketObserver& iObserver;
+        TBuf8<KTransferBufferSize> iTransferBuffer;
+        TBuf8<KSocketWriteBufferSize> iWriteBuffer;
+        CTimeOutTimer* iTimer;
+        TInt iTimeOut; // microseconds
+        TWriteState iWriteStatus;
+    };
+
+#endif // __SOCKETSWRITER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/staticarrayc.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Templated class for using static arrays.
+*
+*/
+
+
+#ifndef __STATIC_ARRAY_C_H__
+#define __STATIC_ARRAY_C_H__
+
+
+// CLASS DECLARATIONS
+
+/**
+* TStaticArrayC
+* This templated class provides a type, and size, safe method of
+* using static arrays.
+*/
+template <class T>
+class TStaticArrayC
+    {
+    public:     // enumerations
+
+        /**
+        * operator[]
+        * Return an element from the array.
+        * @param aIndex the index of the element to return
+        * @return a reference to the object
+        */
+        inline const T& operator[]( TInt aIndex ) const;
+
+        /**
+        * TPanicCode
+        * Panic code
+        * EIndexOutOfBounds index is out of bounds
+        */
+        enum TPanicCode
+            {
+                EIndexOutOfBounds = 1
+            };
+
+        /**
+        * Panic
+        * Generate a panic.
+        * @param aPanicCode the reason code for the panic
+        */
+        inline void Panic( TPanicCode aPanicCode ) const;
+
+    public:     // data
+
+        /** iArray the arrat of elements */
+        const T* iArray;
+
+        /** iCount the number of elements */
+        TInt iCount;
+
+    };
+
+// INCLUDES
+#include "staticarrayc.inl"
+
+/**
+* CONSTRUCT_STATIC_ARRAY_C
+* Initalise a global constant of type TStaticArrayC<>.
+* @param aValue the underlying const array of T
+*/
+#define CONSTRUCT_STATIC_ARRAY_C( aValue ) \
+        {   \
+        aValue,    \
+        sizeof( aValue ) / sizeof( *aValue )  \
+        }  \
+
+#endif //   __STATIC_ARRAY_C_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/staticarrayc.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Inline method implementations of TStaticArrayC.
+*
+*/
+
+
+// CONSTANTS
+_LIT( KStaticArrayPanic,"StaticArray" );
+
+template <class T>
+inline const T& TStaticArrayC<T>::operator[]( TInt aIndex ) const
+    {
+    if ( ( aIndex >= iCount ) || ( aIndex < 0 ) )
+        {
+        Panic( EIndexOutOfBounds );
+        }
+
+    return  iArray[aIndex];
+    }
+
+template <class T>
+inline void TStaticArrayC<T>::Panic( TPanicCode aPanicCode ) const
+    {
+    User::Panic( KStaticArrayPanic, aPanicCode );
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/timeoutnotifier.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface for timeout notification.
+*
+*/
+
+
+#ifndef __TIMEOUTNOTIFIER_H__
+#define __TIMEOUTNOTIFIER_H__
+
+// CLASS DECLARATION
+
+class MTimeOutNotifier
+    {
+    public: // New functions
+
+        /**
+        * The function to be called when a timeout occurs.
+        */
+        virtual void TimerExpired() = 0;
+    };
+
+#endif // __TIMEOUTNOTIFIER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/inc/timeouttimer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Timer.
+*
+*/
+
+
+#ifndef __TIMEOUTTIMER_H__
+#define __TIMEOUTTIMER_H__
+
+// INCLUDES
+#include <e32base.h>
+
+// FORWARD DECLARATIONS
+class MTimeOutNotifier;
+
+// CLASS DECLARATION
+class CTimeOutTimer : public CTimer
+    {
+    public: // Constructors and destructors
+
+        static CTimeOutTimer* NewL( const TInt aPriority,
+                                    MTimeOutNotifier& aObserver);
+        virtual ~CTimeOutTimer();
+
+    protected: // Functions from base classes
+
+        void RunL();
+
+    private: // Constructors and destructors
+
+        CTimeOutTimer( const TInt aPriority,
+                       MTimeOutNotifier& aTimeOutNotify );
+        void ConstructL();
+
+    private: // Data
+
+        MTimeOutNotifier& iObserver;
+    };
+
+#endif // __TIMEOUTTIMER_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/BtSerialClient.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,443 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Bluetooth serial client.
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <c32comm.h>
+#include "BtSerialClient.h"
+#include "messageservicesearcher.h"
+#include "BtSerialEngine.pan"
+#include "HtiBtEngineLogging.h"
+#include "socketswriter.h"
+#include "socketsreader.h"
+
+// CONSTANTS
+const TUint KServiceUid = 0x12341101;
+
+// ----------------------------------------------------------------------------
+EXPORT_C CBtSerialClient* CBtSerialClient::NewL( MBtSerialClientObserver& aObserver )
+    {
+    CBtSerialClient* self = new ( ELeave ) CBtSerialClient( aObserver );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ----------------------------------------------------------------------------
+CBtSerialClient::CBtSerialClient( MBtSerialClientObserver& aObserver )
+: CActive( CActive::EPriorityStandard ), iObserver( aObserver ),
+  iState( EWaitingToGetDevice ), iCurrentServiceIndex( 0 )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C CBtSerialClient::~CBtSerialClient()
+    {
+    delete iSocketReader;
+    delete iSocketWriter;
+
+    Cancel();
+
+    iSocket.Close();
+    iSocketServer.Close();
+
+    delete iServiceSearcher;
+
+    iPowerControl.Close();
+    }
+
+// ----------------------------------------------------------------------------
+void CBtSerialClient::ConstructL()
+    {
+    LOG_D( "CBtSerialClient::ConstructL()" );
+
+    TInt err = iPowerControl.Open();
+    if ( err != KErrNone )
+    	{
+    	LOGFMT_E( "Could not open BT power controller %d", err );
+    	User::Leave( err );
+    	}
+
+    // Check current BT power state and try to turn ON if necessary
+    TBTPowerState powerState = EBTOff;
+    err = iPowerControl.GetPower( ( TBTPowerState& ) powerState, NULL );
+    LOGFMT_D( "GetPower return code %d", err );
+    LOGFMT_D( "Current BT power state %d", powerState );
+    if ( powerState != EBTOn )
+    	{
+    	LOG_I( "Turning BT ON" );
+    	TRequestStatus status = KRequestPending;
+    	iPowerControl.SetPower( EBTOn, NULL, status );
+    	User::WaitForRequest( status );
+    	LOGFMT_D( "SetPower return code %d", status.Int() );
+    	if ( status != KErrNone && status != KErrAlreadyExists )
+    		{
+    		LOGFMT_E( "Could not turn BT on, err: %d", status.Int() );
+    		User::Leave( status.Int() );
+    		}
+        LOG_I( "Waiting a while for BT to turn on" );
+        User::After( 1 * 1000 * 1000 );
+    	}
+
+	err = StartC32();
+    LOGFMT_D( "StartC32 return code %d", err );
+
+    LOG_I( "Continuing BT connect" );
+
+    iServiceSearcher = CMessageServiceSearcher::NewL();
+    User::LeaveIfError( iSocketServer.Connect() );
+    iSocketReader = CSocketsReader::NewL( *this, iSocket );
+    iSocketWriter = CSocketsWriter::NewL( *this, iSocket );
+    }
+
+// ----------------------------------------------------------------------------
+void CBtSerialClient::DoCancel()
+    {
+    LOG_W("CBtSerialClient::DoCancel(): Doing nothing");
+    }
+
+// ----------------------------------------------------------------------------
+void CBtSerialClient::RunL()
+    {
+    if ( iStatus != KErrNone )
+        {
+        switch ( iState )
+            {
+            case EGettingDevice:
+                if ( iStatus == KErrCancel )
+                    {
+                    LOG_W( "CBtSerialClient: No device selected" );
+                    }
+                iState = EWaitingToGetDevice;
+                iObserver.ConnectedToServer( iStatus.Int() );
+                break;
+            case EGettingService:
+                LOGFMT_W( "CBtSerialClient: Failed to fetch remote service: %d", iStatus.Int() );
+                iObserver.ConnectedToServer( iStatus.Int() );
+                iState = EWaitingToGetDevice;
+                break;
+            case EGettingConnection:
+                LOGFMT_W( "CBtSerialClient: Failed to connect to remote service: %d", iStatus.Int() );
+                if ( iCurrentServiceIndex < iServiceSearcher->ServiceCount() )
+                    {
+                    // Try another service
+                    iCurrentServiceIndex++;
+                    ConnectToServerL(); // establish RFComm connection
+                    }
+                else
+                    {
+                    iState = EWaitingToGetDevice;
+                    iObserver.ConnectedToServer( iStatus.Int() );
+                    }
+                break;
+            case EConnected:
+                LOGFMT_I( "CBtSerialClient: Lost connection: %d", iStatus.Int() )
+                DisconnectFromServer();
+                iState = EDisconnecting;
+                break;
+            case EDisconnecting:
+                LOGFMT_I("CBtSerialClient: Disconnected from server: %d", iStatus.Int() );
+                iSocket.Close();
+                iState = EWaitingToGetDevice;
+                iObserver.DisconnectedFromServer();
+                break;
+            default:
+                Panic( EBTPointToPointInvalidLogicState );
+                break;
+            }
+        }
+    else // iStatus = KErrNone
+        {
+        switch ( iState )
+            {
+            case EGettingDevice:
+                // found a device now search for a suitable service
+                LOGFMT_I("CBtSerialClient: Found device: %S. Finding correct service.", &(iServiceSearcher->ResponseParams().DeviceName()) );
+                iState = EGettingService;
+                iStatus = KRequestPending;  // this means that the RunL can not
+                                            // be called until this program
+                                            // does something to iStatus
+                iBTServerDevice = iServiceSearcher->BTDevAddr();
+                iServiceSearcher->FindServiceL( iBTServerDevice, iStatus );
+                SetActive();
+                break;
+            case EGettingService:
+                LOGFMT_I("CBtSerialClient: Found %d remote services", iServiceSearcher->ServiceCount());
+                iState = EGettingConnection;
+                ConnectToServerL(); // establish RFComm connection
+                break;
+            case EGettingConnection:
+                LOG_I( "CBtSerialClient: Connected to remote service" );
+                iState = EConnected;
+                iObserver.ConnectedToServer( KErrNone );
+                break;
+            case EDisconnecting:
+                LOG_I( "CBtSerialClient: Disconnecting" );
+                iSocket.Close();
+                iState = EWaitingToGetDevice;
+                iObserver.DisconnectedFromServer();
+                break;
+            default:
+                LOGFMT_E( "CBtSerialClient: Invalid logic state in RunL: %d. Will panic", iState );
+                Panic( EBTPointToPointInvalidLogicState );
+                break;
+            };
+        }
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C void CBtSerialClient::ConnectL()
+    {
+    if ( iState == EWaitingToGetDevice && !IsActive() )
+        {
+        LOG_D( "CBtSerialClient: Connecting by user selection" );
+        iState = EGettingDevice;
+        iServiceSearcher->SelectDeviceByDiscoveryL( iStatus );
+        SetActive();
+        }
+    else
+        {
+        LOG_W( "CBtSerialClient: Already connecting or connected" );
+        User::Leave( KErrInUse );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C void CBtSerialClient::ConnectL( const TBTDevAddr aBTServerDevice,
+                                         const TInt aPort )
+    {
+    if ( iState == EWaitingToGetDevice && !IsActive() )
+        {
+        if ( aPort >= 0 )
+            {
+            // If there was a valid port given, add it as the first port to try
+            iServiceSearcher->AppendPort( aPort );
+            }
+        LOG_D( "CBtSerialClient: Connecting by address" );
+        iBTServerDevice = aBTServerDevice;
+        iServiceSearcher->FindServiceL( iBTServerDevice, iStatus );
+        iState = EGettingService;
+        iStatus = KRequestPending;  // this means that the RunL can not
+                                    // be called until this program
+                                    // does something to iStatus
+        SetActive();
+        }
+    else
+        {
+        LOG_W("CBtSerialClient: Already connecting or connected");
+        User::Leave( KErrInUse );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C void CBtSerialClient::ConnectL( const TDesC& aBTServerDeviceName,
+                                         const TInt aPort )
+    {
+    if ( iState == EWaitingToGetDevice && !IsActive() )
+        {
+        if ( aPort >= 0 )
+            {
+            // If there was a valid port given, add it as the first port to try
+            iServiceSearcher->AppendPort( aPort );
+            }
+        LOG_D( "CBtSerialClient: Connecting by name" );
+        iState = EGettingDevice;
+        iServiceSearcher->SelectDeviceByNameL( aBTServerDeviceName, iStatus );
+        SetActive();
+        }
+    else
+        {
+        LOG_W( "CBtSerialClient: Already connecting or connected" );
+        User::Leave( KErrInUse );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C TBTDevAddr CBtSerialClient::ServerAddressL()
+    {
+    if ( !Connected() )
+        {
+        LOG_E( "CBtSerialClient: ServerAddressL: Not connected" );
+        User::Leave( KErrNotReady );
+        }
+    return iBTServerDevice;
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C void CBtSerialClient::Disconnect()
+    {
+    if ( iState == EConnected )
+        {
+        DisconnectFromServer();
+        iState = EDisconnecting;
+        }
+    else
+        {
+        LOG_W( "CBtSerialClient: Disconnect: Not connected" );
+        User::Leave( KErrDisconnected );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+void CBtSerialClient::DisconnectFromServer()
+    {
+    // Terminate all operations
+    iSocket.CancelAll();
+    Cancel();
+    iSocketReader->Cancel();
+    iSocketWriter->CancelSending();
+
+    LOG_I( "CBtSerialClient: Disconnecting from server" );
+    iSocket.Shutdown( RSocket::ENormal, iStatus );
+    SetActive();
+    }
+
+// ----------------------------------------------------------------------------
+void CBtSerialClient::ConnectToServerL()
+    {
+    LOG_I("CBtSerialClient: ConnectToServerL")
+    User::LeaveIfError( iSocket.Open( iSocketServer, KStrRFCOMM ) );
+
+    TBTSockAddr address;
+    address.SetBTAddr( iServiceSearcher->BTDevAddr() );
+    address.SetPort( iServiceSearcher->Port( iCurrentServiceIndex ) );
+    TBTServiceSecurity btSec;
+    btSec.SetUid( TUid::Uid( KServiceUid ) );
+    btSec.SetAuthentication( EMitmNotRequired );
+    btSec.SetEncryption( EFalse );
+    btSec.SetAuthorisation( EFalse );
+    btSec.SetDenied( EFalse );
+    address.SetSecurity( btSec );
+
+    LOGFMT_I("CBtSerialClient: ConnectToServerL: Port = %d", address.Port() );
+    iSocket.Connect( address, iStatus );
+
+#ifdef __WINS__
+    User::After( 1 ); // Needed to allow emulator client to connect to server
+#endif
+
+    SetActive();
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C void CBtSerialClient::SendL(const TDesC8& aData)
+    {
+    if ( !Connected() )
+        {
+        LOG_E( "CBtSerialClient: SendL: Not connected" );
+        User::Leave( KErrNotReady );
+        }
+
+    LOGFMT_D("CBtSerialClient::SendL: Sending data (max first 32 bytes): \"%S\"", &(aData.Left(32)));
+    iSocketWriter->SendL( aData ); // Add to data queue and start sending
+    LOG_D("CBtSerialClient::SendL: Sent to socket");
+    }
+
+EXPORT_C void CBtSerialClient::ReadAsyncL()
+    {
+    if ( !Connected() )
+        {
+        LOG_E( "CBtSerialClient: ReadAsyncL: Not connected" );
+        User::Leave( KErrNotReady );
+        }
+    iSocketReader->ReadAsync();
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C TInt CBtSerialClient::FreeSpaceInSendBuffer()
+    {
+    return iSocketWriter->FreeSpaceInSendBuffer();
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C TInt CBtSerialClient::SendBufferMaxSize()
+    {
+    return iSocketWriter->SendBufferMaxSize();
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C TBool CBtSerialClient::Connected()
+    {
+    return (iState == EConnected);
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C TBool CBtSerialClient::Connecting()
+    {
+    return ( ( iState == EGettingDevice ) ||
+             ( iState == EGettingService ) ||
+             ( iState == EGettingConnection ) );
+    }
+
+// ----------------------------------------------------------------------------
+EXPORT_C TInt CBtSerialClient::ServicePort()
+    {
+    if ( !Connected() )
+        {
+        return KErrDisconnected;
+        }
+    return iServiceSearcher->Port( iCurrentServiceIndex );
+    }
+
+// ----------------------------------------------------------------------------
+void CBtSerialClient::ReportError( TErrorType aErrorType, TInt aErrorCode )
+    {
+    LOGFMT_W( "CBtSerialClient::ReportError: %d", aErrorCode );
+    // From socket reader or writer
+    switch ( aErrorType )
+        {
+        case EDisconnected:
+            {
+            LOG_I( "CBtSerialClient: disconnected" );
+            }
+            break;
+        case ETimeOutOnWrite:
+            {
+            LOG_I( "CBtSerialClient: timout writing data. Disconnecting from server" );
+            }
+            break;
+        case EGeneralReadError:
+            {
+            LOG_I( "CBtSerialClient: general read error. Disconnecting from server" );
+            }
+            break;
+        case EGeneralWriteError:
+            {
+            LOG_I( "CBtSerialClient: general write error. Disconnecting from server" );
+            }
+            break;
+        }
+    Disconnect();
+    aErrorCode = aErrorCode;
+    }
+
+// ----------------------------------------------------------------------------
+ void CBtSerialClient::NewData( const TDesC8& aData )
+    {
+    iObserver.DataFromServer( aData );
+    }
+
+// ----------------------------------------------------------------------------
+void CBtSerialClient::AllBufferedDataSent()
+    {
+    iObserver.AllBufferedDataSent();
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/btservicesearcher.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,382 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Bluetooth service searcher.
+*
+*/
+
+
+// INCLUDE FILES
+#include "btservicesearcher.h"
+#include "btservicesearcher.pan"
+
+#include "HtiBtEngineLogging.h"
+
+// ============================ MEMBER FUNCTIONS ==============================
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::CBTServiceSearcher()
+// Constructor.
+// ----------------------------------------------------------------------------
+//
+CBTServiceSearcher::CBTServiceSearcher()
+:  iIsDeviceSelectorConnected( EFalse )
+    {
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::~CBTServiceSearcher()
+// Destructor.
+// ----------------------------------------------------------------------------
+//
+CBTServiceSearcher::~CBTServiceSearcher()
+    {
+    if ( iIsDeviceSelectorConnected )
+        {
+        iDeviceSelector.CancelNotifier( KDeviceSelectionNotifierUid );
+        iDeviceSelector.Close();
+        }
+    delete iSdpSearchPattern;
+    iSdpSearchPattern = NULL;
+
+    delete iAgent;
+    iAgent = NULL;
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::SelectDeviceByDiscoveryL()
+// Select a device.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::SelectDeviceByDiscoveryL(
+        TRequestStatus& aObserverRequestStatus )
+    {
+    if ( ! iIsDeviceSelectorConnected )
+        {
+        User::LeaveIfError( iDeviceSelector.Connect() );
+        iIsDeviceSelectorConnected = ETrue;
+        }
+
+    iSelectionFilter().SetUUID( ServiceClass() );
+
+    iDeviceSelector.StartNotifierAndGetResponse(
+        aObserverRequestStatus,
+        KDeviceSelectionNotifierUid,
+        iSelectionFilter,
+        iResponse );
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::SelectDeviceByNameL()
+// Select a device by BT device name.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::SelectDeviceByNameL( const TDesC& aDeviceName,
+        TRequestStatus& aObserverRequestStatus )
+    {
+    LOG_D( "CBTServiceSearcher::SelectDeviceByNameL" );
+
+    RSocketServ socketServ;
+    User::LeaveIfError( socketServ.Connect() );
+    CleanupClosePushL( socketServ );
+
+    TProtocolDesc pInfo;
+    _LIT( KL2Cap, "BTLinkManager" );
+    User::LeaveIfError(
+        socketServ.FindProtocol( TProtocolName( KL2Cap ), pInfo ) );
+
+    LOG_D( "CBTServiceSearcher: Found protocol" );
+
+    RHostResolver hr;
+    User::LeaveIfError( hr.Open( socketServ,
+                            pInfo.iAddrFamily, pInfo.iProtocol ) );
+    CleanupClosePushL( hr );
+
+    LOG_D( "CBTServiceSearcher: HostResolver open" );
+
+    TInquirySockAddr addr;
+    TNameEntry entry;
+    addr.SetIAC( KGIAC );
+    addr.SetAction( KHostResName | KHostResInquiry );
+
+    User::LeaveIfError( hr.GetByAddress( addr, entry ) );
+    LOG_D( "CBTServiceSearcher: GetByAddress ok" );
+    TBool isFound = EFalse;
+    TInt err = KErrNone;
+    while ( !isFound && !err )
+        {
+        if ( !aDeviceName.CompareF( entry().iName ) )
+            {
+            LOG_D( "CBTServiceSearcher: Name match" );
+            isFound = ETrue;
+            }
+        else
+            {
+            LOG_D( "CBTServiceSearcher: Not match - getting next" );
+            err = hr.Next( entry );
+            }
+        }
+    CleanupStack::PopAndDestroy( 2 ); // hr, socketServ
+
+    iStatusObserver = &aObserverRequestStatus;
+
+    if ( isFound )
+        {
+        TInquirySockAddr& sa = TInquirySockAddr::Cast( entry().iAddr );
+        iResponse().SetDeviceAddress( sa.BTAddr() );
+        iResponse().SetDeviceName( entry().iName );
+        TBTDeviceClass deviceClass( sa.MajorServiceClass(),
+                                    sa.MajorClassOfDevice(),
+                                    sa.MinorClassOfDevice() );
+        iResponse().SetDeviceClass( deviceClass );
+        User::RequestComplete( iStatusObserver, KErrNone );
+        }
+
+    else
+        {
+        LOG_E( "CBTServiceSearcher: Device not found! Can't connect!" );
+        User::RequestComplete( iStatusObserver, err );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::FindServiceL()
+// Find a service on the specified device.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::FindServiceL( const TBTDevAddr& aDeviceAddress,
+    TRequestStatus& aObserverRequestStatus )
+    {
+    iResponse().SetDeviceAddress( aDeviceAddress );
+    if ( !iResponse().IsValidBDAddr() )
+        {
+        User::Leave( KErrArgument );
+        }
+    iHasFoundService = EFalse;
+
+    // delete any existing agent and search pattern
+    delete iSdpSearchPattern;
+    iSdpSearchPattern = NULL;
+
+    delete iAgent;
+    iAgent = NULL;
+
+    iAgent = CSdpAgent::NewL(*this, BTDevAddr());
+
+    iSdpSearchPattern = CSdpSearchPattern::NewL();
+
+    iSdpSearchPattern->AddL( ServiceClass() );
+    // return code is the position in the list that the UUID is inserted at
+    // and is intentionally ignored
+
+    iAgent->SetRecordFilterL( *iSdpSearchPattern );
+
+    iStatusObserver = &aObserverRequestStatus;
+
+    iAgent->NextRecordRequestL();
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::NextRecordRequestComplete()
+// Process the result of the next record request.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::NextRecordRequestComplete(
+    TInt aError,
+    TSdpServRecordHandle aHandle,
+    TInt aTotalRecordsCount)
+    {
+    TRAPD( error,
+           NextRecordRequestCompleteL( aError, aHandle, aTotalRecordsCount );
+    );
+
+    if ( error != KErrNone )
+        {
+        Panic( EBTServiceSearcherNextRecordRequestComplete );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::NextRecordRequestCompleteL()
+// Process the result of the next record request.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::NextRecordRequestCompleteL(
+    TInt aError,
+    TSdpServRecordHandle aHandle,
+    TInt aTotalRecordsCount )
+    {
+    if ( aError == KErrEof )
+        {
+        Finished();
+        return;
+        }
+
+    if ( aError != KErrNone )
+        {
+        LOGFMT_E("CBTServiceSearcher: NextRecordRequestCompleteL: %d", aError );
+        Finished( aError );
+        return;
+        }
+
+    if ( aTotalRecordsCount == 0 )
+        {
+        LOG_I("CBTServiceSearcher: NextRecordRequestCompleteL: No records found");
+        Finished( KErrNotFound );
+        return;
+        }
+
+    //  Request its attributes
+    iAgent->AttributeRequestL( aHandle, KSdpAttrIdProtocolDescriptorList );
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::AttributeRequestResult()
+// Process the next attribute requested.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::AttributeRequestResult(
+    TSdpServRecordHandle aHandle,
+    TSdpAttributeID aAttrID,
+    CSdpAttrValue* aAttrValue )
+    {
+    TRAPD( error,
+         AttributeRequestResultL( aHandle, aAttrID, aAttrValue );
+         );
+    if ( error != KErrNone )
+        {
+        Panic( EBTServiceSearcherAttributeRequestResult );
+        }
+
+    // Delete obsolete local atribute pointer.
+    delete aAttrValue;
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::AttributeRequestResultL()
+// Process the next attribute requested.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::AttributeRequestResultL(
+    TSdpServRecordHandle /*aHandle*/,
+    TSdpAttributeID aAttrID,
+    CSdpAttrValue* aAttrValue )
+    {
+    __ASSERT_ALWAYS( aAttrID == KSdpAttrIdProtocolDescriptorList,
+                     User::Leave( KErrNotFound ) );
+
+    TSdpAttributeParser parser( ProtocolList(), *this );
+
+    // Validate the attribute value, and extract the RFCOMM channel
+    aAttrValue->AcceptVisitorL( parser );
+
+    if ( parser.HasFinished() )
+        {
+        // Found a suitable record so change state
+        iHasFoundService = ETrue;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CBTServiceSearcher::AttributeRequestComplete()
+// Process the attribute request completion.
+// -----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::AttributeRequestComplete( TSdpServRecordHandle aHandle,
+                                                   TInt aError )
+    {
+    TRAPD( error,
+        AttributeRequestCompleteL( aHandle, aError );
+    );
+    if ( error != KErrNone )
+        {
+        Panic( EBTServiceSearcherAttributeRequestComplete );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::AttributeRequestCompleteL()
+// Process the attribute request completion.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::AttributeRequestCompleteL( TSdpServRecordHandle
+                                                    /*aHandle*/,
+                                                    TInt aError )
+    {
+    if ( aError != KErrNone )
+        {
+        LOGFMT_W("CBTServiceSearcher::AttributeRequestCompleteL: %d", aError);
+        }
+    else
+        {
+        // done with attributes of this service record, request next
+        iAgent->NextRecordRequestL();
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::Finished()
+// The search has finished and notify the observer
+// that the process is complete.
+// ----------------------------------------------------------------------------
+//
+void CBTServiceSearcher::Finished( TInt aError /* default = KErrNone */ )
+    {
+    if ( aError == KErrNone && !HasFoundService() )
+        {
+        aError = KErrNotFound;
+        }
+    User::RequestComplete( iStatusObserver, aError );
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::HasFinishedSearching()
+// Is the instance still wanting to search.
+// ----------------------------------------------------------------------------
+//
+TBool CBTServiceSearcher::HasFinishedSearching() const
+    {
+    return EFalse;
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::BTDevAddr()
+// Returns the bluetooth device address.
+// ----------------------------------------------------------------------------
+//
+const TBTDevAddr& CBTServiceSearcher::BTDevAddr()
+    {
+    return iResponse().BDAddr();
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::ResponseParams()
+// Returns information about the device selected by the user.
+// ----------------------------------------------------------------------------
+//
+const TBTDeviceResponseParams& CBTServiceSearcher::ResponseParams()
+    {
+    return iResponse();
+    }
+
+// ----------------------------------------------------------------------------
+// CBTServiceSearcher::HasFoundService()
+// True if a service has been found.
+// ----------------------------------------------------------------------------
+//
+TBool CBTServiceSearcher::HasFoundService() const
+    {
+    return iHasFoundService;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/messageservicesearcher.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,183 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Message service searcher.
+*
+*/
+
+
+// INCLUDE FILES
+#include <bt_sock.h>
+
+#include "messageservicesearcher.h"
+#include "btservicesearcher.pan"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TSdpAttributeParser::SSdpAttributeNode[]
+// Construct a TSdpAttributeParser.
+// -----------------------------------------------------------------------------
+//
+static const TSdpAttributeParser::SSdpAttributeNode gSerialPortProtocolArray[] =
+    {
+        { TSdpAttributeParser::ECheckType, ETypeDES },
+        { TSdpAttributeParser::ECheckType, ETypeDES },
+        { TSdpAttributeParser::ECheckValue, ETypeUUID, KL2CAP },
+        { TSdpAttributeParser::ECheckEnd },
+        { TSdpAttributeParser::ECheckType, ETypeDES },
+        { TSdpAttributeParser::ECheckValue, ETypeUUID, KRFCOMM }, // KRFCOMM defined in bt_sock.h
+        { TSdpAttributeParser::EReadValue, ETypeUint, KRfcommChannel }, // KRfcommChannel is custom key value used in FoundElementL. If there were more than one value to be read, the key value would be usefull
+        { TSdpAttributeParser::ECheckEnd },
+        { TSdpAttributeParser::ECheckEnd },
+        { TSdpAttributeParser::EFinished }
+    };
+
+// ----------------------------------------------------------------------------
+// TStaticArrayC
+// Provides a type and size, safe method of using static arrays.
+// ----------------------------------------------------------------------------
+//
+static const TStaticArrayC<TSdpAttributeParser
+::SSdpAttributeNode> gSerialPortProtocolList = CONSTRUCT_STATIC_ARRAY_C(
+                                               gSerialPortProtocolArray );
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::NewL()
+// Two-phased constructor.
+// ----------------------------------------------------------------------------
+//
+CMessageServiceSearcher* CMessageServiceSearcher::NewL()
+    {
+    CMessageServiceSearcher* self = CMessageServiceSearcher::NewLC();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::NewLC()
+// Two-phased constructor.
+// ----------------------------------------------------------------------------
+//
+CMessageServiceSearcher* CMessageServiceSearcher::NewLC()
+    {
+    CMessageServiceSearcher* self = new (ELeave) CMessageServiceSearcher();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::CMessageServiceSearcher()
+// Construcor.
+// ----------------------------------------------------------------------------
+//
+CMessageServiceSearcher::CMessageServiceSearcher()
+: CBTServiceSearcher(),
+  iServiceClass( KServiceClass )
+    {
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::~CMessageServiceSearcher()
+// Destructor.
+// ----------------------------------------------------------------------------
+//
+CMessageServiceSearcher::~CMessageServiceSearcher()
+    {
+    iPortNumbers.Close();
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::ConstructL()
+// Symbian 2nd phase constructor can leave.
+// ----------------------------------------------------------------------------
+//
+void CMessageServiceSearcher::ConstructL()
+    {
+    // no implementation required
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::ServiceClass()
+// The service class to search.
+// ----------------------------------------------------------------------------
+//
+const TUUID& CMessageServiceSearcher::ServiceClass() const
+    {
+    return iServiceClass;
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::ProtocolList()
+// The list of Protocols required by the service.
+// ----------------------------------------------------------------------------
+//
+const TSdpAttributeParser::TSdpAttributeList& CMessageServiceSearcher
+::ProtocolList() const
+    {
+    return gSerialPortProtocolList;
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::FoundElementL()
+// Read the data element.
+// ----------------------------------------------------------------------------
+//
+void CMessageServiceSearcher::FoundElementL( TInt aKey, CSdpAttrValue& aValue )
+    {
+    __ASSERT_ALWAYS( aKey == static_cast<TInt>( KRfcommChannel ),
+        Panic( EBTServiceSearcherProtocolRead ) );
+    AppendPort( aValue.Uint() );
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::Port()
+// Port connection on the remote machine.
+// ----------------------------------------------------------------------------
+//
+TInt CMessageServiceSearcher::Port( TInt aIndex )
+    {
+    if ( aIndex < 0 || aIndex >= iPortNumbers.Count() )
+        {
+        return KErrNotFound;
+        }
+    return iPortNumbers[aIndex];
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::AppendPort()
+// Adds a new port number to the port number array. If the port number
+// already exists in the array a duplicate is not added.
+// ----------------------------------------------------------------------------
+//
+void CMessageServiceSearcher::AppendPort( TInt aPort )
+    {
+    if ( iPortNumbers.Find( aPort ) == KErrNotFound )
+        {
+        iPortNumbers.Append( aPort );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// CMessageServiceSearcher::ServiceCount()
+// The amount of requested services found from the remote machine.
+// ----------------------------------------------------------------------------
+//
+TInt CMessageServiceSearcher::ServiceCount()
+    {
+    return iPortNumbers.Count();
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/sdpattributeparser.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,231 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads selected parts of SDP attribute values.
+*
+*/
+
+
+// INCLUDE FILES
+#include <bt_sock.h>
+
+#include "sdpattributeparser.h"
+#include "sdpattributeparser.pan"
+#include "sdpattributenotifier.h"
+
+// ============================ MEMBER FUNCTIONS ==============================
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::TSdpAttributeParser()
+// Construct a TSdpAttributeParser.
+// ----------------------------------------------------------------------------
+//
+
+TSdpAttributeParser::TSdpAttributeParser(
+    TSdpAttributeList& aNodeList,
+    MSdpAttributeNotifier& aObserver
+)
+:   iObserver( aObserver ),
+    iNodeList( aNodeList ),
+    iCurrentNodeIndex( 0 )
+    {
+    // no implementation required
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::HasFinished()
+// Check if parsing processed the whole list.
+// ----------------------------------------------------------------------------
+//
+TBool TSdpAttributeParser::HasFinished() const
+    {
+    return CurrentNode().iCommand == EFinished;
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::VisitAttributeValueL()
+// Process a data element.
+// ----------------------------------------------------------------------------
+//
+void TSdpAttributeParser::VisitAttributeValueL( CSdpAttrValue& aValue,
+                                                TSdpElementType aType )
+    {
+    switch ( CurrentNode().iCommand )
+        {
+        case ECheckType:
+            CheckTypeL( aType );
+            break;
+
+        case ECheckValue:
+            CheckTypeL( aType );
+            CheckValueL( aValue );
+            break;
+
+        case ECheckEnd:
+            User::Leave( KErrGeneral ); //list element contains too many items
+            break;
+
+        case ESkip:
+            break;  // no checking required
+
+        case EReadValue:
+            CheckTypeL( aType );
+            ReadValueL( aValue );
+            break;
+
+        case EFinished:
+            User::Leave( KErrGeneral ); // element is after
+            return;                     // value should have ended
+
+        default:
+            Panic( ESdpAttributeParserInvalidCommand );
+        }
+
+    AdvanceL();
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::StartListL()
+// Process the start of a data element list.
+// ----------------------------------------------------------------------------
+//
+void TSdpAttributeParser::StartListL( CSdpAttrValueList& /*aList*/ )
+    {
+    // no checks done here
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::EndListL()
+// Process the end of a data element list.
+// ----------------------------------------------------------------------------
+//
+void TSdpAttributeParser::EndListL()
+    {
+    // check we are at the end of a list
+    if ( CurrentNode().iCommand != ECheckEnd )
+        {
+        User::Leave( KErrGeneral );
+        }
+
+    AdvanceL();
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::CheckTypeL()
+// Check the type of the current node is the same as the specified type.
+// ----------------------------------------------------------------------------
+//
+void TSdpAttributeParser::CheckTypeL( TSdpElementType aElementType ) const
+    {
+    if ( CurrentNode().iType != aElementType )
+        {
+        User::Leave( KErrGeneral );
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::CheckValueL()
+// Check the value of the current node is the same as the specified type.
+// ----------------------------------------------------------------------------
+//
+void TSdpAttributeParser::CheckValueL( CSdpAttrValue& aValue ) const
+    {
+    switch ( aValue.Type() )
+        {
+        case ETypeNil:
+            Panic( ESdpAttributeParserNoValue );
+            break;
+
+        case ETypeUint:
+            if ( aValue.Uint() != ( TUint )CurrentNode().iValue )
+                {
+                User::Leave( KErrArgument );
+                }
+            break;
+
+        case ETypeInt:
+            if ( aValue.Int() != CurrentNode().iValue )
+                {
+                User::Leave( KErrArgument );
+                }
+            break;
+
+        case ETypeBoolean:
+            if ( aValue.Bool() != CurrentNode().iValue )
+                {
+                User::Leave( KErrArgument );
+                }
+            break;
+
+        case ETypeUUID:
+            if ( aValue.UUID() != TUUID( CurrentNode().iValue ) )
+                {
+                User::Leave( KErrArgument );
+                }
+            break;
+
+        // these are lists, so have to check contents
+        case ETypeDES:
+        case ETypeDEA:
+            Panic( ESdpAttributeParserValueIsList );
+            break;
+
+        // these aren't supported - use EReadValue and leave on error
+        //case ETypeString:
+        //case ETypeURL:
+        //case ETypeEncoded:
+        default:
+            Panic( ESdpAttributeParserValueTypeUnsupported );
+            break;
+        }
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::ReadValueL()
+// Pass the data element value to the observer.
+// ----------------------------------------------------------------------------
+//
+void TSdpAttributeParser::ReadValueL( CSdpAttrValue& aValue ) const
+    {
+    iObserver.FoundElementL( CurrentNode().iValue, aValue );
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::CurrentNode()
+// Get the current node.
+// ----------------------------------------------------------------------------
+//
+const TSdpAttributeParser::SSdpAttributeNode& TSdpAttributeParser
+::CurrentNode() const
+    {
+    return  iNodeList[iCurrentNodeIndex];
+    }
+
+// ----------------------------------------------------------------------------
+// TSdpAttributeParser::AdvanceL()
+// Advance to the next node.
+// ----------------------------------------------------------------------------
+//
+void TSdpAttributeParser::AdvanceL()
+    {
+    // check not at end
+    if ( CurrentNode().iCommand == EFinished )
+        {
+        User::Leave( KErrEof );
+        }
+
+    // move to the next item
+    ++iCurrentNodeIndex;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/socketsreader.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,104 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Reads from socket.
+*
+*/
+
+
+// INCLUDE FILES
+#include "BtSerialEngine.pan"
+#include "socketsreader.h"
+#include "SocketObserver.h"
+
+// -----------------------------------------------------------------------------
+CSocketsReader* CSocketsReader::NewL( MSocketObserver& aEngineNotifier,
+                                      RSocket& aSocket )
+    {
+    CSocketsReader* self = new ( ELeave ) CSocketsReader( aEngineNotifier,
+                                                          aSocket );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+CSocketsReader::CSocketsReader( MSocketObserver& aObserver,
+                                RSocket& aSocket )
+: CActive( EPriorityStandard ),
+  iSocket( aSocket ),
+  iObserver( aObserver )
+    {
+    // No implementation required
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsReader::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+CSocketsReader::~CSocketsReader()
+    {
+    Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsReader::DoCancel()
+    {
+    // Cancel asychronous read request
+    iSocket.CancelRead();
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsReader::RunL()
+    {
+    switch ( iStatus.Int() )
+        {
+        case KErrNone:
+            iObserver.NewData(iBuffer);
+//            IssueRead(); // Immediately start another read
+            break;
+        case KErrDisconnected:
+            iObserver.ReportError( MSocketObserver::EDisconnected,
+                                   iStatus.Int() );
+            break;
+        default:
+            iObserver.ReportError( MSocketObserver::EGeneralReadError,
+                                   iStatus.Int() );
+            break;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsReader::IssueRead()
+    {
+    // Initiate a new read from socket into iBuffer
+    __ASSERT_ALWAYS( !IsActive(), Panic(EBTSerialEngineReadSocketBadState) );
+    iSocket.RecvOneOrMore( iBuffer, 0, iStatus, iLen );
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsReader::ReadAsync()
+    {
+    // Initiate a new read from socket into iBuffer
+    if (!IsActive())
+        {
+        IssueRead();
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/socketswriter.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,171 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Writes to socket.
+*
+*/
+
+
+// INCLUDE FILES
+#include "socketswriter.h"
+#include "timeouttimer.h"
+#include "BtSerialEngine.pan"
+#include "SocketObserver.h"
+#include "HtiBtEngineLogging.h"
+
+// STATIC MEMBER INITIALISATIONS
+const TInt KTimeOut = 10 * 1000 * 1000; // 10 seconds time-out
+
+// ========================= MEMBER FUNCTIONS ==================================
+
+// -----------------------------------------------------------------------------
+CSocketsWriter* CSocketsWriter::NewL( MSocketObserver& aEngineNotifier,
+                                      RSocket& aSocket )
+    {
+    CSocketsWriter* self = new ( ELeave ) CSocketsWriter( aEngineNotifier,
+                                                          aSocket );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+CSocketsWriter::CSocketsWriter( MSocketObserver& aEngineNotifier,
+                                RSocket& aSocket )
+: CActive( EPriorityStandard ),
+  iSocket( aSocket ),
+  iObserver( aEngineNotifier )
+    {
+    // No implementation required
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsWriter::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    iTimeOut = KTimeOut;
+    iTimer = CTimeOutTimer::NewL( CActive::EPriorityUserInput, *this );
+    iWriteStatus = EIdle;
+    }
+
+// -----------------------------------------------------------------------------
+CSocketsWriter::~CSocketsWriter()
+    {
+    CancelSending();
+    delete iTimer;
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsWriter::DoCancel()
+    {
+    // Cancel asychronous write request
+    iSocket.CancelWrite();
+    iTimer->Cancel();
+    iWriteStatus = EIdle;
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsWriter::RunL()
+    {
+    iTimer->Cancel();
+
+    // Active object request complete handler
+    if ( iStatus == KErrNone )
+        {
+        switch ( iWriteStatus )
+            {
+            // Character has been written to socket
+            case ESending:
+                SendNextPacket();
+                break;
+            default:
+                LOGFMT_E( "CSocketsWriter: Bad write status: %d", iWriteStatus )
+                Panic( EBTSerialEngineWriteSocketBadState );
+                break;
+            };
+        }
+    else
+        {
+        iWriteStatus = EIdle;
+        iWriteBuffer.Zero();
+        iTransferBuffer.Zero();
+        iObserver.ReportError( MSocketObserver::EGeneralWriteError,
+                                     iStatus.Int() );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsWriter::TimerExpired()
+    {
+    Cancel();
+    iWriteStatus = EIdle;
+    iObserver.ReportError( MSocketObserver::ETimeOutOnWrite,
+                                 KErrTimedOut );
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsWriter::SendL(const TDesC8& aData)
+    {
+    if ( aData.Length() > FreeSpaceInSendBuffer() )
+        User::Leave( KErrOverflow );
+
+    iTransferBuffer.Append( aData );
+    SendNextPacket();
+    }
+
+// -----------------------------------------------------------------------------
+TInt CSocketsWriter::FreeSpaceInSendBuffer()
+    {
+    return iTransferBuffer.MaxSize() - iTransferBuffer.Size();
+    }
+
+// -----------------------------------------------------------------------------
+TInt CSocketsWriter::SendBufferMaxSize()
+    {
+    return iTransferBuffer.MaxLength();
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsWriter::SendNextPacket()
+    {
+    if ( IsActive() )
+        {
+        return; // already sending
+        }
+    if ( iTransferBuffer.Length() > 0 )
+        {
+        // Move data from transfer buffer to actual write buffer
+        iWriteBuffer.Copy(iTransferBuffer.Left(iWriteBuffer.MaxLength()));
+        iTransferBuffer.Delete(0, iWriteBuffer.MaxLength());
+        iSocket.Write( iWriteBuffer, iStatus ); // Initiate actual write
+
+        iWriteStatus = ESending;
+        iTimer->After( iTimeOut );
+        SetActive();
+        }
+    else
+        {
+        iWriteStatus = EIdle;
+        iObserver.AllBufferedDataSent();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+void CSocketsWriter::CancelSending()
+    {
+    Cancel();
+    iWriteBuffer.Zero();
+    iTransferBuffer.Zero();
+    }
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/BtEngine/src/timeouttimer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,71 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Timer.
+*
+*/
+
+
+// INCLUDE FILES
+#include "timeouttimer.h"
+#include "timeoutnotifier.h"
+#include "HtiBtEngineLogging.h"
+
+// -----------------------------------------------------------------------------
+CTimeOutTimer* CTimeOutTimer::NewL( const TInt aPriority,
+                                    MTimeOutNotifier& aTimeOutNotify )
+    {
+    CTimeOutTimer* self = new ( ELeave ) CTimeOutTimer( aPriority,
+                                                        aTimeOutNotify );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+CTimeOutTimer::CTimeOutTimer( const TInt aPriority,
+                              MTimeOutNotifier& aObserver )
+: CTimer( aPriority ), iObserver( aObserver )
+    {
+    // No implementation required
+    }
+
+// -----------------------------------------------------------------------------
+void CTimeOutTimer::ConstructL()
+    {
+    CTimer::ConstructL();
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+CTimeOutTimer::~CTimeOutTimer()
+    {
+    // No implementation required
+    }
+
+// -----------------------------------------------------------------------------
+void CTimeOutTimer::RunL()
+    {
+    // Timer request has completed, so notify the timer's owner
+    if ( iStatus == KErrNone )
+        {
+        iObserver.TimerExpired();
+        }
+    else
+        {
+        LOGFMT_E("CTimeOutTimer: bad completion code: %d", iStatus.Int())
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommEcomPlugin/data/200212CB.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for HtiBtComm ECOM plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+
+//  RESOURCE DEFINITIONS
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x200212CB;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB8;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x200212CC;
+                    version_no         = 1;
+                    display_name       = "Bt serial comm";
+                    default_data       = "BTSERIAL";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommEcomPlugin/inc/HtiBtCommEcomPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin to communicate over BT serial port
+*
+*/
+
+
+#ifndef CHTIBTCOMMECOMPLUGIN_H
+#define CHTIBTCOMMECOMPLUGIN_H
+
+class CBtSerialClient;
+
+// INCLUDES
+#include <c32comm.h>
+#include <HtiCommPluginInterface.h> // defined in HtiFramework project
+
+#include "HtiBtCommInterface.h" // RHtiBtCommInterface
+
+// FORWARD DECLARATIONS
+class CHtiCfg;
+
+// CLASS DECLARATION
+/**
+* ECOM plugin module for communicating with PC using serial port.
+*
+*/
+class CHtiBtCommEcomPlugin :
+    public CHTICommPluginInterface
+    {
+public:
+
+    /**
+    * Create instance of plugin.
+    * @return Connected plugin instance.
+    */
+    static CHtiBtCommEcomPlugin* NewL();
+
+    /**
+    * Destructor
+    */
+    ~CHtiBtCommEcomPlugin();
+
+public: // CHTICommPluginInterface interface implementation
+
+    /**
+    * Receive data from Bluetooth.
+    * The size of supplied buffer must equal to size given by GetBufferSize.
+    * The number of received bytes may be anything between 1 and GetBufferSize.
+    *
+    * @param aRawdataBuf Buffer where the result is written
+    * @param aStatus Request status
+    */
+    void Receive( TDes8& aRawdataBuf, TRequestStatus& aStatus );
+
+    /**
+    * Send data to Bluetooth. The size of data must not exceed GetBufferSize.
+    * @param aRawdataBuf Buffer where the data is read from.
+    * @param aStatus Request status
+    */
+    void Send( const TDesC8& aRawdataBuf, TRequestStatus& aStatus );
+
+    /**
+    * Cancel read operation
+    */
+    void CancelReceive();
+
+    /**
+    * Cancel send operation
+    */
+    void CancelSend();
+
+    /**
+     *  Return required buffer size for Send operation.
+     */
+    TInt GetSendBufferSize();
+
+    /**
+     *  Return required buffer size for Receive operation.
+     */
+    TInt GetReceiveBufferSize();
+
+private:
+
+    /**
+    * Constructor of this plugin.
+    */
+    CHtiBtCommEcomPlugin();
+
+    /**
+    * Second phase construction. Connects the Bluetooth.
+    */
+    void ConstructL();
+
+    /**
+    * Load configuration file.
+    */
+    void LoadConfigL();
+
+    /**
+    * Read and parse the configuration values.
+    */
+    void ReadConfig();
+
+    /**
+     * Parse the possible port (channel) number value from name or address param
+     */
+     TInt ParsePortNumber();
+
+     /**
+     * StorePortNumberL()
+     * Store the given port number to configuration file
+     * @param aPortNumber the port number to store
+     */
+     void StorePortNumberL( TInt aPortNumber );
+
+private: // Data
+
+    RHtiBtCommInterface iBtCommInterface;
+
+    CHtiCfg* iCfg;
+    HBufC8*  iBtDeviceNameOrAddress;
+    TInt     iPort;
+
+    };
+
+#endif // CHTIBTCOMMECOMPLUGIN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommEcomPlugin/src/HtiBtCommEcomPlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,277 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin for communication over serial port
+*
+*/
+
+
+// INCLUDE FILES
+#include <badesca.h>
+#include <f32file.h>
+
+#include "HtiBtCommEcomPlugin.h"
+#include "BtSerialClient.h"
+#include <HtiCfg.h>
+#include <HtiLogging.h>
+
+// CONSTANTS
+_LIT( KHtiCfgPath,       "\\" ); // root of drive
+_LIT( KHtiBtCommCfg,     "HTIBtComm.cfg" );
+_LIT8( KBtDeviceAddress, "BtDeviceAddress" );
+_LIT8( KBtDeviceName,    "BtDeviceName" );
+
+
+const TInt KBtAddressHexStringLength = 12; // 6 bytes
+const TUint KPortSeparatorChar = 30; // ASCII control char "record separator"
+
+// ----------------------------------------------------------------------------
+CHtiBtCommEcomPlugin* CHtiBtCommEcomPlugin::NewL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiBtCommEcomPlugin::NewL" );
+    CHtiBtCommEcomPlugin* plugin = new (ELeave) CHtiBtCommEcomPlugin();
+    CleanupStack::PushL( plugin );
+    plugin->ConstructL();
+    CleanupStack::Pop( plugin );
+    HTI_LOG_FUNC_OUT( "CHtiBtCommEcomPlugin::NewL" );
+    return plugin;
+    }
+
+// ----------------------------------------------------------------------------
+CHtiBtCommEcomPlugin::~CHtiBtCommEcomPlugin()
+    {
+    HTI_LOG_FUNC_IN( "CHtiBtCommEcomPlugin::~CHtiBtCommEcomPlugin" );
+    iBtCommInterface.CancelReceive();
+    iBtCommInterface.CancelSend();
+    iBtCommInterface.Close();
+    delete iBtDeviceNameOrAddress;
+    delete iCfg;
+    HTI_LOG_FUNC_OUT( "CHtiBtCommEcomPlugin::~CHtiBtCommEcomPlugin" );
+    }
+
+// ----------------------------------------------------------------------------
+CHtiBtCommEcomPlugin::CHtiBtCommEcomPlugin():iPort( -1 )
+    {
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiBtCommEcomPlugin::ConstructL()
+    {
+    TRAPD( err, LoadConfigL() );
+    if ( err == KErrNone )
+        {
+        ReadConfig();
+        }
+    else
+        {
+        TBufC8<1> emptyBuf( KNullDesC8 );
+        iBtDeviceNameOrAddress = emptyBuf.AllocL();
+        iPort = KErrNotFound;
+        }
+     // May take long!
+    User::LeaveIfError( iBtCommInterface.Connect(
+            *iBtDeviceNameOrAddress, iPort ) );
+
+    // Get the connected service port number (channel) and store it if needed
+    TInt connectedPort = iBtCommInterface.GetPortNumber();
+    HTI_LOG_FORMAT( "Connected port number = %d", connectedPort );
+    if ( connectedPort != iPort && connectedPort >= 0 )
+        {
+        TRAP( err, StorePortNumberL( connectedPort ) ); // ignore error
+        }
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiBtCommEcomPlugin::Receive( TDes8& aRawdataBuf,
+                                    TRequestStatus& aStatus )
+    {
+    iBtCommInterface.Receive( aRawdataBuf, aStatus );
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiBtCommEcomPlugin::Send( const TDesC8& aRawdataBuf,
+                                       TRequestStatus& aStatus )
+    {
+    iBtCommInterface.Send( aRawdataBuf, aStatus );
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiBtCommEcomPlugin::CancelReceive()
+    {
+    iBtCommInterface.CancelReceive();
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiBtCommEcomPlugin::CancelSend()
+    {
+    iBtCommInterface.CancelSend();
+    }
+
+// ----------------------------------------------------------------------------
+TInt CHtiBtCommEcomPlugin::GetSendBufferSize()
+    {
+    return iBtCommInterface.GetSendBufferSize();
+    }
+
+// ----------------------------------------------------------------------------
+TInt CHtiBtCommEcomPlugin::GetReceiveBufferSize()
+    {
+    return iBtCommInterface.GetReceiveBufferSize();
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiBtCommEcomPlugin::LoadConfigL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiBtCommEcomPlugin::LoadConfigL" );
+    iCfg = CHtiCfg::NewL();
+    iCfg->LoadCfgL( KHtiCfgPath, KHtiBtCommCfg );
+    HTI_LOG_TEXT( "cfg file loaded" );
+    HTI_LOG_FUNC_OUT( "CHtiBtCommEcomPlugin::LoadConfigL" );
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiBtCommEcomPlugin::ReadConfig()
+    {
+    HTI_LOG_FUNC_IN( "CHtiBtCommEcomPlugin::ReadConfig" );
+    // First try to get address - if found and length is correct it is used
+    TRAPD( paramErr, iBtDeviceNameOrAddress = iCfg->GetParameterL(
+                                                KBtDeviceAddress ).AllocL() );
+
+    if ( paramErr == KErrNone )
+        {
+        TInt port = ParsePortNumber();
+        if ( port >= 0 ) iPort = port;
+        else iPort = KErrNotFound;
+        }
+
+    if ( paramErr ||
+         iBtDeviceNameOrAddress->Length() != KBtAddressHexStringLength )
+        {
+        HTI_LOG_TEXT( "BT address not defined or not valid - getting name" );
+        delete iBtDeviceNameOrAddress;
+        iBtDeviceNameOrAddress = NULL;
+        // Address was not found - try to get name.
+        TRAP( paramErr, iBtDeviceNameOrAddress = iCfg->GetParameterL(
+                                                 KBtDeviceName ).AllocL() );
+        if ( paramErr )
+            {
+            HTI_LOG_TEXT( "BT name not defined either" );
+            TBufC8<1> emptyBuf( KNullDesC8 );
+            iBtDeviceNameOrAddress = emptyBuf.AllocL();
+            iPort = KErrNotFound;
+            }
+        else
+            {
+            TInt port = ParsePortNumber();
+            if ( port >= 0 ) iPort = port;
+            else iPort = KErrNotFound;
+            }
+        }
+    HTI_LOG_TEXT( "BT device name or address:" );
+    HTI_LOG_DES( *iBtDeviceNameOrAddress );
+    HTI_LOG_FORMAT( "Port number: %d", iPort );
+    HTI_LOG_FUNC_OUT( "CHtiBtCommEcomPlugin::ReadConfig" );
+    }
+
+// ----------------------------------------------------------------------------
+TInt CHtiBtCommEcomPlugin::ParsePortNumber()
+    {
+    HTI_LOG_FUNC_IN( "CHtiBtCommEcomPlugin::ParsePortNumber" );
+    TInt port = KErrNotFound;
+    TInt separatorIndex = iBtDeviceNameOrAddress->LocateReverse(
+            TChar( KPortSeparatorChar ) );
+    if ( separatorIndex != KErrNotFound )
+        {
+        TPtrC8 value = iBtDeviceNameOrAddress->Right(
+                iBtDeviceNameOrAddress->Length() - ( separatorIndex + 1 ) );
+        TLex8 lex( value );
+        lex.Val( port );
+        // Strip away the port number
+        iBtDeviceNameOrAddress->Des().SetLength( separatorIndex );
+        }
+    HTI_LOG_FORMAT( "ParsePortNumber returning %d", port );
+    HTI_LOG_FUNC_OUT( "CHtiBtCommEcomPlugin::ParsePortNumber" );
+    return port;
+    }
+
+// ----------------------------------------------------------------------------
+void CHtiBtCommEcomPlugin::StorePortNumberL( TInt aPortNumber )
+    {
+    HTI_LOG_FUNC_IN( "CHtiBtCommEcomPlugin::StorePortNumberL" );
+    if ( !iCfg )
+        {
+        iCfg = CHtiCfg::NewL();
+        }
+    iCfg->LoadCfgL( KHtiCfgPath, KHtiBtCommCfg );
+
+    TBool changesMade = EFalse;
+
+    // Add or replace port number to address parameter if it exists
+    HBufC8* value = NULL;
+    TRAPD( err, value = iCfg->GetParameterL( KBtDeviceAddress ).AllocL() );
+    if ( !err )
+        {
+        HTI_LOG_FORMAT( "Found address param (length = %d)", value->Length() );
+        CleanupStack::PushL( value );
+        TInt separatorIndex = value->Locate( TChar( KPortSeparatorChar ) );
+        if ( separatorIndex != KErrNotFound )
+            {
+            HTI_LOG_FORMAT( "Separator char found from index %d", separatorIndex );
+            value->Des().SetLength( separatorIndex );
+            }
+        value = value->ReAllocL( value->Length() + 5 );
+        // The old value has been deleted by ReAllocL and new allocated,
+        // so update cleanup stack.
+        CleanupStack::Pop();
+        CleanupStack::PushL( value );
+        TPtr8 ptr = value->Des();
+        ptr.Append( TChar( KPortSeparatorChar ) );
+        ptr.AppendNum( aPortNumber );
+        TRAP( err, iCfg->SetParameterL( KBtDeviceAddress, *value ) );
+        if ( !err ) changesMade = ETrue;
+        CleanupStack::PopAndDestroy(); // value
+        }
+
+    // Add or replace port number to name parameter if it exists
+    TRAP( err, value = iCfg->GetParameterL( KBtDeviceName ).AllocL() );
+    if ( !err )
+        {
+        HTI_LOG_FORMAT( "Found name param (length = %d)", value->Length() );
+        CleanupStack::PushL( value );
+        TInt separatorIndex = value->Locate( TChar( KPortSeparatorChar ) );
+        if ( separatorIndex != KErrNotFound )
+            {
+            HTI_LOG_FORMAT( "Separator char found from index %d", separatorIndex );
+            value->Des().SetLength( separatorIndex );
+            }
+        value = value->ReAllocL( value->Length() + 5 );
+        // The old value has been deleted by ReAllocL and new allocated,
+        // so update cleanup stack.
+        CleanupStack::Pop();
+        CleanupStack::PushL( value );
+        TPtr8 ptr = value->Des();
+        ptr.Append( TChar( KPortSeparatorChar ) );
+        ptr.AppendNum( aPortNumber );
+        TRAP( err, iCfg->SetParameterL( KBtDeviceName, *value ) );
+        if ( !err ) changesMade = ETrue;
+        CleanupStack::PopAndDestroy(); // value
+        }
+
+    if ( changesMade )
+        {
+        iCfg->SaveCfgL( KHtiCfgPath, KHtiBtCommCfg );
+        }
+    HTI_LOG_FUNC_OUT( "CHtiBtCommEcomPlugin::StorePortNumberL" );
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommEcomPlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM implementations in this dll
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiBtCommEcomPlugin.h"
+
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+
+/*---------------------------------------------------------------------------*/
+// Provides a key value pair table, this is used to identify
+// the correct construction function for the requested interface.
+const TImplementationProxy ImplementationTable[] =
+    {
+        IMPLEMENTATION_PROXY_ENTRY( 0x200212CC,  CHtiBtCommEcomPlugin::NewL )
+    };
+
+/*---------------------------------------------------------------------------*/
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/HtiBtClientServerCommon.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Global definitions for BtCommServer and client side interface.
+*
+*/
+
+
+#ifndef __HTIBTCLIENTSERVERCOMMON_H__
+#define __HTIBTCLIENTSERVERCOMMON_H__
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+
+// The server name (and server thread name)
+_LIT( KBtCommServerName,"HtiBtCommServer" );
+
+// The version of the server
+const TUint KBtCommServerMajorVersionNumber = 1;
+const TUint KBtCommServerMinorVersionNumber = 0;
+const TUint KBtCommServerBuildVersionNumber = 0;
+
+const TInt KClientReceiveBufferMaxSize = 0x1000; // 4096 bytes
+const TInt KClientSendBufferMaxSize = 0x1000; // 4096 bytes
+
+
+// DATA TYPES
+
+// The message ID's of BtCommServer
+// from Symbian side
+enum TBtCommServerRqst
+    {
+    EBtCommServerConnect = 0,
+    EBtCommServerRecv,
+    EBtCommServerSend,
+    ECancelBtCommServerRecv,
+    ECancelBtCommServerSend,
+    EGetServicePortNumber
+    };
+
+
+// FUNCTION PROTOTYPES
+/**
+* Start HtiBtCommServer thread. This is called by client interface.
+*/
+IMPORT_C TInt StartThread();
+
+#endif // __HTIBTCLIENTSERVERCOMMON_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/HtiBtCommInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,149 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Client side interface to HtiBtCommServer
+*
+*/
+
+
+#ifndef __HTIBTCOMMINTERFACE_H__
+#define __HTIBTCOMMINTERFACE_H__
+
+//  INCLUDES
+#include <e32test.h>
+#include <e32base.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+/**
+ * Remote interface to HtiBtCommServer.
+ * HtiBtCommServer runs in separate thread, but always within the
+ * client process.
+ *
+ * The thread is started and session to server created, when the
+ * Connect is called for the first time.
+ *
+ * Server allows only one connection (session) at a time.
+ *
+ * Library: htibtcomminterface.lib
+ */
+class RHtiBtCommInterface : public RSessionBase
+    {
+    public: // Constructor and destructor
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C RHtiBtCommInterface();
+
+    public:
+        /**
+        * Connects and creates session to BtCommServer. Additionally,
+        * connects to remote BT device. This may take a while
+        * and may require user interaction (device selection).
+        *
+        * If the server is not running within this process, it is
+        * started in a new thread. Note that server allows only one
+        * connection (session).
+        * @return Error code
+        */
+        IMPORT_C TInt Connect( TDesC8& aDeviceNameOrAddress, TInt aPort );
+
+        /**
+        * Close the session to server and wait for servers death.
+        * Will disconnect the server from remote BT host, if connected.
+        */
+        IMPORT_C void Close();
+
+        /**
+        * Returns server version
+        * @return Version
+        */
+        IMPORT_C TVersion Version() const;
+
+        /**
+         *  Return required buffer max size for Send operation.
+         */
+        IMPORT_C TInt GetSendBufferSize() const;
+
+        /**
+         *  Return required buffer max size for Receive operation.
+         */
+        IMPORT_C TInt GetReceiveBufferSize() const;
+
+        /**
+        * Receives data from BtCommServer.
+        * Note: The aData buffer size must equal to GetReceiveBufferSize().
+        * (server will write 1 to GetReceiveBufferSize bytes to the buffer).
+        * @param aData Descriptor where data is received
+        * @param aStatus Asynchronous request status
+        */
+        IMPORT_C void Receive( TDes8& aData,
+                           TRequestStatus& aStatus );
+
+        /**
+        * Sends data to BtCommServer.
+        * Note: The aData buffer size must equal to GetSendBufferSize().
+        * (server will read as much as there is data in aData. There must
+        * never be more data than GetSendBufferSize. This is important to notice,
+        * if HBufC is used, because its actual max size can be greater than
+        * initially suggested in its construction)
+        *
+        * @param aData Data to be sent
+        * @param aStatus Asynchronous request status
+        */
+        IMPORT_C void Send( const TDesC8& aData,
+                           TRequestStatus& aStatus );
+
+
+        /**
+        * Cancels pending Receive request on server.
+        */
+        IMPORT_C void CancelReceive();
+
+        /**
+        * Cancels pending Send request on server.
+        */
+        IMPORT_C void CancelSend();
+
+        /**
+        * Gets the port number of the remote service where the server is
+        * connected.
+        * @return Port number or KErrDisconnected if server is not connected
+        */
+         IMPORT_C TInt GetPortNumber() const;
+
+    private:
+
+        /**
+        * During Connect(), connect the server
+        * to remote BT host service.
+        */
+        TInt RHtiBtCommInterface::ConnectBt( TDesC8& aDeviceNameOrAddress,
+                                             TInt aPort );
+
+};
+
+#endif // __HTIBTCOMMINTERFACE_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/HtiBtCommServer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CHtiBtCommServer declaration
+*
+*/
+
+
+#ifndef __HTIBTCOMMSERVER_H__
+#define __HTIBTCOMMSERVER_H__
+
+//  INCLUDES
+
+#include <e32def.h>
+#include <e32base.h>
+
+//  CONSTANTS
+
+// Reasons for BtCommServer panic
+enum TBtCommServerPanic
+    {
+    EBadRequest,
+    EBadDescriptor,
+    EMainSchedulerError,
+    ESvrCreateServer,
+    ESvrStartServer,
+    ECreateTrapCleanup,
+    ENotImplementedYet,
+    EFailedToInitMessageBox,
+    EFailedToOpenBTconnection,
+    EFailedToOpenPhonetChannel,
+    EFailedToRecPhonetMsg,
+    EFailedToSendPhonetMsg,
+    ETooManyAsyncRequests
+    };
+
+//  FUNCTION PROTOTYPES
+
+// Function to panic the server
+GLREF_C void PanicServer( TBtCommServerPanic aPanic );
+
+// Thread function for server
+GLREF_C TInt BtCommServerThread( TAny * );
+
+//  FORWARD DECLARATIONS
+class CHtiBtCommServerSession;
+class CHtiBtReaderWriter;
+
+// CLASS DECLARATION
+
+/**
+* Server class for BT communication.
+*/
+class CHtiBtCommServer : public CServer2
+    {
+
+    private: // Constructors and destructor
+       /**
+        * C++ default constructor.
+        */
+        CHtiBtCommServer( TInt aPriority );
+
+       /**
+        * Second Phase constructor
+        */
+        void ConstructL();
+
+    public:
+       /**
+        * Symbian Two-phased constructor.
+        */
+        static CHtiBtCommServer* NewL();
+
+       /**
+        * Destructor.
+        */
+        ~CHtiBtCommServer();
+
+    public: // callbacks from session
+
+        /**
+        * Session was deleted notification.
+        * Session notifies server, when client is disconnecting
+        * and session is being deleted. Server will start shutdown.
+        */
+        void SessionFreed();
+
+        /**
+        * Session was created notification.
+        * @param aSession Session, which is notifying server of its creation.
+        */
+        void SessionCreated( CHtiBtCommServerSession* aSession );
+
+    public:
+       /**
+        * Creates a new client session
+        * @param aVersion Version of the server
+        * @param aMessage Client message
+        * @return Pointer to the client session
+        */
+        virtual CSession2* NewSessionL( const TVersion& aVersion,
+            const RMessage2& aMessage ) const;
+
+       /**
+        * Creates server thread
+        * @param aStarted semaphore
+        * @return Error code
+        */
+        static TInt ThreadFunction( TAny* aStarted );
+
+public: // Data
+    // Priority of the server
+    enum TBtServPriority
+        {
+        EBtCommServerPriority = 100
+        };
+
+private:
+
+    CHtiBtCommServerSession* iSession; // Not owned. Only one session allowed!
+
+    };
+
+#endif // __HTIBTCOMMSERVER_H__
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/HtiBtCommServerSession.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Server side session in HtiBtCommServer.
+*
+*/
+
+
+#ifndef CHTIBTCOMMSERVERSESSION_H
+#define CHTIBTCOMMSERVERSESSION_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+#include "BtSerialClient.h" // MBtSerialClientObserver
+
+// FORWARD DECLARATIONS
+
+class CHtiBtCommServer;
+
+// CLASS DECLARATION
+
+/**
+* This class represents a client session in the server.
+*
+* Server owns one instance of session (meaning only one client session
+* is allowed for this server).
+* Session allows only one outstanding read request and write request at a time.
+* Read request and write request may be outstanding simultaneously.
+*/
+class CHtiBtCommServerSession :
+    public CSession2,
+    public MBtSerialClientObserver
+    {
+public:
+
+   /**
+    * Two phase constructor.
+    *
+    * @param aServer Pointer to the server instance
+    */
+    static CHtiBtCommServerSession* NewL( CHtiBtCommServer* aServer );
+
+private: // Construction
+
+   /**
+    * C++ default constructor.
+    *
+    * @param aClient
+    * @param aServer
+    */
+    CHtiBtCommServerSession( CHtiBtCommServer* aServer );
+
+    /**
+     * Second phase construction.
+     */
+    void ConstructL();
+
+   /**
+    * Destructor.
+    */
+    ~CHtiBtCommServerSession();
+
+private: // From MBtSerialClientObserver
+
+    void ConnectedToServer(TInt aError);
+    void DisconnectedFromServer();
+    void DataFromServer(const TDesC8& aData);
+    void AllBufferedDataSent();
+
+private:
+
+    /**
+    * Handle client request. This is invoced by client server framework.
+    * @param aMessage Message object describing client request
+    */
+    virtual void ServiceL(const RMessage2 &aMessage);
+
+    /**
+    * Determine client request type and delegate handling accordingly.
+    * @param aMessage Message object describing client request
+    */
+    void DispatchMessageL(const RMessage2 &aMessage);
+
+    void HandleConnectRequestL(const RMessage2& aMessage);
+
+    /**
+    * Handle client's send request.
+    * Copies data from client address space to internal send buffer and starts
+    * sending it.
+    * @param aMessage Message object describing client request
+    */
+    void HandleSendRequestL(const RMessage2& aMessage);
+
+    /**
+    * Handle client's read request.
+    * Wait for incoming data. Once received, copy its data to client's
+    * address space and complete client's request.
+    * @param aMessage Message object describing client request
+    */
+    void HandleReadRequestL(const RMessage2& aMessage);
+
+    /**
+    * Handle client's cancel requests.
+    * Cancel either read or write operation depending on client request.
+    * @param aMessage Message object describing client request
+    */
+    void HandleCancelRequestL(const RMessage2& aMessage);
+
+    /**
+     * Handle port number request
+     * Write the port number of the currently connected service. If not
+     * connected writes KErrDisconnected.
+     */
+    void HandlePortNumberRequestL(const RMessage2& aMessage);
+
+private: // Helpers
+
+    void PanicClient(TInt aPanic) const;
+    void ResetAll(TInt aCompletionCode);
+    void TryCompleteReadRequest();
+
+private: // Data
+
+    CHtiBtCommServer *iBtCommServer; // referenced
+
+    RMessage2 iReadRequest;
+    RMessage2 iWriteRequest;
+    RMessage2 iConnectRequest;
+    TBool iWriteRequestComplete; // ETrue: no previous pending write request
+    TBool iReadRequestComplete; // ETrue: no previous pending read request
+    TBool iConnectRequestComplete;
+
+    CBtSerialClient* iBtClient;
+
+    HBufC8* iIncomingDataBuf; // Coming from remote host
+    HBufC8* iSendBuffer;      // Sent to remote host
+
+    };
+
+#endif // CHTIBTCOMMSERVERSESSION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/inc/Logger.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,70 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logger library
+*
+*/
+
+
+#ifndef __LOGGER_H_____
+#define __LOGGER_H_____
+
+//  INCLUDES
+#include <e32std.h>
+
+// CONSTANTS
+const TInt KLogLevelDebug   = 0;
+const TInt KLogLevelInfo    = 10;
+const TInt KLogLevelWarning = 20;
+const TInt KLogLevelError   = 30;
+
+const TInt KMinimumLogLevel = KLogLevelInfo;
+
+
+// When __ENABLE_LOGGING__ macro is defined, logging functions are
+// compiled to final build.
+//
+// Example usage: LOGFW(DebugLog(_L("Got an error %d"), 5))
+//
+#ifdef __ENABLE_LOGGING__
+
+    #define LOGFW(a) a;
+
+    _LIT(KLogFileName, "c:\\HTI_BtComm.log");
+
+    // panics
+    _LIT(KLogPanicCategory, "CustNotifyLog");
+    static const TInt KPanicFsConnectFailed = 1;
+    static const TInt KPanicFileCreateFailed = 2;
+    static const TInt KPanicFileWriteFailed = 3;
+
+    const TInt KLogEntryMaxLength = 156;
+
+    // Usage example: DOLOG(_L("Logstring"));
+    void DebugLog(TRefByValue<const TDesC> aFmt,...);
+    void InfoLog(TRefByValue<const TDesC> aFmt,...);
+    void WarnLog(TRefByValue<const TDesC> aFmt,...);
+    void ErrLog(TRefByValue<const TDesC> aFmt,...);
+
+    void Log(TInt aLevel, TRefByValue<const TDesC> aFmt, VA_LIST list);
+
+    void LogBytes(const TDesC8& aData, TInt aMaxBytesToLog );
+
+#else  //__ENABLE_LOGGING__
+
+    #define LOGFW(a)
+
+#endif //__ENABLE_LOGGING__
+
+#endif //__LOGGER_H_____
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/src/HtiBtCommInterface.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,188 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Implementation of RHtiBtCommInterface class.
+*              Symbian side component uses this interface to receive and
+*              send HTI data to HtiBtCommServer.
+*              HtiBtCommServer acts as proxy to send and receive data
+*              to and from PC.
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiBtClientServerCommon.h"
+#include "HtiBtCommInterface.h"
+
+#include <e32uid.h>
+#include <HtiLogging.h>
+
+// CONSTANTS
+const TUint KBtCommServerDefaultMessageSlots = 4; // Read, write, readCancel, writeCancel
+
+// Constants
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C RHtiBtCommInterface::RHtiBtCommInterface()
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::RHtiBtCommInterface()" );
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C TInt RHtiBtCommInterface::Connect( TDesC8& aDeviceNameOrAddress,
+                                            TInt aPort )
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::Connect()" );
+
+    TInt error = StartThread(); // see HtiBtClientServerCommon.h
+    if (error == KErrNone)
+        {
+        error = CreateSession( KBtCommServerName,
+                               Version(),
+                               KBtCommServerDefaultMessageSlots );
+        }
+    if ( error )
+        return error;
+
+    return ConnectBt( aDeviceNameOrAddress, aPort );
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C void RHtiBtCommInterface::Close()
+    {
+    HTI_LOG_FUNC_IN( "RHtiBtCommInterface::Close" );
+
+    // Use thread finder to find the server thread
+    TFullName threadName;
+    TFullName matchPattern;
+    matchPattern.Append( _L( "*" ) );
+    matchPattern.Append( KBtCommServerName );
+    matchPattern.Append( _L( "*" ) );
+
+    TFindThread threadFinder;
+    threadFinder.Find( matchPattern );
+    TInt err = threadFinder.Next( threadName );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "RHtiBtCommInterface::Close: Failed to find server thread: %d", err );
+        User::Panic( _L( "BtIf Close, server thread not found" ), err );
+        }
+
+    HTI_LOG_TEXT( "RHtiBtCommInterface::Close: Found server thread:" );
+    HTI_LOG_DES( threadName );
+
+    RThread thread;
+    err = thread.Open( threadName );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "RHtiBtCommInterface::Close: Failed to open server thread: %d", err );
+        User::Panic( _L( "BtIf Close, error opening server thread" ), err );
+        }
+    else
+        {
+        // initiate server shutdown
+        RSessionBase::Close();
+
+        // For clean server stop, wait for its death
+        HTI_LOG_TEXT( "RHtiBtCommInterface::Close: Waiting for server thread to die..." );
+        TRequestStatus status;
+        thread.Logon( status );
+        User::WaitForRequest( status );
+        HTI_LOG_TEXT( "RHtiBtCommInterface::Close: Server thread dead." );
+        }
+
+    thread.Close();
+    HTI_LOG_FUNC_OUT( "RHtiBtCommInterface::Close" );
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C TVersion RHtiBtCommInterface::Version(void) const
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::Connect()" );
+    return ( TVersion( KBtCommServerMajorVersionNumber,
+                       KBtCommServerMinorVersionNumber,
+                       KBtCommServerBuildVersionNumber ) );
+
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C TInt RHtiBtCommInterface::GetSendBufferSize() const
+    {
+    return KClientSendBufferMaxSize;
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C TInt RHtiBtCommInterface::GetReceiveBufferSize() const
+    {
+    return KClientReceiveBufferMaxSize;
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C void RHtiBtCommInterface::Receive(TDes8& aData,
+                                        TRequestStatus& aStatus)
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::Receive()" );
+    SendReceive( EBtCommServerRecv, TIpcArgs( &aData ), aStatus );
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C void RHtiBtCommInterface::Send(const TDesC8& aData,
+                                        TRequestStatus& aStatus)
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::Send()" );
+    SendReceive( EBtCommServerSend, TIpcArgs( &aData ), aStatus );
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C void RHtiBtCommInterface::CancelReceive()
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::CancelReceive()" );
+    SendReceive( ECancelBtCommServerRecv, TIpcArgs( NULL ) );
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C void RHtiBtCommInterface::CancelSend()
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::CancelSend()" );
+    SendReceive( ECancelBtCommServerSend, TIpcArgs( NULL ) );
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C TInt RHtiBtCommInterface::GetPortNumber() const
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::GetPortNumber()" );
+    TPckgBuf<TInt> pckg;
+    TInt ret = SendReceive( EGetServicePortNumber, TIpcArgs( &pckg ) );
+    if ( ret == KErrNone )
+        {
+        ret = pckg();
+        }
+    return ret;
+    }
+
+/*---------------------------------------------------------------------------*/
+TInt RHtiBtCommInterface::ConnectBt( TDesC8& aDeviceNameOrAddress, TInt aPort )
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::ConnectBt()" );
+    return SendReceive( EBtCommServerConnect,
+                            TIpcArgs( &aDeviceNameOrAddress, aPort ) );
+    }
+
+/*---------------------------------------------------------------------------*/
+GLDEF_C TInt E32Main()
+    {
+    HTI_LOG_TEXT( "RHtiBtCommInterface::E32Main()" );
+    return KErrNone;
+    }
+
+// End of the file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/src/HtiBtCommServer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,244 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: This file contains the implementation of the
+*              CHtiBtCommServer class.
+*              CHtiBtCommServer handles Symbian server side operations
+*              such as server starting and client session creation.
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiBtClientServerCommon.h"
+#include "HtiBtCommServer.h"
+#include "HtiBtCommServerSession.h"
+#include "Logger.h"
+
+#include <e32base.h>
+#include <e32std.h>
+#include <e32svr.h>
+#include <e32uid.h>
+
+// CONSTANTS
+// For memory allocations
+const TUint KBtCommServerHeapSizeMin       = 0x6000;
+const TUint KBtCommServerHeapSizeMax       = 0x20000;
+const TUint KBtCommServerStackSize         = 0x8000;
+
+
+//*****************************************************************************
+//
+// Class CHtiBtCommServer
+//
+//*****************************************************************************
+
+/*---------------------------------------------------------------------------*/
+CHtiBtCommServer::CHtiBtCommServer( TInt aPriority )
+    : CServer2( aPriority, ESharableSessions )
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer: CHtiBtCommServer()")))
+    __DECLARE_NAME(_S( "CHtiBtCommServer" ));
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServer::ConstructL()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer: ConstructL()")))
+    }
+
+/*---------------------------------------------------------------------------*/
+CHtiBtCommServer* CHtiBtCommServer::NewL()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer: NewL()"));)
+
+    CHtiBtCommServer *pS =
+        new (ELeave) CHtiBtCommServer( EBtCommServerPriority );
+    CleanupStack::PushL( pS );
+    __ASSERT_ALWAYS( pS != NULL, PanicServer( ESvrCreateServer ) );
+
+    pS->ConstructL();
+    CleanupStack::Pop( pS );
+    User::SetProcessCritical( User::ENotCritical );
+    User::SetCritical( User::ENotCritical );
+    LOGFW(InfoLog(_L("Server was started")))
+    return pS;
+    }
+
+/*---------------------------------------------------------------------------*/
+CHtiBtCommServer::~CHtiBtCommServer()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer: ~CHtiBtCommServer()")))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServer::SessionFreed()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer: SessionFreed(): Stopping active scheduler"));)
+    iSession = NULL; // iSession is owned by server framework, not deleted here
+    CActiveScheduler::Stop();
+    LOGFW(DebugLog(_L("CHtiBtCommServer: SessionFreed(): Done"));)
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServer::SessionCreated( CHtiBtCommServerSession* aSession )
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer: SessionCreated()"));)
+    iSession = aSession;
+    }
+
+/*---------------------------------------------------------------------------*/
+CSession2* CHtiBtCommServer::NewSessionL( const TVersion &aVersion,
+    const RMessage2& aMessage ) const
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer: NewSessionL() - IPC V2"));)
+    aMessage.IsNull();
+    if ( iSession )
+        User::Leave( KErrAlreadyExists ); // Allow only one session
+
+    // Check that server is the right version
+    TVersion ver( KBtCommServerMajorVersionNumber,
+                  KBtCommServerMinorVersionNumber,
+                  KBtCommServerBuildVersionNumber );
+    if ( !User::QueryVersionSupported( ver, aVersion ) )
+        {
+        User::Leave( KErrNotSupported );
+        }
+    return CHtiBtCommServerSession::NewL( (CHtiBtCommServer*)this );
+    }
+
+/*---------------------------------------------------------------------------*/
+GLDEF_C TInt CHtiBtCommServer::ThreadFunction( TAny* anArg )
+    {
+    LOGFW(_L("CHtiBtCommServer: ThreadFunction(): Starting"));
+
+    __UHEAP_MARK;
+
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+
+    // Convert argument into semaphore reference
+    RSemaphore& semaphore = *(RSemaphore*)anArg;
+
+    // Start scheduler...
+    LOGFW(DebugLog(_L("CHtiBtCommServer: ThreadFunction(): Installing active scheduler"));)
+    CActiveScheduler *pA = new CActiveScheduler;
+    __ASSERT_ALWAYS( pA != NULL, PanicServer( EMainSchedulerError ) );
+    CActiveScheduler::Install( pA );
+
+    CHtiBtCommServer* pS = NULL;
+    TRAPD(err,
+        // ...and server
+        LOGFW(DebugLog(_L("CHtiBtCommServer: ThreadFunction(): Creating server instance"));)
+        pS = CHtiBtCommServer::NewL();
+        )
+
+    if ( err != KErrNone )
+        {
+        LOGFW(DebugLog(_L("CHtiBtCommServer: ThreadFunction(): Failed creating server instance"));)
+        }
+
+    LOGFW(DebugLog(_L("CHtiBtCommServer: ThreadFunction(): Starting server"));)
+    __ASSERT_ALWAYS( pS->Start(KBtCommServerName) == KErrNone,
+        PanicServer( ESvrStartServer ) ); // Make first request pending,
+
+    // Signal that server has started
+    LOGFW(DebugLog(_L("CHtiBtCommServer: ThreadFunction(): Signalling client: server is up and running"));)
+    semaphore.Signal();
+
+    LOGFW(DebugLog(_L("CHtiBtCommServer: ThreadFunction(): Waiting for server's death"));)
+    // Start receiving requests from clients
+    CActiveScheduler::Start();
+    LOGFW(DebugLog(_L("CHtiBtCommServer: ThreadFunction(): Server was stopped"));)
+    LOGFW(InfoLog(_L("Server was stopped")))
+    delete pS;
+    LOGFW(DebugLog(_L("CHtiBtCommServer: ThreadFunction(): Server was deleted"));)
+
+    // Finished
+    delete pA;
+    pA = NULL;
+
+     // Destroy clean-up stack
+    delete cleanup;
+    cleanup = NULL;
+
+    __UHEAP_MARKEND;
+    return KErrNone;
+    }
+
+/*---------------------------------------------------------------------------*/
+GLDEF_C void PanicServer( TBtCommServerPanic aPanic )
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer: PanicServer()"));)
+    _LIT( KTxtServerPanic, "BtCommServer panic" );
+    User::Panic( KTxtServerPanic, aPanic );
+    }
+
+/*---------------------------------------------------------------------------*/
+EXPORT_C TInt StartThread()
+    {
+//    LOGFW(_L("CHtiBtCommServer: StartThread()"));
+    TInt res = KErrNone;
+
+    // Create server - if one of this name does not already exist
+    TFindServer findBtCommServer( KBtCommServerName );
+    TFullName name;
+    if ( findBtCommServer.Next( name ) != KErrNone ) // Server doesn't exist
+        {
+         // Create a semaphore to know when thread initialization has finished
+        RSemaphore semaphore;
+        semaphore.CreateLocal(0);
+
+//        LOGFW(_L("CHtiBtCommServer: Created Semaphore...\n"));
+
+        // Create new server thread and thread's main function
+        RThread thread;
+        res = thread.Create( KBtCommServerName,
+                             CHtiBtCommServer::ThreadFunction,
+                             KBtCommServerStackSize,
+                             KBtCommServerHeapSizeMin,
+                             KBtCommServerHeapSizeMax,
+                             &semaphore );
+
+
+        if ( res == KErrNone ) // Thread created ok - now start it going
+            {
+//            LOGFW(_L("CHtiBtCommServer: StartThread() - Create OK"));
+
+            thread.SetPriority( EPriorityNormal );
+//            TRequestStatus stat1;
+//            thread.Logon(stat1);
+
+            thread.Resume();  // Start it going
+
+            semaphore.Wait(); // Wait until it's initialized
+
+            thread.Close();   // No longer interest in the other thread
+            }
+        else // Thread not created ok
+            {
+            // No further interest in it
+//            LOGFW(_L("CHtiBtCommServer: StartThread() - Create FAIL"));
+            thread.Close();
+            }
+        semaphore.Close();
+        }
+    return res;
+    }
+
+/*---------------------------------------------------------------------------*/
+GLDEF_C TInt E32Main()
+    {
+    return KErrNone;
+    }
+
+// End of the file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/src/HtiBtCommServerSession.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,419 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CHtiBtCommServerSession class. This class
+*                represents the client session in server.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "HtiBtClientServerCommon.h"
+#include "HtiBtCommServerSession.h"
+#include "HtiBtCommServer.h"
+#include "BtSerialClient.h"
+#include "Logger.h"
+
+#include <e32base.h>
+#include <e32std.h>
+#include <e32svr.h>
+
+#include <HtiCommPluginInterface.h> // KErrComModuleReset;
+
+// CONSTANTS
+ _LIT(KBtComSessPanic, "BtComSessAssrt");
+
+const TInt KBtAddressHexStringLength = 12; // 6 bytes
+const TInt KIncomingDataBufSize = 32 * 1024;
+
+//*****************************************************************************
+//
+// Class CHtiBtCommServerSession
+//
+//*****************************************************************************
+
+/*---------------------------------------------------------------------------*/
+CHtiBtCommServerSession::CHtiBtCommServerSession( CHtiBtCommServer* aServer )
+    : CSession2()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: CHtiBtCommServerSession()")))
+
+    __DECLARE_NAME( _S( "CHtiBtCommServerSession" ) );
+    iBtCommServer = aServer;
+    iReadRequestComplete = ETrue;  // ready to accept read request
+    iWriteRequestComplete = ETrue;
+    iConnectRequestComplete = ETrue;
+    iBtCommServer->SessionCreated(this);
+    }
+
+/*---------------------------------------------------------------------------*/
+CHtiBtCommServerSession* CHtiBtCommServerSession::NewL(
+    CHtiBtCommServer* aServer )
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: NewL()")))
+    CHtiBtCommServerSession* session =
+        new (ELeave) CHtiBtCommServerSession( aServer );
+    CleanupStack::PushL( session );
+    session->ConstructL();
+    CleanupStack::Pop( session );
+    return session;
+    }
+
+/*---------------------------------------------------------------------------*/
+
+void CHtiBtCommServerSession::ConstructL()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: ConstructL()")))
+    iBtClient = CBtSerialClient::NewL(*this);
+    iIncomingDataBuf = HBufC8::NewL(KIncomingDataBufSize);
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: ConstructL(): Done")))
+    }
+
+/*---------------------------------------------------------------------------*/
+CHtiBtCommServerSession::~CHtiBtCommServerSession()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: ~CHtiBtCommServerSession()")))
+    delete iBtClient;
+    ResetAll(KErrCancel);
+    delete iIncomingDataBuf;
+    if ( iBtCommServer )
+        {
+        iBtCommServer->SessionFreed();
+        }
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: ~CHtiBtCommServerSession(): Done")))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::ServiceL( const RMessage2& aMessage )
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: ServiceL()")))
+
+    TRAPD( error, DispatchMessageL( aMessage ) );
+    if ( error != KErrNone )
+        {
+        LOGFW(DebugLog(_L("CHtiBtCommServerSession::ServiceL error %d"), error);)
+        }
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: ServiceL(): Done")))
+    }
+
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::DispatchMessageL( const RMessage2 &aMessage )
+    {
+    LOGFW( DebugLog( _L( "CHtiBtCommServerSession: DispatchMessageL()" ) ) )
+
+    switch ( aMessage.Function() )
+        {
+        case EBtCommServerConnect:
+            {
+            HandleConnectRequestL( aMessage );
+            }
+            break;
+
+        case EBtCommServerSend:
+            {
+            HandleSendRequestL( aMessage );
+            }
+            break;
+        case EBtCommServerRecv:
+            {
+            HandleReadRequestL( aMessage );
+            }
+            break;
+
+        case ECancelBtCommServerRecv:
+        case ECancelBtCommServerSend:
+            {
+            HandleCancelRequestL( aMessage );
+            }
+            break;
+
+        case EGetServicePortNumber:
+            {
+            HandlePortNumberRequestL( aMessage );
+            }
+            break;
+
+        default:
+            {
+            LOGFW(ErrLog(_L("CHtiBtCommServerSession::DispatchMessageL: Unknown request: %d. Panicing Client"), aMessage.Function());)
+            PanicClient( EBadRequest );
+            User::Panic( KBtComSessPanic, 1 );
+            }
+            break;
+        }
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: DispatchMessageL(): Done")))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::HandleConnectRequestL( const RMessage2& aMessage )
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL()")))
+    if ( !iConnectRequestComplete )
+        {
+        LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Already connecting")))
+        aMessage.Complete( KErrNotReady );
+        }
+    else
+        {
+        if ( iBtClient->Connected() )
+            {
+            LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Already connected")))
+            aMessage.Complete( KErrNone ); // Already connected. This is not an error?
+            }
+        else
+            {
+            LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Starting to connect to remote host")))
+            iConnectRequest = aMessage;
+            iConnectRequestComplete = EFalse;
+
+            TInt dataLength = (TUint16)aMessage.GetDesLength( 0 ); //first message slot
+            LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Data length = %d"), dataLength));
+
+            TInt port = aMessage.Int1();
+            LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Port = %d"), port));
+
+            if ( dataLength < 1 )
+                {
+                LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): No address or name - need to ask device")))
+                iBtClient->ConnectL(); // Request is completed in ConnectedToServer
+                }
+            else if ( dataLength == KBtAddressHexStringLength )
+                {
+                TBuf8<KBtAddressHexStringLength> addressBuf8;
+                aMessage.ReadL( 0, addressBuf8 );
+                TBuf<KBtAddressHexStringLength> addressBuf;
+                addressBuf.Copy( addressBuf8 );
+                TBTDevAddr address;
+                TInt result = address.SetReadable( addressBuf );
+                LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): SetReadable result = %d"), result));
+                if ( result != KBtAddressHexStringLength )
+                    {
+                    LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Not valid address - use it as name")))
+                    iBtClient->ConnectL( addressBuf, port );
+                    }
+                else
+                    {
+                    LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Valid address - connect")))
+                    iBtClient->ConnectL( address, port );
+                    }
+                }
+            else
+                {
+                LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Using name to connect")))
+                TBTDeviceName8 deviceName8;
+                aMessage.ReadL( 0, deviceName8 );
+                TBTDeviceName deviceName;
+                deviceName.Copy( deviceName8 );
+                iBtClient->ConnectL( deviceName, port );
+                }
+            }
+        }
+    LOGFW(DebugLog(_L("CHtiBtCommServer:HandleConnectRequestL(): Done")))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::HandleReadRequestL( const RMessage2& aMessage )
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: HandleReadRequestL()")))
+
+    if ( !iReadRequestComplete )
+        {
+        LOGFW(WarnLog(_L("CHtiBtCommServerSession: HandleReadRequestL(): Pending request. ret=KErrNotReady")))
+        // Two simultaneous read requests are not allowed.
+        aMessage.Complete(KErrNotReady);
+        return;
+        }
+
+    // No data in read buffer. Must wait for new data before completing request
+    iReadRequest = aMessage;
+    iReadRequestComplete = EFalse; // Not ready to complete next request
+    TryCompleteReadRequest(); // if there is something in the readbuffer,
+                              // use it for completion.
+
+    if ( iIncomingDataBuf->Des().Length() == 0 )
+        {
+        // Read some bytes to buffer even before client's request.
+        iBtClient->ReadAsyncL(); // Issue async request to read more data.
+        }
+
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: HandleReadRequestL(): Done")))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::HandleSendRequestL( const RMessage2& aMessage )
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: HandleSendRequestL()")))
+
+    TInt dataLength = (TUint16)aMessage.GetDesLength( 0 ); //first message slot
+    LOGFW( InfoLog( _L( "Framework requested to send data: %d bytes" ), dataLength ) )
+    if ( iBtClient->SendBufferMaxSize() < dataLength )
+        {
+        aMessage.Complete(KErrOverflow);
+        LOGFW(ErrLog(_L("CHtiBtCommServerSession: HandleSendRequestL(): client is giving too big data. Cannot handle.")))
+        }
+    else if ( !iWriteRequestComplete )
+        {
+        LOGFW(WarnLog(_L("CHtiBtCommServerSession: HandleSendRequestL(): Pending request. ret=KErrNotReady")))
+        // Already pending send request. Two simultaneous send requests not allowed.
+        aMessage.Complete( KErrNotReady );
+        }
+    else
+        {
+        if ( iBtClient->FreeSpaceInSendBuffer() < dataLength )
+            {
+            LOGFW(DebugLog(_L("CHtiBtCommServerSession: HandleSendRequestL(): Completing send request delayed")))
+            // No space in the iBtClient's send buffer. Copy the data to internal
+            // buffer and wait for iBtClient to send its data out before adding
+            // data to its send buffer.
+            delete iSendBuffer;
+            iSendBuffer = NULL;
+            iSendBuffer = HBufC8::NewL(dataLength);
+            TPtr8 ptr = iSendBuffer->Des();
+            aMessage.ReadL( 0, ptr );
+            iWriteRequestComplete = EFalse;
+            iWriteRequest = aMessage;
+            // Wait for callback call AllBufferedDataSent. Complete request there.
+            }
+        else
+            {
+            LOGFW(DebugLog(_L("CHtiBtCommServerSession: HandleSendRequestL(): Completing send request immediately")))
+            // All data can be sent immediately, because there is enough space in
+            // iBtClient's send buffer.
+            HBufC8* data = HBufC8::NewLC( dataLength );
+            TPtr8 ptr = data->Des();
+            aMessage.ReadL( 0, ptr );
+            iBtClient->SendL( ptr );
+            CleanupStack::PopAndDestroy( data );
+            aMessage.Complete( KErrNone );
+            }
+        }
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: HandleSendRequestL(): Done")))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::HandleCancelRequestL( const RMessage2& aMessage )
+    {
+    ResetAll( KErrCancel );
+    aMessage.Complete( KErrNone );
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::HandlePortNumberRequestL(const RMessage2& aMessage)
+    {
+    TPckgBuf<TInt> p( iBtClient->ServicePort() );
+    TInt err = aMessage.Write( 0, p, 0 );
+    aMessage.Complete( err );
+    }
+
+/*---------------------------------------------------------------------------*/
+
+void CHtiBtCommServerSession::PanicClient(TInt aPanic) const
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: PanicClient(): %d"), aPanic))
+    LOGFW(WarnLog(_L("CHtiBtCommServerSession: PanicClient(): %d. NOT IMPLEMENTED"), aPanic))
+    aPanic = aPanic;
+    // should be done with RMessage2?
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::ResetAll(TInt aCompletionCode)
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: ResetAll()")))
+    if ( !iWriteRequestComplete )
+        iWriteRequest.Complete( aCompletionCode );
+    if ( !iReadRequestComplete )
+        iReadRequest.Complete( aCompletionCode );
+    if ( !iConnectRequestComplete )
+        iConnectRequest.Complete( aCompletionCode ); // error when making connection
+    iWriteRequestComplete = ETrue;
+    iReadRequestComplete = ETrue;
+    iConnectRequestComplete = ETrue;
+    delete iIncomingDataBuf;
+    iIncomingDataBuf = NULL;
+    delete iSendBuffer;
+    iSendBuffer = NULL;
+    iIncomingDataBuf = HBufC8::New(KIncomingDataBufSize);
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: ResetAll(): Done")))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::ConnectedToServer(TInt aError)
+    {
+    // Connected to server. Reading has been started.
+    LOGFW(InfoLog(_L("CHtiBtCommServerSession: ConnectedToServer: connected to remote host")))
+    iConnectRequestComplete = ETrue;
+    iConnectRequest.Complete( aError );
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::DisconnectedFromServer()
+    {
+    LOGFW(InfoLog(_L("CHtiBtCommServerSession: DisconnectedFromServer: disconnected from remote host")))
+    ResetAll( KErrDisconnected );
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::DataFromServer(const TDesC8& aData)
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: DataFromServer: %d bytes"), aData.Length()))
+    TPtr8 ptr = iIncomingDataBuf->Des();
+    if ( aData.Length() > ptr.MaxLength() - ptr.Length() )
+        PanicClient( KErrUnderflow ); // Client is reading too slowly
+
+    ptr.Append( aData );
+    TryCompleteReadRequest();
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: DataFromServer: done"), aData.Length()))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::AllBufferedDataSent()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: AllBufferedDataSent")))
+    if ( !iWriteRequestComplete )
+        {
+        // iBtClient has sent all of its data and is ready to send more.
+        TPtr8 ptr = iSendBuffer->Des();
+        TRAPD( err, iBtClient->SendL( ptr ); )
+        iWriteRequest.Complete( err );
+        iWriteRequestComplete = ETrue;
+        delete iSendBuffer;
+        iSendBuffer = NULL;
+        }
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: AllBufferedDataSent: Done")))
+    }
+
+/*---------------------------------------------------------------------------*/
+void CHtiBtCommServerSession::TryCompleteReadRequest()
+    {
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: TryCompleteReadRequest")))
+    TPtr8 ptr = iIncomingDataBuf->Des();
+
+    if ( iReadRequestComplete || ptr.Length() == 0 )
+        {
+        LOGFW(DebugLog(_L("CHtiBtCommServerSession: TryCompleteReadRequest: Nothing to complete")))
+        return; // No outstanding client request to complete
+        }
+
+    TInt dataMaxLength = (TUint16)iReadRequest.GetDesMaxLength(0); //first message slot
+    TPtrC8 dataToClient = ptr.Left(dataMaxLength);
+    TRAPD(err, iReadRequest.WriteL(0, dataToClient);)
+
+    ptr.Delete(0, dataToClient.Length());
+    iReadRequest.Complete(err);
+    iReadRequestComplete = ETrue;
+    LOGFW(DebugLog(_L("CHtiBtCommServerSession: TryCompleteReadRequest: Done")))
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/HtiBtCommServer/src/Logger.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,201 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logger implementation.
+*
+*/
+
+
+// INCLUDE FILES
+#include "Logger.h"
+#include <f32file.h>
+
+#ifdef __ENABLE_LOGGING__
+
+// CONSTANTS
+_LIT(KDebugStr, "DEBUG: ");
+_LIT(KInfoStr,  "INFO:  ");
+_LIT(KWarnStr,  "WARN:  ");
+_LIT(KErrStr,   "ERROR: ");
+
+
+/*---------------------------------------------------------------------------*/
+void LogBytes( const TDesC8& aData, TInt aMaxBytesToLog )
+    {
+    TInt i = 0;
+    while ( i < aData.Length() && i < aMaxBytesToLog )
+        {
+        TBuf<64> hexbuf;
+        TBuf<32> stringbuf;
+        TInt k=0;
+        while ( i < aMaxBytesToLog && i < aData.Length() && k < 16 )
+            {
+            const TUint8 uint8 = aData[i];
+            hexbuf.AppendFormat( _L( "%02X "), uint8 );
+
+            if ( uint8 == '%' )
+                {
+                stringbuf.Append( _L( "%%" ) ); // escape character in format string
+                }
+            else if ( uint8 < 32 || uint8 > 126 )
+                {
+                stringbuf.Append( _L(".") );
+                }
+            else
+                {
+                stringbuf.Append( ( TChar ) uint8 );
+                }
+            i++;
+            k++;
+            }
+        TBuf<128> finalbuf;
+        finalbuf.Copy( hexbuf );
+        finalbuf.Append( _L(" | " ) );
+        finalbuf.Append( stringbuf );
+        DebugLog( finalbuf );
+        }
+    }
+
+/*---------------------------------------------------------------------------*/
+class TOverflowHandler : public TDes16Overflow
+    {
+    void Overflow( TDes16& aDes )
+        {
+        TBuf<KLogEntryMaxLength> logString( _L("LOG ERROR: overflow: ") );
+        logString.Append( aDes.Left(
+            KLogEntryMaxLength - logString.Length() ) );
+        aDes.Copy( logString );
+        }
+    };
+
+/*---------------------------------------------------------------------------*/
+// Usage example: DOLOG(_L("Logstring"));
+void DebugLog( TRefByValue<const TDesC> aFmt, ... )
+    {
+    VA_LIST list;
+    VA_START( list, aFmt );
+    Log( KLogLevelDebug, aFmt, list );
+    }
+
+/*---------------------------------------------------------------------------*/
+void InfoLog( TRefByValue<const TDesC> aFmt, ... )
+    {
+    VA_LIST list;
+    VA_START( list, aFmt );
+    Log( KLogLevelInfo, aFmt, list );
+    }
+
+/*---------------------------------------------------------------------------*/
+void WarnLog( TRefByValue<const TDesC> aFmt, ... )
+    {
+    VA_LIST list;
+    VA_START( list, aFmt );
+    Log( KLogLevelWarning, aFmt, list );
+    }
+
+/*---------------------------------------------------------------------------*/
+void ErrLog( TRefByValue<const TDesC> aFmt, ...)
+    {
+    VA_LIST list;
+    VA_START( list, aFmt );
+    Log( KLogLevelError, aFmt, list );
+    }
+
+/*---------------------------------------------------------------------------*/
+void Log( TInt aLevel, TRefByValue<const TDesC> aText, VA_LIST list )
+    {
+
+    if ( aLevel < KMinimumLogLevel )
+        return;
+
+    _LIT( KLineFeed, "\n" );
+
+    /**
+     *  Log time format (see TTime) is
+     *  Day-Month-Year Hours:Minutes:Seconds:Milliseconds
+     *
+     *  Example: 30-12-2004 23:00:55:990
+     */
+    _LIT( KLogTimeFormat, "%F%D-%M-%Y %H:%T:%S:%*C3" );
+
+    TBuf8<KLogEntryMaxLength> writeBuffer;
+    TBuf16<KLogEntryMaxLength> logEntry;
+    RFs FileServer;
+    RFile File;
+
+    if ( FileServer.Connect() != KErrNone )
+        {
+        FileServer.Close(); // just in case
+        User::Panic( KLogPanicCategory(), KPanicFsConnectFailed );
+        return;
+        }
+
+    // Open file for writing, if exists. Othervise create new file.
+    if ( File.Open( FileServer, KLogFileName(), EFileWrite ) != KErrNone )
+        {
+        if ( File.Create( FileServer, KLogFileName(), EFileWrite )
+            != KErrNone )
+            {
+            FileServer.Close();
+            User::Panic( KLogPanicCategory(), KPanicFileCreateFailed );
+            }
+        }
+
+    TTime currentTime;
+    currentTime.UniversalTime();
+    TBuf<32> timeString;
+
+    // currentTime is now in universal time. Convert it to home time.
+    TLocale locale;
+    TTimeIntervalSeconds universalTimeOffset( locale.UniversalTimeOffset() );
+    TTimeIntervalHours daylightSaving( 0 );
+    if ( locale.QueryHomeHasDaylightSavingOn() )
+        {
+        daylightSaving = 1;
+        }
+    currentTime = currentTime + universalTimeOffset + daylightSaving;
+    currentTime.FormatL( timeString, KLogTimeFormat );
+
+    // Add LogString to the end of file and close the file
+    TInt currentSize = 0, returnCode;
+    writeBuffer.Append( timeString );
+    writeBuffer.Append( _L(": ") );
+
+    if ( aLevel < KLogLevelInfo )
+        writeBuffer.Append(KDebugStr);
+    else if ( aLevel < KLogLevelWarning )
+        writeBuffer.Append(KInfoStr);
+    else if ( aLevel < KLogLevelError )
+        writeBuffer.Append(KWarnStr);
+    else
+        writeBuffer.Append(KErrStr);
+
+    logEntry.AppendFormatList( aText, list ); //, &overFlowHandler );
+    writeBuffer.Append( logEntry.Left(
+        KLogEntryMaxLength - writeBuffer.Length() ) );
+    writeBuffer.Append( KLineFeed );
+    File.Size( currentSize );
+    returnCode = File.Write( currentSize,
+                             writeBuffer,
+                             writeBuffer.Length() );
+    File.Close();
+    // Close file server session
+    FileServer.Close();
+
+    if ( returnCode != KErrNone )
+        {
+        User::Panic( KLogPanicCategory(), KPanicFileWriteFailed );
+        }
+    }
+
+#endif // __ENABLE_LOGGING__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/eabi/HtiBtCommInterfaceu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,14 @@
+EXPORTS
+	_ZN19RHtiBtCommInterface10CancelSendEv @ 1 NONAME
+	_ZN19RHtiBtCommInterface13CancelReceiveEv @ 2 NONAME
+	_ZN19RHtiBtCommInterface4SendERK6TDesC8R14TRequestStatus @ 3 NONAME
+	_ZN19RHtiBtCommInterface5CloseEv @ 4 NONAME
+	_ZN19RHtiBtCommInterface7ConnectER6TDesC8i @ 5 NONAME
+	_ZN19RHtiBtCommInterface7ReceiveER5TDes8R14TRequestStatus @ 6 NONAME
+	_ZN19RHtiBtCommInterfaceC1Ev @ 7 NONAME
+	_ZN19RHtiBtCommInterfaceC2Ev @ 8 NONAME
+	_ZNK19RHtiBtCommInterface13GetPortNumberEv @ 9 NONAME
+	_ZNK19RHtiBtCommInterface17GetSendBufferSizeEv @ 10 NONAME
+	_ZNK19RHtiBtCommInterface20GetReceiveBufferSizeEv @ 11 NONAME
+	_ZNK19RHtiBtCommInterface7VersionEv @ 12 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/eabi/HtiBtCommServeru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,7 @@
+EXPORTS
+	_Z11StartThreadv @ 1 NONAME
+	_ZTI16CHtiBtCommServer @ 2 NONAME ; #<TI>#
+	_ZTI23CHtiBtCommServerSession @ 3 NONAME ; #<TI>#
+	_ZTV16CHtiBtCommServer @ 4 NONAME ; #<VT>#
+	_ZTV23CHtiBtCommServerSession @ 5 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/eabi/HtiBtSerialComHelperu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,32 @@
+EXPORTS
+	_ZN15CBtSerialClient10ConnectingEv @ 1 NONAME
+	_ZN15CBtSerialClient10DisconnectEv @ 2 NONAME
+	_ZN15CBtSerialClient10ReadAsyncLEv @ 3 NONAME
+	_ZN15CBtSerialClient11ServicePortEv @ 4 NONAME
+	_ZN15CBtSerialClient14ServerAddressLEv @ 5 NONAME
+	_ZN15CBtSerialClient17SendBufferMaxSizeEv @ 6 NONAME
+	_ZN15CBtSerialClient21FreeSpaceInSendBufferEv @ 7 NONAME
+	_ZN15CBtSerialClient4NewLER23MBtSerialClientObserver @ 8 NONAME
+	_ZN15CBtSerialClient5SendLERK6TDesC8 @ 9 NONAME
+	_ZN15CBtSerialClient8ConnectLE10TBTDevAddri @ 10 NONAME
+	_ZN15CBtSerialClient8ConnectLERK7TDesC16i @ 11 NONAME
+	_ZN15CBtSerialClient8ConnectLEv @ 12 NONAME
+	_ZN15CBtSerialClient9ConnectedEv @ 13 NONAME
+	_ZN15CBtSerialClientD0Ev @ 14 NONAME
+	_ZN15CBtSerialClientD1Ev @ 15 NONAME
+	_ZN15CBtSerialClientD2Ev @ 16 NONAME
+	_ZTI13CTimeOutTimer @ 17 NONAME ; #<TI>#
+	_ZTI14CSocketsReader @ 18 NONAME ; #<TI>#
+	_ZTI14CSocketsWriter @ 19 NONAME ; #<TI>#
+	_ZTI15CBtSerialClient @ 20 NONAME ; #<TI>#
+	_ZTI18CBTServiceSearcher @ 21 NONAME ; #<TI>#
+	_ZTI19TSdpAttributeParser @ 22 NONAME ; #<TI>#
+	_ZTI23CMessageServiceSearcher @ 23 NONAME ; #<TI>#
+	_ZTV13CTimeOutTimer @ 24 NONAME ; #<VT>#
+	_ZTV14CSocketsReader @ 25 NONAME ; #<VT>#
+	_ZTV14CSocketsWriter @ 26 NONAME ; #<VT>#
+	_ZTV15CBtSerialClient @ 27 NONAME ; #<VT>#
+	_ZTV18CBTServiceSearcher @ 28 NONAME ; #<VT>#
+	_ZTV19TSdpAttributeParser @ 29 NONAME ; #<VT>#
+	_ZTV23CMessageServiceSearcher @ 30 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtComm.cfg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,12 @@
+# HTIBtComm communication plugin configuration file
+
+# Following parameters configure the PC where HTI will try to connect.
+# Define only one of them, either PC's Bluetooth name or Bluetooth address.
+# If both are defined, address will be used and name is ignored.
+# If neither is defined the device selection dialog will be shown and user
+# has to select the device where to connect.
+#
+# The BtDeviceAddress must be 12 hex characters.
+
+#BtDeviceName=MyComputer
+#BtDeviceAddress=01A2B3C4D5EF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtCommEcomPlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM Plugin project to support communication over serial port
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiBtCommEcomPlugin.dll
+TARGETTYPE      PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID             0x10009D8D 0x200212CB
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../HtiBtCommEcomPlugin/src
+SOURCE          proxy.cpp
+SOURCE          HtiBtCommEcomPlugin.cpp
+
+USERINCLUDE     ../HtiBtCommEcomPlugin/inc ../BtEngine/inc ../HtiBtCommServer/inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/200212CB.rss
+TARGET          HtiBtCommEcomPlugin.rsc
+END
+
+LIBRARY         euser.lib
+LIBRARY         ecom.lib
+LIBRARY         c32.lib
+LIBRARY         hticfg.lib
+LIBRARY         htibtcomminterface.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtCommInterface.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiBtCommInterface. Client interface to HtiBtCommServer
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiBtCommInterface.dll
+TARGETTYPE      DLL
+
+UID             0x200212D2
+DEFFILE         HtiBtCommInterface.def
+
+VENDORID       0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../HtiBtCommServer/src
+SOURCE          HtiBtCommInterface.cpp
+
+USERINCLUDE     ../HtiBtCommServer/inc
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         htibtcommserver.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtCommServer.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiBtCommServer DLL project
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiBtCommServer.dll
+TARGETTYPE      DLL
+
+UID             0x200212D1
+DEFFILE         HtiBtCommServer.def
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../HtiBtCommServer/src
+SOURCE          HtiBtCommServer.cpp
+SOURCE          HtiBtCommServerSession.cpp
+SOURCE          Logger.cpp
+
+USERINCLUDE     ../HtiBtCommServer/inc  ../BtEngine/inc
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         efsrv.lib
+LIBRARY         bluetooth.lib
+LIBRARY         HtiBtSerialComHelper.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/group/HtiBtSerialComHelper.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiBtSerialComHelper project definition.
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiBtSerialComHelper.dll
+TARGETTYPE      DLL
+
+UID             0x1000008d 0x200212D3
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../BtEngine/src
+SOURCE          timeouttimer.cpp
+SOURCE          socketsreader.cpp
+SOURCE          socketswriter.cpp
+SOURCE          BtSerialClient.cpp
+SOURCE          messageservicesearcher.cpp
+SOURCE          btservicesearcher.cpp
+SOURCE          sdpattributeparser.cpp
+
+USERINCLUDE     ../BtEngine/inc
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY         bafl.lib
+LIBRARY         bluetooth.lib
+LIBRARY         btdevice.lib
+LIBRARY         btextnotifiers.lib
+LIBRARY         btmanclient.lib
+LIBRARY         btpowercontrol.lib
+LIBRARY         c32.lib
+LIBRARY         efsrv.lib
+LIBRARY         esock.lib
+LIBRARY         euser.lib
+LIBRARY         flogger.lib
+LIBRARY         sdpagent.lib
+LIBRARY         sdpdatabase.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiBtCommPlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiBtCommPlugin build info
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiBtSerialComHelper.mmp
+HtiBtCommServer.mmp
+HtiBtCommInterface.mmp
+HtiBtCommEcomPlugin.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/BWINS/HtiIPCommInterfaceU.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,12 @@
+EXPORTS
+	??0RHtiIPCommServer@@QAE@XZ @ 1 NONAME ; RHtiIPCommServer::RHtiIPCommServer(void)
+	?CancelReceive@RHtiIPCommServer@@QAEXXZ @ 2 NONAME ; void RHtiIPCommServer::CancelReceive(void)
+	?CancelSend@RHtiIPCommServer@@QAEXXZ @ 3 NONAME ; void RHtiIPCommServer::CancelSend(void)
+	?Close@RHtiIPCommServer@@QAEXXZ @ 4 NONAME ; void RHtiIPCommServer::Close(void)
+	?Connect@RHtiIPCommServer@@QAEHXZ @ 5 NONAME ; int RHtiIPCommServer::Connect(void)
+	?GetReceiveBufferSize@RHtiIPCommServer@@QBEHXZ @ 6 NONAME ; int RHtiIPCommServer::GetReceiveBufferSize(void) const
+	?GetSendBufferSize@RHtiIPCommServer@@QBEHXZ @ 7 NONAME ; int RHtiIPCommServer::GetSendBufferSize(void) const
+	?Receive@RHtiIPCommServer@@QAEXAAVTDes8@@AAVTRequestStatus@@@Z @ 8 NONAME ; void RHtiIPCommServer::Receive(class TDes8 &, class TRequestStatus &)
+	?Send@RHtiIPCommServer@@QAEXABVTDesC8@@AAVTRequestStatus@@@Z @ 9 NONAME ; void RHtiIPCommServer::Send(class TDesC8 const &, class TRequestStatus &)
+	?Version@RHtiIPCommServer@@QBE?AVTVersion@@XZ @ 10 NONAME ; class TVersion RHtiIPCommServer::Version(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/data/200212CD.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for HtiPComm ECOM plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+
+//  RESOURCE DEFINITIONS
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x200212CD;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB8;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x200212CE;
+                    version_no         = 1;
+                    display_name       = "IP comm";
+                    default_data       = "IPCOMM";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/eabi/HtiIPCommInterfaceu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,13 @@
+EXPORTS
+	_ZN16RHtiIPCommServer10CancelSendEv @ 1 NONAME
+	_ZN16RHtiIPCommServer13CancelReceiveEv @ 2 NONAME
+	_ZN16RHtiIPCommServer4SendERK6TDesC8R14TRequestStatus @ 3 NONAME
+	_ZN16RHtiIPCommServer5CloseEv @ 4 NONAME
+	_ZN16RHtiIPCommServer7ConnectEv @ 5 NONAME
+	_ZN16RHtiIPCommServer7ReceiveER5TDes8R14TRequestStatus @ 6 NONAME
+	_ZN16RHtiIPCommServerC1Ev @ 7 NONAME
+	_ZN16RHtiIPCommServerC2Ev @ 8 NONAME
+	_ZNK16RHtiIPCommServer17GetSendBufferSizeEv @ 9 NONAME
+	_ZNK16RHtiIPCommServer20GetReceiveBufferSizeEv @ 10 NONAME
+	_ZNK16RHtiIPCommServer7VersionEv @ 11 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/group/HTIIPComm.cfg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,40 @@
+# HTIIPComm configuration file
+
+# Internet Access Point (IAP) used for creating a connection.
+# IAP can be identified by id or name.
+#
+# If both are defined IAP id will be used.
+
+# Public S60 3rd emulator
+#IAPId=3
+#IAPName=Winsock
+
+# S60 3.x emulator
+# http://s60wiki.nokia.com/S60Wiki/3.0_Emulator_LAN_connection
+IAPName=Ethernet with Daemon Dynamic IP
+
+# S60 3.x hardware
+#IAPName=Easy WLAN
+
+
+# Local port where to start listening for incoming connections.
+#
+# If local port is defined (or set to zero) the comm plugin will start listening
+# for incoming connections and if not it plugin will start connecting
+# to the remote host.
+#
+LocalPort=3000
+
+
+# Remote host & port where to connect.
+#
+#RemoteHost=localhost
+#RemotePort=3000
+
+
+# Timeout in seconds when trying to connect to remote host.
+# If timeout is set to zero there will be no timeout.
+#
+# Default value is 30 seconds
+#
+#ConnectTimeout=30
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/group/HtiIPCommEcomPlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM Plugin project to support communication over IP
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiIPCommEcomPlugin.dll
+TARGETTYPE      PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID             0x10009D8D 0x200212CD
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          proxy.cpp
+SOURCE          HtiIPCommEcomPlugin.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/200212CD.rss
+TARGET          HtiIPCommEcomPlugin.rsc
+END
+
+LIBRARY         euser.lib
+LIBRARY         ecom.lib
+LIBRARY         htiipcommserverclient.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/group/HtiIPCommServer.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiIPCommServer dll project
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET         HtiIPCommServer.exe
+TARGETTYPE     EXE
+
+UID            0x1000008C 0x200212DC
+
+VENDORID       0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH     ../src
+SOURCE         HtiIPCommserver.cpp
+SOURCE         HtiIPCommserverSession.cpp
+SOURCE         HtiConnectionManager.cpp
+SOURCE         HtiSocketMonitor.cpp
+
+USERINCLUDE    ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY        euser.lib
+LIBRARY        commdb.lib
+LIBRARY        esock.lib
+LIBRARY        hticfg.lib
+LIBRARY        insock.lib
+LIBRARY        flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/group/HtiIPCommServerClient.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiIPCommServerClient. Client interface to HtiIPCommServer
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiIPCommServerClient.dll
+TARGETTYPE      DLL
+
+UID             0x200212DB
+DEFFILE         HtiIPCommInterface.def
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          HtiIPCommServerClient.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiIPCommPlugin build info
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+HTIIPComm.cfg   +/winscw/c/HTIIPComm.cfg
+
+PRJ_MMPFILES
+HtiIPCommServer.mmp
+HtiIPCommServerClient.mmp
+HtiIPCommEcomPlugin.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiConnectionManager.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,158 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin to communicate over IP port
+*
+*/
+
+
+#ifndef CHTICONNECTIONMANAGER_H
+#define CHTICONNECTIONMANAGER_H
+
+
+// INCLUDES
+#include <HtiCommPluginInterface.h> // defined in HtiFramework project
+#include <es_sock.h>
+#include <in_sock.h>
+#include <commdbconnpref.h>
+
+#include "HtiIPCommServerCommon.h"
+#include "HtiSocketMonitor.h"
+#include "HtiIPCommServer.h"
+
+
+// FORWARD DECLARATIONS
+class CHtiIPCommServer;
+class CHtiCfg;
+
+// CLASS DECLARATION
+
+class MHtiTimerObserver
+{
+public:
+    virtual void TimerExpiredL() = 0;
+};
+
+
+class CHtiTimer : public CTimer
+{
+public:
+    static CHtiTimer* NewL( MHtiTimerObserver& aObserver );
+    virtual ~CHtiTimer();
+
+protected: // From CActive
+    void RunL();
+    TInt RunError(TInt aError);
+
+private:
+    CHtiTimer( MHtiTimerObserver& aObserver );
+    void ConstructL();
+
+private:
+    MHtiTimerObserver& iObserver;
+};
+
+
+class CHtiConnectionManager : public CActive,
+                              public MHtiSocketObserver,
+                              public MHtiTimerObserver
+{
+public:
+    enum TConnectionstate {
+        EStartingIAP,
+        EWaitingConnection,
+        EConnecting,
+        EConnected,
+        EDisconnecting,
+        EDisconnected
+    };
+
+    static CHtiConnectionManager* NewL( CHtiIPCommServer* aServer );
+    ~CHtiConnectionManager();
+
+    void Receive( const RMessage2& aMessage );
+    void Send( const RMessage2& aMessage );
+    void CancelReceive();
+    void CancelSend();
+
+private:
+    CHtiConnectionManager( CHtiIPCommServer* aServer );
+    void ConstructL();
+
+    // Config file reading separated to 2 parts because
+    // ReadConnectionConfigL might need dns resolver and
+    // that should be done after the IAP is started...
+    void ReadIAPConfigL();
+    void ReadConnectionConfigL();
+
+    void ReadSocket();
+    void WriteSocket();
+
+    void StartConnectingL();
+    void StartListeningL();
+
+    /*
+     *  Cancels all outstanding server session requests
+     */
+    void CancelAllRequests();
+
+    void ShowErrorNotifierL( const TDesC& aText, TInt aErr = KErrGeneral );
+
+protected: // From CActive
+    void RunL();
+    void DoCancel();
+    TInt RunError(TInt aError);
+
+public: // MHtiTimerObserver
+    void TimerExpiredL();
+
+public: // MHtiSocketObserver
+    void ReportComplete( MHtiSocketObserver::TRequestType aType, TInt aError );
+
+
+
+private:
+    CHtiIPCommServer*   iServer;
+
+    CHtiCfg*            iCfg;
+    TUint32             iIAPId;
+
+    TInt                iListenPort;
+    TInetAddr           iRemoteHost;
+
+    RSocketServ         iSocketServ;
+    RConnection         iConnection;
+    RSocket             iDataSocket;
+    RSocket             iListenSocket;
+    TSockXfrLength      iRecvLen;
+    TConnectionstate    iState;
+
+    RMessage2           iReceiveRequest;
+    RMessage2           iSendRequest;
+
+    TBool               iReceiveRequestComplete;
+    TBool               iSendRequestComplete;
+
+    CHtiSocketMonitor*  iSendMonitor;
+    CHtiSocketMonitor*  iReceiveMonitor;
+
+    CHtiTimer*          iConnectTimer;
+    TInt                iConnectTimeout;
+
+    TBuf8<KIPCommServerReceiveBufferMaxSize> iReceiveBuffer;
+    TBuf8<KIPCommServerSendBufferMaxSize>    iSendBuffer;
+    
+    TCommDbConnPref     iConnPref;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommEcomPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,114 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin to communicate over IP port
+*
+*/
+
+
+#ifndef CHTIIPCOMMECOMPLUGIN_H
+#define CHTIIPCOMMECOMPLUGIN_H
+
+
+// INCLUDES
+#include <HtiCommPluginInterface.h> // defined in HtiFramework project
+#include "HtiIPCommServerClient.h"
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+/**
+* ECOM plugin module for communicating with PC using IP port.
+*
+*/
+class CHtiIPCommEcomPlugin :
+    public CHTICommPluginInterface
+    {
+public:
+
+    /**
+    * Create instance of plugin.
+    * Reads configuration, opens and initializes IP connection.
+    * @return Plugin instance.
+    */
+    static CHtiIPCommEcomPlugin* NewL();
+
+    /**
+    * Destructor.
+    */
+    ~CHtiIPCommEcomPlugin();
+
+public: // Interface implementation
+
+    /**
+    * Receive data from IP port.
+    * The size of supplied buffer must equal to size given
+    * by GetReceiveBufferSize.
+    * The number of received bytes may be anything between 1
+    * and GetReceiveBufferSize.
+    *
+    * @param aRawdataBuf Buffer where the result is written
+    * @param aStatus Request status
+    */
+    void Receive( TDes8& aRawdataBuf, TRequestStatus& aStatus );
+
+    /**
+    * Send data to IP port. The size of data must not
+    * exceed GetSendBufferSize.
+    * @param aRawdataBuf Buffer where the data is read from.
+    * @param aStatus Request status
+    */
+    void Send( const TDesC8& aRawdataBuf, TRequestStatus& aStatus );
+
+    /**
+    * Cancel read operation
+    */
+    void CancelReceive();
+
+    /**
+    * Cancel send operation
+    */
+    void CancelSend();
+
+    /**
+     *  Return required buffer size for Send operation.
+     */
+    TInt GetSendBufferSize();
+
+    /**
+     *  Return required buffer size for Receive operation.
+     */
+    TInt GetReceiveBufferSize();
+
+private:
+
+    /**
+    * Constructor of this plugin.
+    */
+    CHtiIPCommEcomPlugin();
+
+    /**
+    * Second phase construction.
+    */
+    void ConstructL();
+
+    /**
+    * Load configuration file.
+    */
+    void LoadConfigL();
+
+private: // Data
+    RHtiIPCommServer iHtiIPCommServer;
+    };
+
+#endif // CHTIIPCOMMECOMPLUGIN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommLogging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logging macros
+*
+*/
+
+
+#ifndef HTIIPCOMMLOGGING_H
+#define HTIIPCOMMLOGGING_H
+
+#define LOG_HTI_FLOW
+
+#ifdef __ENABLE_LOGGING__
+
+#include <flogger.h>
+
+_LIT(KLogFolder, "hti");
+_LIT(KLogFile, "HtiIPComm_log.txt");
+_LIT(KFreeMemFormat, "Total free: %d bytes");
+_LIT(KFreeHeapMemFormat, "Heap available: %d bytes, biggest %d bytes");
+_LIT(KAllocHeapMemFormat, "Heap alloc: %d bytes, %d cells");
+
+#define HTI_LOG_TEXT(a1) {_LIT(temp, a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#define HTI_LOG_DES(a1) {RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, (a1));}
+#define HTI_LOG_FORMAT(a1,a2) {_LIT(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, (a2));}
+#define HTI_LOG_HEX(p,l) {RFileLogger::HexDump(KLogFolder, KLogFile, EFileLoggingModeAppend, NULL, NULL, p, l);}
+
+#define HTI_LOG_FREE_MEM() {TMemoryInfoV1Buf info;UserHal::MemoryInfo(info);RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KFreeMemFormat, info().iFreeRamInBytes);}
+#define HTI_LOG_FREE_HEAP_MEM() {TInt b;TInt free=User::Available(b);RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KFreeHeapMemFormat, free, b);}
+#define HTI_LOG_ALLOC_HEAP_MEM() {TInt b;TInt c = User::AllocSize(b);RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KAllocHeapMemFormat, b, c);}
+
+//define separately macros to track function flow
+#ifdef LOG_HTI_FLOW
+_LIT8(KFuncIn, "-=> %S");
+_LIT8(KFuncOut, "<=- %S");
+
+#define HTI_LOG_FUNC_IN(a1) {_LIT8(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KFuncIn, &temp);}
+#define HTI_LOG_FUNC_OUT(a1) {_LIT8(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KFuncOut, &temp);}
+
+#else // LOG_HTI_FLOW
+
+#define HTI_LOG_FUNC_IN(a1)
+#define HTI_LOG_FUNC_OUT(a1)
+
+#endif // LOG_HTI_FLOW
+
+
+#else // __ENABLE_LOGGING__
+
+#define HTI_LOG_TEXT(a1)
+#define HTI_LOG_DES(a1)
+#define HTI_LOG_FORMAT(a1,a2)
+#define HTI_LOG_HEX(p,l)
+
+#define HTI_LOG_FREE_MEM()
+#define HTI_LOG_FREE_HEAP_MEM()
+#define HTI_LOG_ALLOC_HEAP_MEM()
+
+#define HTI_LOG_FUNC_IN(a1)
+#define HTI_LOG_FUNC_OUT(a1)
+
+#endif // __ENABLE_LOGGING__
+
+#endif  //HTIIPCOMMLOGGING_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommServer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CHtiIPCommServer declaration
+*
+*/
+
+
+#ifndef __HTIIPCOMMSERVER_H__
+#define __HTIIPCOMMSERVER_H__
+
+//  INCLUDES
+
+#include <e32def.h>
+#include <e32base.h>
+
+#include "HtiConnectionManager.h"
+#include "HtiIPCommServerSession.h"
+
+//  CONSTANTS
+
+// Reasons for IPCommServer panic
+enum TIPCommServerPanic
+    {
+    EBadDescriptor = 1,
+    EUnknownCompletion,
+    EUnknownState
+    };
+
+//  FUNCTION PROTOTYPES
+
+// Function to panic the server
+//GLREF_C void PanicServer(TIPCommServerPanic aPanic);
+
+
+//  FORWARD DECLARATIONS
+class CHtiConnectionManager;
+
+// CLASS DECLARATION
+
+
+class CHtiIPCommServer : public CServer2
+{
+public:
+    static CHtiIPCommServer* NewLC();
+
+    /**
+     * Used to inform the server that session has been created
+     */
+    void SessionOpened();
+
+    /**
+     * Used to inform the server that session has been closed
+     */
+    void SessionClosed();
+
+    void CloseServer();
+
+private:
+    CHtiIPCommServer();
+
+    ~CHtiIPCommServer();
+
+    void ConstructL();
+
+   /**
+    * Creates a new client session
+    * @param aVersion Version of the server
+    * @return Pointer to the clinet session
+    */
+    CSession2* NewSessionL( const TVersion& aVersion, const RMessage2& aMessage) const;
+
+public:
+    CHtiConnectionManager* iConnectionManager;
+
+    // Used to prevent stopping active scheduler twice
+    TBool iRunning;
+
+private:
+    TInt  iNrOfSessions;
+};
+
+#endif // __HTIIPCOMMSERVER_H__
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommServerClient.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Client side interface to HtiIPCommServer
+*
+*/
+
+
+#ifndef __HTIIPCOMMSERVERCLIENT_H__
+#define __HTIIPCOMMSERVERCLIENT_H__
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+class RHtiIPCommServer : public RSessionBase
+{
+public: // Constructor and destructor
+    IMPORT_C RHtiIPCommServer();
+
+public:
+    IMPORT_C TInt Connect();
+    IMPORT_C void Close();
+    IMPORT_C TVersion Version() const;
+
+    IMPORT_C void Receive( TDes8& aData, TRequestStatus& aStatus );
+    IMPORT_C void Send( const TDesC8& aData,TRequestStatus& aStatus );
+
+    IMPORT_C void CancelReceive();
+    IMPORT_C void CancelSend();
+
+    IMPORT_C TInt GetSendBufferSize() const;
+    IMPORT_C TInt GetReceiveBufferSize() const;
+};
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommServerCommon.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Global definitions for IPCommServer and client side interface.
+*
+*/
+
+
+#ifndef __HTIIPCOMMSERVERCOMMON_H__
+#define __HTIIPCOMMSERVERCOMMON_H__
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+
+// The server name (and server thread name)
+_LIT( KIPCommServerName, "HtiIPCommServer" );
+const TUid KIPCommServerUid3={0x200212DC};
+
+// The version of the server
+const TUint KIPCommServerMajorVersionNumber = 1;
+const TUint KIPCommServerMinorVersionNumber = 0;
+const TUint KIPCommServerBuildVersionNumber = 0;
+
+// "Hihavakiot"
+const TInt KIPCommServerReceiveBufferMaxSize = 0x1000; // 4096 bytes
+const TInt KIPCommServerSendBufferMaxSize    = 0x1000; // 4096 bytes
+
+
+// DATA TYPES
+
+// The message ID's of IPCommServer
+// from Symbian side
+enum TIPCommServerRqst
+    {
+    EIPCommServerRecv,
+    EIPCommServerSend,
+    EIPCommServerCancelRecv,
+    EIPCommServerCancelSend
+    };
+
+
+#endif // __HTIIPCOMMCLIENTSERVERCOMMON_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiIPCommServerSession.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Server side session in HtiIPCommServer.
+*
+*/
+
+
+#ifndef CHTIIPCOMMSERVERSESSION_H
+#define CHTIIPCOMMSERVERSESSION_H
+
+//  INCLUDES
+
+#include <e32std.h>
+#include <e32base.h>
+
+#include "HtiIPCommServer.h"
+#include "HtiConnectionManager.h"
+
+// FORWARD DECLARATIONS
+class CHtiIPCommServer;
+
+
+// CLASS DECLARATION
+class CHtiIPCommServerSession : public CSession2
+    {
+public:
+    /**
+    * Constructor
+    *
+    * @param aServer Pointer to server instance
+    */
+    CHtiIPCommServerSession( CHtiIPCommServer* aServer );
+
+private:
+
+    /**
+    * Destructor
+    */
+    ~CHtiIPCommServerSession();
+
+    /**
+    * Receives all server command and directs them to
+    * their handlers.
+    *
+    * @param aMessage Message to process
+    */
+    void ServiceL( const RMessage2& aMessage );
+
+    /**
+    * Receives data from socket
+    *
+    * @param aMessage Message containing a descriptor where data is received
+    */
+    void HandleReceiveRequestL( const RMessage2& aMessage );
+
+    /**
+    * Sends data to socket
+    *
+    * @param aMessage Message containing a descriptor of the data to send
+    */
+    void HandleSendRequestL( const RMessage2& aMessage );
+
+    /**
+    * Cancels pending Receive request on server.
+    */
+    void HandleCancelReceiveRequestL( const RMessage2& aMessage );
+
+    /**
+    * Cancels pending Send request on server.
+    */
+    void HandleCancelSendRequestL( const RMessage2& aMessage );
+
+private:
+    /**
+    * Server pointer for calling callbacks functions
+    * and connection manager
+    */
+    CHtiIPCommServer* iServer;
+    };
+
+#endif // CHTIIPCOMMSERVERSESSION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/inc/HtiSocketMonitor.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,66 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin to communicate over IP port
+*
+*/
+
+
+#ifndef CHTISOCKETS_H
+#define CHTISOCKETS_H
+
+
+// INCLUDES
+#include <HtiCommPluginInterface.h> // defined in HtiFramework project
+
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+class MHtiSocketObserver
+{
+public:
+    enum TRequestType
+    {
+    EReadSocket,
+    EWriteSocket
+    };
+
+    virtual void ReportComplete( MHtiSocketObserver::TRequestType aType, TInt aError ) = 0;
+};
+
+
+class CHtiSocketMonitor : public CActive
+{
+public:
+    static CHtiSocketMonitor* NewL( MHtiSocketObserver::TRequestType aType, MHtiSocketObserver* aObserver );
+    void Activate();
+    ~CHtiSocketMonitor();
+
+private:
+    CHtiSocketMonitor( MHtiSocketObserver::TRequestType aType, MHtiSocketObserver* aObserver );
+    void ConstructL();
+
+public: // CActive interface
+    void RunL();
+    void DoCancel();
+    TInt RunError(TInt aError);
+
+private:
+    MHtiSocketObserver::TRequestType iType;
+    MHtiSocketObserver* iObserver;
+};
+
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiConnectionManager.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,853 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin for communication over IP port
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiIPCommEcomPlugin.h"
+#include "HtiConnectionManager.h"
+#include "HtiCfg.h"
+#include "HtiIPCommLogging.h"
+
+#include <commdb.h>             // CCommsDatabase
+#include <HtiCfg.h>
+
+
+// CONSTANTS
+const static TInt KMaxHtiNotifierLength = 128;
+
+_LIT( KHtiIPCommError, "HtiIpCommError" );
+_LIT( KHtiOkButton, "OK" );
+
+_LIT( KHtiCfgPath,      "\\" ); // root of drive
+_LIT( KHtiIPCommCfg,    "HTIIPComm.cfg" );
+_LIT8( KIAPId,          "IAPId" );
+_LIT8( KIAPName,        "IAPName" );
+_LIT8( KLocalPort,      "LocalPort" );
+_LIT8( KRemoteHost,     "RemoteHost" );
+_LIT8( KRemotePort,     "RemotePort" );
+_LIT8( KConnectTimeout, "ConnectTimeout" );
+
+
+void LogLocalHost( RSocket& aSocket )
+    {
+#ifdef __ENABLE_LOGGING__
+    // print the local ip to log
+    HTI_LOG_TEXT( "LocalHost:" );
+    TBuf<0x20> tmp;
+    TInetAddr localHost;
+    aSocket.LocalName( localHost );
+    localHost.Output( tmp );
+    tmp.AppendFormat( _L(":%d"), localHost.Port() );
+    HTI_LOG_DES( tmp );
+#else
+    aSocket.LocalPort();  // avoid compiler warning
+#endif
+    }
+
+void LogRemoteHost( RSocket& aSocket )
+    {
+#ifdef __ENABLE_LOGGING__
+    // print the local ip to log
+    HTI_LOG_TEXT( "RemoteHost:" );
+    TBuf<0x20> tmp;
+    TInetAddr remoteHost;
+    aSocket.RemoteName( remoteHost );
+    remoteHost.Output( tmp );
+    tmp.AppendFormat( _L(":%d"), remoteHost.Port() );
+    HTI_LOG_DES( tmp );
+#else
+    aSocket.LocalPort();  // avoid compiler warning
+#endif
+    }
+
+
+CHtiConnectionManager* CHtiConnectionManager::NewL( CHtiIPCommServer* aServer )
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::NewL" );
+    CHtiConnectionManager* self = new (ELeave) CHtiConnectionManager( aServer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::NewL" );
+    return self;
+    }
+
+CHtiConnectionManager::CHtiConnectionManager( CHtiIPCommServer* aServer ):
+    CActive( EPriorityStandard ),
+    iServer( aServer ),
+    iCfg( NULL ),
+    iListenPort( 0 ),
+    iState( EDisconnected ),
+    iReceiveRequestComplete( ETrue ),
+    iSendRequestComplete( ETrue ),
+    iSendMonitor( NULL ),
+    iReceiveMonitor( NULL ),
+    iConnectTimer( NULL )
+    {
+    iReceiveBuffer.Zero();
+    iSendBuffer.Zero();
+    CActiveScheduler::Add(this);
+    }
+
+CHtiConnectionManager::~CHtiConnectionManager()
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::~CHtiConnectionManager" );
+
+    if ( iCfg )
+        delete iCfg;
+
+    if ( iConnectTimer )
+        delete iConnectTimer;
+
+    if ( iDataSocket.SubSessionHandle() )
+        iDataSocket.Close();
+
+    if ( iListenSocket.SubSessionHandle() )
+        iListenSocket.Close();
+
+    if ( iSendMonitor )
+        delete iSendMonitor;
+
+    if ( iReceiveMonitor )
+        delete iReceiveMonitor;
+
+    if ( iConnection.SubSessionHandle() )
+        iConnection.Close();
+
+    if ( iSocketServ.Handle() )
+        iSocketServ.Close();
+
+    // NOTE: If this is done in the beginning the server will never die!
+    Cancel();
+
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::~CHtiConnectionManager" );
+    }
+
+
+void CHtiConnectionManager::ConstructL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::ConstructL" );
+
+    // Load configuration file
+    iCfg = CHtiCfg::NewL();
+    TRAPD( err, iCfg->LoadCfgL( KHtiCfgPath, KHtiIPCommCfg ) );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "LoadCfgL err %d", err );
+        ShowErrorNotifierL( _L( "Could not load config file" ), err );
+        User::Leave( err );
+        }
+
+    // Get IAP
+    ReadIAPConfigL();
+
+    // Create monitors and timers
+    iSendMonitor    = CHtiSocketMonitor::NewL( MHtiSocketObserver::EWriteSocket, this);
+    iReceiveMonitor = CHtiSocketMonitor::NewL( MHtiSocketObserver::EReadSocket, this);
+    iConnectTimer   = CHtiTimer::NewL( *this );
+
+    // Open socket server
+    err = iSocketServ.Connect();
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "error connecting to socket server %d", err);
+        User::Leave( err );
+        }
+
+/*
+    HTI_LOG_TEXT( "Supported protocols:" );
+    TUint numOfProtocols;
+    iSocketServ.NumProtocols( numOfProtocols );
+    for ( TInt i = 1; i <= numOfProtocols; i++ )
+        {
+        TProtocolDesc desc;
+        iSocketServ.GetProtocolInfo( i, desc  );
+        HTI_LOG_DES( desc.iName );
+        HTI_LOG_FORMAT( "AddrFamily : %d", desc.iAddrFamily );
+        HTI_LOG_FORMAT( "SockType   : %d", desc.iSockType );
+        HTI_LOG_FORMAT( "Protocol   : %d", desc.iProtocol );
+        }
+*/
+
+    // Start IAP
+    err = iConnection.Open( iSocketServ );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "error opening connection %d", err);
+        User::Leave( err );
+        }
+
+    HTI_LOG_TEXT( "Starting IAP" );
+    iConnPref.SetDialogPreference( ECommDbDialogPrefDoNotPrompt );
+    iConnPref.SetIapId( iIAPId );
+    iConnection.Start( iConnPref, iStatus );
+    iState = EStartingIAP;
+    SetActive();
+
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::ConstructL" );
+    }
+
+
+void CHtiConnectionManager::ReadIAPConfigL()
+    {
+    // Try to read IAP id first
+    TRAPD( err, iIAPId = iCfg->GetParameterIntL( KIAPId ) );
+    if ( err == KErrNone )
+        {
+        HTI_LOG_FORMAT( "Using IAP id %d", iIAPId);
+        }
+    else
+        {
+        // IAP id not defined try reading IAP name
+        TBuf8<KMaxParameterValueLength> IAPNameCfg;
+        TRAP( err, IAPNameCfg = iCfg->GetParameterL( KIAPName ) );
+
+        // If IAP name is not defined it wont be found from commsdb...
+
+        HTI_LOG_TEXT( "Searching for IAP:" );
+        HTI_LOG_DES( IAPNameCfg );
+
+        // open commdb
+        CCommsDatabase* commDb = CCommsDatabase::NewL( EDatabaseTypeIAP );
+        CleanupStack::PushL(commDb);
+
+        // open IAP table
+
+        // Using all bearers from TCommDbBearer because when
+        // using KCommDbBearerUnknown it just leaves
+        TUint32 bearerSet = KCommDbBearerCSD|KCommDbBearerPSD|KCommDbBearerLAN|
+                            KCommDbBearerVirtual|KCommDbBearerPAN|
+                            KCommDbBearerWLAN;
+
+        CCommsDbTableView* commView =
+            commDb->OpenIAPTableViewMatchingBearerSetLC(bearerSet,
+                                                        ECommDbConnectionDirectionUnknown);
+
+        // search all IAPs
+        HTI_LOG_TEXT( "IAP records:" );
+        if (commView->GotoFirstRecord() == KErrNone)
+            {
+            do
+                {
+                TBuf8<KCommsDbSvrMaxFieldLength> iapName;
+                commView->ReadTextL( TPtrC(COMMDB_NAME), iapName );
+                HTI_LOG_DES( iapName );
+
+                if ( iapName == IAPNameCfg )
+                    {
+                    commView->ReadUintL( TPtrC(COMMDB_ID), iIAPId );
+                    HTI_LOG_FORMAT( "Found it! IAP id %d", iIAPId );
+                    }
+
+                }
+            while ( commView->GotoNextRecord() == KErrNone );
+            }
+        CleanupStack::PopAndDestroy(2); // commView, commDb
+        }
+
+    // Cannot start if Internet Access Point is not defined
+    if ( iIAPId == 0 )
+        {
+        HTI_LOG_TEXT( "IAP not defined" );
+        ShowErrorNotifierL( _L( "IAP not defined" ), KErrNotFound );
+        User::Leave( KErrNotFound );
+        }
+    }
+
+
+void CHtiConnectionManager::ReadConnectionConfigL()
+    {
+    // Read listening port number from config file
+    TRAPD( err, iListenPort = iCfg->GetParameterIntL( KLocalPort ) );
+
+    if ( iListenPort == 0)
+        {
+        // ...or remote host to connect
+
+        TBuf8<KMaxParameterValueLength> remoteHostCfg;
+        TRAP( err, remoteHostCfg = iCfg->GetParameterL( KRemoteHost ) );
+        if ( err )
+            {
+            HTI_LOG_TEXT( "No remote host specified!" )
+            ShowErrorNotifierL( _L( "No remote host specified!" ), err );
+            User::Leave( err );
+            }
+
+        // Convert TDesC8 -> TDesC
+        TBuf<KMaxParameterValueLength> tmp;
+        tmp.Copy( remoteHostCfg );
+
+        // Check remote host if its a plain ip address
+        if ( iRemoteHost.Input( tmp ) )
+            {
+            // ...its not. Do a DNS-lookup request
+            HTI_LOG_TEXT( "Do a DSN-lookup request" );
+
+            RHostResolver resolver;
+            err = resolver.Open( iSocketServ, KAfInet, KProtocolInetUdp, iConnection );
+            if ( err )
+                {
+                HTI_LOG_FORMAT( "error opening resolver %d", err );
+                User::Leave( err );
+                }
+
+            TNameEntry entry;
+            err = resolver.GetByName( tmp, entry );
+            if ( err )
+                {
+                HTI_LOG_FORMAT( "error getting address by name %d", err );
+                ShowErrorNotifierL(
+                    _L( "Could not resolve remote host!" ), err );
+                User::Leave( err );
+                }
+
+            iRemoteHost = entry().iAddr;
+
+            resolver.Close();
+            }
+
+        // Get remote host port
+        TRAP( err, iRemoteHost.SetPort( iCfg->GetParameterIntL( KRemotePort ) ) );
+        if ( err )
+            {
+            HTI_LOG_TEXT( "No remote port specified!" )
+            ShowErrorNotifierL( _L( "No remote port specified!" ), err );
+            User::Leave( err );
+            }
+
+        // Get connect timeout
+        TRAP( err, iConnectTimeout = iCfg->GetParameterIntL( KConnectTimeout ) );
+        if ( err )
+            {
+            // default is 30 seconds
+            iConnectTimeout = 30;
+            }
+
+        HTI_LOG_FORMAT( "Connect timeout %d", iConnectTimeout );
+        }
+    }
+
+void CHtiConnectionManager::StartConnectingL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::StartConnectingL" );
+    CancelAllRequests();
+
+    // close if open
+    if ( iDataSocket.SubSessionHandle() )
+        iDataSocket.Close();
+
+    // open data socket
+    TInt err = iDataSocket.Open( iSocketServ,
+                        KAfInet,
+                        KSockStream,
+                        KProtocolInetTcp,
+                        iConnection );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "error opening data socket %d", err );
+        User::Leave( err );
+        }
+
+    iDataSocket.Connect( iRemoteHost, iStatus );
+    iState = EConnecting;
+
+    // Set a timeout for this operation if timer is not
+    // already active and there is a timeout defined
+    if ( iConnectTimeout && !iConnectTimer->IsActive() )
+        {
+        // iConnectTimeout is in seconds
+        iConnectTimer->After( iConnectTimeout*1000000 );
+        }
+
+    SetActive();
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::StartConnectingL" );
+    }
+
+
+void CHtiConnectionManager::StartListeningL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::StartListeningL" );
+    HTI_LOG_FORMAT( "Port %d", iListenPort );
+
+    CancelAllRequests();
+
+    // close if open
+    if ( iDataSocket.SubSessionHandle() )
+        iDataSocket.Close();
+
+    // open empty socket
+    TInt err = iDataSocket.Open( iSocketServ  );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "error opening blank socket %d", err );
+        User::Leave( err );
+        }
+
+    // start listening
+    iListenSocket.Accept( iDataSocket, iStatus );
+    iState = EWaitingConnection;
+
+    SetActive();
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::StartListeningL" );
+    }
+
+void CHtiConnectionManager::CancelAllRequests()
+    {
+    HTI_LOG_TEXT( "Cancelling all active server requests" );
+    CancelReceive();
+    CancelSend();
+    }
+
+void CHtiConnectionManager::RunL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::RunL" );
+    HTI_LOG_FORMAT( "status %d", iStatus.Int() );
+
+    TInt err;
+
+    switch ( iState )
+        {
+        case EStartingIAP:
+
+            HTI_LOG_TEXT( "EStartingIAP" );
+
+            if ( iStatus.Int() )
+                {
+                HTI_LOG_FORMAT( "error starting IAP %d", iStatus.Int() );
+                ShowErrorNotifierL( _L( "Error starting IAP" ), iStatus.Int() );
+                User::Leave( iStatus.Int() );
+                }
+
+            ReadConnectionConfigL();
+
+            // remote host is defined - start connecting to it
+            if ( iListenPort == 0 )
+                {
+                StartConnectingL();
+                }
+            // remote host not defined - start listening
+            else
+                {
+                HTI_LOG_TEXT( "Setting up listen socket" );
+
+                // open listening socket
+                err = iListenSocket.Open( iSocketServ,
+                                    KAfInet,
+                                    KSockStream,
+                                    KProtocolInetTcp,
+                                    iConnection );
+                if ( err )
+                    {
+                    HTI_LOG_FORMAT( "error opening listen socket %d", err );
+                    User::Leave( err );
+                    }
+
+                // set the port to listen
+                err = iListenSocket.SetLocalPort( iListenPort );
+                if ( err )
+                    {
+                    HTI_LOG_FORMAT( "error setting local port %d", err );
+                    User::Leave( err );
+                    }
+
+                // set listen queue size
+                err = iListenSocket.Listen( 5 );
+                if ( err )
+                    {
+                    HTI_LOG_FORMAT( "error settig up listening socket %d", err );
+                    User::Leave( err );
+                    }
+
+                StartListeningL();
+                }
+
+
+            break;
+
+        case EWaitingConnection:
+            HTI_LOG_TEXT( "EWaitingConnection" );
+
+            if ( iStatus.Int() )
+                {
+                HTI_LOG_FORMAT( "error accepting connection %d", iStatus.Int() );
+                ShowErrorNotifierL(
+                    _L( "Error accepting connection!" ), iStatus.Int() );
+                User::Leave( iStatus.Int() );
+                }
+
+            iState = EConnected;
+            HTI_LOG_TEXT( "Connected!" );
+            User::InfoPrint( _L("HtiIPComm: connected!") );
+
+            if ( !iReceiveRequestComplete )
+                {
+                // There is a pending read request
+                HTI_LOG_TEXT( "Pending read request" );
+                ReadSocket();
+                }
+
+            if ( !iSendRequestComplete )
+                {
+                // There is a pending write request
+                HTI_LOG_TEXT( "Pending write request" );
+                WriteSocket();
+                }
+
+            break;
+
+        case EConnecting:
+            HTI_LOG_TEXT( "EConnecting" );
+
+            if ( iStatus.Int() )
+                {
+                HTI_LOG_FORMAT( "error connecting to remote host %d", iStatus.Int() );
+                HTI_LOG_TEXT( "trying again..." );
+                User::After( 1000000 ); // wait 1 second before trying again
+                StartConnectingL();
+                }
+            else
+                {
+                // Cancel the timer
+                iConnectTimer->Cancel();
+
+                iState = EConnected;
+                HTI_LOG_TEXT( "Connected!" );
+                User::InfoPrint( _L("HtiIPComm: connected!") );
+
+                //LogLocalHost( iDataSocket );
+                //LogRemoteHost( iDataSocket );
+
+                if ( !iReceiveRequestComplete )
+                    {
+                    // There is a pending read request
+                    HTI_LOG_TEXT( "Pending read request" );
+                    ReadSocket();
+                    }
+
+                if ( !iSendRequestComplete )
+                    {
+                    // There is a pending write request
+                    HTI_LOG_TEXT( "Pending write request" );
+                    WriteSocket();
+                    }
+                }
+
+            break;
+
+        case EConnected:
+            HTI_LOG_TEXT( "EConnected" );
+            break;
+
+        case EDisconnecting:
+            HTI_LOG_TEXT( "EDisconnecting" );
+            break;
+
+        case EDisconnected:
+            HTI_LOG_TEXT( "EDisconnected" );
+            break;
+
+        default:
+            HTI_LOG_TEXT( "Unknown" );
+            User::Panic( _L("HtiIPComm"), EUnknownState );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::RunL" );
+    }
+
+
+void CHtiConnectionManager::DoCancel()
+    {
+    HTI_LOG_TEXT( "CHtiConnectionManager::DoCancel" );
+    }
+
+
+TInt CHtiConnectionManager::RunError(TInt aError)
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::RunError" );
+    HTI_LOG_FORMAT( "error %d closing server...", aError );
+    iServer->CloseServer();
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::RunError" );
+    aError = aError;
+    return KErrNone;
+    }
+
+
+void CHtiConnectionManager::Receive( const RMessage2& aMessage )//( TDes8& aRawdataBuf, TRequestStatus& aStatus )
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::Receive" );
+
+    if ( !iReceiveRequestComplete )
+        {
+        HTI_LOG_TEXT( "complete with KErrServerBusy" );
+        aMessage.Complete( KErrServerBusy );
+        }
+    else
+        {
+        iReceiveRequestComplete = EFalse;
+        iReceiveRequest = aMessage;
+
+        if ( iState == EConnected )
+            {
+            ReadSocket();
+            }
+        else
+            {
+            HTI_LOG_TEXT( "not connected" );
+            }
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::Receive" );
+    }
+
+
+void CHtiConnectionManager::Send( const RMessage2& aMessage )
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::Send" );
+
+    if ( !iSendRequestComplete )
+        {
+        HTI_LOG_TEXT( "complete with KErrServerBusy" );
+        aMessage.Complete( KErrServerBusy );
+        }
+    else
+        {
+        iSendRequestComplete = EFalse;
+        iSendRequest = aMessage;
+        TInt err = aMessage.Read( 0, iSendBuffer );
+        if ( err )
+            {
+            User::Panic( _L("HtiIPComm"), EBadDescriptor );
+            }
+
+        if ( iState == EConnected )
+            {
+            WriteSocket();
+            }
+        else
+            {
+            HTI_LOG_TEXT( "not connected" );
+            }
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::Send" );
+    }
+
+void CHtiConnectionManager::ReadSocket()
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::ReadSocket" );
+
+    iReceiveMonitor->Activate();
+    iReceiveBuffer.Zero();
+    iDataSocket.RecvOneOrMore( iReceiveBuffer, 0,
+        iReceiveMonitor->iStatus, iRecvLen );
+
+    // This works fine with the emulator...
+    //iDataSocket.RecvOneOrMore( *(TDes8*) iReceiveRequest.Ptr0(),
+    //                       0, iReceiveMonitor->iStatus, iRecvLen );
+
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::ReadSocket" );
+    }
+
+void CHtiConnectionManager::WriteSocket()
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::WriteSocket" );
+
+    iSendMonitor->Activate();
+    iDataSocket.Write( iSendBuffer, iSendMonitor->iStatus );
+
+    // This works fine with the emulator...
+    //iDataSocket.Write( *(TDesC8*) iSendRequest.Ptr0(),
+    //               iSendMonitor->iStatus );
+
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::WriteSocket" );
+    }
+
+void CHtiConnectionManager::CancelReceive()
+    {
+    HTI_LOG_TEXT( "CHtiConnectionManager::CancelReceive" );
+
+    if ( !iReceiveRequestComplete )
+        {
+        // Is there an active socket receive?
+        if ( iReceiveMonitor->IsActive() )
+            {
+            // ReportComplete() should complete this
+            HTI_LOG_TEXT( "CancelRecv" );
+            iDataSocket.CancelRecv();
+            }
+        else
+            {
+            HTI_LOG_TEXT( "complete with KErrCancel" );
+            iReceiveRequest.Complete( KErrCancel );
+            iReceiveRequestComplete = ETrue;
+            iReceiveBuffer.Zero();
+            }
+        }
+    }
+
+void CHtiConnectionManager::CancelSend()
+    {
+    HTI_LOG_TEXT( "CHtiConnectionManager::CancelSend" );
+
+    if ( !iSendRequestComplete )
+        {
+        // Is there an active socket send?
+        if ( iSendMonitor->IsActive() )
+            {
+            // ReportComplete() should complete this
+            HTI_LOG_TEXT( "CancelWrite" );
+            iDataSocket.CancelWrite();
+            }
+        else
+            {
+            HTI_LOG_TEXT( "complete with KErrCancel" );
+            iSendRequest.Complete( KErrCancel );
+            iSendRequestComplete = ETrue;
+            iSendBuffer.Zero();
+            }
+        }
+    }
+
+void CHtiConnectionManager::ReportComplete( MHtiSocketObserver::TRequestType aType, TInt aError )
+    {
+    HTI_LOG_FUNC_IN( "CHtiConnectionManager::ReportComplete" );
+
+    HTI_LOG_FORMAT( "error %d", aError );
+
+    TInt err = 0;
+
+    switch ( aType )
+        {
+        case MHtiSocketObserver::EReadSocket:
+            HTI_LOG_TEXT( "EReadSocket" );
+            err = iReceiveRequest.Write( 0 , iReceiveBuffer );
+            if ( err )
+                {
+                HTI_LOG_FORMAT( "Panic! Error writing received data to client buffer %d", err );
+                User::Panic( _L("HtiIPComm"), EBadDescriptor );
+                }
+
+            iReceiveBuffer.Zero();
+            iReceiveRequestComplete = ETrue;
+            iReceiveRequest.Complete( aError );
+
+            break;
+
+        case MHtiSocketObserver::EWriteSocket:
+            HTI_LOG_TEXT( "EWriteSocket" );
+            iSendBuffer.Zero();
+            iSendRequestComplete = ETrue;
+            iSendRequest.Complete( aError );
+            break;
+
+        default:
+            User::Panic( _L("HtiIPComm"), EUnknownCompletion );
+        }
+
+
+    // Disconnect if there is an error.
+    if ( aError &&
+        ( aError != KErrCancel ) ) // ...except when there is a cancel
+        {
+        iState = EDisconnected;
+        HTI_LOG_TEXT( "Disconnected!" );
+        User::InfoPrint( _L("HtiIPComm: Disconnected!") );
+
+        // If disconnected try to listen or connect again
+        if ( iListenPort == 0 )
+            {
+            // wait 1 second before trying again
+            User::After( 1000000 );
+            StartConnectingL();
+            }
+        else
+            {
+            StartListeningL();
+            }
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiConnectionManager::ReportComplete" );
+    }
+
+CHtiTimer* CHtiTimer::NewL( MHtiTimerObserver& aObserver )
+    {
+    CHtiTimer* self = new (ELeave) CHtiTimer( aObserver );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CHtiTimer::CHtiTimer( MHtiTimerObserver& aObserver ):
+    CTimer( EPriorityUserInput ),
+    iObserver( aObserver)
+    {
+    }
+
+CHtiTimer::~CHtiTimer()
+    {
+    Cancel();
+    }
+
+void CHtiTimer::ConstructL()
+    {
+    CTimer::ConstructL();
+    CActiveScheduler::Add( this );
+    }
+
+void CHtiTimer::RunL()
+    {
+    iObserver.TimerExpiredL();
+    }
+
+TInt CHtiTimer::RunError(TInt aError)
+    {
+    HTI_LOG_FORMAT( "CHtiTimer::RunError %d", aError );
+    aError = aError;
+    return KErrNone;
+    }
+
+void CHtiConnectionManager::TimerExpiredL()
+    {
+    HTI_LOG_TEXT( "Timed out! Closing IPCommServer..." );
+    ShowErrorNotifierL(
+        _L( "Timed out connecting to remote host!" ), KErrTimedOut );
+    iServer->CloseServer();
+    }
+
+void CHtiConnectionManager::ShowErrorNotifierL( const TDesC& aText,
+                                                   TInt aErr )
+    {
+    RNotifier notifier;
+    User::LeaveIfError( notifier.Connect() );
+
+    TBuf<KMaxHtiNotifierLength> errorMsg;
+    // aText is cut if it's too long - leaving some space also for error code
+    errorMsg.Append( aText.Left( errorMsg.MaxLength() - 10 ) );
+    errorMsg.Append( _L("\n") );
+    errorMsg.AppendNum( aErr );
+
+    TRequestStatus status;
+    TInt button;
+    notifier.Notify( KHtiIPCommError, errorMsg,
+                     KHtiOkButton, KNullDesC, button, status );
+    User::WaitForRequest( status );
+    notifier.Close();
+    }
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiIPCommEcomPlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin for communication over IP port
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiIPCommEcomPlugin.h"
+#include <HtiLogging.h>
+
+CHtiIPCommEcomPlugin* CHtiIPCommEcomPlugin::NewL()
+    {
+    CHtiIPCommEcomPlugin* self = new (ELeave) CHtiIPCommEcomPlugin();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CHtiIPCommEcomPlugin::CHtiIPCommEcomPlugin()
+    {
+    }
+
+CHtiIPCommEcomPlugin::~CHtiIPCommEcomPlugin()
+    {
+    iHtiIPCommServer.Close();
+    }
+
+void CHtiIPCommEcomPlugin::ConstructL()
+    {
+    TInt err = iHtiIPCommServer.Connect();
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "error connecting to HtiIPCommServer %d", err );
+        User::Leave( err );
+        }
+    }
+
+void CHtiIPCommEcomPlugin::Receive( TDes8& aRawdataBuf, TRequestStatus& aStatus )
+    {
+    iHtiIPCommServer.Receive( aRawdataBuf, aStatus );
+    }
+
+void CHtiIPCommEcomPlugin::Send( const TDesC8& aRawdataBuf, TRequestStatus& aStatus )
+    {
+    iHtiIPCommServer.Send( aRawdataBuf, aStatus );
+    }
+
+void CHtiIPCommEcomPlugin::CancelReceive()
+    {
+    iHtiIPCommServer.CancelReceive();
+    }
+
+void CHtiIPCommEcomPlugin::CancelSend()
+    {
+    iHtiIPCommServer.CancelSend();
+    }
+
+TInt CHtiIPCommEcomPlugin::GetSendBufferSize()
+    {
+    return iHtiIPCommServer.GetSendBufferSize();
+    }
+
+TInt CHtiIPCommEcomPlugin::GetReceiveBufferSize()
+    {
+    return iHtiIPCommServer.GetReceiveBufferSize();
+    }
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiIPCommServerClient.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,181 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of the client side interface to HtiIPCommServer
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32uid.h>
+#include <HtiLogging.h>
+
+#include "HtiIPCommServerCommon.h"
+#include "HtiIPCommServerClient.h"
+
+// CONSTANTS
+const TUint KIPCommServerDefaultMessageSlots = 4; // Read, write, readCancel, writeCancel
+
+//---------------------------------------------------------------------------
+static TInt StartServer()
+    {
+    const TUidType serverUid( KNullUid, KNullUid, KIPCommServerUid3 );
+
+    RProcess server;
+    TInt r = server.Create( KIPCommServerName, KNullDesC, serverUid);
+    if ( r != KErrNone )
+        return r;
+
+    TRequestStatus stat;
+    server.Rendezvous( stat );
+    if ( stat != KRequestPending )
+        server.Kill(0);     // abort startup
+    else
+        server.Resume();    // logon OK - start the server
+
+    User::WaitForRequest( stat );   //wait for start or death
+
+    // we can't use the 'exit reason' if the server panicked as this
+    // is the panic 'reason' and may be '0' which cannot be distinguished
+    // from KErrNone
+    r = ( server.ExitType() == EExitPanic ) ? KErrGeneral : stat.Int();
+    server.Close();
+    return r;
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C RHtiIPCommServer::RHtiIPCommServer()
+    {
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C TInt RHtiIPCommServer::Connect()
+    {
+    HTI_LOG_TEXT( "RHtiIPCommServer::Connect" );
+
+    // Connect to the server, attempting to start it if necessary
+    TInt retry=2;
+    for (;;)
+        {
+        TInt r = CreateSession( KIPCommServerName,
+                                Version(),
+                                KIPCommServerDefaultMessageSlots );
+        HTI_LOG_FORMAT( "CreateSession %d", r );
+        if ( r != KErrNotFound && r != KErrServerTerminated )
+            return r;
+
+        if (--retry==0)
+            return r;
+
+        r = StartServer();
+        HTI_LOG_FORMAT( "StartServer %d", r );
+        if ( r != KErrNone && r != KErrAlreadyExists )
+            return r;
+        }
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C void RHtiIPCommServer::Close()
+    {
+    HTI_LOG_FUNC_IN( "RHtiIPCommServer::Close" );
+
+    // Use thread finder to find the server thread
+    TFullName threadName;
+    TFullName matchPattern;
+    matchPattern.Append( _L( "*" ) );
+    matchPattern.Append( KIPCommServerName );
+    matchPattern.Append( _L( "*" ) );
+
+    TFindThread threadFinder;
+    threadFinder.Find( matchPattern );
+    TInt err = threadFinder.Next( threadName );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "RHtiIPCommServer::Close: Failed to find server thread: %d", err );
+        return;
+        }
+
+    HTI_LOG_TEXT( "RHtiIPCommServer::Close: Found server thread:" );
+    HTI_LOG_DES( threadName );
+
+    RThread thread;
+    err = thread.Open( threadName );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "RHtiIPCommServer::Close: Failed to open server thread: %d", err );
+        }
+    else
+        {
+        // Close this session. Causes a call to ~CHtiIPCommServerSession which should
+        // stop the active scheduler in IPCommServer
+        RSessionBase::Close();
+
+        // For clean server stop, wait for its death
+        HTI_LOG_TEXT( "RHtiIPCommServer::Close: Waiting for server thread to die..." );
+        TRequestStatus status;
+        thread.Logon( status );
+        User::WaitForRequest( status );
+        HTI_LOG_TEXT( "RHtiIPCommServer::Close: Server thread dead." );
+        }
+
+    thread.Close();
+    HTI_LOG_FUNC_OUT( "RHtiIPCommServer::Close" );
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C TVersion RHtiIPCommServer::Version(void) const
+    {
+    return ( TVersion( KIPCommServerMajorVersionNumber,
+                       KIPCommServerMinorVersionNumber,
+                       KIPCommServerBuildVersionNumber ) );
+
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C TInt RHtiIPCommServer::GetSendBufferSize() const
+    {
+    return KIPCommServerSendBufferMaxSize;
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C TInt RHtiIPCommServer::GetReceiveBufferSize() const
+    {
+    return KIPCommServerReceiveBufferMaxSize;
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C void RHtiIPCommServer::Receive(TDes8& aData,
+                                        TRequestStatus& aStatus)
+    {
+    SendReceive( EIPCommServerRecv, TIpcArgs( &aData ), aStatus );
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C void RHtiIPCommServer::Send(const TDesC8& aData,
+                                        TRequestStatus& aStatus)
+    {
+    SendReceive( EIPCommServerSend, TIpcArgs( &aData ), aStatus );
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C void RHtiIPCommServer::CancelReceive()
+    {
+    SendReceive( EIPCommServerCancelRecv, TIpcArgs( NULL ) );
+    }
+
+//---------------------------------------------------------------------------
+EXPORT_C void RHtiIPCommServer::CancelSend()
+    {
+    SendReceive( EIPCommServerCancelSend, TIpcArgs( NULL ) );
+    }
+// End of the file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiIPCommserver.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,146 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: This file contains the implementation of the
+*              CHtiIPCommServer class.
+*              CHtiIPCommServer handles Symbian server side operations
+*              such as server starting and client session creation.
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiIPCommServerCommon.h"
+#include "HtiIPCommServer.h"
+#include "HtiIPCommServerSession.h"
+#include "HtiIPCommLogging.h"
+
+CHtiIPCommServer::CHtiIPCommServer()
+    :CServer2( EPriorityUserInput, EUnsharableSessions ),
+    iConnectionManager( NULL ),
+    iRunning( EFalse ),
+    iNrOfSessions( 0 )
+    {
+    // NOTE: Server needs to have highest priority of all our active
+    // objects to be able to service client requests while other active
+    // objects are running.
+    //
+    // This also affects closing of sessions. If priorities
+    // are the same ~CHtiIPCommServerSession does not get called before active
+    // object completes.
+    }
+
+CHtiIPCommServer::~CHtiIPCommServer()
+    {
+    delete iConnectionManager;
+    }
+
+CHtiIPCommServer* CHtiIPCommServer::NewLC()
+    {
+    CHtiIPCommServer* self=new(ELeave) CHtiIPCommServer;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+void CHtiIPCommServer::ConstructL()
+    {
+    iConnectionManager = CHtiConnectionManager::NewL( this );
+    StartL( KIPCommServerName );
+    }
+
+CSession2* CHtiIPCommServer::NewSessionL( const TVersion&, const RMessage2&) const
+    {
+    // There should be only one session
+    if ( iNrOfSessions )
+        User::Leave( KErrAlreadyExists );
+
+    return new(ELeave) CHtiIPCommServerSession( (CHtiIPCommServer*)this );
+    }
+
+void CHtiIPCommServer::SessionOpened()
+    {
+    iNrOfSessions++;
+    }
+
+void CHtiIPCommServer::SessionClosed()
+    {
+    // Die if no more sessions
+    if ( --iNrOfSessions == 0 )
+        {
+        HTI_LOG_TEXT( "HtiIPCommServer no more sessions - dying..." );
+        CloseServer();
+        }
+    }
+
+void CHtiIPCommServer::CloseServer()
+    {
+    // Can be called from CHtiIPCommServer::SessionClosed and
+    // CHtiConnectionManager::TimerExpiredL
+    // So this can actually be called twice if it is called from
+    // TimerExpiredL - hence the iRunning variable :)
+    if ( iRunning )
+        {
+        iRunning = EFalse;
+        CActiveScheduler::Stop();
+        HTI_LOG_TEXT( "CActiveScheduler::Stop() called" );
+        }
+    }
+
+static void RunServerL()
+    {
+    // naming the server thread after the server helps to debug panics
+
+    User::LeaveIfError( RThread::RenameMe( KIPCommServerName ) );
+
+    // create and install the active scheduler we need
+    CActiveScheduler* as = new ( ELeave ) CActiveScheduler;
+    CleanupStack::PushL( as );
+    CActiveScheduler::Install( as );
+
+    // create the server (leave it on the cleanup stack)
+    CHtiIPCommServer* server = CHtiIPCommServer::NewLC();
+
+    // Rendezvous with the client (RHtiIPCommServer::Connect)
+    RProcess::Rendezvous(KErrNone);
+
+    server->iRunning = ETrue;
+    CActiveScheduler::Start();
+
+    CleanupStack::PopAndDestroy(2);     // server, as
+    }
+
+
+// Server process entry-point
+TInt E32Main()
+    {
+
+    HTI_LOG_TEXT( "*** Starting HtiIPCommServer ***" );
+
+    __UHEAP_MARK;
+
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    TInt r = KErrNoMemory;
+
+    if ( cleanup )
+        {
+        TRAP( r, RunServerL() );
+        delete cleanup;
+        }
+
+    __UHEAP_MARKEND;
+
+    HTI_LOG_TEXT( "*** HtiIPCommServer died! ***" );
+
+    return r;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiIPCommserverSession.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,88 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of CHtiIPCommServerSession class. This class
+*                represents the client session in server.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "HtiIPCommServerCommon.h"
+#include "HtiIPCommServerSession.h"
+#include "HtiIPCommLogging.h"
+
+CHtiIPCommServerSession::CHtiIPCommServerSession( CHtiIPCommServer* aServer )
+    :iServer( aServer )
+    {
+    HTI_LOG_TEXT( "CHtiIPCommServerSession::CHtiIPCommServerSession");
+    iServer->SessionOpened();
+    }
+
+CHtiIPCommServerSession::~CHtiIPCommServerSession()
+    {
+    HTI_LOG_TEXT( "CHtiIPCommServerSession::~CHtiIPCommServerSession");
+    if ( iServer )
+        {
+        iServer->SessionClosed();
+        }
+    }
+
+void CHtiIPCommServerSession::ServiceL( const RMessage2& aMessage )
+    {
+    switch ( aMessage.Function() )
+        {
+        case EIPCommServerRecv:
+            HandleReceiveRequestL( aMessage );
+            break;
+
+        case EIPCommServerSend:
+            HandleSendRequestL( aMessage );
+            break;
+
+        case EIPCommServerCancelRecv:
+            HandleCancelReceiveRequestL( aMessage );
+            break;
+
+        case EIPCommServerCancelSend:
+            HandleCancelSendRequestL( aMessage );
+            break;
+
+        default:
+            aMessage.Panic( _L("IPCommServer"), KErrNotFound );
+            break;
+        }
+    }
+
+void CHtiIPCommServerSession::HandleReceiveRequestL( const RMessage2& aMessage )
+    {
+    iServer->iConnectionManager->Receive( aMessage );
+    }
+
+void CHtiIPCommServerSession::HandleSendRequestL( const RMessage2& aMessage )
+    {
+    iServer->iConnectionManager->Send( aMessage );
+    }
+
+void CHtiIPCommServerSession::HandleCancelReceiveRequestL( const RMessage2& aMessage )
+    {
+    iServer->iConnectionManager->CancelReceive();
+    aMessage.Complete( KErrNone );
+    }
+
+void CHtiIPCommServerSession::HandleCancelSendRequestL( const RMessage2& aMessage )
+    {
+    iServer->iConnectionManager->CancelSend();
+    aMessage.Complete( KErrNone );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/src/HtiSocketMonitor.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin for communication over IP port
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiSocketMonitor.h"
+#include "HtiIPCommLogging.h"
+
+
+CHtiSocketMonitor* CHtiSocketMonitor::NewL( MHtiSocketObserver::TRequestType aType, MHtiSocketObserver* aObserver )
+    {
+    CHtiSocketMonitor* self = new (ELeave) CHtiSocketMonitor( aType, aObserver );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+CHtiSocketMonitor::CHtiSocketMonitor( MHtiSocketObserver::TRequestType aType, MHtiSocketObserver* aObserver ):
+    CActive( EPriorityStandard ),
+    iType( aType ),
+    iObserver( aObserver )
+    {
+    }
+
+CHtiSocketMonitor::~CHtiSocketMonitor()
+    {
+    Cancel();
+    }
+
+void CHtiSocketMonitor::ConstructL()
+    {
+    CActiveScheduler::Add(this);
+    }
+
+void CHtiSocketMonitor::RunL()
+    {
+    iObserver->ReportComplete( iType, iStatus.Int() );
+    }
+
+void CHtiSocketMonitor::DoCancel()
+    {
+    HTI_LOG_TEXT( "CHtiSocketMonitor::DoCancel called" );
+    }
+
+TInt CHtiSocketMonitor::RunError( TInt aError )
+    {
+    HTI_LOG_FORMAT( "CHtiSocketMonitor::RunError %d", aError );
+    aError = aError;
+    return KErrNone;
+    }
+
+void CHtiSocketMonitor::Activate()
+    {
+    HTI_LOG_FUNC_IN( "CHtiSocketMonitor::Activate" );
+
+    if ( !IsAdded() )
+        {
+        HTI_LOG_TEXT( "Panic! HtiSocketMonitor not added" );
+        User::Panic( _L("HtiSocketMonitor not added"), 1 );
+        }
+
+    if ( IsActive() )
+        {
+        HTI_LOG_TEXT( "Panic! HtiSocketMonitor cannot handle more than one request" );
+        User::Panic( _L("HtiSocketMonitor cannot handle more than one request"), 1 );
+        }
+
+    SetActive();
+    HTI_LOG_FUNC_OUT( "CHtiSocketMonitor::Activate" );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiIPCommPlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM implementations in this dll
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiIPCommEcomPlugin.h"
+
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+
+/*---------------------------------------------------------------------------*/
+// Provides a key value pair table, this is used to identify
+// the correct construction function for the requested interface.
+const TImplementationProxy ImplementationTable[] =
+    {
+        IMPLEMENTATION_PROXY_ENTRY(0x200212CE,  CHtiIPCommEcomPlugin::NewL)
+    };
+
+/*---------------------------------------------------------------------------*/
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiSerialCommPlugin/data/10210CC9.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for HtiSerialComm ECOM plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+
+//  RESOURCE DEFINITIONS
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x10210CC9;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB8;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x10210CCA;
+                    version_no         = 1;
+                    display_name       = "SERIAL comm";
+                    default_data       = "SERIAL";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiSerialCommPlugin/group/HtiSerialComm.cfg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,125 @@
+# HTISerialComm communication plugin configuration file
+
+# The CommPort parameter configures the number of the comm port to use.
+# Note that comm port numbering starts from zero, so for example in WINS-
+# emulator comm port 0 is physically COM1 in Windows.
+# Possible values: 0 - 99
+# Default value: 0
+
+#CommPort=0
+
+
+# The DataRate parameter configures the speed of the serial port (bits/sec)
+# Possible values: 2400, 4800, 9600, 19200, 38400, 57600, 115200,
+#                  576000, 1152000, 4000000
+# Default value: 115200
+
+#DataRate=2400
+#DataRate=4800
+#DataRate=9600
+#DataRate=19200
+#DataRate=38400
+#DataRate=57600
+#DataRate=115200
+#DataRate=576000
+#DataRate=1152000
+#DataRate=4000000
+
+
+# The Parity parameter configures the parity to be used
+# Possible values: none, even, odd, mark, space
+# Default value: none
+
+#Parity=none
+#Parity=even
+#Parity=odd
+#Parity=mark
+#Parity=space
+
+
+# The DataBits parameter configures how many data bits to use
+# Possible values: 5, 6, 7, 8
+# Default value: 8
+
+#DataBits=5
+#DataBits=6
+#DataBits=7
+#DataBits=8
+
+
+# The StopBits parameter configures how many stop bits to use
+# Possible values: 1, 2
+# Default value: 1
+
+#StopBits=1
+#StopBits=2
+
+# The SendDelay parameter can be used to slow down the data sending from
+# Symbian to PC. It defines a delay in milliseconds between each write to
+# the serial port. This delay may be needed in some environments when
+# larger amounts of data is transferred. If data transfer seems to fail,
+# try increasing the SendDelay value.
+# The value is defined in milliseconds.
+# Default value: 0
+
+#SendDelay=0
+
+
+# The handshake parameter configures handshaking control bitmask in decimal format
+# Possible values:
+#
+# From d32comm.h :
+# DTE
+# ---
+# KConfigObeyCTS      0x4 = 4
+# KConfigObeyDSR     0x10 = 16
+# KConfigObeyDCD     0x40 = 64
+#
+# KConfigFailCTS      0x8 = 8
+# KConfigFailDCD     0x80 = 128
+# KConfigFailDSR     0x20 = 32
+#
+# KConfigFreeRTS    0x100 = 256
+# KConfigFreeDTR    0x200 = 512
+#
+# DCE
+# ---
+# KConfigObeyDTR    0x400 = 1024
+# KConfigObeyRTS   0x1000 = 4096
+#
+# KConfigFailDTR    0x800 = 2048
+# KConfigFailRTS   0x2000 = 8192
+#
+# KConfigFreeDSR   0x4000 = 16384
+# KConfigFreeCTS   0x8000 = 32768
+# KConfigFreeDCD  0x10000 = 65536
+# KConfigFreeRI   0x20000 = 131072
+#
+# DCD = Data Carrier Detect
+# DTR = Data Terminal Ready
+# DSR = Data Set Ready
+# RTS = Request To Send
+# CTS = Clear To Send
+#
+# For more information about the meaning of the values see Developer Library
+#
+# Default value: 0
+
+# For cables with partial handshaking
+#
+# KConfigObeyDSR | KConfigObeyDCD = 0x50
+#Handshake=80
+# KConfigObeyDSR | KConfigObeyDCD | KConfigObeyDTR = 0x450
+#Handshake=1104
+# KConfigObeyDSR | KConfigObeyDCD | KConfigFreeDSR | KConfigFreeDCD = 0x14050
+#Handshake=82000
+# KConfigObeyDSR | KConfigObeyDCD | KConfigFreeDTR | KConfigObeyDTR | KConfigFreeDSR | KConfigFreeDCD = 0x14650
+#Handshake=83536
+# KConfigObeyCTS | KConfigObeyDSR | KConfigObeyDCD = 0x54
+#Handshake=84
+
+# For cables with full handshaking
+#
+# KConfigObeyCTS | KConfigFreeRTS| KConfigObeyRTS | KConfigFreeCTS
+#Handshake=37124
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiSerialCommPlugin/group/HtiSerialCommEcomPlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM Plugin project to support communication over serial port
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiSerialCommEcomPlugin.dll
+TARGETTYPE      PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID 0x10009D8D 0x10210CC9
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          proxy.cpp
+SOURCE          HtiSerialCommEcomPlugin.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/10210CC9.rss
+TARGET          HtiSerialCommEcomPlugin.rsc
+END
+
+LIBRARY         c32.lib
+LIBRARY         euser.lib
+LIBRARY         ecom.lib
+LIBRARY         hticfg.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiSerialCommPlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiSerialCommPlugin build info
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+HtiSerialComm.cfg   +/winscw/c/HtiSerialComm.cfg
+
+PRJ_MMPFILES
+HtiSerialCommEcomPlugin.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiSerialCommPlugin/inc/HtiSerialCommEcomPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin to communicate over serial port
+*
+*/
+
+
+#ifndef CHTISERIALCOMMECOMPLUGIN_H
+#define CHTISERIALCOMMECOMPLUGIN_H
+
+
+// INCLUDES
+#include <c32comm.h>
+
+#include <HtiCommPluginInterface.h> // defined in HtiFramework project
+
+
+// FORWARD DECLARATIONS
+class CHtiCfg;
+
+// CLASS DECLARATION
+/**
+* ECOM plugin module for communicating with PC using serial port.
+*
+*/
+class CHtiSerialCommEcomPlugin :
+    public CHTICommPluginInterface
+    {
+public:
+
+    /**
+    * Create instance of plugin.
+    * Reads configuration, opens and initializes serial port.
+    * @return Plugin instance.
+    */
+    static CHtiSerialCommEcomPlugin* NewL();
+
+    /**
+    * Destructor.
+    */
+    ~CHtiSerialCommEcomPlugin();
+
+public: // Interface implementation
+
+    /**
+    * Receive data from serial port.
+    * The size of supplied buffer must equal to size given
+    * by GetReceiveBufferSize.
+    * The number of received bytes may be anything between 1
+    * and GetReceiveBufferSize.
+    *
+    * @param aRawdataBuf Buffer where the result is written
+    * @param aStatus Request status
+    */
+    void Receive( TDes8& aRawdataBuf, TRequestStatus& aStatus );
+
+    /**
+    * Send data to serial port. The size of data must not
+    * exceed GetSendBufferSize.
+    * @param aRawdataBuf Buffer where the data is read from.
+    * @param aStatus Request status
+    */
+    void Send( const TDesC8& aRawdataBuf, TRequestStatus& aStatus );
+
+    /**
+    * Cancel read operation
+    */
+    void CancelReceive();
+
+    /**
+    * Cancel send operation
+    */
+    void CancelSend();
+
+    /**
+     *  Return required buffer size for Send operation.
+     */
+    TInt GetSendBufferSize();
+
+    /**
+     *  Return required buffer size for Receive operation.
+     */
+    TInt GetReceiveBufferSize();
+
+private:
+
+    /**
+    * Constructor of this plugin.
+    */
+    CHtiSerialCommEcomPlugin();
+
+    /**
+    * Second phase construction.
+    */
+    void ConstructL();
+
+    /**
+    * Load needed drivers and start comm server.
+    */
+    void InitCommServerL();
+
+    /**
+    * Setup serial port.
+    */
+    void InitCommPortL();
+
+    /**
+    * Load configuration file.
+    */
+    void LoadConfigL();
+
+    /**
+    * Read and parse the configuration values.
+    */
+    void ReadConfig();
+
+    /**
+    * Show error notifier dialog with text and error code.
+    */
+    void ShowErrorNotifierL( const TDesC& aText, TInt aErr );
+
+private: // Data
+
+    CHtiCfg* iCfg;
+
+    // port settings
+    TInt      iPortNumber;
+    TBps      iDataRate;
+    TParity   iParity;
+    TDataBits iDataBits;
+    TStopBits iStopBits;
+
+    // optional delay after each write to RComm
+    TInt iSendDelay;
+
+    // bitmask for handshake
+    TInt iHandshake;
+
+    RCommServ iCommServ;
+    RComm iCommPort;
+    };
+
+#endif // CHTISERIALCOMMECOMPLUGIN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiSerialCommPlugin/src/HtiSerialCommEcomPlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,497 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin for communication over serial port
+*
+*/
+
+
+// INCLUDE FILES
+#include <badesca.h>
+#include <f32file.h>
+
+#include "HtiSerialCommEcomPlugin.h"
+#include <HtiCfg.h>
+#include <HtiLogging.h>
+
+// CONSTANTS
+_LIT( KHtiSerialError, "HtiSerialError" );
+_LIT( KHtiOkButton, "OK" );
+
+_LIT( KHtiCfgPath,          "\\" ); // root of drive
+_LIT( KHtiSerialCommCfg,    "HTISerialComm.cfg" );
+_LIT8( KCommPortNumber,     "CommPort"         );
+_LIT8( KDataRate,           "DataRate"         );
+_LIT8( KParity,             "Parity"           );
+_LIT8( KDataBits,           "DataBits"         );
+_LIT8( KStopBits,           "StopBits"         );
+_LIT8( KSendDelay,          "SendDelay"        );
+_LIT8( KHandshake,          "Handshake"        );
+
+#if defined (__WINS__)
+_LIT( SERIAL_PDD_NAME, "ECDRV" );
+#else
+_LIT( SERIAL_PDD_NAME, "EUART1" );
+#endif
+_LIT( SERIAL_LDD_NAME, "ECOMM" );
+_LIT( RS232_CSY_NAME, "ECUART" );
+
+const static TUint KReceiveBufferLength = 4*1024;
+const static TUint KSendBufferLength = 4*1024;
+const static TInt KMaxCommPortNumber = 99;
+const static TInt KMaxHtiNotifierLength = 128;
+
+CHtiSerialCommEcomPlugin* CHtiSerialCommEcomPlugin::NewL()
+    {
+    HTI_LOG_FUNC_IN( "Serial::NewL" );
+    CHtiSerialCommEcomPlugin* plugin = new (ELeave) CHtiSerialCommEcomPlugin();
+    CleanupStack::PushL( plugin );
+    plugin->ConstructL();
+    CleanupStack::Pop( plugin );
+    HTI_LOG_FUNC_OUT( "Serial::NewL" );
+    return plugin;
+    }
+
+CHtiSerialCommEcomPlugin::~CHtiSerialCommEcomPlugin()
+    {
+    HTI_LOG_FUNC_IN( "Serial::~CHtiSerialCommEcomPlugin" );
+    iCommPort.Close();
+    iCommServ.Close();
+    delete iCfg;
+    User::FreeLogicalDevice( SERIAL_LDD_NAME );
+    User::FreePhysicalDevice( SERIAL_PDD_NAME );
+    HTI_LOG_FUNC_OUT( "Serial::~CHtiSerialCommEcomPlugin" );
+    }
+
+CHtiSerialCommEcomPlugin::CHtiSerialCommEcomPlugin()
+    {
+    // default port settings
+    iPortNumber = 0;
+    iDataRate   = EBps115200;
+    iParity     = EParityNone;
+    iDataBits   = EData8;
+    iStopBits   = EStop1;
+
+    iSendDelay = 0;
+    iHandshake = 0;
+    }
+
+void CHtiSerialCommEcomPlugin::ConstructL()
+    {
+    TRAPD( err, LoadConfigL() );
+    if ( err == KErrNone )
+        {
+        ReadConfig();
+        }
+    InitCommServerL();
+    InitCommPortL();
+    }
+
+void CHtiSerialCommEcomPlugin::LoadConfigL()
+    {
+    HTI_LOG_FUNC_IN( "Serial::LoadConfigL" );
+    iCfg = CHtiCfg::NewL();
+    HTI_LOG_TEXT( "CHtiCfg constructed - loading cfg file" );
+    iCfg->LoadCfgL( KHtiCfgPath, KHtiSerialCommCfg );
+    HTI_LOG_TEXT( "Cfg file loaded" );
+    HTI_LOG_FUNC_OUT( "Serial::LoadConfigL" );
+    }
+
+void CHtiSerialCommEcomPlugin::ReadConfig()
+    {
+    HTI_LOG_FUNC_IN( "Serial::ReadConfig" );
+
+    TInt portNumberCfg = 0;
+    TRAPD( paramErr,
+            portNumberCfg = iCfg->GetParameterIntL( KCommPortNumber ) );
+    if ( paramErr != KErrNone )
+        {
+        HTI_LOG_FORMAT(
+            "ComPort not defined in cfg, using default value %d",
+            iPortNumber );
+        portNumberCfg = iPortNumber;
+        }
+    if ( portNumberCfg > KMaxCommPortNumber || portNumberCfg < 0 )
+        {
+        HTI_LOG_FORMAT( "Unsupported ComPort %d defined in cfg, using default",
+                            portNumberCfg );
+        portNumberCfg = iPortNumber;
+        }
+    iPortNumber = portNumberCfg;
+
+    TInt dataRateCfg = 0;
+    TRAP( paramErr, dataRateCfg = iCfg->GetParameterIntL( KDataRate ) );
+    if ( paramErr != KErrNone )
+        {
+        HTI_LOG_TEXT( "DataRate not defined in cfg, using default" );
+        }
+    else
+        {
+        switch ( dataRateCfg )
+            {
+            case 2400:
+                iDataRate = EBps2400;
+                break;
+            case 4800:
+                iDataRate = EBps4800;
+                break;
+            case 9600:
+                iDataRate = EBps9600;
+                break;
+            case 19200:
+                iDataRate = EBps19200;
+                break;
+            case 38400:
+                iDataRate = EBps38400;
+                break;
+            case 57600:
+                iDataRate = EBps57600;
+                break;
+            case 115200:
+                iDataRate = EBps115200;
+                break;
+            case 576000:
+                iDataRate = EBps576000;
+                break;
+            case 1152000:
+                iDataRate = EBps1152000;
+                break;
+            case 4000000:
+                iDataRate = EBps4000000;
+                break;
+            default:
+                HTI_LOG_FORMAT(
+                    "Unsupported DataRate %d defined - using default",
+                    dataRateCfg );
+                break;
+            }
+        }
+
+    TBuf8<64> parityCfg( KNullDesC8 );
+    TRAP( paramErr, parityCfg = iCfg->GetParameterL( KParity ) );
+    if ( paramErr != KErrNone || parityCfg.Length() == 0 )
+        {
+        HTI_LOG_TEXT( "Parity not defined in cfg, using default" );
+        }
+    else
+        {
+        if ( !parityCfg.CompareF( _L8( "none" ) ) )
+            {
+            iParity = EParityNone;
+            }
+        else if ( !parityCfg.CompareF( _L8( "even" ) ) )
+            {
+            iParity = EParityEven;
+            }
+        else if ( !parityCfg.CompareF( _L8( "odd" ) ) )
+            {
+            iParity = EParityOdd;
+            }
+        else if ( !parityCfg.CompareF( _L8( "mark" ) ) )
+            {
+            iParity = EParityMark;
+            }
+        else if ( !parityCfg.CompareF( _L8( "space" ) ) )
+            {
+            iParity = EParitySpace;
+            }
+        else
+            {
+            HTI_LOG_TEXT( "Unsupported Parity defined - using default" );
+            }
+        }
+
+    TInt dataBitsCfg = 0;
+    TRAP( paramErr, dataBitsCfg = iCfg->GetParameterIntL( KDataBits ) );
+    if ( paramErr != KErrNone )
+        {
+        HTI_LOG_TEXT( "DataBits not defined in cfg, using default value" );
+        }
+    else
+        {
+        switch ( dataBitsCfg )
+            {
+            case 5:
+                iDataBits = EData5;
+                break;
+            case 6:
+                iDataBits = EData6;
+                break;
+            case 7:
+                iDataBits = EData7;
+                break;
+            case 8:
+                iDataBits = EData8;
+                break;
+            default:
+                HTI_LOG_FORMAT(
+                    "Unsupported DataBits %d defined - using default",
+                    dataBitsCfg );
+                break;
+            }
+        }
+
+    TInt stopBitsCfg = 0;
+    TRAP( paramErr, stopBitsCfg = iCfg->GetParameterIntL( KStopBits ) );
+    if ( paramErr != KErrNone )
+        {
+        HTI_LOG_TEXT( "StopBits not defined in cfg, using default value" );
+        }
+    else
+        {
+        switch ( stopBitsCfg )
+            {
+            case 1:
+                iStopBits = EStop1;
+                break;
+            case 2:
+                iStopBits = EStop2;
+                break;
+            default:
+                HTI_LOG_FORMAT(
+                    "Unsupported StopBits %d defined - using default",
+                    stopBitsCfg );
+                break;
+            }
+        }
+
+    TInt sendDelayCfg = 0;
+    TRAP( paramErr, sendDelayCfg = iCfg->GetParameterIntL( KSendDelay ) );
+    if ( paramErr != KErrNone )
+        {
+        HTI_LOG_TEXT( "SendDelay not defined in cfg, using default value" );
+        }
+    else
+        {
+        iSendDelay = sendDelayCfg * 1000; // configured as milliseconds
+        }
+
+    TInt handshakeCfg = 0;
+    TRAP( paramErr, handshakeCfg = iCfg->GetParameterIntL( KHandshake ) );
+    if ( paramErr != KErrNone )
+        {
+        HTI_LOG_TEXT(
+            "Handshake not defined in cfg, using default value" );
+        }
+    else
+        {
+        iHandshake = handshakeCfg;
+        }
+
+    HTI_LOG_FUNC_OUT( "Serial::ReadConfig" );
+    }
+
+void CHtiSerialCommEcomPlugin::InitCommServerL()
+    {
+    HTI_LOG_FUNC_IN( "Serial::InitCommServerL" );
+    //load physical device driver
+    TInt err = User::LoadPhysicalDevice( SERIAL_PDD_NAME );
+    if ( err != KErrNone && err != KErrAlreadyExists )
+        {
+        ShowErrorNotifierL( _L( "Failed to load serial PDD" ), err );
+        User::Leave( err );
+        }
+
+    //load logical device driver
+    err = User::LoadLogicalDevice( SERIAL_LDD_NAME );
+    if ( err != KErrNone && err != KErrAlreadyExists )
+        {
+        ShowErrorNotifierL( _L( "Failed to load serial LDD" ), err );
+        User::Leave( err );
+        }
+
+#if !defined (__WINS__)
+    //User::After(1500000); //resolve
+    //starts the comm server
+    err = StartC32();
+    if ( err != KErrNone && err != KErrAlreadyExists )
+        User::Leave( err );
+#endif
+
+    //connect to RCommServ
+    User::LeaveIfError( iCommServ.Connect() );
+
+    //load protocol module (CSY file)
+    User::LeaveIfError( iCommServ.LoadCommModule( RS232_CSY_NAME ) );
+    HTI_LOG_FUNC_OUT( "Serial::InitCommServerL" );
+    }
+
+void CHtiSerialCommEcomPlugin::InitCommPortL()
+    {
+    HTI_LOG_FUNC_IN( "Serial::InitCommPortL" );
+    TInt numPorts;
+    TInt err;
+    err = iCommServ.NumPorts( numPorts );
+    User::LeaveIfError( err );
+    HTI_LOG_FORMAT( "NumPorts: %d", numPorts );
+
+    // we can get port information for each loaded CSY in turn (note we
+    // index them from 0) - we can find out the number of ports supported
+    // together with their names, and their description. The information is
+    // returned in a TSerialInfo structure together with the name of the
+    // CSY that we've indexed
+
+    TSerialInfo portInfo;
+    TBuf16<12> moduleName;
+
+    for ( TInt index=0 ; index < numPorts ; index++ )
+        {
+        err = iCommServ.GetPortInfo( index, moduleName, portInfo );
+        User::LeaveIfError( err );
+        HTI_LOG_FORMAT( "Port %d", index );
+        HTI_LOG_DES( moduleName );
+        HTI_LOG_DES( portInfo.iDescription );
+        HTI_LOG_DES( portInfo.iName );
+        HTI_LOG_FORMAT( "Low unit %d", portInfo.iLowUnit );
+        HTI_LOG_FORMAT( "High unit %d", portInfo.iHighUnit );
+        }
+
+    TBuf<8> commPort;
+    commPort.AppendFormat( _L( "COMM::%d" ), iPortNumber );
+    HTI_LOG_FORMAT( "Open serial port COMM::%d", iPortNumber );
+    err = iCommPort.Open( iCommServ, commPort, ECommExclusive );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "Failed to open serial port %d", err );
+        ShowErrorNotifierL( _L( "Failed to open serial port" ), err );
+        }
+    User::LeaveIfError( err );
+
+    // Just for debug purposes log the port capabilities
+    TCommCaps portCapabilities;
+    iCommPort.Caps( portCapabilities );
+    HTI_LOG_TEXT( "Port capabilities:" );
+    HTI_LOG_FORMAT( " DataRate  = %d", portCapabilities().iRate );
+    HTI_LOG_FORMAT( " Parity    = %d", portCapabilities().iParity );
+    HTI_LOG_FORMAT( " DataBits  = %d", portCapabilities().iDataBits );
+    HTI_LOG_FORMAT( " StopBits  = %d", portCapabilities().iStopBits );
+    HTI_LOG_FORMAT( " Handshake = %d", portCapabilities().iHandshake );
+    HTI_LOG_FORMAT( " Signals   = %d", portCapabilities().iSignals );
+    HTI_LOG_FORMAT( " Fifo      = %d", portCapabilities().iFifo );
+    HTI_LOG_FORMAT( " SIR       = %d", portCapabilities().iSIR );
+
+    // Set port settings
+    TCommConfig portSettings;
+    iCommPort.Config( portSettings );
+    portSettings().iRate      = iDataRate;
+    portSettings().iParity    = iParity;
+    portSettings().iDataBits  = iDataBits;
+    portSettings().iStopBits  = iStopBits;
+    portSettings().iFifo      = EFifoEnable;
+    portSettings().iHandshake = iHandshake;
+
+    HTI_LOG_TEXT( "Port settings enum values:" );
+    HTI_LOG_FORMAT( " DataRate  %d", portSettings().iRate );
+    HTI_LOG_FORMAT( " Parity    %d", portSettings().iParity );
+    HTI_LOG_FORMAT( " DataBits  %d", portSettings().iDataBits );
+    HTI_LOG_FORMAT( " StopBits  %d", portSettings().iStopBits );
+    HTI_LOG_FORMAT( " Handshake 0x%x",  portSettings().iHandshake );
+    HTI_LOG_FORMAT( " Fifo      %d", portSettings().iFifo );
+
+    // Now activate the settings
+    err = iCommPort.SetConfig( portSettings );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "failed to set port settings %d", err );
+        ShowErrorNotifierL( _L( "Failed to set port settings" ), err );
+        }
+    User::LeaveIfError( err );
+
+    // Turn on DTR and RTS, and set our buffer size
+    iCommPort.SetSignals( KSignalDTR, 0 );
+    iCommPort.SetSignals( KSignalRTS, 0 );
+
+    iCommPort.SetReceiveBufferLength( KReceiveBufferLength );
+
+    // A null read or write powers up the port
+    TRequestStatus readStat;
+    TBuf8<1> temp_buffer;
+    iCommPort.Read( readStat, temp_buffer, 0 );
+    User::WaitForRequest( readStat );
+    err = readStat.Int();
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "Failed to power up the port %d", err );
+        ShowErrorNotifierL( _L( "Failed to power up the port" ), err );
+        }
+    User::LeaveIfError( err );
+
+    HTI_LOG_FUNC_OUT( "Serial::InitCommPortL" );
+    }
+
+void CHtiSerialCommEcomPlugin::Receive( TDes8& aRawdataBuf,
+                                        TRequestStatus& aStatus )
+    {
+    HTI_LOG_FUNC_IN( "Serial::Receive" );
+    HTI_LOG_FORMAT( "Buf max len: %d", aRawdataBuf.MaxLength() );
+    iCommPort.ReadOneOrMore( aStatus, aRawdataBuf );
+    HTI_LOG_FUNC_OUT( "Serial::Receive" );
+    }
+
+void CHtiSerialCommEcomPlugin::Send( const TDesC8& aRawdataBuf,
+                                           TRequestStatus& aStatus )
+    {
+    HTI_LOG_FUNC_IN( "Serial::Send" );
+    iCommPort.Write( aStatus, aRawdataBuf );
+    if ( iSendDelay > 0 )  // optional wait - can be set in serial comm cfg
+        {
+        // If sending large amounts of data from Symbian to PC is failing,
+        // the wait here seems to help.
+        User::After( iSendDelay );
+        }
+    HTI_LOG_FUNC_OUT( "Serial::Send" );
+    }
+
+void CHtiSerialCommEcomPlugin::CancelReceive()
+    {
+    HTI_LOG_FUNC_IN( "Serial::CancelReceive" );
+    iCommPort.ReadCancel();
+    HTI_LOG_FUNC_OUT( "Serial::CancelReceive" );
+    }
+
+void CHtiSerialCommEcomPlugin::CancelSend()
+    {
+    HTI_LOG_FUNC_IN( "Serial::CancelSend" );
+    iCommPort.WriteCancel();
+    HTI_LOG_FUNC_OUT( "Serial::CancelSend" );
+    }
+
+TInt CHtiSerialCommEcomPlugin::GetSendBufferSize()
+    {
+    return KSendBufferLength;
+    }
+
+TInt CHtiSerialCommEcomPlugin::GetReceiveBufferSize()
+    {
+    return KReceiveBufferLength;
+    }
+
+void CHtiSerialCommEcomPlugin::ShowErrorNotifierL( const TDesC& aText,
+                                                   TInt aErr )
+    {
+    RNotifier notifier;
+    User::LeaveIfError( notifier.Connect() );
+
+    TBuf<KMaxHtiNotifierLength> errorMsg;
+    // aText is cut if it's too long - leaving some space also for error code
+    errorMsg.Append( aText.Left( errorMsg.MaxLength() - 10 ) );
+    errorMsg.Append( _L("\n") );
+    errorMsg.AppendNum( aErr );
+
+    TRequestStatus status;
+    TInt button;
+    notifier.Notify( KHtiSerialError, errorMsg,
+                     KHtiOkButton, KNullDesC, button, status );
+    User::WaitForRequest( status );
+    notifier.Close();
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiSerialCommPlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM implementations in this dll
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiSerialCommEcomPlugin.h"
+
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+
+/*---------------------------------------------------------------------------*/
+// Provides a key value pair table, this is used to identify
+// the correct construction function for the requested interface.
+const TImplementationProxy ImplementationTable[] =
+    {
+        IMPLEMENTATION_PROXY_ENTRY(0x10210CCA,  CHtiSerialCommEcomPlugin::NewL)
+    };
+
+/*---------------------------------------------------------------------------*/
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiUsbSerialCommPlugin/data/200212CF.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for HtiUsbSerialComm ECOM plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+
+//  RESOURCE DEFINITIONS
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x200212CF;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB8;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x200212D0;
+                    version_no         = 1;
+                    display_name       = "USB Serial comm";
+                    default_data       = "USBSERIAL";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiUsbSerialCommPlugin/group/HtiUsbSerialComm.cfg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,32 @@
+# HTIUsbSerialComm communication plugin configuration file
+
+# The PortNumber parameter configures the number of the port to use.
+# Default value: 1
+
+#PortNumber=1
+
+
+# The DataRate parameter configures the speed of the port (bits/sec).
+# The port does not necessarily obey the data rate setting.
+# Default value: 115200
+
+#DataRate=2400
+#DataRate=4800
+#DataRate=9600
+#DataRate=19200
+#DataRate=38400
+#DataRate=57600
+#DataRate=115200
+#DataRate=576000
+#DataRate=1152000
+#DataRate=4000000
+
+# The RetryTimes parameter configures the retry amount(times) if the port opening fails.
+# Default value: 10
+
+#RetryTimes=10
+
+# The RetryInterval parameter configures the time(seconds) between retries if the port opening fails.
+# Default value: 10
+
+#RetryInterval=10
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiUsbSerialCommPlugin/group/HtiUsbSerialCommEcomPlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM Plugin project to support USB communication over
+*                serial port (Serial emulation via ACM).
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiUsbSerialCommEcomPlugin.dll
+TARGETTYPE      PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID             0x10009D8D 0x200212CF
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          proxy.cpp
+SOURCE          HtiUsbSerialCommEcomPlugin.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/200212CF.rss
+TARGET          HtiUsbSerialCommEcomPlugin.rsc
+END
+
+LIBRARY         c32.lib
+LIBRARY         euser.lib
+LIBRARY         ecom.lib
+LIBRARY         hticfg.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiUsbSerialCommPlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiUsbSerialCommPlugin build info
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiUsbSerialCommEcomPlugin.mmp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiUsbSerialCommPlugin/inc/HtiUsbSerialCommEcomPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,156 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin to communicate over USB serial emulation
+*
+*/
+
+
+#ifndef CHTIUSBSERIALCOMMECOMPLUGIN_H
+#define CHTIUSBSERIALCOMMECOMPLUGIN_H
+
+// INCLUDES
+#include <c32comm.h>
+#include <HtiCommPluginInterface.h> // defined in HtiFramework project
+
+// FORWARD DECLARATIONS
+class CHtiCfg;
+
+// CLASS DECLARATION
+/**
+* ECOM plugin module for communicating with PC using USB serial emulation.
+*
+*/
+class CHtiUsbSerialCommEcomPlugin :
+    public CHTICommPluginInterface
+    {
+public:
+
+    /**
+    * Create instance of plugin.
+    * Reads configuration, opens and initializes USB port.
+    * @return Plugin instance.
+    */
+    static CHtiUsbSerialCommEcomPlugin* NewL();
+
+    /**
+    * Destructor.
+    */
+    ~CHtiUsbSerialCommEcomPlugin();
+
+public: // Interface implementation
+
+    /**
+    * Receive data from USB serial port.
+    * The size of supplied buffer must equal to size given
+    * by GetReceiveBufferSize.
+    * The number of received bytes may be anything between 1
+    * and GetReceiveBufferSize.
+    *
+    * @param aRawdataBuf Buffer where the result is written
+    * @param aStatus Request status
+    */
+    void Receive( TDes8& aRawdataBuf, TRequestStatus& aStatus );
+
+    /**
+    * Send data to USB serial port. The size of data must not
+    * exceed GetSendBufferSize.
+    * @param aRawdataBuf Buffer where the data is read from.
+    * @param aStatus Request status
+    */
+    void Send( const TDesC8& aRawdataBuf, TRequestStatus& aStatus );
+
+    /**
+    * Cancel read operation
+    */
+    void CancelReceive();
+
+    /**
+    * Cancel send operation
+    */
+    void CancelSend();
+
+    /**
+     *  Return required buffer size for Send operation.
+     */
+    TInt GetSendBufferSize();
+
+    /**
+     *  Return required buffer size for Receive operation.
+     */
+    TInt GetReceiveBufferSize();
+
+private:
+
+    /**
+    * Constructor of this plugin.
+    */
+    CHtiUsbSerialCommEcomPlugin();
+
+    /**
+    * Second phase construction.
+    */
+    void ConstructL();
+
+    /**
+    * Load needed drivers and start comm server.
+    */
+    void InitCommServerL();
+
+    /**
+    * Setup USB serial port.
+    */
+    void InitCommPortL();
+
+    /**
+    * Load configuration file.
+    */
+    void LoadConfigL();
+
+    /**
+    * Read and parse the configuration values.
+    */
+    void ReadConfig();
+
+    /**
+    * Helper to get data rate capability bitmask.
+    */
+    TUint RateCapsBitmaskFromRate( TBps aDataRate );
+
+    /**
+    * Show error notifier dialog with text and error code.
+    */
+    void ShowErrorNotifierL( const TDesC& aText, TInt aErr );
+
+private: // Data
+
+    CHtiCfg* iCfg;
+
+    // port settings
+    TInt      iPortNumber;
+    TBps      iDataRate;
+    TParity   iParity;
+    TDataBits iDataBits;
+    TStopBits iStopBits;
+
+    // bitmask for handshake
+    TInt iHandshake;
+
+    RCommServ iCommServ;
+    RComm iCommPort;
+    };
+
+#endif // CHTIUSBSERIALCOMMECOMPLUGIN_H
+
+// End of file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiUsbSerialCommPlugin/src/HtiUsbSerialCommEcomPlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,524 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM plugin for serial communication over USB port
+*
+*/
+
+
+// INCLUDE FILES
+#include <badesca.h>
+#include <f32file.h>
+
+#include "HtiUsbSerialCommEcomPlugin.h"
+#include <HtiCfg.h>
+#include <HtiLogging.h>
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES
+
+// CONSTANTS
+_LIT( KHtiUsbSerialError, "HtiUsbSerialError" );
+_LIT( KHtiOkButton, "OK" );
+
+_LIT( KHtiCfgPath,          "\\" ); // root of drive
+_LIT( KHtiUsbSerialCommCfg, "HTIUsbSerialComm.cfg" );
+_LIT8( KUsbPortNumber,      "PortNumber" );
+_LIT8( KUsbDataRate,        "DataRate" );
+_LIT8( KUsbRetryTimes,      "RetryTimes" );
+_LIT8( KUsbRetryInterval,   "RetryInterval" );
+
+// _LIT( KUsbPddName, "" );
+_LIT( KUsbLddName, "EUSBC" );
+_LIT( KUsbCsyName, "ECACM");
+
+const TInt KDefaultUsbPort = 1;
+
+const static TUint KReceiveBufferLength = 4 * 1024;
+const static TUint KSendBufferLength =    4 * 1024;
+
+const static TInt KMaxHtiNotifierLength = 128;
+
+// MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+CHtiUsbSerialCommEcomPlugin* CHtiUsbSerialCommEcomPlugin::NewL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::NewL" );
+    CHtiUsbSerialCommEcomPlugin* plugin =
+        new ( ELeave ) CHtiUsbSerialCommEcomPlugin();
+    CleanupStack::PushL( plugin );
+    plugin->ConstructL();
+    CleanupStack::Pop( plugin );
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::NewL" );
+    return plugin;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::~CHtiUsbSerialCommEcomPlugin
+// Destructor.
+// -----------------------------------------------------------------------------
+CHtiUsbSerialCommEcomPlugin::~CHtiUsbSerialCommEcomPlugin()
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::~CHtiUsbSerialCommEcomPlugin" );
+    iCommPort.Close();
+    iCommServ.Close();
+    delete iCfg;
+    User::FreeLogicalDevice( KUsbLddName() );
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::~CHtiUsbSerialCommEcomPlugin" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::CHtiUsbSerialCommEcomPlugin
+// C++ default constructor can NOT contain any code, that might leave.
+// -----------------------------------------------------------------------------
+CHtiUsbSerialCommEcomPlugin::CHtiUsbSerialCommEcomPlugin()
+    {
+    // default port settings
+    iPortNumber = KDefaultUsbPort;
+    iDataRate   = EBps115200;
+    iParity     = EParityNone;
+    iDataBits   = EData8;
+    iStopBits   = EStop1;
+    iHandshake  = 0;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::ConstructL
+// Symbian 2nd phase constructor - can leave.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::ConstructL()
+    {
+    TRAPD( err, LoadConfigL() );
+    if ( err == KErrNone )
+        {
+        ReadConfig();
+        }
+    InitCommServerL();
+    InitCommPortL();
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::LoadConfigL
+// Loads the plugin configuration file from disk to iCfg.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::LoadConfigL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::LoadConfigL" );
+    iCfg = CHtiCfg::NewL();
+    HTI_LOG_TEXT( "CHtiCfg constructed - loading cfg file" );
+    iCfg->LoadCfgL( KHtiCfgPath, KHtiUsbSerialCommCfg );
+    HTI_LOG_TEXT( "Cfg file loaded" );
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::LoadConfigL" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::ReadConfig
+// Reads the parameters from loaded configuration file.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::ReadConfig()
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::ReadConfig" );
+
+    TInt portNumberCfg = 0;
+    TRAPD( paramErr,
+            portNumberCfg = iCfg->GetParameterIntL( KUsbPortNumber ) );
+    if ( paramErr != KErrNone )
+        {
+        HTI_LOG_FORMAT(
+            "PortNumber not defined in cfg, using default value %d",
+            iPortNumber );
+        portNumberCfg = iPortNumber;
+        }
+    iPortNumber = portNumberCfg;
+
+    TInt dataRateCfg = 0;
+    TRAP( paramErr, dataRateCfg = iCfg->GetParameterIntL( KUsbDataRate ) );
+    if ( paramErr != KErrNone )
+        {
+        HTI_LOG_TEXT( "DataRate not defined in cfg, using default" );
+        }
+    else
+        {
+        switch ( dataRateCfg )
+            {
+            case 2400:    iDataRate = EBps2400;    break;
+            case 4800:    iDataRate = EBps4800;    break;
+            case 9600:    iDataRate = EBps9600;    break;
+            case 19200:   iDataRate = EBps19200;   break;
+            case 38400:   iDataRate = EBps38400;   break;
+            case 57600:   iDataRate = EBps57600;   break;
+            case 115200:  iDataRate = EBps115200;  break;
+            case 576000:  iDataRate = EBps576000;  break;
+            case 1152000: iDataRate = EBps1152000; break;
+            case 4000000: iDataRate = EBps4000000; break;
+            default:
+                HTI_LOG_FORMAT(
+                    "Unsupported DataRate %d defined - using default",
+                    dataRateCfg );
+                break;
+            }
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::ReadConfig" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::InitCommServerL
+// Starts the comm server, loads comms module and device drivers.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::InitCommServerL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::InitCommServerL" );
+
+    TInt err = KErrNone;
+
+    // start the comm server
+    err = StartC32();
+    if ( err != KErrNone && err != KErrAlreadyExists )
+        {
+        ShowErrorNotifierL( _L( "Failed to start comm server" ), err );
+        User::Leave( err );
+        }
+
+    // connect to RCommServ
+    err = iCommServ.Connect();
+    if ( err != KErrNone )
+        {
+        ShowErrorNotifierL( _L( "Failed to connect to comm server" ), err );
+        User::Leave( err );
+        }
+
+    // load comms module (CSY file)
+    err = iCommServ.LoadCommModule( KUsbCsyName() );
+    if ( err != KErrNone )
+        {
+        ShowErrorNotifierL( _L( "Failed to load comms module" ), err );
+        User::Leave( err );
+        }
+
+    /* USB PDD is usually a kernel extension so no need to load separately.
+    // load physical device driver
+    TInt err = User::LoadPhysicalDevice( KUsbPddName );
+    if ( err != KErrNone && err != KErrAlreadyExists )
+        {
+        ShowErrorNotifierL( _L( "Failed to load USB PDD" ), err );
+        User::Leave( err );
+        }
+    */
+
+    // load logical device driver
+    err = User::LoadLogicalDevice( KUsbLddName() );
+    if ( err != KErrNone && err != KErrAlreadyExists )
+        {
+        ShowErrorNotifierL( _L( "Failed to load USB LDD" ), err );
+        User::Leave( err );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::InitCommServerL" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::InitCommPortL
+// Checks that the comms module is valid and opens the port.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::InitCommPortL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::InitCommPortL" );
+
+    TInt err = KErrNone;
+    // check the number of loaded comms modules
+    TInt commsCount = 0;
+    err = iCommServ.NumPorts( commsCount );
+    if ( err != KErrNone || commsCount < 1 )
+        {
+        if ( err != KErrNone )
+            {
+            ShowErrorNotifierL( _L( "Failed to get comms module count" ), err );
+            User::Leave( err );
+            }
+        else
+            {
+            ShowErrorNotifierL( _L( "No comms module loaded" ), KErrNotFound );
+            User::Leave( KErrNotFound );
+            }
+        }
+
+    HTI_LOG_FORMAT( "Found %d loaded comms modules", commsCount );
+
+    // get info about our loaded comms module
+    TSerialInfo serialInfo;
+    TBool found = EFalse;
+    for ( TInt i = 0; i < commsCount && !found; i++ )
+        {
+        TBuf<32> moduleName;
+        err = iCommServ.GetPortInfo( i, moduleName, serialInfo );
+        if ( err != KErrNone )
+            {
+            ShowErrorNotifierL( _L( "Failed to get port info" ), err );
+            User::Leave( err );
+            }
+        HTI_LOG_FORMAT( "Found comms module %S", &moduleName );
+        HTI_LOG_FORMAT( "Comms module description: %S",
+            &( serialInfo.iDescription ) );
+        if ( moduleName.CompareF( KUsbCsyName ) == 0 )
+            {
+            found = ETrue;
+            HTI_LOG_FORMAT( "Lowest port num  = %d", serialInfo.iLowUnit );
+            HTI_LOG_FORMAT( "Highest port num = %d", serialInfo.iHighUnit );
+            }
+        }
+
+    if ( !found )
+        {
+        ShowErrorNotifierL( _L( "Failed to get port info" ), KErrNotFound );
+        User::Leave( KErrNotFound );
+        }
+
+    // create port name
+    TBuf<KMaxPortName + 4> commPort;
+    commPort.Append( serialInfo.iName );
+    commPort.AppendFill( ':', 2 );
+    commPort.AppendNum( iPortNumber );
+    HTI_LOG_FORMAT( "Opening port %S", &commPort );
+
+    // try to open the port
+    err = iCommPort.Open( iCommServ, commPort, ECommExclusive, ECommRoleDTE );
+    if ( err )
+        {
+        //read retry parameters from cfg
+        TInt retryTimes = 10;
+        TRAPD( paramRetryTimesErr,
+                retryTimes = iCfg->GetParameterIntL( KUsbRetryTimes ) );
+        if ( paramRetryTimesErr != KErrNone )
+            {
+            HTI_LOG_TEXT( "RetryTimes is not defined in cfg, using default" );
+            }
+        HTI_LOG_FORMAT( " RetryTimes  = %d", retryTimes );
+        
+        TInt retryInterval = 10;
+        TRAPD( paramRetryIntervalErr,
+                retryInterval = iCfg->GetParameterIntL( KUsbRetryInterval ) );
+        if ( paramRetryIntervalErr != KErrNone )
+            {
+            HTI_LOG_TEXT( "RetryInterval is not defined in cfg, using default" );
+            }
+        HTI_LOG_FORMAT( " RetryInterval  = %d(s)", retryInterval );
+
+        // retry to open the port
+        for( TInt i=0; i<retryTimes; i++ )
+            {
+            User::After( retryInterval * 1000000 );
+            err = iCommPort.Open( iCommServ, commPort, ECommExclusive, ECommRoleDTE );
+            if( !err )
+                {
+                break;
+                }
+            }
+
+        if( err )
+            {
+            HTI_LOG_FORMAT( "Failed to open port %d", err );
+            ShowErrorNotifierL( _L( "Failed to open port" ), err );
+            }
+        }
+    User::LeaveIfError( err );
+    HTI_LOG_TEXT( "Port open - checking port capabilities" );
+
+    // check port data rate capability
+    TCommCaps portCaps;
+    iCommPort.Caps( portCaps );
+    HTI_LOG_TEXT( "Port capabilities:" );
+    HTI_LOG_FORMAT( " DataRate  = %d", portCaps().iRate );
+    HTI_LOG_FORMAT( " Parity    = %d", portCaps().iParity );
+    HTI_LOG_FORMAT( " DataBits  = %d", portCaps().iDataBits );
+    HTI_LOG_FORMAT( " StopBits  = %d", portCaps().iStopBits );
+    HTI_LOG_FORMAT( " Handshake = %d", portCaps().iHandshake );
+    HTI_LOG_FORMAT( " Signals   = %d", portCaps().iSignals );
+    HTI_LOG_FORMAT( " Fifo      = %d", portCaps().iFifo );
+    HTI_LOG_FORMAT( " SIR       = %d", portCaps().iSIR );
+
+    TUint reqRateCapsBitmask = RateCapsBitmaskFromRate( iDataRate );
+    HTI_LOG_FORMAT( "Required data rate capability bitmask %d",
+        reqRateCapsBitmask );
+
+    if ( reqRateCapsBitmask == 0 ||
+         ( reqRateCapsBitmask & portCaps().iRate ) == 0 )
+        {
+        ShowErrorNotifierL( _L( "Unsupported data rate configured" ),
+            KErrNotSupported );
+        User::Leave( KErrNotSupported );
+        }
+    HTI_LOG_TEXT( "Data rate supported - setting port configuration" );
+
+    // set port configuration
+    TCommConfig portSettings;
+    iCommPort.Config( portSettings );
+    portSettings().iRate      = iDataRate;
+    portSettings().iParity    = iParity;
+    portSettings().iDataBits  = iDataBits;
+    portSettings().iStopBits  = iStopBits;
+    portSettings().iFifo      = EFifoEnable;
+    portSettings().iHandshake = iHandshake;
+
+    err = iCommPort.SetConfig( portSettings );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "Failed to set port settings %d", err );
+        ShowErrorNotifierL( _L( "Failed to set port settings" ), err );
+        User::Leave( err );
+        }
+
+    iCommPort.SetReceiveBufferLength( KReceiveBufferLength );
+
+    HTI_LOG_TEXT( "Port open and configured" );
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::InitCommPortL" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::Receive
+// Receive data from comm port.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::Receive( TDes8& aRawdataBuf,
+                                        TRequestStatus& aStatus )
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::Receive" );
+    HTI_LOG_FORMAT( "Buf max len: %d", aRawdataBuf.MaxLength() );
+    iCommPort.ReadOneOrMore( aStatus, aRawdataBuf );
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::Receive" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::Send
+// Write data to comm port.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::Send( const TDesC8& aRawdataBuf,
+                                           TRequestStatus& aStatus )
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::Send" );
+    iCommPort.Write( aStatus, aRawdataBuf );
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::Send" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::CancelReceive
+// Cancel a pending read.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::CancelReceive()
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::CancelReceive" );
+    iCommPort.ReadCancel();
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::CancelReceive" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::CancelSend
+// Cancel a pending write.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::CancelSend()
+    {
+    HTI_LOG_FUNC_IN( "CHtiUsbSerialCommEcomPlugin::CancelSend" );
+    iCommPort.WriteCancel();
+    HTI_LOG_FUNC_OUT( "CHtiUsbSerialCommEcomPlugin::CancelSend" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::GetSendBufferSize
+// -----------------------------------------------------------------------------
+TInt CHtiUsbSerialCommEcomPlugin::GetSendBufferSize()
+    {
+    return KSendBufferLength;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::GetReceiveBufferSize
+// -----------------------------------------------------------------------------
+TInt CHtiUsbSerialCommEcomPlugin::GetReceiveBufferSize()
+    {
+    return KReceiveBufferLength;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::RateCapsBitmaskFromRate
+// Converts a TBps enumeration value to a corresponding bitmask.
+// -----------------------------------------------------------------------------
+TUint CHtiUsbSerialCommEcomPlugin::RateCapsBitmaskFromRate( TBps aDataRate )
+    {
+    switch ( aDataRate )
+        {
+        case EBps50:      return KCapsBps50;
+        case EBps75:      return KCapsBps75;
+        case EBps110:     return KCapsBps110;
+        case EBps134:     return KCapsBps134;
+        case EBps150:     return KCapsBps150;
+        case EBps300:     return KCapsBps300;
+        case EBps600:     return KCapsBps600;
+        case EBps1200:    return KCapsBps1200;
+        case EBps1800:    return KCapsBps1800;
+        case EBps2000:    return KCapsBps2000;
+        case EBps2400:    return KCapsBps2400;
+        case EBps3600:    return KCapsBps3600;
+        case EBps4800:    return KCapsBps4800;
+        case EBps7200:    return KCapsBps7200;
+        case EBps9600:    return KCapsBps9600;
+        case EBps19200:   return KCapsBps19200;
+        case EBps38400:   return KCapsBps38400;
+        case EBps57600:   return KCapsBps57600;
+        case EBps115200:  return KCapsBps115200;
+        case EBps230400:  return KCapsBps230400;
+        case EBps460800:  return KCapsBps460800;
+        case EBps576000:  return KCapsBps576000;
+        case EBps1152000: return KCapsBps1152000;
+        case EBps4000000: return KCapsBps4000000;
+        default:          return 0;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiUsbSerialCommEcomPlugin::ShowErrorNotifierL
+// Shows an error notifier dialog with text and error code.
+// -----------------------------------------------------------------------------
+void CHtiUsbSerialCommEcomPlugin::ShowErrorNotifierL( const TDesC& aText,
+                                                      TInt aErr )
+    {
+    RNotifier notifier;
+    User::LeaveIfError( notifier.Connect() );
+
+    TBuf<KMaxHtiNotifierLength> errorMsg;
+    // aText is cut if it's too long - leaving some space also for error code
+    errorMsg.Append( aText.Left( errorMsg.MaxLength() - 10 ) );
+    errorMsg.Append( _L("\n") );
+    errorMsg.AppendNum( aErr );
+
+    TRequestStatus status;
+    TInt button;
+    notifier.Notify( KHtiUsbSerialError, errorMsg,
+                     KHtiOkButton, KNullDesC, button, status );
+    User::WaitForRequest( status );
+    notifier.Close();
+    }
+
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiCommPlugins/HtiUsbSerialCommPlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  ECOM implementations in this dll
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiUsbSerialCommEcomPlugin.h"
+
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+
+/*---------------------------------------------------------------------------*/
+// Provides a key value pair table, this is used to identify
+// the correct construction function for the requested interface.
+const TImplementationProxy ImplementationTable[] =
+    {
+        IMPLEMENTATION_PROXY_ENTRY( 0x200212D0,
+            CHtiUsbSerialCommEcomPlugin::NewL )
+    };
+
+/*---------------------------------------------------------------------------*/
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+    {
+    aTableCount = sizeof( ImplementationTable ) / sizeof( TImplementationProxy );
+    return ImplementationTable;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFileHlp/group/HtiFileHlp.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build description file for HtiFileHlp
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiFileHlp.exe
+TARGETTYPE      EXE
+UID             0x1000008d 0x10210CC8
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL
+
+SOURCEPATH      ../src
+SOURCE          HtiFileHlp.cpp
+
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         efsrv.lib
+
+SMPSAFE
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFileHlp/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiFileHlp
+*
+*/
+
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+HtiFileHlp.mmp
+
+PRJ_TESTMMPFILES
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFileHlp/src/HtiFileHlp.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,210 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiFileHlp implementation. This exe is used for file operations
+*                to TCB folders (requiring capability ALL).
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <f32file.h>
+
+// CONSTANTS
+_LIT( KFileHlpName, "HtiFileHlp" );
+
+_LIT( KCmdCopy,   "c" );
+_LIT( KCmdDelete, "d" );
+_LIT( KCmdMkd,    "m" );
+_LIT( KCmdRmd,    "r" );
+_LIT( KCmdMove,   "mv" );
+_LIT( KCmdRename, "re" );
+_LIT( KDelimiter, "|" );
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ LOCAL FUNCTIONS ===============================
+
+LOCAL_C void HandleCopyMoveRenameL( TDesC& aCmd,
+		TDesC& aFromFile, TDesC& aToFile )
+    {
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+
+    CFileMan* fileMan = CFileMan::NewL( fs );
+    CleanupStack::PushL( fileMan );
+
+    if ( aCmd == KCmdCopy )
+    	{
+    	User::LeaveIfError( fileMan->Copy( aFromFile, aToFile,
+    			CFileMan::ERecurse|CFileMan::EOverWrite ) );
+    	}
+    else if ( aCmd == KCmdMove )
+    	{
+    	User::LeaveIfError( fileMan->Move( aFromFile, aToFile,
+    			CFileMan::ERecurse|CFileMan::EOverWrite ) );
+    	}
+    else
+    	{
+    	User::LeaveIfError( fileMan->Rename( aFromFile, aToFile ) );
+    	}
+
+    CleanupStack::PopAndDestroy();  // fileman
+    CleanupStack::PopAndDestroy();  // fs
+    }
+
+LOCAL_C void HandleDeleteL( TDesC& aFilename )
+    {
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+
+    // check that filenames are valid
+    if ( !fs.IsValidName( aFilename ) )
+        {
+        User::Leave( KErrBadName );
+        }
+
+    // delete file
+    User::LeaveIfError( fs.Delete( aFilename ) );
+
+    CleanupStack::PopAndDestroy();
+    }
+
+LOCAL_C void HandleMkdL( TDesC& aDirName )
+    {
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+
+    User::LeaveIfError( fs.MkDirAll( aDirName ) );
+
+    CleanupStack::PopAndDestroy();
+    }
+
+LOCAL_C void HandleRmdL( TDesC& aDirName )
+    {
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    CleanupClosePushL( fs );
+
+    CFileMan* fileMan = CFileMan::NewL( fs );
+    CleanupStack::PushL( fileMan );
+
+    User::LeaveIfError( fileMan->RmDir( aDirName ) );
+
+    CleanupStack::PopAndDestroy();
+    CleanupStack::PopAndDestroy();
+    }
+
+LOCAL_C TInt StartL()
+    {
+    TInt cmdLen = User::CommandLineLength();
+    if ( cmdLen < 3 )
+        {
+        User::Leave( KErrArgument );
+        }
+    HBufC* cmdLine = HBufC::NewLC( cmdLen );
+    TPtr ptCmdLine = cmdLine->Des();
+    User::CommandLine( ptCmdLine );
+
+    TInt paramStart = 0;
+    TInt paramEnd = 0;
+
+    // Take first parameter (the command)
+    paramEnd = cmdLine->Find( KDelimiter );
+    if ( paramEnd <= paramStart )
+        {
+        User::Leave( KErrArgument );
+        }
+    TPtrC cmd = cmdLine->Mid( paramStart, paramEnd - paramStart );
+
+    // Take the next parameter either until next delimiter or
+    // the rest of the command line.
+    paramStart = paramEnd + 1;
+    paramEnd = cmdLine->Mid( paramStart ).Find( KDelimiter ) + paramStart;
+    if ( paramEnd < paramStart )
+        {
+        // No delimiter found - this is the last parameter
+        paramEnd = cmdLen;
+        }
+
+    TPtrC param1 = cmdLine->Mid( paramStart, paramEnd - paramStart );
+
+    paramStart = paramEnd + 1;
+
+    if ( cmd == KCmdCopy || cmd == KCmdMove || cmd == KCmdRename )
+        {
+        // Copy, Move and Rename should have also the destination parameter
+        // It is assumed to be the rest of the command line from previous delim
+        if ( paramStart >= cmdLen )
+            {
+            User::Leave( KErrArgument );
+            }
+        TPtrC param2 = cmdLine->Mid( paramStart );
+        HandleCopyMoveRenameL( cmd, param1, param2 );
+        }
+    else if ( cmd == KCmdDelete )
+        {
+        HandleDeleteL( param1 );
+        }
+    else if ( cmd == KCmdMkd )
+        {
+        HandleMkdL( param1 );
+        }
+    else if ( cmd == KCmdRmd )
+        {
+        HandleRmdL( param1 );
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        }
+
+    CleanupStack::PopAndDestroy(); // cmdLine
+
+    return KErrNone;
+    }
+
+GLDEF_C TInt E32Main()
+    {
+    __UHEAP_MARK;
+
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    CActiveScheduler* scheduler = new ( ELeave ) CActiveScheduler;
+    CActiveScheduler::Install( scheduler );
+
+    User::RenameThread( KFileHlpName );
+
+    TRAPD( error, StartL() );
+
+    delete scheduler;
+    delete cleanup;
+    __UHEAP_MARKEND;
+
+    //__ASSERT_ALWAYS( !error, User::Panic( KFileHlpName, error ) );
+    return error;
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/group/HtiFramework.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project file for HTI Framework executable
+*
+*/
+
+#include <platform_paths.hrh>
+
+TARGET          HtiFramework.exe
+TARGETTYPE      EXE
+
+UID             0x1000008d 0x1020DEB6
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+USERINCLUDE    ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+SOURCE          HtiFramework.cpp
+SOURCE          HtiDispatcher.cpp
+SOURCE          HtiMessage.cpp
+SOURCE          HtiCommAdapter.cpp
+SOURCE          HtiMessageQueue.cpp
+SOURCE          HtiSecurityManager.cpp
+SOURCE          HtiNotifier.cpp
+
+EPOCSTACKSIZE   0x4000
+EPOCHEAPSIZE    0x400 0x800000
+
+LIBRARY         euser.lib
+LIBRARY         efsrv.lib
+LIBRARY         ecom.lib
+LIBRARY         bafl.lib
+LIBRARY         hticfg.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,30 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information for HtiFramework
+*
+*/
+
+
+PRJ_PLATFORMS
+DEFAULT
+
+PRJ_EXPORTS
+hti.cfg     +/winscw/c/hti.cfg
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+HtiFramework.mmp
+
+PRJ_TESTMMPFILES
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/group/hti.cfg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,97 @@
+# HTIFramework configuration file
+
+
+# Communication plug-in name (the name of ECOM plug-in)
+# Possible values: SERIAL, BTSERIAL, USBSERIAL, IPCOMM
+# Default value: USBSERIAL
+
+#CommPlugin=SERIAL
+#CommPlugin=BTSERIAL
+#CommPlugin=USBSERIAL
+#CommPlugin=IPCOMM
+
+
+# The maximum size of HTI message, in bytes
+# Default value: 10240 (10 kilobytes)
+
+#MaxMsgSize=10240
+
+
+# The amount of memory that can be used by messages
+# in the incoming queue, in bytes
+# Default value: 4194304 (4 megabytes)
+
+#MaxQueueSize=4194304
+
+
+# The heap size for HTI Framework, in bytes
+# Default value: 8388608 (8 megabytes)
+
+#MaxHeapSize=8388608
+
+
+# The priority of the HTI process. Bigger number means higher priority.
+# Default value: 3
+
+#Priority=1
+#Priority=2
+#Priority=3
+#Priority=4
+
+
+# The flag indicating whether or not to create the text console for HTI,
+# when HTI starts up. 0 means no, 1 means yes.
+# Default value: 0
+
+#ShowConsole=0
+#ShowConsole=1
+
+
+# The maximum time in seconds that HTI waits for hardware or emulator
+# to reach the normal state. HTI does not try to start up until the
+# normal state has been reached or maximum wait time has been expired.
+# This feature is required, because all the necessary servers need to
+# be up and running before HTI's communication plugin tries to use them.
+# Default value: 90
+
+#MaxWaitTime=90
+
+
+# The delay in seconds that HTI waits after the hardware or emulator
+# has reached the normal state. This additional delay is required,
+# because all the necessary servers are still not running, although
+# the normal state has been reached.
+# Default value: 5
+
+#StartUpDelay=5
+
+
+# The flag indicating whether or not to start HTI watch dog,
+# when HTI starts up. 0 means no, 1 means yes.
+# Default value: 0
+
+#EnableHtiWatchDog=0
+#EnableHtiWatchDog=1
+
+
+# The flag indicating whether or not HTI should start automatically when,
+# device starts. 0 means no, 1 means yes. If automatic start is not enabled,
+# HTI can be started manually from HtiAdmin application.
+# Default value: 1 
+
+#EnableHtiAutoStart=0
+#EnableHtiAutoStart=1
+
+
+# The flag indicating whether to show error dialog in case of critical
+# error or just silently exit. This does not affect error dialogs shown
+# by communication plugins or possible panic dialogs shown by the OS.
+# Default value: 1
+
+#ShowErrorDialogs=0
+#ShowErrorDialogs=1
+
+# The value in seconds that HTI will delay before reconnecting when connection lost,
+# If the value is 0, reconnect would not happen.
+# Default value: 0
+#ReconnectDelay=0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/inc/HtiCommAdapter.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,204 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of CCommAdapter that uses media plugins to read
+*        HTI messages and send new ones back. Because comm plug-in
+*        interface define async functions, this class is AO.
+*
+*/
+
+
+#ifndef MCOMMADAPTER_H__
+#define MCOMMADAPTER_H__
+
+#include <e32base.h>
+
+//forward declaration
+class CHtiDispatcher;
+class CHTICommPluginInterface;
+class CHtiMessage;
+
+class CHtiCommAdapter: public CActive
+    {
+private:
+    /**
+    * Enum of different states depending on the current operation
+    */
+    enum TCommState
+        {
+        EIdle,
+        EReceiving,
+        EReceivingCont,
+        ESending
+        };
+
+public:
+    /**
+    * Construct the object and adds it to CActiveScheduler.
+    *
+    * @param aCommPlugin communication plug-in
+    * @param aDispatcher message dispatcher
+    * @param aMaxMsgSize max size of an incoming message that will be
+    *           accepted
+    */
+    static CHtiCommAdapter* NewL(CHTICommPluginInterface* aCommPlugin,
+        CHtiDispatcher* aDispatcher,
+        TInt aMaxMsgSize);
+
+    /**
+    * Construct the object and adds it to CActiveScheduler
+    *
+    * @param aCommPlugin communication plug-in
+    * @param aDispatcher message dispatcher
+    * @param aMaxMsgSize max size of an incoming message that will be
+    *           accepted
+    */
+    static CHtiCommAdapter* NewLC(CHTICommPluginInterface* aCommPlugin,
+        CHtiDispatcher* aDispatcher,
+        TInt aMaxMsgSize);
+
+    /**
+    * Destructor
+    */
+    ~CHtiCommAdapter();
+
+    /**
+    * Issue an async request to receive whole HTI message and
+    * pass it to the framework on complition.
+    */
+    void ReceiveMessage();
+
+    /**
+    * Send a HTI message via comm plug-in.
+    * Ownership of aMessage is tranfered to CCommAdapter.
+    * When message is sent, aMessage will be deleted.
+    *
+    * @param aMessage a HTI message to send
+    */
+    void SendMessage(CHtiMessage* aMessage);
+
+    /**
+    * Stop all ongoing operations and clean all internal buffers.
+    */
+    void Reset();
+
+protected:
+
+    CHtiCommAdapter(CHtiDispatcher* aDispatcher,
+                 CHTICommPluginInterface* aCommPlugin,
+                TInt aMaxMsgSize);
+
+    void ConstructL();
+
+
+    /**
+    * Issue request to receive the next packet.
+    * If aContinue = ETrue than iState is set to EReceivingCont
+    * Otherwise it set to EReceiving.
+    * iState set to EReceivingCont after message beginning was received
+    * and its continuation is expected
+    *
+    * @param aContinue continuation flag
+    */
+    void ReceiveMessage(TBool aContinue);
+
+    /**
+    * Handle received data from buffer and reissue request
+    */
+    void HandleReceiveL();
+    void HandleReceiveContL();
+
+    /**
+    * Reissue request to send message
+    */
+    void HandleSend();
+
+
+protected: //from CActive
+    void RunL();
+    void DoCancel();
+    TInt RunError(TInt aError);
+
+private: //data members
+
+    /**
+    * Current communication state
+    */
+    TCommState iState;
+
+    /**
+    * Pointer to message dispatcher.
+    */
+    CHtiDispatcher* iDispatcher;
+
+    /**
+    * Communication ECom plug-in
+    */
+    CHTICommPluginInterface* iCommPlugin;
+
+    /**
+    * Buffer for receiving data. It'is allocated once and used for
+    * all subsequent receiving operation. Data from this buffer copied
+    * to iMsgToReceive buffer that than passed to the framework for
+    * processing
+    */
+    HBufC8* iBuffer;
+
+    /**
+    * Pointer to the buffer for receiveing data
+    */
+    TPtr8 iBufferPtr;
+
+    /**
+    * HTI incoming message. It's passed to the framework
+    * when whole message is received
+    */
+    CHtiMessage* iMsgToReceive;
+
+    /**
+    * Small buffer used when there is some data left in iBuffer that
+    * cannot be processed (less than min header size)
+    */
+    HBufC8* iLeftovers;
+
+    /**
+    * Keep message passed in SendMessage() between calls to comm. plugin
+    * and deleted when sending is complete
+    */
+    CHtiMessage* iMsgToSend;
+
+    /**
+    * Pointer to the part of iMsgToSend started from iMsgToSendOffset
+    * that is being sent via current comm. plug-in
+    */
+    TPtrC8 iMsgToSendPtr; //ptr to msg part passed to plug-ins
+
+    /**
+    * Offset in iMsgToSend of a part that is being sent
+    */
+    TInt iMsgToSendOffset;
+
+    /**
+    * Amount of receving bytes to skip.
+    * It's ussed when there is no memory for incoming message or
+    * its size too big.
+    */
+    TInt iSkipLength;
+
+    /**
+    * Max message size to accept
+    */
+    const TInt iMaxMessageSize;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/inc/HtiDispatcher.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,492 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of MDispatcher interface that used
+*        to dispatch incoming messages to servers
+*        and outcoming to host client.
+*        MDispatcher should be used by services to send outcoming
+*        messages and by communication modules to dispatch messages.
+*        This is the main class in HtiFramework.
+*
+*/
+
+
+#ifndef DISPATCHER_H__
+#define DISPATCHER_H__
+
+#include <e32base.h>
+#include <e32cons.h>
+#include "HtiDispatcherInterface.h"
+#include "HtiMessage.h"
+#include "HtiLogging.h"
+
+const static TUid KHtiSystemServiceUid = { 0x1020DEB6 };
+
+const static TInt KServiceArrayGranularity = 4;
+
+const static TInt KHandbrakeTimerIntervalMS = 100 * 1000; //in microseconds
+const static TInt KMaxFailedDispatchCalls = 4;
+
+//forward declarations
+class CHtiCommAdapter;
+//class CHtiMessage;
+class CHtiMessageQueue;
+class CHTIServicePluginInterface;
+class CHTICommPluginInterface;
+class CHtiSecurityManager;
+
+
+// HTI Framework error codes
+enum THtiError
+    {
+    EHtiErrBigMessage = 1,
+    EHtiErrNoMemory,
+    EHtiErrServiceNotFound,
+    EHtiErrServiceError,
+    EHtiErrNotAuthorized,
+    EHtiErrUnwrap
+    };
+
+// Types for restore factory settings
+enum TRfsType
+    {
+    ERfsUnknown = -1,
+    ERfsNormal  = 0,
+    ERfsDeep    = 1
+    };
+
+/**
+* Helper class that constructs messages
+* used by the HTI system service
+*
+**/
+class THtiSystemProtocolHelper
+    {
+public:
+    static TDesC8* ErrorMessageL( TInt aHtiErrorCode,
+                                  const TUid aTargetServiceUid );
+    static TDesC8* ErrorMessageL( TInt aHtiErrorCode,
+                                  const TUid aTargetServiceUid,
+                                  TInt aErrorCode,
+                                  const TDesC8& aErrorDescription );
+    static TDesC8* AuthMessageL( const TDesC8& aToken );
+    };
+
+class CHtiDispatcher:
+    public CBase,
+    public MHtiDispatcher
+    {
+public:
+    /**
+    * Creates dispatcher. Leaves on failure.
+    *
+    * @param aCommPlugin plug-in name to use for communication
+    * @param aMaxMsgSize maximum size for an incoming message
+    * @param aMaxQueueMemorySize maximum size of all messages in the
+    *        incoming queue
+    * @param aReconnectDelay seconds of delay for reconnecting when connection
+    *        lost. Value 0 means that reconnect would not happen.
+    * @param aShowConsole whether to open a console window for HTI
+    * @param aShowErrorDialogs whether to show a dialog in case of critical
+    *        error or just silently exit
+    * @return pointer to the created CHtiDispatcher instance
+    */
+    static CHtiDispatcher* NewL( const TDesC8& aCommPlugin,
+                                 TInt aMaxMsgSize,
+                                 TInt aMaxQueueMemorySize,
+                                 TInt aReconnectDelay,
+                                 TBool aShowConsole,
+                                 TBool aShowErrorDialogs );
+
+    /**
+    * Creates dispatcher and puts the created isntance to the cleanup stack.
+    * Leaves on failure.
+    *
+    * @param aCommPlugin plug-in name to use for communication
+    * @param aMaxMsgSize maximum size for an incoming message
+    * @param aMaxQueueMemorySize maximum size of all messages in the
+    *        incoming queue
+    * @param aReconnectDelay seconds of delay for reconnecting when connection
+    *        lost. Value 0 means that reconnect would not happen.
+    * @param aShowConsole whether to open a console window for HTI
+    * @param aShowErrorDialogs whether to show a dialog in case of critical
+    *        error or just silently exit
+    * @return pointer to the created CHtiDispatcher instance
+    */
+    static CHtiDispatcher* NewLC( const TDesC8& aCommPlugin,
+                                  TInt aMaxMsgSize,
+                                  TInt aMaxQueueMemorySize,
+                                  TInt aReconnectDelay,
+                                  TBool aShowConsole,
+                                  TBool aShowErrorDialogs );
+
+    /**
+    * Destructor. Frees the allocated resources.
+    */
+    ~CHtiDispatcher();
+
+    /**
+    *
+    * Parse message to a corresponding service
+    * The function returns immediately.
+    * Transfer ownership of aMessage.
+    *
+    *  @param aMessage contains incoming message
+    */
+    void DispatchIncomingMessage( CHtiMessage* aMessage );
+
+    /**
+    * Construct and dispath HTI error message. For internal use.
+    *
+    * @param aHtiErrorCode error code
+    * @param aTargetService UID of the service plug-in that caused the error
+    * @return standard Symbian error code
+    */
+    TInt DispatchOutgoingErrorMessage( THtiError aHtiErrorCode,
+                   const TUid aTargetService = KHtiSystemServiceUid );
+
+public: // Inherited methods from MHtiDispatcher
+    TInt DispatchOutgoingMessage( TDesC8* aMessage,
+                    const TUid aTargetServiceUid,
+                    TBool aWrappedFlag,
+                    THtiMessagePriority aPriority );
+
+    TInt DispatchOutgoingMessage( TDesC8* aMessage,
+                    const TUid aTargetServiceUid );
+
+    TInt DispatchOutgoingErrorMessage( TInt aErrorCode,
+                    const TDesC8& aErrorDescription,
+                    const TUid aTargetServiceUid );
+
+    /**
+    * Adds memory observer.
+    *
+    * @param anObserver memory observer
+    */
+    void AddMemoryObserver( MHtiMemoryObserver* anObserver );
+
+    /**
+    * Removes memory observer.
+    *
+    * @param anObserver memory observer
+    */
+    void RemoveMemoryObserver( MHtiMemoryObserver* anObserver );
+
+    /**
+    * Returns the amount of memory available for message in the incoming queue
+    *
+    */
+    TInt GetFreeMemory();
+
+    void Notify( TInt aError );
+
+    /*
+    * Returns a pointer to the HTI console
+    */
+    CConsoleBase* GetConsole();
+
+    /**
+    * Unload all service plugins and clear queues
+    */
+    void Reset();
+
+    /*
+    * Shutdown HTI and reboot the device.
+    *
+    * Called from service plug-ins or from EHtiReboot HtiSystem command
+    */
+    void ShutdownAndRebootDeviceL();
+
+    /*
+    * Query the ShowErrorDialogs configuration value.
+    * @return iShowErrorDialogs value
+    */
+    TBool GetShowErrorDialogs();
+
+    
+    /*
+     * Delay a period and reconnect when connection lost.
+     * If the period is 0, reconnect would not happen.
+     * @return whether reconnect
+     */
+     TBool CommReconnect();
+     
+protected:
+    /**
+    * Constructors
+    *
+    */
+    CHtiDispatcher( TInt aMaxQueueMemorySize, TInt aReconnectDelay, TBool aShowErrorDialogs );
+
+    void ConstructL( const TDesC8& aCommPlugin,
+                     TInt aMaxMsgSize,
+                     TBool aShowConsole );
+
+    /**
+    * Construct and dispath HTI error message. For internal use
+    *
+    * @param aHtiErrorCode error code
+    * @param aLeaveCode leave code that caused error
+    * @param aTargetServiceUid UID of the service plug-in that caused the error
+    *
+    */
+    TInt DispatchOutgoingErrorMessage( THtiError aHtiErrorCode,
+                                    TInt aLeaveCode,
+                                    const TUid aTargetServiceUid );
+
+    /**
+    * Ensures that iIdle is started
+    * when a new message come
+    *
+    */
+    void Start();
+
+    /**
+    * Does message dispatching one at a time
+    * This method is called by the static callback function
+    * DispatchCallback().
+    *
+    */
+    TInt DoDispatch();
+
+    void DoMemoryNotification();
+
+    /**
+    * Callback functions called by CIdle in idel time to
+    * process messages in the queues
+    *
+    * @param aObj the reference to a CHTIDispatcher is passed
+    *             to call its non-static DoDispatch() method
+    */
+    static TInt DispatchCallback( TAny* aObj );
+
+    /**
+    * Finds and if needed loads specified service
+    * Returns NULL if service in question was not found
+    *
+    */
+    CHTIServicePluginInterface* GetService( const TUid aServiceUid );
+
+    /**
+    * Destructs all loaded services from iLoadedServices array.
+    * Note this function does not delete iLoadedServices object itself.
+    *
+    */
+    void UnloadAllServices();
+
+    /**
+    * Used instead of panic when framework cannot work further
+    * Reason code and description used for logging
+    *
+    * @param aReason code for rebooting
+    * @param aReasonDescr description
+    */
+    void UrgentReboot( TInt aReason, const TDesC8& aReasonDescr );
+
+    /**
+    * Handle HTI message addressed to HTI system service.
+    * It's processed right in the dispatcher.
+    * The method is trapped and no special actions if it leaves.
+    * @param aMessage the message data
+    */
+    void HandleSystemMessageL( const TDesC8& aMessage );
+
+    // functions to handle HTI system commands
+
+    /**
+    * Phone reboot
+    *
+    */
+    void Reboot();
+
+    /**
+    * Activate restore factory settings. Causes also a reboot.
+    * The mode of restore factory settings (normal or deep) is
+    * defined by iRfsMode.
+    */
+    void RestoreFactorySettings();
+
+    /**
+    * Checks whether given file is in a ROM drive.
+    * @param aFileName full path to the file to check
+    */
+    TBool IsFileInRom( const TDesC& aFileName );
+
+    TDesC8* ServicePluginsListL();
+
+    /**
+    * Checks and readjust priorities of comm adapters and idle object to
+    * prevent overflow of message queues.
+    *
+    */
+    void CheckPriorities();
+
+    /**
+    * Kills HTI watchdog process if it exists.
+    *
+    */
+    void KillHtiWatchDogL();
+
+#ifdef __ENABLE_LOGGING__
+    /**
+    * List in log files all found comm and service plugins
+    */
+    void DebugListPlugins();
+#endif
+
+    /**
+    * Generate unique ID for HTI instance.
+    */
+    void CreateInstanceId();
+
+    /**
+    * Maps the service plugin protocol UID to implementation UID and vice versa.
+    */
+    TUid MapServicePluginUid( const TUid aUid );
+
+private:
+    /**
+    * used to dispatch messages when thread is free
+    */
+    CIdle* iIdle;
+
+    /**
+    * Indicates that iIdle was started
+    */
+    TBool iIdleActive;
+
+    /**
+    * Incoming message queue
+    * holds pointers to messages located in heap
+    */
+    CHtiMessageQueue* iIncomingQueue;
+
+    /**
+    * Outgoing message queue
+    * holds pointers to messages located in heap
+    */
+    CHtiMessageQueue* iOutgoingQueue;
+
+    /**
+    * loaded service plugins description
+    */
+    struct TServiceItem
+        {
+        TUid iServiceUid;
+        CHTIServicePluginInterface* iService; /** service instance */
+        };
+
+    /**
+    * An array that keeps all loaded service plugins
+    */
+    RArray<TServiceItem>* iLoadedServices;
+
+    /**
+    * Memory observers
+    */
+    RPointerArray<MHtiMemoryObserver>* iMemoryObservers;
+
+    /**
+    * Instance of comm. plug-in used by iListener and iSender.
+    * It's not used by dispatcher.
+    */
+    CHTICommPluginInterface* iCommPlugin;
+
+    /**
+    * CCommAdapter instance for constant receiving of incoming HTI messages
+    */
+    CHtiCommAdapter* iListener;
+
+    /**
+    * CCommAdapter instance for sending outgoing HTI messages
+    */
+    CHtiCommAdapter* iSender;
+
+    /**
+    * Security manager
+    */
+    CHtiSecurityManager* iSecurityManager;
+
+    /**
+    * maximum size of all messages in the incoming queue
+    */
+    const TInt iMaxQueueMemorySize;
+
+    /**
+    * Flag to indicate reboot after framework stoped
+    */
+    TBool iToReboot;
+
+    /**
+    * Flag indicating the requested factory settings restore mode.
+    */
+    TRfsType iRfsMode;
+
+    /**
+    * Queue size thresold for priorities readjusting
+    */
+    TInt iQueueSizeLowThresold;
+    TInt iQueueSizeHighThresold;
+
+    /**
+    * Console for HTI
+    */
+    CConsoleBase* iConsole;
+
+    /**
+    * By default the idle object and comm adapters AO will have the same priority
+    * iIdle will be added later to the AS that gives comm. adapter AO priority
+    * In case of very fast incoming data there is possibility that idle will not be
+    * called at all, because comm API will comlete async request at once. That will
+    * lead to incoming queue overflow. The solution is to change AOs priorities.
+    * Using AO priorities directly is complicated that active AO's priority cannot be changed.
+    * So the order of AOs with equal priorities used to change the way they will be
+    * picked up by AS.
+    * When new incoming message is added, in comm adapter AO, the incoming queue is checked
+    * in case it reaches predefined high-watermark, comm adapter AO is removed from AS and
+    * added again, so idle AO will be picked next time.
+    * when idle AO checks that incoming queue is less than predefined low-watermark, it will
+    * remove itself and add to AS, to give a way to comm adapter's AO.
+    * The following flag iIdleOverCommAdapter is used when idle is first in AS.
+    *
+    */
+    TBool iIdleOverCommAdapter;
+
+    /**
+    * Unique ID for HTI instance.
+    * The ID is generated only when it is queried for the first time (to add
+    * randomness). Until then it's zero.
+    */
+    TUint32 iHtiInstanceId;
+
+    /**
+    * Indicates whether to show error dialogs (notifiers) in case of critical
+    * errors or just silently exit.
+    */
+    TBool iShowErrorDialogs;
+    
+    /**
+     * Delay a period and reconnect when connection lost.
+     * If the period is 0, reconnect would not happen.
+     */
+    TInt iReconnectDelay;
+    
+    /**
+     * Indicates reboot reason.
+     * Reason type is defined in enum RStarterSession::TResetReason value in starterclient.h
+     */
+    TInt iRebootReason;
+    };
+
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/inc/HtiFramework.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Start HTI framework and provide configuration parameters.
+*
+*/
+
+
+#ifndef HTISERVER_H__
+#define HTISERVER_H__
+
+#include <e32base.h>
+#include <e32svr.h>
+#include <e32panic.h>
+
+#include "HtiDispatcher.h"
+
+class CHtiCfg;
+
+class CHtiFramework : public CBase
+    {
+    public:
+        static CHtiFramework* NewL();
+        ~CHtiFramework();
+
+        /**
+        * Entry point, called after CHTIServer constructed
+        */
+        TInt StartL();
+
+    protected:
+        CHtiFramework();
+        void ConstructL();
+        void StartHtiWatchDogL();
+        void WaitNormalState( TInt aMaxWaitTime, TInt aStartUpDelay );
+        TBool IsHtiRunning();
+        TBool IsStartAcceptedL( TBool aIsAutoStartEnabled );
+
+    private:
+
+    // HTI configuration
+    CHtiCfg* iCfg;
+
+    // Message dispatcher
+    CHtiDispatcher* iDispatcher;
+
+    // Pointer to original heap, used if bigger heap is created for HTI
+    RHeap* iOriginalHeap;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/inc/HtiMessage.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,253 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Hti Message incapsulates HTI protocol messages structure.
+*
+*/
+
+
+#ifndef MESSAGEPARSER_H__
+#define MESSAGEPARSER_H__
+
+#include <e32std.h>
+#include <e32base.h>
+
+
+const TInt KDefaultPriority = 0;
+const TInt KPriorityMask = 0x2;
+const TInt KHtiMsgServiceUidLen = 4;
+
+
+NONSHARABLE_CLASS(CHtiMessage)  : public CBase
+    {
+public:
+    /**
+    * Constructs and parses a new message from descriptor in question.
+    * This method is used to construct hti message from incoming data.
+    * The descriptor must start from HTI header.
+    * Available amount of data is copied from the descriptor depending
+    * on the message size value in the header. The remaining data of
+    * message body must be added using method AddToBody().
+    *
+    * @return new Hti message
+    *
+    * @see CheckValidHeader() for function to define either descriptor
+    *               starts from a valid Hti message header
+    * @see AddToBody()
+    */
+    static CHtiMessage* NewL(const TDesC8& aMessage);
+
+    /**
+    * Creates a new HTI message without extension.
+    * Can leave with KErrArgument if passed data are invalid
+    * or other system-wide leave code (e.g. KErrNoMemory).
+    * Ownership of aMessagBody is transfered.
+    * This method is used to create a new outgoing HTI message.
+    *
+    * @param aMessageBody message body content
+    * @param aServiceUid target service name
+    * @param aWraped flag to indicate either
+    *       Security manager must wrap message body
+    * @param aPriority message priority
+    *
+    */
+    static CHtiMessage* NewL(TDesC8* aMessageBody,
+        const TUid aServiceUid,
+        TBool aWraped = EFalse,
+        TInt aPriority = KDefaultPriority);
+
+    /**
+    * Creates a new HTI message with extension.
+    * Can leave with KErrArgument if passed data are invalid
+    * or other system-wide leave code (e.g. KErrNoMemory).
+    * Ownership of aMessagBody is transfered.
+    * This method is used to create a new outgoing HTI message.
+    *
+    * @param aMessageBody message body content
+    * @param aServiceUid target service name
+    * @param aExtBody extension content
+    * @param aWraped flag to indicate either
+    *       Security manager must wrap message body
+    * @param aPriority message priority
+    *
+    */
+    static CHtiMessage* NewL(TDesC8* aMessageBody,
+        const TUid aServiceUid,
+        const TDesC8& aExtBody,
+        TBool aWraped = EFalse,
+        TInt aPriority = KDefaultPriority);
+
+    /**
+    * Deletes all message data allocated in heap.
+    */
+    virtual ~CHtiMessage();
+
+    /**
+    * Returns ETrue when the descriptor in question starts from
+    * valid HTI header.
+    *
+    * @param aMessage descriptor with probable HTI message
+    *
+    * @return ETrue HTI header is valid
+    */
+    static TBool CheckValidHtiHeader(const TDesC8& aMessage);
+
+    /**
+    * Returns message size based on the header in question
+    *
+    * @param aMessage descriptor with an HTI message
+    */
+    static TInt Size(const TDesC8& aMessage);
+
+    /**
+    * Returns the minimal size of HTI message header.
+    *
+    */
+    static TInt MinHeaderSize();
+
+    /**
+    * Check either HTI message body has body of required size as specified
+    * in Hti header.
+    */
+    TBool IsBodyComplete() const;
+
+    /**
+    * Appends to the body a new part. If the descriptor length bigger
+    * than remaining space for message body, only part
+    * of the descritpor is copied to fill in all available space.
+    *
+    * @param aBodyPart descriptor with remaining message body
+    *
+    * @return number of bytes copied from the descriptor
+    */
+    TInt AddToBody(const TDesC8& aBodyPart);
+
+    /**
+    * Returns the size of a whole message (BodySize()+HeaderSize())
+    */
+    TInt Size() const;
+
+    /**
+    * Returns message service uid
+    */
+    TUid DestinationServiceUid() const;
+
+    /**
+    * Returns message body size
+    */
+    TInt BodySize() const;
+
+    /**
+    * Returns message priority
+    */
+    TInt Priority() const;
+
+    /**
+    * Returns wrap flag
+    */
+    TBool IsWrapped() const;
+
+    /**
+    * Returns header extension
+    */
+    TPtrC8 Extension() const;
+
+    /**
+    * Returns extention section size
+    */
+    TInt ExtSize() const;
+
+    /**
+    * Returns header size including extension section.
+    */
+    TInt HeaderSize() const;
+
+    /**
+    * Returns message body
+    */
+    TPtrC8 Body() const;
+
+    /**
+    * Return message header
+    */
+    TPtrC8 Header() const;
+
+public:
+    /**
+    * Returns the offset of a link data member
+    */
+    static const TInt iLinkOffset;
+
+protected:
+    /**
+    * Constructor
+    */
+    CHtiMessage();
+
+    /**
+    * Second-level constructors
+    */
+    void ConstructL(const TDesC8& aMessage);
+    void ConstructL(const TUid aServiceUid,
+            TDesC8* aMessageBody,
+            const TDesC8& aExtBody,
+            TBool aWraped,
+            TInt aPriority);
+    /**
+    * helper function that make TInt from 3 bytes in big-endian format
+    * @param aSrc bytes with integer
+    *
+    * @return integer
+    */
+    //static TInt ParseLittleEndian3(const TUint8* aSrc);
+
+private:
+    /**
+    * Link used when creating message queues
+    */
+    TSglQueLink iLink;
+
+    /**
+    * Message body used when constructing from parts
+    * when body is ready pointer is copied to iBodyDes
+    */
+    HBufC8* iBody;
+
+    /**
+    * Complete body, used for access methods
+    */
+    TDesC8* iBodyDes;
+
+    /**
+    * Message header in binary format
+    */
+    TUint8* iHeader;
+
+    /**
+    * Body size copied from iHeader for quick access
+    */
+    TInt iBodySize;
+
+    /**
+    * Service UID extracted from iHeader.
+    */
+    TUid iServiceUid;
+
+    /**
+    * Size of extension section to be added to the header
+    * Used during message construction from parts
+    */
+    TInt iExtRemainderSize;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/inc/HtiMessageQueue.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,127 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Simple FIFO Queue class based on single-linked list
+*        (TSglQue<CHtiMessage>). It alsoe provides functionality
+*        to monitor memory allocated by all messages.
+*
+*/
+
+
+#ifndef MESSAGEQUEUE_H__
+#define MESSAGEQUEUE_H__
+
+#include "HtiMessage.h"
+
+NONSHARABLE_CLASS(CHtiMessageQueue)  : public CBase
+    {
+public:
+    /**
+    * Create a new queue
+    *
+    */
+    static CHtiMessageQueue* NewL();
+
+    virtual ~CHtiMessageQueue();
+
+    /**
+    * Adds a new message to the queue
+    *
+    * @param aMessage instance of ready HTI message
+    */
+    void Add(CHtiMessage& aMessage);
+
+    /**
+    * Retrives a message from the queue
+    * and remove it from the queue
+    *
+    * @return a HTI message
+    */
+    CHtiMessage* Remove();
+
+    /**
+    * Removes specifeda message from the queue
+    *
+    * @param aMsg message to remove
+    * @return a HTI message
+    */
+    CHtiMessage* Remove( CHtiMessage* aMsg);
+
+    /**
+    * Deletes all messages from queue
+    */
+    void RemoveAll();
+
+    /**
+    * Starts iteration based on service names
+    * Each call to GetNext() will return next message to the service
+    * different from the service name in the current message
+    */
+    void StartServiceIteration();
+
+    /**
+    * Returns next message with service name different
+    * than in the current message.
+    * This method does not remove message from the queue, so ownership
+    * is not transfered. Remove( CHtiMessage* aMsg) should be used
+    * to delete the message from a queue.
+    *
+    * @return a HTI message or NULL if there is no messages anymore
+    */
+    CHtiMessage* GetNext();
+
+
+    /**
+    * Checks that the queue is empty
+    *
+    * @return ETrue if queue is empty
+    */
+    TBool IsEmpty() const;
+
+    /**
+    * Returns memory allocated by all messages in the queue
+    */
+    TInt QueueSize() const;
+
+protected:
+    CHtiMessageQueue();
+
+protected:
+    /**
+    * Queue
+    */
+    TSglQue<CHtiMessage> iQueue;
+
+    /**
+    * Current memory allocated by hti messages in the queue
+    */
+    TInt iMemoryAllocated;
+
+    /**
+    * queue iterator
+    */
+    TSglQueIter<CHtiMessage> iQueueIter;
+
+    /**
+    * last service uid
+    * used during iteration by service names
+    */
+    TUid iLastServiceUid;
+
+    /**
+    * Used to ommit service name checking for the first GetNext()
+    */
+    TBool iIsFirst;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/inc/HtiNotifier.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Provides a notifier service for all HTI binaries
+*
+*/
+
+#ifndef __HTINOTIFIER_H__
+#define __HTINOTIFIER_H__
+
+// INCLUDES
+#include <e32base.h>
+#include <e32std.h>
+
+const static TInt KMaxHtiNotifierLength = 128;
+
+// CLASS DECLARATION
+class CHtiNotifier : public CBase
+    {
+public:
+
+    /**
+    * Shows a notifier with text
+    * @param aText Text to display
+    * @return none
+    */
+    static void ShowErrorL( const TDesC& aText );
+
+    /**
+    * Shows a notifier with text and symbian error code as a string
+    * @param aText Formatted text to display
+    * @param aErr  Errorcode to display
+    * @return none
+    */
+    static void ShowErrorL( const TDesC& aText, TInt aErr );
+
+    };
+
+#endif // __HTINOTIFIER_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/inc/HtiSecurityManager.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,103 @@
+/*
+* Copyright (c) 2743 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Security interface for HTI framework will provide
+*        implementation of security functionality:
+*        - authenication (establishing security context),
+*        - integrity (generating Message Integrity Code),
+*        - confidentiality (message encryption/decryption).
+*        The interface and terms are based on the GSS API [RFC 2743].
+*
+*/
+
+
+#ifndef SECURITYMANAGER_H__
+#define SECURITYMANAGER_H__
+
+#include <e32base.h>
+
+
+class CHtiSecurityManager : public CBase
+    {
+public:
+    static CHtiSecurityManager* NewL();
+    static CHtiSecurityManager* NewLC();
+
+    virtual ~CHtiSecurityManager();
+
+    /**
+    * Processes the token in question and generates reply tokens
+    * for security context establishment.
+    * The function is called as many times as needed depending on
+    * underlying authentication algorithm
+    *
+    * @param aToken token received from client that wish to establish
+    *       communcation with HTI framework
+    *
+    * @return reply token that should be sent back to the client,
+    *         transfer ownership
+    */
+    TDesC8* SetSecurityContext(const TDesC8& aToken);
+
+    /**
+    * Checks either security context has been established
+    */
+    TBool IsContextEstablashed() const;
+
+    /**
+    * Reset security context
+    */
+    void ResetSecurityContext();
+
+    /**
+    * Implementeion of integrity and confedentiality services.
+    * It can generates message MIC and combine it with message.
+    * Optionaly, the message also can be encrypted.
+    *
+    * @param aMessage message to be wrapped
+    * @param aEncrypt flag indicates that message should be encrypted
+    *
+    * @return wrapped message ready to send, transfer ownership
+    *
+    */
+    TDesC8* WrapL(const TDesC8& aMessage, TBool aEncrypt = EFalse);
+
+    /**
+    * Implementeion of integrity and confedentiality services.
+    * It unwrape message that was previosly wrapped.
+    *
+    * @param aMessage wrapped message
+    *
+    * @return plain message ready for processing, transfer ownership
+    *
+    */
+    TDesC8* UnwrapL(const TDesC8& aMessage);
+
+    /**
+    * Generates MIC for a message in question.
+    *
+    * @param aMessage plain message
+    *
+    * @return MIC generated by an underlying algorithm (e.g. CRC16)
+    */
+    TPtrC8 MIC(const TDesC8& aMessage) const;
+
+protected:
+    CHtiSecurityManager();
+    void ConstructL();
+
+protected:
+    TBool iSecurityContext;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/src/HtiCommAdapter.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,556 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CHtiCommAdapter implementation
+*
+*/
+
+
+#include "HtiCommAdapter.h"
+#include "HtiDispatcher.h"
+#include "HtiCommPluginInterface.h"
+#include "HtiMessage.h"
+#include "HtiNotifier.h"
+
+#include "HtiLogging.h"
+
+//default value for max message size for incoming messages
+//used if value in constructor is not valid (<0)
+const static TInt KMaxMessageSize = 10 * 1024; // 10 KB
+
+const static TInt KHtiCommPriority = 2;
+
+_LIT( KCommPanic, "HtiCommAdapter" );
+
+CHtiCommAdapter* CHtiCommAdapter::NewLC( CHTICommPluginInterface* aCommPlugin,
+    CHtiDispatcher* aDispatcher, TInt aMaxMsgSize )
+    {
+    CHtiCommAdapter* obj = new (ELeave) CHtiCommAdapter( aDispatcher,
+                                        aCommPlugin, aMaxMsgSize );
+    CleanupStack::PushL( obj );
+    obj->ConstructL();
+    return obj;
+    }
+
+CHtiCommAdapter* CHtiCommAdapter::NewL( CHTICommPluginInterface* aCommPlugin,
+    CHtiDispatcher* aDispatcher, TInt aMaxMsgSize )
+    {
+    CHtiCommAdapter* obj = NewLC( aCommPlugin, aDispatcher, aMaxMsgSize );
+    CleanupStack::Pop();
+    return obj;
+    }
+
+CHtiCommAdapter::CHtiCommAdapter( CHtiDispatcher* aDispatcher,
+                           CHTICommPluginInterface* aCommPlugin,
+                           TInt aMaxMsgSize )
+    :CActive( KHtiCommPriority ),
+    iState( EIdle ),
+    iDispatcher( aDispatcher ),
+    iCommPlugin( aCommPlugin ),
+    iBufferPtr( NULL, 0 ),
+    iMsgToReceive( NULL ),
+    iMsgToSend( NULL ),
+    iMsgToSendPtr( NULL, 0 ),
+    iMsgToSendOffset( 0 ),
+    iSkipLength( 0 ),
+    iMaxMessageSize( aMaxMsgSize > 0 ? aMaxMsgSize : KMaxMessageSize )
+    {
+    HTI_LOG_FORMAT( "MaxMsgSize %d", iMaxMessageSize );
+    };
+
+CHtiCommAdapter::~CHtiCommAdapter()
+    {
+    HTI_LOG_FUNC_IN( "CHtiCommAdapter::~CHtiCommAdapter" );
+    Cancel();
+
+    delete iBuffer;
+    delete iLeftovers;
+
+    delete iMsgToReceive;
+    delete iMsgToSend;
+
+    HTI_LOG_FUNC_OUT( "CHtiCommAdapter::~CHtiCommAdapter" );
+    }
+
+void CHtiCommAdapter::ConstructL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiCommAdapter::ConstructL" );
+
+    //allocate recommended buffer plus some extra space
+    //needed to handle msg parsing
+    iBuffer = HBufC8::NewL( iCommPlugin->GetReceiveBufferSize() +
+                CHtiMessage::MinHeaderSize() );
+
+    iBuffer->Des().SetLength( iCommPlugin->GetReceiveBufferSize() );
+    iBufferPtr.Set( iBuffer->Des().LeftTPtr(
+            iCommPlugin->GetReceiveBufferSize() ) );
+
+    iLeftovers = HBufC8::NewL( CHtiMessage::MinHeaderSize() );
+
+    CActiveScheduler::Add( this );
+    HTI_LOG_FUNC_OUT( "CHtiCommAdapter::ConstructL" );
+    }
+
+void CHtiCommAdapter::ReceiveMessage()
+    {
+    ReceiveMessage( EFalse );
+    }
+
+void CHtiCommAdapter::ReceiveMessage( TBool aContinue )
+    {
+    HTI_LOG_FUNC_IN( "CHtiCommAdapter::ReceiveMessage" );
+
+    iState = aContinue?EReceivingCont:EReceiving;
+    iCommPlugin->Receive( iBufferPtr, iStatus );
+    SetActive();
+
+    HTI_LOG_FUNC_OUT( "CHtiCommAdapter::ReceiveMessage" );
+    }
+
+void CHtiCommAdapter::SendMessage( CHtiMessage* aMessage )
+    {
+    HTI_LOG_FUNC_IN( "CCommAdapter::SendMessage" );
+    iState = ESending;
+    if ( aMessage != NULL )
+        {
+        HTI_LOG_TEXT( "send first packet" );
+        iMsgToSend = aMessage;
+        iMsgToSendOffset = 0;
+
+        //first send header
+        iMsgToSendPtr.Set( iMsgToSend->Header() );
+        }
+    else if ( iMsgToSend != NULL )
+        {
+        //send next chunk
+        if ( iMsgToSend->BodySize() <=
+            ( iMsgToSendOffset + iCommPlugin->GetSendBufferSize() ) )
+            {
+            HTI_LOG_TEXT( "send remainder" );
+            iMsgToSendPtr.Set( iMsgToSend->Body().Mid( iMsgToSendOffset ) );
+            iMsgToSendOffset = iMsgToSend->BodySize(); //last sending
+            }
+        else
+            {
+            HTI_LOG_TEXT( "send packet" );
+            iMsgToSendPtr.Set( iMsgToSend->Body().Mid( iMsgToSendOffset,
+                                    iCommPlugin->GetSendBufferSize() ) );
+            iMsgToSendOffset += iCommPlugin->GetSendBufferSize();
+            }
+        }
+    else
+        {
+        User::Panic( KCommPanic, KErrGeneral );
+        }
+
+    iCommPlugin->Send( iMsgToSendPtr, iStatus );
+    SetActive();
+
+    HTI_LOG_FUNC_OUT( "CCommAdapter::SendMessage" );
+    }
+
+void CHtiCommAdapter::Reset()
+    {
+    HTI_LOG_FUNC_IN( "CHtiCommAdapter::Reset" );
+    Cancel();
+    //receiving msg
+    delete iMsgToReceive;
+    iMsgToReceive = NULL;
+
+    //send msg
+    delete iMsgToSend;
+    iMsgToSend = NULL;
+    iMsgToSendOffset = 0;
+
+    //empty buffers
+    iLeftovers->Des().Zero();
+    iBuffer->Des().Zero();
+    iSkipLength = 0;
+
+    //set idle
+    iState = EIdle;
+
+    HTI_LOG_FUNC_OUT( "CHtiCommAdapter::Reset" );
+    }
+
+void CHtiCommAdapter::RunL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiCommAdapter::RunL" );
+    HTI_LOG_FORMAT( "iStatus %d", iStatus.Int() );
+
+    //handle reset code common for all states
+    if ( iStatus == KErrComModuleReset )
+        {
+        HTI_LOG_TEXT( "Reset received from comm module" );
+        //reset dispatcher
+        iDispatcher->Reset();
+        //dispatcher will call Reset() for comm adapters and reissue requests
+        return;
+        }
+
+    //check for critical (unrecoverable) communication errors
+    else if ( iStatus == KErrServerTerminated )
+        {
+        if ( iDispatcher->GetShowErrorDialogs() )
+            {
+            User::Panic( KCommPanic, KErrServerTerminated );
+            }
+        else
+            {
+            User::Exit( KErrServerTerminated );
+            }
+        }
+    // USB errors from d32usbc.h
+    else if ( -6700 > iStatus.Int() && iStatus.Int() > -6712 )
+        {
+        if(iDispatcher->CommReconnect())
+            {
+            return;
+            }
+
+        if ( iDispatcher->GetShowErrorDialogs() )
+            {
+            TBuf<48> errorText;
+            errorText.Append( _L( "USB connection lost (" ) );
+            errorText.AppendNum( iStatus.Int() );
+            errorText.Append( _L( "). HTI stopped." ) );
+            CHtiNotifier::ShowErrorL( errorText );
+            }
+        User::Exit( KErrDisconnected );
+        }
+    else if ( iStatus == KErrDisconnected )
+        {
+        // This happens if Bluetooth connection is lost.
+        if(iDispatcher->CommReconnect())
+            {
+            return;
+            }
+        
+        if ( iDispatcher->GetShowErrorDialogs() )
+            {
+            CHtiNotifier::ShowErrorL(
+                    _L( "Connection lost. HTI stopped." ), KErrDisconnected );
+            }
+        User::Exit( KErrDisconnected );
+        }
+
+    switch ( iState )
+        {
+        case EReceiving:
+            //process
+            HTI_LOG_TEXT( "EReceiving" );
+            if ( iStatus == KErrNone )
+                {
+                iBuffer->Des().SetLength( iBufferPtr.Length() );
+                TRAPD( err, HandleReceiveL() );
+                if ( err != KErrNone )
+                    {
+                    HTI_LOG_FORMAT( "Error in HandleReceiveL %d", err );
+
+                    delete iMsgToReceive;
+                    iMsgToReceive = NULL;
+
+                    iDispatcher->Notify( err );
+
+                    ReceiveMessage();
+                    }
+                }
+            else
+                {
+                HTI_LOG_FORMAT( "Error %d, reissue request", iStatus.Int() );
+                iDispatcher->Notify( iStatus.Int() );
+                User::After(2000000);
+                ReceiveMessage();
+                }
+            break;
+        case EReceivingCont:
+            //process
+            HTI_LOG_TEXT( "EReceivingCont" );
+            if ( iStatus == KErrNone )
+                {
+                iBuffer->Des().SetLength( iBufferPtr.Length() );
+                TRAPD( err, HandleReceiveContL() );
+                if ( err != KErrNone )
+                    {
+                    HTI_LOG_FORMAT( "Error in HandleReceiveContL %d", err );
+
+                    delete iMsgToReceive;
+                    iMsgToReceive = NULL;
+
+                    iDispatcher->Notify( err );
+
+                    ReceiveMessage();
+                    }
+                }
+            else
+                {
+                HTI_LOG_FORMAT( "Error %d, reissue request", iStatus.Int() );
+                HTI_LOG_TEXT( "and dismiss received HTI msg beginning" );
+                delete iMsgToReceive;
+                iMsgToReceive = NULL;
+
+                iDispatcher->Notify( iStatus.Int() );
+                User::After(2000000);
+                ReceiveMessage();
+                }
+            break;
+        case ESending:
+            HTI_LOG_TEXT( "ESending" );
+            if ( iStatus == KErrNone )
+                {
+                HandleSend();
+                }
+            else
+                {
+                HTI_LOG_FORMAT( "Error %d, stop sending, go to EIdle", iStatus.Int() );
+
+                delete iMsgToSend;
+                iMsgToSend = NULL;
+                iMsgToSendOffset = 0;
+                iState = EIdle;
+
+                iDispatcher->Notify( iStatus.Int() );
+                }
+            break;
+        case EIdle:
+            //ERROR
+            HTI_LOG_TEXT( "EIdle" );
+            User::Panic( KCommPanic, KErrGeneral );
+            break;
+        default:
+            //ERROR
+            HTI_LOG_TEXT( "default" );
+            User::Panic( KCommPanic, KErrGeneral );
+        };
+
+    HTI_LOG_FUNC_OUT( "CHtiCommAdapter::RunL" );
+    }
+
+void CHtiCommAdapter::HandleReceiveL()
+    {
+    TBool toContinue = EFalse; //for reissuing state
+
+    if ( iLeftovers->Length() > 0 )
+        {
+        HTI_LOG_TEXT( "handle leftovers" );
+        //if something left from previous time
+        //insert it to the buffer beggining
+        //check that there is enough space (should be)
+        if ( iBuffer->Length() + iLeftovers->Length() <=
+             iBuffer->Des().MaxLength() )
+            {
+            iBuffer->Des().Insert( 0, *iLeftovers );
+            }
+        else
+            {
+            //error
+            HTI_LOG_TEXT( "iMsgToReceive contain too much leftovers, drop them" );
+            }
+
+        iLeftovers->Des().Zero();
+        }
+
+    //use loop cause can be several HTI messages in iBuffer
+    while ( iBuffer->Length() >= CHtiMessage::MinHeaderSize() )
+        {
+        HTI_LOG_FORMAT( "iBuffer.Length() %d", iBuffer->Length() );
+        HTI_LOG_TEXT( "check header" );
+
+        if ( CHtiMessage::CheckValidHtiHeader( *iBuffer ) )
+            {
+            HTI_LOG_TEXT( "valid header" );
+            TInt msgSize = CHtiMessage::Size( *iBuffer );
+            HTI_LOG_FORMAT( "msgSize %d", msgSize );
+            HTI_LOG_HEX( iBuffer->Des().Ptr(), 14 );
+
+            __ASSERT_ALWAYS( iMsgToReceive == NULL,
+                            User::Panic( KCommPanic, KErrGeneral ) );
+
+            //check msgSize is acceptable
+            if ( msgSize > iMaxMessageSize )
+                {
+                //send err message
+                iDispatcher->DispatchOutgoingErrorMessage( EHtiErrBigMessage );
+                iSkipLength = msgSize;
+                }
+            else if ( msgSize > iDispatcher->GetFreeMemory() )
+                {
+                //send err message
+                iDispatcher->DispatchOutgoingErrorMessage( EHtiErrNoMemory );
+                iSkipLength = msgSize;
+                }
+            else
+                {
+                iMsgToReceive = CHtiMessage::NewL( *iBuffer );
+                }
+
+            if ( iMsgToReceive == NULL )
+                {
+                HTI_LOG_TEXT( "skip message" );
+                if ( iSkipLength > iBuffer->Length() )
+                    {
+                    iSkipLength -= iBuffer->Length();
+                    iBuffer->Des().Zero();
+                    // and continue to receive HTI message
+                    //switch state to EReceiveCont
+                    toContinue = ETrue;
+                    }
+                else
+                    {
+                    //should not be here, but just in case
+                    iBuffer->Des().Delete( 0, iSkipLength );
+                    iSkipLength = 0;
+                    }
+                }
+            else if ( iMsgToReceive->IsBodyComplete() )
+                {
+                HTI_LOG_TEXT( "handle small message" );
+                //iMsgToReceive is already contain whole HTI message
+                iDispatcher->DispatchIncomingMessage( iMsgToReceive );
+
+                //delete sent msg from buffer (and procces the rest)
+                iBuffer->Des().Delete( 0, iMsgToReceive->Size() );
+                iMsgToReceive = NULL;
+                }
+            else
+                {
+                HTI_LOG_TEXT( "start receive big message" );
+                //clear it to leave loop
+                iBuffer->Des().Zero();
+                // and continue to receive HTI message
+                //switch state to EReceiveCont
+                toContinue = ETrue;
+                }
+            }
+        else
+            {
+            HTI_LOG_TEXT( "invalid header, dismiss buffer and reissue request" );
+            HTI_LOG_HEX( iBuffer->Des().Ptr(), 14 );
+            // clear all buffer cause don't know where is valid header starts
+            // and wait for the next packet
+            iBuffer->Des().Zero(); //to leave loop
+            }
+        }
+
+    if ( iBuffer->Length() > 0 )
+        {
+        HTI_LOG_FORMAT( "copy leftovers %d", iBuffer->Length() );
+        //header beggining left in the buffer
+        //copy it to iLeftovers
+        ( *iLeftovers ) = ( *iBuffer );
+        }
+    //reissue request
+    ReceiveMessage( toContinue );
+    }
+
+void CHtiCommAdapter::HandleReceiveContL()
+    {
+    HTI_LOG_FORMAT( "In buffer: %d", iBuffer->Length() );
+    TBool toContinue = ETrue;
+
+    if ( iMsgToReceive != NULL && iSkipLength == 0 )
+        {
+        //add new packet to a message
+        TInt copyLen = iMsgToReceive->AddToBody( *iBuffer );
+
+        //delete what we copied to the message
+        iBuffer->Des().Delete( 0, copyLen );
+
+        if ( iMsgToReceive->IsBodyComplete() )
+            {
+            HTI_LOG_FORMAT( "body complete: %d", iMsgToReceive->BodySize() );
+
+            iDispatcher->DispatchIncomingMessage( iMsgToReceive );
+            iMsgToReceive = NULL;
+
+            //message complete, go to state EReceive
+            toContinue = EFalse;
+            }
+        }
+    else if ( iSkipLength > 0 )
+        {
+        HTI_LOG_FORMAT( "continue skipping, remains %d", iSkipLength );
+
+        if ( iSkipLength > iBuffer->Length() )
+            {
+            iSkipLength -= iBuffer->Length();
+            iBuffer->Des().Zero();
+            }
+        else
+            {
+            //skip last bytes
+            iBuffer->Des().Delete( 0, iSkipLength );
+            iSkipLength = 0;
+
+            toContinue = EFalse;
+            }
+        }
+
+    if ( iBuffer->Length() > 0 )
+        {
+        //process remainder and reissue in HandleReceiveL()
+        HandleReceiveL();
+        }
+    else
+        {
+        //reissue
+        ReceiveMessage(toContinue);
+        }
+    }
+
+void CHtiCommAdapter::HandleSend()
+    {
+    if ( iMsgToSendOffset < iMsgToSend->BodySize() )
+        {
+        //reissuse sending
+        SendMessage( NULL );
+        }
+    else
+        {
+        HTI_LOG_TEXT( "finish send, go to idle" );
+        iMsgToSendOffset = 0;
+        delete iMsgToSend;
+        iMsgToSend = NULL;
+        iState = EIdle;
+        iDispatcher->Notify( KErrNone );
+        }
+    }
+
+TInt CHtiCommAdapter::RunError( TInt aError )
+    {
+    TInt err = aError;
+    switch ( aError )
+        {
+        case KErrNoMemory:
+            break;
+        case KErrNotFound:
+            break;
+        }
+    return err;
+    }
+
+void CHtiCommAdapter::DoCancel()
+    {
+    switch ( iState )
+        {
+        case EReceiving:
+        case EReceivingCont:
+            iCommPlugin->CancelReceive();
+            break;
+        case ESending:
+            iCommPlugin->CancelSend();
+            break;
+        default:
+            break;
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/src/HtiDispatcher.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1334 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains the implementations of the CHTIDispatcher
+*                class.
+*
+*/
+
+
+#include "HtiDispatcher.h"
+#include "HtiMessage.h"
+#include "HtiMessageQueue.h"
+#include "HtiLogging.h"
+#include "HtiCommAdapter.h"
+#include "HtiServicePluginInterface.h"
+#include "HtiCommPluginInterface.h"
+#include "HtiSecurityManager.h"
+#include "HtiVersion.h"
+
+#include <e32debug.h>
+
+//active objects priorities
+const static TInt KHtiIdlePriority = 2;
+
+const static TInt KDefaultMaxQueueSize = 4 * 1024 * 1024; // 4 MB
+
+//HTI system service commands
+enum THtiCommand
+    {
+    EHtiAuthentication = 0x01,
+    EHtiVersion        = 0x02,
+    EHtiServiceList    = 0x03,
+    EHtiStop           = 0x04,
+    EHtiReboot         = 0x05,
+    EHtiFormat         = 0x06,
+    EHtiReset          = 0x07,
+    EHtiShowConsole    = 0x08,
+    EHtiHideConsole    = 0x09,
+    EHtiInstanceId     = 0x0A,
+    EHtiDebugPrint     = 0x0B,
+    EHtiRestartServices= 0x0C,
+    EHtiError          = 0xFF
+    };
+
+//HTI error messages
+const static TInt KMaxErrMessageLength = KErrorDescriptionMaxLength + 10;
+
+//error descriptions
+_LIT8( KHtiSystemCmdErrDescr, "Unknown HTI command" );
+_LIT8( KErrDescrDispatchOut, "Failed to dispatch message" );
+_LIT8( KErrDescrWrap, "Failed to wrap message" );
+_LIT8( KErrDescrDispatchOutError, "Failed to dispatch error message" );
+_LIT8( KErrDescrInvalidParameter, "Invalid command parameter" );
+_LIT8( KErrDescrNotInRom, "Command supported only if HTI is running from ROM" );
+
+const static TChar KSpChar = ' ';
+const static TChar KNewLineChar = '\n';
+const static TInt KHtiServiceNameLength = 124;
+const static TInt KHtiServiceListRecordLength = KHtiServiceNameLength + 4;
+
+_LIT( KHtiWatchDogMatchPattern, "HtiWatchDog*" );
+_LIT( KHtiDeviceRebootExeOS,    "HtiDeviceRebootOS.exe" );
+_LIT( KHtiDeviceRebootExeUI,    "HtiDeviceRebootUI.exe" );
+_LIT( KHtiRestartExeName,       "HtiRestart.exe");
+
+_LIT( KParamNormalRfs, "rfsnormal" );
+_LIT( KParamDeepRfs,   "rfsdeep" );
+
+TDesC8* THtiSystemProtocolHelper::ErrorMessageL( TInt aHtiErrorCode,
+                                  const TUid aTargetServiceUid )
+    {
+    HBufC8* msg = HBufC8::NewL( KMaxErrMessageLength );
+    msg->Des().Append( EHtiError ); //one byte
+    msg->Des().Append( aHtiErrorCode ); //one byte
+    msg->Des().AppendFill( 0x00, 4 ); //missed service error code
+    //append uid as TInt32 by copying 4 bytes through pointer
+    msg->Des().Append( ( TUint8* )( &( aTargetServiceUid.iUid ) ), 4 );
+    return msg;
+    }
+
+TDesC8* THtiSystemProtocolHelper::ErrorMessageL( TInt aHtiErrorCode,
+                                  const TUid aTargetServiceUid,
+                                  TInt aErrorCode,
+                                  const TDesC8& aErrorDescription )
+    {
+    HBufC8* msg = HBufC8::NewL( KMaxErrMessageLength );
+    msg->Des().Append( EHtiError ); //one byte
+    msg->Des().Append( aHtiErrorCode ); //one byte
+    msg->Des().Append( ( TUint8* ) ( &aErrorCode ), 4 ); //4 bytes
+    //append uid as TInt32 by copying 4 bytes through pointer
+    msg->Des().Append( ( TUint8* )( &( aTargetServiceUid.iUid ) ), 4 );
+    msg->Des().Append( aErrorDescription );
+    return msg;
+    }
+
+TDesC8* THtiSystemProtocolHelper::AuthMessageL( const TDesC8& aToken )
+    {
+    HBufC8* msg = HBufC8::NewL( aToken.Length() + 1 );
+    msg->Des().Append( EHtiAuthentication );
+    msg->Des().Append( aToken );
+    return msg;
+    }
+
+/*************************************************************************
+*   CHtiDispatcher implementation
+*
+**************************************************************************/
+CHtiDispatcher::CHtiDispatcher( TInt aMaxQueueMemorySize,
+        TInt aReconnectDelay, TBool aShowErrorDialogs ):
+    iIdleActive( EFalse ),
+    iMaxQueueMemorySize( aMaxQueueMemorySize > 0 ?
+                         aMaxQueueMemorySize : KDefaultMaxQueueSize ),
+    iToReboot( EFalse ),
+    iRfsMode( ERfsUnknown ),
+    iConsole( NULL ),
+    iIdleOverCommAdapter( EFalse ),
+    iHtiInstanceId( 0 ),
+    iShowErrorDialogs( aShowErrorDialogs ),
+    iReconnectDelay(aReconnectDelay),
+    iRebootReason(-1)
+    {
+    HTI_LOG_FORMAT( "MaxQueueMemorySize %d", iMaxQueueMemorySize );
+    iQueueSizeLowThresold = ( iMaxQueueMemorySize / 2 ) / 2;
+    iQueueSizeHighThresold = ( iMaxQueueMemorySize / 2 ) * 4 / 5;
+    HTI_LOG_FORMAT( "QueueSizeThresholds low : %d", iQueueSizeLowThresold );
+    HTI_LOG_FORMAT( "QueueSizeThresholds high: %d", iQueueSizeHighThresold );
+    }
+
+void CHtiDispatcher::ConstructL( const TDesC8& aCommPlugin,
+                                 TInt aMaxMsgSize,
+                                 TBool aShowConsole )
+    {
+    HTI_LOG_FUNC_IN( "CHTIDispatcher::ConstructL()" );
+#ifdef __ENABLE_LOGGING__
+    DebugListPlugins();
+#endif
+
+    if ( aShowConsole )
+        {
+        // Create the HTI console
+        iConsole = Console::NewL( _L( "HtiFramework" ),
+                                  TSize( KConsFullScreen, KConsFullScreen ) );
+        iConsole->Printf( _L( "HTI Framework\n" ) );
+        iConsole->Printf( _L( "=============\n\n" ) );
+        iConsole->Printf( _L( "Version %u.%u\n" ),
+                KHtiVersionMajor, KHtiVersionMinor );
+        iConsole->Printf( _L( "Starting up...\n" ) );
+        }
+
+    //create queues
+    iIncomingQueue = CHtiMessageQueue::NewL();
+    iOutgoingQueue = CHtiMessageQueue::NewL();
+
+    //security manager init
+    iSecurityManager = CHtiSecurityManager::NewL();
+
+    //plugins array
+    iLoadedServices = new (ELeave)
+                        RArray<TServiceItem>( KServiceArrayGranularity );
+
+    iMemoryObservers = new (ELeave)
+                        RPointerArray<MHtiMemoryObserver>( KServiceArrayGranularity );
+
+    //try to load default plugin if specified can't be found
+    if ( aCommPlugin.Length() == 0 )
+        {
+        HTI_LOG_TEXT( "load default comm plugin" );
+        iCommPlugin = CHTICommPluginInterface::NewL();
+        }
+    else
+        {
+        HTI_LOG_TEXT( "load Comm plugin" );
+        HTI_LOG_DES( aCommPlugin );
+        iCommPlugin = CHTICommPluginInterface::NewL( aCommPlugin );
+        }
+
+    if ( iConsole )
+        {
+        iConsole->Printf( _L( "Communication plugin loaded.\n" ) );
+        }
+
+    iListener = CHtiCommAdapter::NewL( iCommPlugin, this, aMaxMsgSize );
+    iSender = CHtiCommAdapter::NewL( iCommPlugin, this, aMaxMsgSize );
+
+    //!!!!!!!!!!!!! -=IMPORTANT=- !!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    // idle should be created (added to AS) AFTER comm adapters
+    //!!!!!!!!!!!!! -=IMPORTANT=- !!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    //create CIdle object
+    iIdle = CIdle::NewL( KHtiIdlePriority );
+
+    // start listening for incoming messages
+    Reset();
+
+    HTI_LOG_FUNC_OUT( "CHTIDispatcher::ConstructL()" );
+    }
+
+CHtiDispatcher::~CHtiDispatcher()
+    {
+    HTI_LOG_FUNC_IN( "CHTIDispatcher::~CHTIDispatcher" );
+
+    if ( iIdle )
+    {
+        iIdle->Cancel();
+        delete iIdle;
+    }
+
+    UnloadAllServices();
+
+    if ( iLoadedServices )
+        {
+        iLoadedServices->Close();
+        delete iLoadedServices;
+        }
+
+    if ( iMemoryObservers )
+    {
+        iMemoryObservers->Close();
+        delete iMemoryObservers;
+    }
+
+    delete iIncomingQueue;
+    delete iOutgoingQueue;
+
+    delete iListener;
+    delete iSender;
+
+    delete iCommPlugin;
+
+    REComSession::FinalClose();
+
+    delete iSecurityManager;
+
+    if ( iRfsMode == ERfsNormal || iRfsMode == ERfsDeep )
+        {
+        HTI_LOG_FORMAT( "Activating Restore Factory Settings %d", iRfsMode );
+        RestoreFactorySettings();
+        }
+
+    if ( iToReboot )
+        {
+        HTI_LOG_TEXT( "Reboot now" );
+        Reboot();
+        }
+
+    delete iConsole;
+
+    HTI_LOG_FUNC_OUT( "CHTIDispatcher::~CHTIDispatcher" );
+    }
+
+
+CHtiDispatcher* CHtiDispatcher::NewLC( const TDesC8& aCommPlugin,
+                                TInt aMaxMsgSize,
+                                TInt aMaxQueueMemory,
+                                TInt aReconnectDelay,
+                                TBool aShowConsole,
+                                TBool aShowErrorDialogs )
+    {
+    CHtiDispatcher* obj = new (ELeave) CHtiDispatcher(
+            aMaxQueueMemory, aReconnectDelay,aShowErrorDialogs );
+    CleanupStack::PushL( obj );
+    obj->ConstructL( aCommPlugin, aMaxMsgSize, aShowConsole );
+    return obj;
+    }
+
+CHtiDispatcher* CHtiDispatcher::NewL( const TDesC8& aCommPlugin,
+                                TInt aMaxMsgSize,
+                                TInt aMaxQueueMemory,
+                                TInt aReconnectDelay,
+                                TBool aShowConsole,
+                                TBool aShowErrorDialogs )
+    {
+    CHtiDispatcher* obj = NewLC( aCommPlugin, aMaxMsgSize, aMaxQueueMemory,
+            aReconnectDelay,aShowConsole, aShowErrorDialogs );
+    CleanupStack::Pop();
+    return obj;
+    }
+
+CConsoleBase* CHtiDispatcher::GetConsole()
+    {
+    return iConsole;
+    }
+
+TBool CHtiDispatcher::GetShowErrorDialogs()
+    {
+    return iShowErrorDialogs;
+    }
+
+void CHtiDispatcher::CheckPriorities()
+    {
+    // If incoming queue reaches some high limit then lower its priority
+    // below idle object priority.
+    // Make opposite when incoming queue size reaches some low limit
+    if ( iIncomingQueue->QueueSize() > iQueueSizeHighThresold )
+        {
+        if ( !( iListener->IsActive() || iIdleOverCommAdapter ) )
+            {
+            HTI_LOG_TEXT( "Set listener priority low" );
+            iListener->Deque();
+            CActiveScheduler::Add( iListener );
+            iIdleOverCommAdapter = ETrue;
+            }
+        }
+    }
+
+void CHtiDispatcher::DispatchIncomingMessage( CHtiMessage* aMessage )
+    {
+    HTI_LOG_FUNC_IN( "DispatchIncomingMessage" );
+
+    iIncomingQueue->Add( *aMessage );
+
+    //start CIdle if needed
+    Start();
+    CheckPriorities();
+
+    HTI_LOG_FUNC_OUT( "DispatchIncomingMessage" );
+    }
+
+TInt CHtiDispatcher::DispatchOutgoingMessage( TDesC8* aMessage,
+                    const TUid aTargetServiceUid,
+                    TBool aWrappedFlag,
+                    THtiMessagePriority aPriority )
+    {
+    HTI_LOG_FUNC_IN( "DispatchOutgoingMessage" );
+    HTI_LOG_TEXT( "Construct HTI message" );
+
+    //send only if enough memory
+    TInt returnErr = KErrNone;
+    if ( aMessage->Size() <= GetFreeMemory() )
+        {
+        //call here wrapping
+        CHtiMessage* msg = NULL;
+        if ( aWrappedFlag )
+            {
+            TDesC8* wrapped = NULL;
+            TRAP( returnErr, wrapped = iSecurityManager->WrapL( *aMessage ) );
+            if ( returnErr == KErrNone )
+                {
+                TRAP( returnErr,
+                      msg = CHtiMessage::NewL( wrapped, aTargetServiceUid,
+                            aWrappedFlag, aPriority ) );
+                if ( returnErr != KErrNone )
+                    {
+                    UrgentReboot( returnErr, KErrDescrDispatchOut );
+                    }
+                //wrapped message is kept, original is deleted
+                delete aMessage;
+                }
+            else
+                {
+                UrgentReboot( returnErr, KErrDescrWrap );
+                }
+            }
+        else
+            {
+            TRAP( returnErr, msg = CHtiMessage::NewL( aMessage,
+                                aTargetServiceUid, aWrappedFlag, aPriority ) );
+
+            if ( returnErr != KErrNone )
+                {
+                UrgentReboot( returnErr, KErrDescrDispatchOut );
+                }
+            }
+
+        // put in a queue
+        if ( msg )
+            iOutgoingQueue->Add( *msg );
+
+        //start CIdle if needed
+        Start();
+        }
+    else
+        {
+        returnErr = KErrNoMemory;
+        }
+
+    HTI_LOG_FUNC_OUT( "DispatchOutgoingMessage" );
+    return returnErr;
+    }
+
+TInt CHtiDispatcher::DispatchOutgoingErrorMessage( TInt aErrorCode,
+                    const TDesC8& aErrorDescription,
+                    const TUid aTargetServiceUid )
+    {
+    HTI_LOG_FUNC_IN( "DispatchError" );
+
+    if ( aTargetServiceUid == TUid::Null() )
+        {
+        return KErrArgument;
+        }
+
+    HTI_LOG_FORMAT( "ErrorCode %d", aErrorCode );
+    TInt err = KErrNone;
+    TDesC8* msg = NULL;
+    TRAP( err, msg = THtiSystemProtocolHelper::ErrorMessageL(
+                        EHtiErrServiceError,
+                        aTargetServiceUid,
+                        aErrorCode,
+                        aErrorDescription ) );
+
+    if ( err != KErrNone )
+        {
+        UrgentReboot( err, KErrDescrDispatchOutError );
+        }
+
+    err = DispatchOutgoingMessage( msg, KHtiSystemServiceUid,
+                             EFalse, EHtiPriorityDefault );
+
+    if ( err == KErrNoMemory )
+        {
+        delete msg;
+        }
+
+    HTI_LOG_FUNC_OUT( "DispatchError" );
+    return err;
+    }
+
+TInt CHtiDispatcher::DispatchOutgoingErrorMessage( THtiError aHtiErroreCode,
+                                    TInt aLeaveCode,
+                                    const TUid aTargetServiceUid )
+    {
+    HTI_LOG_FORMAT( "leaveCode %d", aLeaveCode );
+    TInt err = KErrNone;
+    TDesC8* msg = NULL;
+
+    TRAP( err, msg = THtiSystemProtocolHelper::ErrorMessageL(
+                        aHtiErroreCode,
+                        aTargetServiceUid,
+                        aLeaveCode,
+                        KNullDesC8 ) );
+
+    if ( err != KErrNone )
+        {
+        UrgentReboot( err, KErrDescrDispatchOutError );
+        }
+
+    err = DispatchOutgoingMessage( msg, KHtiSystemServiceUid,
+                             EFalse, EHtiPriorityDefault );
+
+    if ( err == KErrNoMemory )
+        {
+        delete msg;
+        }
+
+    return err;
+    }
+
+TInt CHtiDispatcher::DispatchOutgoingErrorMessage( THtiError aHtiErrorCode,
+                                    const TUid aTargetServiceUid )
+    {
+    HTI_LOG_FORMAT( "HtiErrorCode %d", aHtiErrorCode );
+    TInt err = KErrNone;
+    TDesC8* msg = NULL;
+
+    TRAP( err, msg = THtiSystemProtocolHelper::ErrorMessageL( aHtiErrorCode,
+                                                aTargetServiceUid ) );
+
+    if ( err != KErrNone )
+        {
+        UrgentReboot( err, KErrDescrDispatchOutError );
+        }
+
+    err = DispatchOutgoingMessage( msg, KHtiSystemServiceUid,
+                             EFalse, EHtiPriorityDefault );
+
+    if ( err == KErrNoMemory )
+        {
+        delete msg;
+        }
+
+    return err;
+    }
+
+TInt CHtiDispatcher::DispatchOutgoingMessage(TDesC8* aMessage,
+                    const TUid aTargetServiceUid)
+    {
+    return DispatchOutgoingMessage( aMessage, aTargetServiceUid,
+                             EFalse, EHtiPriorityDefault );
+    }
+
+void CHtiDispatcher::AddMemoryObserver( MHtiMemoryObserver* anObserver )
+    {
+    if ( iMemoryObservers->FindInAddressOrder( anObserver ) == KErrNotFound )
+        {
+        iMemoryObservers->InsertInAddressOrder( anObserver );
+        }
+    }
+
+void CHtiDispatcher::RemoveMemoryObserver( MHtiMemoryObserver* anObserver )
+    {
+    TInt removeIndex = iMemoryObservers->FindInAddressOrder( anObserver );
+    if ( removeIndex != KErrNotFound )
+        {
+        iMemoryObservers->Remove( removeIndex );
+        }
+    }
+
+void CHtiDispatcher::DoMemoryNotification()
+    {
+    if ( iMemoryObservers->Count() > 0 )
+        {
+        TInt memory = GetFreeMemory();
+        for ( TInt i = 0; i < iMemoryObservers->Count(); ++i )
+            {
+            ( *iMemoryObservers )[i]->NotifyMemoryChange( memory );
+            }
+        }
+    }
+
+TInt CHtiDispatcher::GetFreeMemory()
+    {
+    return iMaxQueueMemorySize
+           - iIncomingQueue->QueueSize()
+           - iOutgoingQueue->QueueSize();
+    }
+
+void CHtiDispatcher::Start()
+    {
+    if ( !( iIdle->IsActive() || iIdleActive ) )
+        {
+        HTI_LOG_TEXT( "Start CIdle" );
+        iIdleActive = ETrue;
+        iIdle->Start( TCallBack( DispatchCallback, this ) );
+        }
+    }
+
+void CHtiDispatcher::Notify( TInt anError )
+    {
+    HTI_LOG_FORMAT( "CHtiDispatcher::Notify: %d", anError );
+    anError = anError;
+    //start CIdle to check for messages
+    Start();
+    }
+
+TInt CHtiDispatcher::DoDispatch()
+    {
+    HTI_LOG_FUNC_IN( "DoDispatch" );
+
+    TBool isFailed = ETrue;
+
+    //dispatch
+    CHtiMessage* msg = NULL;
+
+    //Process message from the queues
+    if ( !iSender->IsActive() )
+        {
+        msg = iOutgoingQueue->Remove();
+        if ( msg )
+            {
+            //process outgoing
+            iSender->SendMessage( msg );
+            isFailed = EFalse;
+            }
+
+        //after some messages removed do memory notification
+        DoMemoryNotification();
+        }
+
+    iIncomingQueue->StartServiceIteration();
+    TBool msgProcessed = EFalse;
+    while ( ( msg = iIncomingQueue->GetNext() ) != NULL && !msgProcessed )
+        {
+        //processing of incoming HTI message
+        HTI_LOG_TEXT( "incoming msg" );
+
+        //1. find service
+        HTI_LOG_TEXT( "service uid" );
+        TUid cmd = msg->DestinationServiceUid();
+        THtiMessagePriority msgPriority = ( msg->Priority() && KPriorityMask ) ?
+                                            EHtiPriorityControl:
+                                            EHtiPriorityData;
+        HTI_LOG_FORMAT( "UID: %d", cmd.iUid );
+
+        //check if it's a system message
+        if ( cmd == KHtiSystemServiceUid )
+            {
+            TPtrC8 body = msg->Body();
+            TRAPD( err, HandleSystemMessageL( body ) );
+            if ( err != KErrNone )
+                {
+                //do nothing
+                HTI_LOG_FORMAT( "Failed handle HTI service, err %d", err );
+                }
+            msgProcessed = ETrue;
+            }
+        else
+            {
+            if ( iSecurityManager->IsContextEstablashed() )
+                {
+                CHTIServicePluginInterface* service = GetService( cmd );
+                if ( service )
+                    {
+                    //2. call service
+                    if ( !service->IsBusy() )
+                        {
+                        TInt err;
+                        if ( msg->IsWrapped() )
+                            {
+                            TDesC8* unwrapped = NULL;
+                            TRAP( err,
+                                  unwrapped = iSecurityManager->UnwrapL(
+                                                msg->Body() ) );
+                            if ( err == KErrNone && unwrapped )
+                                {
+                                TRAP( err, service->ProcessMessageL(
+                                                *unwrapped,
+                                                msgPriority ) );
+
+                                delete unwrapped;
+                                }
+                            else
+                                {
+                                HTI_LOG_FORMAT( "ERROR: Unwrap %d", err );
+                                DispatchOutgoingErrorMessage( EHtiErrUnwrap,
+                                    err, cmd );
+                                err = KErrNone;
+                                }
+                            }
+                        else
+                            {
+                            TPtrC8 body = msg->Body();
+                            TRAP( err, service->ProcessMessageL( body,
+                                                                msgPriority ) );
+                            }
+
+                        if ( err != KErrNone )
+                            {
+                            HTI_LOG_FORMAT( "ERROR: Service Error %d", err );
+                            DispatchOutgoingErrorMessage( EHtiErrServiceError,
+                                                err, cmd );
+                            }
+
+                        msgProcessed = ETrue;
+                        }
+                    else
+                        {
+                        HTI_LOG_TEXT( "service is busy" );
+                        }
+                    }
+                else
+                    {
+                    //send error message ServiceNotFound
+                    HTI_LOG_TEXT( "ERROR: service not found" );
+                    DispatchOutgoingErrorMessage( EHtiErrServiceNotFound, cmd );
+                    msgProcessed = ETrue;
+                    }
+                }
+            else
+                {
+                //not authorized acces
+                HTI_LOG_TEXT( "ERROR: not authorized acces" );
+                DispatchOutgoingErrorMessage( EHtiErrNotAuthorized, cmd );
+                msgProcessed = ETrue;
+                }
+            }
+        if ( msgProcessed )
+            {
+            //remove msg from dispatcher
+            if ( iIncomingQueue->Remove( msg ) )
+                {
+                delete msg;
+                }
+
+            isFailed = EFalse;
+            }
+        }
+
+    HTI_LOG_FORMAT( "IQ:%d", iIncomingQueue->QueueSize() );
+    HTI_LOG_FORMAT( "OQ:%d", iOutgoingQueue->QueueSize() );
+
+    HTI_LOG_FREE_MEM();
+    HTI_LOG_ALLOC_HEAP_MEM();
+
+    //if queues are empty & listener stopped - stop all
+    if ( iIncomingQueue->IsEmpty() && iOutgoingQueue->IsEmpty() &&
+        !iListener->IsActive() )
+        {
+        CActiveScheduler::Stop();
+        }
+
+    if ( iIncomingQueue->QueueSize() < iQueueSizeLowThresold && iIdleOverCommAdapter )
+        {
+        HTI_LOG_TEXT( "set listener priority high" );
+        iIdle->Deque();
+        CActiveScheduler::Add( iIdle );
+        iIdleOverCommAdapter = EFalse;
+        }
+
+    if ( isFailed )
+        {
+        HTI_LOG_TEXT( "dispatch failed, stop CIdle" );
+        //stop iIdle if there are long outgoing requests
+        iIdleActive = EFalse;
+        }
+    else
+        {
+        iIdleActive = !iIncomingQueue->IsEmpty() || !iOutgoingQueue->IsEmpty();
+        }
+
+    HTI_LOG_FUNC_OUT( "DoDispatch" );
+    return iIdleActive;
+    }
+
+CHTIServicePluginInterface* CHtiDispatcher::GetService(
+    const TUid aServiceUid )
+    {
+    CHTIServicePluginInterface* result = NULL;
+    for ( TInt i = 0; i < iLoadedServices->Count(); ++i )
+        {
+        if ( aServiceUid == (*iLoadedServices)[i].iServiceUid )
+            return (*iLoadedServices)[i].iService;
+        }
+
+    HTI_LOG_FORMAT( "Load service: %d", aServiceUid.iUid );
+
+    TRAPD( err, result = CHTIServicePluginInterface::NewL(
+        MapServicePluginUid( aServiceUid ) ) );
+    if ( err == KErrNone )
+        {
+        //set dispatcher
+        result->SetDispatcher( this );
+        //call InitL()
+        TRAP( err, result->InitL() );
+        if ( err != KErrNone )
+            {
+            HTI_LOG_TEXT( "Failed at InitL()" );
+            delete result;
+            result = NULL;
+            }
+        else
+            {
+            //add service to the array
+            TServiceItem serviceItem;
+            serviceItem.iServiceUid = aServiceUid;
+            serviceItem.iService = result;
+
+            if ( iLoadedServices->Append( serviceItem ) != KErrNone )
+                {
+                HTI_LOG_TEXT( "Failed to load service" );
+                delete result;
+                result = NULL;
+                }
+            }
+        }
+    else
+        {
+        result = NULL;
+        HTI_LOG_FORMAT( "Failed to load service %d", err );
+        }
+
+    return result;
+    }
+
+void CHtiDispatcher::UnloadAllServices()
+    {
+    if ( iLoadedServices )
+        {
+        for ( TInt i=0; i < iLoadedServices->Count(); ++i )
+            {
+            delete (*iLoadedServices)[i].iService;
+            }
+        iLoadedServices->Reset();
+        }
+    if ( iMemoryObservers )
+        {
+        iMemoryObservers->Reset();
+        }
+    }
+
+TInt CHtiDispatcher::DispatchCallback( TAny* aObj )
+    {
+    return ( reinterpret_cast<CHtiDispatcher*>( aObj ) )->DoDispatch();
+    }
+
+void CHtiDispatcher::Reset()
+    {
+    UnloadAllServices();
+    iIncomingQueue->RemoveAll();
+    iOutgoingQueue->RemoveAll();
+    iSecurityManager->ResetSecurityContext();
+
+    iListener->Reset();
+    iSender->Reset();
+
+    iListener->ReceiveMessage();
+    }
+
+void CHtiDispatcher::HandleSystemMessageL( const TDesC8& aMessage )
+    {
+    HTI_LOG_FUNC_IN( "HandleSystemMessage" );
+
+    if ( aMessage.Length() > 0 )
+        {
+        HTI_LOG_FORMAT( "cmd %d", aMessage[0] );
+        if ( aMessage[0] == EHtiAuthentication )
+            {
+            //pass token to security manager
+            TPtrC8 token = aMessage.Mid( 1 );//token start at the second byte
+
+            TDesC8* replyToken = iSecurityManager->SetSecurityContext( token );
+            CleanupStack::PushL( replyToken );
+            //prepare reply message
+            TDesC8* reply = THtiSystemProtocolHelper::AuthMessageL(
+                                *replyToken );
+
+            CleanupStack::PushL( reply );
+
+            User::LeaveIfError( DispatchOutgoingMessage(
+                                    reply,
+                                    KHtiSystemServiceUid ) );
+
+            CleanupStack::Pop(); //reply
+            CleanupStack::PopAndDestroy(); //replyToken
+            }
+        else if ( iSecurityManager->IsContextEstablashed() )
+            {
+            switch ( aMessage[0] )
+                {
+                case EHtiServiceList:
+                    {
+                    TDesC8* list = ServicePluginsListL();
+                    CleanupStack::PushL( list );
+                    User::LeaveIfError( DispatchOutgoingMessage( list,
+                                        KHtiSystemServiceUid ) );
+                    CleanupStack::Pop();
+                    }
+                    break;
+
+                case EHtiVersion:
+                    {
+                    HBufC8* msg =  HBufC8::NewLC( 2 );
+                    msg->Des().Append( KHtiVersionMajor );
+                    msg->Des().Append( KHtiVersionMinor );
+                    User::LeaveIfError(
+                        DispatchOutgoingMessage( msg, KHtiSystemServiceUid ) );
+                    CleanupStack::Pop(); // msg
+                    }
+                    break;
+
+                case EHtiInstanceId:
+                    {
+                    if ( iHtiInstanceId == 0 )
+                        {
+                        CreateInstanceId();
+                        }
+                    HBufC8* msg = HBufC8::NewLC( sizeof( TUint32 ) );
+                    msg->Des().Append( ( TUint8* ) ( &iHtiInstanceId ), sizeof( TUint32 ) );
+                    User::LeaveIfError(
+                        DispatchOutgoingMessage( msg, KHtiSystemServiceUid ) );
+                    CleanupStack::Pop(); // msg
+                    if ( iConsole )
+                        {
+                        iConsole->Printf( _L( "Instance ID = %u\n" ), iHtiInstanceId );
+                        }
+                    }
+                    break;
+
+                case EHtiReboot:
+                    {
+                    if(aMessage.Length() == 2)
+                        {
+                        iRebootReason = aMessage[1];
+                        }
+                    else if(aMessage.Length() == 1)
+                        {
+                        iRebootReason = -1;
+                        }
+                    else
+                        {
+                        User::LeaveIfError(DispatchOutgoingErrorMessage( KErrArgument,
+                                      KErrDescrInvalidParameter,
+                                      KHtiSystemServiceUid ) );
+                        break;
+                        }
+                    ShutdownAndRebootDeviceL();
+                    }
+                    break;
+
+                case EHtiStop:
+                    {
+                    HTI_LOG_TEXT( "STOP" );
+                    //stop all requests
+                    //cancel just incoming request
+                    //after all outgoing messages sent system will go down
+                    iListener->Cancel();
+
+                    // kill the watchdog, so HTI stays stopped
+                    KillHtiWatchDogL();
+                    }
+                    break;
+
+                case EHtiRestartServices:
+                    {
+                    HTI_LOG_TEXT("RESTARTSERVISE");
+                    if(aMessage.Length() != 1 && aMessage.Length() != 5)
+                        {
+                        User::LeaveIfError(DispatchOutgoingErrorMessage( KErrArgument,
+                                                    KErrDescrInvalidParameter,
+                                                    KHtiSystemServiceUid ) );
+                        break;
+                        }
+                    
+                    //stop all requests
+                    //cancel just incoming request
+                    //after all outgoing messages sent system will go down
+                    iListener->Cancel();
+
+                    // kill the watchdog, so HTI stays stopped
+                    KillHtiWatchDogL();
+                    
+                    TUint milliseconds = 0;
+                    if(aMessage.Length() == 5)
+                        {
+                        milliseconds = aMessage[1] + ( aMessage[2] << 8 )
+                                + ( aMessage[3] << 16 )
+                                + ( aMessage[4] << 24 );
+                        }
+                    
+                    TBuf<20> buf;
+                    buf.Format(_L("%d"), milliseconds * 1000);
+                    
+                    RProcess htiProcess;
+                    User::LeaveIfError( htiProcess.Create(
+                            KHtiRestartExeName, buf ) );
+                    htiProcess.Resume();
+                    htiProcess.Close();
+                    break;
+                    }
+                case EHtiReset:
+                    {
+                    HTI_LOG_TEXT( "RESET" );
+                    Reset();
+                    }
+                    break;
+
+                case EHtiFormat:
+                    {
+                    HTI_LOG_TEXT( "RESET FACTORY SETTINGS" );
+                    if ( aMessage.Length() == 2 )
+                        {
+                        //set the flag to do rfs
+                        iRfsMode = ( TRfsType ) aMessage[1];
+                        }
+                    if ( iRfsMode != ERfsNormal && iRfsMode != ERfsDeep )
+                        {
+                        iRfsMode = ERfsUnknown;
+                        User::LeaveIfError(
+                            DispatchOutgoingErrorMessage( KErrArgument,
+                                          KErrDescrInvalidParameter,
+                                          KHtiSystemServiceUid ) );
+                        }
+                    else
+                        {
+                        RProcess thisProcess;
+                        // ERfsDeep is supported only if HTI running from ROM
+                        if ( iRfsMode == ERfsNormal ||
+                                 IsFileInRom( thisProcess.FileName() ) )
+                            {
+                            //stop
+                            iListener->Cancel();
+                            }
+                        else
+                            {
+                            iRfsMode = ERfsUnknown;
+                            User::LeaveIfError(
+                                DispatchOutgoingErrorMessage( KErrNotSupported,
+                                              KErrDescrNotInRom,
+                                              KHtiSystemServiceUid ) );
+                            }
+                        }
+                    }
+                    break;
+
+                case EHtiShowConsole:
+                    {
+                    HTI_LOG_TEXT( "SHOW CONSOLE" );
+                    if ( !iConsole )
+                        {
+                        iConsole = Console::NewL( _L( "HtiFramework" ),
+                                                  TSize( KConsFullScreen,
+                                                         KConsFullScreen ) );
+                        iConsole->Printf( _L( "HTI Framework\n" ) );
+                        iConsole->Printf( _L( "=============\n\n" ) );
+                        }
+
+                    HBufC8* msg =  HBufC8::NewLC( 1 );
+                    msg->Des().Append( 0 );
+                    User::LeaveIfError(
+                        DispatchOutgoingMessage( msg, KHtiSystemServiceUid ) );
+                    CleanupStack::Pop(); // msg
+                    }
+                    break;
+
+                case EHtiHideConsole:
+                    {
+                    HTI_LOG_TEXT( "HIDE CONSOLE" );
+                    delete iConsole;
+                    iConsole = NULL;
+
+                    HBufC8* msg =  HBufC8::NewLC( 1 );
+                    msg->Des().Append( 0 );
+                    User::LeaveIfError(
+                        DispatchOutgoingMessage( msg, KHtiSystemServiceUid ) );
+                    CleanupStack::Pop(); // msg
+                    }
+                    break;
+
+                case EHtiDebugPrint:
+                    {
+                    if ( aMessage.Length() > 1 )
+                        {
+                        RDebug::RawPrint( aMessage.Mid( 1 ) );
+                        }
+                    HBufC8* msg =  HBufC8::NewLC( 1 );
+                    msg->Des().Append( 0 );
+                    User::LeaveIfError(
+                        DispatchOutgoingMessage( msg, KHtiSystemServiceUid ) );
+                    CleanupStack::Pop(); // msg
+                    }
+                    break;
+
+                default:
+                    {
+                    //unknown command
+                    HTI_LOG_TEXT( "Error: Unknown HTI system command:" );
+                    DispatchOutgoingErrorMessage( KErrArgument,
+                        KHtiSystemCmdErrDescr,
+                        KHtiSystemServiceUid );
+                    }
+                }
+            }
+        else
+            {
+            HTI_LOG_TEXT( "ERROR: not authorized acces" );
+            DispatchOutgoingErrorMessage( EHtiErrNotAuthorized );
+            }
+        }
+    else
+        {
+        HTI_LOG_TEXT( "Error: empty command" );
+        DispatchOutgoingErrorMessage( KErrArgument,
+            KHtiSystemCmdErrDescr,
+            KHtiSystemServiceUid );
+        }
+    HTI_LOG_FUNC_OUT( "HandleSystemMessage" );
+    }
+
+void CHtiDispatcher::UrgentReboot( TInt aReason, const TDesC8& aReasonDescr )
+    {
+    HTI_LOG_FORMAT( "UrgentReboot: %d", aReason );
+    HTI_LOG_DES( aReasonDescr );
+    aReason = aReason;
+    aReasonDescr.Size();
+    //empty queues
+    delete iIncomingQueue;
+    iIncomingQueue = NULL;
+    delete iOutgoingQueue;
+    iOutgoingQueue = NULL;
+    //stop
+    iListener->Cancel();
+    //reboot
+    Reboot();
+    }
+
+void CHtiDispatcher::Reboot()
+    {
+    if ( iConsole )
+        {
+        iConsole->Printf( _L( "Reboot requested.\n" ) );
+        }
+    TInt err = KErrNone;
+    RProcess rebootProcess;
+    // First try the UI layer rebooter
+    if(iRebootReason == -1)
+        {
+        err = rebootProcess.Create( KHtiDeviceRebootExeUI, KNullDesC );
+        }
+    else
+        {
+        TBuf<8> reasonNumber;
+        reasonNumber.Num(iRebootReason);
+        err = rebootProcess.Create( KHtiDeviceRebootExeUI, reasonNumber );
+        }
+    if ( err != KErrNone )
+        {
+        HTI_LOG_FORMAT( "UI layer rebooter failed with %d", err );
+        // Try if there is OS layer rebooter present
+        err = rebootProcess.Create( KHtiDeviceRebootExeOS, KNullDesC );
+        }
+    if ( err == KErrNone )
+        {
+        rebootProcess.Resume();
+        rebootProcess.Close();
+        }
+    else
+        {
+        HTI_LOG_FORMAT( "Reboot err %d", err );
+        if ( iConsole )
+            {
+            iConsole->Printf( _L( "Reboot error %d.\n" ), err );
+            User::After( 3000000 ); // to let the console display a while
+            }
+        // Can't send any error message here - communications have been stopped
+        }
+    }
+
+void CHtiDispatcher::RestoreFactorySettings()
+    {
+    HTI_LOG_FUNC_IN( "CHtiDispatcher::RestoreFactorySettings" );
+    if ( iConsole )
+        {
+        iConsole->Printf( _L( "RFS requested, type %d.\n" ), iRfsMode );
+        }
+    TInt err = KErrNone;
+    RProcess rebootProcess;
+    if ( iRfsMode == ERfsNormal )
+        {
+        err = rebootProcess.Create( KHtiDeviceRebootExeUI, KParamNormalRfs );
+        }
+    else if ( iRfsMode == ERfsDeep )
+        {
+        err = rebootProcess.Create( KHtiDeviceRebootExeUI, KParamDeepRfs );
+        }
+
+
+    if ( err == KErrNone )
+        {
+        rebootProcess.Resume();
+        rebootProcess.Close();
+        }
+    else
+        {
+        HTI_LOG_FORMAT( "RFS err %d", err );
+        if ( iConsole )
+            {
+            iConsole->Printf( _L( "RFS error %d.\n" ), err );
+            User::After( 3000000 ); // to let the console display a while
+            }
+        // Can't send any error message here - communications have been stopped
+        }
+    HTI_LOG_FUNC_OUT( "CHtiDispatcher::RestoreFactorySettings" );
+    }
+
+TBool CHtiDispatcher::IsFileInRom( const TDesC& aFileName )
+    {
+    HTI_LOG_FUNC_IN( "CHtiDispatcher::IsFileInRom" );
+    HTI_LOG_DES( aFileName );
+    TBool isInRom = EFalse;
+    _LIT( KDriveZ, "z:" );
+    if ( aFileName.FindF( KDriveZ ) == 0 )
+        {
+        isInRom = ETrue;
+        }
+
+    HTI_LOG_FORMAT( "IsFileInRom returning %d", isInRom );
+    HTI_LOG_FUNC_OUT( "CHtiDispatcher::IsFileInRom" );
+    return isInRom;
+    }
+
+void CleanupRArray( TAny* object )
+    {
+    ( ( RImplInfoPtrArray* ) object )->ResetAndDestroy();
+    }
+
+TDesC8* CHtiDispatcher::ServicePluginsListL()
+    {
+    RImplInfoPtrArray aImplInfoArray;
+    CleanupStack::PushL( TCleanupItem( CleanupRArray, &aImplInfoArray ) );
+
+    REComSession::ListImplementationsL(
+        KHTIServiceInterfaceUid,
+        aImplInfoArray );
+
+    //alloc memory for the list
+    TInt maxMemory = aImplInfoArray.Count() * KHtiServiceListRecordLength;
+    HBufC8* list = HBufC8::NewLC( maxMemory );
+
+    for ( TInt i = 0; i < aImplInfoArray.Count(); ++i )
+        {
+        //add uid
+        TUid uid = MapServicePluginUid(
+            aImplInfoArray[i]->ImplementationUid() );
+
+        list->Des().Append( ( TUint8* )( &( uid.iUid ) ), 4 );
+
+        //add display name, converted to 8-bit text
+        TBuf8<KHtiServiceNameLength> serviceName8;
+        serviceName8.Copy(
+            aImplInfoArray[i]->DisplayName().Left( KHtiServiceNameLength ) );
+
+        list->Des().Append( serviceName8 );
+        list->Des().AppendFill( 0,
+                       KHtiServiceNameLength - serviceName8.Length() );
+        }
+
+    CleanupStack::Pop();//list
+    CleanupStack::PopAndDestroy();//aImplInfoArray
+
+    return list;
+    }
+
+void CHtiDispatcher::KillHtiWatchDogL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiDispatcher::KillHtiWatchDogL" );
+
+    TFullName processName;
+    TFindProcess finder( KHtiWatchDogMatchPattern );
+    TInt err = finder.Next( processName );
+    if ( err == KErrNone )
+        {
+        HTI_LOG_TEXT( "HTI watchdog process found. Trying to open and kill it..." );
+        RProcess prs;
+        User::LeaveIfError( prs.Open( finder ) );
+        prs.Kill( 1 );
+        prs.Close();
+        HTI_LOG_TEXT( "HTI watchdog killed" );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiDispatcher::KillHtiWatchDogL" );
+    }
+
+
+#ifdef __ENABLE_LOGGING__
+void CHtiDispatcher::DebugListPlugins()
+    {
+    HTI_LOG_FUNC_IN( "ListPlugins" );
+    RImplInfoPtrArray aImplInfoArray;
+    HTI_LOG_TEXT( "COMM PLUGINS" );
+    REComSession::ListImplementationsL( KHTICommInterfaceUid, aImplInfoArray );
+    HTI_LOG_FORMAT( "Num of implementations: %d", aImplInfoArray.Count() );
+    TInt i;
+    for ( i = 0; i < aImplInfoArray.Count(); ++i )
+        {
+        HTI_LOG_FORMAT( "uid: %d", aImplInfoArray[i]->ImplementationUid().iUid );
+        HTI_LOG_DES( aImplInfoArray[i]->DataType() );
+        HTI_LOG_DES( aImplInfoArray[i]->DisplayName() );
+        }
+    aImplInfoArray.ResetAndDestroy();
+
+    HTI_LOG_TEXT( "SERVICE PLUGINS" );
+    REComSession::ListImplementationsL( KHTIServiceInterfaceUid, aImplInfoArray );
+    HTI_LOG_FORMAT( "Num of implementations: %d", aImplInfoArray.Count() );
+    for ( i = 0; i < aImplInfoArray.Count(); ++i )
+        {
+        HTI_LOG_FORMAT( "uid: %d", aImplInfoArray[i]->ImplementationUid().iUid );
+        HTI_LOG_DES( aImplInfoArray[i]->DataType() );
+        HTI_LOG_DES( aImplInfoArray[i]->DisplayName() );
+
+        }
+    aImplInfoArray.ResetAndDestroy();
+    HTI_LOG_FUNC_OUT( "ListPlugins" );
+    }
+#endif
+
+void CHtiDispatcher::ShutdownAndRebootDeviceL()
+    {
+    HTI_LOG_TEXT( "REBOOT" );
+    //stop
+    iListener->Cancel();
+    //and set flag to reboot
+    iToReboot = ETrue;
+    }
+
+void CHtiDispatcher::CreateInstanceId()
+    {
+    iHtiInstanceId = User::FastCounter();
+    HTI_LOG_FORMAT( "Generated instance ID %u", iHtiInstanceId );
+    }
+
+TUid CHtiDispatcher::MapServicePluginUid( const TUid aUid )
+    {
+    TUid mappedUid = TUid::Uid( aUid.iUid );
+    switch ( aUid.iUid )
+        {
+        case 0x10210CCD:
+            mappedUid.iUid = 0x200212C4;
+            break;
+        case 0x10210CCF:
+            mappedUid.iUid = 0x200212C6;
+            break;
+        case 0x10210CD1:
+            mappedUid.iUid = 0x200212C8;
+            break;
+        case 0x10210CD3:
+            mappedUid.iUid = 0x200212CA;
+            break;
+        case 0x200212C4:
+            mappedUid.iUid = 0x10210CCD;
+            break;
+        case 0x200212C6:
+            mappedUid.iUid = 0x10210CCF;
+            break;
+        case 0x200212C8:
+            mappedUid.iUid = 0x10210CD1;
+            break;
+        case 0x200212CA:
+            mappedUid.iUid = 0x10210CD3;
+            break;
+        default:
+            break;
+        }
+    return mappedUid;
+    }
+
+TBool CHtiDispatcher::CommReconnect()
+    {
+    if(iReconnectDelay == 0)
+        {
+        return EFalse;
+        }
+    
+    //Delay
+    HTI_LOG_FORMAT( "Reconnect deley : %d seconds", iReconnectDelay);
+    User::After(iReconnectDelay * 1000 * 1000);
+    
+    //Reconnect
+    iIncomingQueue->RemoveAll();
+    iOutgoingQueue->RemoveAll();
+    
+    iListener->Reset();
+    iSender->Reset();
+    iListener->ReceiveMessage();
+
+    return ETrue;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/src/HtiFramework.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,566 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file contains the implementations of the
+*               CHtiFramework class.
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiFramework.h"
+#include "HtiLogging.h"
+#include <badesca.h>
+#include <e32std.h>
+#include <f32file.h>
+#include <HtiCfg.h>
+#include <HtiStartupWaitInterface.h>
+
+// CONSTANTS
+_LIT( KHtiFrameworkMatchPattern, "HtiFramework*" );
+_LIT( KHtiMainThreadName,        "HtiMain" );
+_LIT( KHtiWatchDogExeName,       "HtiWatchDog.exe" );
+_LIT( KHtiWatchDogMatchPattern,  "HtiWatchDog*" );
+_LIT( KHtiAdminStartParameter,   "admin" );
+_LIT( KEComServerMatchPattern,   "EComServer*" );
+_LIT( KHtiStartupWaitDllName,    "HtiStartupWait.dll" );
+
+// config file parameters
+_LIT( KCfgFilePath,         "\\");
+_LIT( KHtiCfgFileName,      "hti.cfg" );
+_LIT8( KCommPlugin,         "CommPlugin" );
+_LIT8( KMaxMsgSize,         "MaxMsgSize" );
+_LIT8( KMaxQueueSize,       "MaxQueueSize" );
+_LIT8( KMaxHeapSize,        "MaxHeapSize" );
+_LIT8( KPriority,           "Priority" );
+_LIT8( KShowConsole,        "ShowConsole" );
+_LIT8( KMaxWaitTime,        "MaxWaitTime" );
+_LIT8( KStartUpDelay,       "StartUpDelay" );
+_LIT8( KEnableHtiWatchDog,  "EnableHtiWatchDog" );
+_LIT8( KEnableHtiAutoStart, "EnableHtiAutoStart" );
+_LIT8( KShowErrorDialogs,   "ShowErrorDialogs" );
+_LIT8( KReconnectDelay,     "ReconnectDelay");
+
+const static TInt KDefaultMaxWaitTime  = 90; // seconds
+const static TInt KDefaultStartUpDelay = 5;  // seconds
+const static TInt KHtiDefaultPriority = 3;
+const static TInt KHtiWatchDogEnabledDefault = 0;
+const static TInt KHtiConsoleEnabledDefault = 0;
+const static TInt KHtiAutoStartEnabledDefault = 0;
+const static TInt KHtiShowErrorDialogsDefault = 1;
+const static TInt KHtiReconnectDelay = 0;
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::CHtiFramework
+// Constructor
+// -----------------------------------------------------------------------------
+CHtiFramework::CHtiFramework():
+    iCfg( NULL ),
+    iDispatcher( NULL ),
+    iOriginalHeap( NULL )
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::ConstructL
+// Second phase constructor
+// -----------------------------------------------------------------------------
+void CHtiFramework::ConstructL()
+    {
+    HTI_LOG_FUNC_IN("CHtiFramework::ConstructL");
+
+    if ( IsHtiRunning() )
+        {
+        HTI_LOG_TEXT( "HTI already running - not starting second instance" );
+        User::Leave( KErrAlreadyExists );
+        }
+
+    TInt priority = KHtiDefaultPriority;
+    TInt enableHtiWatchDog = KHtiWatchDogEnabledDefault;
+    TInt showConsole = KHtiConsoleEnabledDefault;
+    TInt enableHtiAutoStart = KHtiAutoStartEnabledDefault;
+    TInt showErrorDialogs = KHtiShowErrorDialogsDefault;
+    TInt reconnectDelay = KHtiReconnectDelay;
+
+    TRAPD( err, iCfg = CHtiCfg::NewL() );
+    if ( err == KErrNone )
+        {
+        HTI_LOG_TEXT( "CHtiCfg constructed" );
+        TRAP( err, iCfg->LoadCfgL( KCfgFilePath, KHtiCfgFileName ) );
+        if ( err == KErrNone )
+            {
+            HTI_LOG_TEXT( "Cfg file loaded" );
+
+            TBuf8<64> commPlugin( KNullDesC8 );
+            TRAPD( paramErr, commPlugin = iCfg->GetParameterL( KCommPlugin ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KCommPlugin );
+                }
+
+            TInt maxMsgSize = 0;
+            TRAP( paramErr, maxMsgSize = iCfg->GetParameterIntL( KMaxMsgSize ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KMaxMsgSize );
+                }
+
+            TInt maxQueueSize = 0;
+            TRAP( paramErr, maxQueueSize = iCfg->GetParameterIntL( KMaxQueueSize ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KMaxQueueSize );
+                }
+
+            TInt maxHeapSize = 0;
+            TRAP( paramErr, maxHeapSize = iCfg->GetParameterIntL( KMaxHeapSize ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KMaxHeapSize );
+                }
+            else
+                {
+                //create new heap and switch heaps
+                RHeap* newHeap = UserHeap::ChunkHeap( NULL, //local
+                                                      KMinHeapSize, //min size
+                                                      maxHeapSize //max size
+                                                     );
+                if ( newHeap )
+                    {
+                    HTI_LOG_TEXT( "SwitchHeap" );
+                    iOriginalHeap = User::SwitchHeap( newHeap );
+                    HTI_LOG_ALLOC_HEAP_MEM();
+                    }
+                else
+                    {
+                    HTI_LOG_TEXT( "Failed create new heap" );
+                    User::Leave( KErrNoMemory );
+                    }
+                }
+
+            TRAP( paramErr, priority = iCfg->GetParameterIntL( KPriority ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KPriority );
+                }
+
+            TRAP( paramErr, showConsole = iCfg->GetParameterIntL( KShowConsole ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KShowConsole );
+                }
+
+            TInt maxWaitTime = KDefaultMaxWaitTime;
+            TRAP( paramErr, maxWaitTime = iCfg->GetParameterIntL( KMaxWaitTime ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KMaxWaitTime );
+                }
+
+            TInt startUpDelay = KDefaultStartUpDelay;
+            TRAP( paramErr, startUpDelay = iCfg->GetParameterIntL( KStartUpDelay ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KStartUpDelay );
+                }
+
+            TRAP( paramErr, enableHtiWatchDog = iCfg->GetParameterIntL( KEnableHtiWatchDog ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KEnableHtiWatchDog );
+                }
+
+            TRAP( paramErr, enableHtiAutoStart = iCfg->GetParameterIntL( KEnableHtiAutoStart ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KEnableHtiAutoStart );
+                }
+
+            TRAP( paramErr, showErrorDialogs = iCfg->GetParameterIntL( KShowErrorDialogs ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KShowErrorDialogs );
+                }
+            
+            TRAP( paramErr, reconnectDelay = iCfg->GetParameterIntL( KReconnectDelay ) );
+            if ( paramErr != KErrNone )
+                {
+                HTI_LOG_TEXT( "The following parameter not defined in cfg, using default value:" );
+                HTI_LOG_DES( KReconnectDelay );
+                }
+            
+            if ( !IsStartAcceptedL( enableHtiAutoStart ) )
+                {
+                User::Leave( KErrAbort );
+                }
+
+            WaitNormalState( maxWaitTime, startUpDelay );
+            iDispatcher = CHtiDispatcher::NewL( commPlugin, maxMsgSize,
+                    maxQueueSize, reconnectDelay, showConsole != 0, showErrorDialogs != 0 );
+            }
+        }
+
+
+    // cfg file was not found or it could not be opened
+    if ( err )
+        {
+        HTI_LOG_TEXT( "Error loading cfg file, use default values" );
+
+        if ( !IsStartAcceptedL( enableHtiAutoStart ) )
+            {
+            User::Leave( KErrAbort );
+            }
+
+        WaitNormalState( KDefaultMaxWaitTime, KDefaultStartUpDelay );
+
+        //create with default values
+        iDispatcher = CHtiDispatcher::NewL(
+            KNullDesC8, 0, 0, 0, showConsole != 0, showErrorDialogs != 0 );
+        }
+
+    HTI_LOG_FORMAT( "Priority setting = %d", priority );
+    // Set HTI priority
+    switch ( priority )
+        {
+        case 1:
+            RProcess().SetPriority( EPriorityBackground ); // 250
+            break;
+        case 2:
+            RProcess().SetPriority( EPriorityForeground ); // 350
+            break;
+        // case 3: goes to default
+        case 4:
+            RThread().SetPriority( EPriorityAbsoluteHigh ); // 500
+            break;
+        default:
+            RProcess().SetPriority( EPriorityHigh );        // 450
+            break;
+        }
+
+    // start hti watchdog, if it is enabled in config file
+    if ( enableHtiWatchDog != 0 ) StartHtiWatchDogL();
+
+    HTI_LOG_FORMAT( "Process priority %d", RProcess().Priority() );
+    HTI_LOG_FORMAT( "Thread priority %d", RThread().Priority() );
+    HTI_LOG_FUNC_OUT("CHtiFramework::ConstructL");
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::~CHtiFramework
+// Destructor.
+// -----------------------------------------------------------------------------
+CHtiFramework::~CHtiFramework()
+    {
+    HTI_LOG_FUNC_IN("~CHTIServer");
+    delete iDispatcher;
+
+    HTI_LOG_ALLOC_HEAP_MEM();
+    //switch before deleting iCfg
+    //'cause iCfg was allocated in the original heap
+    if ( iOriginalHeap )
+        {
+        User::SwitchHeap( iOriginalHeap );
+        }
+
+    delete iCfg;
+    HTI_LOG_FUNC_OUT("~CHTIServer");
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+CHtiFramework* CHtiFramework::NewL()
+    {
+    CHtiFramework* obj = new ( ELeave ) CHtiFramework;
+    CleanupStack::PushL( obj );
+    obj->ConstructL();
+    CleanupStack::Pop();
+    return obj;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::StartL
+// The method that gets the show going.
+// -----------------------------------------------------------------------------
+TInt CHtiFramework::StartL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiFramework::StartL" );
+
+    CConsoleBase* console = iDispatcher->GetConsole();
+    if ( console )
+        {
+        console->Printf( _L( "HTI up and running.\n" ) );
+        }
+
+    // start scheduler
+    CActiveScheduler::Start();
+
+    HTI_LOG_FUNC_OUT( "CHtiFramework::StartL" );
+    return KErrNone;
+
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::StartHtiWatchDogL
+// Launches the HTI Watchdog process if necessary.
+// -----------------------------------------------------------------------------
+void CHtiFramework::StartHtiWatchDogL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiFramework::StartHtiWatchDogL" );
+
+    TFullName processName;
+    TFindProcess finder( KHtiWatchDogMatchPattern );
+    TInt err = finder.Next( processName );
+    if ( err == KErrNone )
+        {
+        // ok, already running
+        HTI_LOG_TEXT( "HtiWatchDog already running" );
+        }
+    else
+        {
+        // start watchdog
+        HTI_LOG_TEXT( "Starting HtiWatchDog..." );
+        RProcess watchDogProcess;
+        err = watchDogProcess.Create( KHtiWatchDogExeName, KNullDesC );
+        if ( err == KErrNone )
+            {
+            watchDogProcess.Resume();
+            watchDogProcess.Close();
+            HTI_LOG_TEXT( "HtiWatchDog up and running" );
+            }
+        else
+            {
+            HTI_LOG_FORMAT( "Could not start HtiWatchDog, err: %d", err );
+            User::Leave( err );
+            }
+        }
+    HTI_LOG_FUNC_OUT( "CHtiFramework::StartHtiWatchDogL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::WaitNormalState
+// Delays HTI startup until device reaches normal state.
+// -----------------------------------------------------------------------------
+void CHtiFramework::WaitNormalState( TInt aMaxWaitTime, TInt aStartUpDelay )
+    {
+    HTI_LOG_FUNC_IN("CHtiFramework::WaitNormalState");
+    // First make sure that EComServer is running before continuing
+    TFullName processName;
+    TFindProcess finder( KEComServerMatchPattern );
+    while ( finder.Next( processName ) != KErrNone )
+        {
+        HTI_LOG_TEXT( "HTI waiting for EComServer startup" );
+        finder.Find( KEComServerMatchPattern );
+        User::After( 1000000 ); // wait 1 second
+        }
+    HTI_LOG_TEXT( "EComServer process found - HTI startup continuing" );
+
+    if ( aMaxWaitTime > 0 )
+        {
+        TInt err = KErrNone;
+        RFs fs;
+        err = fs.Connect();
+        if ( err == KErrNone )
+            {
+            RLibrary library;
+            err = library.Load( KHtiStartupWaitDllName );
+            HTI_LOG_FORMAT( "StartupWait library load returned %d", err );
+            if ( err == KErrNone &&
+                 library.Type()[1] == KHtiStartupWaitInterfaceUid )
+                {
+                HTI_LOG_TEXT( "StartupWait DLL found" );
+                TLibraryFunction entry = library.Lookup( 1 );
+                if ( entry != NULL )
+                    {
+                    MHtiStartupWaitInterface* startupWait =
+                        ( MHtiStartupWaitInterface* ) entry();
+                    err = startupWait->WaitForStartup( aMaxWaitTime );
+                    HTI_LOG_FORMAT( "StartupWait returned %d", err );
+                    delete startupWait;
+                    startupWait = NULL;
+                    }
+                }
+            library.Close();
+            }
+        }
+
+    HTI_LOG_FORMAT( "HTI Starting after %d seconds", aStartUpDelay );
+    User::After( aStartUpDelay * 1000 * 1000 );
+
+    HTI_LOG_FUNC_OUT( "CHtiFramework::WaitNormalState" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::IsHtiRunning
+// Checks whether HTI Framework process is already running.
+// -----------------------------------------------------------------------------
+TBool CHtiFramework::IsHtiRunning()
+    {
+    HTI_LOG_FUNC_IN( "CHtiFramework::IsHtiRunning" );
+    TInt htiInstanceCount = 0;
+    TBool isRunning = EFalse;
+    TFullName processName;
+    TFindProcess finder( KHtiFrameworkMatchPattern );
+    TInt err = finder.Next( processName );
+    while ( err == KErrNone && processName.Length() > 0 )
+        {
+        HTI_LOG_FORMAT( "Found process %S", &processName );
+        RProcess process;
+        err = process.Open( finder );
+        if ( err == KErrNone )
+            {
+            if ( process.ExitType() == EExitPending )
+                {
+                HTI_LOG_TEXT( "Process is running" );
+                htiInstanceCount++;
+                }
+            process.Close();
+            }
+        err = finder.Next( processName );
+        }
+    if ( htiInstanceCount > 1 )
+        {
+        isRunning = ETrue;
+        }
+    HTI_LOG_FUNC_OUT( "CHtiFramework::IsHtiRunning" );
+    return isRunning;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiFramework::IsStartAccepted
+// Checks whether HTI Framework should start or not. If automatic startup is
+// disabled HTI should start only when started by HtiAdmin.
+// -----------------------------------------------------------------------------
+TBool CHtiFramework::IsStartAcceptedL( TBool aIsAutoStartEnabled )
+    {
+    HTI_LOG_FUNC_IN( "CHtiFramework::IsStartAccepted" );
+    TBool isStartAccepted = EFalse;
+
+    if ( aIsAutoStartEnabled )
+        {
+        // If auto start is enabled, no additional checks needed. OK to start.
+        isStartAccepted = ETrue;
+        }
+
+    else
+        {
+        // If we have "admin" parameter given from command line, start is
+        // requested by HtiAdmin or HtiWatchDog and we are OK to start -
+        // otherwise this is an auto start and we deny it.
+        TInt cmdLen = User::CommandLineLength();
+        HBufC* cmdLine = HBufC::NewL( cmdLen );
+        TPtr ptrCmdLine = cmdLine->Des();
+        User::CommandLine( ptrCmdLine );
+        TLex parser( *cmdLine );
+        parser.SkipCharacters();
+        if ( parser.MarkedToken().Compare( KHtiAdminStartParameter ) == 0  )
+            {
+            isStartAccepted = ETrue;
+            }
+        delete cmdLine;
+        cmdLine = NULL;
+        }
+
+    HTI_LOG_FORMAT( "HTI start accepted = %d", isStartAccepted );
+    HTI_LOG_FUNC_OUT( "CHtiFramework::IsStartAccepted" );
+    return isStartAccepted;
+    }
+
+
+// ============================ LOCAL FUNCTIONS ===============================
+
+LOCAL_C TInt StartL()
+    {
+    User::__DbgMarkStart( RHeap::EUser );
+
+    User::RenameThread( KHtiMainThreadName );
+
+    TInt error;
+    CHtiFramework* server = NULL;
+    TRAP( error, server = CHtiFramework::NewL() );
+
+    if ( error == KErrNone )
+        {
+        CleanupStack::PushL( server );
+        TRAP( error, server->StartL() );
+
+        if ( error )
+            {
+            HTI_LOG_FORMAT( "Leave happened in StartL(): %d", error );
+            }
+
+        CleanupStack::PopAndDestroy();
+        }
+    else
+        {
+        HTI_LOG_FORMAT( "Leave when constructing: %d", error );
+        }
+
+    User::__DbgMarkEnd( RHeap::EUser, 0 );
+    HTI_LOG_TEXT( "NO memory leaks: past __UHEAP_MARKEND" );
+    return error;
+    }
+
+
+GLDEF_C TInt E32Main()
+    {
+    __UHEAP_MARK;
+    HTI_LOG_ALLOC_HEAP_MEM();
+
+    _LIT( KHTIServer, "CHtiFramework" );
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    CActiveScheduler *scheduler = new ( ELeave ) CActiveScheduler;
+    CActiveScheduler::Install( scheduler );
+
+    TRAPD( error, StartL() );
+
+    delete scheduler;
+    delete cleanup;
+    __UHEAP_MARKEND;
+    HTI_LOG_ALLOC_HEAP_MEM();
+
+    __ASSERT_ALWAYS( !error, User::Panic( KHTIServer, error ) );
+    return KErrNone;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/src/HtiMessage.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,315 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CHtiMessage implementation
+*
+*/
+
+
+#include "HtiMessage.h"
+#include "HtiLogging.h"
+
+//format constants
+
+const TInt KMsgServiceNameOffset = 0;
+const TInt KMsgBodySizeLen = 4;
+const TInt KMsgBodySizeOffset = KMsgServiceNameOffset + KHtiMsgServiceUidLen;
+const TInt KMsgVersionOffset = KMsgBodySizeOffset+KMsgBodySizeLen;
+const TInt KMsgPriorityOffset = KMsgVersionOffset+1;
+const TInt KMsgWrapFlagOffset = KMsgPriorityOffset+1;
+const TInt KMsgExtSizeOffset = KMsgWrapFlagOffset+1;
+const TInt KMsgCrcOffset = KMsgExtSizeOffset+1; //two bytes field
+const TInt KMsgExtOffset = KMsgCrcOffset+2;
+
+const TInt KMsgHeaderMinSize = KMsgExtOffset;
+
+const TInt KMsgMaxBodySize = 0xFFFFFF; //max in KMsgBodySizeLen bytes
+const TInt KMsgMaxExtSize = 0xFF;
+
+const TUint16 KCrcInitValue = 0xFFFF;
+
+const TUint8 KDefaultVersion = 1;
+
+const TInt CHtiMessage::iLinkOffset = _FOFF( CHtiMessage, iLink );
+
+CHtiMessage::CHtiMessage():
+    iBody( NULL ),
+    iBodyDes( NULL ),
+    iBodySize( 0 ),
+    iServiceUid(),
+    iExtRemainderSize( 0 )
+    {
+
+    }
+
+CHtiMessage::~CHtiMessage()
+    {
+    HTI_LOG_FUNC_IN("~CHtiMessage");
+    delete iHeader;
+    delete iBodyDes;
+    delete iBody; //delete if incomplete message is destructed
+    HTI_LOG_FUNC_OUT("~CHtiMessage");
+    }
+
+CHtiMessage* CHtiMessage::NewL(const TDesC8& aMessage)
+    {
+    CHtiMessage* obj = new(ELeave) CHtiMessage();
+    CleanupStack::PushL(obj);
+    obj->ConstructL( aMessage );
+    CleanupStack::Pop();
+    return obj;
+    }
+
+CHtiMessage* CHtiMessage::NewL( TDesC8* aMessageBody,
+                               const TUid aServiceUid,
+                               TBool aWraped,
+                               TInt aPriority)
+    {
+    CHtiMessage* obj = new(ELeave) CHtiMessage();
+    CleanupStack::PushL(obj);
+    obj->ConstructL( aServiceUid, aMessageBody,
+                    KNullDesC8, aWraped, aPriority );
+    CleanupStack::Pop();
+    return obj;
+    }
+
+CHtiMessage* CHtiMessage::NewL( TDesC8* aMessageBody,
+                               const TUid aServiceUid,
+                               const TDesC8& aExtBody,
+                               TBool aWraped,
+                               TInt aPriority)
+    {
+    CHtiMessage* obj = new(ELeave) CHtiMessage();
+    CleanupStack::PushL(obj);
+    obj->ConstructL( aServiceUid, aMessageBody,
+            aExtBody, aWraped, aPriority );
+    CleanupStack::Pop();
+    return obj;
+    }
+
+void CHtiMessage::ConstructL(const TUid aServiceUid,
+        TDesC8* aMessageBody,
+        const TDesC8& aExtBody,
+        TBool aWraped,
+        TInt aPriority)
+    {
+    if ( aMessageBody->Length()>KMsgMaxBodySize ||
+         aExtBody.Length()>KMsgMaxExtSize)
+        {
+        User::Leave(KErrArgument);
+        }
+
+    iBodyDes = aMessageBody;
+    iBodySize = iBodyDes->Length();
+
+    //allocate header space
+    iHeader = new(ELeave) TUint8[MinHeaderSize() + aExtBody.Length()];
+
+    //set UID
+    *((TInt32*)(iHeader+KMsgServiceNameOffset)) = aServiceUid.iUid;
+    iServiceUid = aServiceUid;
+
+    //set msg body size in little-endian
+    *((TUint32*)(iHeader+KMsgBodySizeOffset)) = iBodySize;
+
+    //set version
+    iHeader[KMsgVersionOffset] = KDefaultVersion;
+
+    //priority
+    iHeader[KMsgPriorityOffset] = aPriority;
+
+    //wrapped flag
+    iHeader[KMsgWrapFlagOffset] = aWraped?1:0;
+
+    //ext size
+    iHeader[KMsgExtSizeOffset] = aExtBody.Length();
+
+    //set CRC16
+    TUint16 crc16 = KCrcInitValue;
+    Mem::Crc( crc16, iHeader, KMsgCrcOffset );
+    //put crc16 in little-endian format
+    *((TUint16*)(iHeader + KMsgCrcOffset)) = crc16;
+
+    if ( aExtBody.Length()>0 )
+        {
+        Mem::Copy( iHeader + KMsgExtOffset,
+                   aExtBody.Ptr(),
+                   aExtBody.Length() );
+        }
+    }
+
+void CHtiMessage::ConstructL(const TDesC8& aMessage)
+    {
+    if ( !CheckValidHtiHeader( aMessage ) )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    const TUint8* src = aMessage.Ptr();
+    iBodySize = * ( ( TUint32* ) ( src + KMsgBodySizeOffset ) );
+    TInt extSize = src[KMsgExtSizeOffset];
+    TInt headerSize = MinHeaderSize() + extSize;
+
+    //allocate header space
+    iHeader = new ( ELeave ) TUint8[headerSize];
+    iBody = HBufC8::NewL( iBodySize );
+
+    //copy header wo ext
+    Mem::Copy( iHeader, src, MinHeaderSize() );
+
+    //set iServiceUid
+    iServiceUid.iUid = *( ( TInt32* ) ( src + KMsgServiceNameOffset ) );
+
+    //copy ext
+    if ( extSize>0 )
+        {
+        if ( aMessage.Length() >= headerSize )
+            {
+            //copy whole extension section
+            Mem::Copy( iHeader + KMsgExtOffset, src + MinHeaderSize(),
+                       extSize );
+            }
+        else
+            {
+            //copy part
+            TInt copyLen = aMessage.Length() - MinHeaderSize();
+            Mem::Copy( iHeader + KMsgExtOffset, src + MinHeaderSize(),
+                       copyLen );
+            iExtRemainderSize = extSize - copyLen;
+            }
+        }
+
+    //copy body
+    if ( iExtRemainderSize==0 ) //if it's not 0, then there is nothing in
+        {                       //aMessage left
+        TInt availableData = aMessage.Length() - headerSize;
+        if ( availableData >= iBodySize )
+            {
+            iBody->Des().Copy( aMessage.Mid( headerSize, iBodySize ) );
+            //body ready
+            iBodyDes = iBody;
+            iBody = NULL;
+            }
+        else
+            {
+            iBody->Des().Copy( aMessage.Mid( headerSize, availableData ) );
+            }
+        }
+    }
+
+TBool CHtiMessage::CheckValidHtiHeader( const TDesC8& aMessage )
+    {
+    TBool parsingResult = aMessage.Length() >= MinHeaderSize();
+    if ( parsingResult )
+        {
+        //check CRC16
+        const TUint8* data = aMessage.Ptr();
+        TUint16 headerCrc16 = * ( ( TUint16* ) ( data + KMsgCrcOffset ) );
+        TUint16 calcCrc16 = KCrcInitValue;
+        Mem::Crc( calcCrc16, data,  KMsgCrcOffset );
+        parsingResult = ( headerCrc16 == calcCrc16 );
+        }
+    return parsingResult;
+    }
+
+TInt CHtiMessage::Size( const TDesC8& aMessage )
+    {
+    const TUint8* data = aMessage.Ptr();
+    return ( *( ( TUint32* ) ( data + KMsgBodySizeOffset ) ) ) + KMsgExtOffset
+             + data[KMsgExtSizeOffset];
+    }
+
+TBool CHtiMessage::IsBodyComplete() const
+    {
+    return iBody==NULL;
+    }
+
+TInt CHtiMessage::AddToBody( const TDesC8& aBodyPart )
+    {
+    if ( ( aBodyPart.Length() + iBody->Length() ) >= iBodySize )
+        {
+        //body ready
+        TInt copyLen = iBodySize - iBody->Length();
+        iBody->Des().Append( aBodyPart.Left( copyLen ) );
+
+        iBodyDes = iBody;
+        iBody = NULL;
+
+        return copyLen;
+        }
+    else
+        {
+        //continue
+        iBody->Des().Append( aBodyPart );
+        }
+    return aBodyPart.Length();
+    }
+
+TInt CHtiMessage::MinHeaderSize()
+    {
+    return KMsgHeaderMinSize;
+    }
+
+TUid CHtiMessage::DestinationServiceUid() const
+    {
+    return iServiceUid;
+    }
+
+TInt CHtiMessage::Size() const
+    {
+    return BodySize() + HeaderSize();
+    }
+
+TInt CHtiMessage::BodySize() const
+    {
+    return iBodySize;
+    }
+
+TInt CHtiMessage::Priority() const
+    {
+    return iHeader[KMsgPriorityOffset];
+    }
+
+TBool CHtiMessage::IsWrapped() const
+    {
+    return iHeader[KMsgWrapFlagOffset]!=0;
+    }
+
+TInt CHtiMessage::ExtSize() const
+    {
+    return iHeader[KMsgExtSizeOffset];
+    }
+
+TPtrC8 CHtiMessage::Extension() const
+    {
+    return TPtrC8( iHeader + KMsgExtOffset, ExtSize() );
+    }
+
+TInt CHtiMessage::HeaderSize() const
+    {
+    return KMsgExtOffset + ExtSize();
+    }
+
+TPtrC8 CHtiMessage::Header() const
+    {
+    return TPtrC8( iHeader, HeaderSize() );
+    }
+
+TPtrC8 CHtiMessage::Body() const
+    {
+    if ( iBodyDes != NULL )
+        {
+        return TPtrC8( *iBodyDes );
+        }
+    return TPtrC8( KNullDesC8 );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/src/HtiMessageQueue.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,125 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  CHtiMessageQueue implementation
+*
+*/
+
+
+#include "HtiMessageQueue.h"
+
+CHtiMessageQueue* CHtiMessageQueue::NewL()
+    {
+    return new (ELeave) CHtiMessageQueue;
+    }
+
+CHtiMessageQueue::CHtiMessageQueue():
+    iQueue( CHtiMessage::iLinkOffset ),
+    iMemoryAllocated( 0 ),
+    iQueueIter( iQueue ),
+    iIsFirst ( ETrue )
+    {
+    }
+
+CHtiMessageQueue::~CHtiMessageQueue()
+    {
+    RemoveAll();
+    }
+
+void CHtiMessageQueue::RemoveAll()
+    {
+    if ( !IsEmpty() )
+        {
+        CHtiMessage* msg;
+
+        iQueueIter.SetToFirst();
+        while ( ( msg = iQueueIter++ ) != NULL )
+            {
+            iQueue.Remove( *msg );
+            delete msg;
+            }
+        }
+        iMemoryAllocated = 0;
+    }
+
+CHtiMessage* CHtiMessageQueue::Remove()
+    {
+    CHtiMessage* msg = NULL;
+    if ( !IsEmpty() )
+        {
+        msg = iQueue.First();
+        iQueue.Remove( *msg );
+        iMemoryAllocated -= msg->Size();
+        }
+    return msg;
+    }
+
+CHtiMessage* CHtiMessageQueue::Remove( CHtiMessage* aMsg)
+    {
+    if ( aMsg && !IsEmpty() )
+        {
+        iQueue.Remove( *aMsg );
+        iMemoryAllocated -= aMsg->Size();
+        return aMsg;
+        }
+    return NULL;
+    }
+
+void CHtiMessageQueue::StartServiceIteration()
+    {
+    if ( !IsEmpty() )
+        {
+        iQueueIter.SetToFirst();
+        iIsFirst = ETrue;
+        }
+    }
+
+CHtiMessage* CHtiMessageQueue::GetNext()
+    {
+    CHtiMessage* msg = NULL;
+    if ( !IsEmpty() )
+        {
+        while ( ( msg = iQueueIter++ ) != NULL )
+            {
+            if ( iIsFirst )
+                {
+                iIsFirst = EFalse;
+                iLastServiceUid = msg->DestinationServiceUid();
+                return msg;
+                }
+            else if ( msg->DestinationServiceUid() != iLastServiceUid )
+                {
+                iLastServiceUid = msg->DestinationServiceUid();
+                return msg;
+                }
+            }
+        }
+    return msg;
+    }
+
+
+void CHtiMessageQueue::Add( CHtiMessage& aMessage )
+    {
+    iQueue.AddLast( aMessage );
+    iMemoryAllocated += aMessage.Size();
+    }
+
+TBool CHtiMessageQueue::IsEmpty() const
+    {
+    return iQueue.IsEmpty();
+    }
+
+TInt CHtiMessageQueue::QueueSize() const
+    {
+    return iMemoryAllocated;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/src/HtiNotifier.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiNotifier implementation
+*
+*/
+
+#include "HtiNotifier.h"
+
+_LIT( KHtiError, "HtiError" );
+_LIT( KHtiOkButton, "Ok" );
+
+
+/**
+*
+* Helper function to convert Symbian os error codes
+* to readable format.
+*
+*/
+LOCAL_C HBufC* SOSErr2DesL( TInt err )
+{
+    TBuf<50> s;
+    switch ( err )
+    {
+    case KErrNone:                  s.Append( _L("KErrNone") ); break;
+    case KErrNotFound:              s.Append( _L("KErrNotFound") ); break;
+    case KErrGeneral:               s.Append( _L("KErrGeneral") ); break;
+    case KErrCancel:                s.Append( _L("KErrCancel") ); break;
+    case KErrNoMemory:              s.Append( _L("KErrNoMemory") ); break;
+    case KErrNotSupported:          s.Append( _L("KErrNotSupported") ); break;
+    case KErrArgument:              s.Append( _L("KErrArgument") ); break;
+    case KErrTotalLossOfPrecision:  s.Append( _L("KErrTotalLossOfPrecision") ); break;
+    case KErrBadHandle:             s.Append( _L("KErrBadHandle") ); break;
+    case KErrOverflow:              s.Append( _L("KErrOverflow") ); break;
+    case KErrUnderflow:             s.Append( _L("KErrUnderflow") ); break;
+    case KErrAlreadyExists:         s.Append( _L("KErrAlreadyExists") ); break;
+    case KErrPathNotFound:          s.Append( _L("KErrPathNotFound") ); break;
+    case KErrDied:                  s.Append( _L("KErrDied") ); break;
+    case KErrInUse:                 s.Append( _L("KErrInUse") ); break;
+    case KErrServerTerminated:      s.Append( _L("KErrServerTerminated") ); break;
+    case KErrServerBusy:            s.Append( _L("KErrServerBusy") ); break;
+    case KErrCompletion:            s.Append( _L("KErrCompletion") ); break;
+    case KErrNotReady:              s.Append( _L("KErrNotReady") ); break;
+    case KErrUnknown:               s.Append( _L("KErrUnknown") ); break;
+    case KErrCorrupt:               s.Append( _L("KErrCorrupt") ); break;
+    case KErrAccessDenied:          s.Append( _L("KErrAccessDenied") ); break;
+    case KErrLocked:                s.Append( _L("KErrLocked") ); break;
+    case KErrWrite:                 s.Append( _L("KErrWrite") ); break;
+    case KErrDisMounted:            s.Append( _L("KErrDisMounted") ); break;
+    case KErrEof:                   s.Append( _L("KErrEof") ); break;
+    case KErrDiskFull:              s.Append( _L("KErrDiskFull") ); break;
+    case KErrBadDriver:             s.Append( _L("KErrBadDriver") ); break;
+    case KErrBadName:               s.Append( _L("KErrBadName") ); break;
+    case KErrCommsLineFail:         s.Append( _L("KErrCommsLineFail") ); break;
+    case KErrCommsFrame:            s.Append( _L("KErrCommsFrame") ); break;
+    case KErrCommsOverrun:          s.Append( _L("KErrCommsOverrun") ); break;
+    case KErrCommsParity:           s.Append( _L("KErrCommsParity") ); break;
+    case KErrTimedOut:              s.Append( _L("KErrTimedOut") ); break;
+    case KErrCouldNotConnect:       s.Append( _L("KErrCouldNotConnect") ); break;
+    case KErrCouldNotDisconnect:    s.Append( _L("KErrCouldNotDisconnect") ); break;
+    case KErrDisconnected:          s.Append( _L("KErrDisconnected") ); break;
+    case KErrBadLibraryEntryPoint:  s.Append( _L("KErrBadLibraryEntryPoint") ); break;
+    case KErrBadDescriptor:         s.Append( _L("KErrBadDescriptor") ); break;
+    case KErrAbort:                 s.Append( _L("KErrAbort") ); break;
+    case KErrTooBig:                s.Append( _L("KErrTooBig") ); break;
+    case KErrDivideByZero:          s.Append( _L("KErrDivideByZero") ); break;
+    case KErrBadPower:              s.Append( _L("KErrBadPower") ); break;
+    case KErrDirFull:               s.Append( _L("KErrDirFull") ); break;
+    case KErrHardwareNotAvailable:  s.Append( _L("KErrHardwareNotAvailable") ); break;
+    case KErrSessionClosed:         s.Append( _L("KErrSessionClosed") ); break;
+    case KErrPermissionDenied:      s.Append( _L("KErrPermissionDenied") ); break;
+    case KErrExtensionNotSupported: s.Append( _L("KErrExtensionNotSupported") ); break;
+    case KErrCommsBreak:            s.Append( _L("KErrCommsBreak") ); break;
+    default:
+            s.AppendFormat( _L("errorcode %d"), err );
+            return s.AllocL();
+    }
+    s.AppendFormat( _L("(%d)"), err );
+    return s.AllocL();
+}
+
+/**
+*
+* CHtiNotifier implementation
+*
+*/
+void CHtiNotifier::ShowErrorL( const TDesC& aText )
+{
+    RNotifier notifier;
+    User::LeaveIfError( notifier.Connect() );
+
+    TRequestStatus status;
+    TInt button;
+    notifier.Notify( KHtiError, aText,
+                     KHtiOkButton, KNullDesC, button, status );
+    User::WaitForRequest( status );
+    notifier.Close();
+}
+
+void CHtiNotifier::ShowErrorL( const TDesC& aText, TInt aErr )
+{
+    RNotifier notifier;
+    User::LeaveIfError( notifier.Connect() );
+
+    TBuf<KMaxHtiNotifierLength> errorMsg;
+    errorMsg.Append( aText );
+    errorMsg.Append( _L("\n") );
+    HBufC* errString = SOSErr2DesL( aErr );
+    errorMsg.Append( errString->Des() );
+    delete errString;
+
+    TRequestStatus status;
+    TInt button;
+    notifier.Notify( KHtiError, errorMsg,
+                     KHtiOkButton, KNullDesC, button, status );
+    User::WaitForRequest( status );
+    notifier.Close();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiFramework/src/HtiSecurityManager.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,88 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Empty implementation of the default HtiSecurityManager
+*
+*/
+
+
+#include "HtiSecurityManager.h"
+
+CHtiSecurityManager* CHtiSecurityManager::NewL()
+    {
+    CHtiSecurityManager* obj = NewLC();
+    CleanupStack::Pop();
+    return obj;
+    }
+
+CHtiSecurityManager* CHtiSecurityManager::NewLC()
+    {
+    CHtiSecurityManager* obj = new (ELeave) CHtiSecurityManager;
+    CleanupStack::PushL(obj);
+    obj->ConstructL();
+    return obj;
+    }
+
+CHtiSecurityManager::CHtiSecurityManager()
+    {
+    iSecurityContext = EFalse;
+    }
+
+void CHtiSecurityManager::ConstructL()
+    {
+    }
+
+CHtiSecurityManager::~CHtiSecurityManager()
+    {
+    }
+
+TDesC8* CHtiSecurityManager::SetSecurityContext(const TDesC8& /*aToken*/)
+    {
+    iSecurityContext = ETrue;
+    HBufC8* replyToken = HBufC8::NewL(0);
+    return replyToken; //null token
+    }
+
+void CHtiSecurityManager::ResetSecurityContext()
+    {
+    iSecurityContext = EFalse;
+    }
+
+TBool CHtiSecurityManager::IsContextEstablashed() const
+    {
+    return iSecurityContext;
+    }
+
+TDesC8* CHtiSecurityManager::WrapL(const TDesC8& aMessage, TBool /*aEncrypt*/)
+    {
+    //just copy message
+    HBufC8* wrapped = HBufC8::NewLC( aMessage.Size() );
+    (*wrapped) = aMessage;
+    CleanupStack::Pop();
+    return wrapped;
+    }
+
+TDesC8* CHtiSecurityManager::UnwrapL(const TDesC8& aMessage)
+    {
+    //just copy message
+    HBufC8* unwrapped = HBufC8::NewLC( aMessage.Size() );
+    (*unwrapped) = aMessage;
+    CleanupStack::Pop();
+    return unwrapped;
+    }
+
+TPtrC8 CHtiSecurityManager::MIC(const TDesC8& /*aMessage*/) const
+    {
+    return TPtrC8(KNullDesC8);
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiRestart/group/HtiRestart.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build description file for HtiRestart
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET		  HtiRestart.exe
+TARGETTYPE	  exe
+
+UID             0x1000008d 0x200315B3
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE		  HtiRestart.cpp
+
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiRestart/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiRestart
+*
+*/
+
+
+PRJ_PLATFORMS
+
+DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+HtiRestart.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiRestart/src/HtiRestart.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiWatchDog implementation.
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32base.h>
+
+#ifdef __ENABLE_LOGGING__
+
+#include <flogger.h>
+_LIT( KLogFolder, "hti" );
+_LIT( KLogFile,   "htirestart.txt" );
+
+#define HTI_LOG_TEXT(a1) {_LIT(temp, a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#define HTI_LOG_DES(a1) {RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, a1);}
+#define HTI_LOG_FORMAT(a1,a2) {_LIT(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, (a2));}
+
+#else   // !__ENABLE_LOGGING__
+
+#define HTI_LOG_TEXT(a1)
+#define HTI_LOG_DES(a1)
+#define HTI_LOG_FORMAT(a1,a2)
+
+#endif // __ENABLE_LOGGING__
+
+// CONSTANTS
+_LIT( KHtiFrameworkExeName,    "HtiFramework.exe" );
+_LIT( KHtiMainThreadName,      "HtiMain" );
+_LIT( KHtiRestartName,        "HtiRestart" );
+_LIT( KHtiAdminStartParameter, "admin" );
+
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ LOCAL FUNCTIONS ===============================
+
+LOCAL_C void StartHtiProcessL()
+    {
+    RProcess htiProcess;
+    User::LeaveIfError( htiProcess.Create(
+            KHtiFrameworkExeName, KHtiAdminStartParameter ) );
+    htiProcess.Resume();
+    htiProcess.Close();
+    }
+
+
+LOCAL_C TInt StartL()
+    {
+    HTI_LOG_TEXT( "HtiRestart starting..." );
+    TFullName threadName;
+    TFullName matchPattern;
+    matchPattern.Append(_L( "*" ));
+    matchPattern.Append(KHtiMainThreadName);
+    matchPattern.Append(_L( "*" ));
+
+    // Use thread finder to find the HTI main thread
+    TFindThread threadFinder;
+    threadFinder.Find(matchPattern);
+    HTI_LOG_TEXT( "Trying to find HTI main thread" );
+    TInt err = threadFinder.Next(threadName);
+
+    if (err == KErrNone)
+        {
+        HTI_LOG_TEXT( "HTI main thread found, opening it" );
+        RThread thread;
+        err = thread.Open(threadName);
+        if (err)
+            {
+            HTI_LOG_FORMAT( "Could not open HTI main thread, err: %d", err );
+            User::Panic(_L( "HTI open err" ), err);
+            }
+
+        // Logon to HTI main thread and wait for its death
+        HTI_LOG_TEXT( "HTI main thread opened, waiting for its death" );
+        TRequestStatus status;
+        thread.Logon(status);
+        User::WaitForRequest(status);
+        thread.Close();
+
+        HTI_LOG_TEXT( "HTI died");
+        }
+
+    TBuf<0x20> cmd;
+    User::CommandLine(cmd);
+
+    TLex lex(cmd);
+    TInt microseconds = 0;
+    lex.Val(microseconds);
+    HTI_LOG_FORMAT("After %d milliseconds...", microseconds);
+    User::After(microseconds);
+
+    // try to restart HTI
+    HTI_LOG_TEXT( "Trying to restart it" );
+    TRAP( err, StartHtiProcessL() );
+    if (err)
+        {
+        HTI_LOG_FORMAT( "Could not restart HTI, err: %d", err );
+        User::Panic(_L( "HTI start err" ), err);
+        }
+
+    HTI_LOG_TEXT( "HtiRestart shutting down" );
+    return KErrNone;
+    }
+
+GLDEF_C TInt E32Main()
+    {
+    __UHEAP_MARK;
+
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    CActiveScheduler *scheduler = new(ELeave) CActiveScheduler;
+    CActiveScheduler::Install( scheduler );
+
+    User::RenameThread( KHtiRestartName );
+
+    TRAPD( err, StartL() );
+
+    delete scheduler;
+    delete cleanup;
+
+   __UHEAP_MARKEND;
+
+    return err;
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiAppServicePlugin/data/1020DEC6.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 1020 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for app service ECOM plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+//  RESOURCE DEFINITIONS
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x1020DEC6;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB7;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x1020DEC7;
+                    version_no         = 1;
+                    display_name       = "Application control service";
+                    default_data       = "APP";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiAppServicePlugin/group/HtiAppServicePlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build description file for HtiAppServicePlugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET      HtiAppServicePlugin.dll
+TARGETTYPE  PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID 0x10009D8D 0x1020DEC6
+
+VENDORID    0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH  ../src
+SOURCE      proxy.cpp
+SOURCE      HtiAppServicePlugin.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/1020DEC6.rss
+TARGET          HtiAppServicePlugin.rsc
+END
+
+LIBRARY     bafl.lib
+LIBRARY     ecom.lib
+LIBRARY     efsrv.lib
+LIBRARY     euser.lib
+LIBRARY     flogger.lib
+
+SMPSAFE
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiAppServicePlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiAppServicePlugin
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiAppServicePlugin.mmp
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiAppServicePlugin/inc/HtiAppServicePlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,188 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of ECOM plug-in service interface providing
+*                process and application control service.
+*
+*/
+
+
+
+#ifndef HTIAPPSERVICEPLUGIN_H__
+#define HTIAPPSERVICEPLUGIN_H__
+
+//  INCLUDES
+#include <e32base.h>
+#include <HtiServicePluginInterface.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CDesC8ArrayFlat;
+
+// CLASS DECLARATION
+/**
+*  Implementation of ECOM plug-in service interface.
+*  Provides the service to control processes and applications.
+*
+*/
+class CHtiAppServicePlugin : public CHTIServicePluginInterface
+    {
+protected:
+    //commands
+    enum TAppCommand
+        {
+        //commands
+        //process control
+        EStartProcess       = 0x02,
+        EStartProcess_u     = 0x03,
+        EStatusProcess      = 0x04,
+        EStatusProcess_u    = 0x05,
+        EStatusProcess_id   = 0x06,
+        EStopProcess        = 0x08,
+        EStopProcess_u      = 0x09,
+        EStopProcess_id     = 0x0A,
+        EListProcesses      = 0x0C,
+        EListProcesses_u    = 0x0D,
+        EStartProcessRetVal = 0x0E,
+        EStartProcessRetVal_u = 0x07,
+        EGetProcessExitCode = 0x0B,
+
+        EProcessLastCommand = 0x0F, //!!! used to sort process control from
+                                    //!!! app control
+
+        //app control
+        EStartApp           = 0x10,
+        EStartApp_u         = 0x11,
+        EStartApp_uid       = 0x12,
+        EStartApp_uid_u     = 0x13,
+        EStartDoc           = 0x14,
+        EStartDoc_u         = 0x15,
+        EStatusApp          = 0x16,
+        EStatusApp_u        = 0x17,
+        EStatusDoc          = 0x18,
+        EStatusDoc_u        = 0x19,
+        EStatusApp_uid      = 0x1A,
+        EStopApp            = 0x1C,
+        EStopApp_u          = 0x1D,
+        EStopDoc            = 0x1E,
+        EStopDoc_u          = 0x1F,
+        EStopApp_uid        = 0x20,
+        EListApps           = 0x24,
+        EListApps_u         = 0x25,
+
+        EAppLastCommand     = 0x2F, //!!! used to sort process control from
+                                    //!!! app control
+        EInstall         = 0x30,
+        EInstall_u       = 0x31,
+        EUnInstall       = 0x32,
+        EUnInstallName_u = 0x33,
+        EUnInstallName   = 0x34,
+
+        ESisLastCommand = 0x3F, //!!! used to sort sis control from
+                                //!!! app control
+        //responses
+        EOk             = 0xF0,
+        ENotFound       = 0xF1,
+        EAlreadyRunning = 0xF2,
+        EAlreadyStopped = 0xF3,
+        ERunning        = 0xF4,
+        EKilled         = 0xF5,
+        EPanic          = 0xF6
+        };
+
+public:
+    static CHtiAppServicePlugin* NewL();
+
+    // Interface implementation
+    void ProcessMessageL(const TDesC8& aMessage,
+                         THtiMessagePriority aPriority);
+    
+    /**
+	* Called by HTI-framework to initialize this plugin
+	*/
+    void InitL();
+
+protected:
+    CHtiAppServicePlugin();
+    void ConstructL();
+
+    virtual ~CHtiAppServicePlugin();
+
+    void HandleProcessControlL(const TDesC8& aMessage);
+
+    /**
+    * Extracts string from incoming request and convert it to unicode
+    * for non-unicode request
+    * aResult should have enough maz length and it will contain
+    * Function returns either offset for a next parameter in aRequest
+    * or some symbian error code
+    */
+    TInt ParseString( const TDesC8& aRequest,
+                      TInt anOffset,
+                      TBool aUnicode,
+                      TDes& aResult);
+
+    //command handlers
+    void HandleStartProcessL( const TDesC& aProgramName,
+                              const TDesC& aCmdLine,
+                              TBool aStoreProcessHandle );
+
+    void HandleStopProcessL( RProcess& aProcess );
+    void HandleStatusProcessL( RProcess& aProcess );
+
+    void HandleListProcessesL( const TDesC& aMatch );
+
+    //construct and send short message
+    void SendMessageL(TAppCommand aResponseCode, const TDesC8& aMsg = KNullDesC8 );
+
+    /**
+    * Helper to send error message
+    * @return KErrNone or some system-wide error code
+    */
+    inline TInt SendErrorMsg( TInt anError, const TDesC8& aMsg );
+
+    /**
+    *
+    */
+    TInt OpenProcessL( RProcess& aProcess, const TDesC& aMatch );
+    TInt OpenProcessL( RProcess& aProcess, const TUint32 aProcessId );
+
+    /**
+    * Convert string to T 32bit int (e.g. TUint, TInt32)
+    */
+    template<class T> T Parse32( const TDesC8& a32int);
+    
+    
+
+protected:
+
+    // Container array for process handles for querying the process exit codes
+    RArray<RProcess> iProcessHandleArray;
+    
+private:
+	CHTIServicePluginInterface* iAppServiceUiPlugin;
+	RLibrary iLibrary;
+
+
+    };
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiAppServicePlugin/src/HtiAppServicePlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,721 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiAppServicePlugin implementation
+*
+*/
+
+
+// INCLUDE FILES
+#include <badesca.h>
+#include <f32file.h>
+
+#include "HtiAppServicePlugin.h"
+#include <HtiDispatcherInterface.h>
+#include <HtiLogging.h>
+
+// CONSTANTS
+const static TUid KAppServiceUid = { 0x1020DEC7 };
+
+//error descriptions
+_LIT8( KErrDescrNoMemory, "No memory" );
+_LIT8( KErrDescrInvalidCmd, "Invalid command" );
+_LIT8( KErrDescrInvalidArguments, "Invalid arguments" );
+_LIT8( KErrDescrFailedCreateProcess, "Failed create process" );
+_LIT8( KErrDescrFailedOpenProcess, "Failed open process" );
+_LIT8( KErrDescrInvalidProcessId, "Invalid process id" );
+_LIT8( KErrDescrNotSupported, "Command not supported" );
+_LIT( KHtiAppControlDll, "HtiAppControl.dll" );
+
+const static TUint8 KUnicodeMask = 0x01;
+const static TInt KTerminateReason = 0;
+const static TInt KTUintLength = sizeof(TUint);
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// Create instance of concrete ECOM interface implementation
+CHtiAppServicePlugin* CHtiAppServicePlugin::NewL()
+    {
+    CHtiAppServicePlugin* self = new ( ELeave ) CHtiAppServicePlugin;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// Constructor
+CHtiAppServicePlugin::CHtiAppServicePlugin()
+    {
+    }
+
+CHtiAppServicePlugin::~CHtiAppServicePlugin()
+    {
+    HTI_LOG_FUNC_IN( "~CHtiAppServicePlugin" );
+
+    for ( TInt i = 0; i < iProcessHandleArray.Count(); i++ )
+        {
+        iProcessHandleArray[i].Close();
+        }
+    iProcessHandleArray.Close();
+
+    delete iAppServiceUiPlugin;
+
+    iLibrary.Close();
+
+    HTI_LOG_FUNC_OUT( "~CHtiAppServicePlugin" );
+    }
+
+ //Second phase construction.
+void CHtiAppServicePlugin::ConstructL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiAppServicePlugin::ConstructL" );
+
+    TInt err = iLibrary.Load( KHtiAppControlDll );
+    HTI_LOG_FORMAT( "HtiAppControlDll library load returned %d", err );
+
+    if ( err == KErrNone &&
+            iLibrary.Type()[1] == KHTIServiceInterfaceUid )
+        {
+        HTI_LOG_TEXT( "HtiAppControlDll DLL found" );
+        TLibraryFunction entry = iLibrary.Lookup( 1 );
+        if ( entry != NULL )
+            {
+            iAppServiceUiPlugin = ( CHTIServicePluginInterface* ) entry();
+            }
+        }
+    else if ( err == KErrNotFound )
+        {
+        //No HtiAppControl.dll found so CHtiAppServicePlugin can handle only
+        //process control commands
+        HTI_LOG_TEXT( "HtiAppControlDll DLL not found" );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiAppServicePlugin::ConstructL" );
+    }
+
+void CHtiAppServicePlugin::InitL()
+    {
+    if ( iAppServiceUiPlugin )
+        {
+        iAppServiceUiPlugin->SetDispatcher( iDispatcher );
+        }
+    }
+
+TInt CHtiAppServicePlugin::ParseString( const TDesC8& aRequest,
+                                        TInt anOffset,
+                                        TBool aUnicode,
+                                        TDes& aResult )
+    {
+    HTI_LOG_FUNC_IN( "CHtiAppServicePlugin::ParseString" );
+    //validate parameters
+    //if offset outside the string return empty string
+    if ( anOffset >= aRequest.Size() )
+        {
+        return anOffset;
+        }
+
+    TInt len = aRequest[anOffset];
+    HTI_LOG_FORMAT( "length %d", len );
+
+    if ( len > aResult.MaxLength() )
+        {
+        return KErrBadDescriptor;
+        }
+
+    TInt nextOffset = ( aUnicode ? len * 2 : len ) + anOffset + 1;
+    HTI_LOG_FORMAT( "nextOffset %d", nextOffset );
+    HTI_LOG_FORMAT( "reqSize %d", aRequest.Size() );
+    if ( nextOffset > aRequest.Size() )
+        {
+        return KErrArgument;
+        }
+
+    if ( aUnicode )
+        {
+        const TPtrC8 aFrom( aRequest.Mid( anOffset + 1, len * 2 ) );
+        aResult.SetLength( len );
+        for ( TInt i = 0; i < len; ++i )
+            {
+            aResult[i] = ( TUint16 ) aFrom[i << 1] +
+                ( ( ( TUint16 ) aFrom[( i << 1 ) + 1] ) << 8 );
+            }
+        }
+    else
+        {
+        aResult.Copy( aRequest.Mid( anOffset + 1, len ) );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiAppServicePlugin::ParseString" );
+    return nextOffset;
+    }
+
+void CHtiAppServicePlugin::ProcessMessageL( const TDesC8& aMessage,
+                THtiMessagePriority aPriority )
+    {
+    HTI_LOG_FUNC_IN( "CHtiAppServicePlugin::ProcessMessage" );
+    if ( aMessage.Length() < 1 )
+        {
+        // no command
+        SendErrorMsg( KErrArgument, KErrDescrInvalidCmd );
+        return;
+        }
+
+    if ( aMessage.Length() < 2 &&
+         aMessage[0] != EListProcesses &&
+         aMessage[0] != EListProcesses_u )
+        {
+         // parameter is required with all command except listing processes
+        SendErrorMsg( KErrArgument, KErrDescrInvalidCmd );
+        return;
+        }
+
+    HTI_LOG_FORMAT( "cmd %d", aMessage[0] );
+    if ( aMessage[0] < EProcessLastCommand )
+        {
+        HandleProcessControlL( aMessage );
+        }
+    else if ( aMessage[0] <= EUnInstallName )
+        {
+        if ( iAppServiceUiPlugin )
+            {
+            iAppServiceUiPlugin->ProcessMessageL( aMessage, aPriority );
+            }
+        else
+            {
+            SendErrorMsg( KErrNotSupported, KErrDescrNotSupported );
+            }
+        }
+    else
+        {
+        SendErrorMsg( KErrArgument, KErrDescrInvalidCmd );
+        }
+    HTI_LOG_FUNC_OUT( "CHtiAppServicePlugin::ProcessMessage" );
+    }
+
+void CHtiAppServicePlugin::HandleProcessControlL( const TDesC8& aMessage )
+    {
+    HTI_LOG_FUNC_IN( "CHtiAppServicePlugin::HandleProcessControl" );
+    TBool unicode = aMessage[0] & KUnicodeMask;
+
+    HTI_LOG_FORMAT( "unicode %d", unicode );
+
+    TFileName programName;
+
+    switch ( aMessage[0] )
+        {
+        case EStartProcess:
+        case EStartProcess_u:
+            {
+            TFileName cmdLine;
+            TInt offset = ParseString( aMessage, 1, unicode, programName );
+            if ( offset >= 0 )
+                {
+                offset = ParseString( aMessage, offset, unicode, cmdLine );
+                if ( offset >= 0 )
+                    {
+                    HandleStartProcessL( programName, cmdLine, EFalse );
+                    }
+                }
+            if ( offset < 0 )
+                {
+                SendErrorMsg( offset, KErrDescrInvalidArguments );
+                }
+            }
+            break;
+        case EStopProcess:
+        case EStopProcess_u:
+            {
+            TInt err = ParseString( aMessage, 1, unicode, programName );
+            if ( err >= 0 )
+                {
+                RProcess process;
+                err = OpenProcessL( process, programName );
+                if ( err == KErrNone )
+                    {
+                    CleanupClosePushL( process );
+
+                    HandleStopProcessL( process );
+
+                    CleanupStack::PopAndDestroy();
+                    }
+                else if ( err == KErrNotFound )
+                    {
+                    SendMessageL( ENotFound );
+                    }
+                else
+                    {
+                    SendErrorMsg( err , KErrDescrFailedOpenProcess );
+                    }
+                }
+            else
+                {
+                SendErrorMsg( err , KErrDescrInvalidArguments );
+                }
+            }
+            break;
+        case EStopProcess_id:
+            {
+            TPtrC8 processId8 = aMessage.Mid( 1 );
+            if ( processId8.Length() == 4 )
+                {
+                RProcess process;
+                TUint32 processId = Parse32<TUint32>( processId8 );
+                TInt err = process.Open( TProcessId( processId ) );
+                if ( err == KErrNone )
+                    {
+                    CleanupClosePushL( process );
+
+                    HandleStopProcessL( process );
+
+                    CleanupStack::PopAndDestroy();
+                    }
+                else if ( err == KErrNotFound )
+                    {
+                    SendMessageL( ENotFound );
+                    }
+                else
+                    {
+                    SendErrorMsg( err , KErrDescrFailedOpenProcess );
+                    }
+                }
+            else
+                {
+                SendErrorMsg( KErrArgument , KErrDescrInvalidProcessId );
+                }
+            }
+            break;
+        case EStatusProcess:
+        case EStatusProcess_u:
+            {
+            TInt err = ParseString( aMessage, 1, unicode, programName );
+            if ( err >= 0 )
+                {
+                RProcess process;
+                err = OpenProcessL( process, programName );
+                if ( err == KErrNone )
+                    {
+                    CleanupClosePushL( process );
+
+                    HandleStatusProcessL( process );
+
+                    CleanupStack::PopAndDestroy();
+                    }
+                else if ( err == KErrNotFound )
+                    {
+                    SendMessageL( ENotFound );
+                    }
+                else
+                    {
+                    SendErrorMsg( err , KErrDescrFailedOpenProcess );
+                    }
+                }
+            else
+                {
+                SendErrorMsg( err , KErrDescrInvalidArguments );
+                }
+            }
+            break;
+        case EStatusProcess_id:
+            {
+            TPtrC8 processId8 = aMessage.Mid( 1 );
+            if ( processId8.Length() == 4 )
+                {
+                RProcess process;
+                TUint32 processId = Parse32<TUint32>( processId8 );
+                TInt err = process.Open( TProcessId( processId ) );
+                if ( err == KErrNone )
+                    {
+                    CleanupClosePushL( process );
+
+                    HandleStatusProcessL( process );
+
+                    CleanupStack::PopAndDestroy();
+                    }
+                else if ( err == KErrNotFound )
+                    {
+                    SendMessageL( ENotFound );
+                    }
+                else
+                    {
+                    SendErrorMsg( err , KErrDescrFailedOpenProcess );
+                    }
+                }
+            else
+                {
+                SendErrorMsg( KErrArgument , KErrDescrInvalidProcessId );
+                }
+            }
+            break;
+        case EListProcesses:
+        case EListProcesses_u:
+            {
+            if ( aMessage.Length() > 1 )
+                {
+                // there is a match pattern as a parameter
+                TInt err = ParseString( aMessage, 1, unicode, programName );
+                if ( err >= 0 )
+                    {
+                    HandleListProcessesL( programName );
+                    }
+                else
+                    {
+                    SendErrorMsg( err , KErrDescrInvalidArguments );
+                    }
+                }
+            else
+                {
+                // no match pattern defined
+                HandleListProcessesL( KNullDesC );
+                }
+
+            }
+            break;
+
+        case EStartProcessRetVal:
+        case EStartProcessRetVal_u:
+            {
+            TFileName cmdLine;
+            TInt offset = ParseString( aMessage, 1, unicode, programName );
+            if ( offset >= 0 )
+                {
+                offset = ParseString( aMessage, offset, unicode, cmdLine );
+                if ( offset >= 0 )
+                    {
+                    HandleStartProcessL( programName, cmdLine, ETrue );
+                    }
+                }
+            if ( offset < 0 )
+                {
+                SendErrorMsg( offset, KErrDescrInvalidArguments );
+                }
+            }
+            break;
+
+        case EGetProcessExitCode:
+            {
+            HTI_LOG_TEXT( "EGetProcessExitCode" );
+            TPtrC8 processId8 = aMessage.Mid( 1 );
+            if ( processId8.Length() == 4 )
+                {
+                TBool processFound = EFalse;
+                TUint processId = Parse32<TUint>( processId8 );
+                RProcess process;
+                TBuf8<1 + 4 + 1 + KMaxExitCategoryName> response;
+
+                HTI_LOG_FORMAT( "Starting to search process with id: %d", processId );
+
+                for ( TInt i = 0; i < iProcessHandleArray.Count(); i++ )
+                    {
+                    process = iProcessHandleArray[i];
+                    TUint id = process.Id();
+
+                    if ( id == processId )
+                        {
+                        HTI_LOG_TEXT( "Matching process found" );
+
+                        TInt exitReason = process.ExitReason();
+                        response.Append( process.ExitType() );
+                        response.Append( (TUint8*)(&exitReason), 4 );
+                        response.Append( process.ExitCategory().Length() );
+                        response.Append( process.ExitCategory() );
+
+                        SendMessageL( EOk, response );
+
+                        // Close the process handle and remove it from the array
+                        // if the process is not running anymore and the exit
+                        // code has been queried.
+                        if ( process.ExitType() != EExitPending )
+                            {
+                            HTI_LOG_TEXT( "Closing and removing the handle" );
+                            iProcessHandleArray[i].Close();
+                            iProcessHandleArray.Remove( i );
+                            }
+
+                        processFound = ETrue;
+                        break;
+                        }
+                    }
+
+                if ( !processFound )
+                    {
+                    SendErrorMsg( KErrNotFound , KErrDescrInvalidProcessId );
+                    }
+                }
+            else
+                {
+                SendErrorMsg( KErrArgument , KErrDescrInvalidProcessId );
+                }
+            }
+            break;
+
+        default:
+            {
+            SendErrorMsg( KErrArgument, KErrDescrInvalidCmd );
+            }
+        }
+    HTI_LOG_FUNC_OUT( "CHtiAppServicePlugin::HandleProcessControl" );
+    }
+
+void CHtiAppServicePlugin::HandleStartProcessL( const TDesC& aProgramName,
+                                                const TDesC& aCmdLine,
+                                                TBool aStoreProcessHandle )
+    {
+    HTI_LOG_FUNC_IN( "CHtiAppServicePlugin::HandleStartProcessL" );
+    HTI_LOG_FORMAT( "progr name %d", aProgramName.Length() );
+    HTI_LOG_DES( aProgramName );
+
+    RProcess process;
+    TInt err = process.Create( aProgramName, aCmdLine ); // command parameters
+
+    if ( err == KErrNone )
+        {
+        CleanupClosePushL( process );
+
+        //convert process id to binary des
+        TUint processId = process.Id();
+        HTI_LOG_FORMAT( "process id %d", processId );
+
+        TBuf8<KTUintLength> processIdDes;
+        processIdDes.Append(
+                ( TUint8* )( &processId ), KTUintLength );
+
+        SendMessageL( EOk, processIdDes );
+
+        process.Resume();
+
+        if ( aStoreProcessHandle )
+            {
+            HTI_LOG_TEXT( "Storing the process handle" );
+            iProcessHandleArray.Append( process );
+            CleanupStack::Pop();
+            }
+        else
+            {
+            CleanupStack::PopAndDestroy();
+            }
+        }
+    else if ( err == KErrNotFound )
+        {
+        SendMessageL( ENotFound );
+        }
+    else
+        {
+        SendErrorMsg( err ,KErrDescrFailedCreateProcess );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiAppServicePlugin::HandleStartProcessL" );
+    }
+
+void CHtiAppServicePlugin::HandleStopProcessL( RProcess& aProcess )
+    {
+    if ( aProcess.ExitType() == EExitPending )
+        {
+        aProcess.Kill( KTerminateReason );
+        SendMessageL( EOk );
+        }
+    else
+        {
+        SendMessageL( EAlreadyStopped );
+        }
+    }
+
+void CHtiAppServicePlugin::HandleStatusProcessL( RProcess& aProcess )
+    {
+    TExitType exT = aProcess.ExitType();
+
+    switch ( exT )
+        {
+        case EExitPending:
+            {
+            SendMessageL( ERunning );
+            }
+            break;
+        case EExitKill:
+        case EExitTerminate:
+            {
+            SendMessageL( EKilled );
+            }
+            break;
+        case EExitPanic:
+            {
+            SendMessageL( EPanic );
+            }
+            break;
+        };
+    }
+
+
+void CHtiAppServicePlugin::HandleListProcessesL( const TDesC& aMatch )
+    {
+    HTI_LOG_FUNC_IN( "CHtiAppServicePlugin::HandleListProcessesL" );
+
+    RProcess process;
+    TFullName processName;
+    TUint processId;
+    TBuf8<KTUintLength> processIdDes;
+    TExitType exitType;
+
+    TBuf8<128> buf;
+    CBufFlat* processListBuf = NULL;
+    TRAPD( err, processListBuf = CBufFlat::NewL( 128 ) );
+    if ( err )
+        {
+        SendErrorMsg( err ,KErrDescrNoMemory );
+        return;
+        }
+
+    CleanupStack::PushL( processListBuf );
+
+    // The default match pattern is the single character *
+    TFindProcess finder;
+
+    // if some real match pattern is defined, use it
+    if ( aMatch.Length() > 0 )
+        {
+        HTI_LOG_TEXT( "Match pattern was given:" );
+        HTI_LOG_DES( aMatch );
+        finder.Find( aMatch );
+        }
+
+    TInt pos = 0;
+    TUint numberOfEntries = 0;
+
+    while ( finder.Next( processName ) == KErrNone )
+        {
+        err = process.Open( finder );
+
+        //convert process id to binary des
+        processId = process.Id();
+        processIdDes.Append( ( TUint8* ) ( &processId ), KTUintLength );
+        buf.Append( processIdDes );
+
+        // status
+        exitType = process.ExitType();
+        switch ( exitType )
+            {
+            case EExitPending:
+                {
+                buf.Append( ERunning );
+                }
+                break;
+            case EExitKill:
+            case EExitTerminate:
+                {
+                buf.Append( EKilled );
+                }
+                break;
+            case EExitPanic:
+                {
+                buf.Append( EPanic );
+                }
+                break;
+            };
+
+        // name length
+        buf.Append( processName.Length() );
+
+        // name
+        buf.Append( processName );
+
+        process.Close();
+
+        TRAP( err, processListBuf->ExpandL( pos, buf.Length() ) );
+        if ( err )
+            {
+            SendErrorMsg( err , KErrDescrNoMemory );
+            delete processListBuf;
+            return;
+            }
+        processListBuf->Write( pos, buf, buf.Length() );
+
+        pos += buf.Length();
+        buf.Zero();
+        processIdDes.Zero();
+        numberOfEntries++;
+        }
+
+    // insert the number of entries in the beginning
+    TBuf8<2> entries;
+    entries.Append( ( TUint8* ) ( &numberOfEntries ), 2 );
+    processListBuf->ExpandL( 0, 2 );
+    processListBuf->Write( 0, entries, 2 );
+
+    SendMessageL( EOk, processListBuf->Ptr( 0 ) );
+
+    CleanupStack::PopAndDestroy( processListBuf );
+
+    HTI_LOG_FUNC_OUT( "CHtiAppServicePlugin::HandleListProcessesL" );
+    }
+
+TInt CHtiAppServicePlugin::OpenProcessL( RProcess& aProcess,
+                                         const TDesC& aMatch )
+    {
+    HTI_LOG_FUNC_IN( "CHtiAppServicePlugin::OpenProcessL" );
+    TFullName processName;
+    TInt err = KErrNone;
+    TFindProcess finder( aMatch );
+
+    err = finder.Next( processName );
+    if ( err == KErrNone )
+        {
+        err = aProcess.Open( finder );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiAppServicePlugin::OpenProcessL" );
+    return err;
+    }
+
+template<class T> T CHtiAppServicePlugin::Parse32(
+                        const TDesC8& a32int )
+    {
+    //manually construct TUint or TInt32
+    return T( a32int[0] + ( a32int[1] << 8 ) +
+                      ( a32int[2] << 16) + ( a32int[3] << 24) );
+    }
+
+void CHtiAppServicePlugin::SendMessageL( TAppCommand aResponseCode,
+                                         const TDesC8& aMsg )
+    {
+    HTI_LOG_FORMAT( "SendMessage %d", aResponseCode );
+    HTI_LOG_FORMAT( "Message len %d", aMsg.Length() );
+    HBufC8* sendMsg = HBufC8::NewL( 1 + aMsg.Length() );
+    CleanupStack::PushL( sendMsg );
+    sendMsg->Des().Append( aResponseCode );
+    sendMsg->Des().Append( aMsg );
+
+    User::LeaveIfError( iDispatcher->DispatchOutgoingMessage(
+                            sendMsg,
+                            KAppServiceUid ) );
+    CleanupStack::Pop();
+    }
+
+inline TInt CHtiAppServicePlugin::SendErrorMsg( TInt anError,
+                                                const TDesC8& aMsg )
+    {
+    return iDispatcher->DispatchOutgoingErrorMessage( anError,
+                                               aMsg,
+                                               KAppServiceUid );
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiAppServicePlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy for app service plugin dll
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+#include "HtiAppServicePlugin.h"
+
+const TImplementationProxy ImplementationTable[] =
+    {
+        IMPLEMENTATION_PROXY_ENTRY(0x1020DEC7,  CHtiAppServicePlugin::NewL)
+    };
+
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiEchoServicePlugin/data/1020DEBE.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for echo service ECOM plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x1020DEBE;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB7;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x1020DEBF;
+                    version_no         = 1;
+                    display_name       = "Echo(ping) service";
+                    default_data       = "ECHO";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiEchoServicePlugin/group/HtiEchoServicePlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build description file for HtiEchoServicePlugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET      HtiEchoServicePlugin.dll
+TARGETTYPE  PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID 0x10009D8D 0x1020DEBE
+
+VENDORID    0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH  ../src
+SOURCE      proxy.cpp
+SOURCE      HtiEchoServicePlugin.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/1020DEBE.rss
+TARGET          HtiEchoServicePlugin.rsc
+END
+
+LIBRARY     ecom.lib
+LIBRARY     euser.lib
+LIBRARY     flogger.lib
+
+SMPSAFE
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiEchoServicePlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiEchoServicePlugin
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiEchoServicePlugin.mmp
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiEchoServicePlugin/inc/HtiEchoServicePlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,68 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of ECOM plug-in service interface providing
+*                the echo service.
+*
+*/
+
+
+#ifndef CHTIECHOSERVICEPLUGIN_H__
+#define CHTIECHOSERVICEPLUGIN_H__
+
+// INCLUDES
+#include <HtiServicePluginInterface.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+/**
+*  Implementation of ECOM plug-in service interface.
+*  Provides the echo service.
+*
+*/
+class CHtiEchoServicePlugin : public CHTIServicePluginInterface
+    {
+public:
+
+    static CHtiEchoServicePlugin* NewL();
+
+    // Interface implementation
+    void ProcessMessageL(const TDesC8& aMessage,
+                        THtiMessagePriority aPriority);
+
+    void NotifyMemoryChange(TInt aAvailableMemory);
+
+protected:
+
+    CHtiEchoServicePlugin();
+    void ConstructL();
+
+    virtual ~CHtiEchoServicePlugin();
+
+protected:
+    HBufC8* iReply;
+    };
+
+#endif // CHTIECHOSERVICEPLUGIN_H__
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiEchoServicePlugin/src/HtiEchoServicePlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,127 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiEchoServicePlugin implementation
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiEchoServicePlugin.h"
+#include <HtiDispatcherInterface.h>
+#include <HtiLogging.h>
+
+// CONSTANTS
+const static TUid KEchoServiceUid = { 0x1020DEBF };
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// Create instance of concrete ECOM interface implementation
+CHtiEchoServicePlugin* CHtiEchoServicePlugin::NewL()
+    {
+    CHtiEchoServicePlugin* self = new (ELeave) CHtiEchoServicePlugin;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// Constructor
+CHtiEchoServicePlugin::CHtiEchoServicePlugin():
+    iReply( NULL )
+    {
+    }
+
+CHtiEchoServicePlugin::~CHtiEchoServicePlugin()
+    {
+    HTI_LOG_TEXT( "CHtiEchoServicePlugin destroy" );
+    delete iReply;
+    }
+
+// Second phase construction.
+void CHtiEchoServicePlugin::ConstructL()
+    {
+    HTI_LOG_TEXT( "CHtiEchoServicePlugin::ConstructL" );
+    }
+
+void CHtiEchoServicePlugin::ProcessMessageL( const TDesC8& aMessage,
+                                 THtiMessagePriority /*aPriority*/ )
+    {
+    HTI_LOG_FUNC_IN( "CHtiEchoServicePlugin::ProcessMessage" );
+    HTI_LOG_FORMAT( "Msg len: %d", aMessage.Length() );
+
+    if ( iReply )
+        {
+        HTI_LOG_TEXT( "sending previous echo, reject request" );
+        return;
+        }
+
+    //make copy of the message and send it back
+    iReply = HBufC8::NewL( aMessage.Length() );
+    iReply->Des().Copy( aMessage );
+
+    if ( iDispatcher->DispatchOutgoingMessage( iReply, KEchoServiceUid )
+            == KErrNoMemory )
+        {
+        HTI_LOG_TEXT( "KErrNoMemory" );
+        iDispatcher->AddMemoryObserver( this );
+        }
+    else
+        {
+        iReply = NULL;
+        }
+    HTI_LOG_FUNC_OUT( "CHtiEchoServicePlugin::ProcessMessage" );
+    }
+
+void CHtiEchoServicePlugin::NotifyMemoryChange( TInt aAvailableMemory )
+    {
+
+    if ( iReply )
+        {
+        if ( aAvailableMemory >= iReply->Size() )
+            {
+            TInt err = iDispatcher->DispatchOutgoingMessage( iReply,
+                            KEchoServiceUid );
+
+            if (  err == KErrNone )
+                {
+                iReply = NULL;
+                iDispatcher->RemoveMemoryObserver( this );
+                }
+            else if ( err != KErrNoMemory ) //some other error
+                {
+                delete iReply;
+                iReply = NULL;
+                iDispatcher->RemoveMemoryObserver( this );
+                }
+            }
+        }
+    else
+        {
+        //some error, should not be called
+        iDispatcher->RemoveMemoryObserver( this );
+        }
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiEchoServicePlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy for echo service plugin dll
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+#include "HtiEchoServicePlugin.h"
+
+// Provides a key value pair table, this is used to identify
+// the correct construction function for the requested interface.
+const TImplementationProxy ImplementationTable[] =
+    {
+        IMPLEMENTATION_PROXY_ENTRY(0x1020DEBF,  CHtiEchoServicePlugin::NewL)
+    };
+
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiFtpServicePlugin/data/1020DEC4.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for FTP service ECOM plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x1020DEC4;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB7;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x1020DEC5;
+                    version_no         = 1;
+                    display_name       = "FTP service";
+                    default_data       = "FTP";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiFtpServicePlugin/group/HtiFtpServicePlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build description file for HtiFtpServicePlugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiFtpServicePlugin.dll
+TARGETTYPE      PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID             0x10009D8D 0x1020DEC4
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          proxy.cpp
+SOURCE          HtiFtpServicePlugin.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/1020DEC4.rss
+TARGET          HtiFtpServicePlugin.rsc
+END
+
+LIBRARY         euser.lib
+LIBRARY         ecom.lib
+LIBRARY         efsrv.lib
+LIBRARY         hash.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiFtpServicePlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiFtpServicePlugin
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiFtpServicePlugin.mmp
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiFtpServicePlugin/inc/HtiFtpServicePlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,488 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of ECOM plug-in service interface providing
+*               the FTP service.
+*
+*/
+
+
+#ifndef HTIFTPSERVICEPLUGIN_H__
+#define HTIFTPSERVICEPLUGIN_H__
+
+// INCLUDES
+#include <e32std.h>
+#include <f32file.h>
+#include <HtiServicePluginInterface.h>
+
+// CONSTANTS
+enum TFtpCommand
+    {
+    EFtpSTOR                = 0x02,
+    EFtpSTOR_u              = 0x03,
+    EFtpRETR                = 0x04,
+    EFtpRETR_u              = 0x05,
+    EFtpLIST                = 0x06,
+    EFtpLIST_u              = 0x07,
+    EFtpMKD                 = 0x08,
+    EFtpMKD_u               = 0x09,
+    EFtpRMD                 = 0x0A,
+    EFtpRMD_u               = 0x0B,
+    EFtpDELE                = 0x0C,
+    EFtpDELE_u              = 0x0D,
+    EFtpCANCEL              = 0x0E,
+    EFtpFILESIZE            = 0x0F,
+    EFtpLISTDIR             = 0x10,
+    EFtpLISTDIR_u           = 0x11,
+    EFtpLISTSIZES           = 0x12,
+    EFtpLISTSIZES_u         = 0x13,
+    EFtpLISTDRIVES          = 0x14,
+    EFtpLISTDRIVES_u        = 0x15,
+    EFtpRENAME              = 0x16,
+    EFtpRENAME_u            = 0x17,
+    EFtpCOPY                = 0x18,
+    EFtpCOPY_u              = 0x19,
+    EFtpMOVE                = 0x1A,
+    EFtpMOVE_u              = 0x1B,
+    EFtpSETFORCE            = 0x20,
+    EFtpCHECKSUM            = 0x30,
+    EFtpCHECKSUM_u          = 0x31,
+    EFtpListDetail          = 0x32,
+    EFtpListDetail_u        = 0x33,
+    EFtpListDirDetail       = 0x34,
+    EFtpListDirDetail_u     = 0x35,
+    EFtpFORMAT              = 0x40,
+    EFtpOK                  = 0xF0,
+    };
+
+enum TAlgorithm
+    {
+    EMD5 = 0x01,
+    };
+
+_LIT(KHtiFileHlp, "HtiFileHlp.exe");
+
+//temporary file used if file is uploaded to Tcb
+_LIT(KTmpFileName, "C:\\htitemp.bin");
+
+//tokens used for command line for HtiFileHlp.exe
+_LIT( KHtiFileHlpDeleteCmd, "d" );
+_LIT( KHtiFileHlpCopyCmd,   "c" );
+_LIT( KHtiFileHlpMkdCmd,    "m" );
+_LIT( KHtiFileHlpRmdCmd,    "r" );
+_LIT( KHtiFileHlpMoveCmd,   "mv" );
+_LIT( KHtiFileHlpRenameCmd, "re" );
+_LIT( KHtiFileHlpDelim,     "|" );
+
+//tokens used to id Tcb folders
+_LIT(KHtiTcbSys, "\\sys\\");
+_LIT(KHtiTcbResource, "\\resource\\");
+
+//offset where first folder's backslash starts in absolute filename
+                                   // 012
+const static TInt KPathOffset = 2; //"C:\"
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CHtiFtpBackupFakeBase;
+
+// CLASS DECLARATION
+/**
+* Callback interface for AO
+*/
+class MFtpObserverAO
+    {
+public:
+    virtual void FtpComplete( TInt anError) = 0;
+    };
+
+
+// CLASS DECLARATION
+/**
+* AO for async request to CFileMan and RFile
+*/
+class CFtpHandlerAO : public CActive, public MFileManObserver
+    {
+public:
+    CFtpHandlerAO(MFtpObserverAO* anObserver);
+    ~CFtpHandlerAO();
+
+    /** Set AO active */
+    void Start();
+
+public: //MFileManObserver
+    virtual MFileManObserver::TControl NotifyFileManStarted();
+    virtual MFileManObserver::TControl NotifyFileManOperation();
+    virtual MFileManObserver::TControl NotifyFileManEnded();
+
+protected: //from CActive
+    void RunL();
+    /**
+    * no direct cancel for RFile and CFileMan
+    */
+    void DoCancel();
+    //TInt RunError(TInt aError);
+
+protected:
+    MFtpObserverAO* iObserver;
+    /** set to ERtue if CFileMan operation should be canceled */
+    TBool iCancelFileMan;
+    };
+
+
+class CProcessLogonAO : public CActive
+    {
+public:
+    CProcessLogonAO(MFtpObserverAO* anObserver);
+    ~CProcessLogonAO();
+
+    /** Set AO active */
+    void Start(const TDesC& aCmdLine);
+
+protected: //from CActive
+    void RunL();
+    void DoCancel();
+
+protected:
+    MFtpObserverAO* iObserver;
+    RProcess iProcess;
+    };
+
+
+// CLASS DECLARATION
+/**
+* FTP plugin implementation
+*/
+class CHtiFtpServicePlugin : public CHTIServicePluginInterface,
+                             public MFtpObserverAO
+    {
+protected:
+    /**
+    * Major states of FPT plug-in
+    */
+    enum TFtpServiceState
+        {
+        EIdle,          /** waits for a new command                 */
+        EListBusy,      /** waits for memory to send LIST response  */
+        ERmdBusy,       /** outstanding request CFileMan::RmDir()   */
+        EDeleBusy,      /** outstanding request CFileMan::Delete()  */
+        EStorWait,      /** waits for data packages                 */
+        EStorBusy,      /** outstanding request to RFile::Write()   */
+        ERetrBusy,      /** outstanding request to RFile::Read()    */
+        ERetrWait,      /** waits for memory to send data package   */
+        EStorTcbBusy,   /** outstandig request to HtiFileHlp.exe    */
+        EDeleTcbBusy,   /** outstandig request to HtiFileHlp.exe    */
+        EMkdTcbBusy,    /** outstandig request to HtiFileHlp.exe    */
+        ERmdTcbBusy,    /** outstandig request to HtiFileHlp.exe    */
+        ERenameBusy,    /** outstanding request CFileMan::Rename()  */
+        ERenameTcbBusy, /** outstandig request to HtiFileHlp.exe   */
+        ECopyBusy,      /** outstanding request CFileMan::Copy()    */
+        ECopyTcbBusy,   /** outstandig request to HtiFileHlp.exe   */
+        EMoveBusy,      /** outstanding request CFileMan::Move()    */
+        EMoveTcbBusy    /** outstandig request to HtiFileHlp.exe   */
+        };
+public:
+
+    static CHtiFtpServicePlugin* NewL();
+
+    // Interface implementation
+
+    /**
+    * Calculates iBufferSize based on iDispatcher->FreeMemory() value
+    */
+    void InitL();
+
+    /**
+    * @return ETrue when in any EXXXBusy state
+    */
+    TBool IsBusy();
+
+    /**
+    * Process either control or data message depending on aPriority
+    *
+    * @param aMessage message with commands or data
+    * @param aPriority indicates type of aMessage
+    */
+    void ProcessMessageL( const TDesC8& aMessage,
+                         THtiMessagePriority aPriority );
+
+    void NotifyMemoryChange( TInt aAvailableMemory );
+
+public: // MFtpObserverAO
+    void FtpComplete( TInt anError );
+
+protected:
+    CHtiFtpServicePlugin();
+    void ConstructL();
+
+    virtual ~CHtiFtpServicePlugin();
+
+    /**
+    * Handle FTP control messages
+    *
+    * @param aMessage message with command
+    */
+    void HandleControlMessageL( const TDesC8& aMessage );
+
+    /**
+    * Handle expected CANCEL control message
+    * received in EStorWait or ERetrWait state
+    * If aMessage does not contain CANCEL command,
+    * BUSY message is sent, otherwise current operation is canceled
+    * and plugin goes to EIdle state and sends OK message.
+    *
+    * @param aMessage message with command
+    */
+    void HandleCancelL( const TDesC8& aMessage );
+
+    /**
+    * Accepts data messages for STOR command
+    *
+    * @param aMessage message with file data
+    */
+    void HandleDataMessageL( const TDesC8& aMessage );
+
+    //command handlers
+
+    /**
+    * Handle STOR command request
+    */
+    void HandleReceiveFileL();
+
+    /**
+    * Handle RETR command request
+    */
+    void HandleSendFileL();
+
+    /**
+    * Reads one portion of file data during RETR command handeling.
+    */
+    void ReadToBuffer();
+
+    /**
+    * Sends one portion of file data during RETR command handeling.
+    */
+    void SendBuffer();
+
+    /**
+    * Handle LIST command
+    *
+    * @param aUnicodText if ETrue then response in unicode
+    * @param aReadingAtt specifies what entries to read from a dir
+    * @param aSizes if ETrue filesizes are included in the response
+    */
+    void HandleListL( TBool aUnicodText, TUint aReadingAtt, TBool aSizes );
+    
+    /**
+    * Handle LIST FILES DETAIL command
+    *
+    * @param aUnicodText if ETrue then response in unicode
+    * @param aReadingAtt specifies what entries to read from a dir
+    */
+    void HandleListDetailL( TBool aUnicodText, TUint aReadingAtt);
+
+    /**
+    * Extracts and validate file name to iFileName
+    * If error sends err msg
+    * Return ETrue when filename is valid
+    * @param aFilename descriptor with filename
+    * @param aToUnicode flag indicates that data in aFilename
+    *                   should be treated as an unicode string
+    */
+    TBool GetFileNameL( const TDesC8& aFilename, TBool aToUnicode );
+
+    /**
+    * Extracts and validates path to iFileName
+    * If error sends err msg
+    * Return ETrue when directory is valid
+    * @param aDirname descriptor with directory name
+    * @param aToUnicode flag indicates that data in aFilename
+    *                   should be treated as an unicode string
+    */
+    TBool GetDirectoryL( const TDesC8& aDirname, TBool aToUnicode );
+
+    /**
+    * Helper to send short control messages
+    * (e.g. OK, BUSY, FILESIZE)
+    * @param aCmd command code
+    * @param aMsg additional command parameters
+    * @return KErrNone or Symbian error code
+    */
+    TInt SendControlMsg( TFtpCommand aCmd, const TDesC8& aMsg );
+
+    /**
+    * Helper to send error message
+    * @return KErrNone or some system-wide error code
+    */
+    inline TInt SendErrorMsg( TInt anError, const TDesC8& aMsg );
+
+    /**
+    * Handle delete command
+    * @param aFilename the file to delete
+    */
+    void HandleDeleteL( const TDesC& aFilename );
+
+    /**
+    * Handle rename command
+    * @param aMessage message that contains
+    * old and new file/directory names.
+    * @param aToUnicode flag indicates that data in aFilename
+    *  should be treated as an unicode string
+    */
+    void HandleRenameL( const TDesC8& aMessage, TBool aUnicode );
+
+    /**
+    * Handle copy command
+    * @param aMessage message that contains the file/directory to be copied
+    * and the location and name of the copy.
+    * @param aToUnicode flag indicates that data in aFilename
+    *  should be treated as an unicode string
+    */
+    void HandleCopyL( const TDesC8& aMessage, TBool aUnicode );
+
+    /**
+    * Handle move command
+    * @param aMessage message that contains the file/directory to be moved
+    * and the new location
+    * @param aToUnicode flag indicates that data in aFilename
+    *  should be treated as an unicode string
+    */
+    void HandleMoveL( const TDesC8& aMessage, TBool aUnicode );
+
+    /**
+    * Safe unicode copying from 8bit descr to 16bit buffer
+    * @param aTo destination descriptor
+    * @param aFrom source descriptor
+    */
+    void CopyUnicode( TDes& aTo, const TDesC8& aFrom );
+
+    /**
+    * Check either aFilename point in a TCB directories (sys, private, resource)
+    * @param aFilename the file to check
+    */
+    TBool IsFileTcb( const TDesC& aFilename );
+
+    /**
+    * Uses HtiFileHlp.exe to delete file from TCB directories
+    * @param aFilename the file to delete
+    */
+    void HandleTcbDeleteL( const TDesC& aFilename );
+
+    /**
+    * Uses HtiFileHlp.exe to copy files/folders to TCB directories
+    * @param aFromFilename the source path
+    * @param aToFilename the destination path
+    */
+    void HandleTcbCopyL( const TDesC& aFromFilename, const TDesC& aToFilename );
+
+    /**
+    * Uses HtiFileHlp.exe to makedir in TCB directories
+    * @param aDirname the directory to create
+    */
+    void HandleTcbMkdL( const TDesC& aDirname );
+
+    /**
+    * Uses HtiFileHlp.exe to delete dir in TCB directories
+    * @param aDirname the directory to delete
+    */
+    void HandleTcbRmdL( const TDesC& aDirname );
+
+    /**
+    * Uses HtiFileHlp.exe to do rename in TCB folders
+    * @param aTargetName the path to rename
+    * @param aDestName the new path name
+    */
+    void HandleTcbRenameL( const TDesC& aTargetName, const TDesC& aDestName );
+
+    /**
+    * Uses HtiFileHlp.exe to do move to TCB folders
+    * @param aTargetName the path to move
+    * @param aDestName the destination path
+    */
+    void HandleTcbMoveL( const TDesC& aTargetName, const TDesC& aDestName );
+
+    /**
+    * Sets the faking of backup/restore operation on/off.
+    * If aOn is ETrue sets backup/restore on, otherwise sets it off.
+    * @return KErrNone on success, otherwise system error code
+    */
+    TInt SetBURFakeState( TBool aOn );
+
+    /**
+    * Calculates a checksum for the given file with the given algorithm.
+    */
+    void HandleCheckSumCalcL( TAlgorithm aAlgorithm,
+                              const TDesC& aFilename );
+
+    /**
+    * Formats a drive.
+    */
+    void HandleFormat( const TUint8 aDrive, const TUint8 aMode );
+
+    /**
+    * Creates a list of drives.
+    */
+    void HandleListDrivesL( TBool aUnicode );
+
+private:
+    void RemoveEndBackslash( TFileName& aFileName );
+
+protected:
+    /** plugin state */
+    TFtpServiceState iState;
+    /** File server */
+    RFs iFs;
+    /** File manager used for RMD and DELE */
+    CFileMan* iFileMan;
+    /** current file for STOR and RETR*/
+    RFile iFile;
+    /** file name of iFile */
+    TFileName iFileName;
+
+    /** current offset in file during STOR or RETR */
+    TInt iCurrentOffset; //mean received bytes or sent bytes
+    /** the final size of iFile */
+    TInt iFileSize;
+
+    /** the size of iSendBuffer, calculated in InitL() */
+    TInt iBufferSize;
+    /** send buffer for RETR and LIST commands */
+    HBufC8* iSendBuffer;
+    /** des of iSendBuffer, used for RETR */
+    TPtr8 iSendBufferDes;
+
+    /** AO to handle current asyn request */
+    CFtpHandlerAO* iHandlerAO;
+
+    /** used for HtiFileHlp.exe */
+    CProcessLogonAO* iProcessLogonAO;
+
+    /**
+    * Class for activating/deactivating a backup session.
+    * This is used for forced operations to locked files. Activating backup
+    * should release locks on files that are in use by some other application.
+    */
+    CHtiFtpBackupFakeBase* iBackupFake;
+
+    /** Handle to the DLL for activating/deactivating backup */
+    RLibrary iBackupFakeLib;
+    };
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiFtpServicePlugin/src/HtiFtpServicePlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2318 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiFtpServicePlugin implementation
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiFtpServicePlugin.h"
+#include <HtiFtpBackupFakeBase.h>
+#include <HtiDispatcherInterface.h>
+#include <HtiLogging.h>
+
+#include <e32property.h>
+#include <hash.h>
+
+// CONSTANTS
+static const TUid KFtpServiceUid = { 0x1020DEC5 };
+_LIT( KBackslash, "\\" );
+_LIT( KRootPathFormat, "%c:\\" );
+_LIT( KHtiFtpBackupFakeDllName, "HtiFtpBackupFake.dll" );
+const static TInt KMinBufferSize = 1024;
+const static TUint8 KUnicodeMask = 0x1;
+const static TInt KFileSizeMsgSize = 5;
+
+//error description
+_LIT8( KErrDescrUnknownCmd, "unknown command" );
+_LIT8( KErrDescrNoSpace, "no disk space" );
+_LIT8( KErrDescrFailedRead, "failed read file" );
+_LIT8( KErrDescrFailedWrite, "failed write file" );
+_LIT8( KErrDescrFailedGetDir, "failed to read directory" );
+_LIT8( KErrDescrEmptyDirname, "directory name empty" );
+_LIT8( KErrDescrInvalidDirnameLength, "invalid directory name length" );
+_LIT8( KErrDescrEmptyFilename, "file name empty" );
+_LIT8( KErrDescrInvalidFilenameLength, "invalid file name length" );
+_LIT8( KErrDescrFailedMkDir, "failed create directory" );
+_LIT8( KErrDescrFailedRmDir, "failed remove directory" );
+_LIT8( KErrDescrFailedDeleFile, "failed delete file" );
+_LIT8( KErrDescrFailedRenameFile, "failed rename file" );
+_LIT8( KErrDescrFailedCopyFile, "failed copy file" );
+_LIT8( KErrDescrFailedMoveFile, "failed move file" );
+_LIT8( KErrDescrInvalidStorArgument, "invalid arguments" );
+_LIT8( KErrDescrFailedCreateFile, "invalid create file" );
+_LIT8( KErrDescrFailedOpenFile, "failed open file" );
+_LIT8( KErrDescrFailedCloseFile, "failed close file" );
+_LIT8( KErrDescrInvalidDataMessage, "invalid data message" );
+_LIT8( KErrDescrNoMemory, "no memory to send file" );
+_LIT8( KErrDescrNoCancel, "nothing to cancel" );
+_LIT8( KErrDescrBusy, "Busy" );
+_LIT8( KErrDescrFailedCopyTcb, "Failed to copy to Tcb directories" );
+_LIT8( KErrDescrInvalidForceArgs, "invalid arguments for setforce" );
+_LIT8( KErrDescrInvalidChecksumArgs, "invalid arguments for checksum" );
+_LIT8( KErrDescrInvalidFormatArgs, "invalid arguments for format" );
+_LIT8( KErrDescrInvalidDriveListArgs, "invalid arguments for drive list" );
+_LIT8( KErrDescrFailedFormat, "failed to format" );
+_LIT8( KErrDescrNotSupported, "command not supported" );
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+/**
+* CFtpHandlerAO implementation
+*/
+CFtpHandlerAO::CFtpHandlerAO( MFtpObserverAO* anObserver ):
+    CActive( EPriorityStandard ),
+    iObserver( anObserver ),
+    iCancelFileMan( EFalse )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+CFtpHandlerAO::~CFtpHandlerAO()
+    {
+    }
+
+void CFtpHandlerAO::Start()
+    {
+    SetActive();
+    }
+
+MFileManObserver::TControl CFtpHandlerAO::NotifyFileManStarted()
+    {
+    return iCancelFileMan?
+                MFileManObserver::EAbort :
+                MFileManObserver::EContinue;
+    }
+
+MFileManObserver::TControl CFtpHandlerAO::NotifyFileManOperation()
+    {
+    return iCancelFileMan?
+                MFileManObserver::ECancel :
+                MFileManObserver::EContinue;
+    }
+
+MFileManObserver::TControl CFtpHandlerAO::NotifyFileManEnded()
+    {
+    return iCancelFileMan?
+                MFileManObserver::EAbort :
+                MFileManObserver::EContinue;
+    }
+
+void CFtpHandlerAO::RunL()
+    {
+    iObserver->FtpComplete( iStatus.Int() );
+    }
+
+void CFtpHandlerAO::DoCancel()
+    {
+    iCancelFileMan = ETrue;
+    }
+
+CProcessLogonAO::CProcessLogonAO( MFtpObserverAO* anObserver ):
+    CActive( EPriorityStandard ),
+    iObserver( anObserver )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+CProcessLogonAO::~CProcessLogonAO()
+    {
+    Cancel();
+    iProcess.Close();
+    }
+
+void CProcessLogonAO::Start( const TDesC& aCmdLine )
+    {
+    TInt err = iProcess.Create( KHtiFileHlp, aCmdLine );
+
+    if ( err == KErrNone )
+        {
+        iProcess.Logon( iStatus );
+        //start HtiFileHlp.exe
+        iProcess.Resume();
+        }
+    else
+        {
+        TRequestStatus* pS = &iStatus;
+        User::RequestComplete( pS, err );
+        }
+    SetActive();
+    }
+
+void CProcessLogonAO::RunL()
+    {
+    iObserver->FtpComplete( iStatus.Int() );
+    }
+
+void CProcessLogonAO::DoCancel()
+    {
+    iProcess.LogonCancel( iStatus );
+    }
+
+// Create instance of concrete ECOM interface implementation
+CHtiFtpServicePlugin* CHtiFtpServicePlugin::NewL()
+    {
+    CHtiFtpServicePlugin* self = new (ELeave) CHtiFtpServicePlugin;
+    CleanupStack::PushL (self);
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// Constructor
+CHtiFtpServicePlugin::CHtiFtpServicePlugin():
+    iState( EIdle ),
+    iSendBuffer( NULL ),
+    iSendBufferDes( NULL, 0 ),
+    iHandlerAO( NULL ),
+    iProcessLogonAO( NULL )
+    {
+    }
+
+CHtiFtpServicePlugin::~CHtiFtpServicePlugin()
+    {
+    HTI_LOG_FUNC_IN("~CHtiFtpServicePlugin");
+    delete iSendBuffer;
+    delete iHandlerAO;
+    delete iProcessLogonAO;
+    delete iFileMan;
+    delete iBackupFake;
+    iBackupFakeLib.Close();
+    iFs.Close();
+    HTI_LOG_FUNC_OUT("~CHtiFtpServicePlugin");
+    }
+
+// Second phase construction.
+void CHtiFtpServicePlugin::ConstructL()
+    {
+    HTI_LOG_FUNC_IN("CHtiFtpServicePlugin::ConstructL");
+
+    User::LeaveIfError( iFs.Connect() );
+    iFileMan = CFileMan::NewL( iFs );
+
+    HTI_LOG_FUNC_OUT("CHtiFtpServicePlugin::ConstructL");
+    }
+
+void CHtiFtpServicePlugin::InitL()
+    {
+    if ( iDispatcher->GetFreeMemory() < KMinBufferSize )
+        {
+        User::Leave( KErrNoMemory );
+        }
+    // just guess
+
+    iBufferSize = iDispatcher->GetFreeMemory()/10;
+    iBufferSize = iBufferSize < KMinBufferSize ?
+                    KMinBufferSize :
+                    iBufferSize;
+    //test
+    iBufferSize = 3*KMinBufferSize;
+    }
+
+TInt CHtiFtpServicePlugin::SendControlMsg( TFtpCommand aCmd,
+                                           const TDesC8& aMsg  )
+    {
+    TInt err = KErrNone;
+    HBufC8* temp = NULL;
+    TRAP( err, temp = HBufC8::NewL( 1 + aMsg.Size() ) );
+    if ( err == KErrNone )
+        {
+        temp->Des().Append( aCmd );
+        temp->Des().Append( aMsg );
+        err = iDispatcher->DispatchOutgoingMessage( temp,
+                        KFtpServiceUid,
+                        EFalse,
+                        EHtiPriorityControl );
+        if ( err != KErrNone )
+            {
+            delete temp;
+            }
+        }
+    return err;
+    }
+
+inline TInt CHtiFtpServicePlugin::SendErrorMsg( TInt anError,
+                                                const TDesC8& aMsg )
+    {
+    SetBURFakeState( EFalse ); // errors ignored
+    return iDispatcher->DispatchOutgoingErrorMessage( anError,
+                                               aMsg,
+                                               KFtpServiceUid);
+    }
+
+TBool CHtiFtpServicePlugin::IsBusy()
+    {
+    return !( iState == EIdle || iState == EStorWait || iState == ERetrWait );
+    }
+
+void CHtiFtpServicePlugin::ProcessMessageL(const TDesC8& aMessage,
+                THtiMessagePriority aPriority)
+    {
+    HTI_LOG_FUNC_IN("CHtiFtpServicePlugin::ProcessMessage");
+
+    if ( IsBusy() )
+        {
+        //should not happend - service busy,deny request
+        User::Leave( KErrInUse );
+        }
+
+    switch ( aPriority )
+        {
+        case EHtiPriorityData:
+            {
+            HandleDataMessageL( aMessage );
+            }
+            break;
+        case EHtiPriorityControl:
+            {
+            if ( iState == EStorWait || iState == ERetrWait )
+                {
+                HandleCancelL( aMessage );
+                }
+            else
+                {
+                HandleControlMessageL( aMessage );
+                }
+            }
+            break;
+        default:
+            HTI_LOG_TEXT("Unknown priority");
+        }
+
+    HTI_LOG_FUNC_OUT("CHtiFtpServicePlugin::ProcessMessage");
+    }
+
+void CHtiFtpServicePlugin::HandleControlMessageL(const TDesC8& aMessage)
+    {
+    TInt err = KErrNone;
+
+    if ( aMessage.Length() > 0 )
+        {
+        TBool unicode = aMessage[0]&KUnicodeMask;
+        HTI_LOG_FORMAT("cmd %d", aMessage[0] );
+
+        switch ( aMessage[0] )
+            {
+            case EFtpSTOR:
+            case EFtpSTOR_u:
+                {
+                //receive file
+                //get filesize
+                if ( aMessage.Length() > 5 )
+                    {
+                    iFileSize = aMessage[1] +
+                                ( aMessage[2] << 8  ) +
+                                ( aMessage[3] << 16 ) +
+                                ( aMessage[4] << 24 );
+
+                    HTI_LOG_FORMAT( "Filesize %d", iFileSize );
+                    //get fileName
+                    if ( GetFileNameL( aMessage.Mid( 5 ),
+                                      unicode ) )
+                        {
+                        HandleReceiveFileL();
+                        }
+                    }
+                else
+                    {
+                    HTI_LOG_TEXT("no file size or file name");
+                    User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                            KErrDescrInvalidStorArgument) );
+
+                    }
+                }
+                break;
+            case EFtpRETR:
+            case EFtpRETR_u:
+                {
+                //send file
+                //get fileName and size
+                if ( GetFileNameL( aMessage.Mid(1),
+                                   unicode ) )
+                    {
+                    HandleSendFileL();
+                    }
+                }
+                break;
+            case EFtpLIST:
+            case EFtpLIST_u:
+            case EFtpLISTSIZES:
+            case EFtpLISTSIZES_u:
+                {
+                if ( GetDirectoryL( aMessage.Mid( 1 ),
+                                   unicode ) )
+                    {
+                    HandleListL( unicode,
+                        ( KEntryAttHidden| KEntryAttSystem|KEntryAttNormal ),
+                        ( aMessage[0] == EFtpLISTSIZES ||
+                          aMessage[0] == EFtpLISTSIZES_u ) );
+                    }
+                }
+                break;
+            case EFtpListDetail:
+            case EFtpListDetail_u:
+                {
+                if ( GetDirectoryL( aMessage.Mid( 1 ),
+                                   unicode ) )
+                    {
+                    HandleListDetailL( unicode,
+                        KEntryAttHidden| KEntryAttSystem|KEntryAttNormal);
+                    }
+                }
+                break;
+            case EFtpLISTDIR:
+            case EFtpLISTDIR_u:
+                {
+                if ( GetDirectoryL( aMessage.Mid( 1 ),
+                                   unicode ) )
+                    {
+                    HandleListL( unicode,
+                                (KEntryAttMatchExclusive|
+                                KEntryAttHidden|KEntryAttSystem|
+                                KEntryAttDir), EFalse );
+                    }
+                }
+                break;
+            case EFtpListDirDetail:
+            case EFtpListDirDetail_u:
+                {
+                if ( GetDirectoryL( aMessage.Mid( 1 ),
+                                   unicode ) )
+                    {
+                    HandleListDetailL( unicode,
+                            KEntryAttMatchExclusive|KEntryAttHidden|
+                            KEntryAttSystem|KEntryAttDir);
+                    }
+                }
+                break;
+            case EFtpMKD:
+            case EFtpMKD_u:
+                {
+                if ( GetDirectoryL( aMessage.Mid( 1 ),
+                                   unicode ) )
+                    {
+                    if ( IsFileTcb( iFileName ) )
+                        {
+                        HandleTcbMkdL( iFileName );
+                        }
+                    else
+                        {
+                        err = iFs.MkDirAll( iFileName );
+                        if ( err == KErrNone || err == KErrAlreadyExists )
+                            {
+                            User::LeaveIfError( SendControlMsg( EFtpOK,
+                                                                KNullDesC8) );
+                            }
+                        else
+                            {
+                            User::LeaveIfError( SendErrorMsg( err,
+                                                        KErrDescrFailedMkDir ) );
+
+                            }
+                        }
+                    }
+                }
+                break;
+            case EFtpRMD:
+            case EFtpRMD_u:
+                {
+                if ( GetDirectoryL( aMessage.Mid( 1 ),
+                                   unicode ) )
+                    {
+                    if ( IsFileTcb( iFileName ) )
+                        {
+                        HandleTcbRmdL( iFileName );
+                        }
+                    else
+                        {
+                        delete iHandlerAO;
+                        iHandlerAO = NULL;
+
+                        iHandlerAO = new(ELeave) CFtpHandlerAO( this );
+                        err = iFileMan->RmDir( iFileName, iHandlerAO->iStatus );
+                        if ( err == KErrNone)
+                            {
+                            iState = ERmdBusy;
+                            iHandlerAO->Start();
+                            }
+                        else
+                            {
+                            delete iHandlerAO;
+                            iHandlerAO = NULL;
+                            User::LeaveIfError( SendErrorMsg( err,
+                                                        KErrDescrFailedRmDir ) );
+                            }
+                        }
+                    }
+                }
+                break;
+            case EFtpDELE:
+            case EFtpDELE_u:
+                {
+                if ( GetFileNameL( aMessage.Mid( 1 ),
+                                   unicode ) )
+                    {
+                    if ( IsFileTcb( iFileName ) )
+                        {
+                        HandleTcbDeleteL( iFileName );
+                        }
+                    else
+                        {
+                        HandleDeleteL( iFileName );
+                        }
+                    }
+                }
+                break;
+            case EFtpCANCEL:
+                {
+                User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                                KErrDescrNoCancel ) );
+                }
+                break;
+            case EFtpSETFORCE:
+                {
+                if ( aMessage.Length() != 2 )
+                    {
+                    User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                                KErrDescrInvalidForceArgs ) );
+                    }
+                else
+                    {
+                    if ( aMessage[1] )
+                        {
+                        // Setting forced operations on
+                        err = iBackupFakeLib.Load( KHtiFtpBackupFakeDllName );
+                        HTI_LOG_FORMAT( "BackupFake DLL load returned %d", err );
+                        if ( err == KErrNone && iBackupFakeLib.Type()[1] ==
+                                KHtiFtpBackupFakeInterfaceUid )
+                            {
+                            HTI_LOG_TEXT( "BackupFake DLL found" );
+                            TLibraryFunction entry = iBackupFakeLib.Lookup( 1 );
+                            if ( entry != NULL )
+                                {
+                                iBackupFake = ( CHtiFtpBackupFakeBase* ) entry();
+                                TRAP( err, iBackupFake->ConstructL( &iFs ) );
+                                }
+                            }
+                        if ( err == KErrNone )
+                            {
+                            SendControlMsg( EFtpOK, KNullDesC8 );
+                            }
+                        else
+                            {
+                            User::LeaveIfError( SendErrorMsg( KErrNotSupported,
+                                KErrDescrNotSupported ) );
+                            }
+                        }
+                    else
+                        {
+                        // Setting forced operations off
+                        delete iBackupFake;
+                        iBackupFake = NULL;
+                        iBackupFakeLib.Close();
+                        SendControlMsg( EFtpOK, KNullDesC8 );
+                        }
+                    }
+                }
+                break;
+            case EFtpCHECKSUM:
+            case EFtpCHECKSUM_u:
+                {
+                if ( aMessage.Length() < 3 )
+                    {
+                    User::LeaveIfError(
+                        SendErrorMsg( KErrArgument,
+                                      KErrDescrInvalidChecksumArgs ) );
+                    }
+                else if ( GetFileNameL( aMessage.Mid( 2 ), unicode ) )
+                    {
+                    HandleCheckSumCalcL( (TAlgorithm)aMessage[1], iFileName );
+                    }
+                }
+                break;
+            case EFtpFORMAT:
+                {
+                if ( aMessage.Length() != 3 )
+                    {
+                    User::LeaveIfError( SendErrorMsg( KErrArgument,
+                            KErrDescrInvalidFormatArgs ) );
+                    }
+                else
+                    {
+                    HandleFormat( aMessage[1], aMessage[2] );
+                    }
+                }
+                break;
+            case EFtpLISTDRIVES:
+            case EFtpLISTDRIVES_u:
+                {
+                if ( aMessage.Length() != 1 )
+                    {
+                    User::LeaveIfError( SendErrorMsg( KErrArgument,
+                        KErrDescrInvalidDriveListArgs ) );
+                    }
+                else
+                    {
+                    HandleListDrivesL( unicode );
+                    }
+                }
+                break;
+            case EFtpRENAME:
+            case EFtpRENAME_u:
+                {
+                HandleRenameL( aMessage, unicode );
+                }
+                break;
+            case EFtpCOPY:
+            case EFtpCOPY_u:
+                {
+                HandleCopyL( aMessage, unicode );
+                }
+                break;
+            case EFtpMOVE:
+            case EFtpMOVE_u:
+                {
+                HandleMoveL( aMessage, unicode );
+                }
+                break;
+            default:
+                {
+                //Error: unknown command
+                User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                                KErrDescrUnknownCmd ) );
+                }
+            }
+        }
+    else
+        {
+        //error: empty request
+        User::LeaveIfError( SendErrorMsg( KErrArgument, KErrDescrUnknownCmd ) );
+        }
+    }
+
+void CHtiFtpServicePlugin::HandleDeleteL( const TDesC& aFilename )
+    {
+    HTI_LOG_FUNC_IN( "CHtiFtpServicePlugin::HandleDeleteL" );
+    delete iHandlerAO;
+    iHandlerAO = NULL;
+
+    iHandlerAO = new(ELeave) CFtpHandlerAO( this );
+    TInt err = iFileMan->Delete( aFilename, 0, iHandlerAO->iStatus );
+    if ( err == KErrNone)
+        {
+        iState = EDeleBusy;
+        iHandlerAO->Start();
+        }
+    else
+        {
+        HTI_LOG_FORMAT( "Delete failed %d", err );
+        delete iHandlerAO;
+        iHandlerAO = NULL;
+        User::LeaveIfError( SendErrorMsg( err,
+                                    KErrDescrFailedDeleFile ) );
+        }
+    HTI_LOG_FUNC_OUT( "CHtiFtpServicePlugin::HandleDeleteL" );
+    }
+
+void CHtiFtpServicePlugin::HandleRenameL( const TDesC8& aMessage, TBool aUnicode )
+    {
+    delete iHandlerAO;
+    iHandlerAO = NULL;
+
+    TInt originalLenngth = aMessage[1];
+
+    GetFileNameL( aMessage.Mid( 1, originalLenngth + 1 ), aUnicode );
+
+    //If last character is back slash remove it
+    RemoveEndBackslash(iFileName);
+
+    TFileName origName = iFileName;
+
+    TInt newNamePos = originalLenngth + 2 ;
+    TInt newNameLength = aMessage[newNamePos];
+    GetFileNameL( aMessage.Mid( newNamePos, newNameLength + 1 ), aUnicode );
+
+    RemoveEndBackslash( iFileName );
+
+    if ( IsFileTcb( origName ) || IsFileTcb( iFileName ) )
+        {
+        HandleTcbRenameL( origName, iFileName );
+        }
+    else
+        {
+        iHandlerAO = new ( ELeave ) CFtpHandlerAO( this );
+        TInt err = iFileMan->Rename( origName, iFileName,
+                    CFileMan::EOverWrite, iHandlerAO->iStatus );
+
+        if ( err == KErrNone )
+            {
+            iState = ERenameBusy;
+            iHandlerAO->Start();
+            }
+        else
+            {
+            HTI_LOG_FORMAT( "Rename failed %d", err );
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+            User::LeaveIfError( SendErrorMsg(
+                    err, KErrDescrFailedRenameFile ) );
+            }
+        }
+
+    }
+
+void CHtiFtpServicePlugin::RemoveEndBackslash( TFileName& aFileName  )
+    {
+    //If last character is back slash remove it
+    if ( aFileName.Right( 1 ) == KBackslash )
+        {
+        aFileName.Delete( aFileName.Length() - 1, 1 );
+        }
+    }
+
+void CHtiFtpServicePlugin::HandleCopyL( const TDesC8& aMessage, TBool aUnicode )
+    {
+    delete iHandlerAO;
+    iHandlerAO = NULL;
+
+    TInt originalLenngth = aMessage[1];
+
+    GetFileNameL( aMessage.Mid( 1, originalLenngth + 1 ), aUnicode );
+    TFileName origName = iFileName;
+
+    TInt newNamePos = originalLenngth + 2 ;
+    TInt newNameLength = aMessage[newNamePos];
+    GetFileNameL( aMessage.Mid( newNamePos, newNameLength + 1 ), aUnicode );
+
+    TInt msglen = aMessage.Length();
+    TInt recurse = 1;
+    if(msglen>originalLenngth+newNameLength+3)        
+        {
+        recurse = aMessage[newNamePos+1+newNameLength];
+        }
+    
+    TInt err=0;
+    if ( IsFileTcb( origName ) || IsFileTcb( iFileName ) )
+        {
+        HandleTcbCopyL( origName, iFileName );
+        }
+    else{
+        iHandlerAO = new ( ELeave ) CFtpHandlerAO( this );
+        
+        if (recurse)
+            {
+            err = iFileMan->Copy( origName, iFileName,
+                ( CFileMan::EOverWrite | CFileMan::ERecurse ),
+                iHandlerAO->iStatus );
+            }
+        else
+            {
+            err = iFileMan->Copy( origName, iFileName,
+                ( CFileMan::EOverWrite ),
+                iHandlerAO->iStatus );
+            }
+
+        if ( err == KErrNone)
+            {
+            iState = ECopyBusy;
+            iHandlerAO->Start();
+            }
+        else
+            {
+            HTI_LOG_FORMAT( "Rename failed %d", err );
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+            User::LeaveIfError( SendErrorMsg( err,
+                                        KErrDescrFailedCopyFile ) );
+            }
+        }
+    }
+
+void CHtiFtpServicePlugin::HandleMoveL( const TDesC8& aMessage, TBool aUnicode )
+    {
+    delete iHandlerAO;
+    iHandlerAO = NULL;
+
+    TInt originalLenngth = aMessage[1];
+
+    GetFileNameL( aMessage.Mid( 1, originalLenngth + 1 ), aUnicode );
+
+    RemoveEndBackslash( iFileName );
+
+    TFileName origName = iFileName;
+
+    TInt newNamePos = originalLenngth + 2 ;
+    TInt newNameLength = aMessage[newNamePos];
+    GetFileNameL( aMessage.Mid( newNamePos, newNameLength + 1 ), aUnicode );
+    // make sure destination ends with backslash - destination always directory
+    if ( iFileName.Right( 1 ) != KBackslash )
+        {
+        iFileName.Append( KBackslash );
+        }
+
+    if ( IsFileTcb( origName ) || IsFileTcb( iFileName ) )
+        {
+        HandleTcbMoveL( origName, iFileName );
+        }
+    else
+        {
+        iHandlerAO = new ( ELeave ) CFtpHandlerAO( this );
+        TInt err = iFileMan->Move( origName, iFileName,
+                ( CFileMan::EOverWrite | CFileMan::ERecurse ),
+                iHandlerAO->iStatus );
+
+        if ( err == KErrNone )
+            {
+            iState = EMoveBusy;
+            iHandlerAO->Start();
+            }
+        else
+            {
+            HTI_LOG_FORMAT( "Move failed %d", err );
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+            User::LeaveIfError( SendErrorMsg( err,
+                                        KErrDescrFailedMoveFile ) );
+            }
+        }
+    }
+
+void CHtiFtpServicePlugin::HandleCancelL(const TDesC8& aMessage)
+    {
+
+    if ( aMessage.Length()>0 )
+        {
+        HTI_LOG_FORMAT("cmd %d", aMessage[0]);
+
+        if ( aMessage[0] == EFtpCANCEL )
+            {
+            //handle cancel
+            iFile.Close();
+
+            if ( iState == EStorWait )
+                {
+                iFs.Delete(iFileName);
+                }
+            else if ( iState == ERetrWait )
+                {
+                iDispatcher->RemoveMemoryObserver(this);
+
+                delete iSendBuffer;
+                iSendBuffer = NULL;
+                }
+            //other states filtered out before
+
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+
+            iState = EIdle;
+
+            User::LeaveIfError( SendControlMsg( EFtpOK, KNullDesC8) );
+            }
+        else
+            {
+            User::LeaveIfError( SendErrorMsg( KErrServerBusy,
+                            KErrDescrBusy) );
+            }
+        }
+    else
+        {
+        //send err
+        User::LeaveIfError( SendErrorMsg( KErrArgument,
+                            KErrDescrUnknownCmd ) );
+        }
+    }
+
+void CHtiFtpServicePlugin::CopyUnicode( TDes& aTo, const TDesC8& aFrom )
+{
+    HTI_LOG_FUNC_IN("CHtiFtpServicePlugin::CopyUnicode");
+    TInt len = aFrom.Length()>>1;
+    aTo.SetLength( len );
+    for ( TInt i = 0; i < len; ++i )
+    {
+        aTo[i] = (TUint16)aFrom[i<<1] + (((TUint16)aFrom[(i<<1)+1])<<8);
+    }
+    HTI_LOG_FUNC_OUT("CHtiFtpServicePlugin::CopyUnicode");
+}
+
+TBool CHtiFtpServicePlugin::GetFileNameL( const TDesC8& aFilename,
+                                          TBool aToUnicode )
+    {
+    HTI_LOG_FUNC_IN("CHtiFtpServicePlugin::GetFileNameL");
+    if ( aFilename.Length() > 1 )
+        {
+        TInt length = aFilename[0];
+        TInt size = aToUnicode ? ( length * 2 ) : length;
+
+        if ( ( size + 1 ) == aFilename.Size() )
+            {
+            if ( aToUnicode )
+                {
+                //const TPtrC8 ptr = aFilename.Mid(1).Ptr();
+                //iFileName.Copy( (TUint16*)ptr, len );
+                CopyUnicode( iFileName, aFilename.Mid( 1 ) );
+                }
+            else
+                {
+                iFileName.Copy( aFilename.Mid( 1, length ) );
+                }
+
+            HTI_LOG_TEXT( "filename:" );
+            HTI_LOG_DES( iFileName );
+            return ETrue;
+            }
+        else
+            {
+            User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                              KErrDescrInvalidFilenameLength ) );
+            }
+        }
+    else
+        {
+        User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                          KErrDescrEmptyFilename ) );
+        }
+
+    HTI_LOG_FUNC_OUT("CHtiFtpServicePlugin::GetFileNameL");
+    return EFalse;
+    }
+
+TBool CHtiFtpServicePlugin::GetDirectoryL( const TDesC8& aDirname,
+                                           TBool aToUnicode )
+    {
+    HTI_LOG_FUNC_IN("CHtiFtpServicePlugin::GetDirectoryL");
+    if ( aDirname.Length() > 1 )
+        {
+        TInt len = aDirname[0];
+        TInt size = aToUnicode ? ( len * 2 ) : len;
+        if ( ( size + 1 ) == aDirname.Size() )
+            {
+            if ( aToUnicode )
+                {
+                //const TUint8* ptr = aDirname.Mid(1).Ptr();
+                //iFileName.Copy( (TUint16*)ptr, len );
+                CopyUnicode( iFileName, aDirname.Mid(1) );
+                }
+            else
+                {
+                iFileName.Copy( aDirname.Mid( 1, len ) );
+                }
+
+            HTI_LOG_TEXT( "dir:" );
+            HTI_LOG_DES( iFileName );
+            if ( iFileName.Right( 1 ) != KBackslash )
+                {
+                iFileName.Append( KBackslash );
+                }
+            HTI_LOG_FUNC_OUT("CHtiFtpServicePlugin::GetDirectoryL");
+            return ETrue;
+            }
+        else
+            {
+            User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                              KErrDescrInvalidDirnameLength ) );
+            }
+        }
+    else
+        {
+        User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                          KErrDescrEmptyDirname ) );
+        }
+
+    HTI_LOG_FUNC_OUT("CHtiFtpServicePlugin::GetDirectoryL");
+    return EFalse;
+    }
+
+void CHtiFtpServicePlugin::HandleListL( TBool aUnicodText,
+                                        TUint aReadingAtt, TBool aSizes )
+    {
+    HTI_LOG_FUNC_IN("HandleListL");
+    CDir* dir;
+    TInt err = iFs.GetDir( iFileName, aReadingAtt, ESortNone, dir );
+    if ( err != KErrNone )
+        {
+        User::LeaveIfError( SendErrorMsg( err, KErrDescrFailedGetDir ) );
+        return;
+        }
+
+    CleanupStack::PushL( dir );
+    //build list
+    delete iSendBuffer;
+    iSendBuffer = NULL;
+    TInt bufferLen = dir->Count()*KMaxFileName;
+    if ( aUnicodText )
+        {
+        bufferLen *= 2;
+        }
+    bufferLen += dir->Count();
+    if ( aSizes )
+        {
+        bufferLen += 4 * dir->Count();
+        }
+
+    iSendBuffer = HBufC8::NewL( bufferLen );
+    TInt dirNameLen = 0;
+    for ( TInt i = 0; i < dir->Count(); ++i)
+        {
+        dirNameLen = (*dir)[i].iName.Length();
+        iSendBuffer->Des().Append( dirNameLen );
+        if ( aUnicodText )
+            {
+            iSendBuffer->Des().Append( (TUint8*)((*dir)[i].iName.Ptr()),
+                                       dirNameLen*2 );
+            }
+        else
+            {
+            iSendBuffer->Des().Append( (*dir)[i].iName );
+            }
+        if ( aSizes )
+            {
+            TInt size = (*dir)[i].iSize;
+            iSendBuffer->Des().Append( (TUint8*)(&size), 4 );
+            }
+        }
+
+    err = iDispatcher->DispatchOutgoingMessage(iSendBuffer,
+                        KFtpServiceUid,
+                        EFalse,
+                        EHtiPriorityControl);
+
+    if (  err != KErrNone )
+        {
+        //wait for a memory
+        iState = EListBusy;
+        iDispatcher->AddMemoryObserver( this );
+        }
+    else
+        {
+        iSendBuffer = NULL;
+        }
+
+    CleanupStack::PopAndDestroy();//dir
+    HTI_LOG_FUNC_OUT("HandleListL");
+    }
+
+void CHtiFtpServicePlugin::HandleListDetailL( TBool aUnicodText, TUint aReadingAtt)
+    {
+    HTI_LOG_FUNC_IN("HandleListDetailL");
+    CDir* dir;
+    TInt err = iFs.GetDir( iFileName, aReadingAtt, ESortNone, dir );
+    if ( err != KErrNone )
+        {
+        User::LeaveIfError( SendErrorMsg( err, KErrDescrFailedGetDir ) );
+        return;
+        }
+
+    CleanupStack::PushL( dir );
+    //build list
+    delete iSendBuffer;
+    iSendBuffer = NULL;
+    TInt bufferLen = dir->Count()*KMaxFileName;
+    if ( aUnicodText )
+        {
+        bufferLen *= 2;
+        }
+    // 1 bytes for name length, 4 bytes for file size, 
+    // 6 bytes for date time, 3 bytes for attributes(hide, readonly and system)
+    bufferLen += (1 + 4 + 6 + 3) * dir->Count();
+
+    iSendBuffer = HBufC8::NewL( bufferLen );
+    TInt dirNameLen = 0;
+    for ( TInt i = 0; i < dir->Count(); ++i)
+        {
+        dirNameLen = (*dir)[i].iName.Length();
+        iSendBuffer->Des().Append( dirNameLen );
+        if ( aUnicodText )
+            {
+            iSendBuffer->Des().Append( (TUint8*)((*dir)[i].iName.Ptr()),
+                                       dirNameLen*2 );
+            }
+        else
+            {
+            iSendBuffer->Des().Append( (*dir)[i].iName );
+            }
+        TInt year = (*dir)[i].iModified.DateTime().Year();
+        iSendBuffer->Des().Append((TUint8*)(&year), 2 );
+        iSendBuffer->Des().Append( (*dir)[i].iModified.DateTime().Month()+1);
+        iSendBuffer->Des().Append( (*dir)[i].iModified.DateTime().Day()+1);
+        iSendBuffer->Des().Append( (*dir)[i].iModified.DateTime().Hour());
+        iSendBuffer->Des().Append( (*dir)[i].iModified.DateTime().Minute());
+        iSendBuffer->Des().Append( (*dir)[i].iModified.DateTime().Second());
+        iSendBuffer->Des().Append( (*dir)[i].IsHidden());
+        iSendBuffer->Des().Append( (*dir)[i].IsReadOnly());
+        iSendBuffer->Des().Append( (*dir)[i].IsSystem());
+        if((*dir)[i].IsDir() == EFalse)
+            {
+            TInt size = (*dir)[i].iSize;
+            iSendBuffer->Des().Append( (TUint8*)(&size), 4 );
+            }
+        }
+
+    err = iDispatcher->DispatchOutgoingMessage(iSendBuffer,
+                        KFtpServiceUid,
+                        EFalse,
+                        EHtiPriorityControl);
+
+    if (  err != KErrNone )
+        {
+        //wait for a memory
+        iState = EListBusy;
+        iDispatcher->AddMemoryObserver( this );
+        }
+    else
+        {
+        iSendBuffer = NULL;
+        }
+
+    CleanupStack::PopAndDestroy();//dir
+    HTI_LOG_FUNC_OUT("HandleListDetailL");
+    }
+
+void CHtiFtpServicePlugin::HandleDataMessageL( const TDesC8& aMessage )
+    {
+    switch ( iState )
+        {
+        case EStorWait:
+            {
+            iState = EStorBusy;
+            iCurrentOffset += aMessage.Size();
+
+            TInt anError = iFile.Write( aMessage );
+            if ( anError == KErrNone  )
+                {
+                HTI_LOG_FORMAT("received %d", iCurrentOffset);
+                if ( iCurrentOffset == iFileSize )
+                    {
+                    HTI_LOG_TEXT("receiving is over");
+                    //receiving is over
+                    TInt err = iFile.Flush();
+                    iFile.Close();
+                    iState = EIdle;
+                    if ( err != KErrNone )
+                        {
+                        //err
+                        HTI_LOG_TEXT("failed to close file");
+                        iFs.Delete(iFileName);
+                        SendErrorMsg( err, KErrDescrFailedCloseFile );
+                        }
+                    else
+                        {
+                        //if file should be copied to TCB
+                        //copy it to to TCB from temp location
+                        if ( IsFileTcb( iFileName ) )
+                            {
+                            HandleTcbCopyL( KTmpFileName, iFileName );
+                            }
+                        else
+                            {
+                            SetBURFakeState( EFalse );
+                            SendControlMsg( EFtpOK, KNullDesC8 );
+                            }
+                        }
+                    }
+                else
+                    {
+                    iState = EStorWait;
+                    }
+                }
+            else
+                {
+                HTI_LOG_FORMAT("error writing file %d", anError);
+                //abort operation and send err msg
+
+                iFile.Close();
+                iFs.Delete(iFileName);
+                iState = EIdle;
+                SendErrorMsg( anError, KErrDescrFailedWrite );
+                }
+            }
+            break;
+        default:
+            //do nothing
+            User::LeaveIfError( SendErrorMsg( KErrArgument,
+                                              KErrDescrInvalidDataMessage ) );
+            break;
+        }
+    }
+
+void CHtiFtpServicePlugin::HandleReceiveFileL()
+    {
+    HTI_LOG_FUNC_IN("HandleReceiveFileL");
+
+    // create file
+    TInt err = KErrNone;
+
+    //if file should be copied to TCB
+    //first copy it to temp location
+    if ( IsFileTcb( iFileName ) )
+        {
+        err = iFile.Replace( iFs, KTmpFileName, EFileWrite );
+        }
+        else
+        {
+        err = iFile.Replace(
+            iFs, iFileName, EFileWrite | EFileShareExclusive );
+        }
+
+    if ( err != KErrNone )
+        {
+        err = iFile.Replace(
+            iFs, iFileName, EFileWrite | EFileShareAny );
+        }
+
+    if ( err != KErrNone )
+        {
+        err = iFile.Replace(
+            iFs, iFileName, EFileWrite | EFileShareReadersOrWriters );
+        }
+
+    if ( err != KErrNone )
+        {
+        if ( SetBURFakeState( ETrue ) == KErrNone )
+            {
+            err = iFile.Replace(
+                iFs, iFileName, EFileWrite | EFileShareExclusive );
+            }
+        }
+
+    if ( err != KErrNone )
+        {
+        HTI_LOG_TEXT("failed create file");
+        SendErrorMsg( err, KErrDescrFailedCreateFile );
+        return;
+        }
+
+    //check that there is enough disk space
+    err = iFile.SetSize( iFileSize );
+    if ( err != KErrNone )
+        {
+        HTI_LOG_TEXT("not enough space");
+        SendErrorMsg( err, KErrDescrNoSpace );
+        iFile.Close();
+        iFs.Delete( iFileName );
+        return;
+        }
+
+    // init receiving byte counter
+    iCurrentOffset = 0;
+    iState = EStorWait;
+
+    //send ok and
+    User::LeaveIfError( SendControlMsg( EFtpOK, KNullDesC8 ) );
+    //...wait for data messages
+    HTI_LOG_FUNC_OUT("HandleReceiveFileL");
+    }
+
+void CHtiFtpServicePlugin::HandleSendFileL()
+    {
+    //open it
+    TInt err = iFile.Open( iFs, iFileName, EFileRead | EFileShareAny );
+
+    if ( err != KErrNone )
+        {
+        err = iFile.Open( iFs, iFileName, EFileRead | EFileShareReadersOnly );
+        }
+
+    if ( err != KErrNone )
+        {
+        err = iFile.Open( iFs, iFileName, EFileRead | EFileShareReadersOrWriters );
+        }
+
+    if ( err != KErrNone )
+        {
+        if ( SetBURFakeState( ETrue ) == KErrNone )
+            {
+            err = iFile.Open(
+                iFs, iFileName, EFileRead | EFileShareReadersOnly );
+            }
+        }
+
+    if ( err != KErrNone )
+        {
+        HTI_LOG_FORMAT("failed open file %d", err);
+        SendErrorMsg( err, KErrDescrFailedOpenFile );
+        return;
+        }
+
+    //send file size
+    err = iFile.Size( iFileSize );
+    if ( err != KErrNone )
+        {
+        HTI_LOG_TEXT("failed get filesize");
+        User::LeaveIfError( SendErrorMsg( err, KErrDescrFailedOpenFile ) );
+        }
+
+    TBuf8<KFileSizeMsgSize> fileSizeMsg;
+    fileSizeMsg.Append( (TUint8*)(&iFileSize), 4 );
+    User::LeaveIfError( SendControlMsg( EFtpFILESIZE, fileSizeMsg ) );
+
+    iCurrentOffset = 0;
+    //start sending
+    //always observe when sending
+    iDispatcher->AddMemoryObserver( this );
+
+    //create handler for following RFile::Write
+    delete iHandlerAO;
+    iHandlerAO = NULL;
+    iHandlerAO = new(ELeave) CFtpHandlerAO( this );
+
+    //start operation
+    ReadToBuffer();
+    }
+
+void CHtiFtpServicePlugin::ReadToBuffer()
+    {
+    HTI_LOG_FUNC_IN("ReadToBuffer");
+    //check that iHandlerAO valid
+    if ( iHandlerAO )
+        {
+        if ( !iHandlerAO->IsActive() )
+            {
+            //dispatch messages in the outgoing queue until run out of memory
+            TInt err;
+            //allocate memory and read from file
+            delete iSendBuffer;
+            iSendBuffer = NULL;
+
+            TRAP( err, iSendBuffer = HBufC8::NewL( iBufferSize ) );
+            if ( err == KErrNone )
+                {
+                HTI_LOG_TEXT("read file");
+                iState = ERetrBusy;
+                iSendBufferDes.Set( iSendBuffer->Des() );
+                iFile.Read( iSendBufferDes, iHandlerAO->iStatus  );
+                iHandlerAO->Start();
+                }
+            else
+                {
+                //go to idle state
+                HTI_LOG_TEXT("impossible to alloc mem");
+                iDispatcher->RemoveMemoryObserver( this );
+
+                delete iHandlerAO;
+                iHandlerAO = NULL;
+
+                iFile.Close();
+                iState = EIdle;
+                //try to send err message
+                SendErrorMsg( KErrNoMemory, KErrDescrNoMemory );
+                }
+            }
+        else
+            {
+            //error, ignore
+            HTI_LOG_TEXT("ERROR: Call ReadBuffer with active handler");
+            }
+        }
+    else
+        {
+        //error
+        HTI_LOG_TEXT("ERROR: Call ReadBuffer with no handler");
+        //go to idle
+        iState = EIdle;
+        }
+    HTI_LOG_FUNC_OUT("ReadToBuffer");
+    }
+
+void CHtiFtpServicePlugin::SendBuffer()
+    {
+    HTI_LOG_FUNC_IN("SendBuffer");
+    if ( iSendBuffer )
+        {
+        HTI_LOG_FORMAT("iCurrentOffset %d bytes", iCurrentOffset);
+        //send buffer
+        TInt err = iDispatcher->DispatchOutgoingMessage( iSendBuffer,
+                        KFtpServiceUid,
+                        EFalse,
+                        EHtiPriorityData);
+
+        if ( err == KErrNone )
+            {
+            HTI_LOG_TEXT("message was dispatched");
+            //message was dispatched
+            iSendBuffer = NULL;
+            //check do we have to continue
+            if ( iCurrentOffset >= iFileSize )
+                {
+                HTI_LOG_TEXT( "over sending" );
+
+                delete iHandlerAO;
+                iHandlerAO = NULL;
+
+                iFile.Close();
+                iState = EIdle;
+
+                iDispatcher->RemoveMemoryObserver( this );
+                SetBURFakeState( EFalse );
+                }
+            else
+                {
+                //read and send next package
+                ReadToBuffer();
+                }
+            }
+        else if ( err == KErrNoMemory )
+            {
+            //wait for memory
+            //observer should be active
+            iState = ERetrWait;
+            }
+        else if ( err != KErrNone )
+            {
+            HTI_LOG_FORMAT("error dispatching outgoing message %d", err );
+            //some err, abort operation
+            delete iSendBuffer;
+            iSendBuffer = NULL;
+
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+
+            iFile.Close();
+
+            iState = EIdle;
+
+            iDispatcher->RemoveMemoryObserver( this );
+            SetBURFakeState( EFalse );
+            }
+        }
+    else
+        {
+        //really weird error, go to idle
+        HTI_LOG_TEXT("ERROR: SendBuffer with empty iSendBuffer");
+        iState = EIdle;
+        SetBURFakeState( EFalse );
+        }
+    HTI_LOG_FUNC_OUT("SendBuffer");
+    }
+
+void CHtiFtpServicePlugin::FtpComplete( TInt anError)
+    {
+    HTI_LOG_FUNC_IN("FtpComplete");
+    HTI_LOG_FORMAT("error %d", anError);
+
+    //NOTE: can't leave from here
+    switch ( iState )
+        {
+        case ERmdBusy:
+            {
+            //send OK message
+            if ( anError == KErrNone )
+                {
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                SendErrorMsg( anError, KErrDescrFailedRmDir );
+                }
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+
+            iState = EIdle;
+            }
+            break;
+        case EDeleBusy:
+            {
+            //send OK message
+            if ( anError == KErrNone )
+                {
+                SetBURFakeState( EFalse );
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                if ( SetBURFakeState( ETrue ) != KErrNone )
+                    {
+                    // Force was not requested, not supported OR already tried.
+                    SendErrorMsg( anError, KErrDescrFailedDeleFile );
+                    }
+                else
+                    {
+                    // try delete again
+                    TRAPD( err, HandleDeleteL( iFileName ) );
+                    if ( err == KErrNone )
+                        {
+                        break;
+                        }
+                    else
+                        {
+                        SendErrorMsg( err, KErrDescrFailedDeleFile );
+                        }
+                    }
+                }
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+
+            iState = EIdle;
+            }
+            break;
+        case ERenameBusy:
+            {
+            //send OK message
+            if ( anError == KErrNone )
+                {
+                SetBURFakeState( EFalse );
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                SendErrorMsg( anError, KErrDescrFailedRenameFile );
+                }
+
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+
+            iState = EIdle;
+            }
+            break;
+        case ECopyBusy:
+            {
+            //send OK message
+            if ( anError == KErrNone )
+                {
+                SetBURFakeState( EFalse );
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                SendErrorMsg( anError, KErrDescrFailedCopyFile );
+                }
+
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+
+            iState = EIdle;
+            }
+            break;
+        case EMoveBusy:
+            {
+            //send OK message
+            if ( anError == KErrNone )
+                {
+                SetBURFakeState( EFalse );
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                SendErrorMsg( anError, KErrDescrFailedMoveFile );
+                }
+
+            delete iHandlerAO;
+            iHandlerAO = NULL;
+
+            iState = EIdle;
+            }
+            break;
+        case EMoveTcbBusy:
+            {
+            //send OK message
+            if ( anError == KErrNone )
+                {
+                SetBURFakeState( EFalse );
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                SendErrorMsg( anError, KErrDescrFailedMoveFile );
+                }
+
+            delete iProcessLogonAO;
+            iProcessLogonAO = NULL;
+
+            iState = EIdle;
+            }
+            break;
+        case ERenameTcbBusy:
+            {
+            //send OK message
+            if ( anError == KErrNone )
+                {
+                SetBURFakeState( EFalse );
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                SendErrorMsg( anError, KErrDescrFailedRenameFile );
+                }
+
+            delete iProcessLogonAO;
+            iProcessLogonAO = NULL;
+
+            iState = EIdle;
+            }
+            break;
+        case EDeleTcbBusy:
+            {
+            //send OK message
+            if ( anError == KErrNone )
+                {
+                SetBURFakeState( EFalse );
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                if ( SetBURFakeState( ETrue ) != KErrNone )
+                    {
+                    // Force was not requested, not supported OR already tried.
+                    SendErrorMsg( anError, KErrDescrFailedDeleFile );
+                    }
+                else
+                    {
+                     // try delete again
+                    TRAPD( err, HandleTcbDeleteL( iFileName ) );
+                    if ( err == KErrNone )
+                        {
+                        break;
+                        }
+                    else
+                        {
+                        SendErrorMsg( err, KErrDescrFailedDeleFile );
+                        }
+                    }
+                }
+            delete iProcessLogonAO;
+            iProcessLogonAO = NULL;
+
+            iState = EIdle;
+            }
+            break;
+        case EMkdTcbBusy:
+            {
+            if ( anError == KErrNone || anError == KErrAlreadyExists )
+                {
+                SendControlMsg( EFtpOK, KNullDesC8);
+                }
+            else
+                {
+                SendErrorMsg( anError, KErrDescrFailedMkDir );
+                }
+            delete iProcessLogonAO;
+            iProcessLogonAO = NULL;
+
+            iState = EIdle;
+
+            }
+            break;
+        case ERmdTcbBusy:
+            {
+            if ( anError == KErrNone || anError == KErrAlreadyExists )
+                {
+                SendControlMsg( EFtpOK, KNullDesC8);
+                }
+            else
+                {
+                SendErrorMsg( anError, KErrDescrFailedRmDir );
+                }
+            delete iProcessLogonAO;
+            iProcessLogonAO = NULL;
+
+            iState = EIdle;
+
+            }
+            break;
+
+        case EStorBusy:
+            {
+            if ( anError == KErrNone  )
+                {
+                HTI_LOG_FORMAT("received %d", iCurrentOffset);
+                if ( iCurrentOffset == iFileSize )
+                    {
+                    HTI_LOG_TEXT("receiveing is over");
+                    //receiveing is over
+                    delete iHandlerAO;
+                    iHandlerAO = NULL;
+
+                    iState = EIdle;
+
+                    TInt err = iFile.Flush();
+                    iFile.Close();
+                    if ( err != KErrNone )
+                        {
+                        //err
+                        HTI_LOG_TEXT("failed to close file");
+                        iFs.Delete(iFileName);
+                        SendErrorMsg( err, KErrDescrFailedCloseFile );
+                        }
+                    else
+                        {
+                        //if file should be copied to TCB
+                        //copy it to to TCB from temp location
+                        if ( IsFileTcb( iFileName ) )
+                            {
+                            TRAP( err, HandleTcbCopyL(
+                                KTmpFileName, iFileName ) );
+                            if ( err != KErrNone )
+                                {
+                                SendErrorMsg( anError, KErrDescrFailedCopyTcb );
+                                iFs.Delete( KTmpFileName );
+                                delete iProcessLogonAO;
+                                iProcessLogonAO = NULL;
+                                iState = EIdle;
+                                }
+                            }
+                        else
+                            {
+                            SetBURFakeState( EFalse );
+                            SendControlMsg( EFtpOK, KNullDesC8 );
+                            }
+                        }
+                    }
+                else
+                    {
+                    iState = EStorWait;
+                    //busy state is over
+                    iDispatcher->Notify(KErrNone);
+                    }
+                }
+            else
+                {
+                HTI_LOG_FORMAT("error writing file %d", anError);
+                //abort operation and send err msg
+                delete iHandlerAO;
+                iHandlerAO = NULL;
+
+                iFile.Close();
+                iFs.Delete(iFileName);
+                iState = EIdle;
+                SendErrorMsg( anError, KErrDescrFailedWrite );
+                }
+            }
+            break;
+
+        case EStorTcbBusy:
+            {
+            if ( anError == KErrNone )
+                {
+                SetBURFakeState( EFalse );
+                SendControlMsg( EFtpOK, KNullDesC8 );
+                }
+            else
+                {
+                if ( SetBURFakeState( ETrue ) != KErrNone )
+                    {
+                    // Force was not requested, not supported OR already tried.
+                    HTI_LOG_FORMAT("error copy to tcb %d", anError);
+                    //abort operation and send err msg
+                    SendErrorMsg( anError, KErrDescrFailedCopyTcb );
+                    }
+                else
+                    {
+                    // try copy again
+                    TRAPD( err, HandleTcbCopyL( KTmpFileName, iFileName ) );
+                    if ( err == KErrNone )
+                        {
+                        break;
+                        // don't continue, this method will be called again
+                        // by the AO after copying is tried
+                        }
+                    else
+                        {
+                        SendErrorMsg( err, KErrDescrFailedCopyTcb );
+                        }
+                    }
+                }
+
+            //delete temp file
+            HTI_LOG_TEXT("delete tmp file");
+            TInt err = iFs.Delete(KTmpFileName);
+            if ( err != KErrNone )
+                {
+                HTI_LOG_FORMAT("error delete tmp file %d", err);
+                }
+
+            delete iProcessLogonAO;
+            iProcessLogonAO = NULL;
+            iState = EIdle;
+            }
+            break;
+
+        case ERetrBusy:
+            {
+            if ( anError == KErrNone )
+                {
+                HTI_LOG_FORMAT("read %d bytes", iSendBuffer->Size());
+                iCurrentOffset += iSendBuffer->Size();
+
+                SendBuffer();
+                }
+            else
+                {
+                HTI_LOG_FORMAT("failed read file %d", anError);
+                //error reading file
+                //abort operation and send err msg
+                delete iSendBuffer;
+                iSendBuffer = NULL;
+
+                delete iHandlerAO;
+                iHandlerAO = NULL;
+
+                iFile.Close();
+
+                iState = EIdle;
+                iDispatcher->RemoveMemoryObserver( this );
+
+                SendErrorMsg( anError, KErrDescrFailedRead );
+                }
+            }
+            break;
+        default:
+            {
+            //some error, should not be called
+            HTI_LOG_TEXT("invalid state for FtpComplete");
+            }
+        }
+    HTI_LOG_FUNC_OUT("FtpComplete");
+    }
+
+void CHtiFtpServicePlugin::NotifyMemoryChange( TInt aAvailableMemory )
+    {
+    HTI_LOG_FUNC_IN("NotifyMemoryChange");
+    switch ( iState )
+        {
+        case ERetrWait:
+            {
+            if ( iSendBuffer )
+                {
+                if ( aAvailableMemory >= iSendBuffer->Size() )
+                    {
+                    //continue sending
+                    SendBuffer();
+                    }
+                }
+            else
+                {//impossible
+                //nothing to send
+                //just reset
+                HTI_LOG_TEXT("invalid state for mem");
+
+                delete iHandlerAO;
+                iHandlerAO = NULL;
+                iFile.Close();
+                iDispatcher->RemoveMemoryObserver(this);
+                iState = EIdle;
+                }
+            }
+            break;
+        case EListBusy:
+            {
+            if ( iSendBuffer )
+                {
+                if ( aAvailableMemory >= iSendBuffer->Size() )
+                    {
+                    //send buffer
+                    TInt err = iDispatcher->DispatchOutgoingMessage(
+                                    iSendBuffer,
+                                    KFtpServiceUid,
+                                    EFalse,
+                                    EHtiPriorityData);
+                    if ( err != KErrNone )
+                        {
+                        //error, reset
+                        HTI_LOG_TEXT("failed to send LIST");
+                        delete iSendBuffer;
+                        }
+                    iSendBuffer = NULL;
+                    iDispatcher->RemoveMemoryObserver(this);
+                    iState = EIdle;
+                    }
+                }
+            else
+                {//impossible
+                //nothing to send
+                //just reset
+                HTI_LOG_TEXT("invalid state for mem");
+                iDispatcher->RemoveMemoryObserver(this);
+                iState = EIdle;
+                }
+            }
+            break;
+        default:
+            //some error, should not be called
+            HTI_LOG_TEXT("invalid state for mem");
+            //iDispatcher->RemoveMemoryObserver(this);
+            //iState = EIdle;
+        }
+    HTI_LOG_FUNC_OUT("NotifyMemoryChange");
+    }
+
+TBool CHtiFtpServicePlugin::IsFileTcb( const TDesC& aFilename )
+    {
+    return aFilename.FindF( KHtiTcbSys ) == KPathOffset ||
+           aFilename.FindF( KHtiTcbResource ) == KPathOffset;
+    }
+
+void CHtiFtpServicePlugin::HandleTcbDeleteL( const TDesC& aFilename )
+    {
+    HTI_LOG_FUNC_IN("HandleTcbDeleteL");
+    HBufC* cmdLine = HBufC::NewLC( aFilename.Length() + 2 );
+
+    //make command line "d|filename"
+    cmdLine->Des().Copy( KHtiFileHlpDeleteCmd );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aFilename );
+
+    HTI_LOG_DES( *cmdLine );
+
+    delete iProcessLogonAO;
+    iProcessLogonAO = NULL;
+
+    iProcessLogonAO = new(ELeave) CProcessLogonAO( this );
+    iProcessLogonAO->Start( *cmdLine );
+
+    iState = EDeleTcbBusy;
+
+    CleanupStack::PopAndDestroy( cmdLine );
+    HTI_LOG_FUNC_OUT("HandleTcbDeleteL");
+    }
+
+void CHtiFtpServicePlugin::HandleTcbCopyL( const TDesC& aFromFilename,
+                                           const TDesC& aToFilename )
+    {
+    HTI_LOG_FUNC_IN("HandleTcbCopyL");
+    HBufC* cmdLine = HBufC::NewLC( aFromFilename.Length() + aToFilename.Length() + 3 );
+
+    //make command line "c|fromfilename|tofilename"
+    cmdLine->Des().Copy( KHtiFileHlpCopyCmd );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aFromFilename );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aToFilename );
+
+    HTI_LOG_DES( *cmdLine );
+
+    delete iProcessLogonAO;
+    iProcessLogonAO = NULL;
+
+    iProcessLogonAO = new(ELeave) CProcessLogonAO( this );
+    iProcessLogonAO->Start( *cmdLine );
+
+    iState = EStorTcbBusy;
+
+    CleanupStack::PopAndDestroy( cmdLine );
+    HTI_LOG_FUNC_OUT("HandleTcbCopyL");
+    }
+
+void CHtiFtpServicePlugin::HandleTcbMkdL( const TDesC& aDirname )
+    {
+    HTI_LOG_FUNC_IN("HandleTcbMkdL");
+    HBufC* cmdLine = HBufC::NewLC( aDirname.Length() + 2 );
+
+    //make command line "m|dirname"
+    cmdLine->Des().Copy( KHtiFileHlpMkdCmd );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aDirname );
+
+    HTI_LOG_DES( *cmdLine );
+
+    delete iProcessLogonAO;
+    iProcessLogonAO = NULL;
+
+    iProcessLogonAO = new(ELeave) CProcessLogonAO( this );
+    iProcessLogonAO->Start(*cmdLine);
+
+    iState = EMkdTcbBusy;
+
+    CleanupStack::PopAndDestroy(cmdLine);
+    HTI_LOG_FUNC_OUT("HandleTcbMkdL");
+    }
+
+void CHtiFtpServicePlugin::HandleTcbRmdL( const TDesC& aDirname )
+    {
+    HTI_LOG_FUNC_IN("HandleTcbRmdL");
+    HBufC* cmdLine = HBufC::NewLC( aDirname.Length() + 2 );
+
+    //make command line "r|dirname"
+    cmdLine->Des().Copy( KHtiFileHlpRmdCmd );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aDirname );
+
+    HTI_LOG_DES( *cmdLine );
+
+    delete iProcessLogonAO;
+    iProcessLogonAO = NULL;
+
+    iProcessLogonAO = new ( ELeave ) CProcessLogonAO( this );
+    iProcessLogonAO->Start( *cmdLine );
+
+    iState = ERmdTcbBusy;
+
+    CleanupStack::PopAndDestroy( cmdLine );
+    HTI_LOG_FUNC_OUT("HandleTcbRmdL");
+    }
+
+void CHtiFtpServicePlugin::HandleTcbRenameL(
+        const TDesC& aTargetName, const TDesC& aDestName )
+    {
+    HTI_LOG_FUNC_IN("HandleTcbRenameL");
+    HBufC* cmdLine = HBufC::NewLC( aTargetName.Length() + 4 + aDestName.Length());
+
+    //make command line "r|dirname"
+    cmdLine->Des().Copy( KHtiFileHlpRenameCmd );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aTargetName );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aDestName );
+
+    HTI_LOG_DES( *cmdLine );
+
+    delete iProcessLogonAO;
+    iProcessLogonAO = NULL;
+
+    iProcessLogonAO = new ( ELeave ) CProcessLogonAO( this );
+    iProcessLogonAO->Start( *cmdLine );
+
+    iState = ERenameTcbBusy;
+
+    CleanupStack::PopAndDestroy( cmdLine );
+    HTI_LOG_FUNC_OUT("HandleTcbRenameL");
+    }
+
+void CHtiFtpServicePlugin::HandleTcbMoveL(
+        const TDesC& aTargetName, const TDesC& aDestName )
+    {
+    HTI_LOG_FUNC_IN("HandleTcbRenameL");
+    HBufC* cmdLine = HBufC::NewLC( aTargetName.Length() + 4 + aDestName.Length());
+
+    //make command line "r|dirname"
+    cmdLine->Des().Copy( KHtiFileHlpMoveCmd );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aTargetName );
+    cmdLine->Des().Append( KHtiFileHlpDelim );
+    cmdLine->Des().Append( aDestName );
+
+    HTI_LOG_DES( *cmdLine );
+
+    delete iProcessLogonAO;
+    iProcessLogonAO = NULL;
+
+    iProcessLogonAO = new ( ELeave ) CProcessLogonAO( this );
+    iProcessLogonAO->Start( *cmdLine );
+
+    iState = EMoveTcbBusy;
+
+    CleanupStack::PopAndDestroy( cmdLine );
+    HTI_LOG_FUNC_OUT("HandleTcbRenameL");
+    }
+
+TInt CHtiFtpServicePlugin::SetBURFakeState( TBool aOn )
+    {
+    HTI_LOG_FUNC_IN( "CHtiFtpServicePlugin::SetBURFakeStateL" );
+    TInt err = KErrNone;
+
+    if ( iBackupFake == NULL )
+        {
+        // Foreced operations not requested or not supported
+        err = KErrNotSupported;
+        }
+
+    else if ( aOn )
+        {
+        HTI_LOG_TEXT( "Calling ActivateBackup()" );
+        err = iBackupFake->ActivateBackup();
+        }
+
+    else
+        {
+        HTI_LOG_TEXT( "Calling DeactivateBackup()" );
+        err = iBackupFake->DeactivateBackup();
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiFtpServicePlugin::SetBURFakeStateL" );
+    return err;
+    }
+
+void CHtiFtpServicePlugin::HandleCheckSumCalcL( TAlgorithm aAlgorithm,
+                                                const TDesC& aFilename )
+    {
+    HTI_LOG_FUNC_IN( "CHtiFtpServicePlugin::HandleCheckSumCalcL" );
+
+    RFile file;
+    TInt err = file.Open( iFs, aFilename, EFileRead | EFileShareReadersOnly );
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "Error opening file, err: %d", err );
+        SendErrorMsg( err, KErrDescrFailedOpenFile );
+        return;
+        }
+
+    CleanupClosePushL( file );
+    switch ( aAlgorithm )
+        {
+        case EMD5:
+            {
+            HTI_LOG_TEXT( "Using MD5 algorithm" );
+            const TInt KBufSize( 1024 );
+            TInt size = 0;
+            TInt offset = 0;
+
+            file.Size( size );
+
+            HBufC8* buf = HBufC8::NewMaxLC( KBufSize );
+            TPtr8 filePtr( buf->Des() );
+
+            CMD5* md5 = CMD5::NewL();
+            CleanupStack::PushL( md5 );
+
+            while ( offset < size - KBufSize )
+                {
+                User::LeaveIfError( file.Read( filePtr, KBufSize ) );
+                md5->Hash( filePtr );
+                offset += filePtr.Length();
+                }
+
+            file.Read( filePtr, size - offset );
+            filePtr.SetLength( size - offset );
+            md5->Hash( filePtr );
+
+            filePtr.Set( NULL, 0, 0 );
+            HBufC8* result = md5->Hash( filePtr ).AllocL();
+            CleanupStack::PushL( result );
+
+            HTI_LOG_TEXT( "Got following MD5:" );
+            HTI_LOG_DES( *result );
+
+            User::LeaveIfError(
+                iDispatcher->DispatchOutgoingMessage( result,
+                                                      KFtpServiceUid,
+                                                      EFalse,
+                                                      EHtiPriorityControl ) );
+            CleanupStack::Pop( result ); // do not delete, ownership transfered
+            CleanupStack::PopAndDestroy( 2 ); // md5, buf
+            break;
+            }
+
+        default:
+            {
+            HTI_LOG_FORMAT( "Invalid algorithm: %d", aAlgorithm );
+            SendErrorMsg( KErrNotFound, KErrDescrInvalidChecksumArgs );
+            break;
+            }
+        }
+    CleanupStack::PopAndDestroy(); // file
+
+    HTI_LOG_FUNC_OUT( "CHtiFtpServicePlugin::HandleCheckSumCalcL" );
+    }
+
+void CHtiFtpServicePlugin::HandleFormat( const TUint8 aDrive, const TUint8 aMode )
+    {
+    HTI_LOG_FUNC_IN( "CHtiFtpServicePlugin::HandleFormat" );
+
+    // Convert the format mode: in HTI protocol 0 means full format and 1
+    // (or anything else currently) means quick format
+    TUint formatMode = 0;
+    if ( aMode )
+        formatMode = ESpecialFormat | EQuickFormat;
+    else
+        formatMode = ESpecialFormat | EFullFormat;
+
+    // Create the drive name (drive letter and colon)
+    TDriveName drive;
+    drive.Append( aDrive );
+    drive.Append( _L( ":" ) );
+
+    // Check that HTI is not running from the drive that is to be formatted
+    RProcess thisProcess;
+    if ( thisProcess.FileName().FindF( drive ) == 0 )
+        {
+        HTI_LOG_FORMAT( "HTI running from drive %S cannot format", &drive );
+        SendErrorMsg( KErrInUse, KErrDescrFailedFormat );
+        HTI_LOG_FUNC_OUT( "CHtiFtpServicePlugin::HandleFormat" );
+        return;
+        }
+
+    // Activate backup/restore to close apps that might have files open.
+    // Ignore errors - try to format even if backup fake is not supported.
+    SetBURFakeState( ETrue );
+
+    // Start the format
+    HTI_LOG_FORMAT( "Starting to format drive %S", &drive );
+    HTI_LOG_FORMAT( "Format mode = %d", formatMode );
+    TInt remainingTracks = 0;
+    RFormat format;
+    TInt err = format.Open( iFs, drive, formatMode, remainingTracks );
+    if ( err == KErrNone )
+        {
+        HTI_LOG_FORMAT( "Formatting %d tracks", remainingTracks );
+        while ( remainingTracks && err == KErrNone )
+            {
+            err = format.Next( remainingTracks );
+            HTI_LOG_FORMAT( "Tracks remaining: %d", remainingTracks );
+            }
+        }
+    format.Close();
+
+    // Deactivate backup/restore - errors ignored.
+    SetBURFakeState( EFalse );
+
+    if ( err == KErrNone )
+        {
+        SendControlMsg( EFtpOK, KNullDesC8 );
+        }
+
+    else
+        {
+        SendErrorMsg( err, KErrDescrFailedFormat );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiFtpServicePlugin::HandleFormat" );
+    }
+
+void CHtiFtpServicePlugin::HandleListDrivesL( TBool aUnicode )
+    {
+    HTI_LOG_FUNC_IN( "CHtiFtpServicePlugin::HandleListDrivesL" );
+    TInt driveCount = 0;
+    TDriveList driveList;
+
+    User::LeaveIfError( iFs.DriveList( driveList, KDriveAttAll ) );
+
+    // Buffer for the drive list that is returned
+    CBufFlat* driveListBuf = CBufFlat::NewL( 256 );
+    CleanupStack::PushL( driveListBuf );
+    TInt bufPos = 0;
+
+    for ( TInt i = 0; i < KMaxDrives; i++ )
+        {
+        if ( driveList[i] )
+            {
+            HTI_LOG_FORMAT( "Found drive number %d", i );
+            TVolumeInfo volInfo;
+            if ( iFs.Volume( volInfo, i ) == KErrNone )
+                {
+                driveCount++;
+                // root path with length byte
+                TChar driveLetter;
+                iFs.DriveToChar( i, driveLetter );
+                HTI_LOG_FORMAT( "Got volume info for drive %c",
+                        TUint( driveLetter ) );
+                TBuf<3> rootPathBuf;
+                rootPathBuf.AppendFormat( KRootPathFormat,
+                        TUint( driveLetter ) );
+                TBuf8<1> lengthBuf;
+                lengthBuf.Append( rootPathBuf.Length() );
+                TBuf8<6> rootPathBuf8;
+                if ( aUnicode )
+                    {
+                    rootPathBuf8.Append( ( TUint8* ) rootPathBuf.Ptr(),
+                            rootPathBuf.Length() * 2 );
+                    }
+                else
+                    {
+                    rootPathBuf8.Copy( rootPathBuf );
+                    }
+                driveListBuf->ExpandL( bufPos, rootPathBuf8.Length() + 1 );
+                driveListBuf->Write( bufPos, lengthBuf, 1 );
+                bufPos++;
+                driveListBuf->Write( bufPos, rootPathBuf8 );
+                bufPos += rootPathBuf8.Length();
+
+                // media type 1 byte
+                TBuf8<8> tmpBuf;
+                tmpBuf.Append( volInfo.iDrive.iType );
+                driveListBuf->ExpandL( bufPos, tmpBuf.Length() );
+                driveListBuf->Write( bufPos, tmpBuf );
+                bufPos += tmpBuf.Length();
+
+                // UID 4 bytes
+                tmpBuf.Copy( ( TUint8* ) ( &volInfo.iUniqueID ), 4 );
+                driveListBuf->ExpandL( bufPos, tmpBuf.Length() );
+                driveListBuf->Write( bufPos, tmpBuf );
+                bufPos += tmpBuf.Length();
+
+                // size 8 bytes
+                tmpBuf.Copy( ( TUint8* ) ( &volInfo.iSize ), 8 );
+                driveListBuf->ExpandL( bufPos, tmpBuf.Length() );
+                driveListBuf->Write( bufPos, tmpBuf );
+                bufPos += tmpBuf.Length();
+
+                // free space 8 bytes
+                tmpBuf.Copy( ( TUint8* ) ( &volInfo.iFree ), 8 );
+                driveListBuf->ExpandL( bufPos, tmpBuf.Length() );
+                driveListBuf->Write( bufPos, tmpBuf );
+                bufPos += tmpBuf.Length();
+
+                // name with length byte
+                HBufC8* driveNameBuf8 = NULL;
+                TInt driveNameLength = volInfo.iName.Length();
+                lengthBuf.Zero();
+                lengthBuf.Append( driveNameLength );
+                driveListBuf->ExpandL( bufPos, 1 );
+                driveListBuf->Write( bufPos, lengthBuf, 1 );
+                bufPos++;
+                if ( driveNameLength > 0 )
+                    {
+                    if ( aUnicode )
+                        {
+                        driveNameBuf8 = HBufC8::NewL( driveNameLength * 2 );
+                        driveNameBuf8->Des().Append(
+                                ( TUint8* ) volInfo.iName.Ptr(),
+                                driveNameLength * 2 );
+                        }
+                    else
+                        {
+                        driveNameBuf8 = HBufC8::NewL( driveNameLength );
+                        driveNameBuf8->Des().Append( volInfo.iName );
+                        }
+                    HTI_LOG_FORMAT( "Drive name: %S", &volInfo.iName );
+                    driveListBuf->ExpandL( bufPos, driveNameBuf8->Length() );
+                    driveListBuf->Write( bufPos, driveNameBuf8->Ptr(),
+                        driveNameBuf8->Length() );
+                    bufPos += driveNameBuf8->Length();
+                    delete driveNameBuf8;
+                    driveNameBuf8 = NULL;
+                    }
+                }
+            }
+        }
+
+    // All drives added - write number of drives to the beginning of buffer
+    TBuf8<1> countBuf;
+    countBuf.Append( ( TUint8* ) ( &driveCount ), 1 );
+    driveListBuf->InsertL( 0, countBuf, 1 );
+
+    // Make a copy of the buffer to iSendBuffer
+    delete iSendBuffer;
+    iSendBuffer = NULL;
+    iSendBuffer = driveListBuf->Ptr( 0 ).AllocL();
+    CleanupStack::PopAndDestroy(); // driveListBuf
+
+    // ...and send it away
+    TInt err = iDispatcher->DispatchOutgoingMessage(
+        iSendBuffer, KFtpServiceUid, EFalse, EHtiPriorityControl );
+
+    if (  err != KErrNone )
+        {
+        //wait for memory
+        iState = EListBusy;
+        iDispatcher->AddMemoryObserver( this );
+        }
+    else
+        {
+        iSendBuffer = NULL; // ownership transferred
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiFtpServicePlugin::HandleListDrivesL" );
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiFtpServicePlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy for FTP service plugin dll
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+#include "HtiFtpServicePlugin.h"
+
+const TImplementationProxy ImplementationTable[] =
+    {
+        IMPLEMENTATION_PROXY_ENTRY(0x1020DEC5,  CHtiFtpServicePlugin::NewL)
+    };
+
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/CIPProxyEngine.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,190 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Main class for IPProxyEngine
+*
+*/
+
+
+
+#ifndef CIPPROXYENGINE_H
+#define CIPPROXYENGINE_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <es_sock.h>
+#include "MIPProxyEngine.h"
+#include "Mhostconnectionobserver.h"
+#include "MLocalTCPConnectionObserver.h"
+#include "MTCPPortListenerObserver.h"
+#include "MSocketRouterObserver.h"
+
+
+// FORWARD DECLARATIONS
+class MHostConnection;
+class CTCPPortListener;
+class CSocketRouter;
+class MIPProxyEngineObserver;
+class CLocalTCPConnection;
+class MHostConnection;
+class MAbstractConnection;
+
+// CLASS DECLARATION
+
+/**
+*  Main class for IPProxyEngine.
+*/
+NONSHARABLE_CLASS( CIPProxyEngine ) : public CActive,
+    public MIPProxyEngine,
+    public MTCPPortListenerObserver,
+    public MHostConnectionObserver,
+    public MLocalTCPConnectionObserver,
+    public MSocketRouterObserver
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aConnection pointer to host connection.
+        */
+        static CIPProxyEngine* NewL( MAbstractConnection* aConnection );
+
+        /**
+        * Factory function.
+        * @param aConnection pointer to host connection.
+        */
+        static CIPProxyEngine* NewLC( MAbstractConnection* aConnection );
+
+        /**
+        * Destructor.
+        */
+        ~CIPProxyEngine();
+
+
+    protected: // Functions from base classes
+
+        /**
+        * From CActive. Pending request has been completed.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Pending request has been cancelled.
+        */
+        void DoCancel();
+
+
+    public:     // Functions from base classes
+
+        /**
+        * From MIPProxyEngine.
+        * Set observer of IPProxyEngine.
+        * @param aObserver Pointer to observer.
+        */
+        void SetObserver( MIPProxyEngineObserver* aObserver );
+
+        /**
+        * From MIPProxyEngine.
+        * Add port to listen.
+        * @param aPort Port to listen.
+        */
+        void AddPeerListeningPortL( TInt aPort );
+
+        /**
+        * From MIPProxyEngine.
+        * Starts listening peers.
+        */
+        void StartListening();
+
+        /**
+        * From MIPProxyEngine.
+        * Stops listening peers.
+        */
+        void StopListening();
+
+        /**
+        * From MIPProxyEngine.
+        * Disconnects all peers and the host connection.
+        */
+        void DisconnectAllConnections();
+
+    protected:  // Functions from MTCPPortListenerObserver
+
+        void ConnectionAcceptedL( RSocket* aSocket );
+        void ErrorL( TInt aErrorCode );
+        void ObserverLeaved( TInt aLeaveCode );
+
+    protected:  // Functions from MHostConnectionObserver
+
+        void ConnectionEstablishedL();
+        void HostConnectionErrorL( TInt aErrorCode );
+        void HostConnectionObserverLeaved( TInt aLeaveCode );
+
+    protected:  // Functions from MLocalTCPConnectionObserver
+
+        void LocalTCPConnectionEstablishedL( TUint aPort );
+        void LocalTCPConnectionErrorL( TInt aPort, TInt aErrorCode );
+        void LocalTCPConnectionObserverLeaved( TInt aPort, TInt aLeaveCode );
+
+    protected:  // Functions from MSocketRouterObserver
+
+        void SocketRouterErrorL( const MSocket* aSocket, TInt aErrorCode );
+        void ObserverLeaved( const MSocket* aSocket, TInt aLeaveCode );
+        void PeerDisconnectedL( const MSocket* aSocket );
+        void HostDisconnectedL( const MSocket* aSocket );
+        void OpenLocalTCPConnectionL( TUint aPort );
+        void OpenListeningTCPConnectionL( TUint aPort );
+        void CloseTCPConnection( TUint aPort );
+        void CloseAllTCPConnections();
+        void AssureConnectionL();
+
+    protected:
+
+        /**
+        * Default constructor.
+        */
+        CIPProxyEngine( MAbstractConnection* aConnection );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private: // New functions
+
+        /**
+        * Helper function to find the correct connection from the local
+        * TCP connection -list.
+        * @param aPort The remote port of the connection to find
+        * @return index of the local conn in the iLocalConnArray
+        */
+        TInt FindLocalTCPConn( TUint aPort );
+
+    private:    // Owned data
+
+        RSocketServ iSocketServ;
+        CArrayPtr<CTCPPortListener>* iPeerListenerArray;
+        CArrayPtr<CLocalTCPConnection>* iLocalConnArray;
+        TBool iListening;
+        CSocketRouter* iSocketRouter;
+        RTimer iTimer;
+
+    private:    // Not owned data
+        MAbstractConnection* iAbstractConnection;
+        MHostConnection* iHostConnection;
+        MIPProxyEngineObserver* iObserver;
+    };
+
+#endif      // CIPPROXYENGINE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/CommRouterDefinitions.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Constant definitions for IPProxyEngine
+*
+*/
+
+
+
+#ifndef COMMROUTERDEFINITIONS_H
+#define COMMROUTERDEFINITIONS_H
+
+
+// Definitions for protocol frames
+_LIT8( KTCPPrefix, "TCP:" );
+_LIT8( KTCPOpenPrefix, "TCP_OPEN:" );
+_LIT8( KTCPLstnPrefix, "TCP_LSTN:" );
+_LIT8( KTCPClosePrefix, "TCP_CLOSE:" );
+_LIT8( KTCPCloseAllPrefix, "TCP_CLOSEALL:" );
+_LIT8( KUDPPrefix, "UDP:" );
+
+const TInt KMaxPrefixLength = 10;
+
+_LIT8( KPortSuffix, "," );
+_LIT8( KLengthSuffix, ",[" );
+_LIT8( KDataSuffix, "]" );
+_LIT8( KMessageSuffix, "" );
+
+_LIT8( KTCPPortPrefix, "[" );
+_LIT8( KTCPPortSuffix, "]" );
+
+const TInt KHexDecimalLength = 4;
+_LIT8( KHexFormat,"%04x" );
+
+#endif      // COMMROUTERDEFINITIONS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/IPProxyEnginefactory.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Factory class for IPProxyEngine
+*
+*/
+
+
+
+#ifndef IPPROXYENGINEFACTORY_H
+#define IPPROXYENGINEFACTORY_H
+
+// INCLUDE FILES
+#include <e32def.h>
+
+// FORWARD DECLARATIONS
+class MIPProxyEngine;
+class MAbstractConnection;
+
+// CLASS DECLARATION
+
+/**
+*  Factory class for IPProxyEngine.
+*/
+class IPProxyEngineFactory
+    {
+    public: // New functions
+
+        /**
+        * IPProxyEngine factory method.
+        * @param aConnection pointer to abstract connection
+        * @return Instance of an object that implements IPProxyEngine
+        * interface. Ownership transfers to the caller.
+        */
+        IMPORT_C static MIPProxyEngine* CreateProxyEngineL( MAbstractConnection* aConnection );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        IPProxyEngineFactory();
+    };
+
+#endif      // IPPROXYENGINEFACTORY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MAbstractConnection.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Host connection interface
+*
+*/
+
+
+
+#ifndef MABSTRACTCONNETION_H
+#define MABSTRACTCONNETION_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// FORWARD DECLARATIONS
+class MSocket;
+class MHostConnection;
+
+// CLASS DECLARATION
+
+/**
+*  Host connection interface
+*/
+NONSHARABLE_CLASS( MAbstractConnection )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Get pointer to current socket instance.
+        * @return Pointer to current RSocket object. The ownership always
+        *  remains in the class which derives from this interface.
+        */
+        virtual MSocket* GetSocket() = 0;
+
+        /**
+        * Get pointer to current host connection instance.
+        * @return Pointer to current RSocket object. The ownership always
+        *  remains in the class which derives from this interface.
+        */
+        virtual MHostConnection* GetHostConnection() = 0;
+    };
+
+#endif      // MABSTRACTCONNETION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MHostConnection.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,71 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Host connection interface
+*
+*/
+
+
+
+#ifndef MHOSTCONNECTION_H
+#define MHOSTCONNECTION_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// FORWARD DECLARATIONS
+class MHostConnectionObserver;
+class RSocket;
+
+// CLASS DECLARATION
+
+/**
+*  Host connection interface
+*/
+NONSHARABLE_CLASS( MHostConnection )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Starts connecting procedure to host.
+        */
+        virtual void IssueConnectL() = 0;
+
+        /**
+        * Starts disconnection procedure.
+        */
+        virtual void IssueDisconnect() = 0;
+
+        /**
+        * Sets observer.
+        * @param aObserver Pointer to observer.
+        */
+        virtual void SetObserver( MHostConnectionObserver* aObserver ) = 0;
+
+        /**
+        * @return Connection state.
+        */
+        virtual TBool IsConnected() = 0;
+
+        /**
+        * @return Pointer to current RSocket object. The ownership always
+        * remains in this class.
+        */
+        virtual RSocket* Socket() = 0;
+
+    };
+
+#endif      // MHOSTCONNECTION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MIPProxyEngine.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Main interface for IPProxyEngine
+*
+*/
+
+
+
+#ifndef IPPROXYENGINE_H
+#define IPPROXYENGINE_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// FORWARD DECLARATIONS
+class MIPProxyEngineObserver;
+
+// CLASS DECLARATION
+
+/**
+*  Main interface for IPProxyEngine.
+*/
+class MIPProxyEngine
+    {
+    public: // Abstract functions
+        /**
+        * Virtual destructor makes it possible to delete the object via this
+        * interface.
+        */
+        virtual ~MIPProxyEngine() {};
+
+        /**
+        * Set observer of IPProxyEngine.
+        * @param aObserver Pointer to observer.
+        */
+        virtual void SetObserver( MIPProxyEngineObserver* aObserver ) = 0;
+
+        /**
+        * Add port to listen.
+        * @param aPort Port to listen.
+        */
+        virtual void AddPeerListeningPortL( TInt aPort ) = 0;
+
+        /**
+        * Starts listening peers.
+        */
+        virtual void StartListening() = 0;
+
+        /**
+        * Stops listening peers.
+        */
+        virtual void StopListening() = 0;
+
+        /**
+        * Disconnects all peers and the host connection.
+        */
+        virtual void DisconnectAllConnections() = 0;
+    };
+
+#endif      // IPPROXYENGINE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MIPProxyEngineObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxyEngine events
+*
+*/
+
+
+
+#ifndef IPPROXYENGINEOBSERVER_H
+#define IPPROXYENGINEOBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <es_sock.h>
+
+
+// CLASS DECLARATION
+
+/**
+*  IPProxyEngine events.
+*/
+class MIPProxyEngineObserver
+    {
+
+    public: // Abstract functions
+        /**
+        * Notifies that error has occurred.
+        * @param aErrorCode Error code.
+        */
+        virtual void RouterErrorL( TInt aErrorCode ) = 0;
+
+        /**
+        * Notifies that the observer has leaved while executing the callback
+        * function.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void ObserverLeaved( TInt aLeaveCode ) = 0;
+    };
+
+#endif      // IPPROXYENGINEOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MLocalTCPConnectionObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Events for local TCP connections
+*
+*/
+
+
+
+#ifndef MLOCALTCPCONNECTIONOBSERVER_H
+#define MLOCALTCPCONNECTIONOBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// CLASS DECLARATION
+
+/**
+*  Events for host connection
+*/
+NONSHARABLE_CLASS( MLocalTCPConnectionObserver )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Connection to host established.
+        * @param aPort Port that was connected.
+        */
+        virtual void LocalTCPConnectionEstablishedL( TUint aPort ) = 0;
+
+
+        /**
+        * Error when connecting to host.
+        * @param aPort Port that reported error.
+        * @param aErrorCode Error code.
+        */
+        virtual void LocalTCPConnectionErrorL( TInt aPort, TInt aErrorCode ) = 0;
+
+
+        /**
+        * Observer leaved in RunL.
+        * @param aPort Port that caused the leave.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void LocalTCPConnectionObserverLeaved( TInt aPort, TInt aLeaveCode ) = 0;
+
+    };
+
+#endif      // MLOCALTCPCONNECTIONOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MSocket.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MSocket interface
+*
+*/
+
+
+
+#ifndef MSOCKET_H
+#define MSOCKET_H
+
+//  INCLUDES
+#include <es_sock.h>
+#include "MSocketWriter.h"
+
+// FORWARD DECLARATIONS
+class RSocket;
+class MSocketObserver;
+
+// CLASS DECLARATION
+
+/**
+*  MSocket interface.
+*/
+NONSHARABLE_CLASS( MSocket ) : public MSocketWriter
+    {
+    public:
+        virtual ~MSocket() {};
+
+    public: // Abstract functions
+
+        /**
+        * @return RSocket object
+        */
+        virtual RSocket* GetRSocket() = 0;
+
+        /**
+        * @return Local TCP port.
+        */
+        virtual TUint LocalPort() const = 0;
+
+        /**
+        * @return Remote TCP port.
+        */
+        virtual TUint RemotePort() const = 0;
+
+        /**
+        * Sets observer.
+        * @param aObserver Pointer to observer.
+        */
+        virtual void SetObserver( MSocketObserver* aObserver ) = 0;
+
+        /**
+        * Sets the ownership mode of RSocket object. If set ETrue
+        * the socket will be closed and RSocket object will be deleted
+        * in the destruction.
+        * @param aHasOwnership Ownership mode.
+        */
+        virtual void SetSocketOwnershipMode( TBool aHasOwnership ) = 0;
+
+        /**
+        * Starts receiving data.
+        */
+        virtual void IssueRead() = 0;
+
+        /**
+        * Cancels all pending requests.
+        */
+        virtual void Cancel() = 0;
+
+        /*
+        * Returns the protocol information of the socket
+        */
+        virtual void SocketInfo( TProtocolDesc& aDesc) const = 0;
+
+        /*
+        * Is this a UDP socket
+        */
+        virtual TBool IsUDP() const = 0;
+
+    public: // From MSocketWriter
+        /**
+        * Issues writing data to socket.
+        * @param aData Data to be written.
+        */
+        virtual void WriteL( const TDesC8& aData ) = 0;
+    };
+
+#endif      // MSOCKET_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MSocketObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Events for socket
+*
+*/
+
+
+
+#ifndef MSOCKETOBSERVER_H
+#define MSOCKETOBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <es_sock.h>
+
+
+// FORWARD DECLARATIONS
+class MSocket;
+class CSocket;
+
+// CLASS DECLARATION
+
+/**
+*  Events for socket.
+*/
+NONSHARABLE_CLASS( MSocketObserver )
+    {
+    // Abstract functions
+    public:
+        /**
+        * Data has been received.
+        * @param aSocket MSocket where the data received from.
+        * @param aData Received data.
+        */
+        virtual void DataReceivedL(
+            const MSocket* aSocket, const TDesC8& aData ) = 0;
+
+        /**
+        * Error occurred in socket.
+        * @param aSocket MSocket object that caused error.
+        * @param aErrorCode Error code.
+        */
+        virtual void ErrorL( const MSocket* aSocket, TInt aErrorCode ) = 0;
+
+        /**
+        * Socket disconnected.
+        * @param aSocket Socket that disconnected.
+        */
+        virtual void DisconnectedL( const MSocket* aSocket ) = 0;
+
+        /**
+        * Notifies that the observer has leaved while executing the callback
+        * function.
+        * @param aSocket Socket that caused the leave.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void ObserverLeaved(
+            const MSocket* aSocket, TInt aLeaveCode ) = 0;
+    };
+
+#endif      // MSOCKETOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MSocketRouterObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for socket router
+*
+*/
+
+
+
+#ifndef MSOCKETROUTEROBSERVER_H
+#define MSOCKETROUTEROBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+
+
+// FORWARD DECLARATIONS
+class MSocket;
+class CSocket;
+
+// CLASS DECLARATION
+
+/**
+*  Observer for socket router.
+*/
+NONSHARABLE_CLASS( MSocketRouterObserver )
+    {
+    public: // Abstract functions
+
+        /**
+        * Error occurred in socket.
+        * @param aSocket MSocket object that caused error.
+        * @param aErrorCode Error code.
+        */
+        virtual void SocketRouterErrorL(
+            const MSocket* aSocket, TInt aErrorCode ) = 0;
+
+        /**
+        * Observer leaved in RunL.
+        * @param aSocket CSocket object that caused leave.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void ObserverLeaved(
+            const MSocket* aSocket, TInt aLeaveCode ) = 0;
+
+        /**
+        * Peer disconnected.
+        * @param aSocket Socket that disconnected.
+        */
+        virtual void PeerDisconnectedL( const MSocket* aSocket ) = 0;
+
+        /**
+        * Host disconnected.
+        * @param aSocket Socket that disconnected.
+        */
+        virtual void HostDisconnectedL( const MSocket* aSocket ) = 0;
+
+        /**
+        * Open a TCP connection to phone side port
+        * @param aPort Port number where to connect
+        */
+        virtual void OpenLocalTCPConnectionL( TUint aPort ) = 0;
+
+        /**
+        * Open a listening TCP port on the phone side
+        * @param aPort Port number where to start listening
+        */
+        virtual void OpenListeningTCPConnectionL( TUint aPort ) = 0;
+
+        /**
+        * Close a TCP connection to phone side port
+        * @param aPort Port number to close
+        */
+        virtual void CloseTCPConnection( TUint aPort ) = 0;
+
+        /**
+        * Close all TCP connections from listening & connecting ports
+        */
+        virtual void CloseAllTCPConnections() = 0;
+    };
+
+#endif      // MSOCKETROUTEROBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MSocketWriter.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MSocketWriter interface
+*
+*/
+
+
+
+#ifndef MSOCKETWRITER_H
+#define MSOCKETWRITER_H
+
+//  INCLUDES
+#include <e32def.h>
+
+
+// CLASS DECLARATION
+
+/**
+*  MSocketWriter interface.
+*/
+NONSHARABLE_CLASS( MSocketWriter )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Writes data to socket.
+        * @param aData Data to be written.
+        */
+        virtual void WriteL( const TDesC8& aData ) = 0;
+
+    };
+
+#endif      // MSOCKETWRITER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/MTCPPortListenerObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Events for TCP port listener
+*
+*/
+
+
+
+#ifndef MTCPPORTLISTENEROBSERVER_H
+#define MTCPPORTLISTENEROBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <es_sock.h>
+
+
+// CLASS DECLARATION
+
+/**
+*  Events for TCP port listener.
+*/
+NONSHARABLE_CLASS( MTCPPortListenerObserver )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Notifies that TCP port listener has accepted an incoming
+        * TPC connection.
+        * @param aSocket RSocket object that has an opened subsession
+        * to Socket server. This means that the object who implements
+        * this event has the ownership and is responsible in closing the
+        * subsession too!
+        */
+        virtual void ConnectionAcceptedL( RSocket* aSocket ) = 0;
+
+        /**
+        * Notifies that error has occurred.
+        * @param aErrorCode Error code.
+        */
+        virtual void ErrorL( TInt aErrorCode ) = 0;
+
+        /**
+        * Notifies that the observer has leaved while executing the callback
+        * function.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void ObserverLeaved( TInt aLeaveCode ) = 0;
+    };
+
+#endif      // MTCPPORTLISTENEROBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Inc/Mhostconnectionobserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Events for host connection
+*
+*/
+
+
+
+#ifndef MHOSTCONNECTIONOBSERVER_H
+#define MHOSTCONNECTIONOBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// CLASS DECLARATION
+
+/**
+*  Events for host connection
+*/
+NONSHARABLE_CLASS( MHostConnectionObserver )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Connection to host established.
+        */
+        virtual void ConnectionEstablishedL() = 0;
+
+        /**
+        * Error when connecting to host.
+        * @param aErrorCode Error code.
+        */
+        virtual void HostConnectionErrorL( TInt aErrorCode ) = 0;
+
+        /**
+        * Observer leaved in RunL.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void HostConnectionObserverLeaved( TInt aLeaveCode ) = 0;
+
+    };
+
+#endif      // MHOSTCONNECTIONOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPClose.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,145 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxy TCP protocol expression for closing phone side TCP
+*                connection.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CExprTCPClose.h"
+#include "CommRouterDefinitions.h"
+#include "MExpressionObserverTCP.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CExprTCPClose::CExprTCPClose
+// -----------------------------------------------------------------------------
+//
+CExprTCPClose::CExprTCPClose( MExpressionObserverTCP* aObserver )
+    : iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPClose::NewL
+// -----------------------------------------------------------------------------
+//
+CExprTCPClose* CExprTCPClose::NewL( MExpressionObserverTCP* aObserver )
+    {
+    CExprTCPClose* self = CExprTCPClose::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPClose::NewLC
+// -----------------------------------------------------------------------------
+//
+CExprTCPClose* CExprTCPClose::NewLC( MExpressionObserverTCP* aObserver )
+    {
+    CExprTCPClose* self = new( ELeave ) CExprTCPClose( aObserver );
+    CleanupStack::PushL( self );
+
+    return self;
+    }
+
+
+// Destructor
+CExprTCPClose::~CExprTCPClose()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CExprTCPClose::HandleReceivedDataL()
+// -----------------------------------------------------------------------------
+//
+TBool CExprTCPClose::HandleRecievedMsgL( TDes8& aData, TInt& aStartPos,
+                                         TInt& aLength  )
+    {
+    // Check if the prefix matches
+    aStartPos = aData.Find( KTCPClosePrefix );
+
+    if ( aStartPos != KErrNotFound  )
+        {
+        // Found a matching prefix
+        // Let the observer know
+        iObserver->FrameStarted();
+
+        TPtr8 dataToParse( aData.MidTPtr( aStartPos ) );
+
+        TInt err = TryParsingL( dataToParse, aLength );
+
+        if ( err != KErrNone )
+            {
+            // corrupted data in the frame
+            iObserver->ProtocolErrorL( err, aData );
+            // delete the corrupted data
+            aData.SetLength( 0 );
+            }
+
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPClose::TryParsing
+// -----------------------------------------------------------------------------
+//
+TInt CExprTCPClose::TryParsingL( TDes8& aData, TInt& aLength )
+    {
+    __ASSERT_ALWAYS( aData.Left( KTCPClosePrefix().Length() ) == KTCPClosePrefix,
+        User::Panic( _L("Protocol"), 1 ) );
+
+    // TCP_CLOSE:0fff
+    TInt frameOverhead =
+        KTCPClosePrefix().Length() +
+        KHexDecimalLength;
+
+    if ( aData.Length() >= frameOverhead )
+        {
+        TPtrC8 portPtr(
+            aData.Mid( KTCPClosePrefix().Length(), KHexDecimalLength ) );
+
+        TLex8 portLexer( portPtr );
+        TUint port;
+        if ( portLexer.Val( port, EHex ) != KErrNone )
+            {
+            return KErrCorrupt;
+            }
+
+        // send parsed results
+        iObserver->CloseTCPConnectionL( port );
+
+        aLength = frameOverhead;
+
+        return KErrNone;
+        }
+    return KErrNone;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPClose.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,88 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxy TCP protocol expression for closing phone side TCP
+*                connection.
+*
+*/
+
+
+
+#ifndef CBPEXPRTCPCLOSE_H
+#define CBPEXPRTCPCLOSE_H
+
+//  INCLUDES
+#include <e32base.h>
+
+#include "MBPExpression.h"
+
+// CONSTANTS
+
+
+// FORWARD DECLARATIONS
+
+class MExpressionObserverTCP;
+
+// CLASS DECLARATION
+
+/**
+*  TCP protocol expression for closing a new TCP connection from PC-side
+*  to phone side port
+*/
+NONSHARABLE_CLASS( CExprTCPClose ) : public CBase, public MBPExpression
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPClose* NewL( MExpressionObserverTCP* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPClose* NewLC( MExpressionObserverTCP* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CExprTCPClose();
+
+    public: // from MBPExpression
+
+        TBool HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength );
+
+    public: // new functions
+
+        TInt TryParsingL( TDes8& aData, TInt& aLength );
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CExprTCPClose( MExpressionObserverTCP* aObserver );
+
+    private:    // Data
+
+        MExpressionObserverTCP* iObserver;
+    };
+
+#endif      // CBPEXPRTCPCLOSE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPCloseAll.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IP-Proxy TCP protocol expression for closing all phone side
+*                sockets.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CExprTCPCloseAll.h"
+#include "CommRouterDefinitions.h"
+#include "MExpressionObserverTCP.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CExprTCPCloseAll::CExprTCPCloseAll
+// -----------------------------------------------------------------------------
+//
+CExprTCPCloseAll::CExprTCPCloseAll( MExpressionObserverTCP* aObserver )
+    : iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPCloseAll::NewL
+// -----------------------------------------------------------------------------
+//
+CExprTCPCloseAll* CExprTCPCloseAll::NewL( MExpressionObserverTCP* aObserver )
+    {
+    CExprTCPCloseAll* self = CExprTCPCloseAll::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPCloseAll::NewLC
+// -----------------------------------------------------------------------------
+//
+CExprTCPCloseAll* CExprTCPCloseAll::NewLC( MExpressionObserverTCP* aObserver )
+    {
+    CExprTCPCloseAll* self = new( ELeave ) CExprTCPCloseAll( aObserver );
+    CleanupStack::PushL( self );
+
+    return self;
+    }
+
+
+// Destructor
+CExprTCPCloseAll::~CExprTCPCloseAll()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CExprTCPCloseAll::HandleReceivedDataL()
+// -----------------------------------------------------------------------------
+//
+TBool CExprTCPCloseAll::HandleRecievedMsgL( TDes8& aData, TInt& aStartPos,
+                                         TInt& aLength  )
+    {
+    // Check if the prefix matches
+    aStartPos = aData.Find( KTCPCloseAllPrefix );
+
+    if ( aStartPos != KErrNotFound  )
+        {
+        // Found a matching prefix
+        // Let the observer know
+        iObserver->FrameStarted();
+
+        TPtr8 dataToParse( aData.MidTPtr( aStartPos ) );
+
+        TInt err = TryParsing( dataToParse, aLength );
+
+        if ( err != KErrNone )
+            {
+            // corrupted data in the frame
+            iObserver->ProtocolErrorL( err, aData );
+            // delete the corrupted data
+            aData.SetLength( 0 );
+            }
+
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPOpen::TryParsing
+// -----------------------------------------------------------------------------
+//
+TInt CExprTCPCloseAll::TryParsing( TDes8& aData, TInt& aLength )
+    {
+    __ASSERT_ALWAYS( aData.Left( KTCPCloseAllPrefix().Length() ) == KTCPCloseAllPrefix,
+        User::Panic( _L("Protocol"), 1 ) );
+
+    // TCP_CLOSEALL:
+    TInt frameOverhead = KTCPCloseAllPrefix().Length();
+
+    if ( aData.Length() >= frameOverhead )
+        {
+        // send parsed results
+        iObserver->CloseAllTCPConnections();
+
+        aLength = frameOverhead;
+        }
+    return KErrNone;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPCloseAll.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,87 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IP-Proxy TCP protocol expression for closing all phone side
+*                sockets.
+*
+*/
+
+
+
+#ifndef CBPEXPRTCPCLOSEALL_H
+#define CBPEXPRTCPCLOSEALL_H
+
+//  INCLUDES
+#include <e32base.h>
+
+#include "MBPExpression.h"
+
+// CONSTANTS
+
+
+// FORWARD DECLARATIONS
+
+class MExpressionObserverTCP;
+
+// CLASS DECLARATION
+
+/**
+*  TCP protocol expression for closing all socket ports
+*/
+NONSHARABLE_CLASS( CExprTCPCloseAll ) : public CBase, public MBPExpression
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPCloseAll* NewL( MExpressionObserverTCP* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPCloseAll* NewLC( MExpressionObserverTCP* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CExprTCPCloseAll();
+
+    public: // from MBPExpression
+
+        TBool HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength );
+
+    public: // new functions
+
+        TInt TryParsing( TDes8& aData, TInt& aLength );
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CExprTCPCloseAll( MExpressionObserverTCP* aObserver );
+
+    private:    // Data
+
+        MExpressionObserverTCP* iObserver;
+    };
+
+#endif      // CBPEXPRTCPCLOSEALL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPLstn.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,142 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IP-Proxy TCP protocol expression for opening listening phone
+*                side TCP socket.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CExprTCPLstn.h"
+#include "CommRouterDefinitions.h"
+#include "MExpressionObserverTCP.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CExprTCPLstn::CExprTCPLstn
+// -----------------------------------------------------------------------------
+//
+CExprTCPLstn::CExprTCPLstn( MExpressionObserverTCP* aObserver )
+    : iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPLstn::NewL
+// -----------------------------------------------------------------------------
+//
+CExprTCPLstn* CExprTCPLstn::NewL( MExpressionObserverTCP* aObserver )
+    {
+    CExprTCPLstn* self = CExprTCPLstn::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPLstn::NewLC
+// -----------------------------------------------------------------------------
+//
+CExprTCPLstn* CExprTCPLstn::NewLC( MExpressionObserverTCP* aObserver )
+    {
+    CExprTCPLstn* self = new( ELeave ) CExprTCPLstn( aObserver );
+    CleanupStack::PushL( self );
+
+    return self;
+    }
+
+// Destructor
+CExprTCPLstn::~CExprTCPLstn()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPLstn::HandleReceivedDataL()
+// -----------------------------------------------------------------------------
+//
+TBool CExprTCPLstn::HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength )
+    {
+    // Check if the prefix matches
+    aStartPos = aData.Find( KTCPLstnPrefix );
+
+    if ( aStartPos != KErrNotFound  )
+        {
+        // Found a matching prefix
+        // Let the observer know
+        iObserver->FrameStarted();
+
+        TPtr8 dataToParse( aData.MidTPtr( aStartPos ) );
+
+        TInt err = TryParsingL( dataToParse, aLength );
+
+        if ( err != KErrNone )
+            {
+            // corrupted data in the frame
+            iObserver->ProtocolErrorL( err, aData );
+            // delete the corrupted data
+            aData.SetLength( 0 );
+            }
+
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPLstn::TryParsingL
+// -----------------------------------------------------------------------------
+//
+TInt CExprTCPLstn::TryParsingL( TDes8& aData, TInt& aLength )
+    {
+    __ASSERT_ALWAYS( aData.Left( KTCPLstnPrefix().Length() ) == KTCPLstnPrefix,
+        User::Panic( _L("Protocol"), 1 ) );
+
+    // TCP_LSTN:0123
+    TInt frameOverhead =
+        KTCPLstnPrefix().Length() +
+        KHexDecimalLength;
+
+    if ( aData.Length() >= frameOverhead )
+        {
+        TPtrC8 portPtr(
+            aData.Mid( KTCPLstnPrefix().Length(), KHexDecimalLength ) );
+
+        TLex8 portLexer( portPtr );
+        TUint port;
+        if ( portLexer.Val( port, EHex ) != KErrNone )
+            {
+            return KErrCorrupt;
+            }
+
+        // send parsed results
+        iObserver->OpenListeningTCPConnectionL( port );
+
+        aLength = frameOverhead;
+
+        return KErrNone;
+        }
+    return KErrNone;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPLstn.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,88 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IP-Proxy TCP protocol expression for opening listening phone
+*                side TCP socket.
+*
+*/
+
+
+
+#ifndef CBPEXPRTCPLSTN_H
+#define CBPEXPRTCPLSTN_H
+
+//  INCLUDES
+#include <e32base.h>
+
+#include "MBPExpression.h"
+
+// CONSTANTS
+
+
+// FORWARD DECLARATIONS
+
+class MExpressionObserverTCP;
+
+// CLASS DECLARATION
+
+/**
+*  TCP protocol expression for opening a new listening TCP port from PC-side
+*  to phone
+*/
+NONSHARABLE_CLASS( CExprTCPLstn ) : public CBase, public MBPExpression
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPLstn* NewL( MExpressionObserverTCP* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPLstn* NewLC( MExpressionObserverTCP* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CExprTCPLstn();
+
+    public: // from MBPExpression
+
+        TBool HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength );
+
+    public: // new functions
+
+        TInt TryParsingL( TDes8& aData, TInt& aLength );
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CExprTCPLstn( MExpressionObserverTCP* aObserver );
+
+    private:    // Data
+
+        MExpressionObserverTCP* iObserver;
+    };
+
+#endif      // CBPEXPRTCPLSTN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPMsg.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,203 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxy TCP protocol expression for a regular TCP message
+*                connection.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CExprTCPMsg.h"
+#include "CommRouterDefinitions.h"
+#include "MProtocolObserverTCP.h"
+#include "MExpressionObserver.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CExprTCPMsg::CExprTCPMsg
+// -----------------------------------------------------------------------------
+//
+CExprTCPMsg::CExprTCPMsg( MExpressionObserver* aObserver )
+    : iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPMsg::NewL
+// -----------------------------------------------------------------------------
+//
+CExprTCPMsg* CExprTCPMsg::NewL( MExpressionObserver* aObserver )
+    {
+    CExprTCPMsg* self = CExprTCPMsg::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPMsg::NewLC
+// -----------------------------------------------------------------------------
+//
+CExprTCPMsg* CExprTCPMsg::NewLC( MExpressionObserver* aObserver )
+    {
+    CExprTCPMsg* self = new( ELeave ) CExprTCPMsg( aObserver );
+    CleanupStack::PushL( self );
+
+    return self;
+    }
+
+
+// Destructor
+CExprTCPMsg::~CExprTCPMsg()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CExprTCPMsg::HandleReceivedDataL()
+// -----------------------------------------------------------------------------
+//
+TBool CExprTCPMsg::HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength )
+    {
+    // Check if the prefix matches
+    aStartPos = aData.Find( KTCPPrefix );
+
+    if ( aStartPos != KErrNotFound  )
+        {
+        // Found a matching prefix
+        // Let the observer know
+        iObserver->FrameStarted();
+
+        TPtr8 dataToParse( aData.MidTPtr( aStartPos ) );
+
+        TInt err = TryParsingL( dataToParse, aLength );
+
+        if ( err != KErrNone )
+            {
+            // corrupted data in the frame
+            iObserver->ProtocolErrorL( err, aData );
+            // delete the corrupted data
+            aData.SetLength( 0 );
+            }
+
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPMsg::TryParsingL
+// -----------------------------------------------------------------------------
+//
+TInt CExprTCPMsg::TryParsingL( TDes8& aData, TInt& aLength )
+    {
+    __ASSERT_ALWAYS( aData.Left( KTCPPrefix().Length() ) == KTCPPrefix,
+        User::Panic( _L("Protocol"), 1 ) );
+
+    // TCP:0123,000e,[Some test data]
+    TInt frameOverhead =
+        KTCPPrefix().Length() +
+        KHexDecimalLength +
+        KPortSuffix().Length() +
+        KHexDecimalLength +
+        KLengthSuffix().Length() +
+        KDataSuffix().Length() +
+        KMessageSuffix().Length();
+
+    if ( aData.Length() >= frameOverhead )
+        {
+        TPtrC8 portPtr(
+            aData.Mid( KTCPPrefix().Length(), KHexDecimalLength ) );
+
+        TLex8 portLexer( portPtr );
+        TUint port;
+        if ( portLexer.Val( port, EHex ) != KErrNone )
+            {
+            return KErrCorrupt;
+            }
+        DEBUG_PRINT( DEBUG_STRING( "CExprTCPMsg::TryParsingL, port = %d" ), port );
+
+        //Check port suffix
+        if ( aData.Mid( KTCPPrefix().Length() +
+            KHexDecimalLength, KPortSuffix().Length() ) != KPortSuffix )
+            {
+            return KErrCorrupt;
+            }
+
+        TPtrC8 lengthPtr( aData.Mid( KTCPPrefix().Length() +
+            KHexDecimalLength + KPortSuffix().Length(), KHexDecimalLength ) );
+        TLex8 lengthLexer( lengthPtr );
+        TUint length;
+        if ( lengthLexer.Val( length, EHex ) != KErrNone )
+            {
+            return KErrCorrupt;
+            }
+        DEBUG_PRINT( DEBUG_STRING( "CExprTCPMsg::TryParsingL, length = %d" ), length );
+
+        //Check length suffix
+        if ( aData.Mid(
+            KTCPPrefix().Length() +
+            KHexDecimalLength +
+            KPortSuffix().Length() +
+            KHexDecimalLength, KLengthSuffix().Length() ) != KLengthSuffix )
+            {
+            return KErrCorrupt;
+            }
+
+        if ( aData.Length() >= TInt( frameOverhead + length ) )
+            {
+            TInt messagePos = KTCPPrefix().Length() +
+                KHexDecimalLength +
+                KPortSuffix().Length() +
+                KHexDecimalLength +
+                KLengthSuffix().Length();
+
+            TPtrC8 message( aData.Mid( messagePos, length ) );
+            if ( aData.Mid( messagePos + length,
+                KDataSuffix().Length() ) != KDataSuffix )
+                {
+                return KErrCorrupt;
+                }
+            DEBUG_PRINT( DEBUG_STRING( "CExprTCPMsg::TryParsingL, message OK" ) );
+
+            if ( aData.Mid( messagePos + length + KDataSuffix().Length(),
+                KMessageSuffix().Length() ) != KMessageSuffix )
+                {
+                return KErrCorrupt;
+                }
+
+            // send parsed results
+            iObserver->FrameParsedL( port, message );
+            // set the length of the handled message
+            aLength = frameOverhead + length;
+
+            return KErrNone;
+            }
+
+        }
+    return KErrNone;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPMsg.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,88 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxy TCP protocol expression for a regular TCP message
+*                connection.
+*
+*/
+
+
+
+#ifndef CBPEXPRTCPMSG_H
+#define CBPEXPRTCPMSG_H
+
+//  INCLUDES
+#include <e32base.h>
+
+#include "MBPExpression.h"
+
+// CONSTANTS
+
+
+// FORWARD DECLARATIONS
+
+class MExpressionObserver;
+
+// CLASS DECLARATION
+
+/**
+*  TCP protocol expression for a regular TCP message
+*  to phone side port
+*/
+NONSHARABLE_CLASS( CExprTCPMsg ) : public CBase, public MBPExpression
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPMsg* NewL( MExpressionObserver* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPMsg* NewLC( MExpressionObserver* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CExprTCPMsg();
+
+    public: // from MBPExpression
+
+        TBool HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength );
+
+    public: // new functions
+
+        TInt TryParsingL( TDes8& aData, TInt& aLength );
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CExprTCPMsg( MExpressionObserver* aObserver );
+
+    private:    // Data
+
+        MExpressionObserver* iObserver;
+    };
+
+#endif      // CBPEXPRTCPMSG_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPOpen.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxy TCP protocol expression for opening phone side TCP
+*                connection.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CExprTCPOpen.h"
+#include "CommRouterDefinitions.h"
+#include "MExpressionObserverTCP.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CExprTCPOpen::CExprTCPOpen
+// -----------------------------------------------------------------------------
+//
+CExprTCPOpen::CExprTCPOpen( MExpressionObserverTCP* aObserver )
+    : iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPOpen::NewL
+// -----------------------------------------------------------------------------
+//
+CExprTCPOpen* CExprTCPOpen::NewL( MExpressionObserverTCP* aObserver )
+    {
+    CExprTCPOpen* self = CExprTCPOpen::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPOpen::NewLC
+// -----------------------------------------------------------------------------
+//
+CExprTCPOpen* CExprTCPOpen::NewLC( MExpressionObserverTCP* aObserver )
+    {
+    CExprTCPOpen* self = new( ELeave ) CExprTCPOpen( aObserver );
+    CleanupStack::PushL( self );
+
+    return self;
+    }
+
+
+// Destructor
+CExprTCPOpen::~CExprTCPOpen()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CExprTCPOpen::HandleReceivedDataL()
+// -----------------------------------------------------------------------------
+//
+TBool CExprTCPOpen::HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength )
+    {
+    // Check if the prefix matches
+    aStartPos = aData.Find( KTCPOpenPrefix );
+
+    if ( aStartPos != KErrNotFound  )
+        {
+        // Found a matching prefix
+        // Let the observer know
+        iObserver->FrameStarted();
+
+        TPtr8 dataToParse( aData.MidTPtr( aStartPos ) );
+
+        TInt err = TryParsingL( dataToParse, aLength );
+
+        if ( err != KErrNone )
+            {
+            // corrupted data in the frame
+            iObserver->ProtocolErrorL( err, aData );
+            // delete the corrupted data
+            aData.SetLength( 0 );
+            }
+
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CExprTCPOpen::TryParsingL
+// -----------------------------------------------------------------------------
+//
+TInt CExprTCPOpen::TryParsingL( TDes8& aData, TInt& aLength )
+    {
+    __ASSERT_ALWAYS( aData.Left( KTCPOpenPrefix().Length() ) == KTCPOpenPrefix,
+        User::Panic( _L("Protocol"), 1 ) );
+
+    // TCP_OPEN:0123
+    TInt frameOverhead =
+        KTCPOpenPrefix().Length() +
+        KHexDecimalLength;
+
+    if ( aData.Length() >= frameOverhead )
+        {
+        TPtrC8 portPtr(
+            aData.Mid( KTCPOpenPrefix().Length(), KHexDecimalLength ) );
+
+        TLex8 portLexer( portPtr );
+        TUint port;
+        if ( portLexer.Val( port, EHex ) != KErrNone )
+            {
+            return KErrCorrupt;
+            }
+
+        // send parsed results
+        iObserver->OpenLocalTCPConnectionL( port );
+
+        aLength = frameOverhead;
+
+        return KErrNone;
+        }
+    return KErrNone;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprTCPOpen.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,88 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxy TCP protocol expression for opening phone side TCP
+*                connection.
+*
+*/
+
+
+
+#ifndef CBPEXPRTCPOPEN_H
+#define CBPEXPRTCPOPEN_H
+
+//  INCLUDES
+#include <e32base.h>
+
+#include "MBPExpression.h"
+
+// CONSTANTS
+
+
+// FORWARD DECLARATIONS
+
+class MExpressionObserverTCP;
+
+// CLASS DECLARATION
+
+/**
+*  TCP protocol expression for opening a new TCP connection from PC-side
+*  to phone side port
+*/
+NONSHARABLE_CLASS( CExprTCPOpen ) : public CBase, public MBPExpression
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPOpen* NewL( MExpressionObserverTCP* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprTCPOpen* NewLC( MExpressionObserverTCP* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CExprTCPOpen();
+
+    public: // from MBPExpression
+
+        TBool HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength );
+
+    public: // new functions
+
+        TInt TryParsingL( TDes8& aData, TInt& aLength );
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CExprTCPOpen( MExpressionObserverTCP* aObserver );
+
+    private:    // Data
+
+        MExpressionObserverTCP* iObserver;
+    };
+
+#endif      // CBPEXPRTCPOPEN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprUDPMsg.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,204 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxy UDP protocol expression for a regular UDP message
+*                connection.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CExprUDPMsg.h"
+#include "CommRouterDefinitions.h"
+#include "MExpressionObserver.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CExprUDPMsg::CExprUDPMsg
+// -----------------------------------------------------------------------------
+//
+CExprUDPMsg::CExprUDPMsg( MExpressionObserver* aObserver )
+    : iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CExprUDPMsg::NewL
+// -----------------------------------------------------------------------------
+//
+CExprUDPMsg* CExprUDPMsg::NewL( MExpressionObserver* aObserver )
+    {
+    CExprUDPMsg* self = CExprUDPMsg::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CExprUDPMsg::NewLC
+// -----------------------------------------------------------------------------
+//
+CExprUDPMsg* CExprUDPMsg::NewLC( MExpressionObserver* aObserver )
+    {
+    CExprUDPMsg* self = new( ELeave ) CExprUDPMsg( aObserver );
+    CleanupStack::PushL( self );
+
+    return self;
+    }
+
+
+// Destructor
+CExprUDPMsg::~CExprUDPMsg()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CExprUDPMsg::HandleReceivedDataL()
+// -----------------------------------------------------------------------------
+//
+TBool CExprUDPMsg::HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength )
+    {
+    // Check if the prefix matches
+    aStartPos = aData.Find( KUDPPrefix );
+
+    if ( aStartPos != KErrNotFound  )
+        {
+        // Found a matching prefix
+        // Let the observer know
+        iObserver->FrameStarted();
+
+        TPtr8 dataToParse( aData.MidTPtr( aStartPos ) );
+
+        TInt err = TryParsingL( dataToParse, aLength );
+
+        if ( err != KErrNone )
+            {
+            // corrupted data in the frame
+            iObserver->ProtocolErrorL( err, aData );
+            // delete the corrupted data
+            aData.SetLength( 0 );
+            }
+
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+
+    }
+
+// -----------------------------------------------------------------------------
+// CExprUDPMsg::TryParsingL
+// -----------------------------------------------------------------------------
+//
+TInt CExprUDPMsg::TryParsingL( TDes8& aData, TInt& aLength )
+    {
+    __ASSERT_ALWAYS( aData.Left( KUDPPrefix().Length() ) == KUDPPrefix,
+        User::Panic( _L("Protocol"), 1 ) );
+
+    // UDP:0123,000e,[Some test data]
+    TInt frameOverhead =
+        KUDPPrefix().Length() +
+        KHexDecimalLength +
+        KPortSuffix().Length() +
+        KHexDecimalLength +
+        KLengthSuffix().Length() +
+        KDataSuffix().Length() +
+        KMessageSuffix().Length();
+
+    if ( aData.Length() >= frameOverhead )
+        {
+        TPtrC8 portPtr(
+            aData.Mid( KUDPPrefix().Length(), KHexDecimalLength ) );
+
+        TLex8 portLexer( portPtr );
+        TUint port;
+        if ( portLexer.Val( port, EHex ) != KErrNone )
+            {
+            return KErrCorrupt;
+            }
+        DEBUG_PRINT( DEBUG_STRING( "CExprUDPMsg::TryParsingL, port = %d" ), port );
+
+        //Check port suffix
+        if ( aData.Mid( KUDPPrefix().Length() +
+            KHexDecimalLength, KPortSuffix().Length() ) != KPortSuffix )
+            {
+            return KErrCorrupt;
+            }
+
+        TPtrC8 lengthPtr( aData.Mid( KUDPPrefix().Length() +
+            KHexDecimalLength + KPortSuffix().Length(), KHexDecimalLength ) );
+        TLex8 lengthLexer( lengthPtr );
+        TUint length;
+        if ( lengthLexer.Val( length, EHex ) != KErrNone )
+            {
+            return KErrCorrupt;
+            }
+        DEBUG_PRINT( DEBUG_STRING( "CExprUDPMsg::TryParsingL, length = %d" ), length );
+
+        //Check length suffix
+        if ( aData.Mid(
+            KUDPPrefix().Length() +
+            KHexDecimalLength +
+            KPortSuffix().Length() +
+            KHexDecimalLength, KLengthSuffix().Length() ) != KLengthSuffix )
+            {
+            return KErrCorrupt;
+            }
+
+        DEBUG_PRINT( DEBUG_STRING( "CExprUDPMsg::TryParsingL, parsing data" ), length );
+
+        if ( aData.Length() >= TInt( frameOverhead + length ) )
+            {
+            TInt messagePos = KUDPPrefix().Length() +
+                KHexDecimalLength +
+                KPortSuffix().Length() +
+                KHexDecimalLength +
+                KLengthSuffix().Length();
+
+            TPtrC8 message( aData.Mid( messagePos, length ) );
+            if ( aData.Mid( messagePos + length,
+                KDataSuffix().Length() ) != KDataSuffix )
+                {
+                return KErrCorrupt;
+                }
+            DEBUG_PRINT( DEBUG_STRING( "CExprUDPMsg::TryParsingL, message OK" ) );
+
+            if ( aData.Mid( messagePos + length + KDataSuffix().Length(),
+                KMessageSuffix().Length() ) != KMessageSuffix )
+                {
+                return KErrCorrupt;
+                }
+
+            // send parsed results
+            iObserver->FrameParsedL( port, message );
+            // set the length of the handled message
+            aLength = frameOverhead + length;
+
+            return KErrNone;
+            }
+
+        }
+    return KErrNone;
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CExprUDPMsg.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,88 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxy UDP protocol expression for a regular UDP message
+*                connection.
+*
+*/
+
+
+
+#ifndef CBPEXPRUDPMSG_H
+#define CBPEXPRUDPMSG_H
+
+//  INCLUDES
+#include <e32base.h>
+
+#include "MBPExpression.h"
+
+// CONSTANTS
+
+
+// FORWARD DECLARATIONS
+
+class MExpressionObserver;
+
+// CLASS DECLARATION
+
+/**
+*  UDP protocol expression for a regular UDP message
+*  to phone side port
+*/
+NONSHARABLE_CLASS( CExprUDPMsg ) : public CBase, public MBPExpression
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprUDPMsg* NewL( MExpressionObserver* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CBPExpression instance.
+        */
+        static CExprUDPMsg* NewLC( MExpressionObserver* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CExprUDPMsg();
+
+    public: // from MBPExpression
+
+        TBool HandleRecievedMsgL( TDes8& aData, TInt& aStartPos, TInt& aLength );
+
+    public: // new functions
+
+        TInt TryParsingL( TDes8& aData, TInt& aLength );
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CExprUDPMsg( MExpressionObserver* aObserver );
+
+    private:    // Data
+
+        MExpressionObserver* iObserver;
+    };
+
+#endif      // CBPEXPRUDPMSG_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CIPProxyEngine.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,629 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of the main class for IPProxyEngine
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CIPProxyEngine.h"
+#include "Ctcpportlistener.h"
+#include "CLocalTCPConnection.h"
+#include "Csocketrouter.h"
+#include "MIPProxyEngineObserver.h"
+#include "MHostConnection.h"
+#include "MAbstractConnection.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+const TInt KPeerDisconnectDelay = 60000000;  //60 seconds
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CleanupSocket RSocket pointer cleanup operation
+// -----------------------------------------------------------------------------
+//
+LOCAL_C void CleanupSocket( TAny* aPtr )
+    {
+    RSocket* socket = ( RSocket* ) aPtr;
+    if ( socket )
+        {
+        socket->Close();
+        delete socket;
+        }
+    }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::CIPProxyEngine
+// -----------------------------------------------------------------------------
+//
+CIPProxyEngine::CIPProxyEngine( MAbstractConnection* aConnection )
+    : CActive( EPriorityStandard ), iAbstractConnection( aConnection )
+    {
+    __ASSERT_DEBUG( iAbstractConnection, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::ConstructL()
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::ConstructL()" ) );
+
+    User::LeaveIfError( iTimer.CreateLocal() );
+    User::LeaveIfError( iSocketServ.Connect() );
+
+    iHostConnection = iAbstractConnection->GetHostConnection();
+    __ASSERT_DEBUG( iHostConnection, User::Invariant() );
+    iHostConnection->SetObserver( this );
+
+    // Peer array. Granularity 10 suits fine.
+    iPeerListenerArray = new (ELeave) CArrayPtrFlat<CTCPPortListener> ( 10 );
+
+    // Local TCP connections array
+    iLocalConnArray = new (ELeave) CArrayPtrFlat<CLocalTCPConnection> ( 5 );
+
+    iSocketRouter = CSocketRouter::NewL( this );
+
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::NewL
+// -----------------------------------------------------------------------------
+//
+CIPProxyEngine* CIPProxyEngine::NewL( MAbstractConnection* aConnection )
+    {
+    CIPProxyEngine* self = CIPProxyEngine::NewLC( aConnection );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::NewLC
+// -----------------------------------------------------------------------------
+//
+CIPProxyEngine* CIPProxyEngine::NewLC( MAbstractConnection* aConnection )
+    {
+    CIPProxyEngine* self = new( ELeave ) CIPProxyEngine( aConnection );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// Destructor
+CIPProxyEngine::~CIPProxyEngine()
+    {
+    Cancel();
+    iTimer.Close();
+    delete iSocketRouter;
+
+    if ( iPeerListenerArray )
+        {
+        iPeerListenerArray->ResetAndDestroy();
+        delete iPeerListenerArray;
+        }
+    if ( iLocalConnArray )
+        {
+        iLocalConnArray->ResetAndDestroy();
+        delete iLocalConnArray;
+        }
+
+    iSocketServ.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::RunL
+// This is called when the timer expires
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::RunL()
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CIPProxyEngine::RunL()" ) );
+    DEBUG_PRINT( DEBUG_STRING( "    peer count = %d" ),
+        iSocketRouter->SocketCount() );
+
+    if ( iSocketRouter->SocketCount() == 0 )
+        {
+        iHostConnection->IssueDisconnect();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::DoCancel()
+    {
+    iTimer.Cancel();
+    DEBUG_PRINT( DEBUG_STRING( "Timeout timer cancelled" ) );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::SetObserver
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::SetObserver( MIPProxyEngineObserver* aObserver )
+    {
+    iObserver = aObserver;
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::AddPeerListeningPortL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::AddPeerListeningPortL( TInt aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::AddPeerListeningPortL(%d)" ), aPort );
+
+    CTCPPortListener* newListener = CTCPPortListener::NewLC( aPort, this );
+    iPeerListenerArray->AppendL( newListener );
+    if ( iListening )
+        {
+        newListener->IssueListen();
+        }
+    CleanupStack::Pop( newListener );
+
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::AddPeerListeningPortL, Adding also UDP listener(%d)" ),
+         aPort );
+
+    // Adding also UDP listener for the port
+    iSocketRouter->AddUDPSocketL( aPort );
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::StartListening
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::StartListening()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::StartListening()" ) );
+    TInt peerListenerArrayCount = iPeerListenerArray->Count();
+    for ( TInt i = 0; i < peerListenerArrayCount; i++ )
+        {
+        iPeerListenerArray->At( i )->IssueListen();
+        }
+    iListening = ETrue;
+
+    AssureConnectionL();
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::StopListening
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::StopListening()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::StopListening()" ) );
+
+    TInt peerListenerArrayCount = iPeerListenerArray->Count();
+    for ( TInt i = 0; i < peerListenerArrayCount; i++ )
+        {
+        iPeerListenerArray->At( i )->Cancel();
+        }
+    iListening = EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::DisconnectAllConnections
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::DisconnectAllConnections()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::ConnectionAcceptedL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::ConnectionAcceptedL( RSocket* aSocket )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::ConnectionAcceptedL()" ) );
+
+    Cancel();   //Possible timeout timer
+
+    CleanupStack::PushL( TCleanupItem( CleanupSocket, aSocket ) );
+    iSocketRouter->AddPeerSocketL( aSocket );
+    CleanupStack::Pop(); //aSocket
+
+    AssureConnectionL();
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::ErrorL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::ErrorL( TInt aErrorCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::ErrorL(%d)" ), aErrorCode );
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::ObserverLeaved
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::ObserverLeaved( TInt aLeaveCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::ObserverLeaved(%d)" ), aLeaveCode );
+    if ( iObserver )
+        {
+        iObserver->ObserverLeaved( aLeaveCode );
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::ConnectionEstablishedL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::ConnectionEstablishedL()
+    {
+    // Connection to host established via bluetooth
+
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::ConnectionEstablishedL()" ) );
+
+    MSocket* socket = iAbstractConnection->GetSocket();
+    if ( socket )
+        {
+        iSocketRouter->SetHostSocketL( socket );
+        iSocketRouter->StartRouting();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::HostConnectionErrorL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::HostConnectionErrorL( TInt aErrorCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::HostConnectionErrorL(%d)" ), aErrorCode );
+    iHostConnection->IssueDisconnect();
+    iSocketRouter->RemoveAllPeers();
+    iSocketRouter->StopRouting();
+    iSocketRouter->ResetQueue();
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::HostConnectionObserverLeaved
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::HostConnectionObserverLeaved( TInt aLeaveCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::HostConnectionObserverLeaved(%d)" ), aLeaveCode );
+    if ( iObserver )
+        {
+        iObserver->ObserverLeaved( aLeaveCode );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::LocalTCPConnectionEstablishedL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::LocalTCPConnectionEstablishedL( TUint aPort )
+    {
+    // Connection to local host (via TCP connection) established.
+
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::LocalTCPConnectionEstablishedL(), port=%d" ), aPort );
+
+    // TCP connection that was initiated from the PC side, got connected
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::ConnectionEstablishedL() -\
+         Local conn. was connected, adding the socket to socket router" ) );
+
+    TInt connIndex = FindLocalTCPConn( aPort );
+    if ( connIndex >= 0 )
+        {
+        CLocalTCPConnection* conn = iLocalConnArray->At( connIndex );
+        iSocketRouter->AddPeerSocketL( conn->Socket() );
+        // Socket router took ownership of the socket
+        conn->SetSocketOwnership( EFalse );
+        // Connection was established,
+        conn->Cancel();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::LocalTCPConnectionErrorL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::LocalTCPConnectionErrorL( TInt aPort, TInt aErrorCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::LocalTCPConnectionErrorL(%d)" ), aErrorCode );
+
+    TInt connIndex = FindLocalTCPConn( aPort );
+    if ( connIndex >= 0 )
+        {
+        RSocket* localSocket = iLocalConnArray->At( connIndex )->Socket();
+        iSocketRouter->RemovePeerSocket( localSocket );
+        iLocalConnArray->Delete( connIndex );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::LocalTCPConnectionObserverLeaved
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::LocalTCPConnectionObserverLeaved( TInt aPort,
+                                                       TInt aLeaveCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::HostConnectionObserverLeaved(%d), port%d" ),
+        aLeaveCode, aPort );
+    if ( iObserver )
+        {
+        iObserver->ObserverLeaved( aLeaveCode );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::SocketRouterErrorL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::SocketRouterErrorL(
+    const MSocket* /*aSocket*/, TInt aErrorCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::SocketRouterErrorL(%d)" ), aErrorCode );
+
+    if ( aErrorCode == -6305 )  //BT disconnected
+        {
+        iHostConnection->IssueDisconnect();
+        iSocketRouter->RemoveAllPeers();
+        iSocketRouter->StopRouting();
+        iSocketRouter->ResetQueue();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::ObserverLeaved
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::ObserverLeaved(
+    const MSocket* /*aSocket*/, TInt aLeaveCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::ObserverLeaved(%d)" ), aLeaveCode );
+    if ( iObserver )
+        {
+        iObserver->ObserverLeaved( aLeaveCode );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::PeerDisconnectedL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::PeerDisconnectedL( const MSocket* aSocket )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::PeerDisconnectedL(), localPort= %d. remotePort=%d" ),
+        aSocket->LocalPort(), aSocket->RemotePort() );
+
+    // Check if the socket was a local TCP connection socket
+    TInt indexOfConn = -1;
+    indexOfConn = FindLocalTCPConn( aSocket->RemotePort() );
+    if ( indexOfConn >= 0 )
+        {
+        // Notify PC side that the connection was disconnected
+        iSocketRouter->SendCloseTCPConnection( aSocket->RemotePort() );
+
+        DEBUG_PRINT( DEBUG_STRING(
+            "CIPProxyEngine::PeerDisconnectedL(), Deleting local connection." ),
+            aSocket->LocalPort(), aSocket->RemotePort() );
+        iLocalConnArray->Delete( indexOfConn );
+        }
+
+    Cancel();
+    iTimer.After( iStatus, KPeerDisconnectDelay );
+    SetActive();
+    DEBUG_PRINT( DEBUG_STRING( "Timeout timer activated" ) );
+
+    if ( iSocketRouter->SocketCount() == 0 )
+        {
+        iSocketRouter->StopRouting();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::HostDisconnectedL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::HostDisconnectedL( const MSocket* /*aSocket*/ )
+    {
+    iHostConnection->IssueDisconnect();
+    if ( iSocketRouter->IsRouting() )
+        {
+        iSocketRouter->StopRouting();
+        }
+    iSocketRouter->ResetQueue();
+    iSocketRouter->RemoveAllPeers();
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::OpenLocalTCPConnectionL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::OpenLocalTCPConnectionL( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::OpenLocalTCPConnectionL(), port=%d"), aPort );
+
+    CLocalTCPConnection* newConn =
+        CLocalTCPConnection::NewLC( this, aPort );
+
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::OpenLocalTCPConnectionL(), Issuing connection") );
+    iLocalConnArray->AppendL( newConn );
+    CleanupStack::Pop( newConn );
+
+    newConn->IssueConnectL();
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::OpenListeningTCPConnectionL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::OpenListeningTCPConnectionL( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::OpenListeningTCPConnectionL(), port=%d"), aPort );
+
+    TInt count = iPeerListenerArray->Count();
+    for ( TInt i = 0; i < count; i++ )
+        {
+        if ( iPeerListenerArray->At( i )->Port() == aPort )
+            {
+            // Port already listening
+            return;
+            }
+        }
+
+    // AddPeerListeningPortL will call IssueListen() only if iListening is set
+    // to ETrue
+    iListening = ETrue;
+    AddPeerListeningPortL( aPort );
+    AssureConnectionL();
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::CloseTCPConnection
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::CloseTCPConnection( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::CloseTCPConnection(), port=%d"), aPort );
+
+    // Delete local TCP connections
+    TInt index = FindLocalTCPConn( aPort );
+    if ( index > -1 )
+        {
+        CLocalTCPConnection* conn = iLocalConnArray->At( index );
+        iLocalConnArray->Delete( index );
+        delete conn;
+
+        DEBUG_PRINT( DEBUG_STRING(
+            "CIPProxyEngine::CloseTCPConnection(), conn deleted.") );
+        }
+    
+    // stop listening on this port
+    TInt peerListenerArrayCount = iPeerListenerArray->Count();
+    for ( TInt i = 0; i < peerListenerArrayCount; i++ )
+        {
+        CTCPPortListener* listener = iPeerListenerArray->At( i );
+        if(listener->Port() == aPort)
+            {
+            listener->Cancel();
+            iPeerListenerArray->Delete(i);
+            delete listener;
+            break;
+            }
+        }
+    
+    if(iPeerListenerArray->Count() == 0)
+        {
+        iListening = EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::CloseAllTCPConnections
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::CloseAllTCPConnections()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::CloseAllTCPConnections()" ) );
+
+    iSocketRouter->ResetQueue();
+    iSocketRouter->RemoveAllPeers();
+
+    iLocalConnArray->ResetAndDestroy();
+    
+    StopListening();
+
+    if ( iPeerListenerArray )
+        {
+        iPeerListenerArray->ResetAndDestroy();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::FindLocalTCPConn
+// -----------------------------------------------------------------------------
+//
+TInt CIPProxyEngine::FindLocalTCPConn( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CIPProxyEngine::FindLocalTCPConn(), port=%d"), aPort );
+    for ( TInt i = 0; i < iLocalConnArray->Count(); i++ )
+        {
+        if ( iLocalConnArray->At(i)->Port() == aPort )
+            {
+            return i;
+            }
+        }
+    return -1;
+    }
+
+// -----------------------------------------------------------------------------
+// CIPProxyEngine::AssureConnectionL
+// -----------------------------------------------------------------------------
+//
+void CIPProxyEngine::AssureConnectionL()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "AssureConnectionL()" ) );
+    if ( iHostConnection->IsConnected() )
+        {
+        DEBUG_PRINT( DEBUG_STRING(
+            "AssureConnectionL, connected" ) );
+        if ( !iSocketRouter->IsRouting() )
+            {
+            DEBUG_PRINT( DEBUG_STRING(
+                "AssureConnectionL, starting routing" ) );
+            iSocketRouter->StartRouting();
+            }
+        }
+    else
+        {
+        DEBUG_PRINT( DEBUG_STRING(
+            "AssureConnectionL, not connected, connecting" ) );
+        iHostConnection->IssueConnectL();
+        }
+    }
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CLocalHostConnection.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,194 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Local TCP connection for emulator testing
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CLocalHostConnection.h"
+#include "MHostConnectionObserver.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CLocalHostConnection::CLocalHostConnection
+// -----------------------------------------------------------------------------
+//
+CLocalHostConnection::CLocalHostConnection(
+    RSocketServ& aSocketServer,  TInt aPort ) :
+    CActive( EPriorityStandard ),
+    iSocketServer( aSocketServer )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalHostConnection::CLocalHostConnection() aPort=%d" ), aPort );
+
+    iAddr.SetPort( aPort );
+    iAddr.SetAddress( KInetAddrLoop );
+    }
+
+// -----------------------------------------------------------------------------
+// CLocalHostConnection::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CLocalHostConnection::ConstructL()
+    {
+
+    User::LeaveIfError( iClientSocket.Open(
+        iSocketServer, KAfInet, KSockStream, KProtocolInetTcp ) );
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CLocalHostConnection::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CLocalHostConnection* CLocalHostConnection::NewL(
+    RSocketServ& aSocketServer,  TInt aPort  )
+    {
+    CLocalHostConnection* self =
+        CLocalHostConnection::NewLC( aSocketServer, aPort );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+CLocalHostConnection* CLocalHostConnection::NewLC(
+    RSocketServ& aSocketServer,  TInt aPort  )
+    {
+    CLocalHostConnection* self =
+        new( ELeave ) CLocalHostConnection( aSocketServer, aPort );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+// Destructor
+CLocalHostConnection::~CLocalHostConnection()
+    {
+    Cancel();
+    iClientSocket.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CLocalHostConnection::RunL
+// -----------------------------------------------------------------------------
+//
+void CLocalHostConnection::RunL()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalHostConnection::RunL(), iStatus=%d" ),
+        iStatus.Int() );
+
+    if ( iStatus.Int() == KErrNone )
+        {
+        switch ( iState )
+            {
+            case ELCStateConnecting:
+                {
+                DEBUG_PRINT( DEBUG_STRING(
+                    "CLocalHostConnection::RunL(), ELCStateConnecting" ) );
+                iState = ELCStateConnected;
+                iObserver->ConnectionEstablishedL();
+                break;
+                }
+            case ELCStateDisconnecting:
+                {
+                DEBUG_PRINT( DEBUG_STRING(
+                    "CLocalHostConnection::RunL(), ELCStateDisconnecting" ) );
+                iState = ELCStateDisconnected;
+
+                iClientSocket.Close();
+                User::LeaveIfError( iClientSocket.Open(
+                    iSocketServer, KAfInet, KSockStream, KProtocolInetTcp ) );
+                break;
+                }
+            }
+        }
+    else
+        {
+        iObserver->HostConnectionErrorL( iStatus.Int() );
+        iClientSocket.Close();
+        User::LeaveIfError( iClientSocket.Open(
+            iSocketServer, KAfInet, KSockStream, KProtocolInetTcp ) );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CLocalHostConnection::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CLocalHostConnection::DoCancel()
+    {
+    iClientSocket.CancelConnect();
+    }
+
+TInt CLocalHostConnection::RunError( TInt aError )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalHostConnection::RunError( %d )" ), aError );
+
+    iObserver->HostConnectionObserverLeaved( aError );
+    return KErrNone;
+    }
+
+TInt CLocalHostConnection::Port()
+    {
+    return iAddr.Port();
+    }
+
+void CLocalHostConnection::IssueConnectL()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalHostConnection::IssueConnectL()" ) );
+
+    iClientSocket.Connect( iAddr, iStatus );
+    SetActive();
+    iState = ELCStateConnecting;
+    }
+
+void CLocalHostConnection::IssueDisconnect()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalHostConnection::IssueDisconnect()" ) );
+    iClientSocket.CancelAll();
+    Cancel();
+    iClientSocket.Shutdown( RSocket::ENormal, iStatus );
+    SetActive();
+    iState = ELCStateDisconnecting;
+    }
+
+void CLocalHostConnection::SetObserver( MHostConnectionObserver* aObserver )
+    {
+    iObserver = aObserver;
+    }
+
+RSocket* CLocalHostConnection::Socket()
+    {
+    return &iClientSocket;
+    }
+
+TBool CLocalHostConnection::IsConnected()
+    {
+    return ( iState == ELCStateConnected || iState == ELCStateDisconnecting );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CLocalHostConnection.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,155 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Local TCP connection for emulator testing
+*
+*/
+
+
+
+#ifndef CLOCALHOSTCONNECTION_H
+#define CLOCALHOSTCONNECTION_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <es_sock.h>
+//#include "MSocket.h"
+#include "MHostConnection.h"
+#include <in_sock.h>
+
+// DATA TYPES
+enum TLocalConnState
+    {
+    ELCStateDisconnected = 0,
+    ELCStateConnecting,
+    ELCStateConnected,
+    ELCStateDisconnecting
+    };
+
+
+// FORWARD DECLARATIONS
+class MHostConnectionObserver;
+
+// CLASS DECLARATION
+
+/**
+*  Local TCP connection for emulator testing.
+*  Due to problematic testing of bluetooth connections in emulator
+*  this class is used to simulate the connection to local TCP port instead.
+*  There must be running TCP port listener when connecting with this class.
+*/
+NONSHARABLE_CLASS( CLocalHostConnection ) : public CActive,
+    public MHostConnection
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aSocketServer Opened Socket server session
+        * @param aPort Port to connect.
+        * @return New CLocalHostConnection instance.
+        */
+        static CLocalHostConnection* NewL(
+            RSocketServ& aSocketServer, TInt aPort );
+
+        /**
+        * Factory function.
+        * @param aSocketServer Opened Socket server session
+        * @param aPort Port to connect.
+        * @return New CLocalHostConnection instance.
+        */
+        static CLocalHostConnection* NewLC(
+            RSocketServ& aSocketServer, TInt aPort );
+
+        /**
+        * Destructor.
+        */
+        ~CLocalHostConnection();
+
+    public: // Functions from MHostConnection
+
+        /**
+        * Starts connecting procedure to host.
+        */
+        void IssueConnectL();
+
+        /**
+        * Starts disconnection procedure.
+        */
+        void IssueDisconnect();
+
+        /**
+        * Sets observer.
+        * @param aObserver Pointer to observer.
+        */
+        void SetObserver( MHostConnectionObserver* aObserver );
+
+        /**
+        * @return Connection state.
+        */
+        TBool IsConnected();
+
+        /**
+        * @return Pointer to current RSocket object. The ownership always
+        * remains in this class.
+        */
+        RSocket* Socket();
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive. Pending request has been completed.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Pending request has been cancelled.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. RunL has leaved.
+        */
+        TInt RunError( TInt aError );
+
+    public: // New methods
+
+        /**
+        * Returns the port number of this connection
+        * @return Port number
+        */
+        TInt Port();
+
+    private:
+
+        /**
+        * Default constructor.
+        */
+        CLocalHostConnection( RSocketServ& aSocketServer, TInt aPort );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:    // Data
+        MHostConnectionObserver* iObserver;
+        RSocketServ& iSocketServer;
+        RSocket iClientSocket;
+        TInetAddr iAddr;
+        TLocalConnState iState;
+    };
+
+#endif      // CLOCALHOSTCONNECTION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CLocalTCPConnection.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,133 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Local TCP connection for emulator testing
+*
+*/
+
+
+
+#ifndef CLOCALTCPCONNECTION_H
+#define CLOCALTCPCONNECTION_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <es_sock.h>
+#include <in_sock.h>
+
+
+// DATA TYPES
+enum TLocalTCPConnState
+    {
+    ELTCStateDisconnected = 0,
+    ELTCStateConnecting,
+    ELTCStateConnected,
+    ELTCStateDisconnecting
+    };
+
+
+// FORWARD DECLARATIONS
+class MLocalTCPConnectionObserver;
+
+// CLASS DECLARATION
+
+/**
+*  Local TCP connection, which connects to local TCP port.
+*
+*/
+NONSHARABLE_CLASS( CLocalTCPConnection ) : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver TCP connection observer.
+        * @param aPort Port to connect to.
+        * @return New CLocalTCPConnection instance.
+        */
+        static CLocalTCPConnection* NewL(
+            MLocalTCPConnectionObserver* aObserver, TInt aPort );
+
+        /**
+        * Factory function.
+        * @param aObserver TCP connection observer.
+        * @param aPort Port to connect to.
+        * @return New CLocalTCPConnection instance.
+        */
+        static CLocalTCPConnection* NewLC(
+            MLocalTCPConnectionObserver* aObserver, TInt aPort );
+
+        /**
+        * Destructor.
+        */
+        ~CLocalTCPConnection();
+
+    public: // New functions
+
+        void IssueConnectL();
+        void IssueDisconnect();
+        void SetObserver( MLocalTCPConnectionObserver* aObserver );
+        TBool IsConnected();
+        RSocket* Socket();
+        void SetSocketOwnership( TBool aOwns );
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive. Pending request has been completed.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Pending request has been cancelled.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. RunL has leaved.
+        */
+        TInt RunError( TInt aError );
+
+    public: // New methods
+
+        /**
+        * Returns the port number of this connection
+        * @return Port number
+        */
+        TInt Port();
+
+    private:
+
+        /**
+        * Default constructor.
+        */
+        CLocalTCPConnection( MLocalTCPConnectionObserver* aObserver,
+                             TInt aPort );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:    // Data
+        MLocalTCPConnectionObserver* iObserver;
+        RSocketServ iSocketServer;
+        RSocket* iSocket;
+        TInetAddr iAddr;
+        TLocalTCPConnState iState;
+        TBool iOwnsSocket;
+    };
+
+#endif      // CLOCALTCPCONNECTION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CProtocolTCP.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,272 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HTTPProxy protocol implementation
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CProtocolTCP.h"
+#include "CExprTCPMsg.h"
+#include "CExprTCPOpen.h"
+#include "CExprTCPLstn.h"
+#include "CExprTCPClose.h"
+#include "CExprTCPCloseAll.h"
+#include "MSocketWriter.h"
+#include "MProtocolObserverTCP.h"
+#include "CommRouterDefinitions.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::CProtocolTCP
+// -----------------------------------------------------------------------------
+//
+CProtocolTCP::CProtocolTCP( MProtocolObserverTCP* aObserver )
+    : iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::ConstructL()
+    {
+    // Add all the expressions for TCP
+    iExpressionArray = new (ELeave) CArrayPtrFlat<MBPExpression> ( 5 );
+
+    CExprTCPMsg* tcpMsg = CExprTCPMsg::NewL( this );
+    iExpressionArray->AppendL( tcpMsg );
+
+    CExprTCPOpen* tcpOpen = CExprTCPOpen::NewL( this );
+    iExpressionArray->AppendL( tcpOpen );
+
+    CExprTCPLstn* tcpLstn = CExprTCPLstn::NewL( this );
+    iExpressionArray->AppendL( tcpLstn );
+
+    CExprTCPClose* tcpClose = CExprTCPClose::NewL( this );
+    iExpressionArray->AppendL( tcpClose );
+
+    CExprTCPCloseAll* tcpCloseAll = CExprTCPCloseAll::NewL( this );
+    iExpressionArray->AppendL( tcpCloseAll );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::NewL
+// -----------------------------------------------------------------------------
+//
+CProtocolTCP* CProtocolTCP::NewL( MProtocolObserverTCP* aObserver )
+    {
+    CProtocolTCP* self = CProtocolTCP::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::NewLC
+// -----------------------------------------------------------------------------
+//
+CProtocolTCP* CProtocolTCP::NewLC( MProtocolObserverTCP* aObserver )
+    {
+    CProtocolTCP* self = new( ELeave ) CProtocolTCP( aObserver );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::~CProtocolTCP
+// -----------------------------------------------------------------------------
+//
+CProtocolTCP::~CProtocolTCP()
+    {
+    if ( iExpressionArray )
+        {
+        iExpressionArray->ResetAndDestroy();
+        delete iExpressionArray;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::FrameStarted
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::FrameStarted()
+    {
+    iObserver->FrameStarted();
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::FrameParsedL
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::FrameParsedL( TUint aPort, const TDesC8& aData )
+    {
+    iObserver->TCPFrameParsedL( aPort, aData );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::ProtocolErrorL
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::ProtocolErrorL(
+    TInt aErrorCode, const TDesC8& aReceivedData )
+    {
+    iObserver->ProtocolErrorL( aErrorCode, aReceivedData );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::OpenLocalTCPConnectionL
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::OpenLocalTCPConnectionL( TUint aPort )
+    {
+    iObserver->OpenLocalTCPConnectionL( aPort );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::OpenListeningTCPConnectionL
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::OpenListeningTCPConnectionL( TUint aPort )
+    {
+    iObserver->OpenListeningTCPConnectionL( aPort );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::CloseTCPConnection
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::CloseTCPConnectionL( TUint aPort )
+    {
+    iObserver->CloseTCPConnectionL( aPort );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::ProtocolErrorL
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::CloseAllTCPConnections()
+    {
+    iObserver->CloseAllTCPConnections();
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::WriteFrameL
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::WriteFrameL( MSocketWriter& aSocketWriter,
+            TUint aPeerPort, TUint aOriginalPort, const TDesC8& aData ) const
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CProtocolTCP::WriteFrameL(), peer port=%d, original port=%d" ),
+        aPeerPort, aOriginalPort );
+
+    TInt bufSize = 0;
+    bufSize += KTCPPrefix().Length();
+    bufSize += KHexDecimalLength;
+    bufSize += KPortSuffix().Length();
+    bufSize += KHexDecimalLength;
+    bufSize += KPortSuffix().Length();
+    bufSize += KHexDecimalLength;
+    bufSize += KLengthSuffix().Length();
+    bufSize += aData.Length();
+    bufSize += KDataSuffix().Length();
+    bufSize += KMessageSuffix().Length(); // ? is this really needed
+
+    TBuf8<KHexDecimalLength> hexbuf;
+    HBufC8* buf = HBufC8::NewLC( bufSize );
+    TPtr8 ptr( buf->Des() );
+
+    // Append TCP prefix
+    ptr.Append( KTCPPrefix );
+
+    // Append peer port
+    hexbuf.Format( KHexFormat, aPeerPort );
+    ptr.Append( hexbuf );
+    ptr.Append( KPortSuffix );
+
+    // Append host port
+    hexbuf.Format( KHexFormat, aOriginalPort );
+    ptr.Append( hexbuf );
+    ptr.Append( KPortSuffix );
+
+    // Append data length
+    hexbuf.Format( KHexFormat, aData.Length() );
+    ptr.Append( hexbuf );
+    ptr.Append( KLengthSuffix );
+
+    // Append data
+    ptr.Append( aData );
+    ptr.Append( KDataSuffix );
+    ptr.Append( KMessageSuffix );
+
+    // Write to socket
+    aSocketWriter.WriteL( *buf );
+
+    CleanupStack::PopAndDestroy( buf );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::HandleReceivedDataL
+// -----------------------------------------------------------------------------
+//
+TBool CProtocolTCP::HandleReceivedDataL( TDes8& aData, TInt& aStartPos,
+                                         TInt& aLength )
+    {
+    TBool msgHandled = EFalse;
+    TInt protCount = iExpressionArray->Count();
+
+    for ( TInt i = 0; i < protCount; i++ )
+        {
+        msgHandled = iExpressionArray->At( i )->HandleRecievedMsgL( aData,
+                                                                    aStartPos,
+                                                                    aLength);
+        if ( msgHandled )
+            {
+            break;
+            }
+        }
+
+    return msgHandled;
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolTCP::SendCloseTCPConnection
+// -----------------------------------------------------------------------------
+//
+void CProtocolTCP::SendCloseTCPConnection( MSocketWriter& aSocketWriter,
+        TUint aPort )
+    {
+    DEBUG_PRINT(
+        DEBUG_STRING( "CProtocolTCP::SendCloseTCPConnection, port %d" ),
+        aPort );
+
+    aSocketWriter.WriteL( KTCPClosePrefix );
+    TBuf8<KHexDecimalLength> portBuf;
+    portBuf.Format( KHexFormat, aPort );
+    aSocketWriter.WriteL( portBuf );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CProtocolTCP.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  TCP protocol implementation for IP proxy
+*
+*/
+
+
+
+#ifndef CPROTOCOLTCP_H
+#define CPROTOCOLTCP_H
+
+//  INCLUDES
+#include "MBPProtocol.h"
+#include "MBPExpression.h"
+#include "MExpressionObserverTCP.h"
+
+#include <e32base.h>
+
+
+// FORWARD DECLARATIONS
+class MProtocolObserverTCP;
+class MSocketWriter;
+
+// CLASS DECLARATION
+
+/**
+* HTTPProxy protocol implementation. Writes and interpretes data in
+* protocol frame.
+*/
+NONSHARABLE_CLASS( CProtocolTCP ) : public CBase, public MBPProtocol,
+                                    public MExpressionObserverTCP
+    {
+
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CProtocol instance.
+        */
+        static CProtocolTCP* NewL( MProtocolObserverTCP* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CProtocol instance.
+        */
+        static CProtocolTCP* NewLC( MProtocolObserverTCP* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CProtocolTCP();
+
+    public: // From MExpressionObserverTCP
+
+        void FrameStarted();
+        void FrameParsedL( TUint aPort, const TDesC8& aData );
+        void ProtocolErrorL( TInt aErrorCode, const TDesC8& aReceivedData );
+        void OpenLocalTCPConnectionL( TUint aPort );
+        void OpenListeningTCPConnectionL( TUint aPort );
+        void CloseTCPConnectionL( TUint aPort );
+        void CloseAllTCPConnections();
+
+    public: // From MBPProtocol
+
+        void WriteFrameL( MSocketWriter& aSocketWriter,
+            TUint aPeerPort, TUint aOriginalPort, const TDesC8& aData ) const;
+
+        TBool HandleReceivedDataL( TDes8& aData, TInt& aStartPos, TInt& aLength );
+
+    public: // New functions
+
+        /**
+        * Sends command via HTI to close the TCP connection
+        * @param aPort Remote port to close
+        */
+        void SendCloseTCPConnection( MSocketWriter& aSocketWriter,
+                                          TUint aPort );
+
+    protected:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CProtocolTCP( MProtocolObserverTCP* aObserver );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+
+    private:    // Owned data
+
+        CArrayPtr<MBPExpression>* iExpressionArray;
+
+    private:    // Not owned data
+        MProtocolObserverTCP* iObserver;
+
+    };
+
+#endif      // CPROTOCOLTCP_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CProtocolUDP.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,196 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  UDP protocol implementation for IP proxy
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CProtocolUDP.h"
+#include "CExprUDPMsg.h"
+#include "MSocketWriter.h"
+#include "MProtocolObserverUDP.h"
+#include "CommRouterDefinitions.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::CProtocolUDP
+// -----------------------------------------------------------------------------
+//
+CProtocolUDP::CProtocolUDP( MProtocolObserverUDP* aObserver )
+    : iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CProtocolUDP::ConstructL()
+    {
+    // Add all the expressions for UDP
+    iExpressionArray = new (ELeave) CArrayPtrFlat<MBPExpression> ( 3 );
+
+    CExprUDPMsg* UDPMsg = CExprUDPMsg::NewL( this );
+    iExpressionArray->AppendL( UDPMsg );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::NewL
+// -----------------------------------------------------------------------------
+//
+CProtocolUDP* CProtocolUDP::NewL( MProtocolObserverUDP* aObserver )
+    {
+    CProtocolUDP* self = CProtocolUDP::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::NewLC
+// -----------------------------------------------------------------------------
+//
+CProtocolUDP* CProtocolUDP::NewLC( MProtocolObserverUDP* aObserver )
+    {
+    CProtocolUDP* self = new( ELeave ) CProtocolUDP( aObserver );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::~CProtocolUDP
+// -----------------------------------------------------------------------------
+//
+CProtocolUDP::~CProtocolUDP()
+    {
+    if ( iExpressionArray )
+        {
+        iExpressionArray->ResetAndDestroy();
+        delete iExpressionArray;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::FrameStarted
+// -----------------------------------------------------------------------------
+//
+void CProtocolUDP::FrameStarted()
+    {
+    iObserver->FrameStarted();
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::FrameParsedL
+// -----------------------------------------------------------------------------
+//
+void CProtocolUDP::FrameParsedL( TUint aPort, const TDesC8& aData )
+    {
+    iObserver->UDPFrameParsedL( aPort, aData );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::ProtocolErrorL
+// -----------------------------------------------------------------------------
+//
+void CProtocolUDP::ProtocolErrorL(
+    TInt aErrorCode, const TDesC8& aReceivedData )
+    {
+    iObserver->ProtocolErrorL( aErrorCode, aReceivedData );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::WriteFrameL
+// -----------------------------------------------------------------------------
+//
+void CProtocolUDP::WriteFrameL( MSocketWriter& aSocketWriter,
+            TUint aPeerPort, TUint aOriginalPort, const TDesC8& aData ) const
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CProtocolUDP::WriteFrameL(), peer port=%d, original port=%d" ),
+        aPeerPort, aOriginalPort );
+
+    TInt bufSize = 0;
+    bufSize += KUDPPrefix().Length();
+    bufSize += KHexDecimalLength;
+    bufSize += KPortSuffix().Length();
+    bufSize += KHexDecimalLength;
+    bufSize += KLengthSuffix().Length();
+    bufSize += aData.Length();
+    bufSize += KDataSuffix().Length();
+    bufSize += KMessageSuffix().Length();
+    
+    TBuf8<KHexDecimalLength> hexbuf;
+    HBufC8* buf = HBufC8::NewLC( bufSize );
+    TPtr8 ptr( buf->Des() );
+    
+    // Append UDP prefix
+    ptr.Append( KUDPPrefix );
+
+    // Append peer port
+    hexbuf.Format( KHexFormat, aPeerPort );
+    ptr.Append( hexbuf );
+    ptr.Append( KPortSuffix );
+
+    // Append data length
+    hexbuf.Format( KHexFormat, aData.Length() );
+    ptr.Append( hexbuf );
+    ptr.Append( KLengthSuffix );
+
+    // Append data
+    ptr.Append( aData );
+    ptr.Append( KDataSuffix );
+    ptr.Append( KMessageSuffix );
+    
+    // Write to socket
+    aSocketWriter.WriteL( *buf );
+
+    CleanupStack::PopAndDestroy( buf );
+    }
+
+// -----------------------------------------------------------------------------
+// CProtocolUDP::HandleReceivedDataL
+// -----------------------------------------------------------------------------
+//
+TBool CProtocolUDP::HandleReceivedDataL( TDes8& aData, TInt& aStartPos,
+                                         TInt& aLength )
+    {
+    TBool msgHandled = EFalse;
+    TInt protCount = iExpressionArray->Count();
+
+    for ( TInt i = 0; i < protCount; i++ )
+        {
+        msgHandled = iExpressionArray->At( i )->HandleRecievedMsgL( aData,
+                                                                    aStartPos,
+                                                                    aLength);
+        if ( msgHandled )
+            {
+            break;
+            }
+        }
+
+    return msgHandled;
+    }
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CProtocolUDP.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,104 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  UDP protocol implementation for IP proxy
+*
+*/
+
+
+
+#ifndef CPROTOCOLUDP_H
+#define CPROTOCOLUDP_H
+
+//  INCLUDES
+#include "MBPProtocol.h"
+#include "MBPExpression.h"
+#include "MExpressionObserverUDP.h"
+
+#include <e32base.h>
+
+
+// FORWARD DECLARATIONS
+class MProtocolObserverUDP;
+class MSocketWriter;
+
+// CLASS DECLARATION
+
+/**
+* UDP protocol implementation. Writes and interpretes data in
+* protocol frame.
+*/
+NONSHARABLE_CLASS( CProtocolUDP ) : public CBase, public MBPProtocol,
+                                    public MExpressionObserver
+    {
+
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CProtocol instance.
+        */
+        static CProtocolUDP* NewL( MProtocolObserverUDP* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CProtocol instance.
+        */
+        static CProtocolUDP* NewLC( MProtocolObserverUDP* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CProtocolUDP();
+
+    public: // From MExpressionObserverUDP
+
+        void FrameStarted();
+        void FrameParsedL( TUint aPort, const TDesC8& aData );
+        void ProtocolErrorL( TInt aErrorCode, const TDesC8& aReceivedData );
+
+    public: // From MBPProtocol
+
+        void WriteFrameL( MSocketWriter& aSocketWriter,
+            TUint aPeerPort, TUint aOriginalPort, const TDesC8& aData ) const;
+
+        TBool HandleReceivedDataL( TDes8& aData, TInt& aStartPos, TInt& aLength );
+
+    protected:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CProtocolUDP( MProtocolObserverUDP* aObserver );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+
+    private:    // Owned data
+
+        CArrayPtr<MBPExpression>* iExpressionArray;
+
+    private:    // Not owned data
+        MProtocolObserverUDP* iObserver;
+
+    };
+
+#endif      // CPROTOCOLUDP_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CSocketReader.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,187 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Socket reader
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "Csocketreader.h"
+#include "MSocketReaderObserver.h"
+#include <badesca.h>
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSocketReader::CSocketReader
+// -----------------------------------------------------------------------------
+//
+CSocketReader::CSocketReader( RSocket& aSocket,
+        TInt aUDPRemotePort /*= -1*/ ) :
+    CActive( EPriorityStandard ),
+    iSocket( aSocket ),
+    iUDPRemotePort( aUDPRemotePort )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketReader::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CSocketReader::ConstructL()
+    {
+    CActiveScheduler::Add( this );
+    IssueRead();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketReader::NewL
+// -----------------------------------------------------------------------------
+//
+CSocketReader* CSocketReader::NewL( RSocket& aSocket,
+        TInt aUDPRemotePort /*= -1*/ )
+    {
+    CSocketReader* self = CSocketReader::NewLC( aSocket, aUDPRemotePort );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketReader::NewLC
+// -----------------------------------------------------------------------------
+//
+CSocketReader* CSocketReader::NewLC( RSocket& aSocket,
+        TInt aUDPRemotePort /*= -1*/ )
+    {
+    CSocketReader* self = new( ELeave ) CSocketReader( aSocket, aUDPRemotePort );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// Destructor
+CSocketReader::~CSocketReader()
+    {
+    Cancel();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSocketReader::SetObserver
+// -----------------------------------------------------------------------------
+//
+void CSocketReader::SetObserver( MSocketReaderObserver* aObserver )
+    {
+    iObserver = aObserver;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketReader::IssueRead
+// -----------------------------------------------------------------------------
+//
+void CSocketReader::IssueRead()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketReader::IssueRead +" ) );
+
+    __ASSERT_ALWAYS( !IsActive() || iStatus != KRequestPending,
+        User::Panic( _L ( "s-reader" ), 1 ) );
+
+    TProtocolDesc desc;
+    TInt err = iSocket.Info( desc );
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketReader::IssueRead, err = %d" ), err );
+    DEBUG_PRINT( DEBUG_STRING(
+        "desc.iProtocol = %d, iUDPRemotePort=%d" ), desc.iProtocol, iUDPRemotePort );
+
+    if ( desc.iProtocol == KProtocolInetUdp && iUDPRemotePort > -1 )
+        {
+        // UDP
+        DEBUG_PRINT( DEBUG_STRING(
+            "CSocketReader::IssueRead(), UDP, local port=%d" ), iUDPRemotePort );
+        iSocket.RecvFrom( iReadBuffer, iUDPRemoteAddr, 0, iStatus );
+        }
+    else
+        {
+        // TCP
+        DEBUG_PRINT( DEBUG_STRING(
+            "CSocketReader::IssueRead(), TCP, local port=%d" ), iSocket.LocalPort() );
+        iSocket.RecvOneOrMore( iReadBuffer, 0, iStatus, iReceivedDataLength );
+        }
+
+    SetActive();
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketReader::IssueRead() -" ) );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketReader::Start
+// -----------------------------------------------------------------------------
+//
+void CSocketReader::Start()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketReader::Start" ) );
+    if ( !IsActive() )
+        {
+        IssueRead();
+        }
+    }
+// -----------------------------------------------------------------------------
+// CSocketReader::RunL
+// -----------------------------------------------------------------------------
+//
+void CSocketReader::RunL()
+    {
+    TInt status = iStatus.Int();
+    if ( status == KErrNone )
+        {
+        iObserver->DataReceivedL( iReadBuffer );
+        iReadBuffer.SetLength( 0 );
+        IssueRead();
+        }
+    else
+        {
+        iObserver->ReaderErrorL( status );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketReader::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CSocketReader::DoCancel()
+    {
+    iSocket.CancelRead();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketReader::RunError
+// -----------------------------------------------------------------------------
+//
+TInt CSocketReader::RunError( TInt aError )
+    {
+    iObserver->ObserverLeaved( aError );
+    iReadBuffer.SetLength( 0 );
+    IssueRead();
+    return KErrNone;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CSocketWriter.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,140 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Socket writer
+*
+*/
+
+
+
+#ifndef CSOCKETWRITER_H
+#define CSOCKETWRITER_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+const TInt KWriteBufferSize = 128;
+
+// FORWARD DECLARATIONS
+class MSocketWriterObserver;
+class RSocket;
+class CDesC8Array;
+
+// CLASS DECLARATION
+
+/**
+*  Socket writer. Asynchronously writes data to opened socket.
+*/
+NONSHARABLE_CLASS( CSocketWriter ) : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aSocket RSocket instance which is used to write data.
+        * @param aUDPRemotePort Remote UDB port.
+        * @return New CSocketWriter instance.
+        */
+        static CSocketWriter* NewL( RSocket& aSocket,
+            TInt aUDPRemotePort = -1 );
+
+        /**
+        * Factory function.
+        * @param aSocket RSocket instance which is used to write data.
+        * @param aUDPRemotePort Remote UDB port.
+        * @return New CSocketWriter instance.
+        */
+        static CSocketWriter* NewLC( RSocket& aSocket,
+            TInt aUDPRemotePort = -1 );
+
+        /**
+        * Destructor.
+        */
+        ~CSocketWriter();
+
+    public: // New functions
+
+        /**
+        * Sets observer.
+        * @param aObserver Pointer to observer.
+        */
+        void SetObserver( MSocketWriterObserver* aObserver );
+
+        /**
+        * Issues writing data to socket. If the request is already
+        * pending the data will be written to queue and it will be
+        * handled afterwards.
+        * @param aData Data to be written.
+        */
+        void IssueWriteL( const TDesC8& aData );
+
+        /**
+        * Resets transfer buffer.
+        */
+        void ResetTransferBuffer();
+
+        /**
+        * Continues writing if there is something in the buffer left.
+        */
+        void ContinueAfterError();
+
+    private:
+        /**
+        * Writes one descriptor from queue.
+        */
+        void IssueWrite();
+
+    protected: // Functions from base classes
+
+        /**
+        * From CActive. Pending request has been completed.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Pending request has been cancelled.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. RunL has leaved.
+        */
+        TInt RunError( TInt aError );
+
+
+    private:
+
+        /**
+        * Default constructor.
+        */
+        CSocketWriter( RSocket& aSocket, TInt aUDPRemotePort = -1 );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:    // Data
+        CDesC8Array* iTransferBufferArray;
+        MSocketWriterObserver* iObserver;
+        RSocket& iSocket;
+        TBuf8<KWriteBufferSize> iWriteBuffer;
+        RTimer iTimer;
+        TBool iWaiting;
+        const TInt iUDPRemotePort;
+    };
+
+#endif      // CSOCKETWRITER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CUDPSender.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,232 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  UDP packet sender
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CUDPSender.h"
+#include "MUDPSenderObserver.h"
+
+#include <badesca.h>
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+const TInt KServerBusyWaiting = 200000;  //200 ms delay
+const TInt KUDPSenderSlots = 50;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CUDPSender::CUDPSender
+// -----------------------------------------------------------------------------
+//
+CUDPSender::CUDPSender( MUDPSenderObserver* aObserver ) :
+    CActive( EPriorityStandard ), iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CUDPSender::ConstructL()
+    {
+    User::LeaveIfError( iSocketServ.Connect( KUDPSenderSlots ) );
+
+    // Create the socket
+    User::LeaveIfError( iSocket.Open( iSocketServ, KAfInet, KSockDatagram,
+        KProtocolInetUdp  ) );
+
+    iRemoteAddr.SetAddress(KInetAddrLoop);
+    
+    iTransferBufferArray = new (ELeave) CDesC8ArraySeg( 10 );
+    User::LeaveIfError( iTimer.CreateLocal() );
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::NewL
+// -----------------------------------------------------------------------------
+//
+CUDPSender* CUDPSender::NewL( MUDPSenderObserver* aObserver )
+    {
+    CUDPSender* self = CUDPSender::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::NewLC
+// -----------------------------------------------------------------------------
+//
+CUDPSender* CUDPSender::NewLC( MUDPSenderObserver* aObserver )
+    {
+    CUDPSender* self = new( ELeave ) CUDPSender( aObserver );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// Destructor
+CUDPSender::~CUDPSender()
+    {
+    Cancel();
+
+    iSocket.Close();
+    iSocketServ.Close();
+
+    iTimer.Close();
+    delete iTransferBufferArray;
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::IssueWriteL
+// -----------------------------------------------------------------------------
+//
+void CUDPSender::IssueWriteL( TUint aPort, const TDesC8& aData )
+    {
+    iRemoteAddr.SetPort(aPort);
+
+    // slice the size of data if bigger than KWriteBufferSize
+
+    TInt dsize = aData.Size();
+
+    for ( TInt i = 0; i < dsize; i+=KWriteBufferSize )
+        {
+        if ( i + KWriteBufferSize - 1 >= dsize )
+            {
+            __ASSERT_DEBUG( i + aData.Mid( i ).Size() == dsize ,
+                User::Panic( _L( "writer" ), 100 ) );
+            iTransferBufferArray->AppendL( aData.Mid(i) );
+            }
+        else
+            {
+            iTransferBufferArray->AppendL( aData.Mid( i, KWriteBufferSize ) );
+            }
+        }
+
+    if ( !IsActive() )
+        {
+        IssueWrite();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::IssueWrite
+// -----------------------------------------------------------------------------
+void CUDPSender::IssueWrite()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CUDPSender::IssueWrite" ) );
+    iWriteBuffer = (*iTransferBufferArray)[ 0 ];
+
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketWriter::IssueWrite()" ) );
+
+    iSocket.SendTo( iWriteBuffer, iRemoteAddr, 0, iStatus );
+
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::ContinueAfterError
+// -----------------------------------------------------------------------------
+void CUDPSender::ContinueAfterError()
+    {
+    if ( iTransferBufferArray->Count() > 0 )
+        {
+        IssueWrite();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::ResetTransferBuffer
+// -----------------------------------------------------------------------------
+void CUDPSender::ResetTransferBuffer()
+    {
+    iTransferBufferArray->Reset();
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::RunL
+// -----------------------------------------------------------------------------
+//
+void CUDPSender::RunL()
+    {
+    TInt status = iStatus.Int();
+    if ( status == KErrNone )
+        {
+        if ( iWaiting )
+            {
+            DEBUG_PRINT( DEBUG_STRING(
+                "Trying to write again..." ) );
+
+            iWaiting = EFalse;
+            IssueWrite();
+            }
+        else
+            {
+            iTransferBufferArray->Delete( 0 );
+            if ( iTransferBufferArray->Count() > 0 )
+                {
+                IssueWrite();
+                }
+            }
+        }
+    else
+        {
+        DEBUG_PRINT( DEBUG_STRING(
+            "CUDPSender::RunL(), iStatus=%d" ), status );
+        iObserver->UDPSenderErrorL( status );
+        //If Socket server is busy, wait for a while and try again
+        if ( status == KErrServerBusy )
+            {
+            DEBUG_PRINT( DEBUG_STRING(
+                "Socket server busy. Waiting for a while..." ) );
+            iWaiting = ETrue;
+            iTimer.After( iStatus, KServerBusyWaiting );
+            SetActive();
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CUDPSender::DoCancel()
+    {
+    iTimer.Cancel();
+    iSocket.CancelWrite();
+    }
+
+// -----------------------------------------------------------------------------
+// CUDPSender::RunError
+// -----------------------------------------------------------------------------
+//
+TInt CUDPSender::RunError( TInt aError )
+    {
+    iObserver->UDPSenderLeavedL( aError );
+    return KErrNone;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CUDPSender.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,133 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  UDP packet sender
+*
+*/
+
+
+
+#ifndef CUDPSENDER_H
+#define CUDPSENDER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <in_sock.h>
+
+// CONSTANTS
+const TInt KWriteBufferSize = 128;
+
+// FORWARD DECLARATIONS
+class MUDPSenderObserver;
+class CDesC8Array;
+
+// CLASS DECLARATION
+
+/**
+*  Socket writer. Asynchronously writes data to opened socket.
+*/
+NONSHARABLE_CLASS( CUDPSender ) : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CUDPSender instance.
+        */
+        static CUDPSender* NewL( MUDPSenderObserver* aObserver );
+
+        /**
+        * Factory function.
+        * @param aObserver Pointer to observer.
+        * @return New CUDPSender instance.
+        */
+        static CUDPSender* NewLC( MUDPSenderObserver* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CUDPSender();
+
+    public: // New functions
+
+        /**
+        * Issues writing data to UDP socket. If the request is already
+        * pending the data will be written to queue and it will be
+        * handled afterwards.
+        * @param aPort Port to write to.
+        * @param aData Data to be written.
+        */
+        void IssueWriteL( TUint aPort, const TDesC8& aData );
+
+        /**
+        * Resets transfer buffer.
+        */
+        void ResetTransferBuffer();
+
+        /**
+        * Continues writing if there is something in the buffer left.
+        */
+        void ContinueAfterError();
+
+    private:
+        /**
+        * Writes one descriptor from queue.
+        */
+        void IssueWrite();
+
+    protected: // Functions from base classes
+
+        /**
+        * From CActive. Pending request has been completed.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Pending request has been cancelled.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. RunL has leaved.
+        */
+        TInt RunError( TInt aError );
+
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CUDPSender( MUDPSenderObserver* aObserver );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:    // Data
+        RSocketServ iSocketServ;
+        CDesC8Array* iTransferBufferArray;
+        MUDPSenderObserver* iObserver;
+        RSocket iSocket;
+        TBuf8<KWriteBufferSize> iWriteBuffer;
+        RTimer iTimer;
+        TBool iWaiting;
+        TInetAddr iRemoteAddr;
+    };
+
+#endif      // CUDPSender_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CWriteEvent.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,119 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Write event for queuing data to be sent
+*
+*/
+
+
+
+// INCLUDE FILES
+#include    "CWriteEvent.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CWriteEvent::CWriteEvent
+// -----------------------------------------------------------------------------
+//
+CWriteEvent::CWriteEvent( TProtocolDesc aProtocolDesc, TInt aPeerPort,
+    TInt aOriginalPort ) :
+    iPeerPort( aPeerPort ),
+    iOriginalPort( aOriginalPort ),
+    iProtocolDesc( aProtocolDesc )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CWriteEvent::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CWriteEvent::ConstructL( const TDesC8& aData )
+    {
+    iData = aData.AllocL();
+    }
+
+// -----------------------------------------------------------------------------
+// CWriteEvent::NewL
+// -----------------------------------------------------------------------------
+//
+CWriteEvent* CWriteEvent::NewL( TProtocolDesc aProtocolDesc,
+    const TDesC8& aData, TInt aPeerPort, TInt aOriginalPort )
+    {
+    CWriteEvent* self = CWriteEvent::NewLC( aProtocolDesc, aData, aPeerPort, aOriginalPort );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CWriteEvent::NewLC
+// -----------------------------------------------------------------------------
+//
+CWriteEvent* CWriteEvent::NewLC( TProtocolDesc aProtocolDesc,
+    const TDesC8& aData, TInt aPeerPort, TInt aOriginalPort )
+    {
+    CWriteEvent* self = new( ELeave ) CWriteEvent( aProtocolDesc, aPeerPort,
+        aOriginalPort );
+    CleanupStack::PushL( self );
+
+    self->ConstructL( aData );
+    return self;
+    }
+
+
+// Destructor
+CWriteEvent::~CWriteEvent()
+    {
+    delete iData;
+    }
+
+// -----------------------------------------------------------------------------
+// CWriteEvent::ProtocolDesc
+// -----------------------------------------------------------------------------
+//
+TProtocolDesc CWriteEvent::ProtocolDesc() const
+    {
+    return iProtocolDesc;
+    }
+
+// -----------------------------------------------------------------------------
+// CWriteEvent::Data
+// -----------------------------------------------------------------------------
+//
+const TDesC8& CWriteEvent::Data() const
+    {
+    return *iData;
+    }
+
+// -----------------------------------------------------------------------------
+// CWriteEvent::PeerPort
+// -----------------------------------------------------------------------------
+//
+TInt CWriteEvent::PeerPort() const
+    {
+    return iPeerPort;
+    }
+
+// -----------------------------------------------------------------------------
+// CWriteEvent::OriginalPort
+// -----------------------------------------------------------------------------
+//
+TInt CWriteEvent::OriginalPort() const
+    {
+    return iOriginalPort;
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/CWriteEvent.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,110 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Write event for queuing data to be sent
+*
+*/
+
+
+
+#ifndef CWRITEEVENT_H
+#define CWRITEEVENT_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <es_sock.h>
+
+// CLASS DECLARATION
+
+/**
+*  Write event for queuing data to be sent. The class only stores
+*  data and ports.
+*/
+NONSHARABLE_CLASS( CWriteEvent ) : public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aProtocolDesc Protocol description to store.
+        * @param aData Data to store.
+        * @param aPeerPort Peer port to store.
+        * @param aOriginalPort Original port to store.
+        */
+        static CWriteEvent* NewL( TProtocolDesc aProtocolDesc,
+            const TDesC8& aData, TInt aPeerPort, TInt aOriginalPort );
+
+        /**
+        * Factory function.
+        * @param aProtocolDesc Protocol description to store.
+        * @param aData Data to store.
+        * @param aPeerPort Peer port to store.
+        * @param aOriginalPort Original port to store.
+        */
+        static CWriteEvent* NewLC( TProtocolDesc aProtocolDesc,
+            const TDesC8& aData, TInt aPeerPort, TInt aOriginalPort );
+
+        /**
+        * Destructor.
+        */
+        ~CWriteEvent();
+
+    public: // New functions
+
+        /**
+        * @return Protocol description
+        */
+        TProtocolDesc ProtocolDesc() const;
+
+        /**
+        * @return Data
+        */
+        const TDesC8& Data() const;
+
+        /**
+        * @return Peer port
+        */
+        TInt PeerPort() const;
+
+        /**
+        * @return Original port
+        */
+        TInt OriginalPort() const;
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aProtocolDesc Protocol description to store.
+        * @param aPeerPort Peer port to store.
+        * @param aOriginalPort Original port to store.
+        */
+        CWriteEvent( TProtocolDesc aProtocolDesc, TInt aPeerPort, TInt aOriginalPort );
+
+        /**
+        * 2nd phase constructor.
+        * @param aData Data to store
+        */
+        void ConstructL( const TDesC8& aData );
+
+
+    private:    // Data
+        HBufC8* iData;
+        TInt iPeerPort;
+        TInt iOriginalPort;
+        TProtocolDesc iProtocolDesc;
+    };
+
+#endif      // CWRITEEVENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Clocaltcpconnection.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,219 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Local TCP connection for emulator testing
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CLocalTCPConnection.h"
+#include "MLocalTCPConnectionObserver.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CLocalTCPConnection::CLocalTCPConnection
+// -----------------------------------------------------------------------------
+//
+CLocalTCPConnection::CLocalTCPConnection(
+    MLocalTCPConnectionObserver* aObserver, TInt aPort ) :
+    CActive( EPriorityStandard )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalTCPConnection::CLocalTCPConnection() aPort=%d" ), aPort );
+
+    iOwnsSocket = ETrue;
+    iObserver = aObserver;
+    iAddr.SetPort( aPort );
+    iAddr.SetAddress( KInetAddrLoop );
+    }
+
+// -----------------------------------------------------------------------------
+// CLocalTCPConnection::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CLocalTCPConnection::ConstructL()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalTCPConnection::ConstructL, opening socket..." ) );
+
+    iSocket = new (ELeave) RSocket;
+    User::LeaveIfError( iSocketServer.Connect() );
+    User::LeaveIfError( iSocket->Open(
+        iSocketServer, KAfInet, KSockStream, KProtocolInetTcp ) );
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalTCPConnection::ConstructL, socket opened." ) );
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CLocalTCPConnection::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CLocalTCPConnection* CLocalTCPConnection::NewL(
+    MLocalTCPConnectionObserver* aObserver,
+    TInt aPort  )
+    {
+    CLocalTCPConnection* self =
+        CLocalTCPConnection::NewLC( aObserver, aPort );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+CLocalTCPConnection* CLocalTCPConnection::NewLC(
+    MLocalTCPConnectionObserver* aObserver,
+    TInt aPort  )
+    {
+    CLocalTCPConnection* self =
+        new( ELeave ) CLocalTCPConnection( aObserver, aPort );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+// Destructor
+CLocalTCPConnection::~CLocalTCPConnection()
+    {
+    Cancel();
+
+    if ( iOwnsSocket )
+        {
+        if ( iSocket )
+            {
+            iSocket->Close();
+            delete iSocket;
+            }
+        }
+
+    iSocketServer.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CLocalTCPConnection::RunL
+// -----------------------------------------------------------------------------
+//
+void CLocalTCPConnection::RunL()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalTCPConnection::RunL(), iStatus=%d" ),
+        iStatus.Int() );
+
+    if ( iStatus.Int() == KErrNone )
+        {
+        switch ( iState )
+            {
+            case ELTCStateConnecting:
+                {
+                DEBUG_PRINT( DEBUG_STRING(
+                    "CLocalTCPConnection::RunL(), ELCStateConnecting" ) );
+                iState = ELTCStateConnected;
+                iObserver->LocalTCPConnectionEstablishedL( Port() );
+                break;
+                }
+            case ELTCStateDisconnecting:
+                {
+                DEBUG_PRINT( DEBUG_STRING(
+                    "CLocalTCPConnection::RunL(), ELCStateDisconnecting" ) );
+                iState = ELTCStateDisconnected;
+
+                iSocket->Close();
+                User::LeaveIfError( iSocket->Open(
+                    iSocketServer, KAfInet, KSockStream, KProtocolInetTcp ) );
+                break;
+                }
+            }
+        }
+    else
+        {
+        iObserver->LocalTCPConnectionErrorL( Port(), iStatus.Int() );
+        iSocket->Close();
+        User::LeaveIfError( iSocket->Open(
+            iSocketServer, KAfInet, KSockStream, KProtocolInetTcp ) );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CLocalTCPConnection::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CLocalTCPConnection::DoCancel()
+    {
+    iSocket->CancelConnect();
+    }
+
+TInt CLocalTCPConnection::RunError( TInt aError )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalTCPConnection::RunError( %d )" ), aError );
+
+    iObserver->LocalTCPConnectionObserverLeaved( Port(), aError );
+    return KErrNone;
+    }
+
+TInt CLocalTCPConnection::Port()
+    {
+    return iAddr.Port();
+    }
+
+void CLocalTCPConnection::IssueConnectL()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalTCPConnection::IssueConnectL()" ) );
+
+    iSocket->Connect( iAddr, iStatus );
+    SetActive();
+    iState = ELTCStateConnecting;
+    }
+
+void CLocalTCPConnection::IssueDisconnect()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CLocalTCPConnection::IssueDisconnect()" ) );
+    iSocket->CancelAll();
+    Cancel();
+    iSocket->Shutdown( RSocket::ENormal, iStatus );
+    SetActive();
+    iState = ELTCStateDisconnecting;
+    }
+
+void CLocalTCPConnection::SetObserver( MLocalTCPConnectionObserver* aObserver )
+    {
+    iObserver = aObserver;
+    }
+
+RSocket* CLocalTCPConnection::Socket()
+    {
+    return iSocket;
+    }
+
+void CLocalTCPConnection::SetSocketOwnership( TBool aOwns )
+    {
+    iOwnsSocket = aOwns;
+    }
+
+
+TBool CLocalTCPConnection::IsConnected()
+    {
+    return ( iState == ELTCStateConnected || iState == ELTCStateDisconnecting );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocket.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,270 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  General purpose socket implementetion
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "Csocket.h"
+#include <es_sock.h>
+#include <in_sock.h>
+#include "CSocketWriter.h"
+#include "Csocketreader.h"
+#include "MSocketObserver.h"
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSocket::CSocket
+// -----------------------------------------------------------------------------
+//
+CSocket::CSocket( RSocket* aSocket, TInt aUDPRemotePort /*= -1*/ ) :
+    iSocket( aSocket ),
+    iHasOwnership( EFalse ),
+    iUDPRemotePort( aUDPRemotePort )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CSocket::ConstructL()
+    {
+    iSocketWriter = CSocketWriter::NewL( *iSocket, iUDPRemotePort );
+    iSocketWriter->SetObserver( this );
+    iSocketReader = CSocketReader::NewL( *iSocket, iUDPRemotePort );
+    iSocketReader->SetObserver( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::NewL
+// -----------------------------------------------------------------------------
+//
+CSocket* CSocket::NewL( RSocket* aSocket, TInt aUDPRemotePort /*= -1*/ )
+    {
+    CSocket* self = CSocket::NewLC( aSocket, aUDPRemotePort );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::NewLC
+// -----------------------------------------------------------------------------
+//
+CSocket* CSocket::NewLC( RSocket* aSocket, TInt aUDPRemotePort /*= -1*/ )
+    {
+    CSocket* self = new( ELeave ) CSocket( aSocket, aUDPRemotePort );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// Destructor
+CSocket::~CSocket()
+    {
+    delete iSocketWriter;
+    delete iSocketReader;
+    if ( iHasOwnership && iSocket )
+        {
+        TRequestStatus status;
+        iSocket->Shutdown( RSocket::EImmediate, status );
+        User::WaitForRequest( status );
+        iSocket->Close();
+        delete iSocket;
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSocket::WriteL
+// -----------------------------------------------------------------------------
+//
+void CSocket::WriteL( const TDesC8& aData )
+    {
+    iSocketWriter->IssueWriteL( aData );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::GetRSocket
+// -----------------------------------------------------------------------------
+//
+RSocket* CSocket::GetRSocket()
+    {
+    return iSocket;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::RemotePort
+// -----------------------------------------------------------------------------
+//
+TUint CSocket::RemotePort() const
+    {
+    if ( IsUDP() )
+        {
+        return iUDPRemotePort;
+        }
+    else
+        {
+        TSockAddr addr;
+        iSocket->RemoteName( addr );
+        return addr.Port();
+        }
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::LocalPort
+// -----------------------------------------------------------------------------
+//
+TUint CSocket::LocalPort() const
+    {
+    return iSocket->LocalPort();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::SetObserver
+// -----------------------------------------------------------------------------
+//
+void CSocket::SetObserver( MSocketObserver* aObserver )
+    {
+    iObserver = aObserver;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::SetSocketOwnershipMode
+// -----------------------------------------------------------------------------
+//
+void CSocket::SetSocketOwnershipMode( TBool aHasOwnership )
+    {
+    iHasOwnership = aHasOwnership;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::IssueRead
+// -----------------------------------------------------------------------------
+//
+void CSocket::IssueRead()
+    {
+    iSocketReader->Start();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::Cancel
+// -----------------------------------------------------------------------------
+//
+void CSocket::Cancel()
+    {
+    iSocketReader->Cancel();
+    iSocketWriter->Cancel();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::DataReceivedL
+// -----------------------------------------------------------------------------
+//
+void CSocket::SocketInfo( TProtocolDesc& aDesc) const
+    {
+    iSocket->Info( aDesc );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::IsUDP
+// -----------------------------------------------------------------------------
+//
+TBool CSocket::IsUDP() const
+    {
+    TProtocolDesc desc;
+    iSocket->Info( desc );
+    if ( desc.iProtocol == KProtocolInetUdp && iUDPRemotePort > -1 )
+        {
+        return ETrue;
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::DataReceivedL
+// -----------------------------------------------------------------------------
+//
+void CSocket::DataReceivedL( const TDesC8& aData )
+    {
+    iObserver->DataReceivedL( this, aData );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::BufferUnderrunL
+// -----------------------------------------------------------------------------
+//
+void CSocket::BufferUnderrunL()
+    {
+    //No implementation
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::WriterErrorL
+// -----------------------------------------------------------------------------
+//
+void CSocket::WriterErrorL( TInt aErrorCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocket::WriterErrorL( %d )" ), aErrorCode );
+
+    iObserver->ErrorL( this, aErrorCode );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocket::ReaderErrorL
+// -----------------------------------------------------------------------------
+//
+void CSocket::ReaderErrorL( TInt aErrorCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocket::ReaderErrorL( %d ), UDP port=%d" ), aErrorCode, iUDPRemotePort );
+
+    if ( aErrorCode == KErrEof || aErrorCode == KErrCancel ||
+        aErrorCode == KErrDisconnected || aErrorCode == KErrNotReady )
+        {
+        iObserver->DisconnectedL( this );
+        }
+    else
+        {
+        iObserver->ErrorL( this, aErrorCode );
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSocket::ObserverLeaved
+// -----------------------------------------------------------------------------
+//
+void CSocket::ObserverLeaved( TInt aLeaveCode )
+    {
+    iObserver->ObserverLeaved( this, aLeaveCode );
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocket.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,187 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  General purpose socket implementetion
+*
+*/
+
+
+
+#ifndef CSOCKET_H
+#define CSOCKET_H
+
+//  INCLUDES
+#include <e32base.h>
+#include "MSocketWriterObserver.h"
+#include "MSocketReaderObserver.h"
+#include "MSocket.h"
+
+// FORWARD DECLARATIONS
+class CSocketWriter;
+class CSocketReader;
+
+// CLASS DECLARATION
+
+/**
+*  General purpose socket implementetion.
+*  With this class the client can write and receive data
+*  to and from the opened RSocket object.
+*/
+NONSHARABLE_CLASS( CSocket ) : public CBase,
+    public MSocketWriterObserver,
+    public MSocketReaderObserver,
+    public MSocket
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aSocket Opened RSocket instance that is used to read and write
+        * data.
+        * @param aUDPRemotePort Remote UDB port.
+
+        */
+        static CSocket* NewL( RSocket* aSocket, TInt aUDPRemotePort = -1 );
+
+        /**
+        * Factory function.
+        * @param aSocket Opened RSocket instance that is used to read and write
+        * data.
+        * @param aUDPRemotePort Remote UDB port.
+        */
+        static CSocket* NewLC( RSocket* aSocket, TInt aUDPRemotePort = -1  );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSocket();
+
+    public: // New functions
+
+        /**
+        * @return RSocket object
+        */
+        RSocket* GetRSocket();
+
+        /**
+        * @return Local TCP port.
+        */
+        TUint LocalPort() const;
+
+        /**
+        * @return Remote TCP port.
+        */
+        TUint RemotePort() const;
+
+        /**
+        * Sets observer.
+        * @param aObserver Pointer to observer.
+        */
+        void SetObserver( MSocketObserver* aObserver );
+
+        /**
+        * Sets the ownership mode of RSocket object. If set ETrue
+        * the socket will be closed and RSocket object will be deleted
+        * in the destruction.
+        * @param aHasOwnership Ownership mode.
+        */
+        void SetSocketOwnershipMode( TBool aHasOwnership );
+
+        /**
+        * Starts receiving data.
+        */
+        void IssueRead();
+
+        /**
+        * Cancels all pending requests.
+        */
+        void Cancel();
+
+        /*
+        * Returns the protocol information of the socket
+        */
+        void SocketInfo( TProtocolDesc& aDesc) const;
+
+        /*
+        * Is this a UDP socket
+        */
+        TBool IsUDP() const;
+
+    public: // From MSocketWriter
+        /**
+        * Issues writing data to socket.
+        * @param aData Data to be written.
+        */
+        void WriteL( const TDesC8& aData );
+
+    protected:  // From MSocketReaderObserver
+        /**
+        * From MSocketReaderObserver.
+        * Data has been received.
+        * @param aData Received data.
+        */
+        void DataReceivedL( const TDesC8& aData );
+
+        /**
+        * From MSocketReaderObserver.
+        * Notifies that error has occurred.
+        * @param aErrorCode Error code.
+        */
+        void ReaderErrorL( TInt aErrorCode );
+
+        /**
+        * From MSocketWriterObserver.
+        * Notifies that error has occurred.
+        * @param aErrorCode Error code.
+        */
+        void WriterErrorL( TInt aErrorCode );
+
+        /**
+        * From MSocketWriterObserver.
+        * Notifies that all data has succesfully been written.
+        */
+        void BufferUnderrunL();
+
+        /**
+        * From MSocketReaderObserver and MSocketWriterObserver.
+        * Notifies that the observer has leaved while executing the callback
+        * function.
+        * @param aLeaveCode Leave code.
+        */
+        void ObserverLeaved( TInt aLeaveCode );
+
+
+    private:
+
+        /**
+        * Default constructor.
+        */
+        CSocket( RSocket* aSocket, TInt aUDPRemotePort = -1  );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:    // Data
+         RSocket* iSocket;
+         CSocketWriter* iSocketWriter;
+         CSocketReader* iSocketReader;
+         MSocketObserver* iObserver;
+         TBool iHasOwnership;
+         const TInt iUDPRemotePort;
+    };
+
+#endif      // CSOCKET_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocketreader.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,129 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Socket reader
+*
+*/
+
+
+
+#ifndef CSOCKETREADER_H
+#define CSOCKETREADER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <es_sock.h>
+#include <in_sock.h>
+
+
+// CONSTANTS
+const TInt KReadBufferSize = 8*1024;  //bytes
+
+// FORWARD DECLARATIONS
+class MSocketReaderObserver;
+class RSocket;
+class CDesC8Array;
+
+// CLASS DECLARATION
+
+/**
+*  Socket reader. ActiveObject that reads data from opened RSocket.
+*/
+NONSHARABLE_CLASS( CSocketReader ) : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aSocket Opened RSocket session from where data is read.
+        * @param aUDPRemotePort Peer ends port.
+        * @return New CSocketReader instance.
+        */
+        static CSocketReader* NewL( RSocket& aSocket,
+            TInt aUDPRemotePort = -1 );
+
+        /**
+        * Factory function.
+        * @param aSocket Opened RSocket session from where data is read.
+        * @param aUDPRemotePort Peer ends port.
+        * @return New CSocketReader instance.
+        */
+        static CSocketReader* NewLC( RSocket& aSocket,
+            TInt aUDPRemotePort = -1 );
+
+        /**
+        * Destructor.
+        */
+        ~CSocketReader();
+
+    public: // New functions
+
+        /**
+        * Sets observer.
+        * @param aObserver Pointer to observer.
+        */
+        void SetObserver( MSocketReaderObserver* aObserver );
+
+        /**
+        * Starts reading the socket.
+        */
+        void Start();
+
+    private:
+        /**
+        * Starts reading the socket.
+        */
+        void IssueRead();
+
+    protected: // Functions from base classes
+
+        /**
+        * From CActive. Pending request has been completed.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Pending request has been cancelled.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. RunL has leaved.
+        */
+        TInt RunError( TInt aError );
+
+
+    private:
+
+        /**
+        * Default constructor.
+        */
+        CSocketReader( RSocket& aSocket, TInt aUDPRemotePort = -1 );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:    // Data
+        TSockXfrLength iReceivedDataLength;
+        TBuf8<KReadBufferSize> iReadBuffer;
+        MSocketReaderObserver* iObserver;
+        RSocket& iSocket;
+        const TInt iUDPRemotePort;
+        TInetAddr iUDPRemoteAddr;
+    };
+
+#endif      // CSOCKETREADER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocketrouter.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,738 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Routes data from peers to host and vice versa
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "Csocketrouter.h"
+#include "CommRouterDefinitions.h"
+#include "MSocketRouterObserver.h"
+#include "MBPProtocol.h"
+#include "CProtocolTCP.h"
+#include "CProtocolUDP.h"
+#include "CLocalTCPConnection.h"
+#include "CUDPSender.h"
+#include "IPProxyEngine.pan"
+
+#include <es_sock.h>
+
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+// LOCAL CONSTANTS
+const TInt KSocketRouterSlots = 60;
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::CSocketRouter
+// -----------------------------------------------------------------------------
+//
+CSocketRouter::CSocketRouter( MSocketRouterObserver* aObserver )
+    : CActive( EPriorityIdle ), iObserver( aObserver )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::ConstructL()
+    {
+    User::LeaveIfError( iSocketServ.Connect( KSocketRouterSlots ) );
+
+    iReceiveBuffer = HBufC8::NewL( 0 );
+
+    iWriteEventArray = new (ELeave) CArrayPtrSeg<CWriteEvent> ( 10 );
+    iPeerSocketArray = new (ELeave) CArrayPtrFlat<CSocket> ( 10 );
+    iProtocolArray = new (ELeave) CArrayPtrFlat<MBPProtocol> ( 2 );
+
+    // Add the protocols
+    iProtocolTCP = CProtocolTCP::NewL( this );
+    // takes the ownership
+    iProtocolArray->AppendL( iProtocolTCP );
+
+    iProtocolUDP = CProtocolUDP::NewL( this );
+    // takes the ownership
+    iProtocolArray->AppendL( iProtocolUDP );
+
+    iUDPSender = CUDPSender::NewL( this );
+
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::NewL
+// -----------------------------------------------------------------------------
+//
+CSocketRouter* CSocketRouter::NewL( MSocketRouterObserver* aObserver )
+    {
+    CSocketRouter* self = CSocketRouter::NewLC( aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::NewLC
+// -----------------------------------------------------------------------------
+//
+CSocketRouter* CSocketRouter::NewLC( MSocketRouterObserver* aObserver )
+    {
+    CSocketRouter* self = new( ELeave ) CSocketRouter( aObserver );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// Destructor
+CSocketRouter::~CSocketRouter()
+    {
+    Cancel();
+
+    delete iUDPSender;
+    delete iReceiveBuffer;
+
+    if ( iProtocolArray )
+        {
+        iProtocolArray->ResetAndDestroy();
+        delete iProtocolArray;
+        }
+    if ( iPeerSocketArray )
+        {
+        iPeerSocketArray->ResetAndDestroy();
+        delete iPeerSocketArray;
+        }
+    if ( iWriteEventArray )
+        {
+        iWriteEventArray->ResetAndDestroy();
+        delete iWriteEventArray;
+        }
+
+    iSocketServ.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::AddPeerSocketL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::AddPeerSocketL( RSocket* aSocket )
+    {
+    CSocket* newSocket = CSocket::NewLC( aSocket );
+    newSocket->SetObserver( this );
+    iPeerSocketArray->AppendL( newSocket );
+    newSocket->SetSocketOwnershipMode( ETrue );
+
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketRouter::AddPeerSocketL(), localport=%d, remote port=%d" ),
+        newSocket->LocalPort(),
+        newSocket->RemotePort() );
+
+    CleanupStack::Pop( newSocket );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::AddUDPSocketL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::AddUDPSocketL( TUint aPort )
+    {
+    RSocket* newSocket = new (ELeave) RSocket();
+    CleanupStack::PushL( newSocket );
+
+    // Open the socket
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::AddUDPSocketL, Trying to open UDP port %d" ), aPort );
+
+    User::LeaveIfError( newSocket->Open( iSocketServ, KAfInet, KSockDatagram,
+        KProtocolInetUdp  ) );
+
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::AddUDPSocketL, UDP port opened." ), aPort );
+
+    // Bind the  socket to the correct port.
+    TInetAddr anyAddrOnPort( KInetAddrAny, aPort );
+    newSocket->Bind( anyAddrOnPort );
+
+    CSocket* cSocket = CSocket::NewLC( newSocket, aPort );
+    cSocket->SetObserver( this );
+    iPeerSocketArray->AppendL( cSocket );
+    cSocket->SetSocketOwnershipMode( ETrue );
+    CleanupStack::Pop( cSocket );
+
+    CleanupStack::Pop( newSocket );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::RemovePeerSocket
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::RemovePeerSocket( TInt aIndex )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::RemovePeerSocket()" ) );
+    CSocket* socket = iPeerSocketArray->At( aIndex );
+    iPeerSocketArray->Delete( aIndex );
+    delete socket;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::RemovePeerSocket
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::RemovePeerSocket( RSocket* aSocket )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::RemovePeerSocket()" ) );
+    TInt count = iPeerSocketArray->Count();
+    for ( TInt i = 0; i < count; i++ )
+        {
+        if ( iPeerSocketArray->At( i )->GetRSocket() == aSocket )
+            {
+            iPeerSocketArray->Delete( i );
+            break;
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::FindPeerSocket
+// -----------------------------------------------------------------------------
+//
+TInt CSocketRouter::FindPeerSocket( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::FindPeerSocket()" ) );
+    TInt count = iPeerSocketArray->Count();
+    for ( TInt i = 0; i < count; i++ )
+        {
+        if ( iPeerSocketArray->At( i )->RemotePort() == aPort 
+                || iPeerSocketArray->At( i )->LocalPort() == aPort)
+            {
+            return i;
+            }
+        }
+    return -1;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::RemoveAllPeers
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::RemoveAllPeers()
+    {
+    iPeerSocketArray->ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::SocketCount
+// -----------------------------------------------------------------------------
+//
+TInt CSocketRouter::SocketCount() const
+    {
+    return iPeerSocketArray->Count();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::SetHostSocketL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::SetHostSocketL( MSocket* aSocket )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketRouter::SetHostSocketL()" ) );
+
+    iHostSocket = aSocket;
+    iHostSocket->SetObserver( this );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::RunL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::RunL()
+    {
+    WriteQueueL();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::DoCancel()
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::StartRouting
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::StartRouting()
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::StartRouting()" ) );
+
+    iRouting = ETrue;
+    iHostSocket->IssueRead();
+    TInt peerSocketArrayCount = iPeerSocketArray->Count();
+    for ( TInt i = 0;i < peerSocketArrayCount; i++ )
+        {
+        CSocket* socket = iPeerSocketArray->At( i );
+        socket->IssueRead();
+        }
+    IssueHandleQueue();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::IssueHandleQueue
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::IssueHandleQueue()
+    {
+    if ( !IsActive() )
+        {
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete( status, KErrNone );
+
+        SetActive();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::StopRouting
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::StopRouting()
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::StopRouting()" ) );
+
+    Cancel();   //If HandleQueue is issued
+
+    iRouting = EFalse;
+    if ( iHostSocket )
+        {
+        iHostSocket->Cancel();
+        }
+    TInt peerSocketArrayCount = iPeerSocketArray->Count();
+    for ( TInt i = 0;i < peerSocketArrayCount; i++ )
+        {
+        CSocket* socket = iPeerSocketArray->At( i );
+        socket->Cancel();
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::IsRouting
+// -----------------------------------------------------------------------------
+//
+TBool CSocketRouter::IsRouting() const
+    {
+    return iRouting;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::ResetQueue
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::ResetQueue()
+    {
+    iWriteEventArray->ResetAndDestroy();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::SendCloseTCPConnection
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::SendCloseTCPConnection( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::SendCloseTCPConnection" ) );
+
+    iProtocolTCP->SendCloseTCPConnection( *iHostSocket, aPort );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::WriteCorrectFrame
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::WriteCorrectFrameL( TProtocolDesc aProtocolDesc,
+                        TUint aPeerPort,
+                        TUint aOriginalPort,
+                        const TDesC8& aData )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+            "CSocketRouter::WriteCorrectFrameL(), protocol = %d" ),
+            aProtocolDesc.iProtocol );
+
+    MBPProtocol* protocol;
+
+    if ( aProtocolDesc.iProtocol == KProtocolInetUdp )
+        {
+        // UDP frame
+        DEBUG_PRINT( DEBUG_STRING(
+            "CSocketRouter::WriteCorrectFrameL(), UDP" ) );
+        protocol = iProtocolUDP;
+        }
+    else
+        {
+        // TCP frame
+        DEBUG_PRINT( DEBUG_STRING(
+            "CSocketRouter::WriteCorrectFrameL(), TCP" ) );
+        protocol = iProtocolTCP;
+        }
+
+    protocol->WriteFrameL(
+        *iHostSocket, aPeerPort,
+        aOriginalPort, aData );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::DataReceivedL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::DataReceivedL( const MSocket* aSocket, const TDesC8& aData )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::DataReceivedL()" ) );
+
+    __ASSERT_ALWAYS( aSocket, Panic( IPProxyEngineNullSocket ) );
+
+    if ( iRouting )
+        {
+        //Route all data received from the host socket to protocol data handler.
+        if ( aSocket == iHostSocket )
+            {
+            // join the previous buffer if there's something left
+            TInt neededLength = iReceiveBuffer->Length() + aData.Length();
+            HBufC8* joinedBuffers = HBufC8::NewLC( neededLength );
+            TPtr8 joinedBuffersPtr( joinedBuffers->Des() );
+            joinedBuffersPtr.Append( *iReceiveBuffer );
+            joinedBuffersPtr.Append( aData );
+
+            // Check if there's a protocol that can handle this message
+            TInt length = 0; // length of the full msg
+            TInt startPos = 0; // where the msg prefix starts
+            TBool msgHandled = EFalse;
+            TInt protCount = iProtocolArray->Count();
+
+            for ( TInt i = 0; i < protCount && !msgHandled; i++ )
+                {
+                msgHandled = iProtocolArray->At( i )->HandleReceivedDataL(
+                                                        joinedBuffersPtr,
+                                                        startPos,
+                                                        length  );
+                }
+            if ( msgHandled )
+                {
+                if ( length > 0 )
+                    {
+                    // Length is set only when whole msg is processed
+                    // and correct.
+                    // Store the rest of the msg for the next round
+                    delete iReceiveBuffer;
+                    iReceiveBuffer = NULL;
+                    iReceiveBuffer =
+                            joinedBuffers->Mid( startPos + length ).AllocL();
+                    CleanupStack::PopAndDestroy( joinedBuffers );
+
+                    if ( iReceiveBuffer->Length() > 0 )
+                        {
+                        // Start again to process the rest
+                        iState = EStateWaitingFrameStart;
+                        DataReceivedL( aSocket, KNullDesC8 );
+                        }
+                    }
+                else
+                    {
+                    delete iReceiveBuffer;
+                    iReceiveBuffer = joinedBuffers;
+                    CleanupStack::Pop( joinedBuffers );
+                    }
+                }
+            else
+                {
+                // Could not find a valid prefix for this protocol
+                // store data for the next round
+                HBufC8* newBuffer = HBufC8::NewLC( KMaxPrefixLength -1 );
+                TPtr8 newBufferPtr( newBuffer->Des() );
+                if ( joinedBuffersPtr.Length() > 3 )
+                    {
+                    newBufferPtr =
+                        joinedBuffersPtr.Right( KMaxPrefixLength - 1 );
+                    }
+                else
+                    {
+                    iState = EStateWaitingFrameStart;
+                    newBufferPtr = joinedBuffersPtr;
+                    }
+                delete iReceiveBuffer;
+                iReceiveBuffer = newBuffer;
+                CleanupStack::Pop( newBuffer );
+                CleanupStack::PopAndDestroy( joinedBuffers );
+                return;
+                }
+            }
+        else    //Route all data received from any other socket to frame writer.
+            {
+            WriteQueueL();
+            TProtocolDesc info;
+            aSocket->SocketInfo( info );
+            WriteCorrectFrameL(
+                info, aSocket->RemotePort(),
+                aSocket->LocalPort(), aData );
+
+            }
+        }
+    else
+        {
+        //Add to queue
+        TProtocolDesc desc;
+        aSocket->SocketInfo( desc );
+        iWriteEventArray->AppendL( CWriteEvent::NewLC( desc,
+            aData, aSocket->RemotePort(), aSocket->LocalPort() ) );
+
+        DEBUG_PRINT( DEBUG_STRING(
+            "Add to queue: peerPort: %d. origPort: %d" ),
+            aSocket->RemotePort(),
+            aSocket->LocalPort() );
+
+        CleanupStack::Pop(); // CWriteEvent
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::WriteQueueL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::WriteQueueL()
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::WriteQueueL()" ) );
+
+    TInt writeEventArrayCount = iWriteEventArray->Count();
+    for ( TInt i = 0; i < writeEventArrayCount; i++ )
+        {
+        const CWriteEvent* writeEvent = iWriteEventArray->At( 0 );
+        WriteCorrectFrameL( writeEvent->ProtocolDesc(), writeEvent->PeerPort(),
+            writeEvent->OriginalPort(), writeEvent->Data() );
+        DEBUG_PRINT( DEBUG_STRING(
+            "WriteQueueL(): peerPort: %d. origPort: %d" ),
+            writeEvent->PeerPort(),
+            writeEvent->OriginalPort() );
+        iWriteEventArray->Delete( 0 );
+        delete writeEvent;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::ErrorL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::ErrorL( const MSocket* aSocket, TInt aErrorCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::ErrorL()" ) );
+
+    iObserver->SocketRouterErrorL( aSocket, aErrorCode );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::ObserverLeaved
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::ObserverLeaved( const MSocket* aSocket, TInt aLeaveCode )
+    {
+    iObserver->ObserverLeaved( aSocket, aLeaveCode );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::DisconnectedL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::DisconnectedL( const MSocket* aSocket )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::DisconnectedL()" ) );
+
+    if ( aSocket == iHostSocket )
+        {
+        DEBUG_PRINT( DEBUG_STRING( "aSocket == iHostSocket" ) );
+        iObserver->HostDisconnectedL( aSocket );
+        iHostSocket = NULL;
+        }
+    else
+        {
+        TInt peerSocketArrayCount = iPeerSocketArray->Count();
+        for ( TInt i = 0;i < peerSocketArrayCount; i++ )
+            {
+            CSocket* socket = iPeerSocketArray->At( i );
+            if ( socket == aSocket )
+                {
+                SendCloseTCPConnection( socket->RemotePort() );
+                iObserver->PeerDisconnectedL( socket );
+                RemovePeerSocket( i );
+                break;
+                }
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::FrameStarted
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::FrameStarted()
+    {
+    iState = EStateFrameStartFound;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::TCPFrameParsedL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::TCPFrameParsedL( TUint aPort, const TDesC8& aData )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::TCPFrameParsedL()" ) );
+    DEBUG_PRINT( DEBUG_STRING( "    aPort=%d" ), aPort );
+    DEBUG_PRINT( DEBUG_STRING( "    aData.Length=%d" ), aData.Length() );
+
+    for ( TInt i = 0; i < iPeerSocketArray->Count(); i++ )
+        {
+        CSocket* socket = iPeerSocketArray->At( i );
+        if ( socket->RemotePort() == aPort && !socket->IsUDP() )
+            {
+            socket->WriteL( aData );
+            break; //for
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::OpenLocalTCPConnectionL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::OpenLocalTCPConnectionL( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "OpenLocalTCPConnectionL, port = %d" ), aPort );
+    if ( iObserver )
+        {
+        iObserver->OpenLocalTCPConnectionL( aPort );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::OpenListeningTCPConnectionL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::OpenListeningTCPConnectionL( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "OpenListeningTCPConnectionL, port = %d" ), aPort );
+    if ( iObserver )
+        {
+        iObserver->OpenListeningTCPConnectionL( aPort );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::CloseTCPConnection
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::CloseTCPConnectionL( TUint aPort )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CloseTCPConnection, port = %d" ), aPort );
+    
+    // Close the socket if it exists
+    CArrayPtr<CSocket>* socketArrayForDestroy = new (ELeave) CArrayPtrFlat<CSocket> ( 10 );
+    CleanupStack::PushL(socketArrayForDestroy);
+    TInt index = FindPeerSocket( aPort );
+    while ( index > -1 )
+        {
+        socketArrayForDestroy->AppendL(iPeerSocketArray->At( index ));
+        iPeerSocketArray->Delete(index);
+        index = FindPeerSocket( aPort );
+        }
+    socketArrayForDestroy->ResetAndDestroy();
+    CleanupStack::PopAndDestroy(socketArrayForDestroy);
+
+    if ( iObserver )
+        {
+        iObserver->CloseTCPConnection( aPort );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::CloseAllTCPConnections
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::CloseAllTCPConnections()
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CloseAllTCPConnections" ) );
+    if ( iObserver )
+        {
+        iObserver->CloseAllTCPConnections();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::UDPFrameParsedL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::UDPFrameParsedL( TUint aPort, const TDesC8& aData )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::UDPFrameParsedL()" ) );
+    DEBUG_PRINT( DEBUG_STRING( "    aPort=%d" ), aPort );
+    DEBUG_PRINT( DEBUG_STRING( "    aData.Length=%d" ), aData.Length() );
+    iUDPSender->IssueWriteL( aPort, aData );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::ProtocolErrorL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::ProtocolErrorL(
+    TInt aErrorCode, const TDesC8& /* aReceivedData */ )
+    {
+    DEBUG_PRINT( DEBUG_STRING( "CSocketRouter::ProtocolErrorL()" ) );
+    DEBUG_PRINT( DEBUG_STRING( "    aErrorCode=%d" ), aErrorCode );
+
+    if ( iObserver )
+        {
+        iObserver->SocketRouterErrorL( iHostSocket, aErrorCode );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::UDPSenderErrorL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::UDPSenderErrorL( TInt aErrorCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketRouter::UDPSenderErrorL(), error code %d" ), aErrorCode );
+    iObserver->SocketRouterErrorL( NULL, aErrorCode );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketRouter::UDPSenderLeavedL
+// -----------------------------------------------------------------------------
+//
+void CSocketRouter::UDPSenderLeavedL( TInt aLeaveCode )
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketRouter::UDPSenderLeavedL(), leavecode %d" ), aLeaveCode );
+    iObserver->ObserverLeaved( NULL, aLeaveCode );
+    }
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocketrouter.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,241 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Routes data from peers to host and vice versa
+*
+*/
+
+
+
+#ifndef CSOCKETROUTER_H
+#define CSOCKETROUTER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include "Csocket.h"
+#include "MSocketObserver.h"
+#include "MProtocolObserverTCP.h"
+#include "MProtocolObserverUDP.h"
+#include "MUDPSenderObserver.h"
+#include "CWriteEvent.h"
+
+// DATA TYPES
+enum TSocketRouterState
+    {
+    EStateWaitingFrameStart = 0,
+    EStateFrameStartFound
+    };
+
+// FORWARD DECLARATIONS
+class MBPProtocol;
+class MSocketRouterObserver;
+class CProtocolTCP;
+class CProtocolUDP;
+class CUDPSender;
+
+// CLASS DECLARATION
+
+/**
+*  Routes data from peers to host and vice versa.
+*/
+NONSHARABLE_CLASS( CSocketRouter ) : public CActive,
+    public MSocketObserver,
+    public MProtocolObserverTCP,
+    public MProtocolObserverUDP,
+    public MUDPSenderObserver
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param aObserver Pointer to observer.
+        */
+        static CSocketRouter* NewL( MSocketRouterObserver* aObserver );
+
+        /**
+        * Two-phased constructor.
+        * @param aObserver Pointer to observer.
+        */
+        static CSocketRouter* NewLC( MSocketRouterObserver* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CSocketRouter();
+
+    public: // New functions
+
+        /**
+        * Adds peer socket. The ownership transfers.
+        * @param aSocket Opened RSocket object.
+        */
+        void AddPeerSocketL( RSocket* aSocket );
+
+        /**
+        * Adds UDP socket.
+        * @param aPort Port which is "listened" for datagrams
+        */
+        void AddUDPSocketL( TUint aPort );
+
+        /**
+        * Removes peer socket from the array.
+        * @param aIndex Index of array.
+        */
+        void RemovePeerSocket( TInt aIndex );
+
+        /**
+        * Removes peer socket from the array.
+        * @param aSocket Socket to remove.
+        */
+        void RemovePeerSocket( RSocket* aSocket );
+
+        /**
+        * Finds peer socket from the array.
+        * @param aPort A port to remove from the array
+        * @return index of the peer socket, -1 if not found
+        */
+        TInt FindPeerSocket( TUint aPort );
+
+        /**
+        * Removes all peer sockets from the array.
+        */
+        void RemoveAllPeers();
+
+        /**
+        * Get socket array count
+        * @return Number of CSocket instances in iPeerSocketArray
+        */
+        TInt SocketCount() const;
+
+        /**
+        * Sets the host socket. The ownership will NOT be transferred.
+        */
+        void SetHostSocketL( MSocket* aSocket );
+
+        /**
+        * Starts routing.
+        */
+        void StartRouting();
+
+        /**
+        * Stops routing.
+        */
+        void StopRouting();
+
+        /**
+        * @return ETrue if routing is activated and vice versa.
+        */
+        TBool IsRouting() const;
+
+        /**
+        * Resets message queue.
+        */
+        void ResetQueue();
+
+        /**
+        * Sends command via HTI to close the TCP connection
+        * @param aPort Phone remote port (midlet) to close
+        */
+        void SendCloseTCPConnection( TUint aPort );
+
+        /**
+        * Writes the data to with the correct protocol
+        * @param aProtocolDesc Which protocol was used to recieve this data
+        * @param aPeerPort Peer port
+        * @param aOriginalPort Port where the data was sent from
+        * @param aData Data to be transmitted
+        */
+        void WriteCorrectFrameL( TProtocolDesc aProtocolDesc,
+                                TUint aPeerPort,
+                                TUint aOriginalPort,
+                                const TDesC8& aData );
+
+    protected: // Functions from base classes
+
+        /**
+        * From CActive. Pending request has been completed.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Pending request has been cancelled.
+        */
+        void DoCancel();
+
+
+    protected:  // From MSocketObserver
+
+        void DataReceivedL( const MSocket* aSocket, const TDesC8& aData );
+        void ErrorL( const MSocket* aSocket, TInt aErrorCode );
+        void ObserverLeaved( const MSocket* aSocket, TInt aLeaveCode );
+        void DisconnectedL( const MSocket* aSocket );
+
+    protected:  // From MProtocolObserverTCP
+
+        void TCPFrameParsedL( TUint aPort, const TDesC8& aData );
+        void OpenLocalTCPConnectionL( TUint aPort );
+        void OpenListeningTCPConnectionL( TUint aPort );
+        void CloseTCPConnectionL( TUint aPort );
+        void CloseAllTCPConnections();
+
+    protected:  // From MProtocolObserverUDP
+
+        void UDPFrameParsedL( TUint aPort, const TDesC8& aData );
+
+    protected:  // From MProtocolObserver
+
+        void FrameStarted();
+        void ProtocolErrorL( TInt aErrorCode, const TDesC8& aReceivedData );
+
+    protected:  // From MUDPSenderObserver
+
+        void UDPSenderErrorL( TInt aErrorCode );
+        void UDPSenderLeavedL( TInt aLeaveCode );
+
+    private:
+
+        void IssueHandleQueue();
+        void WriteQueueL();
+
+    protected:
+        /**
+        * Default constructor.
+        * @param aObserver Pointer to observer.
+        */
+        CSocketRouter( MSocketRouterObserver* aObserver );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:    // Owned data
+        RSocketServ iSocketServ;
+        TSocketRouterState iState;
+        HBufC8* iReceiveBuffer;
+        CArrayPtr<CSocket>* iPeerSocketArray;
+        CArrayPtr<MBPProtocol>* iProtocolArray;
+        MSocketRouterObserver* iObserver;
+        MSocket* iHostSocket;
+        TBool iRouting;
+        CArrayPtr<CWriteEvent>* iWriteEventArray;
+        CUDPSender* iUDPSender;
+
+    private:    // Not owned
+        CProtocolTCP* iProtocolTCP;
+        CProtocolUDP* iProtocolUDP;
+    };
+
+#endif      // CSOCKETROUTER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Csocketwriter.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,251 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Socket writer
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "CSocketWriter.h"
+#include "MSocketWriterObserver.h"
+#include <in_sock.h>
+#include <badesca.h>
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+
+const TInt KServerBusyWaiting = 200000;  //200 ms delay
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::CSocketWriter
+// -----------------------------------------------------------------------------
+//
+CSocketWriter::CSocketWriter( RSocket& aSocket,
+        TInt aUDPRemotePort /*= -1*/ ) :
+    CActive( EPriorityStandard ),
+    iSocket( aSocket ),
+    iUDPRemotePort( aUDPRemotePort )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CSocketWriter::ConstructL()
+    {
+    iTransferBufferArray = new (ELeave) CDesC8ArraySeg( 10 );
+    User::LeaveIfError( iTimer.CreateLocal() );
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::NewL
+// -----------------------------------------------------------------------------
+//
+CSocketWriter* CSocketWriter::NewL( RSocket& aSocket,
+        TInt aUDPRemotePort /* = -1 */ )
+    {
+    CSocketWriter* self = CSocketWriter::NewLC( aSocket,
+        aUDPRemotePort );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::NewLC
+// -----------------------------------------------------------------------------
+//
+CSocketWriter* CSocketWriter::NewLC( RSocket& aSocket,
+        TInt aUDPRemotePort /* = -1 */ )
+    {
+    CSocketWriter* self = new( ELeave ) CSocketWriter( aSocket,
+        aUDPRemotePort );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// Destructor
+CSocketWriter::~CSocketWriter()
+    {
+    Cancel();
+    iTimer.Close();
+    delete iTransferBufferArray;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::SetObserver
+// -----------------------------------------------------------------------------
+//
+void CSocketWriter::SetObserver( MSocketWriterObserver* aObserver )
+    {
+    iObserver = aObserver;
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::IssueWriteL
+// -----------------------------------------------------------------------------
+//
+void CSocketWriter::IssueWriteL( const TDesC8& aData )
+    {
+    // slice the size of data if bigger than KWriteBufferSize
+
+    TInt dsize = aData.Size();
+
+    for ( TInt i = 0; i < dsize; i+=KWriteBufferSize )
+        {
+        if ( i + KWriteBufferSize - 1 >= dsize )
+            {
+            __ASSERT_DEBUG( i + aData.Mid( i ).Size() == dsize ,
+                User::Panic( _L( "writer" ), 100 ) );
+            iTransferBufferArray->AppendL( aData.Mid(i) );
+            }
+        else
+            {
+            iTransferBufferArray->AppendL( aData.Mid( i, KWriteBufferSize ) );
+            }
+        }
+
+    if ( !IsActive() )
+        {
+        IssueWrite();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::IssueWrite
+// -----------------------------------------------------------------------------
+void CSocketWriter::IssueWrite()
+    {
+    DEBUG_PRINT( DEBUG_STRING(
+        "CSocketWriter::IssueWrite" ) );
+    iWriteBuffer = (*iTransferBufferArray)[ 0 ];
+
+    TProtocolDesc desc;
+    iSocket.Info( desc );
+
+    if ( desc.iProtocol == KProtocolInetUdp && iUDPRemotePort > -1 )
+        {
+        // UDP
+        DEBUG_PRINT( DEBUG_STRING(
+            "CSocketWriter::IssueWrite(), UDP, remote port=%d" ),
+            iUDPRemotePort );
+
+        TInetAddr addrLocalHost( KInetAddrLoop, iUDPRemotePort );
+        iSocket.SendTo( iWriteBuffer, addrLocalHost, 0, iStatus );
+        }
+    else
+        {
+        // TCP
+        iSocket.Write( iWriteBuffer, iStatus );
+        }
+
+    SetActive();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::ContinueAfterError
+// -----------------------------------------------------------------------------
+void CSocketWriter::ContinueAfterError()
+    {
+    if ( iTransferBufferArray->Count() > 0 )
+        {
+        IssueWrite();
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::ResetTransferBuffer
+// -----------------------------------------------------------------------------
+void CSocketWriter::ResetTransferBuffer()
+    {
+    iTransferBufferArray->Reset();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::RunL
+// -----------------------------------------------------------------------------
+//
+void CSocketWriter::RunL()
+    {
+    TInt status = iStatus.Int();
+    if ( status == KErrNone )
+        {
+        if ( iWaiting )
+            {
+            DEBUG_PRINT( DEBUG_STRING(
+                "Trying to write again..." ) );
+
+            iWaiting = EFalse;
+            IssueWrite();
+            }
+        else
+            {
+            iTransferBufferArray->Delete( 0 );
+            if ( iTransferBufferArray->Count() > 0 )
+                {
+                IssueWrite();
+                }
+            else
+                {
+                iObserver->BufferUnderrunL();
+                }
+            }
+        }
+    else
+        {
+        DEBUG_PRINT( DEBUG_STRING(
+            "CSocketWriter::RunL(), iStatus=%d" ), status );
+        iObserver->WriterErrorL( status );
+        //If Socket server is busy, wait for a while and try again
+        if ( status == KErrServerBusy )
+            {
+            DEBUG_PRINT( DEBUG_STRING(
+                "Socket server busy. Waiting for a while..." ) );
+            iWaiting = ETrue;
+            iTimer.After( iStatus, KServerBusyWaiting );
+            SetActive();
+            }
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CSocketWriter::DoCancel()
+    {
+    iTimer.Cancel();
+    iSocket.CancelWrite();
+    }
+
+// -----------------------------------------------------------------------------
+// CSocketWriter::RunError
+// -----------------------------------------------------------------------------
+//
+TInt CSocketWriter::RunError( TInt aError )
+    {
+    iObserver->ObserverLeaved( aError );
+    return KErrNone;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Ctcpportlistener.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,186 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listens TCP port
+*
+*/
+
+
+// INCLUDE FILES
+#include "Ctcpportlistener.h"
+#include "MTCPPortListenerObserver.h"
+#include <in_sock.h>
+
+#define DEBUG_FILENAME "IPProxyEngine.log"
+#include "DebugPrint.h"
+
+// LOCAL CONSTANTS
+const TInt KMaxConnectionsInQueue = 8;
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::CTCPPortListener
+// -----------------------------------------------------------------------------
+//
+CTCPPortListener::CTCPPortListener( TInt aPort,
+                                    MTCPPortListenerObserver* aObserver ) :
+    CActive( EPriorityStandard ), iObserver( aObserver ), iPort( aPort )
+    {
+    __ASSERT_DEBUG( iObserver, User::Invariant() );
+    }
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::ConstructL
+// -----------------------------------------------------------------------------
+//
+void CTCPPortListener::ConstructL()
+    {
+    //Message slots needed is two per socket (read and write) + 1 for
+    //synchronous requests.
+    User::LeaveIfError(
+        iSocketServer.Connect( 2 * KMaxConnectionsInQueue + 1 ) );
+
+    User::LeaveIfError( iListeningSocket.Open(
+        iSocketServer, KAfInet, KSockStream, KProtocolInetTcp ) );
+
+    iAcceptedSocket = new (ELeave) RSocket;
+    User::LeaveIfError( iAcceptedSocket->Open( iSocketServer ) );
+
+    TSockAddr addr;
+    addr.SetPort( iPort );
+    User::LeaveIfError( iListeningSocket.Bind( addr ) );
+
+    CActiveScheduler::Add( this );
+    }
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::NewL
+// -----------------------------------------------------------------------------
+//
+CTCPPortListener* CTCPPortListener::NewL( TInt aPort,
+                                          MTCPPortListenerObserver* aObserver )
+    {
+    CTCPPortListener* self = CTCPPortListener::NewLC( aPort,
+                                                      aObserver );
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::NewLC
+// -----------------------------------------------------------------------------
+//
+CTCPPortListener* CTCPPortListener::NewLC( TInt aPort,
+                                           MTCPPortListenerObserver* aObserver )
+    {
+    CTCPPortListener* self = new( ELeave ) CTCPPortListener( aPort,
+                                                             aObserver );
+    CleanupStack::PushL( self );
+
+    self->ConstructL();
+    return self;
+    }
+
+
+// Destructor
+CTCPPortListener::~CTCPPortListener()
+    {
+    Cancel();
+    iListeningSocket.Close();
+    if ( iAcceptedSocket )
+        {
+        iAcceptedSocket->Close();
+        delete iAcceptedSocket;
+        }
+    iSocketServer.Close();
+    }
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::IssueListen
+// -----------------------------------------------------------------------------
+//
+void CTCPPortListener::IssueListen()
+    {
+    __ASSERT_DEBUG( iAcceptedSocket, User::Invariant() );
+
+    iListeningSocket.Listen( KMaxConnectionsInQueue );
+    iListeningSocket.Accept( *iAcceptedSocket, iStatus );
+    SetActive();
+
+    DEBUG_PRINT( DEBUG_STRING(
+        "CTCPPortListener::IssueListen completed, port %d" ), iPort );
+    }
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::Port
+// -----------------------------------------------------------------------------
+//
+TInt CTCPPortListener::Port() const
+    {
+    return iPort;
+    }
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::RunL
+// -----------------------------------------------------------------------------
+//
+void CTCPPortListener::RunL()
+    {
+    if ( iStatus.Int() == KErrNone )
+        {
+        // Allocate new RSocket first
+        RSocket* next = new ( ELeave ) RSocket;
+        CleanupStack::PushL( next );
+        User::LeaveIfError( next->Open( iSocketServer ) );
+        CleanupClosePushL( *next );
+
+        // temp will be passed to observer
+        RSocket* temp = iAcceptedSocket;
+
+        // Takes ownership of temp immediately
+        iObserver->ConnectionAcceptedL( temp );
+
+        CleanupStack::Pop();        // *next
+        CleanupStack::Pop( next );
+        iAcceptedSocket = next;
+
+        iListeningSocket.Accept( *iAcceptedSocket, iStatus );
+        SetActive();
+        DEBUG_PRINT( DEBUG_STRING(
+            "CTCPPortListener::RunL(), connection accepted, port %d" ), iPort );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::DoCancel
+// -----------------------------------------------------------------------------
+//
+void CTCPPortListener::DoCancel()
+    {
+    iListeningSocket.CancelAccept();
+    }
+
+// -----------------------------------------------------------------------------
+// CTCPPortListener::RunError
+// -----------------------------------------------------------------------------
+//
+TInt CTCPPortListener::RunError( TInt aError )
+    {
+    iObserver->ObserverLeaved( aError );
+    return KErrNone;
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/Ctcpportlistener.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Listens TCP port
+*
+*/
+
+
+
+#ifndef CTCPPORTLISTENER_H
+#define CTCPPORTLISTENER_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <es_sock.h>
+
+
+// FORWARD DECLARATIONS
+class MTCPPortListenerObserver;
+
+// CLASS DECLARATION
+
+/**
+*  ActiveObject which listens a TCP port.
+*/
+NONSHARABLE_CLASS( CTCPPortListener ) : public CActive
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Factory function.
+        * @param aPort TCP port to listen.
+        * @param aObserver Pointer to observer.
+        */
+        static CTCPPortListener* NewL( TInt aPort,
+                                       MTCPPortListenerObserver* aObserver );
+
+        /**
+        * Factory function.
+        * @param aPort TCP port to listen.
+        * @param aObserver Pointer to observer.
+        */
+        static CTCPPortListener* NewLC( TInt aPort,
+                                        MTCPPortListenerObserver* aObserver );
+
+        /**
+        * Destructor.
+        */
+        ~CTCPPortListener();
+
+    public: // New functions
+
+        /**
+        * Starts listening the port.
+        */
+        void IssueListen();
+
+        /**
+        * Retrieve current port number for this listener
+        * @return Port number for this listening socket
+        */
+        TInt Port() const;
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive. Pending request has been completed.
+        */
+        void RunL();
+
+        /**
+        * From CActive. Pending request has been cancelled.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive. RunL has leaved.
+        */
+        TInt RunError( TInt aError );
+
+    private:
+
+        /**
+        * Default constructor.
+        * @param aPort TCP port to listen.
+        * @param aObserver Pointer to observer.
+        */
+        CTCPPortListener( TInt aPort,
+                          MTCPPortListenerObserver* aObserver );
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+    private:    // Data
+        MTCPPortListenerObserver* iObserver;
+        TInt iPort;
+        RSocketServ iSocketServer;
+        RSocket iListeningSocket;
+        RSocket* iAcceptedSocket;
+    };
+
+#endif      // CTCPPORTLISTENER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/DebugPrint.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,230 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Debugging support
+*
+*/
+
+
+/*
+Idea:
+
+    Logging tool for developers, uniform style to write debug log to RDebug or to a File
+
+Usage:
+
+    Configuring:
+     - add to .mmp file
+        // define logging on and logging into file, file must be defined in code
+        // the macros can also be in a header file
+        // and inside ifdef if printing wanted in debug builds
+        MACRO ENABLE_DEBUG_PRINT
+        MACRO DEBUG_OUTPUT_TO_FILE
+        // this library is needed for the file logging, remove if/when not using
+        LIBRARY flogger.lib
+
+        Alternatively you may enable debug print in a header with:
+        #ifdef _DEBUG // comment this if you want logging in release build
+        #define ENABLE_DEBUG_PRINT
+        #define DEBUG_OUTPUT_TO_FILE
+        #endif // _DEBUG
+
+     - make a directory: Epoc32\Wins\c\logs\hti\
+
+    Enabling:
+     - in some source header
+        // log file name if using file logging
+        #define DEBUG_FILENAME "Example.log"
+        // include the printing macros
+        #include "DebugPrint.h"
+
+    Printing:
+
+        // normal string
+        DEBUG_PRINT( DEBUG_STRING( "Debug Print" ) );
+        // string with variables
+        DEBUG_PRINT( DEBUG_LINE( "Debug Print %d" ), 100 );
+        TInt index( 100 );
+        DEBUG_PRINT( DEBUG_STRING( "Debug Print %d" ), index );
+
+        // DEBUG_LINE automatically adds filename and linenumber to output
+        _LIT( KDebugPrintExample, "Example" );
+        DEBUG_PRINT( DEBUG_LINE( "Debug Print %S" ), &KDebugPrintExample );
+
+Known issues:
+
+    - If you use macros from .mmp file remember to abld makefile <target> to change flags from project
+    - Using lots of DEBUG_LINE macros slows down compiling due to excessive preprocessing
+
+Ideas & further development:
+
+    - make rdebug and file logging work simultaneously, currently not possible
+    - enable optional run-time configuring of debug info writing
+
+*/
+
+#ifndef __DEBUGPRINT_H__
+#define __DEBUGPRINT_H__
+
+// Debug logging is enabled, you may enable debug printing in release builds also
+#ifdef ENABLE_DEBUG_PRINT
+
+    // warn if this is a release build!!
+    #ifndef _DEBUG
+        #if defined(__VC32__)
+            #pragma message( "Warning: debug printing is on in release build!" )
+        #else // __GCC32__
+            #warning "debug printing is on in release build!"
+        #endif // __VC32__
+    #endif
+
+// no include files if no debug printing --> faster compile time
+// INCLUDES
+#include <e32std.h>
+#include <e32svr.h>
+#include <flogger.h>
+
+    /**
+     * Depending if the build is UNICODE or not, define the
+     * helper macros that display the source code filename and
+     * linenumber as a part of the debug message.
+     */
+    #ifdef _UNICODE
+        #define STRINGIZE(l) L#l
+        #define TO_NUMBER(l) STRINGIZE(l)
+        #define TOKEN_PASTING(s) L##s
+        #define TO_UNICODE(s) TOKEN_PASTING(s)
+        #define DEBUG_STR(m) TO_UNICODE(__FILE__) L"(" TO_NUMBER(__LINE__) L") : " L##m
+    #else
+        #define STRINGIZE(l) #l
+        #define TO_NUMBER(l) STRINGIZE(l)
+        #define DEBUG_STR __FILE__ "(" TO_NUMBER(__LINE__) ") : "
+    #endif // _UNICODE
+
+    /**
+     * Helper macro for defining debug strings with just the debug text.
+     */
+    #define DEBUG_STRING(s) _L(s)
+
+    /**
+     * Helper macro for defining debug string with filename and linenumber.
+     */
+    #define DEBUG_LINE(s) TPtrC((const TText *) DEBUG_STR(s))
+
+    #ifdef DEBUG_OUTPUT_TO_FILE
+
+        /**
+         * Method to handle file writing
+         */
+        inline void DebugWriteFormat(TRefByValue<const TDesC> aFmt,...)
+            {
+            _LIT(KDir, "hti");
+            #ifdef DEBUG_FILENAME
+                const static TLitC<sizeof(DEBUG_FILENAME)> KName={sizeof(DEBUG_FILENAME)-1, TO_UNICODE( DEBUG_FILENAME ) };
+            #else
+                _LIT(KName, "DebugOutput.log" );
+            #endif // DEBUG_FILENAME
+
+            // take the ellipsis parameters
+            VA_LIST args;
+            VA_START(args,aFmt);
+            RFileLogger::WriteFormat( KDir, KName, EFileLoggingModeAppend, aFmt, args );
+            VA_END(args);
+            }
+
+        /**
+         * Output to log file
+         */
+        #define DEBUG_PRINT DebugWriteFormat
+
+    #else
+        /**
+         * Output to debugger output
+         */
+        #define DEBUG_PRINT RDebug::Print
+    #endif
+
+#else   // ENABLE_DEBUG_PRINT
+
+    /**
+     * Dummy struct for checking that all DEBUG_PRINT's define string
+     * literals using space-saving DEBUG_STRING.
+     */
+    struct TEmptyDebugString { };
+
+    /**
+     * Macro for defining debug-only literal strings (empty release version)
+     */
+    #define DEBUG_STRING(s) TEmptyDebugString()
+
+    /**
+     * Macro for defining debug-only literal strings (empty release version)
+     */
+    #define DEBUG_LINE(s) TEmptyDebugString()
+
+    /// Empty debug print function for release builds.
+    inline void DEBUG_PRINT(TEmptyDebugString)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1>
+    inline void DEBUG_PRINT(TEmptyDebugString,T1)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2>
+    inline void DEBUG_PRINT(TEmptyDebugString,T1,T2)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3>
+    inline void DEBUG_PRINT(TEmptyDebugString,T1,T2,T3)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4>
+    inline void DEBUG_PRINT(TEmptyDebugString,T1,T2,T3,T4)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5>
+    inline void DEBUG_PRINT(TEmptyDebugString,T1,T2,T3,T4,T5)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6>
+    inline void DEBUG_PRINT(TEmptyDebugString,T1,T2,T3,T4,T5,T6)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6,class T7>
+    inline void DEBUG_PRINT(TEmptyDebugString,T1,T2,T3,T4,T5,T6,T7)
+        {
+        }
+
+    /// Empty debug print function for release builds.
+    template<class T1,class T2,class T3,class T4,class T5,class T6,class T7,class T8>
+    inline void DEBUG_PRINT(TEmptyDebugString,T1,T2,T3,T4,T5,T6,T7,T8)
+        {
+        }
+
+#endif  // ENABLE_DEBUG_PRINT
+
+#endif //  __DEBUGPRINT_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/IPProxyEngine.pan	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  IPProxyEngine panic codes
+*
+*/
+
+
+
+#ifndef IPPROXYENGINE_PAN
+#define IPPROXYENGINE_PAN
+
+enum TIPProxyEnginePanics
+    {
+    IPProxyEngineGeneral = 1,
+    IPProxyEngineNullSocket = 2,
+    };
+
+
+_LIT( KPanicText, "IPProxyEngine" );
+
+
+inline void Panic( TIPProxyEnginePanics aReason )
+    {
+    User::Panic( KPanicText, aReason );
+    }
+
+
+#endif // IPPROXYENGINE_PAN
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/IPProxyEngineFactory.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Factory class for IPProxyEngine
+*
+*/
+
+
+
+// INCLUDE FILES
+#include "IPProxyEngineFactory.h"
+#include "CIPProxyEngine.h"
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// IPProxyEngineFactory::IPProxyEngineFactory
+// -----------------------------------------------------------------------------
+//
+EXPORT_C MIPProxyEngine* IPProxyEngineFactory::CreateProxyEngineL( MAbstractConnection* aConnection )
+    {
+    return CIPProxyEngine::NewL( aConnection );
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MBPExpression.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MExpression interface, defines basics for all the protocol
+*                expressions
+*
+*/
+
+
+
+#ifndef MBPEXPRESSION_H
+#define MBPEXPRESSION_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <e32base.h>
+
+class MExpressionObserver;
+
+// CLASS DECLARATION
+
+/**
+*  MProtocol interface.
+*/
+NONSHARABLE_CLASS( MBPExpression )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Tries to handle the message, and informs if the msg does
+        * not belong to it.
+        *
+        * @param aData Message to parse
+        * @param aStartPos The index from where the message frame begins
+        * @param aLength Length of the message
+        * @return ETrue if the expression can handle the message,
+        *         EFalse if not.
+        */
+        virtual TBool HandleRecievedMsgL(  TDes8& aData,
+                                           TInt& aStartPos,
+                                           TInt& aLength ) = 0;
+
+        /** Virtual destructor
+        *
+        */
+        virtual ~MBPExpression() {};
+    };
+
+#endif      // MBPEXPRESSION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MBPProtocol.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,70 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  MBPProtocol interface, defines basics for all the protocols
+*
+*/
+
+
+
+#ifndef MBPPROTOCOL_H
+#define MBPPROTOCOL_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <e32base.h>
+
+#include "MSocketWriter.h"
+
+
+// CLASS DECLARATION
+
+/**
+*  MBPProtocol interface.
+*/
+NONSHARABLE_CLASS( MBPProtocol )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Tries to handle the message, responds if it can do it
+        *
+        * @param aData Data to be interpreted
+        * @param aStartPos The index from where the message frame begins
+        * @param aLength Length of the message
+        * @return ETrue if protocol can handle the msg, otherwise EFalse
+        */
+        virtual TBool HandleReceivedDataL(  TDes8& aData,
+                                            TInt& aStartPos,
+                                            TInt& aLength ) = 0;
+
+        /**
+        * Packs data to frame and sends the frame.
+        * @param aSocketWriter Object that executes the writing.
+        * @param aPeerPort Peer's TCP port.
+        * @param aOriginalPort Original TCP port.
+        * @param aData Data to be sent.
+        */
+        virtual void WriteFrameL( MSocketWriter& aSocketWriter,
+            TUint aPeerPort, TUint aOriginalPort, const TDesC8& aData ) const = 0;
+
+        /** Virtual destructor
+        *
+        */
+        virtual ~MBPProtocol() {};
+    };
+
+#endif      // MBPPROTOCOL_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MExpressionObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,63 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Callback functions for a protocol expression observer
+*
+*/
+
+
+
+#ifndef MEXPRESSIONOBSERVER_H
+#define MEXPRESSIONOBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// CLASS DECLARATION
+
+/**
+*  Events for protocol.
+*/
+NONSHARABLE_CLASS( MExpressionObserver )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Frame has started.
+        */
+        virtual void FrameStarted() = 0;
+
+        /**
+        * Frame has been parsed.
+        * @param aPort Port number parsed from received frame.
+        * @param aData Data parsed from received frame.
+        */
+        virtual void FrameParsedL(
+            TUint aPort,
+            const TDesC8& aData ) = 0;
+
+        /**
+        * Error occurred when parsing data.
+        * @param aErrorCode Error code.
+        * @param aReceivedData Whole frame that failed to be parsed.
+        */
+        virtual void ProtocolErrorL(
+            TInt aErrorCode,
+            const TDesC8& aReceivedData ) = 0;
+
+    };
+
+#endif      // MEXPRESSIONOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MExpressionObserverTCP.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Callback functions for a TCP protocol expression observer.
+*
+*/
+
+
+
+#ifndef MEXPRESSIONOBSERVERTCP_H
+#define MEXPRESSIONOBSERVERTCP_H
+
+//  INCLUDES
+#include "MExpressionObserver.h"
+
+#include <e32def.h>
+
+// CLASS DECLARATION
+
+/**
+*  Events for TCP protocol expressions (eg. TCP_OPEN, ...).
+*/
+NONSHARABLE_CLASS( MExpressionObserverTCP ) :
+            public MExpressionObserver
+    {
+
+    public: // Abstract functions
+
+        virtual void OpenLocalTCPConnectionL( TUint aPort ) = 0;
+
+        virtual void OpenListeningTCPConnectionL( TUint aPort ) = 0;
+
+        virtual void CloseTCPConnectionL( TUint aPort ) = 0;
+
+        virtual void CloseAllTCPConnections() = 0;
+    };
+
+#endif      // MEXPRESSIONOBSERVERTCP_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MExpressionObserverUDP.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Callback functions for a UDP protocol expression observer.
+*
+*/
+
+
+
+#ifndef MEXPRESSIONOBSERVERUDP_H
+#define MEXPRESSIONOBSERVERUDP_H
+
+//  INCLUDES
+#include "MExpressionObserver.h"
+
+#include <e32def.h>
+
+// CLASS DECLARATION
+
+/**
+*  Events for UDP protocol expressions (eg. UDP_OPEN, ...).
+*/
+NONSHARABLE_CLASS( MExpressionObserverUDP ) :
+            public MExpressionObserver
+    {
+
+    public: // Abstract functions
+
+        virtual void OpenLocalUDPConnectionL( TUint aPort ) = 0;
+
+        virtual void CloseUDPConnection( TUint aPort ) = 0;
+
+    };
+
+#endif      // MEXPRESSIONOBSERVERUDP_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MProtocolObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Callback functions for TCP protocol observer
+*
+*/
+
+
+
+#ifndef MPROTOCOLOBSERVER_H
+#define MPROTOCOLOBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+
+// CLASS DECLARATION
+
+/**
+*  Events for protocol.
+*/
+NONSHARABLE_CLASS( MProtocolObserver )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Frame has started.
+        */
+        virtual void FrameStarted() = 0;
+
+        /**
+        * Error occurred when parsing data.
+        * @param aErrorCode Error code.
+        * @param aReceivedData Whole frame that failed to be parsed.
+        */
+        virtual void ProtocolErrorL(
+            TInt aErrorCode,
+            const TDesC8& aReceivedData ) = 0;
+
+    };
+
+#endif      // MPROTOCOLOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MProtocolObserverTCP.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  TCP protocol specific callback functions
+*
+*/
+
+
+
+#ifndef MPROTOCOLOBSERVERTCP_H
+#define MPROTOCOLOBSERVERTCP_H
+
+//  INCLUDES
+#include <e32def.h>
+
+#include "MProtocolObserver.h"
+
+// CLASS DECLARATION
+
+/**
+*  Events for protocol.
+*/
+NONSHARABLE_CLASS( MProtocolObserverTCP ) : public MProtocolObserver
+    {
+
+    public: // Abstract functions
+
+        /**
+        * TCP Frame has been parsed.
+        * @param aPort Port number parsed from received frame.
+        * @param aData Data parsed from received frame.
+        */
+        virtual void TCPFrameParsedL(
+            TUint aPort,
+            const TDesC8& aData ) = 0;
+
+        /**
+        * Open a TCP connection to phone side port
+        * @param aPort Port number where to connect
+        */
+        virtual void OpenLocalTCPConnectionL( TUint aPort ) = 0;
+
+        /**
+        * Open a listening TCP port on the phone side
+        * @param aPort Port number where to start listening
+        */
+        virtual void OpenListeningTCPConnectionL( TUint aPort ) = 0;
+
+        /**
+        * Close a TCP connection
+        * @param aPort Remote port number to close
+        */
+        virtual void CloseTCPConnectionL( TUint aPort ) = 0;
+
+        /**
+        * Close all TCP connections from listening & connecting ports
+        */
+        virtual void CloseAllTCPConnections() = 0;
+    };
+
+#endif      // MPROTOCOLOBSERVERTCP_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MProtocolObserverUDP.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Callback functions for UDP protocol
+*
+*/
+
+
+
+#ifndef MPROTOCOLOBSERVERUDP_H
+#define MPROTOCOLOBSERVERUDP_H
+
+//  INCLUDES
+#include "MProtocolObserver.h"
+
+#include <e32def.h>
+
+// CLASS DECLARATION
+
+/**
+*  Events for protocol.
+*/
+NONSHARABLE_CLASS( MProtocolObserverUDP ) : public MProtocolObserver
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Frame has been parsed.
+        * @param aPort Port number parsed from received frame.
+        * @param aData Data parsed from received frame.
+        */
+        virtual void UDPFrameParsedL(
+            TUint aPort,
+            const TDesC8& aData ) = 0;
+
+    };
+
+#endif      // MPROTOCOLOBSERVERUDP_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MSocketReaderObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Events for socket reader
+*
+*/
+
+
+
+#ifndef MSOCKETREADEROBSERVER_H
+#define MSOCKETREADEROBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <es_sock.h>
+
+
+// CLASS DECLARATION
+
+/**
+*  Events for socket reader.
+*/
+NONSHARABLE_CLASS( MSocketReaderObserver )
+    {
+
+    public: // Abstract functions
+
+        /**
+        * Data has been received.
+        * @param aData Received data.
+        */
+        virtual void DataReceivedL( const TDesC8& aData ) = 0;
+
+        /**
+        * Notifies that error has occurred.
+        * @param aErrorCode Error code.
+        */
+        virtual void ReaderErrorL( TInt aErrorCode ) = 0;
+
+        /**
+        * Notifies that the observer has leaved while executing the callback
+        * function.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void ObserverLeaved( TInt aLeaveCode ) = 0;
+    };
+
+#endif      // MSOCKETREADEROBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MSocketRouterTestObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Observer for socket router for test purposes.
+*                This is currently the only way to get the parsed frame back to
+*                the unit test class.
+*
+*/
+
+
+
+#ifndef MSOCKETROUTERTESTOBSERVER_H
+#define MSOCKETROUTERTESTOBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+
+
+// FORWARD DECLARATIONS
+class CSocket;
+
+// CLASS DECLARATION
+
+/**
+*  Observer for socket router.
+*/
+NONSHARABLE_CLASS( MSocketRouterTestObserver )
+    {
+    public: // Abstract functions
+
+        /**
+        * Starting point of a frame has been found.
+        */
+        virtual void FrameStarted() = 0;
+
+        /**
+        * Forwards the parsed frame info to the observer
+        */
+        virtual void FrameParsedL(
+            TUint aPort,
+            const TDesC8& aData ) = 0;
+
+        /**
+        * Error occurred when parsing data.
+        * @param aErrorCode Error code.
+        * @param aReceivedData Whole frame that failed to be parsed.
+        */
+        virtual void ProtocolErrorL(
+            TInt aErrorCode,
+            const TDesC8& aReceivedData ) = 0;
+
+        /**
+        * Open a TCP connection to phone side port
+        * @param aPort Port number where to connect
+        */
+        virtual void OpenLocalTCPConnectionL( TUint aPort ) = 0;
+
+        /**
+        * Close a TCP connection to phone side port
+        * @param aPort Port number to close
+        */
+        virtual void CloseTCPConnection( TUint aPort ) = 0;
+
+    };
+
+#endif      // MSOCKETROUTERTESTOBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MSocketWriterObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Events for socket writer
+*
+*/
+
+
+
+#ifndef MSOCKETWRITEROBSERVER_H
+#define MSOCKETWRITEROBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <es_sock.h>
+
+
+// CLASS DECLARATION
+
+/**
+*  Events for socket writer.
+*/
+NONSHARABLE_CLASS( MSocketWriterObserver )
+    {
+
+    public: // Abstract functions
+        /**
+        * Notifies that error has occurred.
+        * @param aErrorCode Error code.
+        */
+        virtual void WriterErrorL( TInt aErrorCode ) = 0;
+
+        /**
+        * Notifies that all data has succesfully been written.
+        */
+        virtual void BufferUnderrunL() = 0;
+
+        /**
+        * Notifies that the observer has leaved while executing the callback
+        * function.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void ObserverLeaved( TInt aLeaveCode ) = 0;
+    };
+
+#endif      // MSOCKETWRITEROBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/IPProxyEngine/Src/MUDPSenderObserver.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Events for UDP Sender observer
+*
+*/
+
+
+
+#ifndef MUDPSENDEROBSERVER_H
+#define MUDPSENDEROBSERVER_H
+
+//  INCLUDES
+#include <e32def.h>
+#include <es_sock.h>
+
+
+// CLASS DECLARATION
+
+/**
+*  Events for socket writer.
+*/
+NONSHARABLE_CLASS( MUDPSenderObserver )
+    {
+
+    public: // Abstract functions
+        /**
+        * Notifies that error has occurred.
+        * @param aErrorCode Error code.
+        */
+        virtual void UDPSenderErrorL( TInt aErrorCode ) = 0;
+
+        /**
+        * Notifies that the observer has leaved while executing the callback
+        * function.
+        * @param aLeaveCode Leave code.
+        */
+        virtual void UDPSenderLeavedL( TInt aLeaveCode ) = 0;
+    };
+
+#endif      // MUDPSENDEROBSERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/data/200212C9.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for IP-Proxy service ECOM plugin.
+*
+*/
+
+
+// INCLUDES
+#include <ecom/registryinfo.rh>
+
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x200212C9;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB7;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x200212CA;
+                    version_no         = 1;
+                    display_name       = "IP-Proxy service";
+                    default_data       = "IPPROXY";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/group/HtiIpProxyServicePlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build description file for HtiIpProxyServicePlugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiIpProxyServicePlugin.dll
+TARGETTYPE      PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID             0x10009D8D 0x200212C9
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+//MACRO           ENABLE_DEBUG_PRINT
+//MACRO           DEBUG_OUTPUT_TO_FILE
+
+SOURCEPATH      ../IPProxyEngine/Src
+SOURCE          Ctcpportlistener.cpp
+SOURCE          CIPProxyEngine.cpp
+SOURCE          Csocketwriter.cpp
+SOURCE          CUDPSender.cpp
+SOURCE          CSocketReader.cpp
+SOURCE          Csocket.cpp
+SOURCE          Csocketrouter.cpp
+SOURCE          CProtocolTCP.cpp
+SOURCE          CProtocolUDP.cpp
+SOURCE          CExprTCPMsg.cpp
+SOURCE          CExprTCPOpen.cpp
+SOURCE          CExprTCPLstn.cpp
+SOURCE          CExprTCPClose.cpp
+SOURCE          CExprTCPCloseAll.cpp
+SOURCE          CExprUDPMsg.cpp
+SOURCE          CWriteEvent.cpp
+SOURCE          Clocaltcpconnection.cpp
+
+SOURCEPATH      ../src
+SOURCE          proxy.cpp
+SOURCE          HtiIpProxyServicePlugin.cpp
+
+USERINCLUDE     ../IPProxyEngine/Inc
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/200212C9.rss
+TARGET          HtiIpProxyServicePlugin.rsc
+END
+
+LIBRARY         ecom.lib
+LIBRARY         euser.lib
+LIBRARY         esock.lib
+LIBRARY         insock.lib
+LIBRARY         bafl.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiIpProxyServicePlugin
+*
+*/
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiIpProxyServicePlugin.mmp
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/inc/HtiIpProxyServicePlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,202 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation of ECOM plug-in service interface providing
+*                the IP-Proxy service.
+*
+*/
+
+
+#ifndef HTIIPPROXYSERVICEPLUGIN_H__
+#define HTIIPPROXYSERVICEPLUGIN_H__
+
+// INCLUDES
+#include <HtiServicePluginInterface.h>
+#include "MSocket.h"
+#include "MHostConnection.h"
+#include "MAbstractConnection.h"
+
+// FORWARD DECLARATIONS
+class MSocketObserver;
+class MIPProxyEngine;
+class CDesC8Array;
+class MHostConnectionObserver;
+
+// CLASS DECLARATION
+/**
+* IP-Proxy plugin implementation
+*/
+class CHtiIpProxyServicePlugin :
+    public CHTIServicePluginInterface,
+    public MAbstractConnection,
+    public MSocket,
+    public MHostConnection
+    {
+    public:
+        static CHtiIpProxyServicePlugin* NewL();
+
+    // Interface implementation
+
+        /**
+        * Called by HTI-framework to initialize this plugin
+        */
+        void InitL();
+
+        /**
+        * Return busy state status
+        *
+        * @return ETrue when busy otherwise EFalse
+        */
+        TBool IsBusy();
+
+        /**
+        * Process either control or data message depending on aPriority
+        *
+        * @param aMessage message with commands or data
+        * @param aPriority indicates type of aMessage
+        */
+        void ProcessMessageL( const TDesC8& aMessage,
+                              THtiMessagePriority aPriority );
+
+        /**
+        * Available memory notification from HTI-framework
+        *
+        * @param aAvailableMemory amount of available memory for message dispatching
+        */
+        void NotifyMemoryChange( TInt aAvailableMemory );
+
+    public:     // From MAbstractConnection
+        /**
+        * Get pointer to current socket instance.
+        *
+        * @return Pointer to current RSocket object. The ownership always
+        *  remains in the class which derives from this interface.
+        */
+        virtual MSocket* GetSocket();
+
+        /**
+        * Get pointer to current host connection instance.
+        *
+        * @return Pointer to current RSocket object. The ownership always
+        *  remains in the class which derives from this interface.
+        */
+        virtual MHostConnection* GetHostConnection();
+
+    public:     // From MSocket
+        /**
+        * @return RSocket object
+        */
+        virtual RSocket* GetRSocket();
+
+        /**
+        * @return Local TCP port.
+        */
+        virtual TUint LocalPort() const;
+
+        /**
+        * @return Remote TCP port.
+        */
+        virtual TUint RemotePort() const;
+
+        /**
+        * Sets observer.
+        *
+        * @param aObserver Pointer to observer.
+        */
+        virtual void SetObserver( MSocketObserver* aObserver );
+
+        /**
+        * Sets the ownership mode of RSocket object. If set ETrue
+        * the socket will be closed and RSocket object will be deleted
+        * in the destruction.
+        *
+        * @param aHasOwnership Ownership mode.
+        */
+        virtual void SetSocketOwnershipMode( TBool aHasOwnership );
+
+        /**
+        * Starts receiving data.
+        */
+        virtual void IssueRead();
+
+        /**
+        * Cancels all pending requests.
+        */
+        virtual void Cancel();
+
+        /*
+        * Returns the protocol information of the socket
+        */
+        virtual void SocketInfo( TProtocolDesc& aDesc ) const;
+
+        /*
+        * Is this a UDP socket
+        */
+        virtual TBool IsUDP() const;
+
+    public:     // From MSocketWriter
+        /**
+        * Writes data to socket.
+        * @param aData Data to be written.
+        */
+        virtual void WriteL( const TDesC8& aData );
+
+    public:     // From MHostConnection
+        /**
+        * Starts connecting procedure to host.
+        */
+        virtual void IssueConnectL();
+
+        /**
+        * Starts disconnection procedure.
+        */
+        virtual void IssueDisconnect();
+
+        /**
+        * Sets observer.
+        *
+        * @param aObserver Pointer to observer.
+        */
+        virtual void SetObserver( MHostConnectionObserver* aObserver );
+
+        /**
+        * @return Connection state.
+        */
+        virtual TBool IsConnected();
+
+        /**
+        * @return Pointer to current RSocket object. The ownership always
+        *
+        * remains in this class.
+        */
+        virtual RSocket* Socket();
+
+
+    protected:
+        CHtiIpProxyServicePlugin();
+        virtual ~CHtiIpProxyServicePlugin();
+
+        void ConstructL();
+
+    private:
+        MSocketObserver* iSocketObserver;
+        MHostConnectionObserver* iHostObserver;
+        MIPProxyEngine* iProxyEngine;
+        CDesC8Array* iOutgoingArray;
+        TBool iBusy;
+        TBool iConnected;
+    };
+
+#endif // HTIIPPROXYSERVICEPLUGIN_H__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/src/HtiIpProxyServicePlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,363 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiIpProxyServicePlugin implementation
+*
+*/
+
+
+// INCLUDE FILES
+#include "HtiIpProxyServicePlugin.h"
+#include <HtiDispatcherInterface.h>
+#include <HtiLogging.h>
+#include <badesca.h>
+#include <in_sock.h>
+#include "MSocketObserver.h"
+#include "Mhostconnectionobserver.h"
+#include "CIPProxyEngine.h"
+
+// CONSTANTS
+const static TUid KIpProxyServiceUid = { 0x10210CD3 };
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// Create instance of concrete ECOM interface implementation
+CHtiIpProxyServicePlugin* CHtiIpProxyServicePlugin::NewL()
+    {
+    CHtiIpProxyServicePlugin* self = new( ELeave ) CHtiIpProxyServicePlugin;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+// Constructor
+CHtiIpProxyServicePlugin::CHtiIpProxyServicePlugin() :
+    iSocketObserver( NULL ),
+    iHostObserver( NULL ),
+    iProxyEngine( NULL ),
+    iOutgoingArray( NULL ),
+    iBusy( EFalse ),
+    iConnected( EFalse )
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin" );
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin" );
+    }
+
+CHtiIpProxyServicePlugin::~CHtiIpProxyServicePlugin()
+    {
+    HTI_LOG_FUNC_IN( "~CHtiIpProxyServicePlugin" );
+
+    if ( iProxyEngine )
+        {
+        iProxyEngine->StopListening();
+        }
+    delete iProxyEngine;
+    delete iOutgoingArray;
+
+    HTI_LOG_FUNC_OUT( "~CHtiIpProxyServicePlugin" );
+    }
+
+// Second phase construction.
+void CHtiIpProxyServicePlugin::ConstructL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::ConstructL" );
+
+    iOutgoingArray = new( ELeave ) CDesC8ArraySeg( 10 );
+    iProxyEngine = CIPProxyEngine::NewL( this );
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::ConstructL" );
+    }
+
+
+void CHtiIpProxyServicePlugin::InitL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::InitL" );
+
+    if ( iProxyEngine )
+        {
+        iProxyEngine->StartListening();
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::InitL" );
+    }
+
+TBool CHtiIpProxyServicePlugin::IsBusy()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::IsBusy" );
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::IsBusy" );
+    return iBusy;
+    }
+
+void CHtiIpProxyServicePlugin::ProcessMessageL( const TDesC8& aMessage,
+                                                THtiMessagePriority /* aPriority */ )
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::ProcessMessageL" );
+
+    iBusy = ETrue;
+
+    __ASSERT_ALWAYS( iSocketObserver, User::Panic( _L ( "IP-Proxy ECom-plugin" ), KErrBadHandle ) );
+    iSocketObserver->DataReceivedL( this, aMessage );
+
+    iBusy = EFalse;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::ProcessMessageL" );
+    }
+
+void CHtiIpProxyServicePlugin::NotifyMemoryChange( TInt aAvailableMemory )
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::NotifyMemoryChange" );
+
+    iBusy = ETrue;
+
+    TInt count = iOutgoingArray->Count();
+    if ( !count )
+        {
+        // No outgoing data
+        return;
+        }
+
+    // Calculate needed outgoing buffer size
+    TInt i = 0;
+    TInt neededSize = 0;
+    for ( ; i < count; ++i )
+        {
+        TInt size = ( *iOutgoingArray )[i].Size();
+        if ( neededSize + size <= aAvailableMemory )
+            {
+            neededSize += size;
+            }
+        }
+
+    if ( !neededSize )
+       {
+       // Not enough memory
+       return;
+       }
+
+    // Create an outgoing buffer and join as many buffers as possible
+    HBufC8* message = HBufC8::New( neededSize );
+    if ( !message )
+        {
+        // Not enough memory
+        return;
+        }
+
+    TPtr8 messagePtr( message->Des() );
+    for ( TInt j = 0; j < i; ++j )
+        {
+        messagePtr.Append( ( *iOutgoingArray )[j] );
+        }
+
+    // Dispatch message to HTI-Framework which takes the ownership of message
+    TInt err = iDispatcher->DispatchOutgoingMessage( message, KIpProxyServiceUid );
+    if ( err == KErrNone )
+        {
+        message = NULL;
+        iOutgoingArray->Delete( 0, i );
+        iDispatcher->RemoveMemoryObserver( this );
+        }
+    else if ( err != KErrNoMemory )
+        {
+        delete message;
+        iDispatcher->RemoveMemoryObserver( this );
+
+        __ASSERT_ALWAYS( iHostObserver, User::Panic( _L ( "IP-Proxy ECom-plugin" ), KErrBadHandle ) );
+        TRAP( err, iHostObserver->HostConnectionErrorL( err ) );
+        }
+
+    iBusy = EFalse;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::NotifyMemoryChange" );
+    }
+
+MSocket* CHtiIpProxyServicePlugin::GetSocket()
+    {
+    return this;
+    }
+
+MHostConnection* CHtiIpProxyServicePlugin::GetHostConnection()
+    {
+    return this;
+    }
+
+RSocket* CHtiIpProxyServicePlugin::GetRSocket()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::GetRSocket" );
+
+    RSocket* KSocket = NULL;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::GetRSocket" );
+    return KSocket;
+    }
+
+TUint CHtiIpProxyServicePlugin::LocalPort() const
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::LocalPort" );
+
+    const TUint KLocalPort = 0;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::LocalPort" );
+    return KLocalPort;
+    }
+
+TUint CHtiIpProxyServicePlugin::RemotePort() const
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::RemotePort" );
+
+    const TUint KRemotePort = 0;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::RemotePort" );
+    return KRemotePort;
+    }
+
+void CHtiIpProxyServicePlugin::SetObserver( MSocketObserver* aObserver )
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::SetObserver" );
+
+    iSocketObserver = aObserver;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::SetObserver" );
+    }
+
+void CHtiIpProxyServicePlugin::SetSocketOwnershipMode( TBool /* aHasOwnership */ )
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::SetSocketOwnershipMode" );
+
+    /* Empty implementation */
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::SetSocketOwnershipMode" );
+    }
+
+void CHtiIpProxyServicePlugin::IssueRead()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::IssueRead" );
+
+    /* Empty implementation */
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::IssueRead" );
+    }
+
+void CHtiIpProxyServicePlugin::Cancel()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::Cancel" );
+
+    /* Empty implementation */
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::Cancel" );
+    }
+
+void CHtiIpProxyServicePlugin::SocketInfo( TProtocolDesc& aDesc ) const
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::SocketInfo" );
+
+    aDesc.iProtocol = KProtocolInetTcp;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::SocketInfo" );
+    }
+
+TBool CHtiIpProxyServicePlugin::IsUDP() const
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::IsUDP" );
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::IsUDP" );
+    return EFalse;
+    }
+
+void CHtiIpProxyServicePlugin::WriteL( const TDesC8& aData )
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::WriteL" );
+
+    iBusy = ETrue;
+
+    // Dispatcher takes ownership of the message if no error has occured
+    HBufC8* message = aData.AllocL();
+    TInt err = iDispatcher->DispatchOutgoingMessage( message, KIpProxyServiceUid );
+    if ( err != KErrNone && err != KErrNoMemory )
+        {
+        // Some error occured while dispatching the message
+        delete message;
+        __ASSERT_ALWAYS( iHostObserver, User::Panic( _L ( "IP-Proxy ECom-plugin" ), KErrBadHandle ) );
+        iHostObserver->HostConnectionErrorL( err );
+        }
+    else if ( err == KErrNoMemory )
+        {
+        // No memory was available so add message to queue
+        delete message;
+        iOutgoingArray->AppendL( aData.Mid( 0 ) );
+        iDispatcher->AddMemoryObserver( this );
+        }
+
+    iBusy = EFalse;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::WriteL" );
+    }
+
+void CHtiIpProxyServicePlugin::IssueConnectL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::IssueConnectL" );
+
+    iConnected = ETrue;
+
+    __ASSERT_ALWAYS( iHostObserver, User::Panic( _L ( "IP-Proxy ECom-plugin" ), KErrBadHandle ) );
+    iHostObserver->ConnectionEstablishedL();
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::IssueConnectL" );
+    }
+
+void CHtiIpProxyServicePlugin::IssueDisconnect()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::IssueDisconnect" );
+
+    __ASSERT_ALWAYS( iSocketObserver, User::Panic( _L ( "IP-Proxy ECom-plugin" ), KErrBadHandle ) );
+    TRAP_IGNORE( iSocketObserver->DisconnectedL( this ) );
+
+    iConnected = EFalse;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::IssueDisconnect" );
+    }
+
+void CHtiIpProxyServicePlugin::SetObserver( MHostConnectionObserver* aObserver )
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::SetObserver 2" );
+
+    iHostObserver = aObserver;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::SetObserver 2" );
+    }
+
+TBool CHtiIpProxyServicePlugin::IsConnected()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::IsConnected" );
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::IsConnected" );
+    return iConnected;
+    }
+
+RSocket* CHtiIpProxyServicePlugin::Socket()
+    {
+    HTI_LOG_FUNC_IN( "CHtiIpProxyServicePlugin::Socket" );
+
+    RSocket* KSocket = NULL;
+
+    HTI_LOG_FUNC_OUT( "CHtiIpProxyServicePlugin::Socket" );
+    return KSocket;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiIpProxyServicePlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy for IP-Proxy service plugin dll
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+
+#include "HtiIpProxyServicePlugin.h"
+
+const TImplementationProxy ImplementationTable[] =
+    {
+    IMPLEMENTATION_PROXY_ENTRY( 0x200212CA,  CHtiIpProxyServicePlugin::NewL )
+    };
+
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+    {
+    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+    return ImplementationTable;
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiStifTfServicePlugin/data/10210CC2.rss	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,66 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HTI service plugin for controlling STIF Test Framework
+*
+*/
+
+
+
+//  RESOURCE IDENTIFIER
+
+//  INCLUDES
+#include <ecom/registryinfo.rh>
+
+//  CONSTANTS
+
+//  MACROS
+
+
+//  RESOURCE DEFINITIONS
+// -----------------------------------------------------------------------------
+//
+// theInfo
+// ECom registry info resource.
+//
+// -----------------------------------------------------------------------------
+//
+
+RESOURCE REGISTRY_INFO theInfo
+    {
+    // UID for the DLL
+    dll_uid = 0x10210CC2;
+    // Declare array of interface info
+    interfaces =
+        {
+        INTERFACE_INFO
+            {
+            // UID of interface that is implemented
+            interface_uid = 0x1020DEB7;
+            implementations =
+                {
+                IMPLEMENTATION_INFO
+                    {
+                    implementation_uid = 0x10210CC3;
+                    version_no         = 1;
+                    display_name       = "STIF TF Control Service";
+                    default_data       = "STIF";
+                    opaque_data        = "";
+                    }
+                };
+            }
+        };
+    }
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiStifTfServicePlugin/group/HtiStifTfServicePlugin.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HTI service plugin for controlling STIF Test Framework
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiStifTfServicePlugin.dll
+TARGETTYPE      PLUGIN
+
+// ECom Dll recognition UID followed by the unique UID for this dll
+UID             0x10009D8D 0x10210CC2
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          proxy.cpp
+SOURCE          HtiStifTfServicePlugin.cpp
+SOURCE          HtiStifTfIf.cpp
+
+USERINCLUDE     ../inc
+OS_LAYER_SYSTEMINCLUDE
+
+START RESOURCE  ../data/10210CC2.rss
+TARGET          HtiStifTfServicePlugin.rsc
+END
+
+LIBRARY         bafl.lib
+LIBRARY         charconv.lib
+LIBRARY         ecom.lib
+LIBRARY         efsrv.lib
+LIBRARY         euser.lib
+LIBRARY         stiftfwif.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiStifTfServicePlugin/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiStifTfServicePlugin
+*
+*/
+
+
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+HtiStifTfServicePlugin.mmp
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiStifTfServicePlugin/inc/HtiStifTfIf.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,290 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Defines the class that controls STIF Test Framework through
+*                the STIF TF interface.
+*
+*/
+
+
+
+#ifndef HTISTIFTFIF_H
+#define HTISTIFTFIF_H
+
+//  INCLUDES
+#include <StifTFwIf.h>
+#include <HtiServicePluginInterface.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CDesC8ArrayFlat;
+class CHtiStifTfServicePlugin;
+class CConsoleBase;
+
+// CLASS DECLARATION
+/**
+*  Container class for test modules' test infos.
+*  One instance of this class contains the test infos of one test module in
+*  an RPointerArray and the name of the test module as HBufC.
+*
+*/
+class CHtiTestModuleCaseInfos : public CBase
+    {
+    public: // Constuctors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHtiTestModuleCaseInfos* NewL( const TDesC& aModuleName );
+
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHtiTestModuleCaseInfos* NewLC( const TDesC& aModuleName );
+
+
+        /**
+        * Destructor.
+        */
+        ~CHtiTestModuleCaseInfos();
+
+    public:
+        /**
+        * Compares the order of two CHtiTestMoudleCaseInfos objects.
+        * Order is based on the alphabetical order of the module name.
+        * @param aFirst reference to the first instance to compare
+        * @param aSecond reference to the second instance to compare
+        * @return Positive if the first module's name is greater than the
+        *         second module's name. Negative if the first module's name is
+        *         less than the second module's name. Zero if names are equal.
+        */
+        static TInt Compare( const CHtiTestModuleCaseInfos& aFirst,
+                             const CHtiTestModuleCaseInfos& aSecond );
+
+        /**
+        * Compares the equality of two CHtiTestMoudleCaseInfos objects.
+        * Equality is based on the name of the module.
+        * @param aFirst reference to the first instance to compare
+        * @param aSecond reference to the second instance to compare
+        * @return ETrue if the module names are equal. EFalse otherwise.
+        */
+        static TBool Match(  const CHtiTestModuleCaseInfos& aFirst,
+                             const CHtiTestModuleCaseInfos& aSecond );
+
+    private:
+
+        CHtiTestModuleCaseInfos();
+
+        void ConstructL( const TDesC& aModuleName );
+
+    public: // Data
+
+        // The name of the test module whose test infos this instance contains
+        HBufC* iModuleName;
+
+        // An array of CTestInfo objects (one per test case)
+        RPointerArray<CTestInfo> iTestInfos;
+
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  Implements the STIF Test Framework interface functions.
+*/
+class CHtiStifTfIf : public CStifTFwIf
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHtiStifTfIf* NewL( CHtiStifTfServicePlugin* aPlugin );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CHtiStifTfIf();
+
+    public: // New functions
+
+        /**
+        * Called when there is a message to be processed by this service.
+        * @param aMessage message body destinated to the servive
+        * @param aPriority message priority
+        */
+        void ProcessMessageL( const TDesC8& aMessage,
+            THtiMessagePriority aPriority );
+
+        /**
+        * Called by the plugin to tell the service how much memory is
+        * available for messages in the message queue.
+        * @param aAvailableMemory amount of currently available memory
+        *        in the message queue
+        */
+        void NotifyMemoryChange( TInt aAvailableMemory );
+
+        /**
+        * Sets the dispatcher to send outgoing messages to.
+        * @param aDispatcher pointer to dispatcher instance
+        */
+        void SetDispatcher( MHtiDispatcher* aDispatcher );
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+
+    protected:  // Functions from base classes
+
+        // virtual functions from CStifTFwIf
+        /**
+        * Function that is called when test execution is finished.
+        * @param aTestId id of the test case
+        * @param aTestExecutionResult result of test execution
+        * @param aTestResult actual result of the test case
+        */
+        void TestCompleted( TInt aTestId,
+                            TInt aTestExecutionResult,
+                            TTestResult& aTestResult );
+
+        /**
+        * Function for sending message to ATS.
+        * @param aMessage message to be sent
+        */
+        void AtsSend( const TDesC& aMessage );
+
+        /**
+        * Get device identifier.
+        * Should be overridden to make them unique among slaves.
+        * Returns default value for every slave otherwise.
+        * @return the device ID
+        */
+        TUint16 DevId(){ return iDevId; };
+
+        /**
+        * Function is called when test case prints.
+        */
+        void Print( TInt aTestId, TTestProgress& aProgress );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CHtiStifTfIf();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL( CHtiStifTfServicePlugin* aPlugin );
+
+        // Private helper methods.
+        void HandleOpenCmdL();
+
+        void HandleCloseCmdL();
+
+        void HandleLoadModuleCmdL();
+
+        void HandleUnloadModuleCmdL();
+
+        void HandleListCasesCmdL();
+
+        void HandleStartCaseCmdL();
+
+        void HandleCancelCaseCmdL();
+
+        void HandlePauseCaseCmdL();
+
+        void HandleResumeCaseCmdL();
+
+        void HandleAddCaseFileCmdL();
+
+        void HandleRemoveCaseFileCmdL();
+
+        void HandleCaseMsgCmdL();
+
+        void HandleSetDevIdCmdL();
+
+        void HandleSetAttributeCmdL();
+
+        void LoadTestCaseInfosL();
+
+        void LoadTestCaseInfosL( TDesC& aModuleName );
+
+        void ParseParametersL( const TDesC8& aCommand );
+
+        TInt SendResponseMsg( const TDesC8& aMsg,
+                              const TUint8 aCommandId = 0 );
+
+        TInt SendErrorResponseMsg( TInt aErrorCode,
+                                   const TDesC8& aErrorDescription,
+                                   const TUint8 aCommandId = 0 );
+
+        TInt IndexByModuleName( const TDesC& aModuleName );
+
+        CTestInfo* GetCaseInfoL( TInt aCaseIndex );
+
+
+    public:     // Data
+
+        // Flag telling if the service is busy processing a message
+        TBool iIsBusy;
+
+    protected:  // Data
+
+    private:    // Data
+
+        // ID of the last received command
+        TUint8 iCommandId;
+
+        // Array container for parameters of the last received message
+        CDesC8ArrayFlat* iParameters;
+
+        // The message dispatcher interface
+        MHtiDispatcher* iDispatcher;
+
+        // Container for the response message to be dispatched out
+        HBufC8* iMessage;
+
+        // Error code in the outgoing error message
+        TInt iErrorCode;
+
+        // Flag telling if STIF TF has been opened
+        TBool iStifTfOpen;
+
+        // The device ID
+        TUint16 iDevId;
+
+        // An array holding the test case infos of all loaded test modules
+        RPointerArray<CHtiTestModuleCaseInfos> iLoadedInfos;
+
+        // Pointer to the service plugin instance - this is not owned
+        CHtiStifTfServicePlugin* iPlugin;
+
+        // Pointer to the HTI console
+        CConsoleBase* iConsole;
+    };
+
+#endif      // HTISTIFTFIF_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiStifTfServicePlugin/inc/HtiStifTfServicePlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,125 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Defines the ECom plugin for HTI STIF Test Framework control
+*                service.
+*
+*/
+
+
+
+#ifndef HTISTIFTFSERVICEPLUGIN_H
+#define HTISTIFTFSERVICEPLUGIN_H
+
+//  INCLUDES
+#include <HtiServicePluginInterface.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CHtiStifTfIf;
+
+// CLASS DECLARATION
+
+/**
+*  The ECom plugin for HTI STIF Test Framework control service.
+*
+*/
+class CHtiStifTfServicePlugin : public CHTIServicePluginInterface
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHtiStifTfServicePlugin* NewL();
+
+    public: // New functions
+
+    public: // Functions from base classes
+
+        /**
+        * From CHTIServicePluginInterface
+        * Called by the HTI Framework when sending message to this service.
+        * @param aMessage message body destinated to a servive
+        * @param aPriority message priority
+        */
+        void ProcessMessageL( const TDesC8& aMessage,
+            THtiMessagePriority aPriority );
+
+        /**
+        * From CHTIServicePluginInterface
+        * Called by HTI Framework to tell the service how much memory is
+        * available for messages in the message queue.
+        * @param aAvailableMemory amount of currently available memory
+        *        in the message queue
+        */
+        void NotifyMemoryChange( TInt aAvailableMemory );
+
+        /**
+        * From CHTIServicePluginInterface
+        * Indicates to HTI Framework whether the plugin is ready to process
+        * a new message or if it's busy processing previous message.
+        */
+        TBool IsBusy();
+
+    protected:  // New functions
+
+        /**
+        * C++ default constructor.
+        */
+        CHtiStifTfServicePlugin();
+
+        /**
+        * 2nd phase constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CHtiStifTfServicePlugin();
+
+
+    protected:  // Functions from base classes
+
+    private:
+
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+        // Instance of the class derived from CStifTFwIf
+        CHtiStifTfIf* iStifTfInterface;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+
+    };
+
+#endif      // HTISTIFTFSERVICEPLUGIN_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiStifTfServicePlugin/src/HtiStifTfIf.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2092 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implements the functions to control STIF Test Framework
+*                through the STIF TF interface.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include <badesca.h>
+#include <bautils.h>
+#include <charconv.h>
+#include <e32cons.h>
+#include <HtiLogging.h>
+#include "HtiStifTfIf.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+const static TUid KStifTfServiceUid = { 0x10210CC3 };
+
+enum TStifTfCommands
+    {
+    ECmdOpen            = 0x01,
+    ECmdClose           = 0x02,
+    ECmdLoadModule      = 0x03,
+    ECmdUnloadModule    = 0x04,
+    ECmdListCases       = 0x05,
+    ECmdStartCase       = 0x06,
+    ECmdCancelCase      = 0x07,
+    ECmdPauseCase       = 0x08,
+    ECmdResumeCase      = 0x09,
+    ECmdAddCaseFile     = 0x0A,
+    ECmdRemoveCaseFile  = 0x0B,
+    ECmdCaseMsg         = 0x0C,
+    ECmdSetDevId        = 0x0D,
+    ECmdTestCompleted   = 0x0E,
+    ECmdAtsMessage      = 0x0F,
+    ECmdSetAttribute    = 0x10
+    };
+
+_LIT8( KParameterDelimiter, "|" );
+
+// NOTE: Max length for error description is defined
+// in HtiDispatcherInterface.h (currently 118).
+_LIT8( KErrorStifTfNotOpen, "ERROR: STIF TF is not open" );
+_LIT8( KErrorOpen, "ERROR: Failed to open STIF TF" );
+_LIT8( KErrorAlreadyOpen, "ERROR: STIF TF is already open" );
+_LIT8( KErrorClose, "ERROR: Failed to close STIF TF" );
+_LIT8( KErrorUnknownCmd, "ERROR: Unknown STIF TF command" );
+_LIT8( KErrorNoCmd, "ERROR: No command given" );
+_LIT8( KErrorParameterMissing, "ERROR: Mandatory parameter missing" );
+_LIT8( KErrorParameterTooLong, "ERROR: Parameter too long" );
+_LIT8( KErrorTooManyParameters, "ERROR: Too many parameters" );
+_LIT8( KErrorNoMemory, "ERROR: Memory allocation failure" );
+_LIT8( KErrorLoadModule, "ERROR: Load Module failed" );
+_LIT8( KErrorUnloadModule, "ERROR: Unload Module failed" );
+_LIT8( KErrorInvalidCaseNumber, "ERROR: Invalid test case number parameter" );
+_LIT8( KErrorModuleNotLoaded, "ERROR: Given test module is not loaded" );
+_LIT8( KErrorGetTestCases, "ERROR: Failed to get test cases from module" );
+_LIT8( KErrorGetTestCaseInfos, "ERROR: Failed to get test case infos" );
+_LIT8( KErrorStartTestCase, "ERROR: Failed to start test case" );
+_LIT8( KErrorCancelTestCase, "ERROR: Failed to cancel test case" );
+_LIT8( KErrorPauseTestCase, "ERROR: Failed to pause test case" );
+_LIT8( KErrorResumeTestCase, "ERROR: Failed to resume test case" );
+_LIT8( KErrorInvalidDeviceId, "ERROR: Invalid device ID parameter" );
+_LIT8( KErrorAddCaseFile, "ERROR: Add Case File failed" );
+_LIT8( KErrorRemoveCaseFile, "ERROR: Remove Case File failed" );
+_LIT8( KErrorFileServer, "ERROR: Failed to connect to file server" );
+_LIT8( KErrorCaseFileNotFound, "ERROR: Given test case file was not found" );
+_LIT8( KErrorIniFileNotFound, "ERROR: Given ini-file was not found" );
+_LIT8( KErrorCaseMessage, "ERROR: Test case message sending failed" );
+_LIT8( KErrorCharConv, "ERROR: Character conversion failed" );
+_LIT8( KErrorInvalidAttributeId, "ERROR: Invalid attribute id parameter" );
+_LIT8( KErrorSetAttribute, "ERROR: Failed to set attribute" );
+_LIT8( KErrorUnknown, "ERROR: Unspecified error occured" );
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::CHtiStifTfIf
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CHtiStifTfIf::CHtiStifTfIf():iIsBusy( EFalse ),
+                             iMessage( NULL ),
+                             iErrorCode( 0 ),
+                             iStifTfOpen( EFalse ),
+                             iDevId( KDefaultDevId ),
+                             iConsole( NULL )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::ConstructL( CHtiStifTfServicePlugin* aPlugin )
+    {
+    iCommandId = 0;
+    iParameters = new (ELeave) CDesC8ArrayFlat( 5 );
+    iPlugin = aPlugin;
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CHtiStifTfIf* CHtiStifTfIf::NewL( CHtiStifTfServicePlugin* aPlugin )
+    {
+    CHtiStifTfIf* self = new( ELeave ) CHtiStifTfIf;
+    CleanupStack::PushL( self );
+    self->ConstructL( aPlugin );
+    CleanupStack::Pop();
+    return self;
+    }
+
+
+// Destructor
+CHtiStifTfIf::~CHtiStifTfIf()
+    {
+    if ( iParameters )
+        {
+        iParameters->Reset();
+        }
+    delete iParameters;
+    iLoadedInfos.ResetAndDestroy();
+    iLoadedInfos.Close();
+    delete iMessage;
+    if ( iStifTfOpen ) Close();
+    iPlugin = NULL;  // Not owned, so not deleted.
+    iConsole = NULL; // Not owned, so not deleted.
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::ProcessMessageL
+// Interpretes the message and calls appropriate command handling method.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::ProcessMessageL( const TDesC8& aMessage,
+    THtiMessagePriority /*aPriority*/)
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::ProcessMessageL" );
+    HTI_LOG_FORMAT( "Message length = %d", aMessage.Length() );
+
+    if ( iIsBusy )
+        {
+        HTI_LOG_TEXT( "Plugin is busy - leaving" );
+        User::Leave( KErrInUse );
+        }
+
+    iIsBusy = ETrue;
+
+    if ( aMessage.Length() < 1 )
+        {
+        User::LeaveIfError(
+            SendErrorResponseMsg( KErrArgument, KErrorNoCmd ) );
+        return;
+        }
+
+    iCommandId = aMessage[0];
+    HTI_LOG_FORMAT( "Command = %d", iCommandId );
+
+    TRAPD( err, ParseParametersL( aMessage ) );
+
+    if ( err == KErrNoMemory )
+        {
+        User::LeaveIfError( SendErrorResponseMsg( err, KErrorNoMemory ) );
+        return;
+        }
+
+    else if ( err )
+        {
+        User::LeaveIfError(
+            SendErrorResponseMsg( KErrGeneral, KErrorUnknown ) );
+        return;
+        }
+
+    // If STIF TF is not open, any other command than OPEN returns KErrNotReady
+    if ( !iStifTfOpen )
+        {
+        if ( iCommandId == ECmdOpen )
+            {
+            HandleOpenCmdL();
+            return;
+            }
+        else
+            {
+            User::LeaveIfError(
+                SendErrorResponseMsg( KErrNotReady, KErrorStifTfNotOpen ) );
+            return;
+            }
+        }
+
+
+    // Go through the rest of the commands
+    if ( iCommandId == ECmdLoadModule )
+        {
+        HandleLoadModuleCmdL();
+        }
+
+    else if ( iCommandId == ECmdUnloadModule )
+        {
+        HandleUnloadModuleCmdL();
+        }
+
+    else if ( iCommandId == ECmdListCases )
+        {
+        HandleListCasesCmdL();
+        }
+
+    else if ( iCommandId == ECmdStartCase )
+        {
+        HandleStartCaseCmdL();
+        }
+
+    else if ( iCommandId == ECmdCancelCase )
+        {
+        HandleCancelCaseCmdL();
+        }
+
+    else if ( iCommandId == ECmdPauseCase )
+        {
+        HandlePauseCaseCmdL();
+        }
+
+    else if ( iCommandId == ECmdResumeCase )
+        {
+        HandleResumeCaseCmdL();
+        }
+
+    else if ( iCommandId == ECmdAddCaseFile )
+        {
+        HandleAddCaseFileCmdL();
+        }
+
+    else if ( iCommandId == ECmdRemoveCaseFile )
+        {
+        HandleRemoveCaseFileCmdL();
+        }
+
+    else if ( iCommandId == ECmdCaseMsg )
+        {
+        HandleCaseMsgCmdL();
+        }
+
+    else if ( iCommandId == ECmdSetDevId )
+        {
+        HandleSetDevIdCmdL();
+        }
+
+    else if ( iCommandId == ECmdSetAttribute )
+        {
+        HandleSetAttributeCmdL();
+        }
+
+    else if ( iCommandId == ECmdClose )
+        {
+        HandleCloseCmdL();
+        }
+
+    else if ( iCommandId == ECmdOpen )
+        {
+        User::LeaveIfError(
+            SendErrorResponseMsg( KErrArgument, KErrorAlreadyOpen ) );
+        }
+
+    else
+        {
+        User::LeaveIfError(
+            SendErrorResponseMsg( KErrArgument, KErrorUnknownCmd ) );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::ProcessMessageL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleOpenCmdL
+// Handles opening of the STIF Test Framework.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleOpenCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleOpenCmdL" );
+
+    TInt err = KErrNone;
+
+    // OPEN command has 1 optional parameter (test framework ini-file)
+    if ( iParameters->Count() == 0 )
+        {
+        err = Open();
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorOpen );
+            return;
+            }
+
+        iStifTfOpen = ETrue;
+        SendResponseMsg( _L8( "OK" ) );
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        TBuf<KMaxFileName> iniFilePath;
+        if ( (*iParameters)[0].Length() > iniFilePath.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+
+        iniFilePath.Copy( (*iParameters)[0] );
+
+        RFs fsSession;
+        err = fsSession.Connect();
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorFileServer );
+            return;
+            }
+
+        if ( !( BaflUtils::FileExists( fsSession, iniFilePath ) ) )
+            {
+            SendErrorResponseMsg( KErrNotFound, KErrorIniFileNotFound );
+            fsSession.Close();
+            return;
+            }
+
+        fsSession.Close();
+
+        err = Open( iniFilePath );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorOpen );
+            return;
+            }
+
+        // Load the test case infos of all currently loaded test
+        // modules (modules listed in the given ini-file).
+        TRAP( err, LoadTestCaseInfosL() );
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorGetTestCaseInfos );
+            return;
+            }
+
+        iStifTfOpen = ETrue;
+        SendResponseMsg( _L8( "OK" ) );
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleOpenCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleCloseCmdL
+// Closes the STIF Test Framework.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleCloseCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleCloseCmdL" );
+
+    TInt err = KErrNone;
+
+    // CLOSE command has no parameters
+    if ( iParameters->Count() == 0 )
+        {
+        err = Close();
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorClose );
+            return;
+            }
+
+        iStifTfOpen = EFalse;
+        iLoadedInfos.ResetAndDestroy(); // empty the cache of test case infos
+        SendResponseMsg( _L8( "OK" ) );
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleCloseCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleLoadModuleCmdL
+// Loads a STIF TF test module (optionally with ini-file).
+// Also calls the LoadTestCaseInfosL helper method to load the test case info
+// objects from the test module.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleLoadModuleCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleLoadModuleCmdL" );
+
+    TInt err = KErrNone;
+
+    TBuf<KMaxFileName> moduleName;
+    TBuf<KMaxFileName> iniFilePath;
+
+    // LOAD_MODULE command has 1 mandatory parameter (module name)
+    // and 1 optional parameter (ini-file path).
+    if ( iParameters->Count() == 0 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        if ( (*iParameters)[0].Length() > moduleName.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+        moduleName.Copy( (*iParameters)[0] );
+        err = AddTestModule( moduleName );
+        }
+
+    else if ( iParameters->Count() == 2 )
+        {
+        if ( (*iParameters)[0].Length() > moduleName.MaxLength() ||
+             (*iParameters)[1].Length() > iniFilePath.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+
+        moduleName.Copy( (*iParameters)[0] );
+        iniFilePath.Copy( (*iParameters)[1] );
+
+        RFs fsSession;
+        err = fsSession.Connect();
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorFileServer );
+            return;
+            }
+
+        if ( !( BaflUtils::FileExists( fsSession, iniFilePath ) ) )
+            {
+            SendErrorResponseMsg( KErrNotFound, KErrorIniFileNotFound );
+            fsSession.Close();
+            return;
+            }
+
+        fsSession.Close();
+
+        err = AddTestModule( moduleName, iniFilePath );
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        return;
+        }
+
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "LoadModule: Error %d", err );
+        SendErrorResponseMsg( err, KErrorLoadModule );
+        }
+
+    else
+        {
+        TRAP( err, LoadTestCaseInfosL( moduleName ) );
+
+        if ( err )
+            {
+            HTI_LOG_FORMAT(
+                "LoadModule - Error from LoadTestCaseInfosL %d", err );
+            RemoveTestModule( moduleName );
+            SendErrorResponseMsg( err, KErrorGetTestCases );
+            return;
+            }
+
+        // Sends the name of the loaded module as a response.
+        SendResponseMsg( (*iParameters)[0] );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleLoadModuleCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleUnloadModuleCmdL
+// Unloads a STIF TF test module.
+// Also removes and deletes the corresponding CHtiTestModuleCaseInfos object
+// from iLoadedInfos pointer array.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleUnloadModuleCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleUnloadModuleCmdL" );
+
+    TInt err = KErrNone;
+
+    TBuf<KMaxFileName> moduleName;
+
+    // UNLOAD_MODULE command has always 1 parameter (module name).
+    if ( iParameters->Count() == 0 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    if ( iParameters->Count() == 1 )
+        {
+        if ( (*iParameters)[0].Length() > moduleName.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+        moduleName.Copy( (*iParameters)[0] );
+        err = RemoveTestModule( moduleName );
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        return;
+        }
+
+    if ( err )
+        {
+        HTI_LOG_FORMAT( "UnloadModule: Error %d", err );
+        SendErrorResponseMsg( err, KErrorUnloadModule );
+        }
+
+    else
+        {
+        // Remove the test case infos of the unloaded module.
+        TInt moduleIndex = IndexByModuleName( moduleName );
+        if ( moduleIndex != KErrNotFound )
+            {
+            CHtiTestModuleCaseInfos* module = iLoadedInfos[moduleIndex];
+            iLoadedInfos.Remove( moduleIndex );
+            delete module;
+            }
+
+        // Sends the name of the unloaded module as a response.
+        SendResponseMsg( (*iParameters)[0] );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleUnloadModuleCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleListCasesCmdL
+// Creates a list of titles of the test cases inside the given test module.
+// Output is a string of test case titles separated with the | character.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleListCasesCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleListCasesCmdL" );
+
+    TInt err = KErrNone;
+
+    TBuf<KMaxFileName> moduleName;
+    TBuf8<128> buf8;  // temporary buffer for case titles
+
+    CHtiTestModuleCaseInfos* module = NULL;
+    CTestInfo* caseInfo = NULL;
+
+    // LIST_CASES command has 1 optional parameter (module name).
+
+    // If no parameter given all cases of all currently loaded
+    // modules are listed.
+    if ( iParameters->Count() == 0 )
+        {
+        /*
+        // (Re)load case infos from all loaded modules
+        TRAP( err, LoadTestCaseInfosL() );
+
+        if ( err )
+            {
+            HTI_LOG_FORMAT(
+                "ListCases - Error from LoadTestCaseInfosL %d", err );
+            SendErrorResponseMsg( err, KErrorGetTestCaseInfos );
+            }
+        */
+        CBufFlat* caseListBuf = NULL;
+        TRAP( err, caseListBuf = CBufFlat::NewL( 128 ) );
+        if ( err )
+            {
+            SendErrorResponseMsg( KErrNoMemory, KErrorNoMemory );
+            return;
+            }
+
+        // Loop all loaded test modules
+        TInt pos = 0;
+        for ( TInt i = 0; i < iLoadedInfos.Count(); i++ )
+            {
+            module = NULL;
+            module = iLoadedInfos[i];
+            HTI_LOG_FORMAT( "Listing cases from module %S",
+                module->iModuleName );
+
+            // Loop all case infos in this module
+            for ( TInt j = 0; j < module->iTestInfos.Count(); j++ )
+                {
+                caseInfo = NULL;
+                caseInfo = module->iTestInfos[j];
+
+                if ( !( i == 0 && j == 0 ) )
+                    {
+                    buf8.Append( KParameterDelimiter );
+                    }
+
+                buf8.Append( caseInfo->TestCaseTitle() );
+
+                TRAP( err, caseListBuf->ExpandL( pos, buf8.Length() ) );
+                if ( err )
+                    {
+                    SendErrorResponseMsg( KErrNoMemory, KErrorNoMemory );
+                    delete caseListBuf;
+                    return;
+                    }
+                caseListBuf->Write( pos, buf8, buf8.Length() );
+                pos += buf8.Length();
+                buf8.Zero();
+                }
+            }
+
+        if ( caseListBuf->Size() > 0 )
+            {
+            TPtr8 ptr = caseListBuf->Ptr( 0 );
+            SendResponseMsg( ptr );
+            }
+
+        else
+            {
+            SendResponseMsg( buf8 );
+            }
+
+        delete caseListBuf;
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        if ( (*iParameters)[0].Length() > moduleName.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+
+        moduleName.Copy( (*iParameters)[0] );
+        TInt moduleIndex = IndexByModuleName( moduleName );
+
+        if ( moduleIndex == KErrNotFound )
+            {
+            HTI_LOG_TEXT( "Module is not loaded" );
+            SendErrorResponseMsg( KErrNotFound, KErrorModuleNotLoaded );
+            return;
+            }
+        /*
+        // (Re)load the case infos of given module
+        TRAP( err, LoadTestCaseInfosL( moduleName ) );
+        if ( err )
+            {
+            HTI_LOG_FORMAT(
+                "ListCases - Error from LoadTestCaseInfosL %d", err );
+            SendErrorResponseMsg( err, KErrorGetTestCaseInfos );
+            return;
+            }
+        */
+        module = iLoadedInfos[moduleIndex];
+        CBufFlat* caseListBuf = NULL;
+
+        TRAP( err, caseListBuf = CBufFlat::NewL( 128 ) );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( KErrNoMemory, KErrorNoMemory );
+            return;
+            }
+
+        TInt pos = 0;
+        for ( TInt i = 0; i < module->iTestInfos.Count(); i++ )
+            {
+            caseInfo = NULL;
+            caseInfo = module->iTestInfos[i];
+            buf8.Copy( caseInfo->TestCaseTitle() );
+            if ( !( i == module->iTestInfos.Count() - 1 ) )
+                {
+                buf8.Append( KParameterDelimiter );
+                }
+            TRAP( err, caseListBuf->ExpandL( pos, buf8.Length() ) );
+            if ( err )
+                {
+                SendErrorResponseMsg( KErrNoMemory, KErrorNoMemory );
+                delete caseListBuf;
+                return;
+                }
+            caseListBuf->Write( pos, buf8, buf8.Length() );
+            pos += buf8.Length();
+            buf8.Zero();
+            }
+
+        if ( module->iTestInfos.Count() > 0 )
+            {
+            TPtr8 ptr = caseListBuf->Ptr( 0 );
+            SendResponseMsg( ptr );
+            }
+
+        else
+            {
+            SendResponseMsg( buf8 );
+            }
+
+        delete caseListBuf;
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleListCasesCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleStartCaseCmdL
+// Starts one test case based on test module name and test case index number.
+// STIF TF gives an ID to the started case and that ID is sent as a response
+// message.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleStartCaseCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleStartCaseCmdL" );
+
+    TInt err = KErrNone;
+    TInt caseNumber = -1;
+
+    // START_CASE command has 1 or 2 parameters.
+    // If only one parameter given, it's the index of test case to start. The
+    // index refers to the list of test cases of all currently loaded modules.
+    // If two parameters given, then the first one is the module name and
+    // second is the test case index number inside the given module,
+
+    if ( iParameters->Count() == 0 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        TLex8 lex( (*iParameters)[0] );
+        err = lex.Val( caseNumber );
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorInvalidCaseNumber );
+            return;
+            }
+
+        CTestInfo* caseInfo = NULL;
+        TRAP( err, caseInfo = GetCaseInfoL( caseNumber ) );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorInvalidCaseNumber );
+            return;
+            }
+
+        TInt caseId = -1;
+
+        err = StartTestCase( caseId, *caseInfo );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorStartTestCase );
+            return;
+            }
+
+        TBuf8<32> msg;
+        msg.AppendNum( caseId );
+        SendResponseMsg( msg );
+        }
+
+    else if ( iParameters->Count() == 2 )
+        {
+        TBuf<KMaxFileName> moduleName;
+        if ( (*iParameters)[0].Length() > moduleName.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+
+        moduleName.Copy( (*iParameters)[0] );
+        TLex8 lex( (*iParameters)[1] );
+        err = lex.Val( caseNumber );
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorInvalidCaseNumber );
+            return;
+            }
+
+        TInt moduleIndex = IndexByModuleName( moduleName );
+
+        if ( moduleIndex == KErrNotFound )
+            {
+            // We don't have case infos of given module loaded - try to
+            // load them.
+            TRAP( err, LoadTestCaseInfosL( moduleName ) );
+            if ( err )
+                {
+                HTI_LOG_FORMAT(
+                    "StartCase - Error from LoadTestCaseInfosL %d", err );
+                SendErrorResponseMsg( err, KErrorModuleNotLoaded );
+                return;
+                }
+            // Now there should be the module added - get its index
+            moduleIndex = IndexByModuleName( moduleName );
+            }
+
+        CHtiTestModuleCaseInfos* module = iLoadedInfos[moduleIndex];
+
+        if ( caseNumber < 0 ||
+             caseNumber >= module->iTestInfos.Count() ||
+             module->iTestInfos.Count() == 0 )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorInvalidCaseNumber );
+            return;
+            }
+
+        CTestInfo* caseInfo = module->iTestInfos[caseNumber];
+        TInt caseId = -1;
+
+        err = StartTestCase( caseId, *caseInfo );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorStartTestCase );
+            return;
+            }
+
+        TBuf8<32> msg;
+        msg.AppendNum( caseId );
+        SendResponseMsg( msg );
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleStartCaseCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleCancelCaseCmdL
+// Cancels test case execution based on test case ID.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleCancelCaseCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleCancelCaseCmdL" );
+
+    TInt err = KErrNone;
+
+    // CANCEL_CASE command always has 1 parameter (test case id).
+    if ( iParameters->Count() == 0 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        TInt caseId = -1;
+        TLex8 lex( (*iParameters)[0] );
+        err = lex.Val( caseId );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorInvalidCaseNumber );
+            return;
+            }
+
+        err = CancelTestCase( caseId );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorCancelTestCase );
+            }
+
+        else
+            {
+            SendResponseMsg( _L8( "OK" ) );
+            }
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleCancelCaseCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandlePauseCaseCmdL
+// Pauses test case execution based on test case ID.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandlePauseCaseCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandlePauseCaseCmdL" );
+
+    TInt err = KErrNone;
+
+    // PAUSE_CASE command always has 1 parameter (test case id).
+    if ( iParameters->Count() == 0 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        TInt caseId = -1;
+        TLex8 lex( (*iParameters)[0] );
+        err = lex.Val( caseId );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorInvalidCaseNumber );
+            return;
+            }
+
+        err = PauseTestCase( caseId );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorPauseTestCase );
+            }
+
+        else
+            {
+            SendResponseMsg( _L8( "OK" ) );
+            }
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandlePauseCaseCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleResumeCaseCmdL
+// Resumes execution of a paused test case based on test case ID.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleResumeCaseCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleResumeCaseCmdL" );
+
+    TInt err = KErrNone;
+
+    // RESUME_CASE command always has 1 parameter (test case id).
+    if ( iParameters->Count() == 0 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        TInt caseId = -1;
+        TLex8 lex( (*iParameters)[0] );
+        err = lex.Val( caseId );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorInvalidCaseNumber );
+            return;
+            }
+
+        err = ResumeTestCase( caseId );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorResumeTestCase );
+            }
+
+        else
+            {
+            SendResponseMsg( _L8( "OK" ) );
+            }
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleResumeCaseCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleAddCaseFileCmdL
+// Adds a test case file to an earlier loaded test module.
+// Checks that the module is loaded and that the given test case file exists.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleAddCaseFileCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleAddCaseFileCmdL" );
+
+    TInt err = KErrNone;
+
+    TBuf<KMaxFileName> moduleName;
+    TBuf<KMaxFileName> caseFilePath;
+
+    // ADD_CASE_FILE command always has 2 mandatory parameters (module name
+    // and test case file path).
+    if ( iParameters->Count() == 0 || iParameters->Count() == 1 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 2 )
+        {
+        if ( (*iParameters)[0].Length() > moduleName.MaxLength() ||
+             (*iParameters)[1].Length() > caseFilePath.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+
+        moduleName.Copy( (*iParameters)[0] );
+        caseFilePath.Copy( (*iParameters)[1] );
+
+        RFs fsSession;
+        err = fsSession.Connect();
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorFileServer );
+            return;
+            }
+
+        if ( !( BaflUtils::FileExists( fsSession, caseFilePath ) ) )
+            {
+            SendErrorResponseMsg( KErrNotFound, KErrorCaseFileNotFound );
+            fsSession.Close();
+            return;
+            }
+
+        fsSession.Close();
+
+        err = AddTestCaseFile( moduleName, caseFilePath );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorAddCaseFile );
+            return;
+            }
+
+        // Test case file has been added - update test case infos
+        TRAP( err, LoadTestCaseInfosL( moduleName ) );
+
+        if ( err )
+            {
+            HTI_LOG_FORMAT(
+                "AddCaseFile - Error from LoadTestCaseInfosL %d", err );
+            SendErrorResponseMsg( err, KErrorGetTestCases );
+            return;
+            }
+
+        SendResponseMsg( _L8( "OK" ) );
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleAddCaseFileCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleRemoveCaseFileCmdL
+// Removes a test case file from test module.
+// Checks that the module is loaded and that the given test case file exists.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleRemoveCaseFileCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleRemoveCaseFileCmdL" );
+
+    TInt err = KErrNone;
+
+    TBuf<KMaxFileName> moduleName;
+    TBuf<KMaxFileName> caseFilePath;
+
+    // REMOVE_CASE_FILE command always has 2 mandatory parameters (module name
+    // and test case file path).
+    if ( iParameters->Count() == 0 || iParameters->Count() == 1 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 2 )
+        {
+        if ( (*iParameters)[0].Length() > moduleName.MaxLength() ||
+             (*iParameters)[1].Length() > caseFilePath.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+
+        moduleName.Copy( (*iParameters)[0] );
+        caseFilePath.Copy( (*iParameters)[1] );
+
+        RFs fsSession;
+        err = fsSession.Connect();
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorFileServer );
+            return;
+            }
+
+        if ( !( BaflUtils::FileExists( fsSession, caseFilePath ) ) )
+            {
+            SendErrorResponseMsg( KErrNotFound, KErrorCaseFileNotFound );
+            fsSession.Close();
+            return;
+            }
+
+        fsSession.Close();
+
+        err = RemoveTestCaseFile( moduleName, caseFilePath );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorRemoveCaseFile );
+            return;
+            }
+
+        // Test case file has been removed - update test case infos
+        TRAP( err, LoadTestCaseInfosL( moduleName ) );
+
+        if ( err )
+            {
+            HTI_LOG_FORMAT(
+                "RemoveCaseFile - Error from LoadTestCaseInfosL %d", err );
+            SendErrorResponseMsg( err, KErrorGetTestCases );
+            return;
+            }
+
+        SendResponseMsg( _L8( "OK" ) );
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleRemoveCaseFileCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleCaseMsgCmdL
+// Sends a message to STIF Test Framework.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleCaseMsgCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleCaseMsgCmdL" );
+
+    TInt err = KErrNone;
+
+    // CASE_MESSAGE command always has 1 parameter (the message).
+    if ( iParameters->Count() == 0 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        HBufC* msg = HBufC::New( (*iParameters)[0].Length() );
+        if ( msg == NULL )
+            {
+            SendErrorResponseMsg( KErrNoMemory, KErrorNoMemory );
+            return;
+            }
+        msg->Des().Copy( (*iParameters)[0] );
+        HTI_LOG_TEXT( "Sending case message:" );
+        HTI_LOG_DES( *msg );
+        err = AtsReceive( *msg );
+        delete msg;
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorCaseMessage );
+            }
+
+        else
+            {
+            SendResponseMsg( _L8( "OK" ) );
+            }
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleCaseMsgCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleSetDevIdCmdL
+// Sets device ID. If successfull sends the set ID back as response message.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleSetDevIdCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleSetDevIdCmdL" );
+
+    TInt err = KErrNone;
+
+    // SET_DEVICEID command always has 1 parameter (device id).
+    if ( iParameters->Count() == 0 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        return;
+        }
+
+    else if ( iParameters->Count() == 1 )
+        {
+        TUint16 deviceId = KDefaultDevId;
+        TLex8 lex( (*iParameters)[0] );
+        err = lex.Val( deviceId, EDecimal );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorInvalidDeviceId );
+            return;
+            }
+
+        iDevId = deviceId;
+
+        // On success sends the set device id as response.
+        TBuf8<32> msg;
+        msg.AppendNum( (TInt)iDevId );
+        SendResponseMsg( msg );
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleSetDevIdCmdL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::HandleSetAttributeCmdL
+// Sets attributes for test framework.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::HandleSetAttributeCmdL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::HandleSetAttributeCmdL" );
+
+    TInt err = KErrNone;
+
+    // SET_ATTRIBUTE command always has 2 paramters (attribute id and value)
+    if ( iParameters->Count() < 2 )
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorParameterMissing );
+        }
+
+    else if ( iParameters->Count() == 2 )
+        {
+        TInt attributeId = -1;
+        TLex8 lex( (*iParameters)[0] );
+        err = lex.Val( attributeId );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorInvalidAttributeId );
+            return;
+            }
+
+        TBuf<256> value;
+        if ( (*iParameters)[1].Length() > value.MaxLength() )
+            {
+            SendErrorResponseMsg( KErrArgument, KErrorParameterTooLong );
+            return;
+            }
+        value.Copy( (*iParameters)[1] );
+
+        err = SetAttribute( (TAttribute)attributeId, value );
+
+        if ( err )
+            {
+            SendErrorResponseMsg( err, KErrorSetAttribute );
+            }
+
+        else
+            {
+            SendResponseMsg( _L8( "OK" ) );
+            }
+        }
+
+    else
+        {
+        SendErrorResponseMsg( KErrArgument, KErrorTooManyParameters );
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::HandleSetAttributeCmdL" );
+    }
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::TestCompleted
+// This method is called by the STIF TF when a test case execution completes.
+// The test case result is send out as a formatted string.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::TestCompleted( TInt aTestId,
+                                  TInt aTestExecutionResult,
+                                  TTestResult& aTestResult )
+    {
+    // Note that the STIF TF is not aware whether the service is busy processing,
+    // sending, or waiting to send a previous message. So if this method
+    // is called by the STIF TF while the service is busy, the currently
+    // pending message will be overridden by the message sent from this method.
+
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::TestCompleted" );
+
+    iIsBusy = ETrue;  // Will be set to EFalse when response have been sent
+
+    // The maximum length of TResultDes is 128, so a buffer of 256
+    // should be enough for the whole "Test Completed" message.
+    TBuf8<256> buf8;
+
+    // Add first the test id
+    buf8.AppendFormat( _L8( "%d" ), aTestId );
+    buf8.Append( KParameterDelimiter );
+
+    // Add the test result - if it's 0 case has passed
+    buf8.AppendFormat( _L8( "%d" ), aTestResult.iResult );
+    buf8.Append( KParameterDelimiter );
+
+    // Add the test execution result
+    buf8.AppendFormat( _L8( "%d" ), aTestExecutionResult );
+    buf8.Append( KParameterDelimiter );
+
+    // Finally add the description (if there's any)
+    if ( aTestResult.iResultDes.Length() > 0 )
+        {
+        buf8.Append( aTestResult.iResultDes );
+        }
+
+    // and send it
+    SendResponseMsg( buf8, ECmdTestCompleted );
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::TestCompleted" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::AtsSend
+// This method is called by the STIF TF when it needs to send a message to ATS
+// (or some other PC-side component listening for messages)
+// The message is converted to 8-bit representation before sending.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::AtsSend( const TDesC& aMessage )
+    {
+    // Note that the STIF TF is not aware whether the service is busy processing,
+    // sending, or waiting to send a previous message. So if this method
+    // is called by the STIF TF while the service is busy, the currently
+    // pending message will be overridden by the message sent from this method.
+
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::AtsSend" );
+    HTI_LOG_TEXT( "Message: " );
+    HTI_LOG_DES( aMessage );
+
+    iIsBusy = ETrue;  // Will be set to EFalse when response have been sent
+
+    TInt err = KErrNone;
+
+    CCnvCharacterSetConverter* converter = NULL;
+    TRAP( err, converter = CCnvCharacterSetConverter::NewL() );
+
+    if ( err )
+        {
+        SendErrorResponseMsg( err, KErrorCharConv );
+        return;
+        }
+
+    RFs fsSession;
+    err = fsSession.Connect();
+    if ( err )
+        {
+        SendErrorResponseMsg( err, KErrorFileServer );
+        delete converter;
+        return;
+        }
+
+    CCnvCharacterSetConverter::TAvailability availability =
+        CCnvCharacterSetConverter::ENotAvailable;
+
+    TRAP( err, availability = converter->PrepareToConvertToOrFromL(
+        KCharacterSetIdentifierAscii, fsSession ) );
+
+    if ( err || availability == CCnvCharacterSetConverter::ENotAvailable )
+        {
+        SendErrorResponseMsg( err, KErrorCharConv );
+        fsSession.Close();
+        delete converter;
+        return;
+        }
+
+    fsSession.Close();
+
+    HBufC8* asciiBuffer = NULL;
+    TRAP( err, asciiBuffer = HBufC8::NewL( aMessage.Length() ) );
+
+    if ( err )
+        {
+        SendErrorResponseMsg( err, KErrorNoMemory );
+        delete converter;
+        return;
+        }
+
+    TPtr8 ptr8 = asciiBuffer->Des();
+    ptr8.Zero();
+
+    err = converter->ConvertFromUnicode( ptr8, aMessage );
+
+    if ( err )
+        {
+        SendErrorResponseMsg( err, KErrorCharConv );
+        }
+
+    else
+        {
+        TPtr8 converted = asciiBuffer->Des();
+        HTI_LOG_TEXT( "Converted message: " );
+        HTI_LOG_DES( converted );
+        SendResponseMsg( converted, ECmdAtsMessage );
+        }
+
+    delete converter;
+    delete asciiBuffer;
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::AtsSend" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::Print
+// This method is called by the STIF TF when a test case prints.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::Print( TInt /*aTestId*/,
+                          TTestProgress& aProgress )
+    {
+    if ( iConsole )
+        {
+        iConsole->Printf( _L("%S: %S\n"),
+                         &aProgress.iDescription,
+                         &aProgress.iText );
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::LoadTestCaseInfosL
+// A helper method that loads the test case info objects from all currently
+// loaded test modules. Creates and inserts new CHtiTestModuleCaseInfos objects
+// to iLoadedInfos pointer array. Leaves on failure.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::LoadTestCaseInfosL()
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::LoadTestCaseInfosL()" );
+
+    RPointerArray<CTestInfo> allTestInfos;
+    CleanupClosePushL( allTestInfos );
+
+    HTI_LOG_TEXT( "Getting test cases" );
+    // Ignoring possible errors
+    GetTestCases( allTestInfos );
+    HTI_LOG_FORMAT( "Got %d cases", allTestInfos.Count() );
+
+    // Clear all old test case infos from iLoadedInfos
+    iLoadedInfos.ResetAndDestroy();
+
+    // Loop through all test case infos and add them to the correct modules
+    // to iLoadedInfos
+    for ( TInt i = 0; i < allTestInfos.Count(); i++ )
+        {
+        CHtiTestModuleCaseInfos* currentModule = NULL;
+        CTestInfo* caseInfo = NULL;
+
+        caseInfo = allTestInfos[i];
+
+        // Get or create the CHtiTestModuleCaseInfos where this case belongs.
+        TInt moduleIndex = IndexByModuleName( caseInfo->ModuleName() );
+
+        if ( moduleIndex == KErrNotFound )
+            {
+            HTI_LOG_TEXT( "Module not found - adding it" );
+            currentModule = CHtiTestModuleCaseInfos::NewLC(
+                caseInfo->ModuleName() );
+            User::LeaveIfError( iLoadedInfos.Append( currentModule ) );
+            CleanupStack::Pop(); // currentModule
+            }
+
+        else
+            {
+            HTI_LOG_TEXT( "Module found - getting it" );
+            currentModule = iLoadedInfos[moduleIndex];
+            }
+
+        // Add the case info to the CHtiTestModuleCaseInfos object
+        currentModule->iTestInfos.Append( caseInfo );
+        }
+
+    HTI_LOG_FORMAT( "Case infos of %d modules added", iLoadedInfos.Count() );
+    allTestInfos.Reset();
+    CleanupStack::PopAndDestroy(); // allTestInfos
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::LoadTestCaseInfosL()" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::LoadTestCaseInfosL
+// A helper method that loads the test case info objects from the given test
+// module. Creates and inserts a new CHtiTestModuleCaseInfos object to
+// iLoadedInfos pointer array. Leaves on failure.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::LoadTestCaseInfosL( TDesC& aModuleName )
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::LoadTestCaseInfosL( moduleName )" );
+
+    // Check if test case infos of this module already loaded
+    TInt index = IndexByModuleName( aModuleName );
+    if ( index != KErrNotFound )
+        {
+        // If infos already loaded, delete and load again
+        HTI_LOG_TEXT( "Already loaded - updating" );
+        CHtiTestModuleCaseInfos* module = iLoadedInfos[index];
+        iLoadedInfos.Remove( index );
+        delete module;
+        }
+
+    CHtiTestModuleCaseInfos* newModule =
+            CHtiTestModuleCaseInfos::NewLC( aModuleName );
+
+    HTI_LOG_TEXT( "Getting test cases" );
+
+    // If the module is not loaded STIF TF seems to behave so that
+    // GetTestCases method does not return error but it returns
+    // zero test cases.
+    // At least in some cases if the module is loaded but it does not have
+    // any test cases, GetTestCases returns KErrNotFound.
+    // So possible errors or zero test case situations from GetTestCases
+    // are ignored here - if there's an error then the module will just
+    // have 0 test case infos.
+    GetTestCases( newModule->iTestInfos, aModuleName );
+
+    HTI_LOG_FORMAT( "Got %d cases", newModule->iTestInfos.Count() );
+
+    User::LeaveIfError( iLoadedInfos.Append( newModule ) );
+    CleanupStack::Pop(); // newModule
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::LoadTestCaseInfosL( moduleName )" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::ParseParametersL
+// A helper method for parsing the parameters from the given command message.
+// Parameters must be separated with a character defined by the
+// KParameterDelimiter. Parsed parameters are stored to iParameters array.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::ParseParametersL( const TDesC8& aCommand )
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::ParseParametersL" );
+
+    // Clear the parameter array
+    iParameters->Reset();
+
+    // Then loop all the parameters.
+    TInt sectionStart = 0;
+    TInt sectionEnd = 0;
+    while ( true )
+        {
+        sectionStart = sectionEnd + 1;
+        if ( sectionStart >= aCommand.Length() )
+            {
+            HTI_LOG_FORMAT( "Parameters %d", iParameters->Count() );
+            HTI_LOG_FUNC_OUT( "CHtiStifTfIf::ParseParametersL" );
+            return;
+            }
+
+        sectionEnd = aCommand.Mid( sectionStart ).Find( KParameterDelimiter )
+            + sectionStart;
+
+        if ( sectionEnd >= sectionStart )
+            {
+            iParameters->AppendL(
+                aCommand.Mid( sectionStart, sectionEnd - sectionStart ) );
+            HTI_LOG_DES( aCommand.Mid( sectionStart, sectionEnd - sectionStart ) );
+            }
+        else
+            {
+            iParameters->AppendL( aCommand.Mid( sectionStart ) );
+            HTI_LOG_DES( aCommand.Mid( sectionStart ) );
+            HTI_LOG_FORMAT( "Parameters %d", iParameters->Count() );
+            HTI_LOG_FUNC_OUT( "CHtiStifTfIf::ParseParametersL" );
+            return;  // End of parameters.
+            }
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::SetDispatcher
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::SetDispatcher( MHtiDispatcher* aDispatcher )
+    {
+    iDispatcher = aDispatcher;
+    iConsole = iDispatcher->GetConsole();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::NotifyMemoryChange
+// Called when HTI Framework has dispatched a message forward and the amount
+// of free memory in the message queue has changed.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfIf::NotifyMemoryChange( TInt aAvailableMemory )
+    {
+    if ( iIsBusy && iMessage )
+        {
+        if ( aAvailableMemory >= iMessage->Size() )
+            {
+
+            if ( iErrorCode == 0 )
+                {
+                TInt err = iDispatcher->DispatchOutgoingMessage(
+                    iMessage, KStifTfServiceUid );
+
+                if ( err == KErrNone )
+                    {
+                    // Ownership of iMessage has been transferred
+                    iMessage = NULL;
+                    iIsBusy = EFalse;
+                    iDispatcher->RemoveMemoryObserver(
+                            ( MHtiMemoryObserver* ) iPlugin );
+                    }
+
+                else if ( err == KErrNoMemory )
+                    {
+                    // Just keep retrying.
+                    }
+
+                else // Give up on sending
+                    {
+                    delete iMessage;
+                    iMessage = NULL;
+                    iIsBusy = EFalse;
+                    iDispatcher->RemoveMemoryObserver(
+                            ( MHtiMemoryObserver* ) iPlugin );
+                    }
+
+                }
+
+            else
+                {
+                TInt err = iDispatcher->DispatchOutgoingErrorMessage(
+                    iErrorCode, *iMessage, KStifTfServiceUid );
+
+                // If it was success or some other error than KErrNoMemory
+                // we are done sending or trying to send this message.
+                if ( err != KErrNoMemory )
+                    {
+                    delete iMessage;
+                    iMessage = NULL;
+                    iIsBusy = EFalse;
+                    iDispatcher->RemoveMemoryObserver(
+                            ( MHtiMemoryObserver* ) iPlugin );
+                    }
+
+                else
+                    {
+                    // Just keep retrying.
+                    }
+                }
+            }
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::SendResponseMsg
+// Sends a message out to the message dispatcher.
+// -----------------------------------------------------------------------------
+//
+TInt CHtiStifTfIf::SendResponseMsg( const TDesC8& aMsg,
+                        const TUint8 aCommandId )
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::SendResponseMsg" );
+
+    iErrorCode = 0;
+
+    if ( iDispatcher == NULL )
+        {
+        iIsBusy = EFalse;
+        return KErrGeneral;
+        }
+
+    iDispatcher->RemoveMemoryObserver( ( MHtiMemoryObserver* ) iPlugin );
+
+    delete iMessage;
+    iMessage = NULL;
+    iMessage = HBufC8::New( aMsg.Length() + 1 );
+
+
+    if ( iMessage == NULL )
+        {
+        iIsBusy = EFalse;
+        return KErrNoMemory;
+        }
+
+    TPtr8 ptr8 = iMessage->Des();
+    if ( aCommandId != 0 )
+        {
+        ptr8.Append( aCommandId );
+        }
+    else
+        {
+        ptr8.Append( iCommandId );
+        }
+
+    ptr8.Append( aMsg );
+
+    TInt err = KErrNone;
+
+    err = iDispatcher->DispatchOutgoingMessage( iMessage, KStifTfServiceUid );
+
+    if ( err == KErrNoMemory )
+        {
+        HTI_LOG_TEXT( "Message queue memory full - waiting" );
+        iIsBusy = ETrue; // Should already be true, but just in case
+        iDispatcher->AddMemoryObserver( ( MHtiMemoryObserver* ) iPlugin );
+        // For the caller of this method all is OK, sending is just delayed
+        err = KErrNone;
+        }
+
+    else if ( err == KErrNone )
+        {
+        HTI_LOG_TEXT( "Message sent to dispatcher" );
+        iMessage = NULL; // Ownership of iMessage has been transferred
+        iIsBusy = EFalse;
+        }
+
+    else // give up on sending
+        {
+        HTI_LOG_FORMAT( "Other dispatcher error %d", err );
+        delete iMessage;
+        iMessage = NULL;
+        iIsBusy = EFalse;
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::SendResponseMsg" );
+    return err;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::SendErrorResponseMsg
+// Sends an error message out to the message dispatcher.
+// -----------------------------------------------------------------------------
+//
+TInt CHtiStifTfIf::SendErrorResponseMsg( TInt aErrorCode,
+                        const TDesC8& aErrorDescription,
+                        const TUint8 aCommandId )
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::SendErrorResponseMsg" );
+
+    iErrorCode = aErrorCode;
+
+    if ( iDispatcher == NULL )
+        {
+        iIsBusy = EFalse;
+        return KErrGeneral;
+        }
+
+    iDispatcher->RemoveMemoryObserver( ( MHtiMemoryObserver* ) iPlugin );
+
+    delete iMessage;
+    iMessage = NULL;
+    iMessage = HBufC8::New( aErrorDescription.Length() + 1 );
+
+    if ( iMessage == NULL )
+        {
+        iIsBusy = EFalse;
+        return KErrNoMemory;
+        }
+
+    TPtr8 ptr8 = iMessage->Des();
+    if ( aCommandId != 0 )
+        {
+        ptr8.Append( aCommandId );
+        }
+    else
+        {
+        ptr8.Append( iCommandId );
+        }
+
+    ptr8.Append( aErrorDescription );
+
+    TInt err = KErrNone;
+
+    err = iDispatcher->DispatchOutgoingErrorMessage(
+        aErrorCode, *iMessage, KStifTfServiceUid );
+
+    if ( err == KErrNoMemory )
+        {
+        HTI_LOG_TEXT( "Message queue memory full - waiting" );
+        iIsBusy = ETrue; // Should already be true, but just in case
+        iDispatcher->AddMemoryObserver( ( MHtiMemoryObserver* ) iPlugin );
+        // For the caller of this method all is OK, sending is just delayed
+        err = KErrNone;
+        }
+
+    else if ( err == KErrNone )
+        {
+        HTI_LOG_TEXT( "Error message sent to dispatcher" );
+        delete iMessage;
+        iMessage = NULL;
+        iIsBusy = EFalse;
+        }
+
+    else // give up on sending
+        {
+        HTI_LOG_FORMAT( "Other dispatcher error %d", err );
+        delete iMessage;
+        iMessage = NULL;
+        iIsBusy = EFalse;
+        }
+
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::SendErrorResponseMsg" );
+    return err;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::IndexByModuleName
+// A helper method to search for a CHtiTestModuleCaseInfos object from the
+// iLoadedInfos array based on the module name.
+// -----------------------------------------------------------------------------
+//
+TInt CHtiStifTfIf::IndexByModuleName( const TDesC& aModuleName )
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::IndexByModuleName" );
+
+    CHtiTestModuleCaseInfos* module;
+    for ( TInt i = 0; i < iLoadedInfos.Count(); i++ )
+        {
+        module = NULL;
+        module = iLoadedInfos[i];
+        if ( module->iModuleName->Compare( aModuleName ) == 0 )
+            {
+            HTI_LOG_FORMAT( "Module found from index %d", i );
+            HTI_LOG_FUNC_OUT( "CHtiStifTfIf::IndexByModuleName" );
+            return i;
+            }
+        }
+    HTI_LOG_TEXT( "Module not found" );
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::IndexByModuleName" );
+    return KErrNotFound;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfIf::GetCaseInfoL
+// A helper method to get the correct CTestInfo object based on the index
+// number, referring to list of case infos of all loaded test modules.
+// -----------------------------------------------------------------------------
+//
+CTestInfo* CHtiStifTfIf::GetCaseInfoL( TInt aCaseIndex )
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfIf::GetCaseInfoL" );
+
+    if ( aCaseIndex < 0 )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    TInt index = -1;
+    TInt caseCount = 0;
+    CHtiTestModuleCaseInfos* module = NULL;
+    for ( TInt i = 0; i < iLoadedInfos.Count(); i++ )
+        {
+        module = NULL;
+        module = iLoadedInfos[i];
+        caseCount += module->iTestInfos.Count();
+        HTI_LOG_FORMAT( "Case count = %d", caseCount );
+        if ( aCaseIndex < caseCount )
+            {
+            // This is the right module
+            // Get the case index inside this module
+            index = module->iTestInfos.Count() - ( caseCount - aCaseIndex );
+            }
+        if ( index >= 0 ) break; // Case found - break out of loop
+        }
+
+    if ( index < 0 )
+        {
+        HTI_LOG_TEXT( "Given index was too big - case not found" );
+        User::Leave( KErrNotFound );
+        }
+
+    // Following should never be true - this is for testing.
+    if ( index > module->iTestInfos.Count() )
+        {
+        HTI_LOG_TEXT( "**Calculated index > test info count of module**" );
+        User::Leave( KErrGeneral );
+        }
+
+    HTI_LOG_FORMAT( "Case found from index %d", index );
+    HTI_LOG_FUNC_OUT( "CHtiStifTfIf::GetCaseInfoL" );
+    return module->iTestInfos[index];
+    }
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+
+// -----------------------------------------------------------------------------
+// CHtiTestModuleCaseInfos::NewL
+// -----------------------------------------------------------------------------
+//
+CHtiTestModuleCaseInfos* CHtiTestModuleCaseInfos::NewL(
+                                                const TDesC& aModuleName )
+    {
+    CHtiTestModuleCaseInfos* self = NewLC( aModuleName );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiTestModuleCaseInfos::NewLC
+// -----------------------------------------------------------------------------
+//
+CHtiTestModuleCaseInfos* CHtiTestModuleCaseInfos::NewLC(
+                                                const TDesC& aModuleName )
+    {
+    CHtiTestModuleCaseInfos* self = new (ELeave) CHtiTestModuleCaseInfos;
+    CleanupStack::PushL( self );
+    self->ConstructL( aModuleName );
+    return self;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiTestModuleCaseInfos::ConstructL
+// 2nd phase constructor.
+// -----------------------------------------------------------------------------
+//
+void CHtiTestModuleCaseInfos::ConstructL( const TDesC& aModuleName )
+    {
+    iModuleName = aModuleName.AllocL();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiTestModuleCaseInfos::CHtiTestModuleCaseInfos
+// C++ default constructor
+// -----------------------------------------------------------------------------
+//
+CHtiTestModuleCaseInfos::CHtiTestModuleCaseInfos()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiTestModuleCaseInfos::~CHtiTestModuleCaseInfos
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+CHtiTestModuleCaseInfos::~CHtiTestModuleCaseInfos()
+    {
+    delete iModuleName;
+    iTestInfos.ResetAndDestroy();
+    iTestInfos.Close();
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiTestModuleCaseInfos::Compare
+// Compares the order of two CHtiTestModuleCaseInfos objects using module name
+// as the ordering key.
+// -----------------------------------------------------------------------------
+//
+TInt CHtiTestModuleCaseInfos::Compare( const CHtiTestModuleCaseInfos& aFirst,
+        const CHtiTestModuleCaseInfos& aSecond )
+    {
+    return ( aFirst.iModuleName )->Compare( *aSecond.iModuleName );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiTestModuleCaseInfos::Match
+// Checks the equality of two CHtiTestModuleCaseInfos objects.
+// Objects are considered to be equal if their module name is equal.
+// -----------------------------------------------------------------------------
+//
+TBool CHtiTestModuleCaseInfos::Match( const CHtiTestModuleCaseInfos& aFirst,
+        const CHtiTestModuleCaseInfos& aSecond )
+    {
+    if ( ( aFirst.iModuleName )->Compare( *aSecond.iModuleName ) == 0 )
+        {
+        return true;
+        }
+
+    return false;
+    }
+
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiStifTfServicePlugin/src/HtiStifTfServicePlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implements the ECom plugin for HTI STIF Test Framework control
+*                service.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <HtiDispatcherInterface.h>
+#include <HtiLogging.h>
+
+#include "HtiStifTfServicePlugin.h"
+#include "HtiStifTfIf.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfServicePlugin::CHtiStifTfServicePlugin
+// C++ default constructor can NOT contain any code, that might leave.
+// -----------------------------------------------------------------------------
+//
+CHtiStifTfServicePlugin::CHtiStifTfServicePlugin()
+    {
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfServicePlugin::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfServicePlugin::ConstructL()
+    {
+    iStifTfInterface = CHtiStifTfIf::NewL( this );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfServicePlugin::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CHtiStifTfServicePlugin* CHtiStifTfServicePlugin::NewL()
+    {
+    CHtiStifTfServicePlugin* self = new (ELeave) CHtiStifTfServicePlugin;
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+
+// Destructor
+CHtiStifTfServicePlugin::~CHtiStifTfServicePlugin()
+    {
+    delete iStifTfInterface;
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfServicePlugin::ProcessMessageL
+// Sends the message to be processed by the class implementing the STIF TF
+// interface.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfServicePlugin::ProcessMessageL( const TDesC8& aMessage,
+    THtiMessagePriority aPriority)
+    {
+    HTI_LOG_FUNC_IN( "CHtiStifTfServicePlugin::ProcessMessageL" );
+    iStifTfInterface->SetDispatcher( iDispatcher );
+    iStifTfInterface->ProcessMessageL( aMessage, aPriority );
+    HTI_LOG_FUNC_OUT( "CHtiStifTfServicePlugin::ProcessMessageL" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfServicePlugin::NotifyMemoryChange
+// Just forwards the call to the HtiStifTwIf instance.
+// -----------------------------------------------------------------------------
+//
+void CHtiStifTfServicePlugin::NotifyMemoryChange( TInt aAvailableMemory )
+    {
+    iStifTfInterface->NotifyMemoryChange( aAvailableMemory );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CHtiStifTfServicePlugin::IsBusy
+// -----------------------------------------------------------------------------
+//
+TBool CHtiStifTfServicePlugin::IsBusy()
+    {
+    return iStifTfInterface->iIsBusy;
+    }
+
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiServicePlugins/HtiStifTfServicePlugin/src/proxy.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Implementation proxy for the ECom plugin.
+*
+*/
+
+
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <ecom/implementationproxy.h>
+#include "HtiStifTfServicePlugin.h"
+
+const TImplementationProxy ImplementationTable[] =
+    {
+        IMPLEMENTATION_PROXY_ENTRY( 0x10210CC3, CHtiStifTfServicePlugin::NewL )
+    };
+
+// Function used to return an instance of the proxy table.
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy( TInt& aTableCount )
+    {
+    aTableCount = sizeof( ImplementationTable ) / sizeof( TImplementationProxy );
+    return ImplementationTable;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiWatchDog/group/HtiWatchDog.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build description file for HtiWatchDog
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET          HtiWatchDog.exe
+TARGETTYPE      EXE
+
+UID             0x1000008d 0x200212D4
+
+VENDORID        0x101FB657
+
+CAPABILITY      ALL -TCB
+
+SOURCEPATH      ../src
+SOURCE          HtiWatchDog.cpp
+
+OS_LAYER_SYSTEMINCLUDE
+
+LIBRARY         euser.lib
+LIBRARY         flogger.lib
+
+SMPSAFE
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiWatchDog/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for HtiWatchDog
+*
+*/
+
+
+PRJ_PLATFORMS
+
+DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+HtiWatchDog.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/HtiWatchDog/src/HtiWatchDog.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,165 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HtiWatchDog implementation.
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32base.h>
+
+#ifdef __ENABLE_LOGGING__
+
+#include <flogger.h>
+_LIT( KLogFolder, "hti" );
+_LIT( KLogFile,   "htiwatchdog.txt" );
+
+#define HTI_LOG_TEXT(a1) {_LIT(temp, a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#define HTI_LOG_DES(a1) {RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, a1);}
+#define HTI_LOG_FORMAT(a1,a2) {_LIT(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, (a2));}
+
+#else   // !__ENABLE_LOGGING__
+
+#define HTI_LOG_TEXT(a1)
+#define HTI_LOG_DES(a1)
+#define HTI_LOG_FORMAT(a1,a2)
+
+#endif // __ENABLE_LOGGING__
+
+// CONSTANTS
+_LIT( KHtiFrameworkExeName,    "HtiFramework.exe" );
+_LIT( KHtiMainThreadName,      "HtiMain" );
+_LIT( KHtiWatchDogName,        "HtiWatchDog" );
+_LIT( KHtiAdminStartParameter, "admin" );
+
+const TTimeIntervalSeconds minInterval( 60 );
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================ LOCAL FUNCTIONS ===============================
+
+LOCAL_C void StartHtiProcessL()
+    {
+    RProcess htiProcess;
+    User::LeaveIfError( htiProcess.Create(
+            KHtiFrameworkExeName, KHtiAdminStartParameter ) );
+    htiProcess.Resume();
+    htiProcess.Close();
+    }
+
+
+LOCAL_C TInt StartL()
+    {
+    HTI_LOG_TEXT( "HtiWatchDog starting..." );
+    TFullName threadName;
+    TFullName matchPattern;
+    matchPattern.Append( _L( "*" ) );
+    matchPattern.Append( KHtiMainThreadName );
+    matchPattern.Append( _L( "*" ) );
+
+    TTime startTime;
+    startTime.HomeTime();
+
+    TTimeIntervalSeconds elapsedTime;
+    TTime now;
+
+    while ( true )
+        {
+        // Use thread finder to find the HTI main thread
+        TFindThread threadFinder;
+        threadFinder.Find( matchPattern );
+        HTI_LOG_TEXT( "Trying to find HTI main thread" );
+        TInt err =  threadFinder.Next( threadName );
+        if ( err )
+            {
+            HTI_LOG_FORMAT( "HTI main thread not found, err: %d", err );
+            User::Panic( _L( "HTI find err" ), err );
+            }
+
+        HTI_LOG_TEXT( "HTI main thread found, opening it" );
+        RThread thread;
+        err = thread.Open( threadName );
+        if ( err )
+            {
+            HTI_LOG_FORMAT( "Could not open HTI main thread, err: %d", err );
+            User::Panic( _L( "HTI open err" ), err );
+            }
+
+        // Logon to HTI main thread and wait for its death
+        HTI_LOG_TEXT( "HTI main thread opened, waiting for its death" );
+        TRequestStatus status;
+        thread.Logon( status );
+        User::WaitForRequest( status );
+        thread.Close();
+
+        // try to restart only if minimum interval time has elapsed
+        now.HomeTime();
+        now.SecondsFrom( startTime, elapsedTime );
+        if ( elapsedTime < minInterval )
+            {
+            HTI_LOG_FORMAT( "HTI died too quickly, in %d seconds", elapsedTime.Int() );
+            HTI_LOG_TEXT( "Giving up" );
+            break;
+            }
+
+        // reset the startTime
+        startTime.HomeTime();
+
+        // try to restart HTI
+        HTI_LOG_TEXT( "HTI died, trying to restart it" );
+        TRAP( err, StartHtiProcessL() );
+        if ( err )
+            {
+            HTI_LOG_FORMAT( "Could not restart HTI, err: %d", err );
+            User::Panic( _L( "HTI start err" ), err );
+            }
+
+        // wait a while for HTI process to start
+        User::After( 5 * 100 * 1000 );
+        }
+
+    HTI_LOG_TEXT( "HtiWatchDog shutting down" );
+    return KErrNone;
+    }
+
+GLDEF_C TInt E32Main()
+    {
+    __UHEAP_MARK;
+
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    CActiveScheduler *scheduler = new(ELeave) CActiveScheduler;
+    CActiveScheduler::Install( scheduler );
+
+    User::RenameThread( KHtiWatchDogName );
+
+    TRAPD( err, StartL() );
+
+    delete scheduler;
+    delete cleanup;
+
+   __UHEAP_MARKEND;
+
+    return err;
+    }
+
+
+// End of File
Binary file hti/PC_Tools/DataGateway/BIN/DataGateway.exe has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/DataGateway.sln	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,22 @@
+Microsoft Visual Studio Solution File, Format Version 9.00
+# Visual Studio 2005
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DataGateway", "DataGateway.vcproj", "{B090938F-AA4D-4858-A400-B73A231FE55C}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Release|Win32 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{B090938F-AA4D-4858-A400-B73A231FE55C}.Debug|Win32.ActiveCfg = Debug|Win32
+		{B090938F-AA4D-4858-A400-B73A231FE55C}.Debug|Win32.Build.0 = Debug|Win32
+		{B090938F-AA4D-4858-A400-B73A231FE55C}.Release|Win32.ActiveCfg = Release|Win32
+		{B090938F-AA4D-4858-A400-B73A231FE55C}.Release|Win32.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(DPCodeReviewSolutionGUID) = preSolution
+		DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000}
+	EndGlobalSection
+EndGlobal
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/DataGateway.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,460 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="DataGateway"
+	ProjectGUID="{B090938F-AA4D-4858-A400-B73A231FE55C}"
+	RootNamespace="DataGateway"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory=".\Release"
+			IntermediateDirectory=".\Release"
+			ConfigurationType="1"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			UseOfMFC="0"
+			ATLMinimizesCRunTimeLibraryUsage="false"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TypeLibraryName=".\Release/DataGateway.tlb"
+				HeaderFileName=""
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="1"
+				AdditionalIncludeDirectories=".\inc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_WIN32_DCOM;_CRT_SECURE_NO_DEPRECATE"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				RuntimeTypeInfo="true"
+				UsePrecompiledHeader="0"
+				PrecompiledHeaderFile=".\Release/DataGateway.pch"
+				AssemblerListingLocation=".\Release/"
+				ObjectFile=".\Release/"
+				ProgramDataBaseFileName=".\Release/"
+				WarningLevel="3"
+				SuppressStartupBanner="true"
+				CompileAs="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG"
+				Culture="1035"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="odbc32.lib odbccp32.lib ws2_32.lib"
+				OutputFile=".\Release/DataGateway.exe"
+				LinkIncremental="1"
+				SuppressStartupBanner="true"
+				ProgramDatabaseFile=".\Release/DataGateway.pdb"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy &quot;$(ProjectDir)&quot;ini\datagateway.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(ProjectDir)&quot;ini\serialplugin.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(ProjectDir)&quot;ini\ipcommplugin.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory=".\Debug"
+			IntermediateDirectory=".\Debug"
+			ConfigurationType="1"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			UseOfMFC="0"
+			ATLMinimizesCRunTimeLibraryUsage="false"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TypeLibraryName=".\Debug/DataGateway.tlb"
+				HeaderFileName=""
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories=".\inc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_WIN32_DCOM;_CRT_SECURE_NO_DEPRECATE"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				RuntimeTypeInfo="true"
+				UsePrecompiledHeader="0"
+				PrecompiledHeaderFile=".\Debug/DataGateway.pch"
+				AssemblerListingLocation=".\Debug/"
+				ObjectFile=".\Debug/"
+				ProgramDataBaseFileName=".\Debug/"
+				WarningLevel="3"
+				SuppressStartupBanner="true"
+				DebugInformationFormat="4"
+				CompileAs="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="_DEBUG"
+				Culture="1035"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="odbc32.lib odbccp32.lib ws2_32.lib"
+				OutputFile=".\Debug/DataGateway.exe"
+				LinkIncremental="1"
+				SuppressStartupBanner="true"
+				GenerateDebugInformation="true"
+				ProgramDatabaseFile=".\Debug/DataGateway.pdb"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy &quot;$(ProjectDir)&quot;ini\datagateway.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(ProjectDir)&quot;ini\serialplugin.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(ProjectDir)&quot;ini\ipcommplugin.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+			>
+			<File
+				RelativePath="src\common.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath="src\datagateway.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\Src\IPComm.cpp"
+				>
+			</File>
+			<File
+				RelativePath="src\main.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath="src\plugin.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\Src\safequeue.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\src\SerialComm.cpp"
+				>
+			</File>
+			<File
+				RelativePath="src\Socket.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\src\stdafx.cpp"
+				>
+			</File>
+			<File
+				RelativePath="src\sync.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath="src\util.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="inc\common.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\datagateway.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\error.h"
+				>
+			</File>
+			<File
+				RelativePath=".\INC\IPCommPlugin.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\plugin.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\safequeue.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\SerialCommPlugin.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\Socket.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\sync.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\thread.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\util.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/IPCommPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,227 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of IPCommPlugin,
+*	IPCommReaderThread, IPCommWriterThread and IPCommMonitorThread classes.
+*/
+
+#ifndef IPCOMMPLUGIN_H
+#define IPCOMMPLUGIN_H
+
+//#pragma warning ( disable : 4786 )
+#include <iostream>
+#include <process.h>
+#include <string>
+#include <map>
+#include <WinSock2.h>
+
+
+#include "common.h"
+#include "plugin.h"
+#include "safequeue.h"
+#include "thread.h"
+#include "datagateway.h" // for g_DataGatewayDefaultTcpIpBufferSize
+
+// forward declarations
+class Socket;
+
+using namespace std;
+
+#define IP_INI_FILE_NAME             "ipcommplugin.ini"
+
+#define IP_INI_LOCAL_PORT_PARAM        "LOCAL_PORT"
+#define PARAM_SWITCH_LOCAL_PORT_PARAM  "-LOCAL_PORT"
+#define IP_INI_REMOTE_HOST_PARAM       "REMOTE_HOST"
+#define PARAM_SWITCH_REMOTE_HOST_PARAM "-REMOTE_HOST"
+#define IP_INI_REMOTE_PORT_PARAM       "REMOTE_PORT"
+#define PARAM_SWITCH_REMOTE_PORT_PARAM "-REMOTE_PORT"
+
+const DWORD g_IPCommDefaultTimeout    = 40000; //ms
+const DWORD g_IPPluginTimeout         = 10000; //not used
+
+// Maximum time to wait
+extern long g_MaximumShutdownWaitTime;
+
+//**********************************************************************************
+// Class IPCommReaderThread
+//
+// This thread is used to read bytes from TCP/IP socket, encapsulate the bytes to Data objects 
+// and push them to incoming queue 
+//**********************************************************************************
+
+class IPCommReaderThread : public Thread<IPCommReaderThread>
+{
+public:
+	IPCommReaderThread(SafeQueue<Data*>* q, long bufsize);
+	/*
+	 * Main execution loop which reads bytes from socket, encapsulates the bytes to Data object and pushes them to incoming queue
+	 */	
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	friend class IPCommMonitorThread;
+	//incoming queue
+	SafeQueue<Data*>* m_Queue;
+	//Socket connected to mobile device
+	Socket* m_Socket;
+	bool m_Running;
+	//size of buffer used when reading data from socket
+	long m_TcpIpBufferSize;
+};
+
+//**********************************************************************************
+// Class IPCommWriterThread
+//
+// This thread is used to write data from outgoing queue to TCP/IP port
+//**********************************************************************************
+
+class IPCommWriterThread : public Thread<IPCommWriterThread>
+{
+public:
+	IPCommWriterThread(SafeQueue<Data*>* q);
+	/*
+	 * Main execution loop which gets Data from outgoing queue and sends it to socket
+	 */
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	friend class IPCommMonitorThread;
+	//outgoing queue
+	SafeQueue<Data*>* m_Queue;
+	//Socket connected to mobile device
+	Socket* m_Socket;
+	bool m_Running;
+};
+
+//**********************************************************************************
+// Class IPCommMonitorThread
+//
+// This thread creates and starts reader and writer threads
+// The thread also monitors if reader and writer threads are running and restarts them in case either isn't running
+//**********************************************************************************
+
+class IPCommMonitorThread : public Thread<IPCommMonitorThread>
+{
+public:
+	IPCommMonitorThread(SafeQueue<Data*>* TxQueue,
+		                SafeQueue<Data*>* RxQueue,
+						int m_LocalPort,
+						string& m_RemoteHost,
+						int m_RemotePort);
+	~IPCommMonitorThread();
+	/*
+	 * Main execution loop of thread
+	 * -Creates reader and writer threads and starts them
+	 * -Monitors if either reader or writer thread aren't running and restarts them if not
+	 */
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	/*
+	 * This method has two functionalities
+	 * -It waits for incoming connections if local port is defined
+	 * -It tries to connect to remote host if local host is not defined
+	 */
+	void Connect(Socket*& s);
+
+private:
+	bool                m_Running;
+
+	//outgoing queue
+	SafeQueue<Data*>*   m_TxQueue;
+	//incoming queue
+	SafeQueue<Data*>*   m_RxQueue;
+	//used to read data from TCP/IP port and push them to incoming queue
+	IPCommReaderThread* m_ReaderThread;
+	//used to write data from outgoing queue to TCP/IP port
+	IPCommWriterThread* m_WriterThread;
+	//port that thread should listen to
+	int					m_LocalPort;
+	//hostname that thread should connect to
+	string&				m_RemoteHost;
+    //Port that thread should connect to
+	int					m_RemotePort;
+};
+
+//**********************************************************************************
+// Class IPCommPlugin
+//
+// This class implements a CommChannelPlugin used in TCP/IP communication with device
+//**********************************************************************************
+
+class IPCommPlugin : public CommChannelPlugin
+{
+public:
+	/*
+	 * This method initializes IPCommPlugin and Starts IPCommMonitorThread
+	 */
+	DWORD Init();
+	/*
+	 * This method is used to push given data to outgoing queue and then 
+	 * wait for data to become available and read all data into single Data object 
+	 */	
+	DWORD SendReceive( Data* data_in, Data** data_out, long timeout = g_IPPluginTimeout );
+	/*
+	 * This method pushes the given Data object(of type Data::EData) to outgoing queue
+	 */	
+	DWORD Send( Data* data_in, long timeout = g_IPPluginTimeout );
+	/*
+	 * This method is used to read all data in incoming queue to single Data object and store the result
+	 * to the data object given parameter
+	 */	
+	DWORD Receive( Data** data_out, long timeout = g_IPPluginTimeout );
+	/*
+	 * This method is used to wait for data to become available in incoming queue 
+	 * and then read all data into single Data object which is given as parameter
+	 */	
+	DWORD ReceiveWait( Data** data_out, long timeout = g_IPPluginTimeout );
+	/*
+	 * This method checks if data is available on incoming queue
+	 */	
+	bool IsDataAvailable();
+	DWORD Open();
+	DWORD Close();
+	IPCommPlugin( const CommChannelPluginObserver* observer = NULL );
+	~IPCommPlugin();
+
+private:
+	/*
+	 * This method initializes class member variables from values in map
+	 */
+	void CheckProperties( map<string, string>& props );
+
+private:
+	//outgoing queue
+	SafeQueue<Data*>	m_TxQueue;
+	//incoming queue
+	SafeQueue<Data*>	m_RxQueue;
+	//thread which starts and monitors reader and writer threads
+	IPCommMonitorThread* m_MonitorThread;
+	//port that IPCommPlugin should listen to
+	int					m_PropertyLocalPort;
+	//hostname that IPCommPlugin should connect to
+	string				m_PropertyRemoteHost;
+	//port that IPCommPlugin should connect to
+	int					m_PropertyRemotePort;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/SerialCommPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,205 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of SerialComm communication channel plugin objects. 
+*   These classes are SerialComm, SerialCommPlugin and SerialCommIoThread classes.
+*/
+
+#ifndef SERIALCOMMPLUGIN_H
+#define SERIALCOMMPLUGIN_H
+
+#pragma warning ( disable : 4786 )
+#include <iostream>
+#include <process.h>
+#include <string>
+#include <map>
+#include <comdef.h>
+
+#include "common.h"
+#include "plugin.h"
+#include "safequeue.h"
+#include "thread.h"
+
+using namespace std;
+
+#define SERIAL_INI_FILE_NAME             "serialplugin.ini"
+
+#define SERIAL_INI_INIT_PARAM            "INIT_STRING"
+#define PARAM_SWITCH_INIT_PARAM          "-INIT_STRING"
+#define SERIAL_INI_COMPORT_PARAM         "COMPORT"
+#define PARAM_SWITCH_COMPORT_PARAM       "-COMPORT"
+#define SERIAL_INI_COMPORT_TIMEOUT       "TIMEOUT"
+#define PARAM_SWITCH_COMPORT_TIMEOUT     "-TIMEOUT"
+#define SERIAL_INI_USE_HW_FLOW_CONTROL   "HW_FLOWCONTROL"
+#define PARAM_SWITCH_USE_HW_FLOW_CONTROL "-HW_FLOWCONTROL"
+#define SERIAL_INI_SEND_SLEEP_PAUSE      "SEND_PAUSE"
+#define PARAM_SWITCH_SEND_SLEEP_PAUSE    "-SEND_PAUSE"
+#define SERIAL_INI_SEND_SIZE             "SEND_SIZE"
+#define PARAM_SWITCH_SEND_SIZE           "-SEND_SIZE"
+
+#define SERIAL_DEFAULT_INIT_STRING       "115200,n,8,1"
+#define SERIAL_DEFAULT_COMPORT           "COM2"
+
+const DWORD g_SerialCommDefaultTimeout    = 40000; //ms
+const DWORD g_SerialPluginTimeout         = 10000; //not used
+const long  g_SerialCommDefaultSendPause  = 0;
+
+// Maximum time to wait
+extern long g_MaximumShutdownWaitTime;
+
+//**********************************************************************************
+// Class SerialComm
+//
+// This class implements the actual serial communication
+//**********************************************************************************
+
+class SerialComm
+{
+public:
+	SerialComm();
+	~SerialComm();
+	/*
+	 * This method opens a communication device that uses serial communication and
+	 * configures it according initialization parameters
+	 */	
+	WORD Open( const string& commPort, const string& initParameters, long timeout,
+				bool hwFlowControl, long sendPause, long sendMaxSize );
+	DWORD Close();
+	/*
+	 * This method is used to send Data object using serial communication
+	 */	
+	DWORD Send(const Data& data_in);
+	/*
+	 * This method reads all available data from communication media 
+	 * and returns it in the Data object given as parameter
+	 */
+	DWORD Receive(Data* data_out);
+	/*
+	 * This method returns number of bytes available in incoming queue or
+	 * -1 if communication error has occurred
+	 */
+	LONG  GetRxBytesAvailable();
+private:
+	//handle to communication resource
+	HANDLE m_Com;
+	bool m_Open;
+	long m_SendPause;
+	long m_SendMaxSize;
+};
+
+//**********************************************************************************
+// Class SerialCommIoThread
+//
+// This thread is used to send data from outgoing queue to serial port
+// and read bytes from serial port and push it to incoming queue 
+//**********************************************************************************
+
+class SerialCommIoThread : public Thread<SerialCommIoThread>
+{
+public:
+	SerialCommIoThread(SafeQueue<Data*>* in, SafeQueue<Data*>* out,
+						const string& init, const string& commPort, long timeout,
+						bool hwFlowControl, long sendPause, long sendMaxSize);
+	/*
+	 * Main execution loop which is used to send Data from outgoing queue to serial port
+	 * and read bytes from serial port, encapsulate it to Data objects and push them to incoming queue 
+	 */	
+	void Run();
+	void Stop();
+	void SetTimeout(long timeout);
+	long GetTimeout() const;
+	Event GetOpenedEvent();
+private:
+	//incoming queue
+	SafeQueue<Data*>* m_InQueue;
+	//outgoing queue
+	SafeQueue<Data*>* m_OutQueue;
+	Event m_OpenedEvent;
+	bool m_Running;
+	long m_PropertySerialCommTimeout;
+	const string& m_InitString;
+	const string& m_CommPort;
+	long m_ProperySerialSendPause;
+	bool m_PropertySerialHwFlowControl;
+	long m_PropertySerialMaxSendSize;
+};
+
+//**********************************************************************************
+// Class SerialCommPlugin
+//
+// This class implements a CommChannelPlugin used in serial communication with device
+//**********************************************************************************
+
+class SerialCommPlugin : public CommChannelPlugin
+{
+public:
+	/*
+	 * This method initializes SerialCommPlugin and starts SerialCommPluginIoThread
+	 */
+	DWORD Init();
+	/*
+	 * This method is used to:
+	 * -push given data to outgoing queue
+	 * -wait for data to become available in incoming queue
+	 * -pop the first Data object from queue and store it to the Data object given as parameter
+	 */	
+	DWORD SendReceive(Data* data_in, Data** data_out, long timeout = g_SerialCommDefaultTimeout);
+	/*
+	 * This method pushes the given Data object(of type Data::EData) to outgoing queue
+	 */	
+	DWORD Send(Data* data_in, long timeout = g_SerialCommDefaultTimeout);
+	/*
+	 * This method is used to pop the first data object from incoming queue and store it to data object given as parameter
+	 */	
+	DWORD Receive(Data** data_out, long timeout = g_SerialCommDefaultTimeout);
+	/*
+	 * This method is used to wait for data to become available in incoming queue 
+	 * and then pop the first Data object from the queue and and store it to Data object given as parameter.
+	 */	
+	DWORD ReceiveWait(Data** data_out, long timeout = g_SerialCommDefaultTimeout);
+	/*
+	 * This method checks if data is available on incoming queue
+	 */	
+	bool IsDataAvailable();
+	DWORD Open();
+	/*
+	 * This method stops SerialCommIoThread and waits for it to be in signaled state
+	 */	
+	DWORD Close();
+	SerialCommPlugin(const CommChannelPluginObserver* observer = NULL);
+	~SerialCommPlugin();
+private:
+	/*
+	 * This method initializes class member variables from values in map
+	 */
+	void CheckProperties(map<string, string>& props);
+private:
+    //outgoing queue
+	SafeQueue<Data*> m_TxQueue;
+	//incoming queue
+	SafeQueue<Data*> m_RxQueue;
+	SerialCommIoThread* m_IoThread;
+	//map that properties are read to from ini file
+	map<string, string> m_SerialCommPluginProperties;
+	long m_PropertySerialCommTimeout;
+	string m_PropertySerialCommInitString;
+	string m_PropertySerialCommPort;
+	long m_ProperySerialSendPause;
+	bool m_PropertySerialHwFlowControl;
+	long m_PropertySerialMaxSendSize;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/Socket.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,144 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of Socket, SocketClient, SocketServer and
+*   SocketSelect classes.
+*/
+
+#ifndef __SOCKET_H__
+#define __SOCKET_H__
+
+#include <WinSock2.h>
+
+#include <string>
+
+
+typedef std::string String;
+
+//**********************************************************************************
+// Class Socket
+//
+// This class encapsulates Windows Sockets API Socket functionality
+//**********************************************************************************
+
+class Socket {
+public:
+	Socket(SOCKET s);
+	Socket();
+	virtual ~Socket();
+	Socket(const Socket&);
+	Socket& operator=(Socket&);
+
+	/*
+	 * This method is used to read characters from socket until line separator is encountered
+	 * Returns String including line separator
+	 */
+	String ReceiveLine();
+	/*
+	 * This method is used to read bytes from socket. The method reads all available and combines them to returned String object
+	 */
+	String ReceiveBytes();
+	/*
+	 * This method reads up to maximum amount of bytes from socket to the Data object given as parameter
+	 * The maximum amount is given as parameter
+	 */
+	int ReceiveBytes(BYTE *data, int bytes);
+
+	void   Close();
+
+	/*
+	 * This method is used to send String as a line
+	 * The parameter of SendLine is not a const reference
+	 * because SendLine modifes the String passed.
+	 */
+	void   SendLine (String);
+
+	/*
+	 * This method is used to send String as bytes
+	 * The parameter is a const reference
+	 * because the methos does not modify the String passed 
+	 * (in contrast to SendLine).
+	 */
+	void   SendBytes(const String&);
+	/*
+	 * This method is used to send specific amount of bytes of String
+	 * The parameter is a const reference
+	 * because the methos does not modify the String passed 
+	 * (in contrast to SendLine).
+	 */
+	int SendBytes(const BYTE* data, int bytes);
+
+protected:
+	friend class SocketServer;
+	friend class SocketSelect;
+	//winsock socket
+	SOCKET s_;
+
+	int* refCounter_;
+
+private:
+	static void Start();
+	static void End();
+	static int  nofSockets_;
+};
+
+//**********************************************************************************
+// Class SocketClient
+//
+//**********************************************************************************
+
+class SocketClient : public Socket {
+public:
+  SocketClient(const String& host, int port);
+};
+
+//**********************************************************************************
+// Class SocketServer
+//
+// This class is used to:
+// -listen for incoming connections to a Socket
+// -connect to socket
+//**********************************************************************************
+
+class SocketServer// : public Socket 
+{
+public:
+	SocketServer();
+	/*
+	 * This method binds and opens the given socket to listening mode 
+	 */
+	void Accept(Socket*& s, int port, int connections, String& remoteHost);
+	/*
+	 * This method establishes a connection to the socket
+	 */
+	void Connect(Socket* s, const char* remoteHost, int remotePort);
+};
+
+//**********************************************************************************
+// Class SocketSelect
+//
+//**********************************************************************************
+
+class SocketSelect {
+  public:
+    SocketSelect(Socket const * const s1, Socket const * const s2);
+
+    bool Readable(Socket const * const s);
+
+  private:
+    fd_set fds_;
+}; 
+
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/common.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*     This file contains the headers of the Data and ParameterList classes.
+*/
+
+#ifndef COMMON_H
+#define COMMON_H
+
+#pragma warning ( disable : 4786 )
+
+#include <windows.h>
+
+//**********************************************************************************
+// Class Data
+// 
+// This class provides data encapsulattion for DataGateway
+//**********************************************************************************
+
+class Data
+{
+public:
+	//type of data
+	enum DataType { EEmpty = 0, EControl, EError, EData };
+public:
+	Data(const void* data_in = NULL, DWORD length = 0, DataType type = EEmpty);
+	Data(const void* data_in, DWORD length, DWORD offset, DataType type);
+	Data(const Data& d);
+	virtual ~Data();
+	/*
+	 * returns data in given parameter
+	 */
+	virtual void* GetData(void* data_out = NULL) const;
+	/*
+	 * returns length of data 
+	 */
+	virtual DWORD GetLength() const;
+	/*
+	 * returns type of data
+	 * can be one of the following: EEmpty, EControl, EError, EData
+	 */
+	DataType GetType() const;
+	/*
+	 * This method copies up to length bytes from given data object to class member data object
+	 */
+	bool SetData(const void* data_in, DWORD length, DataType type);
+	/*
+	 * This method copies up to length bytes(starting from offset) from given data object to class member data object
+	 */
+	bool SetData(const void* data_in, DWORD length, DWORD offset, DataType type);
+	/*
+	 * Used to combine different messages into one.
+	 * This method appends new data at the end of already excisting data.
+	 * If new data isn't same type as excisting data it isn't appended.
+	 * Returns bool value of whether the method has succeeded to append the data or not.
+	 */
+	virtual bool AppendData(Data* aData);
+	/*
+	 * This method is used to delete data and set data type to EEmpty
+	 */
+	void FreeData();
+private:
+	//actual data
+	void* m_pData;
+	//length of data
+	DWORD m_dwLength;
+	//type of data
+	DataType m_Type;
+};
+
+const BYTE ControlPhonePowered = 0x01;
+
+const Data CtrlMessagePhonePowered((void*)&ControlPhonePowered, 1, 0, Data::EControl);
+
+const BYTE ErrorSendingData = 0x81;
+
+const Data ErrorMessageSendingData((void*)&ErrorSendingData, 1, 0, Data::EError);
+
+//**********************************************************************************
+// Class ParameterList
+//
+//**********************************************************************************
+
+#include <map>
+#include <string>
+
+using namespace std;
+
+class ParameterList
+{
+public:
+	void Add(const string& key, const void* value);
+	const void* Get(const string& key);
+	ParameterList();
+	~ParameterList();
+private:
+	map<const string,const void*> m_Map;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/datagateway.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,184 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the headers of DataGatewaySocketWriterThread,
+*	DataGatewaySocketReaderThread, DataGatewayClientThread and DataGateway
+*	classes.
+*/
+
+#ifndef DATAGATEWAY_H
+#define DATAGATEWAY_H
+
+#pragma warning ( disable : 4786 )
+
+#include "Socket.h"
+
+#include <windows.h>
+#include <process.h>
+
+#include "util.h"
+#include "common.h"
+#include "plugin.h"
+#include "safequeue.h"
+#include "thread.h"
+
+const int g_DataGatewayDefaultTcpIpPort       = 2000;
+const int g_DataGatewayDefaultTcpIpBufferSize = 8 * 1024;
+
+// Maximum time to wait
+extern long g_MaximumShutdownWaitTime;
+
+extern DWORD g_ErrorCode;
+
+//**********************************************************************************
+// Class DataGatewaySocketWriterThread
+//
+// This thread is used to read Data from outgoing queue 
+// and write it to Socket(connected to program using DataGateway)
+//**********************************************************************************
+
+class DataGatewaySocketWriterThread : public Thread<DataGatewaySocketWriterThread>
+{
+public:
+	DataGatewaySocketWriterThread(SafeQueue<Data*>* q, Socket* s);
+	/*
+	 * Main loop of thread
+	 * Reads Data from outgoing queue and writes it to Socket(connected to program using DataGateway)
+	 */
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	//outgoing queue
+	SafeQueue<Data*>* m_Queue;
+	//socket to which software using DataGateway is connected to
+	Socket* m_Socket;
+	bool m_Running;
+};
+
+//**********************************************************************************
+// Class DataGatewaySocketReaderThread
+//
+// This thread is used to read incoming bytes from Socket(connected to program using DataGateway)
+// which it then encapsulates into Data objects and forwards to outgoing queue
+//**********************************************************************************
+
+class DataGatewaySocketReaderThread : public Thread<DataGatewaySocketReaderThread>
+{
+public:
+	DataGatewaySocketReaderThread(SafeQueue<Data*>* q, long bufsize, Socket* s);
+	/*
+	 * Main loop of thread
+	 * Reads bytes from Socket(connected to program using DataGateway), encapsulates them to Data object and puts these to outgoing queue
+	 */
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	//incoming queue
+	SafeQueue<Data*>* m_Queue;
+	//socket to which software using DataGateway is connected to
+	Socket* m_Socket;
+	bool m_Running;
+	long m_TcpIpBufferSize;
+};
+
+//**********************************************************************************
+// Class DataGatewayClientThread
+//
+// This thread serves DataGateway's clients
+// Gets Data from incoming queue to which DataGatewaySocketReader has pushed it and forwards
+// them to CommChannelPlugin.
+// The thread also reads incoming data from CommChannelPlugin and forwards them to outgoing queue which
+// DataGatewaySocketWriter then reads
+//**********************************************************************************
+
+class DataGatewayClientThread : public Thread<DataGatewayClientThread>
+{
+public:
+	DataGatewayClientThread(Socket** s, long bufsize, const string& commchannel);
+	DataGatewayClientThread(Socket** s, long bufsize, CommChannelPlugin** f);
+	~DataGatewayClientThread();
+	/*
+	 * Main loop of thread
+	 * Gets Data from incoming queue to which DataGatewaySocketReader has pushed it and forwards
+	 * them to CommChannelPlugin.
+	 * Reads incoming data from CommChannelPlugin and forwards them to outgoing queue which
+	 * DataGatewaySocketWriter then reads
+	 */
+	void Run();
+	void Stop();
+
+private:
+	//incoming queue
+	SafeQueue<Data*> m_ReaderQueue;
+	//outgoing queue
+	SafeQueue<Data*> m_WriterQueue;
+	//used to read data from socket to incoming queue
+	DataGatewaySocketReaderThread m_ReaderThread;
+	//used to write data from outgoing queue to socket
+	DataGatewaySocketWriterThread m_WriterThread;
+	//Socket to which software using DataGateway is connected to
+	Socket** m_Socket;
+	//The CommChannelPlugin that is used in communication
+	CommChannelPlugin* m_CommChannelPlugin;
+	//determines which CommChannelPlugin is loaded
+	const string& m_CommChannelPluginName;
+	bool m_Running;
+	//This value states whether or not Communication Channel Plugin uses late initialization
+	bool m_CCLateInit;
+	//This value tells the buffer size that is used
+	long m_TcpIpBufferSize;
+};
+
+//**********************************************************************************
+// Class DataGateway
+//
+// This is the main thread of DataGateway
+//**********************************************************************************
+
+class DataGateway : public Thread<DataGateway>
+{
+public:
+	DataGateway(int port = g_DataGatewayDefaultTcpIpPort,
+		        long bufsize = g_DataGatewayDefaultTcpIpBufferSize,
+				const string& commchannel = "",
+				bool stayalive = false,
+				bool cclateinit = false);
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	//determines which CommChannelPlugin is loaded
+	const string& m_CommChannelPluginName;
+	//reference to CommChannelPlugin
+	CommChannelPlugin* m_CommChannelPlugin;
+	Event m_ShutdownEvent;
+	bool m_Running;
+	//tells whether DataGateway should stay alive after first client has disconnected
+	bool m_StayAlive;
+	//this value states whether or not Communication Channel Plugin uses late initialization
+	bool m_CCLateInit;
+	//the port which DataGateway listens for incoming connections
+    int m_TcpIpPort;
+	//buffer size used in communication
+    long m_TcpIpBufferSize;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/error.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,106 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains global definitions to errors
+*/
+
+#ifndef __ERROR__
+#define __ERROR__
+
+// GLOBAL DEFINES
+#define ERR_BASE			0x1000
+#define ERR_BASE_UTIL		(ERR_BASE + 0x0100)
+#define ERR_BASE_PHOENIX	(ERR_BASE + 0x0200)
+#define ERR_BASE_BLUETOOTH	(ERR_BASE + 0x0300)
+#define ERR_BASE_MTC		(ERR_BASE + 0x0400)
+#define ERR_BASE_DG	        (ERR_BASE + 0x0500)
+
+#define NO_ERRORS						0
+#define ERR_NO_PARAMS					(ERR_BASE + 1)
+#define ERR_UNKNOWN_COMMAND				(ERR_BASE + 2)
+
+#define ERR_UTIL_NO_PARAM_VALUE			(ERR_BASE_UTIL + 2)
+#define ERR_UTIL_UNKNOWN_PARAM			(ERR_BASE_UTIL + 3)
+#define ERR_UTIL_PROPERTIES_NOT_FOUND	(ERR_BASE_UTIL + 4)
+#define ERR_UTIL_NO_PROPERTY_VALUE		(ERR_BASE_UTIL + 5)
+
+#define ERR_BLUETOOTH_CONNECTION_FAILED			(ERR_BASE_BLUETOOTH + 1)
+#define ERR_BLUETOOTH_DISCONNECTION_FAILED		(ERR_BASE_BLUETOOTH + 2)
+#define ERR_BLUETOOTH_LOCAL_SERVICE_MISSING		(ERR_BASE_BLUETOOTH + 3)
+#define ERR_BLUETOOTH_REMOTE_SERVICE_MISSING	(ERR_BASE_BLUETOOTH + 4)
+#define ERR_BLUETOOTH_DEVICE_ADDRESS_MISSING	(ERR_BASE_BLUETOOTH + 5)
+
+#define ERR_MTC_INVALID_MODE	(ERR_BASE_MTC + 1)
+
+#define ERR_DG_SOCKET					 (ERR_BASE_DG + 1)
+#define ERR_DG_COMMCHANNEL				 (ERR_BASE_DG + 2)
+#define ERR_DG_UNINITIALISED_COMMCHANNEL (ERR_BASE_DG + 3)
+#define ERR_DG_COMMCHANNEL_INIT          (ERR_BASE_DG + 4)
+#define ERR_DG_UNKNOWN_COMMCHANNEL		 (ERR_BASE_DG + 5)
+#define ERR_DG_COMMCHANNEL_OPEN			 (ERR_BASE_DG + 6)
+#define ERR_DG_CONSOLEHANDLER			 (ERR_BASE_DG + 7)
+#define ERR_DG_CONNECTION_OPEN					 (ERR_BASE_DG + 8)
+#define ERR_DG_CONNECTION_INIT					 (ERR_BASE_DG + 9)
+#define ERR_DG_COMM_OPEN		         (ERR_BASE_DG + 10)
+#define ERR_DG_COMM_OPEN_TIMEOUT		 (ERR_BASE_DG + 11)
+#define ERR_DG_COMM_OPEN_QUERY			 (ERR_BASE_DG + 12)
+#define ERR_DG_COMM_DATA_RECV			 (ERR_BASE_DG + 13)
+#define ERR_DG_COMM_DATA_RECV_TIMEOUT   (ERR_BASE_DG + 14)
+#define ERR_DG_COMM_DATA_SEND			 (ERR_BASE_DG + 15)
+
+#define ERR_DG_COM_INIT					 (ERR_BASE_DG + 16)
+#define ERR_DG_COM_IF_QUERY				 (ERR_BASE_DG + 17)
+
+typedef struct
+{
+	DWORD err_code;
+	char *err_msg;
+} ErrorLookupEntry;
+
+static const ErrorLookupEntry ErrorLookupTable[] =
+	{
+		{ERR_DG_SOCKET,						"ERR_DG_SOCKET"},
+		{ERR_DG_COMMCHANNEL,				"ERR_DG_COMMCHANNEL"},
+		{ERR_DG_UNINITIALISED_COMMCHANNEL,	"ERR_DG_UNINITIALISED_COMMCHANNEL"},
+		{ERR_DG_COMMCHANNEL_INIT,			"ERR_DG_COMMCHANNEL_INIT"},
+		{ERR_DG_UNKNOWN_COMMCHANNEL,		"ERR_DG_UNKNOWN_COMMCHANNEL"},
+		{ERR_DG_COMMCHANNEL_OPEN,			"ERR_DG_COMMCHANNEL_OPEN"},
+		{ERR_DG_CONSOLEHANDLER,				"ERR_DG_CONSOLEHANDLER"},
+		{ERR_DG_CONNECTION_OPEN,		    "ERR_DG_CONNECTION_OPEN"},
+		{ERR_DG_COMM_OPEN_TIMEOUT,			"ERR_DG_COMM_OPEN_TIMEOUT"},
+		{ERR_DG_COMM_OPEN_QUERY,			"ERR_DG_COMM_OPEN_QUERY"},
+		{ERR_DG_COMM_DATA_RECV,				"ERR_DG_COMM_DATA_RECV"},
+		{ERR_DG_COMM_DATA_RECV_TIMEOUT,		"ERR_DG_COMM_DATA_RECV_TIMEOUT"},
+		{ERR_DG_COMM_DATA_SEND,				"ERR_DG_COMM_DATA_SEND"},
+
+
+		{ERR_DG_COM_INIT,					"ERR_DG_COM_INIT"},
+		{ERR_DG_COM_IF_QUERY,				"ERR_DG_COM_IF_QUERY"}
+	};
+
+#define ERROR_LOOKUP(x) \
+	for (int i = 0; i < sizeof(ErrorLookupTable); i++)										  \
+	{																					      \
+		if (ErrorLookupTable[i].err_code == x)												  \
+		{																			          \
+			char tmp[256];																	  \
+			sprintf(tmp, "[DataGateway] Error: %s (0x%04X)\n", ErrorLookupTable[i].err_msg,   \
+                                                               ErrorLookupTable[i].err_code); \
+			Util::Error(tmp);																  \
+		}																				      \
+	}
+
+#endif
+
+// End of file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/plugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the headers of Plugin, FrontendPlugin,
+*	CommChannelPlugin and CommChannelPluginObserver classes and implementation
+*	of DummyCommObserver.
+*/
+
+#ifndef PLUGIN_H
+#define PLUGIN_H
+
+#pragma warning ( disable : 4786 )
+
+#include <string>
+#include "common.h"
+
+using namespace std;
+
+//**********************************************************************************
+// Class Plugin
+//
+//**********************************************************************************
+
+class Plugin
+{
+public:
+	enum PluginType { null, dummy, frontend, comm_channel };
+
+public:
+	virtual PluginType GetType() { return null; }
+	virtual DWORD Init();
+	virtual const string& GetName(string *name = NULL);
+
+protected:
+	Plugin();
+
+protected:
+	string m_Name;
+};
+
+//**********************************************************************************
+// Class FrontendPlugin
+//
+//**********************************************************************************
+
+class FrontendPlugin : public Plugin
+{
+public:
+	virtual PluginType GetType() { return frontend; }
+	virtual DWORD Init();
+};
+
+//**********************************************************************************
+// Class CommChannelPluginObserver
+//
+//**********************************************************************************
+
+class CommChannelPluginObserver
+{
+public:
+	virtual void NotifyDataAvailable() = 0;
+	virtual void NotifyCommChannelOpened() = 0;
+	virtual void NotifyCommChannelClosed() = 0;
+};
+
+//**********************************************************************************
+// Class DummyCommObserver
+//
+//**********************************************************************************
+
+class DummyCommObserver : public CommChannelPluginObserver
+{
+public:
+	void NotifyDataAvailable() { };
+	void NotifyCommChannelOpened() { };
+	void NotifyCommChannelClosed() { };
+};
+
+//**********************************************************************************
+// Class CommChannelPlugin
+//
+// This class is the parent class of all communication channel plugins used
+// in DataGateway.
+//**********************************************************************************
+
+class CommChannelPlugin : public Plugin
+{
+public:
+	PluginType GetType() { return comm_channel; }
+	virtual DWORD Init();
+	virtual DWORD Open() = 0;
+	virtual bool IsOpen() { return m_Open; }
+	/*
+	 * This method closes and deletes the instance of plugin
+	 */
+	virtual DWORD Close() = 0;
+	/*
+	 * This method is used to send Data object and Receive Data object
+	 */
+	virtual DWORD SendReceive(Data* data_in, Data** data_out, long timeout = 5000) = 0;
+	/*
+	 * This method is used to send Data object
+	 */
+	virtual DWORD Send(Data* data_in, long timeout = 5000) = 0;
+	/*
+	 * This method is used to receive Data object
+	 */
+	virtual DWORD Receive(Data** data_out, long timeout = 5000) = 0;
+	/*
+	 * This method creates instance of specified plugin  
+	 */
+	static CommChannelPlugin* Instance(const string& pluginname,
+		                               const CommChannelPluginObserver* observer = NULL);
+	/*
+	 * This method initializes and connects the instance of plugin
+	 */
+	static DWORD Connect();
+	/*
+	 * This method closes and deletes the instance of plugin
+	 */
+	static DWORD Disconnect();
+
+protected:
+	CommChannelPlugin(const CommChannelPluginObserver* observer = NULL);
+	const CommChannelPluginObserver* GetObserver() { return m_Observer; }
+
+protected:
+	const CommChannelPluginObserver* m_Observer;
+	bool m_Open;
+
+private:
+	static CommChannelPlugin* m_Self;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/pluginmgr.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef PLUGINMGR_H
+#define PLUGINMGR_H
+
+class PluginManager
+{
+public:
+};
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/safequeue.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,216 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*    This file contains headers of SafeQueue template class.
+*/
+
+#ifndef SAFEQUEUE_H
+#define SAFEQUEUE_H
+
+#include "sync.h"
+
+//STL
+#pragma warning (push, 3)
+#pragma warning( disable : 4702 ) // Unreachable code warning
+#pragma warning( disable : 4290 ) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#include <queue>
+
+
+
+
+using namespace std;
+
+//**********************************************************************************
+// Template Class SafeQueue
+// 
+// This template class implements a thread safe queue with generic types
+//**********************************************************************************
+
+template <class T>
+class SafeQueue : private queue<T>,
+				  private Mutex,
+				  private Semaphore
+{
+public:
+    typedef typename queue<T>::size_type size_type;
+    SafeQueue();
+	~SafeQueue();
+	/*
+	 * Adds a new element to the end of the queue
+	 */
+	void push(const T& val);
+	/*
+	 * Removes the next element in the queue
+	 */
+	void pop(void);
+	/*
+	 * Returns whether the queue is empty or not
+	 */
+	bool empty(void) const;
+	/*
+	 * Returns a reference to the last element in the queue
+	 */
+	T& back(DWORD timeout = INFINITE) throw (TimeoutException);
+	/*
+	 * Returns a constant reference to the last element in the queue
+	 */
+	const T& back(DWORD timeout = INFINITE) const throw (TimeoutException);
+	/*
+	 * Returns a reference to the next element in the queue
+	 */
+	T& front(DWORD timeout = INFINITE) throw (TimeoutException);
+	/*
+	 * Returns a constant reference to the next element in the queue
+	 */
+	const T& front(DWORD timeout = INFINITE) const throw (TimeoutException);
+	/*
+	 * Returns the number of elements in the queue
+	 */
+	typename SafeQueue<T>::size_type size(void) const;
+	/*
+	 * This method is used to pop all of the elements in queue and return them in single Data object
+	 */
+	T& popAll(DWORD timeout = INFINITE) throw (TimeoutException);
+};
+
+template <class T>
+SafeQueue<T>::SafeQueue()
+{
+}
+
+template <class T>
+SafeQueue<T>::~SafeQueue()
+{
+}
+
+/*
+ * Adds a new element to the end of the queue
+ */
+template <class T>
+void SafeQueue<T>::push(const T& val)
+{
+	Mutex::Lock();
+	queue<T>::push(val);
+	Mutex::Unlock();
+	Semaphore::Notify();
+}
+
+/*
+ * Removes the next element in the queue
+ */
+template <class T>
+void SafeQueue<T>::pop(void)
+{
+	Mutex::Lock();
+	queue<T>::pop();
+	Mutex::Unlock();
+}
+
+/*
+ * Returns whether the queue is empty or not
+ */
+template <class T>
+bool SafeQueue<T>::empty(void) const
+{
+	const_cast<SafeQueue<T>*>(this)->Lock();
+	bool value = queue<T>::empty();
+	const_cast<SafeQueue<T>*>(this)->Unlock();
+	return value;
+}
+
+/*
+ * Returns a reference to the last element in the queue
+ */
+template <class T>
+T& SafeQueue<T>::back(DWORD timeout)
+	throw (TimeoutException)
+{
+	if (Semaphore::Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue back timed out");
+	}
+	Mutex::Lock();
+	T& value = queue<T>::back();
+	Mutex::Unlock();
+	return value;
+}
+
+/*
+ * Returns a constant reference to the last element in the queue
+ */
+template <class T>
+const T& SafeQueue<T>::back(DWORD timeout) const
+	throw (TimeoutException)
+{
+	if (const_cast<SafeQueue<T>*>(this)->Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue back timed out");;
+	}
+	const_cast<SafeQueue<T>*>(this)->Lock();
+	const T& value = queue<T>::back();
+	const_cast<SafeQueue<T>*>(this)->Unlock();
+	return value;
+}
+
+/*
+ * Returns a reference to the next element in the queue
+ */
+template <class T>
+T& SafeQueue<T>::front(DWORD timeout)
+	throw (TimeoutException)
+{
+	if (Semaphore::Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue front timed out");
+	}
+	Mutex::Lock();
+	T& value = queue<T>::front();
+	Mutex::Unlock();
+	return value;
+}
+
+/*
+ * Returns a constant reference to the next element in the queue
+ */
+template <class T>
+const T& SafeQueue<T>::front(DWORD timeout) const
+	throw (TimeoutException)
+{
+	if (const_cast<SafeQueue<T>*>(this)->Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue front timed out");
+	}
+	const_cast<SafeQueue<T>*>(this)->Lock();
+	const T& value = queue<T>::front();
+	const_cast<SafeQueue<T>*>(this)->Unlock();
+	return value;
+}
+
+/*
+ * Returns the number of elements in the queue
+ */
+template <class T>
+typename SafeQueue<T>::size_type SafeQueue<T>::size(void) const
+{
+	const_cast<SafeQueue<T>*>(this)->Lock();
+	queue<T>::size_type value = queue<T>::size();
+	const_cast<SafeQueue<T>*>(this)->Unlock();
+	return value;
+}
+
+#pragma warning (pop)
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/stdafx.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// stdafx.h : include file for standard system include files,
+// or project specific include files that are used frequently, but
+// are changed infrequently
+//
+
+#pragma once
+
+
+#include <iostream>
+#include <tchar.h>
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/sync.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,101 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of synchronziation objects. These classes are Mutex, Semaphore and
+*   Event classes. Implementation of TimeoutException is defined.
+*/
+
+#ifndef SYNC_H
+#define SYNC_H
+
+#include <windows.h>
+#include <process.h>
+
+#include <string>
+
+using namespace std;
+
+//**********************************************************************************
+// Class TimeoutException
+//
+//**********************************************************************************
+
+class TimeoutException
+{
+public:
+	TimeoutException(const char* s = "") { m_Message.assign(s); }
+	const string& GetMessage() const { return m_Message; }
+private:	
+	string m_Message;
+};
+
+//**********************************************************************************
+// Class Mutex
+//
+// This class implements a Mutex using Windows API synchronization mechanism 
+//**********************************************************************************
+
+
+class Mutex
+{
+public:
+	Mutex(void);
+	~Mutex(void);
+	void Lock(void);
+	void Unlock(void);
+private:
+	CRITICAL_SECTION m_Lock;
+};
+
+//**********************************************************************************
+// Class Semaphore
+//
+// This class encapsulates Windows API Semaphore functionality
+//**********************************************************************************
+
+class Semaphore
+{
+public:
+	Semaphore(void);
+	Semaphore(int available);
+	~Semaphore(void);
+	DWORD Wait(DWORD timeout = INFINITE);
+	void Notify(void);
+	void Notify(int how_many);
+private:
+	HANDLE m_Semaphore;
+};
+
+//**********************************************************************************
+// Class Event
+//
+// This class encapsulates Windows API Event functionality
+//**********************************************************************************
+
+class Event
+{
+public:
+	Event(bool manual_reset = false);
+	~Event(void);
+	void Set(void);
+	void Reset(void);
+	DWORD Wait(DWORD timeout = INFINITE);
+	HANDLE EventHandle() const;
+private:
+	HANDLE m_Event;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/thread.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,200 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of template class Thread and ThreadData.
+*	Interface Runnable is defined.
+*/
+
+#ifndef THREAD_H
+#define THREAD_H
+
+#include "sync.h"
+#include <process.h>
+
+
+typedef unsigned (__stdcall *THREAD_START_FUNC) (void *);
+
+
+//**********************************************************************************
+// Template Class ThreadData
+//
+//**********************************************************************************
+
+template <class T>
+struct ThreadData
+{
+	public:
+		typedef void (T::*TFunc)();
+		HANDLE m_hEvent;
+		T* m_pThreadObject;
+		TFunc m_pThreadFunc;
+		static DWORD _ThreadFunc(ThreadData<T>* pThis)
+		{
+			ThreadData<T> td = *pThis;
+			SetEvent(td.m_hEvent);
+			((*(td.m_pThreadObject)).*(td.m_pThreadFunc))();
+			return 0;
+		}
+};
+
+//**********************************************************************************
+// Template Class Runnable
+// 
+//**********************************************************************************
+
+class Runnable
+{
+	public:
+		virtual void Run() = 0;
+		virtual void Stop() = 0;
+};
+
+//**********************************************************************************
+// Template Class Thread
+//
+// This is the template for thread class, implemented by all threads in DataGateway
+// The template encapsulates Windows API tread functionality
+//**********************************************************************************
+
+template <class T>
+class Thread : public Runnable
+{
+	public:
+		Thread();
+		Thread(Runnable* runnable);
+		~Thread();
+		void Run();
+		void Start();
+		void Stop();
+		void Suspend();
+		void Resume();
+		HANDLE ThreadHandle();
+	private:
+		HANDLE CreateMemberThread(Runnable* p,
+			                      void (Runnable::*func)());
+	private:
+		HANDLE m_hMemberThread;
+		Runnable* m_Runnable;
+};
+
+template <class T>
+Thread<T>::Thread()
+{
+	m_hMemberThread = NULL;
+	m_Runnable = this;
+}
+
+template <class T>
+Thread<T>::Thread(Runnable* runnable)
+{
+	m_hMemberThread = NULL;
+	if (runnable != NULL)
+	{
+		m_Runnable = runnable;
+	}
+	else
+	{
+		m_Runnable = this;
+	}
+}
+
+template <class T>
+Thread<T>::~Thread()
+{
+	if (m_hMemberThread != NULL)
+	{
+		CloseHandle(m_hMemberThread);
+	}
+	m_Runnable = NULL;
+}
+
+template <class T>
+void Thread<T>::Run()
+{
+}
+
+template <class T>
+void Thread<T>::Suspend()
+{
+	if (m_hMemberThread != NULL)
+	{
+		SuspendThread(m_hMemberThread);
+	}
+}
+
+template <class T>
+void Thread<T>::Resume()
+{
+	if (m_hMemberThread != NULL)
+	{
+		ResumeThread(m_hMemberThread);
+	}
+}
+
+template <class T>
+void Thread<T>::Start()
+{
+	if (m_Runnable != NULL)
+	{
+		m_hMemberThread = CreateMemberThread(m_Runnable,
+											 &Runnable::Run);
+		if (m_hMemberThread == NULL)
+		{
+			cerr << "Thread: could not create thread" << endl;
+		}		
+	}
+	else
+	{
+		m_hMemberThread = NULL;
+		cerr << "Thread: threadfunc NULL" << endl;
+	}
+}
+
+template <class T>
+void Thread<T>::Stop()
+{
+	m_Runnable->Stop();
+}
+
+template <class T>
+HANDLE Thread<T>::ThreadHandle()
+{
+	return m_hMemberThread;
+}
+
+template <class T>
+HANDLE Thread<T>::CreateMemberThread(Runnable* p,
+									 void (Runnable::*func)())
+{
+	ThreadData<Runnable> td;
+	td.m_pThreadObject = p;
+	td.m_pThreadFunc = func;
+	td.m_hEvent = CreateEvent(NULL, 0, 0, NULL);
+
+	unsigned int Dummy;
+	HANDLE ThreadHandle = (HANDLE)_beginthreadex(NULL,
+		                               NULL,
+									   (THREAD_START_FUNC)ThreadData<Runnable>::_ThreadFunc,
+									   &td,
+									   NULL,
+									   &Dummy);
+
+	WaitForSingleObject(td.m_hEvent,INFINITE);
+	CloseHandle(td.m_hEvent);
+	return ThreadHandle;
+}
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INC/util.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,208 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of the Util and UtilError.
+*/
+
+#ifndef UTIL_H
+#define UTIL_H
+
+#pragma warning (push, 3)
+#pragma warning( disable : 4702 ) // Unreachable code warning
+#pragma warning( disable : 4290 ) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#pragma warning ( disable : 4786 )
+
+// INCLUDE FILES
+#include <iostream>
+#include <fstream>
+#include <map>
+#include <string>
+#include <time.h>
+#include <windows.h>
+#include <sys/timeb.h>
+#include "error.h"
+
+#define ENABLE_LOG_SYNC //makes logging methods synced to access by multiple threads
+
+#ifdef ENABLE_LOG_SYNC 
+	#include "sync.h"
+#endif
+
+using namespace std;
+
+//**********************************************************************************
+// Class UtilError
+//
+// Error class which is thrown if an exception occurs
+// in Util operations. Holds error code and string.
+//**********************************************************************************
+class UtilError
+{
+public:
+	string iError;
+	HRESULT iResult;
+	UtilError(string aError, HRESULT aResult)
+	{
+		iError = aError;
+		iResult = aResult;
+	}
+};
+
+//**********************************************************************************
+// Class Util
+//
+// Provides static utility functions for logging and string handling.
+//**********************************************************************************
+class Util
+{
+public: // Enumerations
+	enum VerboseLevel {none,     // no output
+		               result,   // only result is reported
+					   error,    // errors reported
+					   info,     // more info reported
+					   debug};
+
+public: // Constructors
+	/*
+	 * Default constructor which initializes logging level.
+	 */
+	Util(const VerboseLevel aVerbose = none) { iVerbose = aVerbose; }
+
+public:
+	/*
+	 * Returns current verbose level.
+	 */
+	static VerboseLevel GetVerboseLevel();
+
+	/*
+	 * Sets new verbose level by string "none", "result", "error", "info" or "debug"
+	 */
+	static void SetVerboseLevel(const string& aVerbose);
+
+	/*
+	 * Sets new verbose level by enumeration.
+	 */
+	static void SetVerboseLevel(const VerboseLevel aVerbose);
+
+	/*
+	 * Enables/disables timestamp from output by string "yes" or "no"
+	 */
+	static void SetTimestamp(const string& aTimestamp);
+
+	/*
+	 * Enables/disables timestamp from output. 0 is disabled.
+	 */
+	static void SetTimestamp(const int aTimestamp);
+
+	/*
+	 * Parses command line parameters to map.
+	 */
+	static void ParseCmdLine(const int aArgc, char **aArgs, map<string, string>& aMap) throw (UtilError);
+
+	/*
+	 * Returns value by key from a map.
+	 */
+	static void GetValue(const string& aKey, const map<string, string>& aMap, string& aValue)  throw (UtilError);
+
+	/*
+	 * Reads properties from a file to a map.
+	 */
+	static void ReadProperties(const string& aFilename, map<string, string>& aMap)  throw (UtilError);
+
+	/*
+	 * Prints message to output in error level.
+	 */
+	static void Error(const string& aMsg);
+
+	/*
+	 * Prints message to output in error level with error code number.
+	 */
+	static void Error(const string& aMsg, const long aCode);
+
+	/*
+	 * Prints hex dump of data to output.
+	 */
+	static void Hex(void *aData, const int aLength);
+
+	/*
+	 * Prints hex dump of char table to output.
+	 */
+	static void Hex(const char aData[]);
+
+	/*
+	 * Prints hex dump of string to output.
+	 */
+	static void Hex(const string& aMsg);
+
+	/*
+	 * Prints hex dump of data to output.
+	 */
+	static void Hex(const unsigned char* aData, const int aLength);
+
+	/*
+	 * Prints hex dump of data to output.
+	 */
+	static void Hex(void* aData, const int aLength, string* aHexDump);
+
+	/*
+	 * Prints message to output in result level.
+	 */
+	static void Log(const string& aMsg);
+
+	/*
+	 * Prints message to output in info level.
+	 */
+	static void Info(const string& aMsg);
+
+	/*
+	 * Prints message to output in debug level.
+	 */
+	static void Debug(const string& aMsg);
+
+	/*
+	 * Prints output to a stream.
+	 */
+	static void Print(ostream& out,
+		              const string& aMsg,
+					  const VerboseLevel aLevel = none,
+					  const long aCode = 0);
+
+	/*
+	 * Converts string to lower case.
+	 */
+	static string& ToLower(string& aString);
+
+	/*
+	 * Converts string to upper case.
+	 */
+	static string& ToUpper(string& aString);
+	
+	/*
+	 * Sets paramvalue if command line parameter is found
+	 */
+	static void CheckCommandlineParam( const string& paramname, string& paramvalue );
+
+private:
+	static VerboseLevel iVerbose;
+	static int iTimestamp;
+#ifdef ENABLE_LOG_SYNC 
+	static Mutex iCritical;
+#endif
+};
+
+#pragma warning (pop)
+
+#endif
+
+// End of file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INI/datagateway.ini	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,15 @@
+### DataGateway parameters
+# TCP/IP port number
+TCPIP_PORT = 2000
+
+# TCP/IP receive buffer size in bytes (dec)
+TCPIP_RECV_BUFFER_SIZE = 8192
+
+# Default communication channel plugin
+DEFAULT_COMM_CHANNEL_PLUGIN = SERIAL
+#DEFAULT_COMM_CHANNEL_PLUGIN = IPCOMM
+
+# Maximum time in milliseconds to wait shutdown
+# NOTE: 0 means no waiting. This may cause
+#       undefined behaviour.
+MAXIMUM_SHUTDOWN_WAITTIME = 3000
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INI/ipcommplugin.ini	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,17 @@
+### IPCOMM plugin parameters
+
+
+# Local TCP/IP port where to listen for incoming HTI connection.
+# If defined remote host & port parameters will be ignored.
+#
+# NOTE: Do not use the same port as HtiGateway!
+#
+#LOCAL_PORT=3000
+
+
+# Remote TCP/IP host & port where HTI is listening.
+#
+REMOTE_HOST=localhost
+REMOTE_PORT=3000
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/INI/serialplugin.ini	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,25 @@
+### Parameters for serial connection
+#init string
+#INIT_STRING = 115200,n,8,1
+#INIT_STRING = 9600,n,8,1
+
+#comm port
+COMPORT = COM1
+
+#timeout for communication operations, in ms
+#default value is 40000
+#TIMEOUT=60000
+
+#enable hw flow control
+#should be "1" to enable
+#disabled by default
+#HW_FLOWCONTROL=1
+
+#make pause after sending over serial, in ms
+#can be used to avoid overflow problem
+# default value is 0
+#SEND_PAUSE=1000
+
+#set the size for output buffer
+# can be set smaller to avoid overrun
+#SEND_SIZE=1000
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/IPComm.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,503 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of the IPCommPlugin,
+*	IPCommReaderThread, IPCommWriterThread and IPCommMonitorThread classes.
+*/
+
+// INCLUDES
+#include "socket.h"
+#include "IPCommPlugin.h"
+
+const static int g_IPMaxResendNumber = 2;
+
+//**********************************************************************************
+// Class IPCommPlugin
+//
+// This class implements a CommChannelPlugin which is used to communicate with device using TCP/IP
+//**********************************************************************************
+
+IPCommPlugin::IPCommPlugin(const CommChannelPluginObserver* observer)
+    : CommChannelPlugin(observer),
+      m_TxQueue(),
+      m_RxQueue(),
+	  m_PropertyLocalPort(0),
+	  m_PropertyRemotePort(0)
+{
+    m_MonitorThread = NULL;
+}
+
+IPCommPlugin::~IPCommPlugin()
+{
+    Util::Debug("IPCommPlugin::~IPCommPlugin()");
+    if (m_Open)
+    {
+        Close();
+    }
+    if (m_MonitorThread != NULL)
+    {
+        delete m_MonitorThread;
+        m_MonitorThread = NULL;
+    }
+}
+
+/*
+ * This method initializes IPCommPlugin and Starts IPCommMonitorThread
+ */
+DWORD IPCommPlugin::Init()
+{
+    Util::Debug("IPCommPlugin::Init()");
+	
+    std::string filename = IP_INI_FILE_NAME;
+	map<string, string> IPCommPluginProperties;
+	Util::ReadProperties(filename.c_str(), IPCommPluginProperties);
+
+	CheckProperties(IPCommPluginProperties);
+
+    CommChannelPlugin::Init();
+
+	m_MonitorThread = new IPCommMonitorThread(
+		&m_TxQueue, &m_RxQueue, m_PropertyLocalPort, m_PropertyRemoteHost, m_PropertyRemotePort);
+
+	m_MonitorThread->Start();
+
+    Util::Debug("IPCommPlugin::Init() IPComm opened");
+    m_Open = true;
+    Util::Debug("IPCommPlugin::Init() OK");
+    return NO_ERRORS;
+}
+
+/*
+ * This method initializes class member variables from values in map
+ */
+void IPCommPlugin::CheckProperties(map<string, string>& props)
+{
+    char tmp[256];
+
+    //Local port
+    string val = props[IP_INI_LOCAL_PORT_PARAM];
+	Util::CheckCommandlineParam( PARAM_SWITCH_LOCAL_PORT_PARAM, val );
+    if (!val.empty())
+    {
+        m_PropertyLocalPort = atol(val.c_str());
+    }
+
+	if( m_PropertyLocalPort )
+	{
+		sprintf(tmp, "[IPComm] Local port : %d", m_PropertyLocalPort );
+		string s(tmp);
+		Util::Info(s);
+	}
+	else
+	{
+		//Remote host
+		m_PropertyRemoteHost = props[IP_INI_REMOTE_HOST_PARAM];
+		//Check and replace if -REMOTE_HOST was given as command line parameter
+		Util::CheckCommandlineParam( PARAM_SWITCH_REMOTE_HOST_PARAM, m_PropertyRemoteHost );
+		if(m_PropertyRemoteHost.empty())
+		{
+			throw "No remote host specified!";
+		}
+		sprintf(tmp, "[IPComm] Remote host : '%s'", m_PropertyRemoteHost.c_str());
+		string s = tmp;
+		Util::Info(s);
+
+		//Remote port
+		val = props[IP_INI_REMOTE_PORT_PARAM];
+		//Check and replace if -REMOTE_POST was given as command line parameter
+		Util::CheckCommandlineParam( PARAM_SWITCH_REMOTE_PORT_PARAM, val );
+		if (!val.empty())
+		{
+			m_PropertyRemotePort = atol(val.c_str());
+		}
+		if( m_PropertyRemotePort == 0)
+			throw "Invalid remote port specified!";
+
+		sprintf(tmp, "[IPComm] Remote port : %d", m_PropertyRemotePort );
+		s = tmp;
+		Util::Info(s);
+	}
+}
+
+/*
+ * This method checks if data is available on incoming queue
+ */
+bool IPCommPlugin::IsDataAvailable()
+{
+    return (!m_RxQueue.empty());
+}
+
+/*
+ * This method is used to push given data to outgoing queue and then 
+ * wait for data to become available and read all data into single Data object 
+ */
+DWORD IPCommPlugin::SendReceive(Data* data_in, Data** data_out, long timeout)
+{
+    DWORD res;
+    if ((res = Send(data_in, timeout)) == NO_ERRORS &&
+        (res = ReceiveWait(data_out, timeout)) == NO_ERRORS)
+    {
+        return NO_ERRORS;
+    }
+    cout << "IPCommPlugin::SendReceive: error" << endl;
+    return res;
+}
+
+/*
+ * This method pushes the given Data object(of type Data::EData) to outgoing queue
+ */
+DWORD IPCommPlugin::Send(Data* data_in, long timeout)
+{
+    Data::DataType type = data_in->GetType();
+    if (type == Data::EData)
+    {
+        DWORD length = data_in->GetLength();
+        m_TxQueue.push(data_in);
+        return NO_ERRORS;
+    }
+    else if (type == Data::EControl)
+    {
+        Util::Debug("IPCommPlugin::Send: Control Message");
+        return NO_ERRORS;
+    }
+    return ERR_DG_COMM_DATA_SEND;
+}
+
+
+/*
+ * This method is used to wait for data to become available in incoming queue 
+ * and then read all data into single Data object which is given as parameter
+ */
+DWORD IPCommPlugin::ReceiveWait(Data** data_out, long timeout)
+{
+    long elapsed = 0;
+    while (elapsed < timeout && !IsDataAvailable())
+    {
+        elapsed += 25;
+        Sleep(25);
+    }
+    if (elapsed >= timeout)
+    {
+        return ERR_DG_COMM_DATA_RECV_TIMEOUT;
+    }
+    return Receive(data_out, timeout);
+}
+
+/*
+ * This method is used to read all data in incoming queue to single Data object and store the result
+ * to the data object given parameter
+ */
+DWORD IPCommPlugin::Receive(Data** data_out, long timeout)
+{
+    if (!m_RxQueue.empty())
+    {
+        *data_out = m_RxQueue.front();
+        m_RxQueue.pop();
+	return NO_ERRORS;
+    }
+    return ERR_DG_COMM_DATA_RECV;
+}
+
+
+DWORD IPCommPlugin::Open()
+{
+    return (m_Open ? NO_ERRORS : ERR_DG_COMM_OPEN);
+}
+
+DWORD IPCommPlugin::Close()
+{
+    m_MonitorThread->Stop();
+    WaitForSingleObject(m_MonitorThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+    return NO_ERRORS;
+}
+
+
+//**********************************************************************************
+// Class IPCommReaderThread
+//
+// This thread is used to read bytes from TCP/IP socket, encapsulate the bytes to Data objects 
+// and push them to incoming queue 
+//**********************************************************************************
+
+IPCommReaderThread::IPCommReaderThread(SafeQueue<Data*>* q,
+                                       long bufsize)
+	:m_Running(false),
+    m_Socket(NULL)
+{
+	m_Queue = q;
+	if (bufsize > 0)
+	{
+		m_TcpIpBufferSize = bufsize;
+	}
+	else
+	{
+		m_TcpIpBufferSize = g_DataGatewayDefaultTcpIpBufferSize;
+	}
+}
+
+/*
+ * Main execution loop which reads bytes from socket, encapsulates the bytes to Data object and pushes them to incoming queue
+ */	
+void IPCommReaderThread::Run()
+{
+	if( m_Socket )
+		m_Running = true;
+
+	BYTE* buffer = new BYTE[m_TcpIpBufferSize];
+	while (m_Running)
+	{
+		//Reading from TCP/IP port
+		//Util::Debug("[IPCommReaderThread] try to read");
+		int bytes_read = -1;
+		bytes_read = m_Socket->ReceiveBytes(buffer, m_TcpIpBufferSize);
+		if (bytes_read < 0)
+		{
+			Stop();
+			break;
+		}
+		if (bytes_read > 0) 
+		{
+			Data* d = new Data((void *)buffer, bytes_read, Data::EData);
+			if (Util::GetVerboseLevel() == Util::debug)
+			{
+				char tmp[64];
+				sprintf(tmp, "m_Socket->ReceiveBytes (%d (dec) bytes):", d->GetLength());
+				string s(tmp);
+				Util::Debug(s);
+			}
+			m_Queue->push(d);
+			d = NULL;
+		}
+		Sleep(50);
+	}
+	delete[] buffer;
+	buffer = NULL;
+}
+
+void IPCommReaderThread::Stop()
+{
+	m_Running = false;
+}
+
+bool IPCommReaderThread::IsRunning()
+{
+	return m_Running;
+}
+
+
+
+//**********************************************************************************
+// Class IPCommWriterThread
+//
+// This thread is used to write data from outgoing queue to TCP/IP socket
+//**********************************************************************************
+
+IPCommWriterThread::IPCommWriterThread(SafeQueue<Data*>* q)
+	:m_Running(false),
+	m_Socket(NULL)
+{
+	m_Queue = q;
+}
+
+/*
+ * This method contains the main execution loop which gets Data from outgoing queue and sends it to socket
+ */
+void IPCommWriterThread::Run()
+{
+	if( m_Socket )
+		m_Running = true;
+
+	while (m_Running)
+	{
+		// Sending to TCP/IP port
+		//Util::Debug("[IPCommWriterThread] try to send");
+		try
+		{
+			Data* d = m_Queue->front(50);
+			char* p = (char *)d->GetData();
+			DWORD l = d->GetLength();
+
+            if (Util::GetVerboseLevel() == Util::debug)
+			{
+				char tmp[64];
+				sprintf(tmp, "[IPCommWriterThread] HTI MsgSize = %d", l);
+				string s(tmp);
+				Util::Debug(s);
+			}
+
+			m_Socket->SendBytes((const unsigned char *)p, l);
+			m_Queue->pop();
+			delete d;
+			d = NULL;
+
+		} catch (TimeoutException te)
+		{
+		//Util::Debug("[IPCommWriterThread]timeout exception");
+		}
+	}
+}
+
+void IPCommWriterThread::Stop()
+{
+	m_Running = false;
+}
+
+bool IPCommWriterThread::IsRunning()
+{
+	return m_Running;
+}
+
+
+//**********************************************************************************
+// Class IPCommMonitorThread
+//
+// This thread creates and starts reader and writer threads
+// The thread also monitors if reader and writer threads are running and restarts them in case either isn't running
+//**********************************************************************************
+
+IPCommMonitorThread::IPCommMonitorThread(SafeQueue<Data*>* TxQueue,
+										 SafeQueue<Data*>* RxQueue,
+										 int localPort,
+                                         string& remoteHost,
+                                         int remotePort)
+	: m_Running(false),
+	m_TxQueue(TxQueue),
+	m_RxQueue(RxQueue),
+	m_ReaderThread(NULL),
+	m_WriterThread(NULL),
+	m_LocalPort(localPort),
+    m_RemoteHost(remoteHost),
+	m_RemotePort(remotePort)
+{
+}
+
+IPCommMonitorThread::~IPCommMonitorThread()
+{
+	if(m_ReaderThread)
+	{
+		delete m_ReaderThread;
+		m_ReaderThread = NULL;
+	}
+	if(m_WriterThread)
+	{
+		delete m_WriterThread;
+		m_WriterThread = NULL;
+	}
+}
+
+
+/*
+ * This method has two functionalities
+ * -It waits for incoming connections if local port is defined
+ * -It tries to connect to remote host if local host is not defined
+ */
+void IPCommMonitorThread::Connect(Socket*& s)
+{
+	// This trickery here is because if there are no sockets (Socket::nofSockets_)
+	// WSACleanup gets called and then SOAP gets messed up.
+	// And creating a new socket for a new connection seems to work better
+	// than using the old when re-connecting / re-listening.
+	Socket* new_s = new Socket();
+	delete s;
+	s = new_s;
+
+	// If local port is defined start open listening socket
+	SocketServer ss;
+	if( m_LocalPort )
+	{
+		Util::Info("[IPComm] Listen for incoming connection...");
+		String remoteHost( "[IPComm] Connected! Remote host : " );
+		ss.Accept( s, m_LocalPort, 1, remoteHost );
+		Util::Info(remoteHost);
+	}
+	// If not start connecting
+	else
+	{
+		Util::Info("[IPComm] Connecting...");
+		ss.Connect( s, m_RemoteHost.c_str(), m_RemotePort );
+		Util::Info("[IPComm] Connected!");
+	}
+}
+
+/*
+ * Main execution loop of thread
+ * -Creates reader and writer threads and starts them
+ * -Monitors if either reader or writer thread aren't running and restarts them if not
+ */
+void IPCommMonitorThread::Run()
+{
+	Socket* s = NULL;
+
+	m_ReaderThread = new IPCommReaderThread( m_RxQueue, g_DataGatewayDefaultTcpIpBufferSize );
+	m_WriterThread = new IPCommWriterThread( m_TxQueue ) ;
+
+	m_Running = true;
+	while (m_Running)
+	{
+		// Reader thread should stop running when connection is lost
+		if( !m_ReaderThread->IsRunning() || !m_WriterThread->IsRunning() )
+		{
+			Util::Info( "[IPComm] Disconnected!" );
+			
+			// Stop the treads
+			m_ReaderThread->Stop();
+		    WaitForSingleObject(m_ReaderThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+			m_WriterThread->Stop();
+			WaitForSingleObject(m_WriterThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+			
+			// Try to connect again. 
+			BOOL connected = false;
+			while( m_Running && connected == false)
+			{
+				try{
+					Connect(s);
+					connected = true;
+					m_ReaderThread->m_Socket = s;
+					m_WriterThread->m_Socket = s;
+
+					// Start threads
+					m_ReaderThread->Start();
+					m_WriterThread->Start();
+				}
+				catch( char* ){
+					Sleep(1000);
+				}
+			}
+		}
+		Sleep(1000);
+	}
+
+	// Stop the treads
+	m_ReaderThread->Stop();
+	WaitForSingleObject(m_ReaderThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+	m_WriterThread->Stop();
+	WaitForSingleObject(m_WriterThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+	// and close the current socket
+	if( s )
+		delete s;
+}
+
+void IPCommMonitorThread::Stop()
+{
+	m_Running = false;
+	m_ReaderThread->Stop();
+	m_WriterThread->Stop();
+}
+
+bool IPCommMonitorThread::IsRunning()
+{
+	return m_Running;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/SerialComm.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,714 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implementation of SerialComm communication channel plugin objects. These classes are SerialComm, SerialCommPlugin and
+*	SerialCommIoThread classes.
+*/
+
+// INCLUDES
+#include "SerialCommPlugin.h"
+#include "util.h"
+
+#define HIGH_COM_PORT "\\\\.\\"
+const static int g_SerialMaxResendNumber = 2;
+
+//**********************************************************************************
+// Class SerialCommPlugin
+//
+// This class implements a CommChannelPlugin used in serial communication with device
+//**********************************************************************************
+
+SerialCommPlugin::SerialCommPlugin(const CommChannelPluginObserver* observer)
+    : CommChannelPlugin(observer),
+      m_TxQueue(),
+      m_RxQueue(),
+      m_PropertySerialCommTimeout(g_SerialCommDefaultTimeout),
+	  m_PropertySerialMaxSendSize(0),
+	  m_ProperySerialSendPause(0),
+	  m_PropertySerialHwFlowControl(false)
+{
+    m_IoThread = NULL;
+}
+
+SerialCommPlugin::~SerialCommPlugin()
+{
+    Util::Debug("SerialCommPlugin::~SerialCommPlugin()");
+    if ( m_Open )
+    {
+        Close();
+    }
+    if ( m_IoThread != NULL )
+    {
+        delete m_IoThread;
+        m_IoThread = NULL;
+    }
+}
+
+/*
+ * This method initializes SerialCommPlugin and starts SerialCommPluginIoThread
+ */
+DWORD SerialCommPlugin::Init()
+{
+    Util::Debug("SerialCommPlugin::Init()");
+
+    std::string filename = SERIAL_INI_FILE_NAME;
+	//read properties from serialplugin.ini file
+	Util::ReadProperties(filename.c_str(), m_SerialCommPluginProperties);
+    
+	CheckProperties(m_SerialCommPluginProperties);
+
+    CommChannelPlugin::Init();
+
+    m_IoThread = new SerialCommIoThread(
+						&m_RxQueue,
+						&m_TxQueue,
+                        m_PropertySerialCommInitString,
+						m_PropertySerialCommPort,
+						m_PropertySerialCommTimeout,
+						m_PropertySerialHwFlowControl,
+						m_ProperySerialSendPause,
+						m_PropertySerialMaxSendSize);
+
+    m_IoThread->SetTimeout(m_PropertySerialCommTimeout);
+
+	m_IoThread->Start();
+
+	Event e = m_IoThread->GetOpenedEvent();
+    if ( e.Wait(m_PropertySerialCommTimeout) == WAIT_TIMEOUT )
+    {
+        Util::Debug("SerialCommPlugin::Init()   SerialComm opening timed out");
+        m_Open = false;
+        return ERR_DG_COMM_OPEN_TIMEOUT;
+    }
+    Util::Debug("SerialCommPlugin::Init() SerialComm opened");
+    m_Open = true;
+    Util::Debug("SerialCommPlugin::Init() OK");
+    return NO_ERRORS;
+}
+
+/*
+ * This method initializes class member variables from values in map
+ */
+void SerialCommPlugin::CheckProperties(map<string, string>& props)
+{
+    char tmp[256];
+
+    // Init values for connection
+    m_PropertySerialCommInitString = props[SERIAL_INI_INIT_PARAM];
+	Util::CheckCommandlineParam( PARAM_SWITCH_INIT_PARAM, m_PropertySerialCommInitString );
+    if ( m_PropertySerialCommInitString.empty() )
+    {
+        m_PropertySerialCommInitString = SERIAL_DEFAULT_INIT_STRING;
+    }
+    sprintf(tmp, "Connection Init : '%s'", m_PropertySerialCommInitString.c_str());
+    string s(tmp);
+    Util::Debug(s);
+
+    // comm port
+    m_PropertySerialCommPort = props[SERIAL_INI_COMPORT_PARAM];
+	Util::CheckCommandlineParam( PARAM_SWITCH_COMPORT_PARAM, m_PropertySerialCommPort );
+    if ( m_PropertySerialCommPort.empty() )
+    {
+        m_PropertySerialCommPort = SERIAL_DEFAULT_COMPORT;
+    }
+    sprintf(tmp, "Connection port : '%s'", m_PropertySerialCommPort.c_str());
+    s = tmp;
+    Util::Debug(s);
+
+    // Serial operations timeout
+    string val = props[SERIAL_INI_COMPORT_TIMEOUT];
+	Util::CheckCommandlineParam( PARAM_SWITCH_COMPORT_TIMEOUT, val );
+	m_PropertySerialCommTimeout = 0;
+    if ( !val.empty() )
+    {
+        m_PropertySerialCommTimeout = atol(val.c_str());
+    }
+
+    if ( m_PropertySerialCommTimeout <= 0 )
+    {
+        m_PropertySerialCommTimeout = g_SerialCommDefaultTimeout;
+    }
+	sprintf(tmp, "Timeout: '%d'", m_PropertySerialCommTimeout);
+    s = tmp;
+    Util::Debug(s);
+
+	// flow control
+	m_PropertySerialHwFlowControl = false;
+	val = props[SERIAL_INI_USE_HW_FLOW_CONTROL];
+	Util::CheckCommandlineParam( PARAM_SWITCH_USE_HW_FLOW_CONTROL, val );
+	if ( !val.empty() && val == "1" )
+	{
+		m_PropertySerialHwFlowControl = true;
+		Util::Debug("Use serial HW flow control");
+	}
+	else
+	{
+		Util::Debug("Do not use serial HW flow control");
+	}
+
+	// send pause
+	val = props[SERIAL_INI_SEND_SLEEP_PAUSE];
+	Util::CheckCommandlineParam( PARAM_SWITCH_SEND_SLEEP_PAUSE, val );
+    if ( !val.empty() )
+    {
+        m_ProperySerialSendPause = atol(val.c_str());
+    }
+    if ( m_ProperySerialSendPause <= 0 )
+    {
+        m_ProperySerialSendPause = g_SerialCommDefaultSendPause;
+    }
+	sprintf(tmp, "Send pause: '%d'", m_ProperySerialSendPause);
+    s = tmp;
+    Util::Debug(s);
+
+	// send size
+	val = props[SERIAL_INI_SEND_SIZE];
+	Util::CheckCommandlineParam( PARAM_SWITCH_SEND_SIZE, val );
+    if ( !val.empty() )
+    {
+        m_PropertySerialMaxSendSize = atol(val.c_str());
+    }
+    if ( m_PropertySerialMaxSendSize <= 0 )
+    {
+        m_PropertySerialMaxSendSize = 0;
+    }
+	sprintf(tmp, "Send max size: '%d'", m_PropertySerialMaxSendSize);
+    s = tmp;
+    Util::Debug(s);
+}
+
+/*
+ * This method checks if data is available on incoming queue
+ */
+bool SerialCommPlugin::IsDataAvailable()
+{
+    return ( !m_RxQueue.empty() );
+}
+
+/*
+ * This method is used to:
+ * -push given data to outgoing queue
+ * -wait for data to become available in incoming queue
+ * -pop the first Data object from queue and store it to the Data object given as parameter
+ */
+DWORD SerialCommPlugin::SendReceive(Data* data_in, Data** data_out, long timeout)
+{
+    DWORD res;
+    if ( ( res = Send(data_in, timeout)) == NO_ERRORS &&
+         ( res = ReceiveWait(data_out, timeout)) == NO_ERRORS )
+    {
+        return NO_ERRORS;
+    }
+    cout << "SerialCommPlugin::SendReceive: error" << endl;
+    return res;
+}
+
+/*
+ * This method pushes the given Data object(of type Data::EData) to outgoing queue
+ */
+DWORD SerialCommPlugin::Send(Data* data_in, long timeout)
+{
+    Data::DataType type = data_in->GetType();
+    if ( type == Data::EData )
+    {
+        DWORD length = data_in->GetLength();
+        m_TxQueue.push(data_in);
+        return NO_ERRORS;
+    }
+    else if ( type == Data::EControl )
+    {
+		Util::Debug("SerialCommPlugin::Send: Control Message Received");
+        return NO_ERRORS;
+    }
+    return ERR_DG_COMM_DATA_SEND;
+}
+
+/*
+ * This method is used to wait for data to become available in incoming queue 
+ * and then pop the first Data object from the queue and and store it to Data object given as parameter.
+ */
+DWORD SerialCommPlugin::ReceiveWait(Data** data_out, long timeout)
+{
+    long elapsed = 0;
+    while (elapsed < timeout && !IsDataAvailable())
+    {
+        elapsed += 25;
+        Sleep(25);
+    }
+    if ( elapsed >= timeout )
+    {
+        return ERR_DG_COMM_DATA_RECV_TIMEOUT;
+    }
+    return Receive(data_out, timeout);
+}
+
+/*
+ * This method is used to pop the first data object from incoming queue and store it to data object given as parameter
+ */
+DWORD SerialCommPlugin::Receive(Data** data_out, long timeout)
+{
+    if ( !m_RxQueue.empty() )
+    {
+        *data_out = m_RxQueue.front();
+        m_RxQueue.pop();
+        return NO_ERRORS;
+    }
+    return ERR_DG_COMM_DATA_RECV;
+}
+
+
+DWORD SerialCommPlugin::Open()
+{
+    return ( m_Open ? NO_ERRORS : ERR_DG_COMM_OPEN );
+}
+
+/*
+ * This method stops SerialCommIoThread and waits for it to be in signaled state
+ */
+DWORD SerialCommPlugin::Close()
+{
+    m_IoThread->Stop();
+    WaitForSingleObject( m_IoThread->ThreadHandle(), g_MaximumShutdownWaitTime );
+    return NO_ERRORS;
+}
+
+//**********************************************************************************
+// Class SerialComm
+//
+// This class implements the actual serial communication using Windows API
+//**********************************************************************************
+
+SerialComm::SerialComm()
+    : m_Open(false),
+	m_SendPause(0),
+	m_SendMaxSize(0)
+{
+
+}
+
+SerialComm::~SerialComm()
+{
+    Util::Debug("SerialComm::~SerialComm()");
+    if ( m_Open )
+    {
+        Close();
+    }
+}
+/*
+ * This method opens a communication device that uses serial communication and
+ * configures it according initialization parameters
+ */
+WORD SerialComm::Open( const string& commPort, const string& initParameters,
+					   long timeout,
+					   bool hwFlowControl, long sendPause, long sendMaxSize)
+{
+    Util::Debug("SerialComm::Open()");
+
+	m_SendPause = sendPause;
+
+	if ( sendMaxSize>0 )
+	{
+		m_SendMaxSize = sendMaxSize;
+	}
+
+	DWORD err;
+	//check commPort and add "\\.\" prefix if port is larger than 9
+	string localCommPort(commPort);
+	static const basic_string <char>::size_type npos = -1;
+	if ( localCommPort.find(HIGH_COM_PORT) == npos &&
+		 localCommPort.find("COM") == 0 &&
+		 localCommPort.length() > 4 //two digit port number
+	   )
+	{
+		localCommPort.insert(0, HIGH_COM_PORT);
+	}
+	Util::Debug(localCommPort.c_str());
+
+    // If COM-port opening fails, it's retried until DataGateway is killed.
+    m_Com = INVALID_HANDLE_VALUE;
+    while ( m_Com == INVALID_HANDLE_VALUE )
+    {
+	    // Open file (COM port)
+	    m_Com = CreateFile( localCommPort.c_str(),
+					    GENERIC_READ | GENERIC_WRITE,
+					    0, //excusive access
+					    NULL, //no security
+					    OPEN_EXISTING, //must use
+					    0, //not overlapped i/o
+					    NULL // must be NULL for comm
+					    );
+	    if ( m_Com == INVALID_HANDLE_VALUE )
+	    {
+		    err = GetLastError();
+            Util::Error("[SerialComm] Failed to open COM port", err);
+            Util::Info("[SerialComm] Retrying...");
+            Sleep(5000);
+        }
+    }
+
+    // Serial port cfg
+	Util::Debug(initParameters.c_str());
+	DCB dcb;
+
+	FillMemory(&dcb, sizeof(dcb), 0);
+	dcb.DCBlength = sizeof(dcb);
+	if ( !BuildCommDCB(initParameters.c_str(), &dcb) )
+	{
+		err = GetLastError();
+		Util::Error("[SerialComm] Failed to build port settings ", err);
+		return ERR_DG_COM_INIT;
+	}
+
+	dcb.fBinary = TRUE ; 
+
+	//set hw handshaking
+	dcb.fOutX  = FALSE;
+    dcb.fInX   = FALSE;
+    dcb.fNull   = FALSE;
+    dcb.fAbortOnError = TRUE;
+	
+	dcb.fOutxDsrFlow = FALSE;
+	dcb.fDtrControl = DTR_CONTROL_DISABLE;
+	dcb.fDsrSensitivity= FALSE;
+
+	if ( hwFlowControl )
+	{
+		dcb.fOutxCtsFlow = TRUE;
+		dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
+	}
+	else
+	{
+		dcb.fOutxCtsFlow = FALSE;
+		dcb.fRtsControl = RTS_CONTROL_ENABLE;
+	}
+    //Configure communication device according to the specifications in a device-control block (a DCB structure)
+	if ( !SetCommState(m_Com, &dcb) )
+	{
+		err = GetLastError();
+		Util::Error("[SerialComm] Failed to set port settings ", err);
+		return ERR_DG_COM_INIT;
+	}
+
+	COMMTIMEOUTS timeouts;
+
+	timeouts.ReadIntervalTimeout = MAXDWORD; 
+
+	timeouts.ReadTotalTimeoutMultiplier = timeout;
+	timeouts.ReadTotalTimeoutConstant = 1;
+	timeouts.WriteTotalTimeoutMultiplier = 1;
+	timeouts.WriteTotalTimeoutConstant = timeout;
+
+	//Set the time-out parameters for all read and write operations on communications device
+	if ( !SetCommTimeouts(m_Com, &timeouts) )
+	{
+		// Error setting time-outs.
+		err = GetLastError();
+		Util::Error("[SerialComm] Failed to set port timeouts ", err);
+		return ERR_DG_COM_INIT;
+	}
+
+	m_Open = true;
+    Util::Debug("SerialComm::Open() OK");
+    Util::Info("[SerialComm] COM port open");
+    return NO_ERRORS;
+}
+
+/*
+ * This method is used to send Data object using serial communication
+ */
+DWORD SerialComm::Send(const Data& data_in)
+{
+    Util::Debug("SerialComm::Send()");
+
+	if ( data_in.GetLength() > 0 )
+	{
+		DWORD sentBytes = 0;
+		void* data = data_in.GetData();
+		int numOfTries = 0;
+		//loop until whole Data object is sent
+		while ( sentBytes < data_in.GetLength() )
+		{
+			//Util::Debug("while");
+			DWORD sent;
+			BOOL r;
+			if ( m_SendMaxSize>0 )
+			{
+				//Write data to the communication device
+				r = WriteFile(m_Com,
+						((char*)data) + sentBytes,
+						//data_in.GetLength() - sentBytes,
+						min(data_in.GetLength() - sentBytes, m_SendMaxSize),
+						&sent,
+						NULL);
+			}
+			else
+			{
+				r = WriteFile(m_Com,
+						((char*)data) + sentBytes,
+						data_in.GetLength() - sentBytes,
+						&sent,
+						NULL);
+			}
+
+			if ( r && sent > 0 )
+			{
+				if (Util::GetVerboseLevel() == Util::debug)
+				{
+					printf("Send %d bytes\r\n", sent);
+					Util::Hex(((char*)data) + sentBytes, min(sent,16));
+				}
+				sentBytes+=sent;
+			}
+			else
+			{
+				if ( !r )
+				{
+					DWORD err = GetLastError();
+					Util::Error("[SerialComm] Send error", err);
+				}
+				else
+				{
+					Util::Error("[SerialComm] Send failed");
+				}
+				if ( numOfTries++==g_SerialMaxResendNumber )
+				{
+					return ERR_DG_COMM_DATA_RECV;
+				}
+			}
+			//used to "solve" overflow problem
+			if ( m_SendPause > 0 )
+			{
+				Sleep(m_SendPause);
+			}
+		}
+	}
+
+    Util::Debug("SerialComm::Send() OK");
+    return NO_ERRORS;
+}
+
+/*
+ * This method reads all available data from communication media 
+ * and returns it in the Data object given as parameter
+ */
+DWORD SerialComm::Receive(Data* data_out)
+{
+    Util::Debug("SerialComm::Receive()");
+
+	//get available bytes in incoming communication channel
+	DWORD rxBytes = GetRxBytesAvailable();
+	//printf("Rx bytes: %d \r\n", rxBytes);
+
+	if ( rxBytes > 0 )
+	{
+		char* data = new char[rxBytes];
+		DWORD readBytes = 0;
+		//read data until all available bytes have been red
+		do
+		{
+			DWORD reallyRead;
+			if ( ReadFile(m_Com,
+					 data + readBytes,
+					 rxBytes - readBytes,
+					 &reallyRead,
+					 NULL) )
+			{
+				if (Util::GetVerboseLevel() == Util::debug)
+				{
+					printf("Received %d bytes\r\n", reallyRead);
+					Util::Hex(data + readBytes, min(16,reallyRead));
+				}
+				readBytes += reallyRead;
+			}
+			else
+			{
+				delete[] data;
+				DWORD err = GetLastError();
+				Util::Error("[SerialComm] Error %d", err);
+				return ERR_DG_COMM_DATA_RECV;
+			}
+			if ( readBytes > rxBytes )
+			{
+				Util::Error("[SerialComm] !!! readBytes > rxBytes !!!");
+			}
+		}
+		while( readBytes < rxBytes );
+
+		data_out->SetData( data, rxBytes, Data::EData);
+		delete[] data;
+	}
+	else if ( rxBytes<0 ) //err
+	{
+        return ERR_DG_COMM_DATA_RECV;
+	}
+	return NO_ERRORS;
+}
+
+/*
+ * This method returns number of bytes available in incoming queue or
+ * -1 if communication error has occurred
+ */
+LONG SerialComm::GetRxBytesAvailable()
+{
+    COMSTAT res;
+	DWORD err;
+
+	if ( ClearCommError(m_Com, &err, &res ) )
+	{
+		return res.cbInQue;
+	}
+	else
+    {
+		DWORD err = GetLastError();
+        Util::Error("[SerialComm] Error getting Rx bytes %d", err);
+        return -1;
+    }
+}
+
+DWORD SerialComm::Close()
+{
+    Util::Debug("SerialComm::Close()");
+    m_Open = false;
+
+	if ( m_Com != INVALID_HANDLE_VALUE )
+	{
+		CloseHandle(m_Com);
+		m_Com = INVALID_HANDLE_VALUE;
+	}
+
+    Util::Debug("SerialComm::Close() OK");
+    return NO_ERRORS;
+}
+
+//**********************************************************************************
+// Class SerialCommIoThread
+//
+// This thread is used to send data from outgoing queue to serial port
+// and read bytes from serial port and push it to incoming queue 
+//**********************************************************************************
+
+SerialCommIoThread::SerialCommIoThread(SafeQueue<Data*>* in,
+                           SafeQueue<Data*>* out,
+                           const string& init,  const string& commPort, long timeout,
+						   bool hwFlowControl, long sendPause, long sendMaxSize)
+    : m_InitString(init),
+	  m_CommPort( commPort ),
+	  m_PropertySerialCommTimeout( timeout ),
+	  m_PropertySerialHwFlowControl( hwFlowControl ),
+	  m_ProperySerialSendPause(sendPause),
+	  m_PropertySerialMaxSendSize(sendMaxSize)
+{
+    m_InQueue = in;
+    m_OutQueue = out;
+    m_Running = true;
+    m_PropertySerialCommTimeout = g_SerialCommDefaultTimeout;
+    m_OpenedEvent.Reset();
+}
+
+/*
+ * Main execution loop which is used to send Data from outgoing queue to serial port
+ * and read bytes from serial port, encapsulate it to Data objects and push them to incoming queue 
+ */
+void SerialCommIoThread::Run()
+{
+    while ( m_Running )
+    {
+	    Util::Debug("SerialCommIoThread::Run()");
+        SerialComm m_SerialComm;
+
+        if ( m_SerialComm.Open(m_CommPort, m_InitString, m_PropertySerialCommTimeout,
+							    m_PropertySerialHwFlowControl, m_ProperySerialSendPause,
+							    m_PropertySerialMaxSendSize) != NO_ERRORS )
+        {
+            m_Running = false;
+            return;
+        }
+        m_OpenedEvent.Set();
+
+	    Util::Debug("SerialCommIoThread::Run() start loop");
+        while ( m_Running )
+        {
+            // Sending data
+            try
+            {
+				Data* out = m_OutQueue->front(30);
+                if ( m_SerialComm.Send(*out) != NO_ERRORS )
+                {
+                    Data* d = new Data("Error sending data", 19, Data::EControl);
+                    m_InQueue->push(d);
+                    d = NULL;
+                }
+                m_OutQueue->pop();
+                delete out;
+                out = NULL;
+            } catch (TimeoutException te) {}
+
+		    // Receiving data
+		    LONG rxBytes = 0;
+            while ( ( rxBytes = m_SerialComm.GetRxBytesAvailable() ) > 0 )
+            {
+			    //printf("rx %d\r\n", rxBytes);
+                Data* in = new Data;
+                if ( m_SerialComm.Receive(in) == NO_ERRORS )
+                {
+				    m_InQueue->push(in);
+				    in = NULL;
+                }
+                else
+                {
+                    delete in;
+                    in = NULL;
+                }
+            }
+            if ( rxBytes < 0 )
+            {
+                Util::Info("[SerialCommIoThread] COM-port lost. Trying to close & reopen");
+                break; // break out but keep the outermost while loop running
+            }
+        }
+        m_OpenedEvent.Reset();
+        m_SerialComm.Close();
+    }
+    Util::Debug("SerialCommIoThread::Run() exiting");
+}
+
+void SerialCommIoThread::Stop()
+{
+    Util::Debug("SerialCommIoThread::Stop()");
+    m_Running = false;
+}
+
+Event SerialCommIoThread::GetOpenedEvent()
+{
+    return m_OpenedEvent;
+}
+
+void SerialCommIoThread::SetTimeout(long timeout)
+{
+    if ( timeout > 0 )
+    {
+        m_PropertySerialCommTimeout = timeout;
+    }
+    else
+    {
+        m_PropertySerialCommTimeout = g_SerialCommDefaultTimeout;
+    }
+}
+
+long SerialCommIoThread::GetTimeout() const
+{
+    return m_PropertySerialCommTimeout;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/Socket.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,325 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implemention of Socket, SocketClient, SocketServer and
+*   SocketSelect classes.
+*/
+
+#include <iostream>
+#include <sstream>
+#include <errno.h>
+
+#include "Socket.h"
+#include "Util.h"
+
+using namespace std;
+
+//**********************************************************************************
+// Class Socket
+//
+// This class encapsulates Windows Sockets API Socket functionality
+//**********************************************************************************
+
+int Socket::nofSockets_= 0;
+
+void Socket::Start() {
+  if (!nofSockets_) {
+    WSADATA info;
+    if (WSAStartup(MAKEWORD(2,0), &info)) {
+      throw "Could not start WSA";
+    }
+  }
+   ++nofSockets_;
+}
+
+void Socket::End() {
+  WSACleanup();
+}
+
+
+Socket::Socket() : s_(0) {
+  Start();
+  // UDP: use SOCK_DGRAM instead of SOCK_STREAM
+  s_ = socket(AF_INET,SOCK_STREAM,0);
+
+  refCounter_ = new int(1);
+}
+
+Socket::Socket(SOCKET s) : s_(s) {
+  Start();
+  refCounter_ = new int(1);
+};
+
+
+Socket::~Socket() {
+  if (! --(*refCounter_)) {
+	Close();
+    delete refCounter_;
+  }
+
+  --nofSockets_;
+  if (!nofSockets_) End();
+}
+
+Socket::Socket(const Socket& o) {
+  refCounter_=o.refCounter_;
+  (*refCounter_)++;
+  s_         =o.s_;
+
+  nofSockets_++;
+}
+
+Socket& Socket::operator =(Socket& o) {
+  (*o.refCounter_)++;
+
+  refCounter_=o.refCounter_;
+  s_         =o.s_;
+
+  nofSockets_++;
+
+  return *this;
+}
+
+
+void Socket::Close() {
+  closesocket(s_);
+}
+
+/*
+ * This method is used to receive data bytes socket. The method reads all available and combines them to returned String object
+ */
+String Socket::ReceiveBytes() {
+  String ret;
+  char buf[1024];
+  int rv;
+  while ((rv=recv(s_, buf, 1024,0)) == WSAEMSGSIZE) {
+	String t;
+    t.assign(buf,1024);
+    ret +=t;
+  }
+
+  String t;
+  t.assign(buf, 0, rv);
+  ret += t;
+
+  printf("t = %s, rv = %d", t.c_str(), rv);
+
+  return ret;
+}
+
+/*
+ * This method reads up to maximum amount of bytes from socket to the Data object given as parameter
+ * The maximum amount is given as parameter
+ */
+int Socket::ReceiveBytes(BYTE *data, int bytes) {
+  int rv = SOCKET_ERROR;
+
+  while (rv == SOCKET_ERROR)
+  {
+	rv = recv(s_, (char *)data, bytes, 0);
+    if (rv == 0 || rv == WSAECONNRESET)
+			return -1;
+	else
+		break;
+  }
+  return rv;
+}
+
+
+/*
+ * This method is used to read characters from socket until line separator is encountered
+ * Returns String including line separator
+ */
+String Socket::ReceiveLine() {
+  String ret;
+   while (1) {
+     char r;
+
+     switch(recv(s_, &r, 1, 0)) {
+       case 0: // not connected anymore;
+         return "";
+       //SOCKET_ERROR == -1
+	   case -1:
+          if (errno == EAGAIN) {
+             return ret;
+          } else {
+            // not connected anymore
+           return "";
+         }
+     }
+
+     ret += r;
+     if (r == '\n')  return ret;
+   }
+}
+
+
+/*
+*This method is used to send String as a line
+*The parameter of SendLine is not a const reference
+*because SendLine modifes the String passed.
+*/
+void Socket::SendLine(String s) {
+  s += '\n';
+  send(s_,s.c_str(),s.length(),0);
+}
+
+/*
+ * This method is used to send String as bytes
+ */
+void Socket::SendBytes(const String& s) {
+  send(s_,s.c_str(),s.length(),0);
+}
+
+/*
+ * This method is used to send specific amount of bytes of String
+ * The parameter is a const reference
+ * because the methos does not modify the String passed 
+ * (in contrast to SendLine).
+ */
+int Socket::SendBytes(const BYTE* data, int bytes)
+{
+	if (bytes <= 0) return 0;
+	send(s_,(char *)data, bytes, 0);
+	return 0;
+}
+
+//**********************************************************************************
+// Class SocketServer
+//
+// This class is used to:
+// -listen for incoming connections to a Socket
+// -connect to socket
+//**********************************************************************************
+
+SocketServer::SocketServer() {
+}
+
+/*
+ * This method binds and opens the given socket to listening mode 
+ */
+void SocketServer::Accept( Socket*& s,int port, int connections, String& remoteHost ) {
+
+  sockaddr_in sa;
+  memset(&sa, 0, sizeof(sa)); /* clear our address */
+  sa.sin_family = PF_INET;             
+  sa.sin_port = htons(port); 
+
+  // Use the given socket for listening
+  Socket* listenSocket = s;
+
+  // bind the socket to the internet address
+  if (bind(listenSocket->s_, (sockaddr *)&sa, sizeof(sockaddr_in)) ==
+      SOCKET_ERROR) {
+    throw "INVALID_SOCKET";
+  }
+  //place a socket in a state in which it is listening for an incoming connection
+  listen(listenSocket->s_, connections);  
+
+  sockaddr_in remoteAddr; 
+  int remoteAddrLen = sizeof(sockaddr_in);
+
+  //extract the first connection on the queue of pending connections on socket
+  //accept blocks if socket is marked blocking
+  SOCKET new_sock = accept(listenSocket->s_, (sockaddr*) &remoteAddr, &remoteAddrLen);
+  if (new_sock == INVALID_SOCKET) 
+  {
+	  throw "Invalid Socket";
+  }
+
+  // Return remote host and port to caller
+  stringstream msg;
+  msg<<inet_ntoa(remoteAddr.sin_addr)<<":"<<ntohs(remoteAddr.sin_port);
+  remoteHost.append( msg.str() );
+   
+  s = new Socket(new_sock);
+  delete listenSocket;
+}
+
+/*
+ * This method establishes a connection to the socket
+ */
+void SocketServer::Connect(Socket* s, const char* remoteHost, int remotePort) {
+  
+  Socket* connectSocket = s;
+  sockaddr_in sa;
+  memset(&sa, 0, sizeof(sa)); /* clear our address */
+  sa.sin_family = AF_INET;
+  if( isalpha(remoteHost[0]) )
+  {
+    HOSTENT* Hostent;
+    if( (Hostent = gethostbyname( remoteHost )) != 0 )
+      sa.sin_addr.s_addr = *(long*) Hostent->h_addr;
+	else
+	  throw "Unknown host!";
+  }
+  else
+    sa.sin_addr.s_addr = inet_addr( remoteHost );
+  
+  sa.sin_port = htons( remotePort );
+
+  // Connect to server.
+  if ( connect( connectSocket->s_, (SOCKADDR*) &sa, sizeof(sa) ) == SOCKET_ERROR) {
+    throw "SOCKET_ERROR";
+  }
+}
+
+//**********************************************************************************
+// Class SocketClient
+//
+//**********************************************************************************
+
+SocketClient::SocketClient(const String& host, int port) : Socket() {
+  String error;
+
+  hostent *he;
+  if ((he = gethostbyname(host.c_str())) == NULL) {
+    error = strerror(errno);
+    throw error;
+  }
+
+  sockaddr_in addr;
+  addr.sin_family = AF_INET;
+  addr.sin_port = htons(port);
+  addr.sin_addr = *((in_addr *)he->h_addr);
+  memset(&(addr.sin_zero), 0, 8); 
+
+  if (::connect(s_, (sockaddr *) &addr, sizeof(sockaddr))) {
+    error = strerror(WSAGetLastError());
+    throw error;
+  }
+}
+
+//**********************************************************************************
+// Class SocketSelect
+//
+//**********************************************************************************
+
+SocketSelect::SocketSelect(Socket const * const s1, Socket const * const s2) {
+  FD_ZERO(&fds_);
+  FD_SET(const_cast<Socket*>(s1)->s_,&fds_);
+  FD_SET(const_cast<Socket*>(s2)->s_,&fds_);
+
+  if (select (0, &fds_, (fd_set*) 0, (fd_set*) 0, (timeval*) 0) 
+      == SOCKET_ERROR) throw "Error in select";
+}
+
+
+bool SocketSelect::Readable(Socket const * const s) {
+  if (FD_ISSET(s->s_,&fds_)) return true;
+  return false;
+}
+
+// End of the file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/common.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,185 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*     This file contains implementation file of the Data and ParameterList classes.
+*/
+
+// INCLUDES
+#include "common.h"
+#include "util.h"
+
+// Maximum time to wait
+long g_MaximumShutdownWaitTime;
+
+DWORD g_ErrorCode = NO_ERRORS;
+
+//**********************************************************************************
+// Class Data
+//
+// This class provides data encapsulattion for DataGateway
+//**********************************************************************************
+
+Data::Data(const void* data_in, DWORD length, DataType type)
+{
+	SetData(data_in, length, 0, type);
+}
+
+
+Data::Data(const void* data_in, DWORD length, DWORD offset, DataType type)
+{
+	SetData(data_in, length, offset, type);
+}
+
+Data::Data(const Data& data)
+{
+	SetData(data.GetData(), data.GetLength(), 0, data.GetType());
+}
+
+Data::~Data()
+{
+	if (m_pData != NULL)
+	{
+		delete[] m_pData;
+		m_pData = NULL;
+	}
+}
+
+/*
+ * This method is used to delete data and set data type to EEmpty
+ */
+void Data::FreeData()
+{
+	if (m_pData != NULL)
+	{
+		delete[] m_pData;
+		m_pData = NULL;
+		m_Type = EEmpty;
+	}
+}
+
+/*
+ * returns data in Data object given parameter
+ */
+void* Data::GetData(void *data_out) const
+{
+	if (data_out != NULL)
+	{
+		data_out = m_pData;
+	}
+	return m_pData;
+}
+
+/*
+ * returns length of data 
+ */
+DWORD Data::GetLength() const
+{
+	return m_dwLength;
+}
+
+/*
+ * returns type of data
+ * can be one of the following: EEmpty, EControl, EError, EData
+ */
+Data::DataType Data::GetType() const
+{
+	return m_Type;
+}
+
+/*
+ * This method copies up to length bytes from given data object to class member data object
+ */
+bool Data::SetData(const void* data_in, DWORD length, DataType type)
+{
+	return SetData(data_in, length, 0, type);
+}
+
+/*
+ * This method copies up to length bytes(starting from offset) from given data object to class member data object
+ */
+bool Data::SetData(const void* data_in, DWORD length, DWORD offset, DataType type)
+{
+	m_Type = type;
+	if (length == 0 || data_in == NULL || offset >= length)
+	{
+		m_pData = NULL;
+		return true;
+	}
+	m_dwLength = (length - offset);
+	m_pData = new BYTE[m_dwLength];
+	if (m_pData == NULL)
+	{
+		Util::Error("Error allocating memory to data object");
+		m_Type = EEmpty;
+		return false;
+	}
+	memset(m_pData, 0, m_dwLength);
+	memcpy(m_pData, &reinterpret_cast<const char*>(data_in)[offset], m_dwLength);
+	return false;
+}
+
+/*
+ * Used to combine different messages into one.
+ * This method appends new data at the end of already excisting data.
+ * If new data isn't same type as excisting data it isn't appended.
+ * Returns bool value of whether the method has succeeded to append the data or not.
+ */
+bool Data::AppendData(Data* aData)
+{
+	if ( m_Type == aData->m_Type )
+	{
+		//realloc memory
+		BYTE* newBlock = (BYTE*) realloc( m_pData, m_dwLength + aData->m_dwLength );
+		if ( newBlock != NULL )
+		{
+			//set new data
+			m_pData = newBlock;
+			//copy data
+			memcpy( ((BYTE*)m_pData) + m_dwLength,
+					aData->GetData(),
+					aData->GetLength() );
+			//update length
+			m_dwLength += aData->GetLength();
+			return true;
+		}
+	}
+	return false;
+}
+
+//**********************************************************************************
+// Class ParameterList
+//
+//**********************************************************************************
+
+
+ParameterList::ParameterList()
+{
+}
+
+ParameterList::~ParameterList()
+{
+	m_Map.clear();
+}
+
+void ParameterList::Add(const string& key, const void* value)
+{
+	m_Map[key] = value;
+}
+
+const void* ParameterList::Get(const string& key)
+{
+	return m_Map[key];
+}
+
+// End of the file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/datagateway.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,495 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of the DataGatewaySocketWriterThread,
+*	DataGatewaySocketReaderThread, DataGatewayClientThread and DataGateway
+*	classes.
+*/
+
+// INCLUDES
+#include "datagateway.h"
+
+//**********************************************************************************
+// Class DataGatewaySocketWriterThread
+//
+// This thread is used to read Data from outgoing queue 
+// and write it to Socket(connected to program using DataGateway)
+//**********************************************************************************
+
+DataGatewaySocketWriterThread::DataGatewaySocketWriterThread(SafeQueue<Data*>* q,
+															 Socket* s)
+	: m_Running(true)
+{
+	m_Queue = q;
+	m_Socket = s;
+}
+
+/*
+ * Main loop of thread
+ * Reads Data from outgoing queue and writes it to Socket(connected to program using DataGateway)
+ */
+void DataGatewaySocketWriterThread::Run()
+{
+	while (m_Running)
+	{
+		// Sending to TCP/IP port
+		//Util::Debug("[DataGatewaySocketWriterThread] try to send");
+		try
+		{
+			Data* d = m_Queue->front(50);
+			char* p = (char *)d->GetData();
+			//DWORD l = (DWORD)((((BYTE)p[g_HtiOffsetMessageSize] << 8) | (BYTE)p[g_HtiOffsetMessageSize+1]));
+			DWORD l = d->GetLength();
+
+			if (Util::GetVerboseLevel() == Util::debug)
+			{
+				char tmp[64];
+				sprintf(tmp, "[DataGatewaySocketWriterThread] HTI MsgSize = %d", l);
+				string s(tmp);
+				Util::Debug(s);
+				//Util::Hex(p, min(16,d->GetLength()));
+			}
+
+			//m_Socket->SendBytes((const unsigned char *)&p[g_HtiOffsetMessageData], l);
+			m_Socket->SendBytes((const unsigned char *)p, l);
+			Util::Debug("[DataGatewaySocketWriterThread] msg send");
+			m_Queue->pop();
+			delete d;
+			d = NULL;
+
+		} catch (TimeoutException te)
+		{
+			//Util::Debug("[DataGatewaySocketWriterThread]timeout exception");
+		}
+	}
+}
+
+void DataGatewaySocketWriterThread::Stop()
+{
+	m_Running = false;
+}
+
+bool DataGatewaySocketWriterThread::IsRunning()
+{
+	return m_Running;
+}
+
+//**********************************************************************************
+// Class DataGatewaySocketReaderThread
+//
+// This thread is used to read incoming bytes from Socket(connected to program using DataGateway)
+// which it then encapsulates into Data objects and forwards to outgoing queue
+//**********************************************************************************
+
+DataGatewaySocketReaderThread::DataGatewaySocketReaderThread(SafeQueue<Data*>* q,
+															 long bufsize,
+															 Socket* s)
+	: m_Running(true)
+{
+	m_Queue = q;
+	m_Socket = s;
+	if (bufsize > 0)
+	{
+		m_TcpIpBufferSize = bufsize;
+	}
+	else
+	{
+		m_TcpIpBufferSize = g_DataGatewayDefaultTcpIpBufferSize;
+	}
+}
+
+/*
+ * Main loop of thread
+ * Reads bytes from Socket(connected to program using DataGateway), encapsulates them to Data object and puts these to outgoing queue
+ */
+void DataGatewaySocketReaderThread::Run()
+{
+	BYTE* buffer = new BYTE[m_TcpIpBufferSize];
+	while (m_Running)
+	{
+		// Reading from TCP/IP port
+		Util::Debug("[DataGatewaySocketReaderThread] try to read");
+		int bytes_read = -1;
+		bytes_read = m_Socket->ReceiveBytes(buffer, m_TcpIpBufferSize);
+		if (bytes_read < 0)
+		{
+			Stop();
+			break;
+		}
+		if (bytes_read > 0) 
+		{
+			Data* d = new Data((void *)buffer, bytes_read, Data::EData);
+			if (Util::GetVerboseLevel() == Util::debug)
+			{
+				char tmp[64];
+				sprintf(tmp, "m_Socket->ReceiveBytes (%d (dec) bytes):", d->GetLength());
+				string s(tmp);
+				Util::Debug(s);
+				//Util::Hex(p, d->GetLength());
+			}
+
+			m_Queue->push(d);
+			d = NULL;
+		}
+		Sleep(50);
+	}
+	delete[] buffer;
+	buffer = NULL;
+}
+
+void DataGatewaySocketReaderThread::Stop()
+{
+	m_Running = false;
+}
+
+bool DataGatewaySocketReaderThread::IsRunning()
+{
+	return m_Running;
+}
+
+//**********************************************************************************
+// Class DataGatewayClientThread
+//
+// This thread serves DataGateway's clients
+// Gets Data from incoming queue to which DataGatewaySocketReader has pushed it and forwards
+// them to CommChannelPlugin.
+// The thread also reads incoming data from CommChannelPlugin and forwards them to outgoing queue which
+// DataGatewaySocketWriter then reads
+//**********************************************************************************
+
+DataGatewayClientThread::DataGatewayClientThread(Socket** s,
+												 long bufsize,
+												 const string& commchannel)
+	: m_ReaderThread(&m_ReaderQueue, bufsize, *s),
+	  m_WriterThread(&m_WriterQueue, *s),
+  	  m_CommChannelPluginName(commchannel),
+	  m_Running(true)
+{
+	m_CCLateInit = true;
+	m_Socket = s;
+	if (bufsize > 0)
+	{
+		m_TcpIpBufferSize = bufsize;
+	}
+	else
+	{
+		m_TcpIpBufferSize = g_DataGatewayDefaultTcpIpBufferSize;
+	}
+}
+
+DataGatewayClientThread::DataGatewayClientThread(Socket** s,
+												 long bufsize,
+										         CommChannelPlugin** f)
+	: m_ReaderThread(&m_ReaderQueue, bufsize, *s),
+	  m_WriterThread(&m_WriterQueue, *s),
+  	  m_CommChannelPluginName((*f)->GetName()),
+	  m_Running(true)
+{
+	m_CCLateInit = false;
+	m_Socket = s;
+	m_CommChannelPlugin = *f;
+	if (bufsize > 0)
+	{
+		m_TcpIpBufferSize = bufsize;
+	}
+	else
+	{
+		m_TcpIpBufferSize = g_DataGatewayDefaultTcpIpBufferSize;
+	}
+}
+
+DataGatewayClientThread::~DataGatewayClientThread()
+{
+	Util::Debug("DataGatewayClientThread::~DataGatewayClientThread()");
+	if (m_Running)
+	{
+		Stop();
+	}
+}
+
+/*
+ * Main loop of thread
+ * Gets Data from incoming queue to which DataGatewaySocketReader has pushed it and forwards
+ * them to CommChannelPlugin.
+ * Reads incoming data from CommChannelPlugin and forwards them to outgoing queue which
+ * DataGatewaySocketWriter then reads
+ */
+void DataGatewayClientThread::Run()
+{
+	DWORD res;
+
+	if (m_CCLateInit)
+	{		
+		m_CommChannelPlugin = CommChannelPlugin::Instance(m_CommChannelPluginName);
+		if (m_CommChannelPlugin == NULL)
+		{
+			g_ErrorCode = ERR_DG_COMMCHANNEL;
+			return;
+		}
+		if ((res = m_CommChannelPlugin->Connect()) != NO_ERRORS)
+		{
+			Util::Error("[DataGateway] Error - Cannot connect to the target.");
+			m_CommChannelPlugin->Disconnect();
+			g_ErrorCode = res;
+			return;
+		}
+		Util::Info("[DataGateway] Communication Channel Plugin loaded succesfully");
+	}
+	
+	//Start DataGatewaySocketReader and DataGatewaySocketWriter threads
+	m_ReaderThread.Start();
+	m_WriterThread.Start();
+
+	// Flush comm input buffer;
+	Data* dummy;
+	while (m_CommChannelPlugin->Receive(&dummy) == NO_ERRORS) continue;
+	dummy = NULL;
+
+	while (m_Running)
+	{
+		if (!m_ReaderThread.IsRunning() ||
+			!m_WriterThread.IsRunning())
+		{
+			Stop();
+			break;
+		}
+			
+		// Receiving from TCP/IP port and
+		// sending to CommChannelPlugin
+		try {
+			Data* d = m_ReaderQueue.front(50);
+			m_ReaderQueue.pop();
+			m_CommChannelPlugin->Send(d);
+			d = NULL;
+		} catch (TimeoutException te) {}
+			
+		// Receiving from CommChannelPlugin and
+		// sending data to TCP/IP port. If message
+		// is error or control message it is also
+		// handled here.
+		Data* out;
+
+		if (m_CommChannelPlugin->Receive(&out) != NO_ERRORS) continue;
+
+		switch (out->GetType())
+		{
+			case Data::EData:
+			{
+				m_WriterQueue.push(out);
+				out = NULL;				
+			}
+			break;
+			case Data::EControl:
+			{
+				Util::Debug("ClientThread: Control Message Received");
+				switch (*(BYTE*)out->GetData())
+				{
+					case ControlPhonePowered:
+						{
+							Util::Info("[DataGateway] Phone powered up");
+						}
+					break;
+				}
+			}
+			break;
+			case Data::EError:
+			{
+				Util::Debug("ClientThread: Error Message Received");
+				Stop();
+			}
+			break;
+
+			default:
+				{
+					Util::Debug("ClientThread: Unknown Message Received");
+				}
+			break;
+		}
+		delete out;
+		out = NULL;
+	}
+	delete *m_Socket;
+	m_Socket = NULL;
+
+	if (m_CCLateInit)
+	{
+		m_CommChannelPlugin->Disconnect();
+		Util::Info("[DataGateway] Communication Channel Plugin unloaded");
+		m_CommChannelPlugin = NULL;
+	}
+}
+
+void DataGatewayClientThread::Stop()
+{
+	m_Running = false;
+	m_WriterThread.Stop();
+	m_ReaderThread.Stop();
+	HANDLE handles[2];
+	handles[0] = m_WriterThread.ThreadHandle();
+	handles[1] = m_ReaderThread.ThreadHandle();
+	WaitForMultipleObjects(2, handles, TRUE, g_MaximumShutdownWaitTime);
+}
+
+//**********************************************************************************
+// Class DataGateway
+//
+// This is the main thread of DataGateway
+//**********************************************************************************
+
+DataGateway::DataGateway(int port,
+						 long bufsize,
+						 const string& commchannel,
+						 bool stayalive,
+						 bool cclateinit)
+	: m_TcpIpPort(port),
+	  m_TcpIpBufferSize(bufsize),
+  	  m_CommChannelPluginName(commchannel),
+	  m_StayAlive(stayalive),
+	  m_CCLateInit(cclateinit),
+	  m_Running(true)
+{
+	m_CommChannelPlugin = NULL;
+}
+
+/*
+ * Main loop of DataGateway
+ * This loop:
+ * -creates instance of CommChannelPlugin if lateinit isn't set on
+ * -starts listening to socket for incoming connections
+ * -after connection has arrived starts DataGatewayClient thread to serve the client
+ */
+void DataGateway::Run()
+{
+	DWORD res;
+	try
+	{
+		if (Util::GetVerboseLevel() >= Util::info)
+		{
+			char tmp[256];
+			sprintf(tmp, "[DataGateway] Using TCP/IP port %d", m_TcpIpPort);
+			string s(tmp);
+			Util::Info(s);
+			
+			sprintf(tmp, "[DataGateway] TCP/IP receive buffer size is %d bytes", m_TcpIpBufferSize);
+			s.assign(tmp);
+			Util::Info(s);
+
+			sprintf(tmp, "[DataGateway] Loading Communication Channel Plugin for [%s]", m_CommChannelPluginName.c_str());
+			s.assign(tmp);
+			Util::Info(s);
+		}
+
+		
+		//Util::Info("[DataGateway] TCP/IP port opened");
+		
+		if (!m_CCLateInit)
+		{
+		    //if not lateinit, CommChannelPlugin may be started
+			m_CommChannelPlugin = CommChannelPlugin::Instance(m_CommChannelPluginName);
+			if (m_CommChannelPlugin == NULL)
+			{
+				throw UtilError("[DataGateway] Error loading Communication Channel.", ERR_DG_COMMCHANNEL);
+			}
+			if ((res = m_CommChannelPlugin->Connect()) != NO_ERRORS)
+			{
+				m_CommChannelPlugin->Disconnect();
+				throw UtilError("[DataGateway] Error connecting to the target.", res);
+			}
+			Util::Info("[DataGateway] Communication Channel Plugin loaded succesfully");
+		}
+		else
+		{
+			Util::Info("[DataGateway] Communication Channel Plugin uses late initialization.");
+		}
+
+		while (m_Running)
+		{
+			g_ErrorCode = NO_ERRORS;
+			Util::Info("[DataGateway] Waiting connection");
+			Socket* s = new Socket(); 
+			SocketServer in;
+			// will use the socket for listening and return a new socket when connection 
+			// is established
+			String remoteHost( "[DataGateway] Connection established! Remote host : " );
+			in.Accept(s, m_TcpIpPort, 1, remoteHost); 
+			Util::Info(remoteHost);
+			DataGatewayClientThread* client;
+			if (m_CCLateInit)
+			{
+				// passes ownership of 's'
+				client = new DataGatewayClientThread(&s, m_TcpIpBufferSize, m_CommChannelPluginName);
+			}
+			else
+			{
+				// passes ownership of 's'
+				client = new DataGatewayClientThread(&s, m_TcpIpBufferSize, &m_CommChannelPlugin);
+			}
+			client->Start();
+
+			HANDLE handles[2];
+			handles[0] = client->ThreadHandle();
+			handles[1] = m_ShutdownEvent.EventHandle();
+			DWORD dwResult = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
+			switch (dwResult)
+			{
+				case WAIT_OBJECT_0 + 0:
+				{
+					Util::Debug("DataGateway::Run() Client thread stopped");
+				}
+				break;
+				case WAIT_OBJECT_0 + 1:
+				{
+					Util::Debug("DataGateway::Run() Request to shutdown");
+					client->Stop();
+					WaitForSingleObject(client->ThreadHandle(), g_MaximumShutdownWaitTime);
+				}
+				break;
+			}
+			Util::Info("[DataGateway] Connection closed.");
+			delete client;
+			client = NULL;
+			
+			if (!m_StayAlive) break;
+		}
+		if (!m_CCLateInit)
+		{
+			m_CommChannelPlugin->Disconnect();
+			Util::Info("[DataGateway] Communication Channel Plugin unloaded");
+			m_CommChannelPlugin = NULL;
+		}
+	} catch (char* s) {
+		char tmp[64];
+		sprintf(tmp, "[DataGateway] Error opening TCP/IP port - %s", s);
+		Util::Error(tmp);
+		g_ErrorCode = ERR_DG_SOCKET;
+	} catch (UtilError ue) {
+		Util::Error(ue.iError, ue.iResult);
+		g_ErrorCode = ue.iResult;
+	}
+
+	Util::Info("[DataGateway] Closed");
+}
+
+void DataGateway::Stop()
+{
+	m_Running = false;
+	m_ShutdownEvent.Set();
+}
+
+bool DataGateway::IsRunning()
+{
+	return m_Running;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/main.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,239 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*    This module contains the UI operations of DataGateway.
+*/
+
+#pragma warning ( disable : 4786 )
+
+#include "Socket.h"
+
+#include <windows.h>
+#include <process.h>
+#include <string>
+#include <map>
+
+#include "util.h"
+#include "datagateway.h"
+#include "common.h"
+
+// GLOBAL DEFINES
+// Command line switches
+#define PARAM_SWITCH_PORT       "-port"
+#define PARAM_SWITCH_BUFSIZE    "-bufsize"
+#define PARAM_SWITCH_COMMPLUGIN "-commchannel"
+#define PARAM_SWITCH_STAYALIVE  "-stayalive"
+#define PARAM_SWITCH_CCLATEINIT "-cclateinit"
+#define PARAM_SWITCH_SWT        "-swt"
+#define PARAM_SWITCH_VERBOSE    "-v"
+#define PARAM_SWITCH_TIMESTAMP  "-t"
+
+#define VERSION "v1.4"
+#define INFO "DataGateway %s - Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). All rights reserved\n\n"
+
+// Event object to catch console signal
+Event g_ConsoleCloseEvent;
+
+// Event object to wait datagateway shutdown
+Event g_DataGatewayClosedEvent;
+
+// Global parameters to be used in datagateway and all plugins
+map<string, string> g_parameters;
+
+// Maximum time to wait
+extern long g_MaximumShutdownWaitTime;
+
+extern DWORD g_ErrorCode;
+
+// FUNCTION PROTOTYPES
+// Prints usage of DataGateway
+void usage();
+
+// Initializes phoenixtool default values
+void init(map<string, string>&, map<string, string>&);
+
+// Catches console control signals
+BOOL WINAPI ConsoleControlHandler(DWORD);
+
+/*
+ * Main method of Datagateway
+ */
+int main(int argv, char *args[])
+{
+    printf(INFO, VERSION);
+    if (argv == 2 && strcmp("-h", args[1]) == 0)
+    {
+        usage();
+        return 0;
+    }
+
+    map<string, string> props;
+
+    try {
+        // Read properties from datagateway.ini file
+        Util::ReadProperties("datagateway.ini", props);
+
+        // Sets values from properties map to global parameters map
+        init(props, g_parameters);
+
+        if (argv > 1)
+        {
+            // Overrides properties file values with ones specified in command line
+            Util::ParseCmdLine(argv, args, g_parameters);
+            Util::SetTimestamp(g_parameters[PARAM_SWITCH_TIMESTAMP]);
+        }
+        Util::SetVerboseLevel(g_parameters[PARAM_SWITCH_VERBOSE]);
+
+        bool stayalive = (strcmp("true", g_parameters[PARAM_SWITCH_STAYALIVE].c_str()) == 0
+                            ? true
+                            : false);
+        bool cclateinit = (strcmp("true", g_parameters[PARAM_SWITCH_CCLATEINIT].c_str()) == 0
+                            ? true
+                            : false);
+        int port = atoi(g_parameters[PARAM_SWITCH_PORT].c_str());
+        long bufsize = atol(g_parameters[PARAM_SWITCH_BUFSIZE].c_str());
+        g_MaximumShutdownWaitTime = atol(g_parameters[PARAM_SWITCH_SWT].c_str());
+        string ch = Util::ToUpper(g_parameters[PARAM_SWITCH_COMMPLUGIN]);
+
+        DataGateway dg(port, bufsize, ch, stayalive, cclateinit);
+
+        // Installs console control handler for catching
+        // signals
+        if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleControlHandler, TRUE))
+        {
+            Util::Error("Error registering the console control handler");
+            return ERR_DG_CONSOLEHANDLER;
+        }
+
+        //start Datagateway's main thread
+        dg.Start();
+        HANDLE handles[2];
+        handles[0] = dg.ThreadHandle();
+        handles[1] = g_ConsoleCloseEvent.EventHandle();
+        //block until Datagateway main thread finishes and console is closed
+        DWORD dwResult = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
+        switch (dwResult)
+        {
+            case WAIT_OBJECT_0 + 0:
+            {
+                Util::Debug("main() Datagateway thread stopped");
+            }
+            break;
+            case WAIT_OBJECT_0 + 1:
+            {
+                dg.Stop();
+                if (g_MaximumShutdownWaitTime > 0)
+                {
+                    Util::Info("[DataGateway] Waiting DataGateway to shutdown");
+                    WaitForSingleObject(dg.ThreadHandle(), g_MaximumShutdownWaitTime);
+                }
+            }
+            break;
+        }
+        g_DataGatewayClosedEvent.Set();
+    } catch (UtilError ue) {
+        Util::Error(ue.iError, ue.iResult);
+        g_ErrorCode = ue.iResult;
+    }
+    if (g_ErrorCode != NO_ERRORS)
+    {
+        // Resolve error code to clear text
+        ERROR_LOOKUP(g_ErrorCode);
+    }
+    return g_ErrorCode;
+}
+
+/*
+ * This method sets values from properties map to global parameters map
+*/
+void init(map<string, string>& props,
+          map<string, string>& params)
+{
+    // Setting default values from properties file
+    // to parameters
+    params[PARAM_SWITCH_BUFSIZE]    = props["TCPIP_RECV_BUFFER_SIZE"];
+    params[PARAM_SWITCH_PORT]       = props["TCPIP_PORT"];
+    params[PARAM_SWITCH_COMMPLUGIN] = props["DEFAULT_COMM_CHANNEL_PLUGIN"];
+    params[PARAM_SWITCH_SWT]        = props["MAXIMUM_SHUTDOWN_WAITTIME"];
+    params[PARAM_SWITCH_VERBOSE]    = "info";
+    params[PARAM_SWITCH_STAYALIVE]  = "true";
+    params[PARAM_SWITCH_TIMESTAMP]  = "false";
+    params[PARAM_SWITCH_CCLATEINIT] = "false";
+}
+
+/*
+ * This method prints help information for DataGateway
+ */
+void usage()
+{
+    cout << "USAGE: datagateway.exe [SWITCHES in form -switch=value]\n\n";
+    cout << "\tSWITCHES:\n";
+    cout << "\t-port         TCP/IP port\n";
+    cout << "\t-bufsize      TCP/IP receive buffer size in bytes\n";
+    cout << "\t-commchannel  Communication Channel Plugin (CCP) name e.g. IPCOMM\n";
+    cout << "\t-stayalive    Whether DataGateway remains when client disconnects\n";
+    cout << "\t              or not\n";
+    cout << "\t-cclateinit   Whether CCP is initialized when client connects or not\n";
+    cout << "\t-swt          Maximum shutdown wait time in milliseconds. 0 means\n";
+    cout << "\t              no waiting.\n";
+    cout << "\t-v            Verbose mode\n";
+    cout << "\t-t            Timestamped output\n\n";
+    cout << "\tBy default these values are defined in datagateway.ini file.\n";
+    cout << "\tIf any switches are used those override values from ini file\n\n";
+    cout << "\tSTAYALIVE:\n";
+    cout << "\tfalse      DataGateway shutdown after client closes connection\n";
+    cout << "\ttrue       DataGateway remains waiting new connections (*)\n\n";
+    cout << "\tCCLATEINIT:\n";
+    cout << "\tfalse      DataGateway initializes CCP when started (*)\n";
+    cout << "\ttrue       DataGateway initializes CCP only when client connects to\n\n";
+    cout << "\tVERBOSE:\n";
+    cout << "\toff        Silent mode\n";
+    cout << "\tresult     Prints only result (no info/errors)\n";
+    cout << "\terror      Prints result and errors (*)\n";
+    cout << "\tinfo       Prints normal output\n";
+    cout << "\tdebug      Prints all\n\n";
+    cout << "\tTIMESTAMPED:\n";
+    cout << "\tfalse      No timestamp (*)\n";
+    cout << "\ttrue       Adds timestamp to output\n\n";
+    cout << "\t(*) means default value\n\n";
+    cout << "\tAll communication channel plugin parameters can also be passed from\n";
+    cout << "\tcommand line just by adding \"-\" to the parameter name. For example:\n";
+    cout << "\t\"-COMPORT=COM3\" or -REMOTE_PORT=3000\n";
+    cout << endl;
+}
+
+BOOL WINAPI ConsoleControlHandler(DWORD dwCtrlType)
+{
+    BOOL bReturnStatus = FALSE;
+    switch (dwCtrlType)
+    {
+        case CTRL_C_EVENT:
+        case CTRL_BREAK_EVENT:
+        case CTRL_CLOSE_EVENT:
+        case CTRL_LOGOFF_EVENT:
+        case CTRL_SHUTDOWN_EVENT:
+        {
+            Util::Info("[DataGateway] Request to terminate");
+            g_ConsoleCloseEvent.Set();
+
+            // Wait DG shutdown before returning control to system
+            WaitForSingleObject(g_DataGatewayClosedEvent.EventHandle(), g_MaximumShutdownWaitTime);
+        }
+        break;
+    }
+    bReturnStatus = TRUE;
+    return bReturnStatus;
+}
+
+// End of the file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/plugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of the Plugin, FrontendPlugin,
+*	CommChannelPlugin and CommChannelPluginObserver classes and implementation
+*	of DummyCommObserver.
+*/
+
+// INCLUDES
+#include "IPCommPlugin.h"
+#include "plugin.h"
+#include "util.h"
+#include "serialcommplugin.h"
+
+
+extern DWORD g_ErrorCode;
+
+//**********************************************************************************
+// Class Plugin
+//
+//**********************************************************************************
+
+Plugin::Plugin()
+{
+	Init();
+}
+
+DWORD Plugin::Init()
+{
+	m_Name = "NULL Plugin";
+	return NO_ERRORS;
+}
+
+const string& Plugin::GetName(string *name)
+{
+	if (name != NULL)
+	{
+		*name = m_Name;
+	}
+	return m_Name;
+}
+
+//**********************************************************************************
+// Class CommChannelPlugin
+//
+// This class is the parent class of all communication channel plugins used
+// in DataGateway.
+//**********************************************************************************
+
+CommChannelPlugin* CommChannelPlugin::m_Self = NULL;
+
+/*
+ * This method creates instance of specified plugin  
+ */
+CommChannelPlugin* CommChannelPlugin::Instance(const string& pluginname,
+											   const CommChannelPluginObserver* observer)
+{
+	if (m_Self == NULL)
+	{
+		if (pluginname.compare("SERIAL") == 0 )
+		{
+			m_Self = new SerialCommPlugin(observer);
+		}
+		else if (pluginname.compare("IPCOMM") == 0 )
+		{
+			m_Self = new IPCommPlugin(observer);
+		}
+		else
+		{
+			string err = "Error when creating communication channel plugin.\n";
+			err += "Unknown plugin '" + pluginname + "'";
+			Util::Error(err);
+			m_Self = NULL;
+			g_ErrorCode = ERR_DG_UNKNOWN_COMMCHANNEL;
+		}
+	}
+	return m_Self;
+}
+
+/*
+ * This method initializes and connects the instance of plugin
+ */
+DWORD CommChannelPlugin::Connect()
+{
+	if (m_Self == NULL) return ERR_DG_UNINITIALISED_COMMCHANNEL;
+	DWORD res;
+	if ((res = m_Self->Init()) != NO_ERRORS) return res;
+	return m_Self->Open();
+}
+
+/*
+ * This method closes and deletes the instance of plugin
+ */
+DWORD CommChannelPlugin::Disconnect()
+{
+	if (m_Self == NULL) return ERR_DG_UNINITIALISED_COMMCHANNEL;
+	Util::Info("[DataGateway] Waiting Communication Channel Plugin to shutdown");
+	m_Self->Close();
+	delete m_Self;
+	m_Self = NULL;
+	return NO_ERRORS;
+}
+
+CommChannelPlugin::CommChannelPlugin(const CommChannelPluginObserver* observer)
+	: Plugin()
+{
+	if (observer == NULL)
+	{
+		m_Observer = new DummyCommObserver;
+	}
+	else
+	{
+		m_Observer = observer;
+	}
+}
+
+DWORD CommChannelPlugin::Init()
+{
+	DWORD res;
+	res = Plugin::Init();
+	m_Open = false;
+	return res;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/safequeue.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*    This file contains implementation of SafeQueue template class popAll method.
+*/
+
+#include "safequeue.h"
+#include "common.h"
+/*
+ * This method is used to pop all of the elements in queue and return them in single Data object
+ */
+template <>
+(Data*)& SafeQueue<Data*>::popAll(DWORD timeout)
+	throw (TimeoutException)
+{
+	if (Semaphore::Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue front timed out");
+	}
+	Mutex::Lock();
+	Data*& first = queue<Data*>::front();
+	queue<Data*>::pop();
+	//add to the first the rest of queue
+	bool s = true;
+	while ( queue<Data*>::size() > 0 && s)
+	{
+		Data*& a = queue<Data*>::front();
+		int len = first->GetLength();
+		first->AppendData( a );
+		//check that size has changed
+		if ( first->GetLength() != len )
+		{
+			queue<Data*>::pop();
+			delete a;
+		}
+		else
+		{
+			s = false;
+		}
+	}
+	Mutex::Unlock();
+	return first;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/stdafx.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// stdafx.cpp : source file that includes just the standard includes
+// SimpleStreamAPIClient.pch will be the pre-compiled header
+// stdafx.obj will contain the pre-compiled type information
+
+#include "stdafx.h"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/sync.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implementation of synchronization objects. These are Mutex, Semaphore and
+*   Event classes.
+*/
+
+// INCLUDES
+#include "sync.h"
+
+//**********************************************************************************
+// Class Mutex
+//
+// This class implements a Mutex using Windows API synchronization mechanism 
+//**********************************************************************************
+
+Mutex::Mutex(void)
+{
+	InitializeCriticalSection(&m_Lock);
+}
+
+Mutex::~Mutex(void)
+{
+}
+
+void Mutex::Lock(void)
+{
+	EnterCriticalSection(&m_Lock);
+}
+
+void Mutex::Unlock(void)
+{
+	LeaveCriticalSection(&m_Lock);
+}
+
+//**********************************************************************************
+// Class Semaphore
+//
+// This class encapsulates Windows API Semaphore functionality
+//**********************************************************************************
+
+Semaphore::Semaphore(void)
+{
+	m_Semaphore = CreateSemaphore(NULL, 0, 0x7FFFFFF, NULL);
+}
+
+Semaphore::Semaphore(int available)
+{
+	m_Semaphore = CreateSemaphore(NULL, available, 0x7FFFFFF, NULL);
+}
+
+Semaphore::~Semaphore(void)
+{
+	CloseHandle(m_Semaphore);
+}
+
+DWORD Semaphore::Wait(DWORD timeout)
+{
+	DWORD dwResult = WaitForSingleObject(m_Semaphore, timeout);
+	switch (dwResult)
+	{
+	case WAIT_OBJECT_0:
+		return 0;
+	case WAIT_TIMEOUT:
+		return WAIT_TIMEOUT;
+	default:
+		return 1;
+	}
+}
+
+void Semaphore::Notify(void)
+{
+	ReleaseSemaphore(m_Semaphore, 1, NULL);
+}
+
+void Semaphore::Notify(int how_many)
+{
+	ReleaseSemaphore(m_Semaphore, how_many, NULL);
+}
+
+//**********************************************************************************
+// Class Event
+//
+// This class encapsulates Windows API Event functionality
+//**********************************************************************************
+
+Event::Event(bool manual_reset)
+{
+	m_Event = CreateEvent(NULL, manual_reset, false, NULL);
+}
+
+Event::~Event(void)
+{
+	CloseHandle(m_Event);
+}
+
+void Event::Set(void)
+{
+	SetEvent(m_Event);
+}
+
+void Event::Reset(void)
+{
+	ResetEvent(m_Event);
+}
+
+DWORD Event::Wait(DWORD timeout)
+{
+	DWORD dwResult = WaitForSingleObject(m_Event, timeout);
+	switch (dwResult)
+	{
+	case WAIT_OBJECT_0:
+		return 0;
+	case WAIT_TIMEOUT:
+		return WAIT_TIMEOUT;
+	default:
+		return 1;
+	}
+}
+
+HANDLE Event::EventHandle() const
+{
+	return m_Event;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/DataGateway/SRC/util.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,738 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This module contains the implementation of Util class member functions. 
+*   Util class provides static utility functions for logging and string
+*	manipulation.
+*/
+
+// INCLUDE FILES
+#include "util.h"
+
+// command line parameters
+extern map<string, string> g_parameters;
+
+//**********************************************************************************
+// Class Util
+//
+// Provides static utility functions for logging and string handling.
+//**********************************************************************************
+
+// The default verbose level for Util output is error
+Util::VerboseLevel Util::iVerbose(Util::error);
+
+// The default output is without timestamp
+int Util::iTimestamp(0);
+
+#ifdef ENABLE_LOG_SYNC 
+	Mutex Util::iCritical;
+#endif
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: SetVerboseLevel
+
+    Description: Sets new verbose level by string:
+	           
+				 "none"
+				 "result"
+				 "error"
+				 "info"
+				 "debug"
+    
+    Parameters: const string& aVerbose : in: Verbose level as string
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::SetVerboseLevel(const string& aVerbose)
+{
+	string verbose(aVerbose);
+	ToLower(verbose);
+	if (verbose.compare("result") == 0)
+	{
+		iVerbose = result;
+	}
+	else if (verbose.compare("error") == 0)
+	{
+		iVerbose = error;
+	}
+	else if (verbose.compare("info") == 0)
+	{
+		iVerbose = info;
+	}
+	else if (verbose.compare("debug") == 0)
+	{
+		iVerbose = debug;
+	}
+	else
+	{
+	 	iVerbose = none;
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: SetVerboseLevel
+
+    Description: Sets new verbose level by enumeration.
+    
+    Parameters: const VerboseLevel aVerbose : in: Verbose level
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::SetVerboseLevel(const VerboseLevel aVerbose)
+{
+	iVerbose = aVerbose;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: GetVerboseLevel
+
+    Description: Returns current verbose level.
+    
+    Parameters: None
+
+    Return Values: VerboseLevel : Current verbose level
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+Util::VerboseLevel Util::GetVerboseLevel()
+{
+	return iVerbose;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: SetTimestamp
+
+    Description: Enables/disables timestamp from output by string "yes" or "no".
+    
+    Parameters: const string& aTimestamp : in : "yes" to enable timestamp, "no" to
+	                                            disable.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::SetTimestamp(const string& aTimestamp)
+{
+	string timestamp(aTimestamp);
+	ToLower(timestamp);
+	if (timestamp.compare("true") == 0)
+	{
+		SetTimestamp(1);
+	}
+	else
+	{
+		SetTimestamp(0);
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: SetTimestamp
+
+    Description: Enables/disables timestamp from output. 0 is disabled.
+    
+    Parameters: const int aTimestamp : in : Enable/disable time stamp
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::SetTimestamp(const int aTimestamp)
+{
+	iTimestamp = aTimestamp;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: ParseCmdLine
+
+    Description: Parses command line parameters to map. The map which is passed
+	             as argument must contain all valid keys (command line swicthes).
+				 Function adds values to map to all keys found from command line.
+				 The command line switch is form <key>=<value>. Default values for
+				 keys can be specified.
+    
+    Parameters: const int aArgc           : in     : The number of arguments
+	            char **aArgs              : in     : Pointer array to arguments
+				map<string, string>& aMap : in/out : Map containing possible command
+				                                     line switches (keys). Values of
+													 switches are returned as values.
+
+    Return Values: None
+
+    Errors/Exceptions: UtilError
+
+-------------------------------------------------------------------------------*/
+void Util::ParseCmdLine(const int aArgc,
+						char **aArgs,
+						map<string, string>& aMap) throw (UtilError)
+{
+	for (int i = 1; i < aArgc; i++)
+	{
+		string p(aArgs[i]);
+		string v;
+		int idx = p.find_first_of("=");
+		if (idx != string::npos)
+		{
+			if ((idx + 1) == p.length())
+			{
+				string err("Parameter '" + p.substr(0, idx) + "' without value");
+				throw UtilError(err, ERR_UTIL_NO_PARAM_VALUE);
+			}
+			v = &aArgs[i][idx + 1];
+			p = p.substr(0, idx);
+		}
+		else
+		{
+			v = "";
+		}
+		aMap[p] = v;
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: GetValue
+
+    Description: Returns value by key from a map.
+    
+    Parameters: const string& aKey        : in  : Key to value 
+				map<string, string>& aMap : in  : Map containing valid keys
+				string& aValue            : out : Value of key
+
+    Return Values: None
+
+    Errors/Exceptions: UtilError
+
+-------------------------------------------------------------------------------*/
+void Util::GetValue(const string& aKey,
+					const map<string,
+					string>& aMap, string& aValue) throw (UtilError)
+{
+	map<string, string>::const_iterator i = aMap.find(aKey);
+	if (i != aMap.end())
+	{
+		aValue = i->second;
+	}
+	else
+	{
+		string err("Unknown parameter '" + aKey + "'");
+		throw UtilError(err, ERR_UTIL_UNKNOWN_PARAM);
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: ReadProperties
+
+    Description: Reads properties from a file to a map. Line beginning with
+	             hash character ('#') are considered as comments. The form
+				 of prooerties in file is <property> = <value>.
+    
+    Parameters: const string& aFilename   : in  : Filename where properties are read
+	            map<string, string>& aMap : out : Map where property values are put
+
+    Return Values: None
+
+    Errors/Exceptions: UtilError
+
+-------------------------------------------------------------------------------*/
+void Util::ReadProperties(const string& aFilename,
+						  map<string, string>& aMap) throw (UtilError)
+{
+	ifstream in(aFilename.c_str());
+	if (!in)
+	{
+		string err("Cannot open properties file '");
+		err += aFilename + "'.";
+		throw UtilError(err, ERR_UTIL_PROPERTIES_NOT_FOUND);
+	}
+	while (in)
+	{
+		char tmp[256];
+		in.getline(tmp, 256);
+		string line(tmp);
+		if (line.length() == 0 || line.find_first_of("#") == 0)
+		{
+			continue;
+		}
+		int idx = line.find_first_of('=');
+		string v, p;
+		if (idx != string::npos)
+		{
+			p = line.substr(0, idx);
+			int r = p.find(" ");
+			while (r != string::npos)
+			{
+				p.replace(r, 1, "");
+				r = p.find(" ");
+			}
+			v = line.substr(idx + 1);
+			string::iterator i = v.begin();
+			int spaces = 0;
+			while (i != v.end() && *i == ' ')
+			{
+				++spaces;
+				++i;
+			}
+			v.erase(0, spaces);
+			if (v.length() == 0)
+			{
+				string err = "Value not specified for parameter '";
+				err += line.substr(0, idx) + "'.";
+				throw UtilError(err, ERR_UTIL_NO_PROPERTY_VALUE);			
+			}
+		}
+		else 
+		{
+			p = line;
+			v = "";
+		}
+		aMap[p] = v;
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Error
+
+    Description: Prints message to output in error level.
+    
+    Parameters: const string& aMsg : in : Error message to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Error(const string& aMsg)
+{
+	Print(cerr, aMsg, error);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Error
+
+    Description: Prints message to output in error level with error code number.
+    
+    Parameters: const string& aMsg : in : Error message to output
+				const long aCode   : in : Error code to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Error(const string& aMsg, const long aCode)
+{
+	Print(cerr, aMsg, error, aCode);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Log
+
+    Description: Prints message to output in result level.
+    
+    Parameters: const string& aMsg : in : Result message to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Log(const string& aMsg)
+{
+	Print(cout, aMsg, result);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Info
+
+    Description: Prints message to output in info level.
+    
+    Parameters: const string& aMsg : in : Info message to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Info(const string& aMsg)
+{
+	Print(cout, aMsg, info);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Debug
+
+    Description: Prints message to output in debug level.
+    
+    Parameters: const string& aMsg : in : Debug message to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Debug(const string& aMsg)
+{
+	Print(cout, aMsg, debug);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Print
+
+    Description: Prints output to a stream.
+    
+    Parameters: ostream& out              : in : Stream where to write
+                const string& aMsg        : in : Message to output
+                const VerboseLevel aLevel : in : Verbose level of message
+				const long aCode          : in : Possible error code if != 0
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Print(ostream& out,
+				 const string& aMsg,
+				 const VerboseLevel aLevel,
+				 const long aCode)
+{
+#ifdef ENABLE_LOG_SYNC 
+	iCritical.Lock();
+#endif
+
+	if (aLevel <= iVerbose)
+	{
+		if (iTimestamp)
+		{
+			char timestamp[128];
+			_strdate(timestamp);
+			char tmp[16];
+			_strtime(tmp);
+			strcat(timestamp, " ");
+			strcat(timestamp, tmp);
+			struct _timeb tb;
+			_ftime(&tb);
+			sprintf(tmp, ".%03d", tb.millitm);
+			strcat(timestamp, tmp);
+			out << "[" << timestamp << "] ";
+		}
+
+		out << aMsg;
+		//if (aLevel == debug)
+		{
+			OutputDebugString(aMsg.c_str());
+			OutputDebugString("\r\n");
+		}
+		if (aCode != 0)
+		{
+			out.setf(ios_base::hex, ios_base::basefield);
+			out << " (error: 0x" << aCode << ")";
+		}
+		out << endl;
+	}
+#ifdef ENABLE_LOG_SYNC 
+	iCritical.Unlock();
+#endif
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: ToLower
+
+    Description: Converts string to lower case.
+    
+    Parameters: string& aString : in/out : String which is converted to lower case
+
+    Return Values: string& : Reference to converted string.
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+string& Util::ToLower(string& aString)
+{
+	string::iterator p = aString.begin();
+	while (p != aString.end())
+	{
+		*p = tolower(*p);
+		++p;
+	}
+	return aString;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: ToUpper
+
+    Description: Converts string to upper case.
+    
+    Parameters: string& aString : in/out : String which is converted to upper case
+
+    Return Values: string& : Reference to converted string.
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+string& Util::ToUpper(string& aString)
+{
+	string::iterator p = aString.begin();
+	while (p != aString.end())
+	{
+		*p = toupper(*p);
+		++p;
+	}
+	return aString;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Hex
+
+    Description: Prints hex dump of char table to output.
+    
+    Parameters: const char aData[] : in : Data to be output as hex dump
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Hex(const char aData[])
+{
+	string s(aData);
+	Hex(s);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Hex
+
+    Description: Prints hex dump of string to output.
+    
+    Parameters: const string& aMsg : in : Data to be output as hex dump
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Hex(const string& aMsg)
+{
+	Hex((const unsigned char *)aMsg.c_str(), aMsg.length());
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Hex
+
+    Description: Prints hex dump of data to output.
+    
+    Parameters: const unsigned char* aData : in : Pointer to data to be output
+	                                              as hex dump
+                const int aLength          : in : The lenght of data
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Hex(const unsigned char* aData, const int aLength)
+{
+	Hex((void *)aData, aLength);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Hex
+
+    Description: Prints hex dump of data to output.
+    
+    Parameters: void *aData       : in : Pointer to data to be output as hex dump
+                const int aLength : in : The lenght of data
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Hex(void *aData, const int aLength)
+{
+	Hex(aData, aLength, NULL);
+}
+
+void Util::Hex(void* aData, const int aLength, string* aHexDump)
+{
+#ifdef ENABLE_LOG_SYNC 
+	iCritical.Lock();
+#endif
+
+	char line[16];
+	int line_len = 16;
+	int bytes_to_copy = 0;
+	int printed = 0;
+	bool print_out = (aHexDump == NULL ? true : false);
+	unsigned char *data = (unsigned char *)aData;
+
+	if (print_out)
+	{
+		printf("\n");
+	}
+	else
+	{
+		aHexDump->append("\r\n");
+	}
+	while (printed < aLength)
+	{
+		bytes_to_copy = ((aLength - printed >= line_len ? line_len : (aLength - printed)));
+		memset(line, 0, sizeof(line));
+		memcpy(line, &data[printed], bytes_to_copy);
+		for (int j = 0; j < line_len; j++)
+		{
+			char hex[4];
+			sprintf(hex, "%02X ", (unsigned char)line[j]);
+			if (print_out)
+			{
+				printf("%s", hex);
+			}
+			else
+			{
+				string s(hex);
+				aHexDump->append(s);
+			}
+		}
+		if (print_out) printf(" | ");
+		for (int j = 0; j < line_len; j++)
+		{
+			char c = line[j];
+			if (c >= ' ' && c <= 'z')
+			{
+				if (print_out)
+				{
+					printf("%c", c);
+				}
+				else
+				{
+					char tmp[2];
+					sprintf(tmp, "%c", c);
+					string s(tmp);
+					aHexDump->append(s);
+				}
+			} 
+			else
+			{
+				if (print_out)
+				{
+					printf(".");
+				}
+				else
+				{
+					aHexDump->append(".");
+				}
+			}
+		}
+		if (print_out)
+		{
+			printf("\n");
+		}
+		else
+		{
+			aHexDump->append("\r\n");
+		}
+		if ((printed - line_len) < aLength)
+		{
+			printed += 16;
+		}
+		else
+		{
+			printed = aLength - printed;
+		}
+	}
+	if (print_out) printf("\n");
+
+#ifdef ENABLE_LOG_SYNC 
+	iCritical.Unlock();
+#endif
+}
+
+/*
+ * Sets paramvalue if command line parameter is found
+ */
+void Util::CheckCommandlineParam( const string& paramname, string& paramvalue )
+{
+	// Command line parameter overrides ini-file value
+	if ( !g_parameters[paramname].empty() )
+		paramvalue = g_parameters[paramname];
+}
+
+// End of the file
\ No newline at end of file
Binary file hti/PC_Tools/HTIGateway/Binaries/HTIGateway_binaries.zip has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiCommon/HtiCommon.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,564 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#define _EXPORT_HTI_COMMON_
+
+#include "..\libs\stdsoap2.h"
+#include "hticommon.h"
+#include "HtiSoapHandlerInterface.h"
+
+//**********************************************************************************
+// General util functions
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// check_mandatory_string_parameter
+//**********************************************************************************
+EXPORT_FROM_DLL int check_mandatory_string_parameter(struct soap* soap,
+													 char* parameter,
+													 char* parameterName)
+{
+	int result = SOAP_OK;
+	
+	if(!parameter)
+	{
+		char msg[] = "Mandatory parameter \"%s\" missing";
+		int msgLen = _scprintf(msg, parameterName)+1; //+1 for nul char
+		char* buf = new char[msgLen];
+		sprintf(buf, msg, parameterName);
+		soap->error = soap_receiver_fault(soap, "HtiGateway", buf);
+		delete buf;
+		result = SOAP_FAULT;
+	}
+	else if(strlen(parameter) == 0)
+	{
+		char msg[] = "Mandatory parameter \"%s\" empty";
+		int msgLen = _scprintf(msg, parameterName)+1; //+1 for nul char
+		char* buf = new char[msgLen];
+		sprintf(buf, msg, parameterName);
+		soap->error = soap_receiver_fault(soap, "HtiGateway", buf);
+		delete buf;
+		result = SOAP_FAULT;		
+	}
+
+	return result;
+}
+
+//**********************************************************************************
+// check_mandatory_wcstring_parameter
+//**********************************************************************************
+EXPORT_FROM_DLL int check_mandatory_wcstring_parameter(struct soap* soap,
+													   wchar_t* parameter,
+													   char* parameterName)
+{
+	int result = SOAP_OK;
+	
+	if ( !parameter )
+	{
+		char msg[] = "Mandatory parameter \"%s\" missing";
+		int msgLen = _scprintf(msg, parameterName)+1; //+1 for nul char
+		char* buf = new char[msgLen];
+		sprintf(buf, msg, parameterName);
+		soap->error = soap_receiver_fault(soap, "HtiGateway", buf);
+		delete buf;
+		result = SOAP_FAULT;
+	}
+	else if ( wcslen(parameter) == 0 )
+	{
+		char msg[] = "Mandatory parameter \"%s\" empty";
+		int msgLen = _scprintf(msg, parameterName)+1; //+1 for nul char
+		char* buf = new char[msgLen];
+		sprintf(buf, msg, parameterName);
+		soap->error = soap_receiver_fault(soap, "HtiGateway", buf);
+		delete buf;
+		result = SOAP_FAULT;		
+	}
+
+	return result;
+}
+
+//**********************************************************************************
+// dump
+//**********************************************************************************
+EXPORT_FROM_DLL void dump(BYTE *data, int dataLen)
+{
+	printf("\nDUMP len %d:\n", dataLen);
+
+	int hex_index = 0;
+	int char_index = 0;
+
+	char hex_buf[48+1];
+	char char_buf[16+1];
+	hex_buf[0]  = 0x0;
+	char_buf[0] = 0x0;
+
+	int j = 0;
+	for(int i=0; i<dataLen; i++)
+	{
+		char tmp[3];
+		sprintf(tmp, "%02x", data[i]);
+		strcat(hex_buf, tmp);
+
+		if( (data[i] != 0x0a) && (data[i] != 0x0d) && (data[i] != 0x08))
+			char_buf[j] = data[i];
+		else
+			char_buf[j] = '.';
+
+		if( i == dataLen-1 )
+		{
+			char_buf[j+1] = 0x0;
+			printf("%-45s\t\t%s\n", hex_buf, char_buf);
+			break;
+		}
+
+		if( !(j%15) && (j!=0) )
+		{
+			char_buf[j+1] = 0x0;
+			printf("%-45s\t\t%s\n", hex_buf, char_buf);
+			j = 0;
+			hex_buf[0]  = 0x0;
+			continue;
+		}
+		else
+			strcat(hex_buf, " ");
+
+		j++;
+	}
+}
+
+//**********************************************************************************
+// soap_receiver_fault_format
+//**********************************************************************************
+EXPORT_FROM_DLL int soap_receiver_fault_format(struct soap *soap,
+											   const char *faultstring,
+											   const char *faultdetail, ...)
+{
+	va_list marker;
+	va_start( marker, faultdetail );
+
+	char* tmp = new char[strlen(faultdetail)+1];
+	memcpy(tmp, faultdetail, strlen(faultdetail)+1);
+	
+	char* token = strtok(tmp, "%");
+	if(token == NULL)
+	{
+		// no parameters
+		delete tmp;
+		return soap_receiver_fault(soap, faultstring, faultdetail);
+	}
+
+	char* text = (char*) malloc( strlen(token) + 1);
+	strcpy(text, token);
+    
+	token = strtok(NULL, "%");
+	while( token != NULL )
+	{
+		char* parse = NULL;
+
+		if(token[0] == 'd')
+		{
+			int var = va_arg( marker, int );
+			parse = new char[ _scprintf("%d", var) + 1 ];
+            sprintf( parse, "%d", var );
+		}
+		else if(token[0] == 'x')
+		{
+			int var = va_arg( marker, int );
+			parse = new char[ _scprintf("%x", var) + 1 ];
+            sprintf( parse, "%x", var );	
+		}
+		else if(token[0] == 's' )
+		{
+			char* var = va_arg( marker, char* );
+			parse = new char[ _scprintf("%s", var) + 1 ];
+            sprintf( parse, "%s", var );
+		}
+
+		// add parsed part
+		if(parse)
+		{
+			text = (char*) realloc( text, strlen(text) + strlen(parse) + 1 );
+			strcat(text, parse);
+			delete parse;
+		}
+        
+		// add remaining part
+		text = (char*) realloc( text, strlen(text) + strlen(token+1) + 1 );
+		strcat(text, token+1);
+
+		token = strtok(NULL, "%");
+	}
+	va_end( marker );
+	delete tmp;
+
+	int res = soap_receiver_fault(soap, faultstring, text);
+	free (text);
+	return res;
+}
+
+//**********************************************************************************
+// HtiMsgHelper class implementation
+//
+//**********************************************************************************
+//**********************************************************************************
+// HtiMsgHelper::HtiMsgHelper
+//**********************************************************************************
+EXPORT_FROM_DLL HtiMsgHelper::HtiMsgHelper(struct soap *soap)
+{
+	m_msgBody = NULL;
+	m_msgBodyLen = 0;
+	m_soap = soap;
+	m_serviceId = 0;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::HtiMsgHelper
+//**********************************************************************************
+EXPORT_FROM_DLL HtiMsgHelper::HtiMsgHelper(struct soap *soap,
+										   DWORD serviceId)
+{
+	m_msgBody = NULL;
+	m_msgBodyLen = 0;
+	m_soap = soap;
+	m_serviceId = serviceId;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::HtiMsgHelper
+//**********************************************************************************
+EXPORT_FROM_DLL HtiMsgHelper::HtiMsgHelper(struct soap *soap,
+										   DWORD serviceId,
+										   BYTE command)
+{
+	m_msgBody = new BYTE[1];
+	m_msgBody[0] = command;
+	m_msgBodyLen = 1;
+	m_soap = soap;
+	m_serviceId = serviceId;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::~HtiMsgHelper
+//**********************************************************************************
+EXPORT_FROM_DLL HtiMsgHelper::~HtiMsgHelper()
+{
+	// m_msgBody is not deleted as we dont have ownership if
+	// it is a received message
+}
+
+//**********************************************************************************
+// HtiMsgHelper::IncBodySize
+//**********************************************************************************
+void HtiMsgHelper::IncBodySize(int size)
+{
+	BYTE *newMsgBody = new BYTE[m_msgBodyLen+size];
+	memcpy(newMsgBody, m_msgBody, m_msgBodyLen);
+	delete m_msgBody;
+	m_msgBody = newMsgBody;
+	m_msgBodyLen += size;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::CheckMsgExactLen
+//**********************************************************************************
+EXPORT_FROM_DLL int HtiMsgHelper::CheckMsgExactLen( int len )
+{
+	if( GetMsgLen() != len )
+	{
+		m_soap->error = soap_receiver_fault_format( m_soap, "HtiError", 
+			"Incorrect HTI msg length. Expecting %d received %d", len, GetMsgLen());
+        return SOAP_FAULT;
+	}
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::CheckMsgMinLen
+//**********************************************************************************
+EXPORT_FROM_DLL int HtiMsgHelper::CheckMsgMinLen( int len )
+{
+	if( GetMsgLen() < len )
+	{
+		m_soap->error = soap_receiver_fault(
+			m_soap, "HtiError", "HTI msg too small");
+        return SOAP_FAULT;
+	}
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// HtiAudioMsg::CheckCommandCode
+//**********************************************************************************
+EXPORT_FROM_DLL int HtiMsgHelper::CheckCommandCode(BYTE code)
+{
+	if(GetByte(0) != code)
+	{
+		m_soap->error = soap_receiver_fault_format(m_soap, "HtiError",
+			"incorrect response CommandCode (0x%x)", GetByte(0));
+		return SOAP_FAULT;
+	}
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddByte
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddByte( BYTE byte )
+{
+	int writePos = m_msgBodyLen;
+	IncBodySize( 1 );
+	m_msgBody[writePos] = byte;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddWord
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddWord( WORD data )
+{
+	int writePos = m_msgBodyLen;
+	IncBodySize( 2 );
+	*(WORD*)(m_msgBody+writePos) = data;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddDWord
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddDWord( DWORD data )
+{
+	int writePos = m_msgBodyLen;
+	IncBodySize( 4 );
+	*(DWORD*)(m_msgBody+writePos) = data;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddInt
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddInt( int data )
+{
+	int writePos = m_msgBodyLen;
+	IncBodySize( 4 );
+	*(int*)(m_msgBody+writePos) = data;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddUInt64
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddUInt64( unsigned __int64 data )
+{
+	int writePos = m_msgBodyLen;
+	IncBodySize( 8 );
+	*(unsigned __int64*)(m_msgBody+writePos) = data;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddString
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddString( char* string )
+{
+	int stringLen = string ? (int) strlen( string ) : 0;
+	if( stringLen == 0 )
+		return;
+
+	int writePos = m_msgBodyLen;
+	IncBodySize( stringLen );
+	memcpy(m_msgBody+writePos, string, stringLen);
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddStringWithLengthByte
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddStringWithLengthByte( char* string )
+{
+	int stringLen = string ? (int) strlen( string ) : 0;
+	if( stringLen == 0 )
+		return;
+
+	AddByte( stringLen );
+	AddString( string );
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddStringWithLengthByteZero
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddStringWithLengthByteZero( char* string )
+{
+	int stringLen = string ? (int) strlen( string ) : 0;
+
+	AddByte( stringLen );
+
+	if( stringLen == 0 )
+		return;
+
+	AddString( string );
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddWCString
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddWCString(wchar_t* string)
+{
+	int stringLen = string ? (int) wcslen( string )*2 : 0;
+	if( stringLen == 0 )
+		return;
+
+	int writePos = m_msgBodyLen;
+	IncBodySize( stringLen );
+	memcpy( m_msgBody+writePos, string, stringLen );
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddWCStringWithLengthByte
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddWCStringWithLengthByte( wchar_t* string )
+{
+	int stringLen = string ? (int) wcslen( string ) : 0;
+	if( stringLen == 0 )
+		return;
+
+	AddByte( stringLen );
+	AddWCString( string );
+}
+//**********************************************************************************
+// HtiMsgHelper::AddData
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddData( void* data, int dataLen )
+{
+	int writePos = m_msgBodyLen;
+	IncBodySize( dataLen );
+	memcpy( m_msgBody+writePos, data, dataLen );
+}
+
+//**********************************************************************************
+// HtiMsgHelper::SendMsg
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::SendMsg()
+{
+	// Send the message to symbian side
+	HtiSoapHandlerInterface* handler = 
+		static_cast<HtiSoapHandlerInterface*>(m_soap->user);
+	handler->SendHtiMessage(m_serviceId, m_msgBody, m_msgBodyLen);
+
+	// destroy the sent message
+	delete m_msgBody;
+	m_msgBody = NULL;
+	m_msgBodyLen = 0;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::ReceiveMsg
+//**********************************************************************************
+EXPORT_FROM_DLL int HtiMsgHelper::ReceiveMsg( int timeout )
+{
+	// Clean these up for received HTI message
+	if( m_msgBody )
+	{
+		delete m_msgBody;
+		m_msgBody = NULL;
+		m_msgBodyLen = 0;
+	}
+	
+	HtiSoapHandlerInterface* handler = 
+		static_cast<HtiSoapHandlerInterface*>(m_soap->user);
+
+	// Wait for OK or error msg
+	if (handler->WaitForHtiMessage(timeout))
+	{
+		if ( !handler->IsReceivedHtiError() )
+		{
+			// Get received message
+			// (handler has ownership of the message body)
+			m_msgBody = (BYTE*) handler->ReceivedHtiMessageBody();
+			m_msgBodyLen = handler->ReceivedHtiMessageBodySize();
+			return SOAP_OK;
+		}
+		else
+		{
+			// Fill the error description
+			handler->SendSoapFaultFromReceivedHtiError();
+			return SOAP_FAULT;
+		}
+	}
+	// ...or timeout
+	else
+	{
+		m_soap->error = soap_receiver_fault(
+			m_soap, "HtiGateway", "No response from symbian side");
+		return SOAP_FAULT;
+	}
+}
+
+//**********************************************************************************
+// HtiMsgHelper::SendReceiveMsg
+//**********************************************************************************
+EXPORT_FROM_DLL int HtiMsgHelper::SendReceiveMsg( int timeout )
+{
+	SendMsg();
+	return ReceiveMsg( timeout );
+}
+
+//**********************************************************************************
+// HtiMsgHelper::GetSoapString
+//**********************************************************************************
+EXPORT_FROM_DLL char* HtiMsgHelper::GetSoapString( int offset, int len )
+{
+	char* string = (char*) soap_malloc( m_soap, len+1 );//+1 for the last null char
+	if ( len > 0 )
+        memcpy( string, m_msgBody + offset, len );
+	string[len] = 0x00; //add null char
+	return string;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::GetSoapWCString
+//**********************************************************************************
+EXPORT_FROM_DLL wchar_t* HtiMsgHelper::GetSoapWCString( int offset, int len )
+{
+	wchar_t* string = (wchar_t*) soap_malloc( m_soap, len*2+2 );//+2 for the last null char
+	if ( len > 0 )
+        memcpy( string, m_msgBody + offset, len*2 );
+	string[len] = 0x0000; //add null char
+	return string;
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddStringWithLengthWordZero
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddStringWithLengthWordZero( char* string )
+{
+	int stringLen = string ? (int) strlen( string ) : 0;
+
+	AddWord( stringLen );
+
+	if( stringLen == 0 )
+		return;
+
+	AddString( string );
+}
+
+//**********************************************************************************
+// HtiMsgHelper::AddWCStringWithLengthByteZero
+//**********************************************************************************
+EXPORT_FROM_DLL void HtiMsgHelper::AddWCStringWithLengthByteZero( wchar_t* string )
+{
+	int stringLen = string ? (int) wcslen( string ) : 0;
+
+	AddByte( stringLen );
+
+	if( stringLen == 0 )
+		return;
+
+	AddWCString( string );
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiCommon/HtiCommon.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_COMMON__
+#define __HTI_COMMON__
+
+#ifdef _EXPORT_HTI_COMMON_
+	#define EXPORT_FROM_DLL __declspec(dllexport)
+#else
+	#define EXPORT_FROM_DLL __declspec(dllimport)
+#endif
+
+#include <windows.h>
+
+// CONSTANTS
+const int HTIMSG_TIMEOUT_5_SECONDS  =  5000; // milliseconds
+const int HTIMSG_TIMEOUT_10_SECONDS = 10000;
+const int HTIMSG_TIMEOUT_30_SECONDS = 30000;
+const int HTIMSG_TIMEOUT_60_SECONDS = 30000;
+
+// GENERAL UTIL FUNCTIONS
+/**
+* Checks if a string parameter is valid. Not null or empty.
+*/
+EXPORT_FROM_DLL int check_mandatory_string_parameter(struct soap* soap,
+													 char* parameter,
+													 char* parameterName);
+/**
+* Checks if a wide character string parameter is valid. Not null or empty.
+*/
+EXPORT_FROM_DLL int check_mandatory_wcstring_parameter(struct soap* soap,
+													   wchar_t* parameter,
+													   char* parameterName);
+/**
+* A little addition to basic soap functions. Same as soap_receiver_fault 
+* but can add formatted data to faultstring.
+*/
+EXPORT_FROM_DLL int soap_receiver_fault_format(struct soap *soap,
+											   const char *faultstring,
+											   const char *faultdetail, ...);
+/**
+* Prints bytes to the screen
+*/
+EXPORT_FROM_DLL void dump( BYTE *data, int dataLen );
+
+
+// CLASSES
+// Class for HTI message manipulation
+class HtiMsgHelper
+{
+public:
+	/**
+	* Constructors.
+	*/
+	EXPORT_FROM_DLL HtiMsgHelper( struct soap *soap );
+	EXPORT_FROM_DLL HtiMsgHelper( struct soap *soap, DWORD serviceId );
+	EXPORT_FROM_DLL HtiMsgHelper( struct soap *soap, DWORD serviceId, BYTE command );
+
+	/**
+	* Destructor.
+	*/
+	EXPORT_FROM_DLL ~HtiMsgHelper();
+	
+	/**
+	* General util methods.
+	*/
+	EXPORT_FROM_DLL BYTE* GetMsgBody() { return m_msgBody; };
+	EXPORT_FROM_DLL int   GetMsgLen() { return m_msgBodyLen; };
+
+	/**
+	* Methods for getting data from HTI message.
+	*/
+	EXPORT_FROM_DLL BYTE  GetByte( int offset ) { return *(BYTE*)(m_msgBody+offset); };
+	EXPORT_FROM_DLL WORD  GetWord( int offset ) { return *(WORD*)(m_msgBody+offset); };
+	EXPORT_FROM_DLL DWORD GetDWord( int offset ) { return *(DWORD*)(m_msgBody+offset); };
+	EXPORT_FROM_DLL int   GetInt( int offset ) { return *(int*)(m_msgBody+offset); };
+	EXPORT_FROM_DLL char* GetSoapString( int offset, int len );
+	EXPORT_FROM_DLL wchar_t* GetSoapWCString( int offset, int len );
+
+	/**
+	* Received HTI message checking methods
+	*/
+	EXPORT_FROM_DLL int CheckMsgExactLen( int len );
+	EXPORT_FROM_DLL int CheckMsgMinLen( int len );
+	EXPORT_FROM_DLL int CheckCommandCode( BYTE code );
+
+	/**
+	* Methods for adding data to HTI message.
+	*/
+	EXPORT_FROM_DLL void AddByte( BYTE data );
+	EXPORT_FROM_DLL void AddWord( WORD data );
+	EXPORT_FROM_DLL void AddDWord( DWORD data );
+	EXPORT_FROM_DLL void AddInt( int data );
+	EXPORT_FROM_DLL void AddUInt64( unsigned __int64 data );
+	EXPORT_FROM_DLL void AddString( char* string );
+	EXPORT_FROM_DLL void AddWCString( wchar_t* string );
+	EXPORT_FROM_DLL void AddData( void* data, int dataLen );
+
+	// does not add if null or length is zero
+	EXPORT_FROM_DLL void AddStringWithLengthByte( char* string ); 
+	EXPORT_FROM_DLL void AddWCStringWithLengthByte( wchar_t* string );
+
+	// adds at least the lenght byte
+	EXPORT_FROM_DLL void AddStringWithLengthByteZero( char* string ); 
+	EXPORT_FROM_DLL void AddStringWithLengthWordZero( char* string );
+    EXPORT_FROM_DLL void AddWCStringWithLengthByteZero( wchar_t* string );
+	
+	/**
+	* Methods for sending and receiving.
+	* Can be replaced if needed.
+	*/
+	virtual EXPORT_FROM_DLL void SendMsg();
+	virtual EXPORT_FROM_DLL int ReceiveMsg( int timeout );
+	virtual EXPORT_FROM_DLL int SendReceiveMsg( int timeout );
+
+protected:
+	/**
+	* Increases m_msgBody for adding new data
+	*/
+	void IncBodySize( int size );
+
+protected:
+	/**
+	* soap env.
+	*/
+	struct soap *m_soap;
+
+	/**
+	* Service id used in sending the message.
+	*/
+	DWORD        m_serviceId;
+
+	/**
+	* The actual message and its length in bytes.
+	* Destroyed when message is sent. Received message is not destroyed 
+	* because we dont have ownership.
+	*/
+	BYTE*        m_msgBody; 
+	int          m_msgBodyLen;
+};
+
+#endif //__HTI_COMMON__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiCommon/HtiCommon.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,220 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiCommon"
+	ProjectGUID="{B49672B8-5D71-4254-AAA2-397C13433450}"
+	RootNamespace="HtiCommon"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\Libs"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;HTICOMMON_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib"
+				OutputFile="$(OutDir)/HtiCommonD.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				ProgramDatabaseFile="$(OutDir)/HtiCommon.pdb"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/HtiCommonD.lib"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(ProjectDir)HtiCommon.h $(TargetDir)&#x0D;&#x0A;copy $(ProjectDir)HtiSoapHandlerInterface.h $(TargetDir)&#x0D;&#x0A;"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\Libs"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;HTICOMMON_EXPORTS"
+				RuntimeLibrary="2"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib msvcrt.lib"
+				OutputFile="$(OutDir)/HtiCommon.dll"
+				LinkIncremental="1"
+				IgnoreDefaultLibraryNames="msvcrtd.lib"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/HtiCommon.lib"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(ProjectDir)HtiCommon.h $(TargetDir)&#x0D;&#x0A;copy $(ProjectDir)HtiSoapHandlerInterface.h $(TargetDir)&#x0D;&#x0A;"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiCommon.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiCommon.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSoapHandlerInterface.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+		<File
+			RelativePath=".\ReadMe.txt"
+			>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiCommon/HtiSoapHandlerInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI__SOAP_HANDLER_INTERFACE_H_
+#define __HTI__SOAP_HANDLER_INTERFACE_H_
+
+#include "hticommon.h"
+
+class HtiSoapHandlerInterface
+{
+public:
+
+	/**
+	* wait for hti message
+	* Suspend thread until HtiMessage for the loaded plug-in is received
+	* Return true if hti message is received or false if timeout
+	**/ 
+	virtual bool WaitForHtiMessage( DWORD timeout ) = 0;
+	virtual bool WaitForHtiMessage( ) = 0;
+
+	/**
+	* Returns received hti message
+	**/
+	//virtual HtiMessage* GetReceivedHtiMessage() = 0;
+	virtual int ReceivedHtiMessageBodySize() = 0;
+	virtual void* ReceivedHtiMessageBody() = 0;
+
+	/**
+	* Send HtiMessage to symbian side
+	**/
+	virtual void SendHtiMessage( DWORD serviceId, void* body, DWORD len ) = 0;
+	virtual void SendHtiMessage( DWORD serviceId, void* body, DWORD len, BYTE priority ) = 0;
+
+	//error message
+	virtual bool IsReceivedHtiError()=0;
+	virtual int HtiErrorCode()=0;
+	virtual int HtiServiceErrorCode()=0;
+	virtual char* HtiServiceErrorDerscription()=0;
+	virtual void SendSoapFaultFromReceivedHtiError()=0;
+};
+
+#endif //__HTI__SOAP_HANDLER_INTERFACE_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway.sln	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,159 @@
+Microsoft Visual Studio Solution File, Format Version 9.00
+# Visual Studio 2005
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiGateway", "HtiGateway\HtiGateway.vcproj", "{132BFDAE-50D6-41F6-81D0-BAD2298470BC}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiCommon", "HtiCommon\HtiCommon.vcproj", "{B49672B8-5D71-4254-AAA2-397C13433450}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "stdsoap2", "stdsoap\stdsoap.vcproj", "{F194912E-201A-4C25-9F86-87076D8985C0}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiApplication", "ServicePlugins\HtiApplication\HtiApplication.vcproj", "{B474C5F8-3653-4D69-A0A2-B85B9F31DCAA}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiAudio", "ServicePlugins\HtiAudio\HtiAudio.vcproj", "{0F3127D8-45F8-4E0D-8A81-7B3545C245D6}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiEcho", "ServicePlugins\HtiEcho\HtiEcho.vcproj", "{A7B882D2-75CF-4720-9C80-86021A6C9714}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiFtp", "ServicePlugins\HtiFtp\HtiFtp.vcproj", "{5BBEEEA4-34D8-4F56-AFEA-8EC04151245F}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiKeyEvent", "ServicePlugins\HtiKeyEvent\HtiKeyEvent.vcproj", "{17A20053-2D4E-448A-9B2F-FE8E5A81FF24}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiScreenshot", "ServicePlugins\HtiScreenshot\HtiScreenshot.vcproj", "{13091F20-7FB9-4A32-8D35-596317F29465}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiStif", "ServicePlugins\HtiStif\HtiStif.vcproj", "{3343A534-2AB9-4543-8396-7BC94B96E8F4}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{F8039331-BC43-4091-8C3C-BE19B4FF1674} = {F8039331-BC43-4091-8C3C-BE19B4FF1674}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiStifSender", "ServicePlugins\HtiStif\HtiStifSender.vcproj", "{F8039331-BC43-4091-8C3C-BE19B4FF1674}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiSysInfo", "ServicePlugins\HtiSysInfo\HtiSysInfo.vcproj", "{0BD9D472-8DA9-4025-9FF7-A7DE5FD2B652}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiSystem", "ServicePlugins\HtiSystem\HtiSystem.vcproj", "{B776DCEA-BDAC-4FCF-BB72-D05DCDA09316}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiMessages", "ServicePlugins\HtiMessages\HtiMessages.vcproj", "{EF5190F8-0DF0-4514-9212-A22665EBA64D}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HtiPIM", "ServicePlugins\HtiPIM\HtiPIM.vcproj", "{3BEB953A-E3DA-440A-8E1C-C5AE8D376E85}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F194912E-201A-4C25-9F86-87076D8985C0} = {F194912E-201A-4C25-9F86-87076D8985C0}
+		{B49672B8-5D71-4254-AAA2-397C13433450} = {B49672B8-5D71-4254-AAA2-397C13433450}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Release|Win32 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{132BFDAE-50D6-41F6-81D0-BAD2298470BC}.Debug|Win32.ActiveCfg = Debug|Win32
+		{132BFDAE-50D6-41F6-81D0-BAD2298470BC}.Debug|Win32.Build.0 = Debug|Win32
+		{132BFDAE-50D6-41F6-81D0-BAD2298470BC}.Release|Win32.ActiveCfg = Release|Win32
+		{132BFDAE-50D6-41F6-81D0-BAD2298470BC}.Release|Win32.Build.0 = Release|Win32
+		{B49672B8-5D71-4254-AAA2-397C13433450}.Debug|Win32.ActiveCfg = Debug|Win32
+		{B49672B8-5D71-4254-AAA2-397C13433450}.Debug|Win32.Build.0 = Debug|Win32
+		{B49672B8-5D71-4254-AAA2-397C13433450}.Release|Win32.ActiveCfg = Release|Win32
+		{B49672B8-5D71-4254-AAA2-397C13433450}.Release|Win32.Build.0 = Release|Win32
+		{F194912E-201A-4C25-9F86-87076D8985C0}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F194912E-201A-4C25-9F86-87076D8985C0}.Debug|Win32.Build.0 = Debug|Win32
+		{F194912E-201A-4C25-9F86-87076D8985C0}.Release|Win32.ActiveCfg = Release|Win32
+		{F194912E-201A-4C25-9F86-87076D8985C0}.Release|Win32.Build.0 = Release|Win32
+		{B474C5F8-3653-4D69-A0A2-B85B9F31DCAA}.Debug|Win32.ActiveCfg = Debug|Win32
+		{B474C5F8-3653-4D69-A0A2-B85B9F31DCAA}.Debug|Win32.Build.0 = Debug|Win32
+		{B474C5F8-3653-4D69-A0A2-B85B9F31DCAA}.Release|Win32.ActiveCfg = Release|Win32
+		{B474C5F8-3653-4D69-A0A2-B85B9F31DCAA}.Release|Win32.Build.0 = Release|Win32
+		{0F3127D8-45F8-4E0D-8A81-7B3545C245D6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{0F3127D8-45F8-4E0D-8A81-7B3545C245D6}.Debug|Win32.Build.0 = Debug|Win32
+		{0F3127D8-45F8-4E0D-8A81-7B3545C245D6}.Release|Win32.ActiveCfg = Release|Win32
+		{0F3127D8-45F8-4E0D-8A81-7B3545C245D6}.Release|Win32.Build.0 = Release|Win32
+		{A7B882D2-75CF-4720-9C80-86021A6C9714}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7B882D2-75CF-4720-9C80-86021A6C9714}.Debug|Win32.Build.0 = Debug|Win32
+		{A7B882D2-75CF-4720-9C80-86021A6C9714}.Release|Win32.ActiveCfg = Release|Win32
+		{A7B882D2-75CF-4720-9C80-86021A6C9714}.Release|Win32.Build.0 = Release|Win32
+		{5BBEEEA4-34D8-4F56-AFEA-8EC04151245F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5BBEEEA4-34D8-4F56-AFEA-8EC04151245F}.Debug|Win32.Build.0 = Debug|Win32
+		{5BBEEEA4-34D8-4F56-AFEA-8EC04151245F}.Release|Win32.ActiveCfg = Release|Win32
+		{5BBEEEA4-34D8-4F56-AFEA-8EC04151245F}.Release|Win32.Build.0 = Release|Win32
+		{17A20053-2D4E-448A-9B2F-FE8E5A81FF24}.Debug|Win32.ActiveCfg = Debug|Win32
+		{17A20053-2D4E-448A-9B2F-FE8E5A81FF24}.Debug|Win32.Build.0 = Debug|Win32
+		{17A20053-2D4E-448A-9B2F-FE8E5A81FF24}.Release|Win32.ActiveCfg = Release|Win32
+		{17A20053-2D4E-448A-9B2F-FE8E5A81FF24}.Release|Win32.Build.0 = Release|Win32
+		{13091F20-7FB9-4A32-8D35-596317F29465}.Debug|Win32.ActiveCfg = Debug|Win32
+		{13091F20-7FB9-4A32-8D35-596317F29465}.Debug|Win32.Build.0 = Debug|Win32
+		{13091F20-7FB9-4A32-8D35-596317F29465}.Release|Win32.ActiveCfg = Release|Win32
+		{13091F20-7FB9-4A32-8D35-596317F29465}.Release|Win32.Build.0 = Release|Win32
+		{3343A534-2AB9-4543-8396-7BC94B96E8F4}.Debug|Win32.ActiveCfg = Debug|Win32
+		{3343A534-2AB9-4543-8396-7BC94B96E8F4}.Debug|Win32.Build.0 = Debug|Win32
+		{3343A534-2AB9-4543-8396-7BC94B96E8F4}.Release|Win32.ActiveCfg = Release|Win32
+		{3343A534-2AB9-4543-8396-7BC94B96E8F4}.Release|Win32.Build.0 = Release|Win32
+		{F8039331-BC43-4091-8C3C-BE19B4FF1674}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8039331-BC43-4091-8C3C-BE19B4FF1674}.Debug|Win32.Build.0 = Debug|Win32
+		{F8039331-BC43-4091-8C3C-BE19B4FF1674}.Release|Win32.ActiveCfg = Release|Win32
+		{F8039331-BC43-4091-8C3C-BE19B4FF1674}.Release|Win32.Build.0 = Release|Win32
+		{0BD9D472-8DA9-4025-9FF7-A7DE5FD2B652}.Debug|Win32.ActiveCfg = Debug|Win32
+		{0BD9D472-8DA9-4025-9FF7-A7DE5FD2B652}.Debug|Win32.Build.0 = Debug|Win32
+		{0BD9D472-8DA9-4025-9FF7-A7DE5FD2B652}.Release|Win32.ActiveCfg = Release|Win32
+		{0BD9D472-8DA9-4025-9FF7-A7DE5FD2B652}.Release|Win32.Build.0 = Release|Win32
+		{B776DCEA-BDAC-4FCF-BB72-D05DCDA09316}.Debug|Win32.ActiveCfg = Debug|Win32
+		{B776DCEA-BDAC-4FCF-BB72-D05DCDA09316}.Debug|Win32.Build.0 = Debug|Win32
+		{B776DCEA-BDAC-4FCF-BB72-D05DCDA09316}.Release|Win32.ActiveCfg = Release|Win32
+		{B776DCEA-BDAC-4FCF-BB72-D05DCDA09316}.Release|Win32.Build.0 = Release|Win32
+		{EF5190F8-0DF0-4514-9212-A22665EBA64D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{EF5190F8-0DF0-4514-9212-A22665EBA64D}.Debug|Win32.Build.0 = Debug|Win32
+		{EF5190F8-0DF0-4514-9212-A22665EBA64D}.Release|Win32.ActiveCfg = Release|Win32
+		{EF5190F8-0DF0-4514-9212-A22665EBA64D}.Release|Win32.Build.0 = Release|Win32
+		{3BEB953A-E3DA-440A-8E1C-C5AE8D376E85}.Debug|Win32.ActiveCfg = Debug|Win32
+		{3BEB953A-E3DA-440A-8E1C-C5AE8D376E85}.Debug|Win32.Build.0 = Debug|Win32
+		{3BEB953A-E3DA-440A-8E1C-C5AE8D376E85}.Release|Win32.ActiveCfg = Release|Win32
+		{3BEB953A-E3DA-440A-8E1C-C5AE8D376E85}.Release|Win32.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/HtiGateway.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,455 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiGateway"
+	ProjectGUID="{132BFDAE-50D6-41F6-81D0-BAD2298470BC}"
+	RootNamespace="HtiGateway"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\Release"
+			IntermediateDirectory="Release"
+			ConfigurationType="1"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			UseOfMFC="0"
+			ATLMinimizesCRunTimeLibraryUsage="false"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TypeLibraryName=".\Release/DataGateway.tlb"
+				HeaderFileName=""
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="1"
+				AdditionalIncludeDirectories=".\inc;&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_CONSOLE;_WIN32_DCOM"
+				StringPooling="true"
+				RuntimeLibrary="2"
+				EnableFunctionLevelLinking="false"
+				RuntimeTypeInfo="true"
+				UsePrecompiledHeader="0"
+				PrecompiledHeaderFile=".\Release/DataGateway.pch"
+				AssemblerListingLocation=".\Release/"
+				ObjectFile=".\Release/"
+				ProgramDataBaseFileName=".\Release/"
+				WarningLevel="3"
+				SuppressStartupBanner="true"
+				CompileAs="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG"
+				Culture="1035"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="odbc32.lib odbccp32.lib stdsoap2.lib HtiCommon.lib ws2_32.lib"
+				LinkIncremental="1"
+				SuppressStartupBanner="true"
+				AdditionalLibraryDirectories="&quot;$(SolutionDir)/Libs&quot;"
+				ProgramDatabaseFile=".\Release/DataGateway.pdb"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy &quot;$(ProjectDir)&quot;ini\HtiGateway.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(ProjectDir)&quot;ini\serialplugin.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(ProjectDir)&quot;ini\ipcommplugin.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(SolutionDir)&quot;\Libs\stdsoap2.dll &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(SolutionDir)&quot;\Libs\HtiCommon.dll &quot;$(TargetDir)&quot;&#x0D;&#x0A;"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\Debug"
+			IntermediateDirectory="Debug"
+			ConfigurationType="1"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			UseOfMFC="0"
+			ATLMinimizesCRunTimeLibraryUsage="false"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TypeLibraryName=".\Debug/DataGateway.tlb"
+				HeaderFileName=""
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories=".\inc;&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_WIN32_DCOM"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				RuntimeTypeInfo="true"
+				UsePrecompiledHeader="0"
+				PrecompiledHeaderFile=".\Debug/DataGateway.pch"
+				AssemblerListingLocation=".\Debug/"
+				ObjectFile=".\Debug/"
+				ProgramDataBaseFileName=".\Debug/"
+				WarningLevel="3"
+				SuppressStartupBanner="true"
+				DebugInformationFormat="4"
+				CallingConvention="0"
+				CompileAs="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="_DEBUG"
+				Culture="1035"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="odbc32.lib odbccp32.lib stdsoap2D.lib HtiCommonD.lib ws2_32.lib"
+				LinkIncremental="1"
+				SuppressStartupBanner="true"
+				AdditionalLibraryDirectories="&quot;$(SolutionDir)/Libs&quot;"
+				GenerateDebugInformation="true"
+				ProgramDatabaseFile=".\Debug/DataGateway.pdb"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy &quot;$(ProjectDir)&quot;ini\HtiGateway.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(ProjectDir)&quot;ini\serialplugin.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(ProjectDir)&quot;ini\ipcommplugin.ini &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(SolutionDir)&quot;\Libs\stdsoap2D.dll &quot;$(TargetDir)&quot;&#x0D;&#x0A;copy &quot;$(SolutionDir)&quot;\Libs\HtiCommonD.dll &quot;$(TargetDir)&quot;&#x0D;&#x0A;"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+			>
+			<File
+				RelativePath="src\common.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\src\datagateway.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\src\HtiDispatcher.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\src\HtiMessage.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\src\IPComm.cpp"
+				>
+			</File>
+			<File
+				RelativePath="src\main.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath="src\plugin.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\src\safequeue.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\src\SerialComm.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\src\SOAPHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\src\Socket.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\src\stdafx.cpp"
+				>
+			</File>
+			<File
+				RelativePath="src\sync.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath="src\util.cpp"
+				>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="2"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+						Optimization="0"
+						AdditionalIncludeDirectories=""
+						PreprocessorDefinitions=""
+						BasicRuntimeChecks="3"
+					/>
+				</FileConfiguration>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="inc\common.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\crc16.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\datagateway.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\DllModule.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\error.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\HtiDispatcher.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\HtiMessage.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\HtiPluginDll.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\IPCommPlugin.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\plugin.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\safequeue.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\SerialCommPlugin.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\SOAPHandler.h"
+				>
+			</File>
+			<File
+				RelativePath=".\inc\stdafx.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\sync.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\thread.h"
+				>
+			</File>
+			<File
+				RelativePath="inc\util.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/DllModule.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+
+#ifndef	_DST_DLL_MODULE_
+#define _DST_DLL_MODULE_
+
+class CDLLModule
+{
+public:
+	CDLLModule() : m_hDLL(NULL)
+	{
+	}
+	virtual ~CDLLModule()	//destructor, free the library
+	{
+		if (m_hDLL)
+			::FreeLibrary(m_hDLL);
+	}
+	//////////////////////////////////////////////////////////////////
+	// See if dll been loaded, returning true dose not mean that all
+	// functions of the dll is valid.
+	bool	IsLoaded(void) 
+	{
+		return m_hDLL != NULL;
+	}
+
+	/////////////////////////////////////////////////////////
+	//	pure virtual, must implemented in derived class
+	//	used macros to generate the implementation
+	virtual bool	Init(LPCTSTR szDll)=0;
+
+protected:
+	HMODULE m_hDLL;
+};
+
+//////////////////////////////////////////////////////////////////////
+// macros to implement the Init function
+#define DECLARE_DLL_FUNCTION(ret, cc, func, params) \
+	ret	(cc* func)params;
+
+#define BEGIN_DLL_INIT() \
+	bool Init(LPCTSTR szDll) \
+	{ \
+		if (m_hDLL) \
+			::FreeLibrary(m_hDLL); \
+		m_hDLL = ::LoadLibrary(szDll); \
+		bool	bOk = true;
+
+#define INIT_DLL_FUNCTION(ret, cc, func, params, origin) \
+		if (m_hDLL) \
+		{ \
+			func = (ret (cc* )params)GetProcAddress(m_hDLL, origin); \
+		} \
+		else \
+			func = NULL; \
+		if (!func) \
+			bOk = false;
+
+#define END_DLL_INIT() \
+		return bOk; \
+	} 
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/HtiDispatcher.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,84 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of HtiDispatcher class.
+*/
+
+#ifndef __HTI_DISPATCHER_H__
+#define __HTI_DISPATCHER_H__
+
+#include <windows.h>
+#include <map>
+#include <string>
+
+#include "safequeue.h"
+#include "thread.h"
+
+//forward declarations
+struct soap;
+class SoapHandler;
+class HtiMessage;
+class Data;
+
+typedef map<string, SoapHandler*> htiSoapActionHashMap;
+typedef map<int, SoapHandler*> htiUIDHashMap;
+
+using namespace std;
+//**********************************************************************************
+// Class HtiDispatcher
+//
+// This class 
+// -forwards Soap requests and Hti messages to correct SOAPHandlers
+// -Is used to initiate SOAPHandlers by reading them from dll's and start them 
+//**********************************************************************************
+class HtiDispatcher : public Thread<HtiDispatcher>
+{
+public:
+	HtiDispatcher(SafeQueue<Data*>* qIn, SafeQueue<Data*>* qOut);
+	~HtiDispatcher();
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+	bool DispatchSoapServe(struct soap* soapEnv);
+	//pass m_IncomingHtiMessage to available handlers
+	void DispatchToSoapHandlers();
+
+	void SendHtiMessage(HtiMessage* msg);
+
+private:
+	/**
+	* read dll plugins and load handlers
+	*/
+	void InitHandlers();
+	void StartHandlers();
+	//void ProcessIncomingDataMessage();
+
+private:
+	//incoming queue from PC side, outgoing to CommChannelPlugin side
+	SafeQueue<Data*>* m_QueueIn;
+	//outgoing queue to PC side, incoming from CommChannelPlugin side
+	SafeQueue<Data*>* m_QueueOut;
+
+	//handlers hash map divided by soap action, it owns handlers
+	htiSoapActionHashMap m_SoapHandlers;
+	//the same as above but of service UID; doesn't own handlers!!!
+	htiUIDHashMap m_HanlersUidMap; 
+
+	HtiMessage* m_IncomingHtiMessage;
+
+	bool m_Running;
+};
+
+#endif // __HTI_DISPATCHER_H__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/HtiMessage.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,132 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of HtiMessage class.
+*/
+#ifndef __HTI_MSG__
+#define __HTI_MSG__
+
+#include <windows.h>
+
+static const DWORD HTI_SYSTEM_SERVICE_UID = 0x1020DEB6;
+
+const int KMsgServiceNameOffset = 0;
+const int KHtiMsgServiceUidLen = 4;
+const int KMsgBodySizeLen = 4;
+const int KMsgBodySizeOffset = KMsgServiceNameOffset + KHtiMsgServiceUidLen;
+const int KMsgVersionOffset = KMsgBodySizeOffset+KMsgBodySizeLen;
+const int KMsgPriorityOffset = KMsgVersionOffset+1;
+const int KMsgWrapFlagOffset = KMsgPriorityOffset+1;
+const int KMsgExtSizeOffset = KMsgWrapFlagOffset+1;
+const int KMsgCrcOffset = KMsgExtSizeOffset+1; //two bytes field
+const int KMsgExtOffset = KMsgCrcOffset+2;
+const int KMsgHeaderMinSize = KMsgExtOffset;
+
+const BYTE KDefaultVersion = 1;
+
+//error message
+const int HtiErrCodeOffset = 1;
+const int HtiServiceErrCodeOffset = HtiErrCodeOffset + 1;
+const int HtiErrServiceUidOffset = HtiServiceErrCodeOffset + 4;
+const int HtiErrDescrOffset = HtiErrServiceUidOffset + 4;
+
+class HtiMessage
+{
+public:
+	/**
+	* Creates HTIMessage using given parameters and message body
+	*/
+	HtiMessage(DWORD serviceId, void* body, DWORD len, BYTE priority=0);
+	
+	/**
+	* Creates HTIMessage parsing ready HTI message (with header)
+	* message may contain only message beginning but should include valid
+	* HTI header (see CheckValidHtiHeader())
+	* The rest of message can be added using AddToBody()
+	*/
+    HtiMessage(void* message, DWORD len);
+
+	/**
+	* Destructor
+	*/
+	~HtiMessage();
+
+	/**
+	* Add body parts if HTIMessage was constructed with incomplete data
+	* Returns number of added bytes.
+	*/
+	DWORD AddToBody(void* data, DWORD len);
+
+	inline bool IsMessageComplete();
+	inline int Reminder();
+
+	/**
+	* Returns whole HTI message including header
+	*/
+	void* HtiData();
+	
+	/**
+	*
+	*/
+	DWORD HtiDataSize();
+
+	DWORD GetBodySize();
+	DWORD GetExtSize();
+	void* GetBody();
+	DWORD GetServiceUID();
+
+	/**
+	* Attemt to read HTI header in provided data.
+	* Pointer should reference to data at least MinHeaderSize() size.
+	*/
+	static bool CheckValidHtiHeader(void* header);
+
+	/**
+	* 
+	*/
+	static DWORD ExtractMsgSizeFromHeader(void* header);
+
+	/**
+	* Returns minimal HTI message header
+	*/
+	static int MinHeaderSize();
+
+	//buit-in support for default error messages
+	static HtiMessage* CreateErrorMessage(int errorCode, const char* errDescr);
+
+	bool IsErrorMessage();
+	int HtiErrorCode();
+	int ServiceErrorCode();
+	char* ErrorDescription();
+	int ErrorServiceUid();
+
+protected:
+	int GetBodyStart();
+
+	DWORD m_Size; //size of whole message (inc. header)
+	BYTE* m_Message; //whole message (inc. header)
+
+	/**
+	* Number of bytes left to copy to m_Message
+	* Used when constructing message from data packages
+	*/
+	DWORD m_MessageReminderSize;
+	//temp string for err descr with 0-ending
+	char* m_ErrDescr;
+};
+
+inline bool HtiMessage::IsMessageComplete(){return m_MessageReminderSize==0;}
+inline int HtiMessage::Reminder(){return m_MessageReminderSize;}
+
+#endif //
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/HtiPluginDll.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of HtiPluginDll class.
+*/
+#ifndef	_HTI_PLUGIN_DLL_
+#define _HTI_PLUGIN_DLL_
+
+#include "DllModule.h"
+
+//forward
+struct soap; 
+struct Namespace;
+class HtiSoapHandlerInterface;
+
+class HtiPluginDll : public CDLLModule
+{
+public:
+    DECLARE_DLL_FUNCTION(int, __cdecl,
+                          serviceUID, (void))
+    DECLARE_DLL_FUNCTION(char*, __cdecl,
+                          soapActionName, (void))
+    DECLARE_DLL_FUNCTION(Namespace*, __cdecl,
+                          serviceNamespaces, (void))
+    DECLARE_DLL_FUNCTION(int, __cdecl,
+                          soap_serve_request, (soap *))
+    DECLARE_DLL_FUNCTION(int, __cdecl,
+                          hti_serve, (HtiSoapHandlerInterface*))
+
+
+    BEGIN_DLL_INIT()
+
+		INIT_DLL_FUNCTION(int, __cdecl,
+			 serviceUID, (void), "serviceUID")
+		INIT_DLL_FUNCTION(char*, __cdecl,
+			 soapActionName, (void), "soapActionName")
+		INIT_DLL_FUNCTION(Namespace*, __cdecl,
+			 serviceNamespaces, (void), "serviceNamespaces")
+        INIT_DLL_FUNCTION(int, __cdecl,
+			 soap_serve_request, (soap *), "soap_serve_request")
+        INIT_DLL_FUNCTION(int, __cdecl,
+			 hti_serve, (HtiSoapHandlerInterface *), "hti_serve")
+
+	END_DLL_INIT()
+};
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/IPCommPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,231 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of IPCommPlugin,
+*	IPCommReaderThread, IPCommWriterThread and IPCommMonitorThread classes.
+*/
+
+#ifndef IPCOMMPLUGIN_H
+#define IPCOMMPLUGIN_H
+
+//#pragma warning ( disable : 4786 )
+#include <iostream>
+#include <process.h>
+#include <string>
+#include <map>
+#include <comdef.h>
+
+#include "common.h"
+#include "plugin.h"
+#include "safequeue.h"
+#include "thread.h"
+#include "datagateway.h" // for g_DataGatewayDefaultTcpIpBufferSize
+
+// forward declarations
+class Socket;
+
+using namespace std;
+
+#define IP_INI_FILE_NAME             "ipcommplugin.ini"
+
+#define IP_INI_LOCAL_PORT_PARAM             "LOCAL_PORT"
+#define IP_INI_REMOTE_HOST_PARAM            "REMOTE_HOST"
+#define IP_INI_REMOTE_PORT_PARAM            "REMOTE_PORT"
+#define IP_INI_RECV_BUFFER_SIZE_PARAM       "RECV_BUFFER_SIZE"
+
+#define PARAM_SWITCH_LOCAL_PORT_PARAM       "-LOCAL_PORT"
+#define PARAM_SWITCH_REMOTE_HOST_PARAM      "-REMOTE_HOST"
+#define PARAM_SWITCH_REMOTE_PORT_PARAM      "-REMOTE_PORT"
+#define PARAM_SWITCH_RECV_BUFFER_SIZE_PARAM "-RECV_BUFFER_SIZE"
+
+const DWORD g_IPCommDefaultTimeout    = 40000; //ms
+const DWORD g_IPPluginTimeout         = 10000; //not used
+
+// Maximum time to wait
+extern long g_MaximumShutdownWaitTime;
+
+//**********************************************************************************
+// Class IPCommReaderThread
+//
+// This thread is used to read bytes from TCP/IP socket, encapsulate the bytes to Data objects 
+// and push them to incoming queue 
+//**********************************************************************************
+
+class IPCommReaderThread : public Thread<IPCommReaderThread>
+{
+public:
+	IPCommReaderThread(SafeQueue<Data*>* q, long bufsize);
+	/*
+	 * Main execution loop which reads bytes from socket, encapsulates the bytes to Data object and pushes them to incoming queue
+	 */		
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	friend class IPCommMonitorThread;
+	//incoming queue
+	SafeQueue<Data*>* m_Queue;
+	//Socket connected to mobile device
+	Socket* m_Socket;
+	bool m_Running;
+	//size of buffer used when reading data from socket
+	long m_TcpIpBufferSize;
+};
+
+//**********************************************************************************
+// Class IPCommWriterThread
+//
+// This thread is used to write data from outgoing queue to TCP/IP port
+//**********************************************************************************
+
+class IPCommWriterThread : public Thread<IPCommWriterThread>
+{
+public:
+	IPCommWriterThread(SafeQueue<Data*>* q);
+	/*
+	 * Main execution loop which gets Data from outgoing queue and sends it to socket
+	 */	
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	friend class IPCommMonitorThread;
+	//outgoing queue
+	SafeQueue<Data*>* m_Queue;
+	//Socket connected to mobile device	
+	Socket* m_Socket;
+	bool m_Running;
+};
+
+//**********************************************************************************
+// Class IPCommMonitorThread
+//
+// This thread creates and starts reader and writer threads
+// The thread also monitors if reader and writer threads are running and restarts them in case either isn't running
+//**********************************************************************************
+
+class IPCommMonitorThread : public Thread<IPCommMonitorThread>
+{
+public:
+	IPCommMonitorThread(SafeQueue<Data*>* TxQueue,
+		                SafeQueue<Data*>* RxQueue,
+						int LocalPort,
+						string& RemoteHost,
+						int RemotePort,
+						long RecvBufferSize);
+	~IPCommMonitorThread();
+	/*
+	 * Main execution loop of thread
+	 * -Creates reader and writer threads and starts them
+	 * -Monitors if either reader or writer thread aren't running and restarts them if not
+	 */	
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	/*
+	 * This method has two functionalities
+	 * -It waits for incoming connections if local port is defined
+	 * -It tries to connect to remote host if local host is not defined
+	 */
+	void Connect(Socket*& s);
+
+private:
+	bool                m_Running;
+	//outgoing queue
+	SafeQueue<Data*>*   m_TxQueue;
+	//incoming queue
+	SafeQueue<Data*>*   m_RxQueue;
+	//used to read data from TCP/IP port and push them to incoming queue
+	IPCommReaderThread* m_ReaderThread;
+	//used to write data from outgoing queue to TCP/IP port	
+	IPCommWriterThread* m_WriterThread;
+	//port that thread should listen to
+	int					m_LocalPort;
+	//hostname that thread should connect to	
+	string&				m_RemoteHost;
+	//Port that thread should connect to
+	int					m_RemotePort;
+	long				m_RecvBufferSize;
+};
+
+//**********************************************************************************
+// Class IPCommPlugin
+//
+// This class implements a CommChannelPlugin used in TCP/IP communication with device
+//**********************************************************************************
+
+class IPCommPlugin : public CommChannelPlugin
+{
+public:
+	/*
+	 * This method initializes IPCommPlugin and Starts IPCommMonitorThread
+	 */
+	DWORD Init();
+	/*
+	 * This method is used to push given data to outgoing queue and then 
+	 * wait for data to become available and read all data into single Data object 
+	 */	
+	DWORD SendReceive( Data* data_in, Data** data_out, long timeout = g_IPPluginTimeout );
+	/*
+	 * This method pushes the given Data object(of type Data::EData) to outgoing queue
+	 */		
+	DWORD Send( Data* data_in, long timeout = g_IPPluginTimeout );
+	/*
+	 * This method is used to read all data in incoming queue to single Data object and store the result
+	 * to the data object given parameter
+	 */		
+	DWORD Receive( Data** data_out, long timeout = g_IPPluginTimeout );
+	/*
+	 * This method is used to wait for data to become available in incoming queue 
+	 * and then read all data into single Data object which is given as parameter
+	 */		
+	DWORD ReceiveWait( Data** data_out, long timeout = g_IPPluginTimeout );
+	/*
+	 * This method checks if data is available on incoming queue
+	 */		
+	bool IsDataAvailable();
+	DWORD Open();
+	DWORD Close();
+	IPCommPlugin( const CommChannelPluginObserver* observer = NULL );
+	~IPCommPlugin();
+
+private:
+	/*
+	 * This method initializes class member variables from values in map
+	 */	
+	void CheckProperties( map<string, string>& props );
+
+private:
+	//outgoing queue
+	SafeQueue<Data*>	m_TxQueue;
+	//incoming queue
+	SafeQueue<Data*>	m_RxQueue;
+	//thread which starts and monitors reader and writer threads
+	IPCommMonitorThread* m_MonitorThread;
+	//port that IPCommPlugin should listen to
+	int					m_PropertyLocalPort;
+	//hostname that IPCommPlugin should connect to
+	string				m_PropertyRemoteHost;
+	//port that IPCommPlugin should connect to
+	int					m_PropertyRemotePort;
+	long                m_PropertyRecvBufferSize;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/SOAPHandler.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,193 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains header of SOAPHandler class
+*/
+
+#ifndef __SOAP__HANDLER_H_
+#define __SOAP__HANDLER_H_
+
+#include "thread.h"
+#include "HtiSoapHandlerInterface.h"
+#include "HtiPluginDll.h"
+
+#include <string>
+
+using namespace std;
+
+#define LOOP_WAIT_INTERVAL INFINITE //in ms
+#define LOOP_CHECK_INTERVAL 100 //in ms
+
+//forward decl.
+class HtiDispatcher;
+class HtiMessage;
+
+//**********************************************************************************
+// Class SOAPHandler
+//
+// This class is used to handle SOAP requests, send HtiMessages 
+// and handle HTI responses by using loaded HtiPluginDll
+//**********************************************************************************
+class SoapHandler: public Thread<SoapHandler>, public HtiSoapHandlerInterface
+{
+public:
+	SoapHandler(const string& pluginName);
+	virtual ~SoapHandler();
+
+	inline void SetDispatcher( HtiDispatcher* dispatcher);
+
+	/**
+	 * This method is used to init HtiPluginDll
+	 */
+	bool LoadPlugin();
+
+	inline char* soapAction(){return m_HtiPlugin->soapActionName();};
+	inline int serviceUID(){return m_HtiPlugin->serviceUID();};
+
+	/**
+	* Just a wrapper around soap_serve() created by gSOAP
+	* called by DataGatewaySOAPServerThread for a new SOAP request
+	* return true if request can be processed
+	*/
+	bool ServeSoap(struct soap* soapEnv);
+
+	/**
+	* Actual SOAP request processing in the thread
+	* if it was accepted in ServeSoap()
+	* The request is processed using HtiPluginDll
+	*/
+	void DoServeSoap();
+
+	/**
+	 * This method tells whether or not this handler is currently busy processing request
+	 */
+	bool IsBusyForSoapRequest();
+
+	/**
+	 * This method tells whether or not this handler is currently busy processing hti message
+	 */
+	bool IsBusyForHtiMessage();
+	
+	/*
+	 * This method is used to check if SoapHandler is currently waiting for Hti Message
+	 */
+	bool IsWaitsForHtiMessage();
+
+	/**
+	* Notification function called when handler receive
+	* new HTI message from Symbian side
+	*/
+	void ProcessHtiResponse();
+	
+	/**
+	 * This loop waits until either a SOAP request or HTI response event has arrived
+	 * When one of them arrives, it is handled and the loop starts again to wait
+	 * for a new request or response
+	 */
+	void Run();
+	void Stop();
+
+	/**
+	* wait for hti message
+	* Suspend thread until HtiMessage for the loaded plug-in is received
+	* Return true if hti message is received or false if timeout
+	*/ 
+	bool WaitForHtiMessage( DWORD timeout );
+	inline bool WaitForHtiMessage( ){return WaitForHtiMessage( INFINITE );};
+
+	int ReceivedHtiMessageBodySize();
+	void* ReceivedHtiMessageBody();
+
+	/*
+	 * HtiPluginDll's call this method
+	 * It creates a HtiMessage of the data given as parameters and sends it using HtiDispatcher
+	 */
+	void SendHtiMessage( DWORD serviceId, void* body, DWORD len );
+	void SendHtiMessage( DWORD serviceId, void* body, DWORD len, BYTE priority );
+
+	//error message
+	bool IsReceivedHtiError();
+	int HtiErrorCode();
+	int HtiServiceErrorCode();
+	char* HtiServiceErrorDerscription();
+	void SendSoapFaultFromReceivedHtiError();
+
+	/**
+	 * This method is called when incoming data has been read from CommChannelPlugin
+	 * The method sets m_hReceiveHtiEvent to signaled state(Run method waits this event object to become signaled)
+	 */
+	bool ReceiveHtiMessage(HtiMessage* message);
+
+private:
+
+	void CleanSoapEnv();
+
+// data members
+protected:
+	string m_PluginName;
+
+	HtiPluginDll* m_HtiPlugin;
+
+	HtiDispatcher* m_HtiDispatcher;
+
+	/**
+	* Message passed to the handler by AcceptHtiMessage()
+	* It is usually processed than 
+	*/
+	HtiMessage* m_ReceiveHtiMsg;
+
+	bool m_Running;
+
+private:
+	/**
+	* used to wait for messages from symbian-side
+	*/
+	HANDLE m_hReceiveHtiEvent;
+
+	/**
+	* used to wait for SOAP request
+	*/
+	HANDLE m_hReceiveSoapEvent;
+
+	/**
+	* Used to allow define either thread is busy
+	*/
+	HANDLE m_hHandlerCanAcceptSoapRequest;
+	HANDLE m_hHandlerCanAcceptHtiMessage;
+
+	/**
+	* Needed to dispatch error messages without tartet service uid
+	**/
+	HANDLE m_hHandlerWaitsHtiMessage;
+
+	/**
+	* Local gSOAP env
+	*/
+	struct soap* m_SoapEnv;
+};
+/*
+inline HtiMessage* SoapHandler::GetReceivedHtiMessage()
+{
+	HtiMessage* r = m_ReceiveHtiMsg;
+	m_ReceiveHtiMsg = NULL;
+	return r;
+}
+*/
+
+inline void SoapHandler::SetDispatcher( HtiDispatcher* dispatcher)
+{
+	m_HtiDispatcher = dispatcher;
+}
+
+#endif //__SOAP__HANDLER_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/SerialCommPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,202 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of SerialComm communication channel plugin objects. 
+*   These classes are SerialComm, SerialCommPlugin and SerialCommIoThread classes.
+*/
+
+#ifndef SERIALCOMMPLUGIN_H
+#define SERIALCOMMPLUGIN_H
+
+#pragma warning ( disable : 4786 )
+#include <iostream>
+#include <process.h>
+#include <string>
+#include <map>
+#include <comdef.h>
+
+#include "common.h"
+#include "plugin.h"
+#include "safequeue.h"
+#include "thread.h"
+
+using namespace std;
+
+#define SERIAL_INI_FILE_NAME             "serialplugin.ini"
+
+#define SERIAL_INI_INIT_PARAM            "INIT_STRING"
+#define PARAM_SWITCH_INIT_PARAM          "-INIT_STRING"
+#define SERIAL_INI_COMPORT_PARAM         "COMPORT"
+#define PARAM_SWITCH_COMPORT_PARAM       "-COMPORT"
+#define SERIAL_INI_COMPORT_TIMEOUT       "TIMEOUT"
+#define PARAM_SWITCH_COMPORT_TIMEOUT     "-TIMEOUT"
+#define SERIAL_INI_USE_HW_FLOW_CONTROL   "HW_FLOWCONTROL"
+#define PARAM_SWITCH_USE_HW_FLOW_CONTROL "-HW_FLOWCONTROL"
+#define SERIAL_INI_SEND_SLEEP_PAUSE      "SEND_PAUSE"
+#define PARAM_SWITCH_SEND_SLEEP_PAUSE    "-SEND_PAUSE"
+#define SERIAL_INI_SEND_SIZE             "SEND_SIZE"
+#define PARAM_SWITCH_SEND_SIZE           "-SEND_SIZE"
+
+#define SERIAL_DEFAULT_INIT_STRING       "115200,n,8,1"
+#define SERIAL_DEFAULT_COMPORT           "COM2"
+
+const DWORD g_SerialCommDefaultTimeout    = 40000; //ms
+const DWORD g_SerialPluginTimeout         = 10000; //not used
+const long  g_SerialCommDefaultSendPause  = 0;
+
+// Maximum time to wait
+extern long g_MaximumShutdownWaitTime;
+
+//**********************************************************************************
+// Class SerialComm
+//
+// This class implements the actual serial communication
+//**********************************************************************************
+
+class SerialComm
+{
+public:
+	SerialComm();
+	~SerialComm();
+	/*
+	 * This method opens a communication device that uses serial communication and
+	 * configures it according initialization parameters
+	 */	
+	WORD Open( const string& commPort, const string& initParameters, long timeout,
+				bool hwFlowControl, long sendPause, long sendMaxSize);
+	DWORD Close();
+	/*
+	 * This method is used to send Data object using serial communication
+	 */		
+	DWORD Send(const Data& data_in);
+	/*
+	 * This method reads all available data from communication media 
+	 * and returns it in the Data object given as parameter
+	 */	
+	DWORD Receive(Data* data_out);
+	/*
+	 * This method returns number of bytes available in incoming queue or
+	 * -1 if communication error has occurred
+	 */	
+	LONG GetRxBytesAvailable();
+private:
+	//handle to communication resource
+	HANDLE m_Com;
+	bool m_Open;
+	long m_SendPause;
+	long m_SendMaxSize;
+};
+
+//**********************************************************************************
+// Class SerialCommIoThread
+//
+// This thread is used to send data from outgoing queue to serial port
+// and read bytes from serial port and push it to incoming queue 
+//**********************************************************************************
+
+class SerialCommIoThread : public Thread<SerialCommIoThread>
+{
+public:
+	SerialCommIoThread(SafeQueue<Data*>* in, SafeQueue<Data*>* out,
+						const string& init, const string& commPort, long timeout,
+						bool hwFlowControl, long sendPause, long sendMaxSize);
+	/*
+	 * Main execution loop which is used to send Data from outgoing queue to serial port
+	 * and read bytes from serial port, encapsulate it to Data objects and push them to incoming queue 
+	 */		
+	void Run();
+	void Stop();
+	void SetTimeout(long timeout);
+	long GetTimeout() const;
+	Event GetOpenedEvent();
+private:
+	//incoming queue
+	SafeQueue<Data*>* m_InQueue;
+	//outgoing queue
+	SafeQueue<Data*>* m_OutQueue;
+	Event m_OpenedEvent;
+	bool m_Running;
+	long m_PropertySerialCommTimeout;
+	const string& m_InitString;
+	const string& m_CommPort;
+	long m_ProperySerialSendPause;
+	bool m_PropertySerialHwFlowControl;
+	long m_PropertySerialMaxSendSize;
+};
+
+//**********************************************************************************
+// Class SerialCommPlugin
+//
+// This class implements a CommChannelPlugin used in serial communication with device
+//**********************************************************************************
+
+class SerialCommPlugin : public CommChannelPlugin
+{
+public:
+	/*
+	 * This method initializes SerialCommPlugin and starts SerialCommPluginIoThread
+	 */
+	DWORD Init();
+	/*
+	 * This method is used to:
+	 * -push given data to outgoing queue
+	 * -wait for data to become available in incoming queue
+	 * -pop the first Data object from queue and store it to the Data object given as parameter
+	 */		
+	DWORD SendReceive(Data* data_in, Data** data_out, long timeout = g_SerialPluginTimeout);
+	/*
+	 * This method pushes the given Data object(of type Data::EData) to outgoing queue
+	 */		
+	DWORD Send(Data* data_in, long timeout = g_SerialPluginTimeout);
+	/*
+	 * This method is used to pop the first data object from incoming queue and store it to data object given as parameter
+	 */		
+	DWORD Receive(Data** data_out, long timeout = g_SerialPluginTimeout);
+	/*
+	 * This method is used to wait for data to become available in incoming queue 
+	 * and then pop the first Data object from the queue and and store it to Data object given as parameter.
+	 */		
+	DWORD ReceiveWait(Data** data_out, long timeout = g_SerialPluginTimeout);
+	/*
+	 * This method checks if data is available on incoming queue
+	 */		
+	bool IsDataAvailable();
+	DWORD Open();
+	/*
+	 * This method stops SerialCommIoThread and waits for it to be in signaled state
+	 */		
+	DWORD Close();
+	SerialCommPlugin(const CommChannelPluginObserver* observer = NULL);
+	~SerialCommPlugin();
+private:
+	void CheckProperties(map<string, string>& props);
+private:
+    //outgoing queue
+	SafeQueue<Data*> m_TxQueue;
+	//incoming queue	
+	SafeQueue<Data*> m_RxQueue;
+	SerialCommIoThread* m_IoThread;
+	//map that properties are read to from ini file
+	map<string, string> m_SerialCommPluginProperties;
+	long m_PropertySerialCommTimeout;
+	string m_PropertySerialCommInitString;
+	string m_PropertySerialCommPort;
+	long m_ProperySerialSendPause;
+	bool m_PropertySerialHwFlowControl;
+	long m_PropertySerialMaxSendSize;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/Socket.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,96 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __SOCKET_H__
+#define __SOCKET_H__
+
+#include <WinSock2.h>
+
+#include <string>
+
+
+typedef std::string String;
+
+
+class Socket {
+public:
+
+  virtual ~Socket();
+  Socket();
+  Socket(const Socket&);
+  Socket& operator=(Socket&);
+
+  String ReceiveLine();
+  String ReceiveBytes();
+  int ReceiveBytes(BYTE *data, int bytes);
+  int Peek(BYTE* data, int bytes );
+
+  void   Close();
+
+  // The parameter of SendLine is not a const reference
+  // because SendLine modifes the String passed.
+  void   SendLine (String);
+
+  // The parameter of SendBytes is a const reference
+  // because SendBytes does not modify the String passed
+  // (in contrast to SendLine).
+  void   SendBytes(const String&);
+  int SendBytes(const BYTE* data, int bytes);
+
+protected:
+  friend class SocketServer;
+  friend class SocketSelect;
+
+  Socket(SOCKET s);
+
+
+
+  SOCKET s_;
+
+  int* refCounter_;
+
+private:
+  static void Start();
+  static void End();
+  static int  nofSockets_;
+};
+
+class SocketClient : public Socket {
+public:
+  SocketClient(const String& host, int port);
+};
+
+
+class SocketServer// : public Socket
+{
+public:
+  SocketServer();
+  void Accept(Socket*& s, int port, int connections, String& remoteHost);
+  void Connect(Socket* s, const char* remoteHost, int remotePort);
+};
+
+// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/wsapiref_2tiq.asp
+class SocketSelect {
+  public:
+    SocketSelect(Socket const * const s1, Socket const * const s2);
+
+    bool Readable(Socket const * const s);
+
+  private:
+    fd_set fds_;
+};
+
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/common.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*     This file contains the headers of the Data and ParameterList classes.
+*/
+
+#ifndef COMMON_H
+#define COMMON_H
+
+#pragma warning ( disable : 4786 )
+
+#include <windows.h>
+
+//**********************************************************************************
+// Class Data
+// 
+// This class provides data encapsulattion for DataGateway
+//**********************************************************************************
+
+class Data
+{
+public:
+	//type of data
+	enum DataType { EEmpty = 0, EControl, EError, EData };
+public:
+	Data(const void* data_in = NULL, DWORD length = 0, DataType type = EEmpty);
+	Data(const void* data_in, DWORD length, DWORD offset, DataType type);
+	Data(const Data& d);
+	virtual ~Data();
+	/*
+	 * returns data in Data object given parameter
+	 */
+	virtual void* GetData(void* data_out = NULL) const;
+	/*
+	 * returns length of data 
+	 */	
+	virtual DWORD GetLength() const;
+	/*
+	 * returns type of data
+	 * can be one of the following: EEmpty, EControl, EError, EData
+	 */	
+	DataType GetType() const;
+	/*
+	 * This method copies up to length bytes from given data object to class member data object
+	 */
+	bool SetData(const void* data_in, DWORD length, DataType type);
+	/*
+	 * This method copies up to length bytes(starting from offset) from given data object to class member data object
+	 */	
+	bool SetData(const void* data_in, DWORD length, DWORD offset, DataType type);
+	Data& operator=(const Data& data);
+	/*
+	 * Used to combine different messages into one.
+	 * This method appends new data at the end of already excisting data.
+	 * If new data isn't same type as excisting data it isn't appended.
+	 * Returns bool value of whether the method has succeeded to append the data or not.
+	 */
+	virtual bool AppendData(Data* aData);
+	/*
+	 * This method is used to free data and set data type to EEmpty
+	 */
+	void FreeData();
+private:
+	//actual data
+	void* m_pData;
+	//length of data
+	DWORD m_dwLength;
+	//type of data
+	DataType m_Type;
+};
+
+const BYTE ControlPhonePowered = 0x01;
+
+const Data CtrlMessagePhonePowered((void*)&ControlPhonePowered, 1, 0, Data::EControl);
+
+const BYTE ErrorSendingData = 0x81;
+
+const Data ErrorMessageSendingData((void*)&ErrorSendingData, 1, 0, Data::EError);
+
+#define CREATE_CONTROL_MESSAGE(str) new Data( (str), strlen(str)+1, Data::EControl)
+
+//**********************************************************************************
+// Class ParameterList
+//
+//**********************************************************************************
+
+#include <map>
+#include <string>
+
+using namespace std;
+
+class ParameterList
+{
+public:
+	void Add(const string& key, const void* value);
+	const void* Get(const string& key);
+	ParameterList();
+	~ParameterList();
+private:
+	map<const string,const void*> m_Map;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/crc16.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_CRC16__
+#define __HTI_CRC16__
+
+WORD CRC16_Lookup[256] = {
+			0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 
+			0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 
+			0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 
+			0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 
+			0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 
+			0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 
+			0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 
+			0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 
+			0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 
+			0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 
+			0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 
+			0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 
+			0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 
+			0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 
+			0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 
+			0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 
+			0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 
+			0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 
+			0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 
+			0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 
+			0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 
+			0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 
+			0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 
+			0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 
+			0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 
+			0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 
+			0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 
+			0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 
+			0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 
+			0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 
+			0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 
+			0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
+		};
+
+static WORD CRC16CCITT(void* data, int length)
+{
+	WORD crc16= 0xFFFF; // the CRC
+	BYTE* dataC = (BYTE*)data;
+
+	for(WORD i= 0; i < length; i++ )
+	{
+		WORD t = (crc16 >> 8) ^ ( (dataC[i]) & 0xFF );
+		crc16 = ((crc16 << 8) & 0xffff) ^ CRC16_Lookup[t];
+	}
+
+	return crc16;
+}
+#endif __HTI_CRC16__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/datagateway.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the headers of DataGatewaySOAPServerThread, DataGatewayClientThread and DataGateway
+*	classes.
+*/
+
+#ifndef DATAGATEWAY_H
+#define DATAGATEWAY_H
+
+#pragma warning ( disable : 4786 )
+
+#include <windows.h>
+#include <process.h>
+
+#include "util.h"
+#include "common.h"
+#include "plugin.h"
+#include "safequeue.h"
+#include "HtiDispatcher.h"
+#include "thread.h"
+
+const int g_DataGatewayDefaultTcpIpPort       = 2000;
+const int g_DataGatewayDefaultTcpIpBufferSize = 8 * 1024;
+
+// Maximum time to wait
+extern long g_MaximumShutdownWaitTime;
+
+extern DWORD g_ErrorCode;
+
+//**********************************************************************************
+// Class DataGatewaySOAPServerThread
+//
+// This thread acts as a SOAP server, it listens to SOAP requests and forwards them
+// to HtiDispatcher which then forwards them to correct SOAPHandlers
+//**********************************************************************************
+
+class DataGatewaySOAPServerThread : public Thread<DataGatewaySOAPServerThread>
+{
+public:
+	DataGatewaySOAPServerThread(HtiDispatcher* htiDispatcher, int port);
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	//SafeQueue<Data*>* m_Queue;
+	HtiDispatcher* m_HtiDispatcher;
+	int m_TcpPort;
+
+	bool m_Running;
+};
+
+//**********************************************************************************
+// Class DataGatewayClientThread
+//
+// This thread serves DataGateway's clients
+// Gets Data objects from incoming queue and forwards them to CommChannelPlugin.
+// The Data objects are actually SOAP requests which were received by DataGatewaySOAPServerThread handled by SOAPHandler and transferred to HtiMessages and eventually Data objects
+// The thread also reads incoming data from CommChannelPlugin and forwards them to outgoing queue which
+// HtiDispatcher then reads and forwards to correct SOAPHandler
+//**********************************************************************************
+
+class DataGatewayClientThread : public Thread<DataGatewayClientThread>
+{
+public:
+	DataGatewayClientThread(int port, long bufsize, const string& commchannel);
+	DataGatewayClientThread(int port, long bufsize, CommChannelPlugin** f);
+	~DataGatewayClientThread();
+	void Run();
+	void Stop();
+
+private:
+	//incoming queue from PC side, outgoing to CommChannelPlugin side
+	SafeQueue<Data*> m_ReaderQueue;
+	//outgoing queue to PC side, incoming from CommChannelPlugin side
+	SafeQueue<Data*> m_WriterQueue;
+
+	DataGatewaySOAPServerThread m_SoapListener;
+	HtiDispatcher m_HtiDispatcher;
+
+	CommChannelPlugin* m_CommChannelPlugin;
+	const string& m_CommChannelPluginName;
+	bool m_Running;
+	bool m_CCLateInit;
+	long m_TcpIpBufferSize;
+};
+
+//**********************************************************************************
+// Class DataGateway
+//
+// Main class/thread of HtiGateway
+//**********************************************************************************
+
+class DataGateway : public Thread<DataGateway>
+{
+public:
+	DataGateway(int port = g_DataGatewayDefaultTcpIpPort,
+		        long bufsize = g_DataGatewayDefaultTcpIpBufferSize,
+				const string& commchannel = "",
+				bool stayalive = false,
+				bool cclateinit = false);
+	void Run();
+	void Stop();
+	bool IsRunning();
+
+private:
+	const string& m_CommChannelPluginName;
+	CommChannelPlugin* m_CommChannelPlugin;
+	Event m_ShutdownEvent;
+	bool m_Running;
+	bool m_StayAlive;
+	bool m_CCLateInit;
+	int m_TcpIpPort;
+	long m_TcpIpBufferSize;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/error.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,103 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains global definitions to errors
+*/
+
+#ifndef __ERROR__
+#define __ERROR__
+
+// GLOBAL DEFINES
+#define ERR_BASE			0x1000
+#define ERR_BASE_UTIL		(ERR_BASE + 0x0100)
+#define ERR_BASE_PHOENIX	(ERR_BASE + 0x0200)
+#define ERR_BASE_BLUETOOTH	(ERR_BASE + 0x0300)
+#define ERR_BASE_MTC		(ERR_BASE + 0x0400)
+#define ERR_BASE_DG	        (ERR_BASE + 0x0500)
+
+#define NO_ERRORS						0
+#define ERR_NO_PARAMS					(ERR_BASE + 1)
+#define ERR_UNKNOWN_COMMAND				(ERR_BASE + 2)
+
+#define ERR_UTIL_NO_PARAM_VALUE			(ERR_BASE_UTIL + 2)
+#define ERR_UTIL_UNKNOWN_PARAM			(ERR_BASE_UTIL + 3)
+#define ERR_UTIL_PROPERTIES_NOT_FOUND	(ERR_BASE_UTIL + 4)
+#define ERR_UTIL_NO_PROPERTY_VALUE		(ERR_BASE_UTIL + 5)
+
+#define ERR_BLUETOOTH_CONNECTION_FAILED			(ERR_BASE_BLUETOOTH + 1)
+#define ERR_BLUETOOTH_DISCONNECTION_FAILED		(ERR_BASE_BLUETOOTH + 2)
+#define ERR_BLUETOOTH_LOCAL_SERVICE_MISSING		(ERR_BASE_BLUETOOTH + 3)
+#define ERR_BLUETOOTH_REMOTE_SERVICE_MISSING	(ERR_BASE_BLUETOOTH + 4)
+#define ERR_BLUETOOTH_DEVICE_ADDRESS_MISSING	(ERR_BASE_BLUETOOTH + 5)
+
+#define ERR_MTC_INVALID_MODE	(ERR_BASE_MTC + 1)
+
+#define ERR_DG_SOCKET					 (ERR_BASE_DG + 1)
+#define ERR_DG_COMMCHANNEL				 (ERR_BASE_DG + 2)
+#define ERR_DG_UNINITIALISED_COMMCHANNEL (ERR_BASE_DG + 3)
+#define ERR_DG_COMMCHANNEL_INIT          (ERR_BASE_DG + 4)
+#define ERR_DG_UNKNOWN_COMMCHANNEL		 (ERR_BASE_DG + 5)
+#define ERR_DG_COMMCHANNEL_OPEN			 (ERR_BASE_DG + 6)
+#define ERR_DG_CONSOLEHANDLER			 (ERR_BASE_DG + 7)
+#define ERR_DG_CONNECTION_OPEN					 (ERR_BASE_DG + 8)
+#define ERR_DG_CONNECTION_INIT					 (ERR_BASE_DG + 9)
+#define ERR_DG_COMM_OPEN		         (ERR_BASE_DG + 10)
+#define ERR_DG_COMM_OPEN_TIMEOUT		 (ERR_BASE_DG + 11)
+#define ERR_DG_COMM_OPEN_QUERY			 (ERR_BASE_DG + 12)
+#define ERR_DG_COMM_DATA_RECV			 (ERR_BASE_DG + 13)
+#define ERR_DG_COMM_DATA_RECV_TIMEOUT   (ERR_BASE_DG + 14)
+#define ERR_DG_COMM_DATA_SEND			 (ERR_BASE_DG + 15)
+#define ERR_DG_COM_INIT					 (ERR_BASE_DG + 16)
+#define ERR_DG_COM_IF_QUERY				 (ERR_BASE_DG + 17)
+
+typedef struct
+{
+	DWORD err_code;
+	char *err_msg;
+} ErrorLookupEntry;
+
+static const ErrorLookupEntry ErrorLookupTable[] =
+	{
+		{ERR_DG_SOCKET,						"ERR_DG_SOCKET"},
+		{ERR_DG_COMMCHANNEL,				"ERR_DG_COMMCHANNEL"},
+		{ERR_DG_UNINITIALISED_COMMCHANNEL,	"ERR_DG_UNINITIALISED_COMMCHANNEL"},
+		{ERR_DG_COMMCHANNEL_INIT,			"ERR_DG_COMMCHANNEL_INIT"},
+		{ERR_DG_UNKNOWN_COMMCHANNEL,		"ERR_DG_UNKNOWN_COMMCHANNEL"},
+		{ERR_DG_COMMCHANNEL_OPEN,			"ERR_DG_COMMCHANNEL_OPEN"},
+		{ERR_DG_CONSOLEHANDLER,				"ERR_DG_CONSOLEHANDLER"},
+		{ERR_DG_CONNECTION_OPEN,		    "ERR_DG_CONNECTION_OPEN"},
+		{ERR_DG_COMM_OPEN_TIMEOUT,			"ERR_DG_COMM_OPEN_TIMEOUT"},
+		{ERR_DG_COMM_OPEN_QUERY,			"ERR_DG_COMM_OPEN_QUERY"},
+		{ERR_DG_COMM_DATA_RECV,				"ERR_DG_COMM_DATA_RECV"},
+		{ERR_DG_COMM_DATA_RECV_TIMEOUT,		"ERR_DG_COMM_DATA_RECV_TIMEOUT"},
+		{ERR_DG_COMM_DATA_SEND,				"ERR_DG_COMM_DATA_SEND"},
+		{ERR_DG_COM_INIT,					"ERR_DG_COM_INIT"},
+		{ERR_DG_COM_IF_QUERY,				"ERR_DG_COM_IF_QUERY"}
+	};
+
+#define ERROR_LOOKUP(x) \
+	for (int i = 0; i < sizeof(ErrorLookupTable); i++)										  \
+	{																					      \
+		if (ErrorLookupTable[i].err_code == x)												  \
+		{																			          \
+			char tmp[256];																	  \
+			sprintf(tmp, "[DataGateway] Error: %s (0x%04X)\n", ErrorLookupTable[i].err_msg,   \
+                                                               ErrorLookupTable[i].err_code); \
+			Util::Error(tmp);																  \
+		}																				      \
+	}
+
+#endif
+
+// End of file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/plugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the headers of Plugin, FrontendPlugin,
+*	CommChannelPlugin and CommChannelPluginObserver classes and implementation
+*	of DummyCommObserver.
+*/
+
+#ifndef PLUGIN_H
+#define PLUGIN_H
+
+#pragma warning ( disable : 4786 )
+
+#include <string>
+#include "common.h"
+
+using namespace std;
+
+//**********************************************************************************
+// Class Plugin
+//
+//**********************************************************************************
+
+class Plugin
+{
+public:
+	enum PluginType { null, dummy, frontend, comm_channel };
+
+public:
+	virtual PluginType GetType() { return null; }
+	virtual DWORD Init();
+	virtual const string& GetName(string *name = NULL);
+
+protected:
+	Plugin();
+
+protected:
+	string m_Name;
+};
+
+//**********************************************************************************
+// Class FrontendPlugin
+//
+//**********************************************************************************
+
+class FrontendPlugin : public Plugin
+{
+public:
+	virtual PluginType GetType() { return frontend; }
+	virtual DWORD Init();
+};
+
+//**********************************************************************************
+// Class CommChannelPluginObserver
+//
+//**********************************************************************************
+
+class CommChannelPluginObserver
+{
+public:
+	virtual void NotifyDataAvailable() = 0;
+	virtual void NotifyCommChannelOpened() = 0;
+	virtual void NotifyCommChannelClosed() = 0;
+};
+
+//**********************************************************************************
+// Class DummyCommObserver
+//
+//**********************************************************************************
+
+class DummyCommObserver : public CommChannelPluginObserver
+{
+public:
+	void NotifyDataAvailable() { };
+	void NotifyCommChannelOpened() { };
+	void NotifyCommChannelClosed() { };
+};
+
+//**********************************************************************************
+// Class CommChannelPlugin
+//
+// This class is the parent class of all communication channel plugins used
+// in DataGateway.
+//**********************************************************************************
+
+class CommChannelPlugin : public Plugin
+{
+public:
+	PluginType GetType() { return comm_channel; }
+	virtual DWORD Init();
+	virtual DWORD Open() = 0;
+	virtual bool IsOpen() { return m_Open; }
+	/*
+	 * This method closes and deletes the instance of plugin
+	 */	
+	virtual DWORD Close() = 0;
+	/*
+	 * This method is used to send Data object and Receive Data object
+	 */
+	virtual DWORD SendReceive(Data* data_in, Data** data_out, long timeout = 5000) = 0;
+	/*
+	 * This method is used to send Data object
+	 */	
+	virtual DWORD Send(Data* data_in, long timeout = 5000) = 0;
+	/*
+	 * This method is used to receive Data object
+	 */	
+	virtual DWORD Receive(Data** data_out, long timeout = 5000) = 0;
+	/*
+	 * This method creates instance of specified plugin  
+	 */
+	static CommChannelPlugin* Instance(const string& pluginname,
+		                               const CommChannelPluginObserver* observer = NULL);
+	/*
+	 * This method initializes and connects the instance of plugin
+	 */	
+	static DWORD Connect();
+	/*
+	 * This method closes and deletes the instance of plugin
+	 */	
+	static DWORD Disconnect();
+
+protected:
+	CommChannelPlugin(const CommChannelPluginObserver* observer = NULL);
+	const CommChannelPluginObserver* GetObserver() { return m_Observer; }
+
+protected:
+	const CommChannelPluginObserver* m_Observer;
+	bool m_Open;
+
+private:
+	static CommChannelPlugin* m_Self;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/pluginmgr.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef PLUGINMGR_H
+#define PLUGINMGR_H
+
+class PluginManager
+{
+public:
+};
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/safequeue.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,218 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*    This file contains headers of SafeQueue template class.
+*/
+
+#ifndef SAFEQUEUE_H
+#define SAFEQUEUE_H
+
+#include "sync.h"
+
+//STL
+#pragma warning (push, 3)
+#pragma warning( disable : 4702 ) // Unreachable code warning
+#pragma warning( disable : 4290 ) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#include <queue>
+
+
+
+
+using namespace std;
+class Data;
+
+//**********************************************************************************
+// Template Class SafeQueue
+//
+// This template class implements a thread safe queue with generic types
+//**********************************************************************************
+
+template <class T>
+class SafeQueue : private queue<T>,
+				  private Mutex,
+				  private Semaphore
+{
+public:
+    typedef typename queue<T>::size_type size_type;
+    SafeQueue();
+	~SafeQueue();
+	/*
+	 * Adds a new element to the end of the queue
+	 */	
+	void push(const T& val);
+	/*
+	 * Removes the next element in the queue
+	 */	
+	void pop(void);
+	/*
+	 * Returns whether the queue is empty or not
+	 */	
+	bool empty(void) const;
+	/*
+	 * Returns a reference to the last element in the queue
+	 */	
+	T& back(DWORD timeout = INFINITE) throw (TimeoutException);
+	/*
+	 * Returns a constant reference to the last element in the queue
+	 */	
+	const T& back(DWORD timeout = INFINITE) const throw (TimeoutException);
+	/*
+	 * Returns a reference to the next element in the queue
+	 */	
+	T& front(DWORD timeout = INFINITE) throw (TimeoutException);
+	/*
+	 * Returns a constant reference to the next element in the queue
+	 */	
+	const T& front(DWORD timeout = INFINITE) const throw (TimeoutException);
+	/*
+	 * Returns the number of elements in the queue
+	 */	
+	typename SafeQueue<T>::size_type size(void) const;
+	/*
+	 * This method is used to pop all of the elements in queue and return them in single Data object
+	 */
+	T& popAll(DWORD timeout = INFINITE) throw (TimeoutException);
+};
+
+template <class T>
+SafeQueue<T>::SafeQueue()
+{
+}
+
+template <class T>
+SafeQueue<T>::~SafeQueue()
+{
+}
+
+/*
+ * Adds a new element to the end of the queue
+ */
+template <class T>
+void SafeQueue<T>::push(const T& val)
+{
+	Mutex::Lock();
+	queue<T>::push(val);
+	Mutex::Unlock();
+	Semaphore::Notify();
+}
+
+/*
+ * Removes the next element in the queue
+ */
+template <class T>
+void SafeQueue<T>::pop(void)
+{
+	Mutex::Lock();
+	queue<T>::pop();
+	Mutex::Unlock();
+}
+
+/*
+ * Returns whether the queue is empty or not
+ */
+template <class T>
+bool SafeQueue<T>::empty(void) const
+{
+	const_cast<SafeQueue<T>*>(this)->Lock();
+	bool value = queue<T>::empty();
+	const_cast<SafeQueue<T>*>(this)->Unlock();
+	return value;
+}
+
+/*
+ * Returns a reference to the last element in the queue
+ */
+template <class T>
+T& SafeQueue<T>::back(DWORD timeout)
+	throw (TimeoutException)
+{
+	if (Semaphore::Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue back timed out");
+	}
+	Mutex::Lock();
+	T& value = queue<T>::back();
+	Mutex::Unlock();
+	return value;
+}
+
+/*
+ * Returns a constant reference to the last element in the queue
+ */
+template <class T>
+const T& SafeQueue<T>::back(DWORD timeout) const
+	throw (TimeoutException)
+{
+	if (const_cast<SafeQueue<T>*>(this)->Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue back timed out");;
+	}
+	const_cast<SafeQueue<T>*>(this)->Lock();
+	const T& value = queue<T>::back();
+	const_cast<SafeQueue<T>*>(this)->Unlock();
+	return value;
+}
+
+/*
+ * Returns a reference to the next element in the queue
+ */
+template <class T>
+T& SafeQueue<T>::front(DWORD timeout)
+	throw (TimeoutException)
+{
+	if (Semaphore::Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue front timed out");
+	}
+	Mutex::Lock();
+	T& value = queue<T>::front();
+	Mutex::Unlock();
+	return value;
+}
+
+/*
+ * Returns a constant reference to the next element in the queue
+ */
+template <class T>
+const T& SafeQueue<T>::front(DWORD timeout) const
+	throw (TimeoutException)
+{
+	if (const_cast<SafeQueue<T>*>(this)->Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue front timed out");
+	}
+	const_cast<SafeQueue<T>*>(this)->Lock();
+	const T& value = queue<T>::front();
+	const_cast<SafeQueue<T>*>(this)->Unlock();
+	return value;
+}
+
+/*
+ * Returns the number of elements in the queue
+ */
+template <class T>
+typename SafeQueue<T>::size_type SafeQueue<T>::size(void) const
+{
+	const_cast<SafeQueue<T>*>(this)->Lock();
+	queue<T>::size_type value = queue<T>::size();
+	const_cast<SafeQueue<T>*>(this)->Unlock();
+	return value;
+}
+
+
+#pragma warning (pop)
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/stdafx.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// stdafx.h : include file for standard system include files,
+// or project specific include files that are used frequently, but
+// are changed infrequently
+//
+
+#pragma once
+
+#include <iostream>
+#include <tchar.h>
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/sync.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,101 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains headers of synchronziation objects. These classes are Mutex, Semaphore and
+*   Event classes. Implementation of TimeoutException is defined.
+*/
+
+#ifndef SYNC_H
+#define SYNC_H
+
+#include <windows.h>
+#include <process.h>
+
+#include <string>
+
+using namespace std;
+
+//**********************************************************************************
+// Class TimeoutException
+//
+//**********************************************************************************
+
+class TimeoutException
+{
+public:
+	TimeoutException(const char* s = "") { m_Message.assign(s); }
+	const string& GetMessage() const { return m_Message; }
+private:	
+	string m_Message;
+};
+
+//**********************************************************************************
+// Class Mutex
+//
+// This class implements a Mutex using Windows API synchronization mechanism 
+//**********************************************************************************
+
+
+class Mutex
+{
+public:
+	Mutex(void);
+	~Mutex(void);
+	void Lock(void);
+	void Unlock(void);
+private:
+	CRITICAL_SECTION m_Lock;
+};
+
+//**********************************************************************************
+// Class Semaphore
+//
+// This class encapsulates Windows API Semaphore functionality
+//**********************************************************************************
+
+class Semaphore
+{
+public:
+	Semaphore(void);
+	Semaphore(int available);
+	~Semaphore(void);
+	DWORD Wait(DWORD timeout = INFINITE);
+	void Notify(void);
+	void Notify(int how_many);
+private:
+	HANDLE m_Semaphore;
+};
+
+//**********************************************************************************
+// Class Event
+//
+// This class encapsulates Windows API Event functionality
+//**********************************************************************************
+
+class Event
+{
+public:
+	Event(bool manual_reset = false);
+	~Event(void);
+	void Set(void);
+	void Reset(void);
+	DWORD Wait(DWORD timeout = INFINITE);
+	HANDLE EventHandle() const;
+private:
+	HANDLE m_Event;
+};
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/thread.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,212 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of template class Thread and ThreadData.
+*	Interface Runnable is defined.
+*/
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This file contains the header file of template class Thread and ThreadData.
+	Interface Runnable is defined.
+
+-------------------------------------------------------------------------------
+*/
+
+#ifndef THREAD_H
+#define THREAD_H
+
+#include "sync.h"
+#include <process.h>
+
+
+typedef unsigned (__stdcall *THREAD_START_FUNC) (void *);
+
+
+//**********************************************************************************
+// Template Class ThreadData
+//
+//**********************************************************************************
+
+template <class T>
+struct ThreadData
+{
+	public:
+		typedef void (T::*TFunc)();
+		HANDLE m_hEvent;
+		T* m_pThreadObject;
+		TFunc m_pThreadFunc;
+		static DWORD _ThreadFunc(ThreadData<T>* pThis)
+		{
+			ThreadData<T> td = *pThis;
+			SetEvent(td.m_hEvent);
+			((*(td.m_pThreadObject)).*(td.m_pThreadFunc))();
+			return 0;
+		}
+};
+
+//**********************************************************************************
+// Template Class Runnable
+//
+//**********************************************************************************
+
+class Runnable
+{
+	public:
+		virtual void Run() = 0;
+		virtual void Stop() = 0;
+};
+
+//**********************************************************************************
+// Template Class Thread
+//
+// This is the template for thread class, implemented by all threads in DataGateway
+// The template encapsulates Windows API tread functionality
+//**********************************************************************************
+
+template <class T>
+class Thread : public Runnable
+{
+	public:
+		Thread();
+		Thread(Runnable* runnable);
+		~Thread();
+		void Run();
+		void Start();
+		void Stop();
+		void Suspend();
+		void Resume();
+		HANDLE ThreadHandle();
+	private:
+		HANDLE CreateMemberThread(Runnable* p,
+			                      void (Runnable::*func)());
+	private:
+		HANDLE m_hMemberThread;
+		Runnable* m_Runnable;
+};
+
+template <class T>
+Thread<T>::Thread()
+{
+	m_hMemberThread = NULL;
+	m_Runnable = this;
+}
+
+template <class T>
+Thread<T>::Thread(Runnable* runnable)
+{
+	m_hMemberThread = NULL;
+	if (runnable != NULL)
+	{
+		m_Runnable = runnable;
+	}
+	else
+	{
+		m_Runnable = this;
+	}
+}
+
+template <class T>
+Thread<T>::~Thread()
+{
+	if (m_hMemberThread != NULL)
+	{
+		CloseHandle(m_hMemberThread);
+	}
+	m_Runnable = NULL;
+}
+
+template <class T>
+void Thread<T>::Run()
+{
+}
+
+template <class T>
+void Thread<T>::Suspend()
+{
+	if (m_hMemberThread != NULL)
+	{
+		SuspendThread(m_hMemberThread);
+	}
+}
+
+template <class T>
+void Thread<T>::Resume()
+{
+	if (m_hMemberThread != NULL)
+	{
+		ResumeThread(m_hMemberThread);
+	}
+}
+
+template <class T>
+void Thread<T>::Start()
+{
+	if (m_Runnable != NULL)
+	{
+		m_hMemberThread = CreateMemberThread(m_Runnable,
+											 &Runnable::Run);
+		if (m_hMemberThread == NULL)
+		{
+			cerr << "Thread: could not create thread" << endl;
+		}		
+	}
+	else
+	{
+		m_hMemberThread = NULL;
+		cerr << "Thread: threadfunc NULL" << endl;
+	}
+}
+
+template <class T>
+void Thread<T>::Stop()
+{
+	m_Runnable->Stop();
+}
+
+template <class T>
+HANDLE Thread<T>::ThreadHandle()
+{
+	return m_hMemberThread;
+}
+
+template <class T>
+HANDLE Thread<T>::CreateMemberThread(Runnable* p,
+									 void (Runnable::*func)())
+{
+	ThreadData<Runnable> td;
+	td.m_pThreadObject = p;
+	td.m_pThreadFunc = func;
+	td.m_hEvent = CreateEvent(NULL, 0, 0, NULL);
+
+	unsigned int Dummy;
+	HANDLE ThreadHandle = (HANDLE)_beginthreadex(NULL,
+		                               NULL,
+									   (THREAD_START_FUNC)ThreadData<Runnable>::_ThreadFunc,
+									   &td,
+									   NULL,
+									   &Dummy);
+
+	WaitForSingleObject(td.m_hEvent,INFINITE);
+	CloseHandle(td.m_hEvent);
+	return ThreadHandle;
+}
+
+#endif
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/inc/util.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,208 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of the Util and UtilError.
+*/
+
+#ifndef UTIL_H
+#define UTIL_H
+
+#pragma warning (push, 3)
+#pragma warning( disable : 4702 ) // Unreachable code warning
+#pragma warning( disable : 4290 ) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
+#pragma warning ( disable : 4786 )
+
+// INCLUDE FILES
+#include <iostream>
+#include <fstream>
+#include <map>
+#include <string>
+#include <time.h>
+#include <windows.h>
+#include <sys/timeb.h>
+#include "error.h"
+
+#define ENABLE_LOG_SYNC //makes logging methods synced to access by multiple threads
+
+#ifdef ENABLE_LOG_SYNC 
+	#include "sync.h"
+#endif
+
+using namespace std;
+
+//**********************************************************************************
+// Class UtilError
+//
+// Error class which is thrown if an exception occurs
+// in Util operations. Holds error code and string.
+//**********************************************************************************
+class UtilError
+{
+public:
+	string iError;
+	HRESULT iResult;
+	UtilError(string aError, HRESULT aResult)
+	{
+		iError = aError;
+		iResult = aResult;
+	}
+};
+
+//**********************************************************************************
+// Class Util
+//
+// Provides static utility functions for logging and string handling.
+//**********************************************************************************
+class Util
+{
+public: // Enumerations
+	enum VerboseLevel {none,     // no output
+		               result,   // only result is reported
+					   error,    // errors reported
+					   info,     // more info reported
+					   debug};
+
+public: // Constructors
+	/*
+	 * Default constructor which initializes logging level.
+	 */
+	Util(const VerboseLevel aVerbose = none) { iVerbose = aVerbose; }
+
+public:
+	/*
+	 * Returns current verbose level.
+	 */
+	static VerboseLevel GetVerboseLevel();
+
+	/*
+	 * Sets new verbose level by string "none", "result", "error", "info" or "debug"
+	 */
+	static void SetVerboseLevel(const string& aVerbose);
+
+	/*
+	 * Sets new verbose level by enumeration.
+	 */
+	static void SetVerboseLevel(const VerboseLevel aVerbose);
+
+	/*
+	 * Enables/disables timestamp from output by string "yes" or "no"
+	 */
+	static void SetTimestamp(const string& aTimestamp);
+
+	/*
+	 * Enables/disables timestamp from output. 0 is disabled.
+	 */
+	static void SetTimestamp(const int aTimestamp);
+
+	/*
+	 * Parses command line parameters to map.
+	 */
+	static void ParseCmdLine(const int aArgc, char **aArgs, map<string, string>& aMap) throw (UtilError);
+
+	/*
+	 * Returns value by key from a map.
+	 */
+	static void GetValue(const string& aKey, const map<string, string>& aMap, string& aValue)  throw (UtilError);
+
+	/*
+	 * Reads properties from a file to a map.
+	 */
+	static void ReadProperties(const string& aFilename, map<string, string>& aMap)  throw (UtilError);
+
+	/*
+	 * Prints message to output in error level.
+	 */
+	static void Error(const string& aMsg);
+
+	/*
+	 * Prints message to output in error level with error code number.
+	 */
+	static void Error(const string& aMsg, const long aCode);
+
+	/*
+	 * Prints hex dump of data to output.
+	 */
+	static void Hex(void *aData, const int aLength);
+
+	/*
+	 * Prints hex dump of char table to output.
+	 */
+	static void Hex(const char aData[]);
+
+	/*
+	 * Prints hex dump of string to output.
+	 */
+	static void Hex(const string& aMsg);
+
+	/*
+	 * Prints hex dump of data to output.
+	 */
+	static void Hex(const unsigned char* aData, const int aLength);
+
+	/*
+	 * Prints hex dump of data to output.
+	 */
+	static void Hex(void* aData, const int aLength, string* aHexDump);
+
+	/*
+	 * Prints message to output in result level.
+	 */
+	static void Log(const string& aMsg);
+
+	/*
+	 * Prints message to output in info level.
+	 */
+	static void Info(const string& aMsg);
+
+	/*
+	 * Prints message to output in debug level.
+	 */
+	static void Debug(const string& aMsg);
+
+	/*
+	 * Prints output to a stream.
+	 */
+	static void Print(ostream& out,
+		              const string& aMsg,
+					  const VerboseLevel aLevel = none,
+					  const long aCode = 0);
+
+	/*
+	 * Converts string to lower case.
+	 */
+	static string& ToLower(string& aString);
+
+	/*
+	 * Converts string to upper case.
+	 */
+	static string& ToUpper(string& aString);
+	
+	/*
+	 * Sets paramvalue if command line parameter is found
+	 */
+	static void CheckCommandlineParam( const string& paramname, string& paramvalue );
+
+private:
+	static VerboseLevel iVerbose;
+	static int iTimestamp;
+#ifdef ENABLE_LOG_SYNC 
+	static Mutex iCritical;
+#endif
+};
+
+#pragma warning (pop)
+
+#endif
+
+// End of file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/ini/HtiGateway.ini	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,15 @@
+### HtiGateway parameters
+# TCP/IP port number
+TCPIP_PORT = 2000
+
+# TCP/IP receive buffer size in bytes (dec)
+TCPIP_RECV_BUFFER_SIZE = 8192
+
+# Default communication channel plugin
+DEFAULT_COMM_CHANNEL_PLUGIN = SERIAL
+#DEFAULT_COMM_CHANNEL_PLUGIN = IPCOMM
+
+# Maximum time in milliseconds to wait shutdown
+# NOTE: 0 means no waiting. This may cause
+#       undefined behaviour.
+MAXIMUM_SHUTDOWN_WAITTIME = 3000
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/ini/ipcommplugin.ini	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,21 @@
+### IPCOMM plugin parameters
+
+
+# Local TCP/IP port where to listen for incoming HTI connection.
+# If defined remote host & port parameters will be ignored.
+#
+# NOTE: Do not use the same port as HtiGateway!
+#
+#LOCAL_PORT=3000
+
+
+# Remote TCP/IP host & port where HTI is listening.
+#
+REMOTE_HOST=localhost
+REMOTE_PORT=3000
+
+
+# Buffer size used for receiving data
+# Default value is 8*1024 bytes (8KB)
+#
+#RECV_BUFFER_SIZE=8192
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/ini/serialplugin.ini	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,25 @@
+### Parameters for serial connection
+#init string
+#INIT_STRING = 115200,n,8,1
+#INIT_STRING = 9600,n,8,1
+
+#comm port
+COMPORT = COM1
+
+#timeout for communication operations, in ms
+#default value is 40000
+#TIMEOUT=60000
+
+#enable hw flow control
+#should be "1" to enable
+#disabled by default
+#HW_FLOWCONTROL=1
+
+#make pause after sending over serial, in ms
+#can be used to avoid overflow problem
+# default value is 0
+#SEND_PAUSE=1000
+
+#set the size for output buffer
+# can be set smaller to avoid overrun
+#SEND_SIZE=1000
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/HtiDispatcher.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,554 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implementation of HtiDispatcher class.
+*/
+
+#include "stdsoap2.h" //should be first because of WinSock2.h errors
+
+#include "common.h"
+#include "HtiDispatcher.h"
+#include "soapHandler.h"
+
+#include "HtiMessage.h"
+#include "util.h"
+#include <sstream>
+
+#include <crtdbg.h>
+
+const static char* HTI_PLUGIN_FOLDER = "ServicePlugins/";
+//used to redispatch hti framework error messages (like not authorized)
+
+/**
+* namespace table is needed to correclty send fault messages
+* each service plugin should explicitly set its one namespace table before processing
+* request
+*/
+SOAP_NMAC struct Namespace namespaces[] =
+{
+	{"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", "http://www.w3.org/*/soap-envelope", NULL},
+	{"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", "http://www.w3.org/*/soap-encoding", NULL},
+	{NULL, NULL, NULL, NULL}
+};
+
+//**********************************************************************************
+// Class HtiDispatcher
+//
+// This class 
+// -forwards Soap requests and Hti messages to correct SOAPHandlers
+// -Is used to initiate SOAPHandlers by reading them from dll's and start them 
+//**********************************************************************************
+HtiDispatcher::HtiDispatcher(SafeQueue<Data*>* qIn,
+                             SafeQueue<Data*>* qOut)
+	: m_Running(true),
+	m_QueueIn(qIn),
+	m_QueueOut(qOut),
+	m_IncomingHtiMessage(NULL)
+{
+}
+
+HtiDispatcher::~HtiDispatcher()
+{
+	for( htiSoapActionHashMap::const_iterator i = m_SoapHandlers.begin();
+		 i != m_SoapHandlers.end();
+		 ++i)
+	{
+		delete i->second;
+	}
+}
+
+/**
+ * This method is used to read all the available SoapHandler dll's and initialize an instance of them and store a reference to m_SoapHandlers(by soap action)
+ * and m_HanlersUidMap(by service uid) maps.
+ */
+void HtiDispatcher::InitHandlers()
+{
+	Util::Info( "HtiDispatcher::InitHandlers" );
+	//1. read exe/plugin directory
+	WIN32_FIND_DATA FileData; 
+	HANDLE hSearch; 
+	bool fFinished = false;
+ 
+	// Start searching for .dll files
+	string searchMask = HTI_PLUGIN_FOLDER;
+	searchMask.append( "*.dll" );
+ 	hSearch = FindFirstFile( searchMask.c_str(), &FileData );
+	if (hSearch == INVALID_HANDLE_VALUE) 
+	{ 
+		Util::Info("No DLLs found."); 
+		return;
+	} 
+ 
+	while (!fFinished) 
+	{ 
+		
+	//2. get list of all DLLs
+	//SoapHandler* t = new SoapHandler("ws_hti.dll");
+		string pluginPath = HTI_PLUGIN_FOLDER;
+		pluginPath.append( FileData.cFileName );
+		Util::Info("Try to load:");
+		Util::Info(pluginPath);
+		SoapHandler* t = new SoapHandler( pluginPath );
+		if( t->LoadPlugin() )
+		{
+			//3. add them to m_SoapHandlers
+			char* soapAction = t->soapAction();
+			m_SoapHandlers[ soapAction ] = t;
+			//add to uid map as well
+			int uid = t->serviceUID();
+			m_HanlersUidMap[ uid ] = t;
+			
+			stringstream s;
+			s<<"Loaded plugin: ";
+			s<<soapAction;
+			s<<", service UID: ";
+			s<<uid;
+			
+			Util::Info( s.str().c_str() );
+		}
+		else
+		{
+			delete t;
+			//
+			Util::Error("Failed load DLL as a plugin");
+		}
+	 
+		if (!FindNextFile(hSearch, &FileData)) 
+		{
+			if (GetLastError() == ERROR_NO_MORE_FILES) 
+			{ 
+				fFinished = TRUE; 
+			} 
+			else 
+			{ 
+				Util::Error("Couldn't find next plugin.");
+				fFinished = TRUE;
+				//return;
+			} 
+		}
+	} 
+	 
+	// Close the search handle. 
+	 
+	FindClose(hSearch);
+
+	stringstream s;
+	s<<"Plugins loaded ";
+	s<<m_SoapHandlers.size();
+	Util::Info( s.str().c_str() );
+}
+
+/**
+ * This method is used to start all the SoapHandler instances that are stored in htiSoapActionHashMap
+ */
+void HtiDispatcher::StartHandlers()
+{
+	for( htiSoapActionHashMap::const_iterator i = m_SoapHandlers.begin();
+		 i != m_SoapHandlers.end();
+		 ++i)
+	{
+		(i->second)->SetDispatcher(this);
+		(i->second)->Start();
+	}
+}
+
+/*
+ * This loop is used to forward incoming Hti messages(arriving from CommChannelPlugin to m_QueueOut side) to correct SoapHandlers
+ */
+void HtiDispatcher::Run()
+{
+	Util::Debug("HtiDispatcher::Run");
+	//m_testHandler.SetDispatcher(this);
+	//m_testHandler.Start();
+	InitHandlers();
+	StartHandlers();
+
+	BYTE* shortData = NULL; //keep data if it's too short to have HtiHeader
+							//or if one Data msg have more than one HtiMessage
+	DWORD msgBufferSize = 8096;
+	BYTE* msgBuffer = (BYTE*)malloc( msgBufferSize );
+	DWORD shortDataLen = 0;
+
+	// By setting this threads priority below others will give soaphandler threads 
+	// more runtime to process the received messages.. This is to avoid the situation
+	// where two messages arrive so close to each other that m_hReceiveHtiEvent is 
+	// signalled twice before the first message has even been processed by the soap plugin.
+	if(!SetThreadPriority( ThreadHandle(), THREAD_PRIORITY_BELOW_NORMAL ))
+		Util::Info("Warning: Could not set HtiDispatcher priority!");
+	
+	while (m_Running)
+	{
+		try
+		{	
+			Data* d = m_QueueOut->front(50);
+			BYTE* p = (BYTE *)d->GetData();
+			DWORD l = d->GetLength();
+			//printf("\td = %d\n", m_QueueOut->size());
+
+			if (Util::GetVerboseLevel() == Util::VerboseLevel::debug)
+			{
+				char tmp[64];
+				sprintf(tmp, "[HtiDispatcher] HTI MsgSize = %d", l);
+				string s(tmp);
+				Util::Debug(s);
+				//Util::Hex(p, d->GetLength());
+			}
+
+			//Util::Debug("leftovers");
+			//copy leftovers to the beginning of the buffer
+			if ( shortDataLen > 0 )
+			{
+				memcpy( msgBuffer, shortData, shortDataLen );
+			}
+			shortData = msgBuffer; //set shortData to the beginning
+
+			//copy data to buffer
+			if ( shortDataLen + l > msgBufferSize )
+			{
+				msgBufferSize = shortDataLen + l;
+				msgBuffer = (BYTE*)realloc(msgBuffer, msgBufferSize);
+				shortData = msgBuffer;
+			}
+			//copy data gotten from queue to the end of shortData
+			memcpy(shortData + shortDataLen, p, l );
+			shortDataLen = l + shortDataLen;
+
+			while ( shortDataLen != 0 &&
+				    (shortDataLen >= HtiMessage::MinHeaderSize() ||
+				    m_IncomingHtiMessage != NULL ) )
+			{
+				//new message
+				if ( m_IncomingHtiMessage == NULL )
+				{
+					if ( shortDataLen >= HtiMessage::MinHeaderSize() )
+					{
+						if ( HtiMessage::CheckValidHtiHeader(shortData) )
+						{
+							m_IncomingHtiMessage = new HtiMessage( shortData, shortDataLen );
+
+							if (Util::GetVerboseLevel() == Util::VerboseLevel::debug)
+							{
+								char tmp[64];
+								sprintf(tmp,"New hti message %d", m_IncomingHtiMessage->HtiDataSize());
+								string s(tmp);
+								Util::Debug(s);
+								//Util::Hex(p, d->GetLength());
+							}
+							
+							//_RPT2(_CRT_WARN, "income msg %x <%d>\n", m_IncomingHtiMessage, sizeof(HtiMessage));
+							//check message
+							if ( m_IncomingHtiMessage->IsMessageComplete() )
+							{
+								Util::Debug("HTI message complete");
+								DWORD msgSize = m_IncomingHtiMessage->HtiDataSize();
+								if (  msgSize < shortDataLen  )
+								{
+									//remove used part
+									//BYTE* temp = new BYTE[shortDataLen-msgSize];
+									//_RPT2(_CRT_WARN, "temp %x <%d>\n", shortData , shortDataLen-msgSize);
+									//memcpy(temp, shortData + msgSize, shortDataLen-msgSize);
+									//_RPT1(_CRT_WARN, "del shortData %x\n", shortData);
+									//delete[] shortData;
+									//shortData = temp;
+									shortData += msgSize; //just move pointer
+									shortDataLen -= msgSize;
+
+								}
+								else
+								{
+									//_RPT1(_CRT_WARN, "del shortData %x\n", shortData);
+									//delete[] shortData;
+									//shortData = NULL;
+									shortDataLen = 0;
+								}
+								//Dispatch incoming message
+								DispatchToSoapHandlers();
+							}
+							else
+							{
+								//_RPT1(_CRT_WARN, "del shortData %x\n", shortData);
+								//delete[] shortData;
+								//shortData = NULL;
+								shortDataLen = 0;
+							}
+						}
+						else
+						{
+							//invalid header
+							Util::Error("Invalid HTI header, dismiss Data message");
+							Util::Hex(shortData, HtiMessage::MinHeaderSize() );
+							//_RPT1(_CRT_WARN, "del shortData %x\n", shortData);
+							//delete[] shortData;
+							//shortData = NULL;
+							shortDataLen = 0;
+						}
+					}
+				}
+				else //body parts
+				{
+					Util::Debug("add");
+					DWORD added = m_IncomingHtiMessage->AddToBody( shortData,
+																   shortDataLen );
+					//printf("reminder %d\n", m_IncomingHtiMessage->Reminder());
+					if ( added < shortDataLen )
+					{
+						//only part of message was added
+						//remove added part
+						//BYTE* temp = new BYTE[shortDataLen-added];
+						//_RPT2(_CRT_WARN, "temp %x <%d>\n", shortData , shortDataLen-added);
+						//memcpy(temp, shortData + added, shortDataLen-added);
+						//_RPT1(_CRT_WARN, "del shortData %x\n", shortData );
+						//delete[] shortData;
+						//shortData = temp;
+						shortData += added;
+						shortDataLen -= added;
+					}
+					else //all data were added
+					{
+						//_RPT1(_CRT_WARN, "del shortData %x\n", shortData );
+						//delete[] shortData;
+						//shortData = NULL;
+						shortDataLen = 0;
+					}
+
+					if ( m_IncomingHtiMessage->IsMessageComplete() )
+					{
+						Util::Debug("HTI message complete");
+						//Dispatch incoming message
+						DispatchToSoapHandlers();
+					}
+				}
+			}
+
+			m_QueueOut->pop();
+			//_RPT1(_CRT_WARN, "del data %x\n", d);
+			delete d;
+			d = NULL;
+		} catch (TimeoutException te)
+		{
+			//Util::Debug("[DataGatewaySocketWriterThread]timeout exception");
+		}
+	}
+	free( msgBuffer );
+}
+
+/**
+ * This method is used to forward the incoming HTI message to correct SoapHandler
+ * The correct SoapHandler is found by service uid
+ */
+void HtiDispatcher::DispatchToSoapHandlers()
+{
+	htiUIDHashMap::const_iterator i;
+	int targetServiceUid;
+	if ( m_IncomingHtiMessage->IsErrorMessage() )
+	{
+		targetServiceUid = m_IncomingHtiMessage->ErrorServiceUid();
+
+		stringstream s;
+		s<<"Received HTI error message\nhtiErrorCode: ";
+		s<<m_IncomingHtiMessage->HtiErrorCode();
+		s<<"\nserviceUid: ";
+		s<<m_IncomingHtiMessage->ErrorServiceUid();
+		s<<"\nserviceErrorCode: ";
+		s<<m_IncomingHtiMessage->ServiceErrorCode();
+		s<<"\nErrorDescription: ";
+		s<<m_IncomingHtiMessage->ErrorDescription();
+		s<<"\ntargetServiceUid: ";
+		s<<targetServiceUid;
+
+		Util::Error(s.str().c_str());
+	}
+	else
+	{
+		targetServiceUid = m_IncomingHtiMessage->GetServiceUID();
+	}
+
+	if ( targetServiceUid == HTI_SYSTEM_SERVICE_UID &&
+		 m_IncomingHtiMessage->IsErrorMessage() )
+	{
+		Util::Debug("dispatch error");
+		//if system plugin doesn't wait for a message then find plugin that
+		//is waiting for a message and delivery the incoming msg to it
+		i = m_HanlersUidMap.find( targetServiceUid  );
+		if ( i != m_HanlersUidMap.end() )
+		{
+			if ( (i->second)->IsWaitsForHtiMessage() )
+			{
+				Util::Debug("dispatch error to system cause it waits");
+				if ( !(i->second)->ReceiveHtiMessage(m_IncomingHtiMessage) )
+				{
+					Util::Error("Failed to dispatch hti message");
+					Util::Hex(m_IncomingHtiMessage->HtiData(), HtiMessage::MinHeaderSize());
+					//dismiss message
+					delete m_IncomingHtiMessage;
+				}
+			}
+			else
+			{
+				Util::Debug("find handler that waits");
+				//find the handler that waits for hti message
+				for( htiUIDHashMap::const_iterator i = m_HanlersUidMap.begin();
+					i != m_HanlersUidMap.end();
+					++i)
+				{
+					Util::Debug((i->second)->soapAction());
+					if ( (i->second)->IsWaitsForHtiMessage() )
+					{
+						Util::Debug("found");
+						if ( !(i->second)->ReceiveHtiMessage(m_IncomingHtiMessage) )
+						{
+							Util::Error("Failed to dispatch hti message");
+							Util::Hex(m_IncomingHtiMessage->HtiData(), HtiMessage::MinHeaderSize());
+							//dismiss message
+							delete m_IncomingHtiMessage;
+						}
+						break;
+					}
+				}
+			}
+		}
+	}
+	else
+	{
+		i = m_HanlersUidMap.find( targetServiceUid  );
+		if ( i != m_HanlersUidMap.end() )
+		{
+			if ( !(i->second)->ReceiveHtiMessage(m_IncomingHtiMessage) )
+			{
+				Util::Error("Failed to dispatch hti message");
+				Util::Hex(m_IncomingHtiMessage->HtiData(), HtiMessage::MinHeaderSize());
+				//dismiss message
+				delete m_IncomingHtiMessage;
+			}
+		}
+		else
+		{
+			Util::Error("Failed to dispatch hti message, no plug-in with appropriate uid",m_IncomingHtiMessage->GetServiceUID() );
+			Util::Hex(m_IncomingHtiMessage->HtiData(), HtiMessage::MinHeaderSize());
+			//dismiss message
+			delete m_IncomingHtiMessage;
+		}
+	}
+	m_IncomingHtiMessage = NULL;
+
+	// This will give other threads (soaphandlers) some runtime to process the
+	// received message.
+	Sleep(0);
+}
+
+/*
+ * This method is used to forward soap request to correct SOAPHandler
+ * Correct SOAPHandler is found by soap action
+ */
+bool HtiDispatcher::DispatchSoapServe(struct soap* soapEnv)
+{
+	Util::Debug("HtiDispatcher::DispatchSoapServe()");
+/*	
+	_CrtMemState localMem;
+	_CrtMemCheckpoint( &localMem );
+*/
+	soap_begin( soapEnv );
+	if (soap_begin_recv(soapEnv))
+	{
+		soap_set_namespaces( soapEnv, namespaces);
+		soap_send_fault(soapEnv);
+		return false;
+	}
+
+	if ( !(soapEnv->action) )
+	{
+		//Util::Error("soapAction is missing");
+		soap_set_namespaces( soapEnv, namespaces);
+		soapEnv->error = soap_sender_fault(soapEnv, "soapAction is missing", NULL); 
+		soap_send_fault(soapEnv);
+		return false;
+	}
+/*
+	//_RPT0(_CRT_WARN, "!!!!!!!!!!!!!!!! Local Objects !!!!!!!!!!!!!!!!\n");
+
+	_CrtMemDumpAllObjectsSince( &localMem );
+	//_RPT1(_CRT_WARN, "action address %x\n", soapEnv->action);
+*/
+	htiSoapActionHashMap::const_iterator it;
+	it = m_SoapHandlers.find( soapEnv->action );
+	if ( it != m_SoapHandlers.end() )
+	{
+		return (it->second)->ServeSoap( soapEnv );
+	}
+	else
+	{
+		//Util::Error("soapAction is unknown:");
+		//Util::Error(soapEnv->action);
+		//soapEnv->error = SOAP_NO_METHOD;
+		soap_set_namespaces( soapEnv, namespaces);
+		soapEnv->error = soap_sender_fault(soapEnv, "No plugin found", "no plugin found for requested service in actionSOAP header field"); 
+		soap_send_fault(soapEnv);
+		return false;
+	}
+
+	Util::Debug("HtiDispatcher::DispatchSoapServe() OK");
+}
+
+/*
+ * SoapHandler calls this method
+ * The method creates a Data object from the HtiMessage given as parameter 
+ * and puts the Data object into incoming queue(going eventually to CommChannelPlugin)
+ */
+void HtiDispatcher::SendHtiMessage(HtiMessage* msg)
+{
+	Util::Debug("HtiDispatcher::SendHtiMessage()");
+	if (msg)
+	{
+		Data* d = new Data(msg->HtiData(), msg->HtiDataSize(), Data::EData);
+		//_RPT2(_CRT_WARN, "d %x <%d>\n", d , sizeof(Data));
+
+		if (Util::GetVerboseLevel() == Util::VerboseLevel::debug)
+		{
+			char tmp[64];
+			sprintf(tmp, "[HtiDispatcher] HTI MsgSize = %d", msg->HtiDataSize());
+			string s(tmp);
+			Util::Debug(s);
+			Util::Hex( (char*)(msg->HtiData()), 16);
+		}
+		m_QueueIn->push(d);
+		//delete msg;
+	}
+	Util::Debug("HtiDispatcher::SendHtiMessage() OK");
+}
+
+void HtiDispatcher::Stop()
+{
+	m_Running = false;
+	HANDLE* handles = new HANDLE[ m_SoapHandlers.size() ];
+	int h = 0;
+	for( htiSoapActionHashMap::const_iterator i = m_SoapHandlers.begin();
+		 i != m_SoapHandlers.end();
+		 ++i)
+	{
+		(i->second)->Stop();
+		handles[ h++ ] = (i->second)->ThreadHandle();
+	}
+
+	WaitForMultipleObjects(m_SoapHandlers.size(),
+					       handles,
+						   TRUE,
+						   5000/*g_MaximumShutdownWaitTime*/);
+
+	delete[] handles;
+}
+
+bool HtiDispatcher::IsRunning()
+{
+	return m_Running;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/HtiMessage.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,228 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implementation of HtiMessage class.
+*/
+
+#include "htimessage.h"
+#include "crc16.h"
+#include <memory.h>
+#include <crtdbg.h>
+#include <stdio.h>
+
+static const BYTE HTI_ERR_CMD = 0xFF;
+static const int HTI_MIN_ERR_MSG_SIZE = 10;
+static const int HTI_MAX_ERR_MSG_SIZE = 0xFF;
+
+
+HtiMessage::HtiMessage(DWORD serviceId, void* body, DWORD len, BYTE priority)
+{
+	m_ErrDescr = NULL;
+	m_Size = len + KMsgHeaderMinSize;
+	m_Message = new BYTE[m_Size];
+	//_RPT1(_CRT_WARN,"HtiMessage::HtiMessage %x\n", body);
+	//_RPT2(_CRT_WARN,"HtiMessage::HtiMessage m_Message %x <%d>\n", m_Message, m_Size);
+	memset(m_Message, 0, KMsgHeaderMinSize);
+	memcpy(m_Message + KMsgHeaderMinSize, body, len);
+	*((DWORD*)(m_Message + KMsgServiceNameOffset)) = serviceId;
+	*((DWORD*)(m_Message + KMsgBodySizeOffset)) = len;
+	m_Message[KMsgVersionOffset] = KDefaultVersion;
+	m_Message[KMsgPriorityOffset] = priority;
+	//CRC
+	*((WORD*)(m_Message + KMsgCrcOffset)) = CRC16CCITT(m_Message, KMsgHeaderMinSize-2);
+}
+
+HtiMessage::HtiMessage(void* message, DWORD len)
+{
+	m_ErrDescr = NULL;
+	BYTE* srcMsg = (BYTE*)message;
+    int extSize = srcMsg[KMsgExtSizeOffset];
+    int headerSize = MinHeaderSize() + extSize;
+
+    m_Size = *((DWORD*)(srcMsg + KMsgBodySizeOffset));
+	m_Size += headerSize;
+    
+    //allocate header space
+    m_Message = new BYTE[m_Size];
+	//_RPT1(_CRT_WARN,"HtiMessage::HtiMessage %x \n", message);
+	//_RPT2(_CRT_WARN,"HtiMessage::HtiMessage m_Message %x <%d>\n", m_Message, m_Size);
+    
+    //copy message
+	m_MessageReminderSize = m_Size;
+	AddToBody( message, len);
+	//memcpy( m_Message, message, min(m_MessageReminderSize, len) );
+	//m_MessageReminderSize -= min(m_MessageReminderSize, len);
+}
+
+DWORD HtiMessage::AddToBody(void* data, DWORD len)
+{
+	//_RPT1(_CRT_WARN,"HtiMessage::AddToBody %x\n", data);
+	DWORD copyLen = min(m_MessageReminderSize, len);
+	memcpy( m_Message + m_Size - m_MessageReminderSize, data, copyLen);
+	m_MessageReminderSize -= copyLen;
+	return copyLen;
+
+/*
+	if ( m_MessageReminderSize <= len) //last part
+	{
+		memcpy(m_Message + m_Size - m_MessageReminderSize, data, m_MessageReminderSize);
+		DWORD copyLen = m_MessageReminderSize;
+		m_MessageReminderSize = 0;
+		return copyLen;
+	}
+	else //in the middle
+	{
+		memcpy(m_Message + m_Size - m_MessageReminderSize, data, len);
+		m_MessageReminderSize -= len;
+	}
+
+	return len;
+*/
+}
+
+HtiMessage::~HtiMessage()
+{
+	//_RPT1(_CRT_WARN,"~HtiMessage err %x\n", m_ErrDescr);
+	//_RPT1(_CRT_WARN,"~HtiMessage msg %x\n", m_Message);
+	delete[] m_ErrDescr;
+	delete[] m_Message;
+}
+
+/**
+* Returns whole HTI message including header
+*/
+void* HtiMessage::HtiData()
+{
+	return m_Message;
+}
+
+DWORD HtiMessage::HtiDataSize()
+{
+	return m_Size;
+}
+
+DWORD HtiMessage::GetBodySize()
+{
+	return  *((DWORD*)(m_Message + KMsgBodySizeOffset));
+}
+
+DWORD HtiMessage::GetExtSize()
+{
+	return m_Message[KMsgExtSizeOffset];
+}
+
+int HtiMessage::GetBodyStart()
+{
+	return GetExtSize()+MinHeaderSize();
+}
+
+void* HtiMessage::GetBody()
+{
+	return m_Message+GetBodyStart();
+}
+
+DWORD HtiMessage::GetServiceUID()
+{
+	return *((DWORD*)(m_Message + KMsgServiceNameOffset));
+}
+
+bool HtiMessage::CheckValidHtiHeader(void* header)
+{
+	//check CRC16
+	WORD headerCrc16 = *((WORD*)((BYTE*)header+KMsgCrcOffset));
+	WORD calcCrc16 = CRC16CCITT(header, KMsgCrcOffset);
+
+	return headerCrc16 == calcCrc16;
+}
+
+DWORD HtiMessage::ExtractMsgSizeFromHeader(void* header)
+{
+	return *((DWORD*)(((BYTE*)header)+KMsgBodySizeOffset));
+}
+
+int HtiMessage::MinHeaderSize()
+{
+	return KMsgHeaderMinSize;
+}
+
+HtiMessage* HtiMessage::CreateErrorMessage(int errorCode, const char* errDescr)
+{
+	BYTE* msg = new BYTE[ HTI_MAX_ERR_MSG_SIZE ];
+	memset(msg, 0, HTI_MAX_ERR_MSG_SIZE );
+	msg[0] = HTI_ERR_CMD;
+	*((DWORD*)(msg + HtiServiceErrCodeOffset)) = errorCode;
+	*((DWORD*)(msg + HtiErrServiceUidOffset)) = HTI_SYSTEM_SERVICE_UID;
+	int descrLen = min(strlen( errDescr ), HTI_MAX_ERR_MSG_SIZE - HtiErrDescrOffset );
+	memcpy( msg + HtiErrDescrOffset,
+			errDescr,
+			descrLen
+			);
+	HtiMessage* newMsg = new HtiMessage(HTI_SYSTEM_SERVICE_UID,
+										msg,
+										descrLen + HtiErrDescrOffset + MinHeaderSize());
+	return newMsg;
+}
+
+bool HtiMessage::IsErrorMessage()
+{
+	if ( m_Message )
+	{
+		return GetServiceUID() == HTI_SYSTEM_SERVICE_UID &&
+		   m_Message[GetBodyStart()] == HTI_ERR_CMD &&
+		   GetBodySize()>= HTI_MIN_ERR_MSG_SIZE ;
+	}
+	return false;
+}
+
+int HtiMessage::HtiErrorCode()
+{
+	if ( IsErrorMessage() )
+	{
+		return m_Message[GetBodyStart()+HtiErrCodeOffset];
+	}
+	return -1;
+}
+int HtiMessage::ServiceErrorCode()
+{
+	if ( IsErrorMessage() )
+	{
+		return  *((DWORD*)(m_Message + GetBodyStart() + HtiServiceErrCodeOffset));
+	}
+	return -1;
+}
+
+char* HtiMessage::ErrorDescription()
+{
+	if ( IsErrorMessage() )
+	{
+		int desrLen = GetBodySize() - HtiErrDescrOffset;
+		m_ErrDescr = new char[desrLen+1];
+		//_RPT2(_CRT_WARN,"HtiMessage::ErrorDescription %x <%d>\n", m_ErrDescr, desrLen+1);
+		memcpy( m_ErrDescr,
+				m_Message + GetBodyStart() + HtiErrDescrOffset,
+				desrLen );
+		m_ErrDescr[desrLen] = 0;
+		return m_ErrDescr;
+	}
+	return NULL;
+}
+
+int HtiMessage::ErrorServiceUid()
+{
+	if ( IsErrorMessage() )
+	{
+		return  *((DWORD*)(m_Message + GetBodyStart() + HtiErrServiceUidOffset));
+	}
+	return -1;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/IPComm.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,518 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of the IPCommPlugin,
+*	IPCommReaderThread, IPCommWriterThread and IPCommMonitorThread classes.
+*/
+
+// INCLUDES
+#include "socket.h"
+#include "IPCommPlugin.h"
+#include "util.h"
+
+
+const static int g_IPMaxResendNumber = 2;
+
+//**********************************************************************************
+// Class IPCommPlugin
+//
+// This class implements a CommChannelPlugin which is used to communicate with device using TCP/IP
+//**********************************************************************************
+
+IPCommPlugin::IPCommPlugin(const CommChannelPluginObserver* observer)
+    : CommChannelPlugin(observer),
+      m_TxQueue(),
+      m_RxQueue(),
+	  m_PropertyLocalPort(0),
+	  m_PropertyRemotePort(0)
+{
+    m_MonitorThread = NULL;
+}
+
+IPCommPlugin::~IPCommPlugin()
+{
+    Util::Debug("IPCommPlugin::~IPCommPlugin()");
+    if (m_Open)
+    {
+        Close();
+    }
+    if (m_MonitorThread != NULL)
+    {
+        delete m_MonitorThread;
+        m_MonitorThread = NULL;
+    }
+}
+
+/*
+ * This method initializes IPCommPlugin and Starts IPCommMonitorThread
+ */
+DWORD IPCommPlugin::Init()
+{
+    Util::Debug("IPCommPlugin::Init()");
+
+    std::string filename = IP_INI_FILE_NAME;
+	map<string, string> IPCommPluginProperties;
+	Util::ReadProperties(filename.c_str(), IPCommPluginProperties);
+
+	CheckProperties(IPCommPluginProperties);
+
+    CommChannelPlugin::Init();
+
+	m_MonitorThread = new IPCommMonitorThread(&m_TxQueue,
+		                                      &m_RxQueue,
+											  m_PropertyLocalPort,
+											  m_PropertyRemoteHost,
+											  m_PropertyRemotePort,
+											  m_PropertyRecvBufferSize);
+
+	m_MonitorThread->Start();
+
+    Util::Debug("IPCommPlugin::Init() IPComm opened");
+    m_Open = true;
+    Util::Debug("IPCommPlugin::Init() OK");
+    return NO_ERRORS;
+}
+
+/*
+ * This method initializes class member variables from values in map
+ */
+void IPCommPlugin::CheckProperties(map<string, string>& props)
+{
+    char tmp[256];
+
+    // Local port
+    string val = props[IP_INI_LOCAL_PORT_PARAM];
+	Util::CheckCommandlineParam( PARAM_SWITCH_LOCAL_PORT_PARAM, val );
+    if (!val.empty())
+    {
+        m_PropertyLocalPort = atol(val.c_str());
+    }
+
+    // Receive TCP/IP buffer size
+    val = props[IP_INI_RECV_BUFFER_SIZE_PARAM];
+	Util::CheckCommandlineParam( PARAM_SWITCH_RECV_BUFFER_SIZE_PARAM, val );
+    if (!val.empty())
+    {
+        m_PropertyRecvBufferSize = atol(val.c_str());
+    }
+	else
+	{
+		// Use 8*1024 bytes (8KB) as default value
+		m_PropertyRecvBufferSize = 8*1024; 
+	}
+
+	if( m_PropertyLocalPort )
+	{
+		sprintf(tmp, "[IPComm] Local port : %d", m_PropertyLocalPort );
+		string s(tmp);
+		Util::Info(s);
+	}
+	else
+	{
+		// Remote host
+		m_PropertyRemoteHost = props[IP_INI_REMOTE_HOST_PARAM];
+		//Check and replace if -REMOTE_HOST was given as command line parameter
+		Util::CheckCommandlineParam( PARAM_SWITCH_REMOTE_HOST_PARAM, m_PropertyRemoteHost );
+		if(m_PropertyRemoteHost.empty())
+		{
+			throw "No remote host specified!";
+		}
+		sprintf(tmp, "[IPComm] Remote host : '%s'", m_PropertyRemoteHost.c_str());
+		string s = tmp;
+		Util::Info(s);
+
+		// Remote port
+		val = props[IP_INI_REMOTE_PORT_PARAM];
+		//Check and replace if -REMOTE_POST was given as command line parameter		
+		Util::CheckCommandlineParam( PARAM_SWITCH_REMOTE_PORT_PARAM, val );
+		if (!val.empty())
+		{
+			m_PropertyRemotePort = atol(val.c_str());
+		}
+		if( m_PropertyRemotePort == 0)
+			throw "Invalid remote port specified!";
+
+		sprintf(tmp, "[IPComm] Remote port : %d", m_PropertyRemotePort );
+		s = tmp;
+		Util::Info(s);
+	}
+}
+
+/*
+ * This method checks if data is available on incoming queue
+ */
+bool IPCommPlugin::IsDataAvailable()
+{
+    return (!m_RxQueue.empty());
+}
+
+/*
+ * This method is used to push given data to outgoing queue and then 
+ * wait for data to become available and read all data into single Data object 
+ */
+DWORD IPCommPlugin::SendReceive(Data* data_in, Data** data_out, long timeout)
+{
+    DWORD res;
+    if ((res = Send(data_in, timeout)) == NO_ERRORS &&
+        (res = ReceiveWait(data_out, timeout)) == NO_ERRORS)
+    {
+        return NO_ERRORS;
+    }
+    cout << "IPCommPlugin::SendReceive: error" << endl;
+    return res;
+}
+
+/*
+ * This method pushes the given Data object(of type Data::EData) to outgoing queue
+ */
+DWORD IPCommPlugin::Send(Data* data_in, long timeout)
+{
+    Data::DataType type = data_in->GetType();
+    if (type == Data::EData)
+    {
+        DWORD length = data_in->GetLength();
+        m_TxQueue.push(data_in);
+        return NO_ERRORS;
+    }
+    else if (type == Data::EControl)
+    {
+        Util::Debug("IPCommPlugin::Send: Control Message");
+        return NO_ERRORS;
+    }
+    return ERR_DG_COMM_DATA_SEND;
+}
+
+/*
+ * This method is used to wait for data to become available in incoming queue 
+ * and then read all data into single Data object which is given as parameter
+ */
+DWORD IPCommPlugin::ReceiveWait(Data** data_out, long timeout)
+{
+    long elapsed = 0;
+    while (elapsed < timeout && !IsDataAvailable())
+    {
+        elapsed += 25;
+        Sleep(25);
+    }
+    if (elapsed >= timeout)
+    {
+        return ERR_DG_COMM_DATA_RECV_TIMEOUT;
+    }
+    return Receive(data_out, timeout);
+}
+
+/*
+ * This method is used to read all data in incoming queue to single Data object and store the result
+ * to the data object given parameter
+ */
+DWORD IPCommPlugin::Receive(Data** data_out, long timeout)
+{
+    if (!m_RxQueue.empty())
+    {
+		*data_out = m_RxQueue.front();
+        m_RxQueue.pop();
+        return NO_ERRORS;
+    }
+    return ERR_DG_COMM_DATA_RECV;
+}
+
+
+DWORD IPCommPlugin::Open()
+{
+    return (m_Open ? NO_ERRORS : ERR_DG_COMM_OPEN);
+}
+
+DWORD IPCommPlugin::Close()
+{
+    m_MonitorThread->Stop();
+    WaitForSingleObject(m_MonitorThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+    return NO_ERRORS;
+}
+
+
+//**********************************************************************************
+// Class IPCommReaderThread
+//
+// This thread is used to read bytes from TCP/IP socket, encapsulate the bytes to Data objects 
+// and push them to incoming queue 
+//**********************************************************************************
+
+IPCommReaderThread::IPCommReaderThread(SafeQueue<Data*>* q,
+                                       long bufsize)
+	:m_Running(false),
+    m_Socket(NULL)
+{
+	m_Queue = q;
+	m_TcpIpBufferSize = bufsize;
+}
+
+/*
+ * Main execution loop which reads bytes from socket, encapsulates the bytes to Data object and pushes them to incoming queue
+ */	
+void IPCommReaderThread::Run()
+{
+	if( m_Socket )
+		m_Running = true;
+
+	BYTE* buffer = new BYTE[m_TcpIpBufferSize];
+	while (m_Running)
+	{
+		// Reading from TCP/IP port
+		//Util::Debug("[IPCommReaderThread] try to read");
+		int bytes_read = -1;
+		bytes_read = m_Socket->ReceiveBytes(buffer, m_TcpIpBufferSize);
+		if (bytes_read < 0)
+		{
+			Stop();
+			break;
+		}
+		if (bytes_read > 0)
+		{
+			Data* d = new Data((void *)buffer, bytes_read, Data::EData);
+			if (Util::GetVerboseLevel() == Util::VerboseLevel::debug)
+			{
+				char tmp[64];
+				sprintf(tmp, "m_Socket->ReceiveBytes (%d (dec) bytes):", d->GetLength());
+				string s(tmp);
+				Util::Debug(s);
+			}
+			m_Queue->push(d);
+			d = NULL;
+		}
+		Sleep(0);
+	}
+	delete[] buffer;
+	buffer = NULL;
+}
+
+void IPCommReaderThread::Stop()
+{
+	m_Running = false;
+}
+
+bool IPCommReaderThread::IsRunning()
+{
+	return m_Running;
+}
+
+
+
+//**********************************************************************************
+// Class DataGatewaySocketWriterThread
+//
+// This thread is used to write data from outgoing queue to TCP/IP socket
+//**********************************************************************************
+
+IPCommWriterThread::IPCommWriterThread(SafeQueue<Data*>* q)
+	:m_Running(false),
+	m_Socket(NULL)
+{
+	m_Queue = q;
+}
+
+/*
+ * This method contains the main execution loop which gets Data from outgoing queue and sends it to socket
+ */
+void IPCommWriterThread::Run()
+{
+	if( m_Socket )
+		m_Running = true;
+
+	while (m_Running)
+	{
+		// Sending to TCP/IP port
+		//Util::Debug("[IPCommWriterThread] try to send");
+		try
+		{
+			Data* d = m_Queue->front(50);
+			char* p = (char *)d->GetData();
+			DWORD l = d->GetLength();
+
+			if (Util::GetVerboseLevel() == Util::VerboseLevel::debug)
+			{
+				char tmp[64];
+				sprintf(tmp, "[IPCommWriterThread] HTI MsgSize = %d", l);
+				string s(tmp);
+				Util::Debug(s);
+			}
+
+			m_Socket->SendBytes((const unsigned char *)p, l);
+			m_Queue->pop();
+			delete d;
+			d = NULL;
+
+		} catch (TimeoutException te)
+		{
+		//Util::Debug("[IPCommWriterThread]timeout exception");
+		}
+	}
+}
+
+void IPCommWriterThread::Stop()
+{
+	m_Running = false;
+}
+
+bool IPCommWriterThread::IsRunning()
+{
+	return m_Running;
+}
+
+
+//**********************************************************************************
+// Class IPCommMonitorThread
+//
+// This thread creates and starts reader and writer threads
+// The thread also monitors if reader and writer threads are running and restarts them in case either isn't running
+//**********************************************************************************
+
+IPCommMonitorThread::IPCommMonitorThread(SafeQueue<Data*>* TxQueue,
+										 SafeQueue<Data*>* RxQueue,
+										 int LocalPort,
+                                         string& RemoteHost,
+                                         int RemotePort,
+										 long RecvBufferSize)
+	: m_Running(false),
+	m_TxQueue(TxQueue),
+	m_RxQueue(RxQueue),
+	m_ReaderThread(NULL),
+	m_WriterThread(NULL),
+	m_LocalPort(LocalPort),
+    m_RemoteHost(RemoteHost),
+	m_RemotePort(RemotePort),
+	m_RecvBufferSize(RecvBufferSize)
+{
+}
+
+IPCommMonitorThread::~IPCommMonitorThread()
+{
+	if(m_ReaderThread)
+	{
+		delete m_ReaderThread;
+		m_ReaderThread = NULL;
+	}
+	if(m_WriterThread)
+	{
+		delete m_WriterThread;
+		m_WriterThread = NULL;
+	}
+}
+
+/*
+ * This method has two functionalities
+ * -It waits for incoming connections if local port is defined
+ * -It tries to connect to remote host if local host is not defined
+ */
+void IPCommMonitorThread::Connect(Socket*& s)
+{
+	// This trickery here is because if there are no sockets (Socket::nofSockets_)
+	// WSACleanup gets called and then SOAP gets messed up.
+	// And creating a new socket for a new connection seems to work better
+	// than using the old when re-connecting / re-listening.
+	Socket* new_s = new Socket();
+	delete s;
+	s = new_s;
+
+	// If local port is defined start open listening socket
+	SocketServer ss;
+	if( m_LocalPort )
+	{
+		Util::Info("[IPComm] Listen for incoming connection...");
+		String remoteHost( "[IPComm] Connected! Remote host : " );
+		ss.Accept( s, m_LocalPort, 1, remoteHost );
+		Util::Info(remoteHost);
+	}
+	// If not start connecting
+	else
+	{
+		Util::Info("[IPComm] Connecting...");
+		ss.Connect( s, m_RemoteHost.c_str(), m_RemotePort );
+		Util::Info("[IPComm] Connected!");
+	}
+}
+
+/*
+ * Main execution loop of thread
+ * -Creates reader and writer threads and starts them
+ * -Monitors if either reader or writer thread aren't running and restarts them if not
+ */
+void IPCommMonitorThread::Run()
+{
+	Socket* s = NULL;
+
+	m_ReaderThread = new IPCommReaderThread( m_RxQueue, m_RecvBufferSize );
+	m_WriterThread = new IPCommWriterThread( m_TxQueue ) ;
+
+	m_Running = true;
+	while (m_Running)
+	{
+		// Reader thread should stop running when connection is lost
+		if( !m_ReaderThread->IsRunning() || !m_WriterThread->IsRunning() )
+		{
+			Util::Info( "[IPComm] Disconnected!" );
+
+			// Stop the treads
+			m_ReaderThread->Stop();
+		    WaitForSingleObject(m_ReaderThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+			m_WriterThread->Stop();
+			WaitForSingleObject(m_WriterThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+
+			// Try to connect again.
+			BOOL connected = false;
+			while( m_Running && connected == false)
+			{
+				try{
+					Connect(s);
+					connected = true;
+					m_ReaderThread->m_Socket = s;
+					m_WriterThread->m_Socket = s;
+
+					// Start threads
+					m_ReaderThread->Start();
+					m_WriterThread->Start();
+					SetThreadPriority( m_ReaderThread->ThreadHandle(), THREAD_PRIORITY_LOWEST);
+					int priority = GetThreadPriority(m_ReaderThread->ThreadHandle());
+					int i = 0;
+				}
+				catch( char* ){
+					Sleep(1000);
+				}
+			}
+		}
+		Sleep(1000);
+	}
+
+	// Stop the treads
+	m_ReaderThread->Stop();
+	WaitForSingleObject(m_ReaderThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+	m_WriterThread->Stop();
+	WaitForSingleObject(m_WriterThread->ThreadHandle(), g_MaximumShutdownWaitTime);
+	// and close the current socket
+	if( s )
+		delete s;
+}
+
+void IPCommMonitorThread::Stop()
+{
+	m_Running = false;
+	m_ReaderThread->Stop();
+	m_WriterThread->Stop();
+}
+
+bool IPCommMonitorThread::IsRunning()
+{
+	return m_Running;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/SOAPHandler.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,482 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implementation of SOAPHandler class
+*/
+
+#include "stdsoap2.h" //should be first because of WinSock2.h errors
+
+#include "SOAPHandler.h"
+#include "HtiMessage.h"
+
+#include "datagateway.h" //for htidispatcher
+#include "util.h"
+
+#include <sstream>
+
+SOAP_NMAC struct Namespace namespaces_l[] =
+{
+	{"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", "http://www.w3.org/*/soap-envelope", NULL},
+	{"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", "http://www.w3.org/*/soap-encoding", NULL},
+	{"xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance", NULL},
+	{"xsd", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/*/XMLSchema", NULL},
+	{"ns1", "urn:hti", NULL, NULL},
+	{NULL, NULL, NULL, NULL}
+};
+
+//**********************************************************************************
+// Class SOAPHandler
+//
+// This class is used to handle SOAP requests, send HtiMessages 
+// and handle HTI responses by using loaded HtiPluginDll
+//**********************************************************************************
+SoapHandler::SoapHandler(const string& pluginName)
+	: m_PluginName(pluginName),
+	  m_Running(false),
+	  m_HtiDispatcher(NULL),
+	  m_SoapEnv(NULL),
+	  m_ReceiveHtiMsg(NULL)
+{
+	m_hReceiveHtiEvent = CreateEvent(NULL, //sec att
+								  FALSE, //not manual-reset
+								  FALSE, //initial state non-signaled
+								  NULL //name
+								  );
+	m_hReceiveSoapEvent = CreateEvent(NULL, //sec att
+								  FALSE, //not manual-reset
+								  FALSE, //initial state non-signaled
+								  NULL //name
+								  );
+
+	m_hHandlerCanAcceptSoapRequest = CreateEvent(NULL, //sec att
+								  TRUE, //manual-reset
+								  TRUE, //initial state signaled
+								  NULL //name
+								  );
+
+	m_hHandlerCanAcceptHtiMessage = CreateEvent(NULL, //sec att
+								  TRUE, //manual-reset
+								  TRUE, //initial state signaled
+								  NULL //name
+								  );
+
+	m_hHandlerWaitsHtiMessage = CreateEvent(NULL, //sec att
+								  TRUE, //manual-reset
+								  FALSE, //initial state non-signaled
+								  NULL //name
+								  );
+
+
+	m_HtiPlugin = new HtiPluginDll();
+}
+
+SoapHandler::~SoapHandler()
+{
+	Stop();
+	CloseHandle(m_hHandlerWaitsHtiMessage);
+	CloseHandle(m_hHandlerCanAcceptSoapRequest);
+	CloseHandle(m_hHandlerCanAcceptHtiMessage);
+	CloseHandle(m_hReceiveHtiEvent);
+	CloseHandle(m_hReceiveSoapEvent);
+	CleanSoapEnv();
+	delete m_HtiPlugin;
+}
+
+void SoapHandler::CleanSoapEnv()
+{
+	if ( m_SoapEnv )
+	{
+		soap_destroy(m_SoapEnv); // dealloc C++ data 
+		soap_end(m_SoapEnv); // dealloc data and clean up 
+		soap_done(m_SoapEnv); // detach soap struct 
+		free(m_SoapEnv);
+		m_SoapEnv = NULL;
+	}
+}
+
+/**
+ * This loop waits until either a SOAP request or HTI response event has arrived
+ * When one of them arrives, it is handled and the loop starts again to wait
+ * for a new request or response
+ */
+void SoapHandler::Run()
+{
+	Util::Debug("SoapHandler::Run()");
+	HANDLE events[2];
+	events[0] = m_hReceiveSoapEvent;
+	events[1] = m_hReceiveHtiEvent;
+	m_Running = true;
+	while (m_Running)
+	{
+		Util::Debug("SoapHandler::Run::WaitForMultipleObjects");
+		DWORD r = WaitForMultipleObjects(
+						2,
+						events,
+                        FALSE, //don't wait all
+						LOOP_WAIT_INTERVAL);
+		switch (r)
+		{
+		case WAIT_OBJECT_0:
+			{
+				//process soap request
+				ResetEvent(m_hHandlerCanAcceptSoapRequest);
+				ResetEvent(m_hHandlerCanAcceptHtiMessage);
+				DoServeSoap();
+				SetEvent(m_hHandlerCanAcceptSoapRequest);
+				SetEvent(m_hHandlerCanAcceptHtiMessage);
+			}
+			break;
+		case WAIT_OBJECT_0+1:
+			{
+				//process HTI response
+				ResetEvent(m_hHandlerCanAcceptSoapRequest);
+				ResetEvent(m_hHandlerCanAcceptHtiMessage);
+				ProcessHtiResponse();
+				SetEvent(m_hHandlerCanAcceptSoapRequest);
+				SetEvent(m_hHandlerCanAcceptHtiMessage);
+			}
+			break;
+		case WAIT_TIMEOUT:
+			{
+				//do nothing
+				//just check for m_Running and waits again
+			}
+			break;
+		default:
+			{
+			}
+		}
+	}
+}
+
+void SoapHandler::Stop()
+{
+	m_Running = false;
+}
+
+/**
+ * wait for hti message
+ * Suspend thread until HtiMessage for the loaded plug-in is received
+ * Return true if hti message is received or false if timeout
+ */
+bool SoapHandler::WaitForHtiMessage(DWORD timeout)
+{
+	SetEvent(m_hHandlerCanAcceptHtiMessage);
+	SetEvent(m_hHandlerWaitsHtiMessage);
+	//delete m_ReceiveHtiMsg;
+	Util::Debug("SoapHandler::WaitForHtiMessage");
+	DWORD r = WaitForSingleObject(m_hReceiveHtiEvent, timeout);
+
+	ResetEvent(m_hHandlerCanAcceptHtiMessage);
+	ResetEvent(m_hHandlerWaitsHtiMessage);
+	switch ( r )
+	{
+	case WAIT_OBJECT_0:
+		{
+			return true;
+		}
+		break;
+	case WAIT_TIMEOUT:
+		{
+		}
+		break;
+	default:
+		{
+		}
+	}
+	Util::Debug("WaitForHtiMessage OK");
+	return false;
+}
+
+/**
+ * This method is used to init HtiPluginDll
+ */
+bool SoapHandler::LoadPlugin()
+{
+	//code to load and init plugin dll m_PluginName
+	return m_HtiPlugin->Init( m_PluginName.c_str() );
+}
+
+/**
+ * This method tells whether or not this handler is currently busy processing request
+ */
+bool SoapHandler::IsBusyForSoapRequest()
+{
+	DWORD r = WaitForSingleObject(m_hHandlerCanAcceptSoapRequest, LOOP_CHECK_INTERVAL);
+	switch ( r )
+	{
+	case WAIT_OBJECT_0:
+		{
+			return false;
+		}
+		break;
+	case WAIT_TIMEOUT:
+		{
+		}
+		break;
+	default:
+		{
+		}
+	}
+	return true;
+}
+
+/**
+ * This method tells whether or not this handler is currently busy processing hti message
+ */
+bool SoapHandler::IsBusyForHtiMessage()
+{
+	DWORD r = WaitForSingleObject(m_hHandlerCanAcceptHtiMessage, LOOP_CHECK_INTERVAL);
+	switch ( r )
+	{
+	case WAIT_OBJECT_0:
+		{
+			return false;
+		}
+		break;
+	case WAIT_TIMEOUT:
+		{
+		}
+		break;
+	default:
+		{
+		}
+	}
+	return true;
+}
+
+/*
+ * This method is used to check if SoapHandler is currently waiting for Hti Message
+ */
+bool SoapHandler::IsWaitsForHtiMessage()
+{
+	DWORD r = WaitForSingleObject(m_hHandlerWaitsHtiMessage, LOOP_CHECK_INTERVAL);
+	switch ( r )
+	{
+	case WAIT_OBJECT_0:
+		{
+			return true;
+		}
+		break;
+	case WAIT_TIMEOUT:
+		{
+		}
+		break;
+	default:
+		{
+		}
+	}
+	return false;
+}
+
+/**
+ * Just a wrapper around soap_serve() created by gSOAP
+ * called by DataGatewaySOAPServerThread for a new SOAP request
+ * return true if request can be processed
+ * This method sets m_hReceiveSoapEvent to signaled state
+ * Run method waits this event object and then handles the soap request when the event switches to signaled state
+ */
+bool SoapHandler::ServeSoap(struct soap* soapEnv)
+{
+	Util::Debug("SoapHandler::ServeSoap");
+	//check can this handler process request in soapEnv
+	if ( !IsBusyForSoapRequest() )
+	{
+		CleanSoapEnv();
+		m_SoapEnv = soap_copy(soapEnv);
+		//soap_free( soapEnv );
+		m_SoapEnv->user = dynamic_cast<HtiSoapHandlerInterface*>( this );
+		SetEvent(m_hReceiveSoapEvent);
+		Util::Debug("SoapHandler::ServeSoap OK");
+		return true;
+	}
+	else
+	{
+		Util::Debug("SoapHandler::ServeSoap NOK");
+		return false;
+	}
+}
+
+/**
+ * This method is called when incoming Hti message has been read from CommChannelPlugin
+ * The method sets m_hReceiveHtiEvent to signaled state(Run method waits this event object to become signaled)
+ */
+bool SoapHandler::ReceiveHtiMessage(HtiMessage* htiMessage)
+{
+	Util::Debug("SoapHandler::ReceiveHtiMessage");
+	//_RPT0(_CRT_WARN, "SoapHandler::ReceiveHtiMessage");
+	//check can this handler process HTI response
+	if ( !IsBusyForHtiMessage() )
+	{
+		//_RPT1(_CRT_WARN, "delete %x\n", m_ReceiveHtiMsg);
+		//_RPT1(_CRT_WARN, "received %x\n", htiMessage);
+		ResetEvent(m_hHandlerCanAcceptHtiMessage);
+		delete m_ReceiveHtiMsg;
+		m_ReceiveHtiMsg = htiMessage;
+		SetEvent(m_hReceiveHtiEvent);
+		Util::Debug("SoapHandler::ReceiveHtiMessage OK");
+		return true;
+	}
+	Util::Debug("SoapHandler::ReceiveHtiMessage NOK");
+	return false;
+}
+
+/**
+* Actual SOAP request processing in the thread
+* if it was accepted in ServeSoap()
+* The request is processed using HtiPluginDll
+*/
+void SoapHandler::DoServeSoap()
+{
+	Util::Debug("SoapHandler::DoServeSoap");
+	soap_set_namespaces( m_SoapEnv, m_HtiPlugin->serviceNamespaces()); 
+	//soap_set_namespaces( m_SoapEnv, namespaces_l);
+
+	if (soap_envelope_begin_in(m_SoapEnv)
+		|| soap_recv_header(m_SoapEnv)
+		|| soap_body_begin_in(m_SoapEnv) )
+	{
+		//soap_set_namespaces( m_SoapEnv, namespaces_l);
+		soap_send_fault(m_SoapEnv);
+		Util::Debug("SoapHandler::DoServeSoap NOK");
+		return;
+	}
+
+	//call soap_serve(soap_server_request) from the dll plug-in
+	//m_HtiPlugin->soap_serve( m_SoapEnv );
+	
+	if (m_HtiPlugin->soap_serve_request(m_SoapEnv)
+		|| (m_SoapEnv->fserveloop && m_SoapEnv->fserveloop(m_SoapEnv)))
+	{
+		//soap_set_namespaces( m_SoapEnv, namespaces_l);
+		soap_send_fault(m_SoapEnv);
+		Util::Debug("SoapHandler::DoServeSoap NOK");
+		return;
+	}
+	
+	CleanSoapEnv();
+	Util::Debug("SoapHandler::DoServeSoap OK");
+}
+
+/*
+ * HtiPluginDll's call this method
+ * It creates a HtiMessage of the data given as parameters and sends it using HtiDispatcher
+ */
+void SoapHandler::SendHtiMessage( DWORD serviceId, void* body, DWORD len )
+{
+	Util::Debug("SoapHandler::SendHtiMessage");
+	HtiMessage* msg = new HtiMessage(serviceId, body, len);
+	//_RPT2(_CRT_WARN, "send msg %x <%d>\n", msg, sizeof(HtiMessage));
+	m_HtiDispatcher->SendHtiMessage( msg );
+	//_RPT2(_CRT_WARN, "del send msg %x <%d>\n", msg, sizeof(HtiMessage));
+	delete msg;
+	Util::Debug("SoapHandler::SendHtiMessage OK");
+}
+
+/*
+ * HtiPluginDll's call this method
+ * It creates a HtiMessage of the data given as parameters and sends it using HtiDispatcher
+ */
+void SoapHandler::SendHtiMessage( DWORD serviceId, void* body, DWORD len, BYTE priority )
+{
+	Util::Debug("SoapHandler::SendHtiMessage");
+	//delegate function to dispatcher
+	HtiMessage* msg = new HtiMessage(serviceId, body, len, priority);
+	//_RPT2(_CRT_WARN, "send msg %x <%d>\n", msg, sizeof(HtiMessage));
+	m_HtiDispatcher->SendHtiMessage( msg );
+	//_RPT2(_CRT_WARN, "del send msg %x <%d>\n", msg, sizeof(HtiMessage));
+	delete msg;
+	Util::Debug("SoapHandler::SendHtiMessage OK");
+}
+
+int SoapHandler::ReceivedHtiMessageBodySize()
+{
+	if ( m_ReceiveHtiMsg )
+	{
+		return m_ReceiveHtiMsg->GetBodySize();
+	}
+	return -1;
+}
+
+void* SoapHandler::ReceivedHtiMessageBody()
+{
+	if ( m_ReceiveHtiMsg )
+	{
+		return m_ReceiveHtiMsg->GetBody();
+	}
+	return NULL;
+}
+
+bool SoapHandler::IsReceivedHtiError()
+{
+	if ( m_ReceiveHtiMsg )
+	{
+		return m_ReceiveHtiMsg->IsErrorMessage();
+	}
+	return false;
+}
+
+int SoapHandler::HtiErrorCode()
+{
+	if ( m_ReceiveHtiMsg )
+	{
+		return m_ReceiveHtiMsg->HtiErrorCode();
+	}
+	return -1;
+}
+
+int SoapHandler::HtiServiceErrorCode()
+{
+	if ( m_ReceiveHtiMsg )
+	{
+		return m_ReceiveHtiMsg->ServiceErrorCode();
+	}
+	return -1;
+}
+
+char* SoapHandler::HtiServiceErrorDerscription()
+{
+	if ( m_ReceiveHtiMsg )
+	{
+		return m_ReceiveHtiMsg->ErrorDescription();
+	}
+	return NULL;
+}
+
+void SoapHandler::SendSoapFaultFromReceivedHtiError()
+{
+	if ( m_SoapEnv && IsReceivedHtiError() )
+	{
+        stringstream s;
+		s<<"<htiError xmlns=\'urn:hti/fault\'><frameworkErrorCode>";
+        s<<m_ReceiveHtiMsg->HtiErrorCode();
+		s<<"</frameworkErrorCode><serviceErrorCode>";
+		s<<m_ReceiveHtiMsg->ServiceErrorCode();
+		s<<"</serviceErrorCode><serviceErrorDescription>";
+		s<<m_ReceiveHtiMsg->ErrorDescription();
+		s<<"</serviceErrorDescription>";
+		s<<"</htiError>";
+		
+		soap_receiver_fault(m_SoapEnv,
+			"HtiError", s.str().c_str() );
+	}
+}
+
+/**
+ * This method makes HtiPluginDll process HTI response 
+ */
+void SoapHandler::ProcessHtiResponse()
+{
+	m_HtiPlugin->hti_serve( dynamic_cast<HtiSoapHandlerInterface*>( this ) );
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/SerialComm.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,714 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implementation of SerialComm communication channel plugin objects. These classes are SerialComm, SerialCommPlugin and
+*	SerialCommIoThread classes.
+*/
+
+// INCLUDES
+#include "SerialCommPlugin.h"
+#include "util.h"
+
+#define HIGH_COM_PORT "\\\\.\\"
+const static int g_SerialMaxResendNumber = 2;
+
+//**********************************************************************************
+// Class SerialCommPlugin
+//
+// This class implements a CommChannelPlugin used in serial communication with device
+//**********************************************************************************
+
+SerialCommPlugin::SerialCommPlugin(const CommChannelPluginObserver* observer)
+    : CommChannelPlugin(observer),
+      m_TxQueue(),
+      m_RxQueue(),
+      m_PropertySerialCommTimeout(g_SerialCommDefaultTimeout),
+	  m_PropertySerialMaxSendSize(0),
+	  m_ProperySerialSendPause(0),
+	  m_PropertySerialHwFlowControl(false)
+{
+    m_IoThread = NULL;
+}
+
+SerialCommPlugin::~SerialCommPlugin()
+{
+    Util::Debug("SerialCommPlugin::~SerialCommPlugin()");
+    if ( m_Open )
+    {
+        Close();
+    }
+    if ( m_IoThread != NULL )
+    {
+        delete m_IoThread;
+        m_IoThread = NULL;
+    }
+}
+
+/*
+ * This method initializes SerialCommPlugin and starts SerialCommPluginIoThread
+ */
+DWORD SerialCommPlugin::Init()
+{
+    Util::Debug("SerialCommPlugin::Init()");
+
+    std::string filename = SERIAL_INI_FILE_NAME;
+	//read properties from serialplugin.ini file
+	Util::ReadProperties(filename.c_str(), m_SerialCommPluginProperties);
+    
+	CheckProperties(m_SerialCommPluginProperties);
+
+    CommChannelPlugin::Init();
+
+    m_IoThread = new SerialCommIoThread(
+						&m_RxQueue,
+						&m_TxQueue,
+                        m_PropertySerialCommInitString,
+						m_PropertySerialCommPort,
+						m_PropertySerialCommTimeout,
+						m_PropertySerialHwFlowControl,
+						m_ProperySerialSendPause,
+						m_PropertySerialMaxSendSize
+						);
+
+	m_IoThread->Start();
+
+	Event e = m_IoThread->GetOpenedEvent();
+    if ( e.Wait(m_PropertySerialCommTimeout) == WAIT_TIMEOUT )
+    {
+        Util::Debug("SerialCommPlugin::Init()   SerialComm opening timed out");
+        m_Open = false;
+        return ERR_DG_COMM_OPEN_TIMEOUT;
+    }
+    Util::Debug("SerialCommPlugin::Init() SerialComm opened");
+    m_Open = true;
+    Util::Debug("SerialCommPlugin::Init() OK");
+    return NO_ERRORS;
+}
+
+/*
+ * This method initializes class member variables from values in map
+ */
+void SerialCommPlugin::CheckProperties(map<string, string>& props)
+{
+    char tmp[256];
+
+    // Init values for connection
+    m_PropertySerialCommInitString = props[SERIAL_INI_INIT_PARAM];
+	Util::CheckCommandlineParam( PARAM_SWITCH_INIT_PARAM, m_PropertySerialCommInitString );
+    if ( m_PropertySerialCommInitString.empty() )
+    {
+        m_PropertySerialCommInitString = SERIAL_DEFAULT_INIT_STRING;
+    }
+    sprintf_s(tmp, 256, "Connection Init : '%s'", m_PropertySerialCommInitString.c_str());
+    string s(tmp);
+    Util::Debug(s);
+
+    // comm port
+    m_PropertySerialCommPort = props[SERIAL_INI_COMPORT_PARAM];
+	Util::CheckCommandlineParam( PARAM_SWITCH_COMPORT_PARAM, m_PropertySerialCommPort );
+    if ( m_PropertySerialCommPort.empty() )
+    {
+        m_PropertySerialCommPort = SERIAL_DEFAULT_COMPORT;
+    }
+    sprintf_s(tmp, 256, "Connection port : '%s'", m_PropertySerialCommPort.c_str());
+    s = tmp;
+    Util::Debug(s);
+
+    // Serial operations timeout
+    string val = props[SERIAL_INI_COMPORT_TIMEOUT];
+	Util::CheckCommandlineParam( PARAM_SWITCH_COMPORT_TIMEOUT, val );
+	m_PropertySerialCommTimeout = 0;
+    if ( !val.empty() )
+    {
+        m_PropertySerialCommTimeout = atol(val.c_str());
+    }
+
+    if ( m_PropertySerialCommTimeout <= 0 )
+    {
+        m_PropertySerialCommTimeout = g_SerialCommDefaultTimeout;
+    }
+	sprintf_s(tmp, 256, "Timeout: '%d'", m_PropertySerialCommTimeout);
+    s = tmp;
+    Util::Debug(s);
+
+	// flow control
+	m_PropertySerialHwFlowControl = false;
+	val = props[SERIAL_INI_USE_HW_FLOW_CONTROL];
+	Util::CheckCommandlineParam( PARAM_SWITCH_USE_HW_FLOW_CONTROL, val );
+	if ( !val.empty() && val == "1" )
+	{
+		m_PropertySerialHwFlowControl = true;
+		Util::Debug("Use serial HW flow control");
+	}
+	else
+	{
+		Util::Debug("Do not use serial HW flow control");
+	}
+
+	// send pause
+	val = props[SERIAL_INI_SEND_SLEEP_PAUSE];
+	Util::CheckCommandlineParam( PARAM_SWITCH_SEND_SLEEP_PAUSE, val );
+    if ( !val.empty() )
+    {
+        m_ProperySerialSendPause = atol(val.c_str());
+    }
+    if ( m_ProperySerialSendPause <= 0 )
+    {
+        m_ProperySerialSendPause = g_SerialCommDefaultSendPause;
+    }
+	sprintf_s(tmp, 256, "Send pause: '%d'", m_ProperySerialSendPause);
+    s = tmp;
+    Util::Debug(s);
+
+	// send size
+	val = props[SERIAL_INI_SEND_SIZE];
+	Util::CheckCommandlineParam( PARAM_SWITCH_SEND_SIZE, val );
+    if ( !val.empty() )
+    {
+        m_PropertySerialMaxSendSize = atol(val.c_str());
+    }
+    if ( m_PropertySerialMaxSendSize <= 0 )
+    {
+        m_PropertySerialMaxSendSize = 0;
+    }
+	sprintf_s(tmp, 256, "Send max size: '%d'", m_PropertySerialMaxSendSize);
+    s = tmp;
+    Util::Debug(s);
+}
+
+/*
+ * This method checks if data is available on incoming queue
+ */
+bool SerialCommPlugin::IsDataAvailable()
+{
+    return ( !m_RxQueue.empty() );
+}
+
+/*
+ * This method is used to:
+ * -push given data to outgoing queue
+ * -wait for data to become available in incoming queue
+ * -pop the first Data object from queue and store it to the Data object given as parameter
+ */
+DWORD SerialCommPlugin::SendReceive(Data* data_in, Data** data_out, long timeout)
+{
+    DWORD res;
+    if ( ( res = Send(data_in, timeout)) == NO_ERRORS &&
+         ( res = ReceiveWait(data_out, timeout)) == NO_ERRORS )
+    {
+        return NO_ERRORS;
+    }
+    cout << "SerialCommPlugin::SendReceive: error" << endl;
+    return res;
+}
+
+/*
+ * This method pushes the given Data object(of type Data::EData) to outgoing queue
+ */
+DWORD SerialCommPlugin::Send(Data* data_in, long timeout)
+{
+    Data::DataType type = data_in->GetType();
+    if ( type == Data::EData )
+    {
+        DWORD length = data_in->GetLength();
+        m_TxQueue.push(data_in);
+        return NO_ERRORS;
+    }
+    else if ( type == Data::EControl )
+    {
+        Util::Debug("SerialCommPlugin::Send: Control Message Received");
+        return NO_ERRORS;
+    }
+    return ERR_DG_COMM_DATA_SEND;
+}
+
+/*
+ * This method is used to wait for data to become available in incoming queue 
+ * and then pop the first Data object from the queue and and store it to Data object given as parameter.
+ */
+DWORD SerialCommPlugin::ReceiveWait(Data** data_out, long timeout)
+{
+    long elapsed = 0;
+    while (elapsed < timeout && !IsDataAvailable())
+    {
+        elapsed += 25;
+        Sleep(25);
+    }
+    if ( elapsed >= timeout )
+    {
+        return ERR_DG_COMM_DATA_RECV_TIMEOUT;
+    }
+    return Receive(data_out, timeout);
+}
+
+/*
+ * This method is used to pop the first data object from incoming queue and store it to data object given as parameter
+ */
+DWORD SerialCommPlugin::Receive(Data** data_out, long timeout)
+{
+    if ( !m_RxQueue.empty() )
+    {
+        *data_out = m_RxQueue.front();
+        m_RxQueue.pop();
+        return NO_ERRORS;
+    }
+    return ERR_DG_COMM_DATA_RECV;
+}
+
+
+DWORD SerialCommPlugin::Open()
+{
+    return ( m_Open ? NO_ERRORS : ERR_DG_COMM_OPEN );
+}
+
+/*
+ * This method stops SerialCommIoThread and waits for it to be in signaled state
+ */
+DWORD SerialCommPlugin::Close()
+{
+    m_IoThread->Stop();
+    WaitForSingleObject( m_IoThread->ThreadHandle(), g_MaximumShutdownWaitTime );
+    return NO_ERRORS;
+}
+
+//**********************************************************************************
+// Class SerialComm
+//
+// This class implements the actual serial communication using Windows API
+//**********************************************************************************
+
+SerialComm::SerialComm()
+    : m_Open(false),
+	m_SendPause(0),
+	m_SendMaxSize(0)
+{
+
+}
+
+SerialComm::~SerialComm()
+{
+    Util::Debug("SerialComm::~SerialComm()");
+    if ( m_Open )
+    {
+        Close();
+    }
+}
+/*
+ * This method opens a communication device that uses serial communication and
+ * configures it according initialization parameters
+ */
+WORD SerialComm::Open( const string& commPort, const string& initParameters,
+					   long timeout,
+					   bool hwFlowControl, long sendPause, long sendMaxSize)
+{
+    Util::Debug("SerialComm::Open()");
+
+	m_SendPause = sendPause;
+
+	if ( sendMaxSize>0 )
+	{
+		m_SendMaxSize = sendMaxSize;
+	}
+
+	DWORD err;
+	//check commPort and add "\\.\" prefix if port is larger than 9
+	string localCommPort(commPort);
+	static const basic_string <char>::size_type npos = -1;
+	if ( localCommPort.find(HIGH_COM_PORT) == npos &&
+		 localCommPort.find("COM") == 0 &&
+		 localCommPort.length() > 4 //two digit port number
+	   )
+	{
+		localCommPort.insert(0, HIGH_COM_PORT);
+	}
+	Util::Debug(localCommPort.c_str());
+
+    // If COM-port opening fails, it's retried until HtiGateway is killed.
+    m_Com = INVALID_HANDLE_VALUE;
+    while ( m_Com == INVALID_HANDLE_VALUE )
+    {
+	    // Open file (COM port)
+	    m_Com = CreateFile( localCommPort.c_str(),
+					    GENERIC_READ | GENERIC_WRITE,
+					    0, //excusive access
+					    NULL, //no security
+					    OPEN_EXISTING, //must use
+					    0, //not overlapped i/o
+					    NULL // must be NULL for comm
+					    );
+
+	    if ( m_Com == INVALID_HANDLE_VALUE )
+	    {
+		    err = GetLastError();
+            Util::Error("[SerialComm] Failed to open COM port", err);
+            Util::Info("[SerialComm] Retrying...");
+            Sleep(5000);
+        }
+    }
+
+    // Serial port cfg
+	Util::Debug(initParameters.c_str());
+	DCB dcb;
+
+	FillMemory(&dcb, sizeof(dcb), 0);
+	dcb.DCBlength = sizeof(dcb);
+	if ( !BuildCommDCB(initParameters.c_str(), &dcb) )
+	{
+		err = GetLastError();
+		Util::Error("[SerialComm] Failed to build port settings ", err);
+		return ERR_DG_COM_INIT;
+	}
+
+	dcb.fBinary = TRUE ; 
+
+	//set hw handshaking
+	dcb.fOutX  = FALSE;
+    dcb.fInX   = FALSE;
+    dcb.fNull   = FALSE;
+    dcb.fAbortOnError = TRUE;
+	
+	dcb.fOutxDsrFlow = FALSE;
+	dcb.fDtrControl = DTR_CONTROL_DISABLE;
+	dcb.fDsrSensitivity= FALSE;
+	dcb.fDtrControl = DTR_CONTROL_DISABLE;
+
+	if ( hwFlowControl )
+	{
+		dcb.fOutxCtsFlow = TRUE;
+		dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
+	}
+	else
+	{
+		dcb.fOutxCtsFlow = FALSE;
+		dcb.fRtsControl = RTS_CONTROL_ENABLE;
+	}
+
+	if ( !SetCommState(m_Com, &dcb) )
+	{
+		err = GetLastError();
+		Util::Error("[SerialComm] Failed to set port settings ", err);
+		return ERR_DG_COM_INIT;
+	}
+
+	COMMTIMEOUTS timeouts;
+
+	timeouts.ReadIntervalTimeout = MAXDWORD; 
+
+	timeouts.ReadTotalTimeoutMultiplier = timeout;
+	timeouts.ReadTotalTimeoutConstant = 1;
+	timeouts.WriteTotalTimeoutMultiplier = 1;
+	timeouts.WriteTotalTimeoutConstant = timeout;
+
+	if ( !SetCommTimeouts(m_Com, &timeouts) )
+	{
+		// Error setting time-outs.
+		err = GetLastError();
+		Util::Error("[SerialComm] Failed to set port timeouts ", err);
+		return ERR_DG_COM_INIT;
+	}
+
+
+	m_Open = true;
+    Util::Debug("SerialComm::Open() OK");
+    Util::Info("[SerialComm] COM port open");
+    return NO_ERRORS;
+}
+
+/*
+ * This method is used to send Data object using serial communication
+ */
+DWORD SerialComm::Send(const Data& data_in)
+{
+    Util::Debug("SerialComm::Send()");
+	if ( data_in.GetLength() > 0 )
+	{
+		DWORD sentBytes = 0;
+		void* data = data_in.GetData();
+		int numOfTries = 0;
+		//loop until whole Data object is sent
+		while ( sentBytes < data_in.GetLength() )
+		{
+			//Util::Debug("while");
+			DWORD sent;
+			BOOL r;
+			if ( m_SendMaxSize>0 )
+			{
+				//Write data to the communication device				
+				r = WriteFile(m_Com,
+						((char*)data) + sentBytes,
+						//data_in.GetLength() - sentBytes,
+						min(data_in.GetLength() - sentBytes, m_SendMaxSize),
+						&sent,
+						NULL);
+			}
+			else
+			{
+				r = WriteFile(m_Com,
+						((char*)data) + sentBytes,
+						data_in.GetLength() - sentBytes,
+						&sent,
+						NULL);
+			}
+
+			if ( r && sent > 0 )
+			{
+				if (Util::GetVerboseLevel() == Util::debug)
+				{
+					Util::Hex(((char*)data) + sentBytes, min(sent,16));
+				}
+				sentBytes+=sent;
+			}
+			else
+			{
+				if ( !r )
+				{
+					DWORD err = GetLastError();
+					Util::Error("[SerialComm] Send error", err);
+				}
+				else
+				{
+					Util::Error("[SerialComm] Send failed");
+				}
+				if ( numOfTries++==g_SerialMaxResendNumber )
+				{
+					return ERR_DG_COMM_DATA_RECV;
+				}
+			}
+			//used to "solve" overflow problem
+			if ( m_SendPause > 0 )
+			{
+				Sleep(m_SendPause);
+			}
+		}
+	}
+
+    Util::Debug("SerialComm::Send() OK");
+    return NO_ERRORS;
+}
+
+/*
+ * This method reads all available data from communication media 
+ * and returns it in the Data object given as parameter
+ */
+DWORD SerialComm::Receive(Data* data_out)
+{
+    Util::Debug("SerialComm::Receive()");
+
+	//get available bytes in incoming communication channel	
+	LONG rxBytes = GetRxBytesAvailable();
+
+	if ( rxBytes > 0 )
+	{
+		char* data = new char[rxBytes];
+		DWORD readBytes = 0;
+		//read data until all available bytes have been red		
+		do
+		{
+			DWORD reallyRead;
+			if ( ReadFile(m_Com,
+					 data + readBytes,
+					 rxBytes - readBytes,
+					 &reallyRead,
+					 NULL) )
+			{
+				if (Util::GetVerboseLevel() == Util::debug)
+				{
+					char temp[64];
+					sprintf_s(temp, 64, "Received %d bytes", reallyRead);
+					Util::Debug( temp );
+					Util::Hex(data + readBytes, min(16,reallyRead));
+				}
+				readBytes += reallyRead;
+			}
+			else
+			{
+				delete[] data;
+				DWORD err = GetLastError();
+				Util::Error("[SerialComm] Error %d", err);
+				return ERR_DG_COMM_DATA_RECV;
+			}
+			if ( readBytes > rxBytes )
+			{
+				Util::Error("[SerialComm] !!! readBytes > rxBytes !!!");
+			}
+		}
+		while( readBytes < rxBytes );
+
+		data_out->SetData( data, rxBytes, Data::EData);
+		delete[] data;
+	}
+	else if ( rxBytes < 0 ) //err
+	{
+        return ERR_DG_COMM_DATA_RECV;
+	}
+	return NO_ERRORS;
+}
+
+/*
+ * This method returns number of bytes available in incoming queue or
+ * -1 if communication error has occurred
+ */
+LONG SerialComm::GetRxBytesAvailable()
+{
+    COMSTAT res;
+	DWORD err;
+
+	if ( ClearCommError(m_Com, &err, &res ) )
+	{
+		return res.cbInQue;
+	}
+	else
+    {
+		DWORD err = GetLastError();
+        Util::Error("[SerialComm] Error getting Rx bytes %d", err);
+        return -1;
+    }
+}
+
+DWORD SerialComm::Close()
+{
+    Util::Debug("SerialComm::Close()");
+    m_Open = false;
+
+	if ( m_Com != INVALID_HANDLE_VALUE )
+	{
+		CloseHandle(m_Com);
+		m_Com = INVALID_HANDLE_VALUE;
+	}
+
+    Util::Debug("SerialComm::Close() OK");
+    return NO_ERRORS;
+}
+
+//**********************************************************************************
+// Class SerialCommIoThread
+//
+// This thread is used to send data from outgoing queue to serial port
+// and read bytes from serial port and push it to incoming queue 
+//**********************************************************************************
+
+SerialCommIoThread::SerialCommIoThread(SafeQueue<Data*>* in,
+                           SafeQueue<Data*>* out,
+                           const string& init,  const string& commPort, long timeout,
+						   bool hwFlowControl, long sendPause, long sendMaxSize)
+    : m_InitString(init),
+	  m_CommPort( commPort ),
+	  m_PropertySerialCommTimeout( timeout ),
+	  m_PropertySerialHwFlowControl( hwFlowControl ),
+	  m_ProperySerialSendPause(sendPause),
+	  m_PropertySerialMaxSendSize(sendMaxSize)
+{
+    m_InQueue = in;
+    m_OutQueue = out;
+    m_Running = true;
+    m_OpenedEvent.Reset();
+}
+
+/*
+ * Main execution loop which is used to send Data from outgoing queue to serial port
+ * and read bytes from serial port, encapsulate it to Data objects and push them to incoming queue 
+ */
+void SerialCommIoThread::Run()
+{
+    while ( m_Running )
+    {
+	    Util::Debug("SerialCommIoThread::Run()");
+        SerialComm m_SerialComm;
+
+        if ( m_SerialComm.Open(m_CommPort, m_InitString, m_PropertySerialCommTimeout,
+							    m_PropertySerialHwFlowControl, m_ProperySerialSendPause,
+							    m_PropertySerialMaxSendSize) != NO_ERRORS )
+        {
+            m_Running = false;
+            return;
+        }
+        m_OpenedEvent.Set();
+
+	    Util::Debug("SerialCommIoThread::Run() start loop");
+        while ( m_Running )
+        {
+            // Sending data
+            try
+            {
+                Data* out = m_OutQueue->front(30);
+                if ( m_SerialComm.Send(*out) != NO_ERRORS )
+                {
+                //Data* d = new Data("Error sending data", 19, Data::EControl);
+				Data* d = CREATE_CONTROL_MESSAGE("[HtiGateway]: Error sending data");
+                    m_InQueue->push(d);
+                    d = NULL;
+                }
+                m_OutQueue->pop();
+                delete out;
+                out = NULL;
+            } catch (TimeoutException te) {}
+
+
+		    // Receiving data
+		    LONG rxBytes = 0;
+            while ( ( rxBytes = m_SerialComm.GetRxBytesAvailable() ) > 0 )
+            {
+                Data* in = new Data;
+                if ( m_SerialComm.Receive(in) == NO_ERRORS )
+                {
+				    m_InQueue->push(in);
+				    in = NULL;
+                }
+                else
+                {
+                    delete in;
+                    in = NULL;
+                }
+            }
+            if ( rxBytes < 0 )
+            {
+                Util::Info("[SerialCommIoThread] COM-port lost. Trying to close & reopen");
+                break; // break out but keep the outermost while loop running
+            }
+        }
+        m_OpenedEvent.Reset();
+        m_SerialComm.Close();
+    }
+    Util::Debug("SerialCommIoThread::Run() exiting");
+}
+
+void SerialCommIoThread::Stop()
+{
+    Util::Debug("SerialCommIoThread::Stop()");
+    m_Running = false;
+}
+
+Event SerialCommIoThread::GetOpenedEvent()
+{
+    return m_OpenedEvent;
+}
+
+void SerialCommIoThread::SetTimeout(long timeout)
+{
+    if ( timeout > 0 )
+    {
+        m_PropertySerialCommTimeout = timeout;
+    }
+    else
+    {
+        m_PropertySerialCommTimeout = g_SerialCommDefaultTimeout;
+    }
+}
+
+long SerialCommIoThread::GetTimeout() const
+{
+    return m_PropertySerialCommTimeout;
+}
+
+// End of the file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/Socket.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,275 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implemention of Socket, SocketClient, SocketServer and
+*   SocketSelect classes.
+*/
+#include <iostream>
+#include <sstream>
+#include <errno.h>
+
+#include "Socket.h"
+#include "util.h"
+
+using namespace std;
+
+int Socket::nofSockets_= 0;
+
+void Socket::Start() {
+  if (!nofSockets_) {
+    WSADATA info;
+    if (WSAStartup(MAKEWORD(2,0), &info)) {
+      throw "Could not start WSA";
+    }
+  }
+   ++nofSockets_;
+}
+
+void Socket::End() {
+  WSACleanup();
+}
+
+
+Socket::Socket() : s_(0) {
+  Start();
+  // UDP: use SOCK_DGRAM instead of SOCK_STREAM
+  s_ = socket(AF_INET,SOCK_STREAM,0);
+
+  refCounter_ = new int(1);
+}
+
+Socket::Socket(SOCKET s) : s_(s) {
+  Start();
+  refCounter_ = new int(1);
+};
+
+
+Socket::~Socket() {
+  if (! --(*refCounter_)) {
+	Close();
+    delete refCounter_;
+  }
+
+  --nofSockets_;
+  if (!nofSockets_) End();
+}
+
+Socket::Socket(const Socket& o) {
+  refCounter_=o.refCounter_;
+  (*refCounter_)++;
+  s_         =o.s_;
+
+  nofSockets_++;
+}
+
+Socket& Socket::operator =(Socket& o) {
+  (*o.refCounter_)++;
+
+  refCounter_=o.refCounter_;
+  s_         =o.s_;
+
+  nofSockets_++;
+
+  return *this;
+}
+
+
+void Socket::Close() {
+  closesocket(s_);
+}
+
+
+String Socket::ReceiveBytes() {
+  String ret;
+  char buf[1024];
+  int rv;
+
+  while ((rv=recv(s_, buf, 1024,0)) == WSAEMSGSIZE) {
+
+	String t;
+    t.assign(buf,1024);
+    ret +=t;
+  }
+  String t;
+  t.assign(buf, 0, rv);
+  ret += t;
+
+  printf("t = %s, rv = %d", t.c_str(), rv);
+
+  return ret;
+}
+
+int Socket::ReceiveBytes(BYTE *data, int bytes)
+{
+  int rv = SOCKET_ERROR;
+  while (rv == SOCKET_ERROR)
+  {
+	rv = recv(s_, (char *)data, bytes, 0);
+	if (rv == 0 || rv == WSAECONNRESET)
+		return -1;
+	else
+		break;
+  }
+  return rv;
+}
+
+String Socket::ReceiveLine() {
+  String ret;
+   while (1) {
+     char r;
+
+     switch(recv(s_, &r, 1, 0)) {
+       case 0: // not connected anymore;
+         return "";
+       case -1:
+          if (errno == EAGAIN) {
+             return ret;
+          } else {
+            // not connected anymore
+           return "";
+         }
+     }
+
+     ret += r;
+     if (r == '\n')  return ret;
+   }
+}
+
+void Socket::SendLine(String s) {
+  s += '\n';
+  send(s_,s.c_str(),s.length(),0);
+}
+
+void Socket::SendBytes(const String& s) {
+  send(s_,s.c_str(),s.length(),0);
+}
+
+int Socket::SendBytes(const BYTE* data, int bytes)
+{
+	if (bytes <= 0) return 0;
+	send(s_,(char *)data, bytes, 0);
+	return 0;
+}
+
+SocketServer::SocketServer() {
+  /*
+	// create a socket
+  s_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (s_ == INVALID_SOCKET) {
+    throw "INVALID_SOCKET";
+  }
+  */
+}
+
+
+void SocketServer::Accept( Socket*& s,int port, int connections, String& remoteHost ) {
+
+  sockaddr_in sa;
+  memset(&sa, 0, sizeof(sa)); /* clear our address */
+  sa.sin_family = PF_INET;
+  sa.sin_port = htons(port);
+
+  // Use the given socket for listening
+  Socket* listenSocket = s;
+
+  // bind the socket to the internet address
+  if (bind(listenSocket->s_, (sockaddr *)&sa, sizeof(sockaddr_in)) ==
+      SOCKET_ERROR) {
+    throw "INVALID_SOCKET";
+  }
+
+  listen(listenSocket->s_, connections);
+
+  sockaddr_in remoteAddr;
+  int remoteAddrLen = sizeof(sockaddr_in);
+  SOCKET new_sock = accept(listenSocket->s_, (sockaddr*) &remoteAddr, &remoteAddrLen);
+  if (new_sock == INVALID_SOCKET)
+  {
+	  throw "Invalid Socket";
+  }
+  // Return remote host and port to caller
+  stringstream msg;
+  msg<<inet_ntoa(remoteAddr.sin_addr)<<":"<<ntohs(remoteAddr.sin_port);
+  remoteHost.append( msg.str() );
+
+
+  s = new Socket(new_sock);
+  delete listenSocket;
+}
+
+void SocketServer::Connect(Socket* s, const char* remoteHost, int remotePort) {
+
+  Socket* connectSocket = s;
+  sockaddr_in sa;
+  memset(&sa, 0, sizeof(sa)); /* clear our address */
+  sa.sin_family = AF_INET;
+  if( isalpha(remoteHost[0]) )
+  {
+    HOSTENT* Hostent;
+    if( (Hostent = gethostbyname( remoteHost )) != 0 )
+      sa.sin_addr.s_addr = *(long*) Hostent->h_addr;
+	else
+	  throw "Unknown host!";
+  }
+  else
+    sa.sin_addr.s_addr = inet_addr( remoteHost );
+
+  sa.sin_port = htons( remotePort );
+
+  // Connect to server.
+  if ( connect( connectSocket->s_, (SOCKADDR*) &sa, sizeof(sa) ) == SOCKET_ERROR) {
+    throw "SOCKET_ERROR";
+  }
+}
+
+
+SocketClient::SocketClient(const String& host, int port) : Socket() {
+  String error;
+
+  hostent *he;
+  if ((he = gethostbyname(host.c_str())) == NULL) {
+    error = strerror(errno);
+    throw error;
+  }
+
+  sockaddr_in addr;
+  addr.sin_family = AF_INET;
+  addr.sin_port = htons(port);
+  addr.sin_addr = *((in_addr *)he->h_addr);
+  memset(&(addr.sin_zero), 0, 8);
+
+  if (::connect(s_, (sockaddr *) &addr, sizeof(sockaddr))) {
+    error = strerror(WSAGetLastError());
+    throw error;
+  }
+}
+
+
+SocketSelect::SocketSelect(Socket const * const s1, Socket const * const s2) {
+  FD_ZERO(&fds_);
+  FD_SET(const_cast<Socket*>(s1)->s_,&fds_);
+  FD_SET(const_cast<Socket*>(s2)->s_,&fds_);
+
+  if (select (0, &fds_, (fd_set*) 0, (fd_set*) 0, (timeval*) 0)
+      == SOCKET_ERROR) throw "Error in select";
+}
+
+
+bool SocketSelect::Readable(Socket const * const s) {
+  if (FD_ISSET(s->s_,&fds_)) return true;
+  return false;
+}
+
+// End of the file
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/common.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,204 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*     This file contains implementation file of the Data and ParameterList classes.
+*/
+
+// INCLUDES
+#include "common.h"
+#include "util.h"
+#include <crtdbg.h>
+
+// Maximum time to wait
+long g_MaximumShutdownWaitTime;
+
+DWORD g_ErrorCode = NO_ERRORS;
+
+//**********************************************************************************
+// Class Data
+//
+// This class provides data encapsulattion for DataGateway
+//**********************************************************************************
+
+Data::Data(const void* data_in, DWORD length, DataType type)
+{
+	////_RPT1(_CRT_WARN,"Data::Data %x\n", data_in);
+	m_pData = NULL;
+	SetData(data_in, length, 0, type);
+}
+
+
+Data::Data(const void* data_in, DWORD length, DWORD offset, DataType type)
+{
+	////_RPT1(_CRT_WARN,"Data::Data %x\n", data_in);
+	m_pData = NULL;
+	SetData(data_in, length, offset, type);
+}
+
+Data::Data(const Data& data)
+{
+	m_pData = NULL;
+	SetData(data.GetData(), data.GetLength(), 0, data.GetType());
+}
+
+Data::~Data()
+{
+	if (m_pData != NULL)
+	{
+		//_RPT1(_CRT_WARN,"~Data %x\n", m_pData);
+		free( m_pData );
+		m_pData = NULL;
+	}
+}
+
+/*
+ * This method is used to free data and set data type to EEmpty
+ */
+void Data::FreeData()
+{
+	if (m_pData != NULL)
+	{
+		//_RPT1(_CRT_WARN,"FreeData %x\n", m_pData);
+		free( m_pData );
+		m_pData = NULL;
+		m_Type = EEmpty;
+	}
+}
+/*
+ * returns data in Data object given parameter
+ */
+void* Data::GetData(void *data_out) const
+{
+	if (data_out != NULL)
+	{
+		data_out = m_pData;
+	}
+	return m_pData;
+}
+
+/*
+ * returns length of data 
+ */
+DWORD Data::GetLength() const
+{
+	return m_dwLength;
+}
+
+/*
+ * returns type of data
+ * can be one of the following: EEmpty, EControl, EError, EData
+ */
+Data::DataType Data::GetType() const
+{
+	return m_Type;
+}
+
+Data& Data::operator=(const Data& data)
+{
+	if ( this != &data )
+	{
+		FreeData();
+		SetData( data.GetData(), data.GetLength(), data.GetType() );
+	}
+	return *this;
+}
+
+/*
+ * This method copies up to length bytes from given data object to class member data object
+ */
+bool Data::SetData(const void* data_in, DWORD length, DataType type)
+{
+	////_RPT1(_CRT_WARN,"Data::SetData %x\n", data_in);
+	return SetData(data_in, length, 0, type);
+}
+
+/*
+ * This method copies up to length bytes(starting from offset) from given data object to class member data object
+ */
+bool Data::SetData(const void* data_in, DWORD length, DWORD offset, DataType type)
+{
+	//_RPT1(_CRT_WARN,"Data::SetData %x\n", data_in);
+	m_Type = type;
+	if (length == 0 || data_in == NULL || offset >= length)
+	{
+		m_pData = NULL;
+		m_dwLength = 0;
+		return true;
+	}
+	m_dwLength = (length - offset);
+	//_ASSERTE(m_pData==NULL);
+	m_pData = (BYTE*)malloc( m_dwLength );
+	//_RPT2(_CRT_WARN,"Data::SetData m_pData %x <%d>\n", m_pData, m_dwLength);
+	if (m_pData == NULL)
+	{
+		Util::Error("Error allocating memory to data object");
+		m_Type = EEmpty;
+		return false;
+	}
+	memset(m_pData, 0, m_dwLength);
+	memcpy(m_pData, &reinterpret_cast<const char*>(data_in)[offset], m_dwLength);
+	return false;
+}
+
+/*
+ * Used to combine different messages into one.
+ * This method appends new data at the end of already excisting data.
+ * If new data isn't same type as excisting data it isn't appended.
+ * Returns bool value of whether the method has succeeded to append the data or not.
+ */
+bool Data::AppendData(Data* aData)
+{
+	if ( m_Type == aData->m_Type )
+	{
+		//realloc memory
+		BYTE* newBlock = (BYTE*) realloc( m_pData, m_dwLength + aData->m_dwLength );
+		if ( newBlock != NULL )
+		{
+			m_pData = newBlock;
+			//copy data
+			memcpy( ((BYTE*)m_pData) + m_dwLength,
+					aData->GetData(),
+					aData->GetLength() );
+			//update length
+			m_dwLength += aData->GetLength();
+			return true;
+		}
+	}
+	return false;
+}
+
+//**********************************************************************************
+// Class ParameterList
+//
+//**********************************************************************************
+ParameterList::ParameterList()
+{
+}
+
+ParameterList::~ParameterList()
+{
+	m_Map.clear();
+}
+
+void ParameterList::Add(const string& key, const void* value)
+{
+	m_Map[key] = value;
+}
+
+const void* ParameterList::Get(const string& key)
+{
+	return m_Map[key];
+}
+
+// End of the file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/datagateway.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,529 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implementation of the DataGatewaySOAPServerThread, 
+*   DataGatewayClientThread and DataGateway classes.
+*/
+
+// INCLUDES
+#include "stdsoap2.h" //should be first because of WinSock2.h errors
+#include "datagateway.h"
+#include "hticommon.h"
+#include "HtiMessage.h"
+#include <sstream>
+
+/*
+ * This method is used to print the SOAP fault to a string
+ */
+void soap_sprint_fault(struct soap *soap, char *fd)
+{ if (soap->error)
+  { const char *c, *v = NULL, *s, **d;
+    d = soap_faultcode(soap);
+    if (!*d)
+      soap_set_fault(soap);
+    c = *d;
+    if (soap->version == 2)
+      v = *soap_faultsubcode(soap);
+    s = *soap_faultstring(soap);
+    d = soap_faultdetail(soap);
+    sprintf(fd, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]");
+  }
+}
+
+//**********************************************************************************
+// Class DataGatewaySOAPServerThread
+//
+// This thread acts as a SOAP server, it listens to SOAP requests and forwards them
+// to HtiDispatcher which then forwards them to correct SOAPHandlers
+//**********************************************************************************
+
+DataGatewaySOAPServerThread::DataGatewaySOAPServerThread(HtiDispatcher* htiDispatcher,
+														int port)
+	: m_HtiDispatcher(htiDispatcher),m_TcpPort(port),m_Running(true)
+{
+}
+
+/*
+ * This loop listens to incoming Soap reuests and forwards them to HtiDispatcher
+ */
+void DataGatewaySOAPServerThread::Run()
+{
+	struct soap soap;
+ 	//Initializes a static/stack-allocated runtime environment 
+	soap_init(&soap);
+	//soap_init2(&soap, SOAP_IO_KEEPALIVE, SOAP_IO_KEEPALIVE);
+	//_CrtDbgReport(_CRT_ERROR, _CRTDBG_MODE_WNDW);
+/*
+#ifdef _DEBUG
+   HANDLE hLogFile;
+   hLogFile = CreateFile("c:\\log.txt", GENERIC_WRITE, FILE_SHARE_WRITE,
+      NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+   _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
+   _CrtSetReportFile(_CRT_WARN, hLogFile);
+
+#endif
+*/
+	while (m_Running)
+	{
+		int m, s; // master and slave sockets
+		Util::Debug("soap_init");
+
+		//Returns master socket (backlog = max. queue size for requests). When host==NULL: host is the machine on which the service runs 
+		m = soap_bind(&soap, NULL, m_TcpPort, 100);
+		if (m < 0)
+		{
+			//Util::Error("Failed to open socket", m_TcpPort);
+			//soap_print_fault(&soap, stderr);
+			char temp[512];
+			soap_sprint_fault(&soap, temp);
+			Util::Error(temp);
+			break;
+		}
+		else
+		{
+			Util::Debug("Socket connection successful");
+/*
+#ifdef _DEBUG
+			_CrtMemState startMem, endMem, diffMem;
+			//Sleep(5000);
+#endif
+*/
+			for (int i = 1; ; i++)
+			{
+				//_RPT1(_CRT_WARN, "---++++=======Iter %d=======++++---\n", i);
+				//_RPT0(_CRT_WARN, "---Start dump---\n");
+
+				//_CrtMemCheckpoint(&startMem);
+				//_CrtMemDumpStatistics(&startMem);
+				//Returns slave socket
+				s = soap_accept(&soap);
+				if (s < 0)
+				{
+					//soap_print_fault(&soap, stderr);
+					char temp[512];
+					soap_sprint_fault(&soap, temp);
+					Util::Error(temp);
+
+					break;
+				}
+				Util::Debug(" accepted connection");
+
+				//start of my dispatching code
+				if ( !m_HtiDispatcher->DispatchSoapServe( &soap ) ) // process RPC request
+				{
+					//soap_print_fault(&soap, stderr); // print error
+					// clean up class instances
+					soap_destroy(&soap);
+					// clean up everything and close socket
+					soap_end(&soap); 
+				}
+				else
+				{
+					// clean up allcated data
+					soap_dealloc(&soap, NULL);
+					// clean up class instances
+					soap_destroy(&soap); 
+					//cleanup temp data
+					soap_free(&soap); 
+
+					//soap_end(&soap); // clean up everything and close socket
+				}
+/*
+#ifdef _DEBUG
+				//Sleep(2000); //wait when hadler thread is over
+
+				//copy
+				memcpy( &startMem, &endMem, sizeof(_CrtMemState) );
+				_CrtMemCheckpoint(&endMem);
+				_CrtMemDumpStatistics(&endMem);
+
+				_RPT0(_CRT_WARN, "==========End diff==========\n");
+
+				if (_CrtMemDifference( &diffMem, &startMem, &endMem ) )
+				{
+
+					_CrtMemDumpStatistics(&diffMem);
+					_RPT0(_CRT_WARN, "########## Objects #############\n");
+					//_CrtMemDumpAllObjectsSince( &diffMem );
+					_RPT0(_CRT_WARN, "++++++End dump++++++\n");
+				}
+#endif
+*/
+				Util::Debug("request dispatched");
+			}
+		}
+	}
+	// Clean up deserialized data (except class instances) and temporary data 
+	soap_end(&soap);
+	// close master socket and detach environment
+	soap_done(&soap); 
+	Stop();
+//#ifdef _DEBUG
+//   CloseHandle(hLogFile);
+//#endif
+}
+
+void DataGatewaySOAPServerThread::Stop()
+{
+	m_Running = false;
+}
+
+bool DataGatewaySOAPServerThread::IsRunning()
+{
+	return m_Running;
+}
+
+//**********************************************************************************
+// Class DataGatewayClientThread
+//
+// This thread serves DataGateway's clients
+// Gets Data objects from incoming queue and forwards them to CommChannelPlugin.
+// The Data objects are actually SOAP requests which were received by DataGatewaySOAPServerThread handled by SOAPHandler and transferred to HtiMessages and eventually Data objects
+// The thread also reads incoming data from CommChannelPlugin and forwards them to outgoing queue which
+// HtiDispatcher then reads and forwards to correct SOAPHandler
+//**********************************************************************************
+
+DataGatewayClientThread::DataGatewayClientThread(int port,
+												 long bufsize,
+												 const string& commchannel)
+	: m_HtiDispatcher(&m_ReaderQueue, &m_WriterQueue),
+	  m_SoapListener(&m_HtiDispatcher, port),
+  	  m_CommChannelPluginName(commchannel),
+	  m_Running(true)
+{
+	m_CCLateInit = true;
+
+	if (bufsize > 0)
+	{
+		m_TcpIpBufferSize = bufsize;
+	}
+	else
+	{
+		m_TcpIpBufferSize = g_DataGatewayDefaultTcpIpBufferSize;
+	}
+}
+
+DataGatewayClientThread::DataGatewayClientThread(int port,
+												 long bufsize,
+										         CommChannelPlugin** f)
+	: m_HtiDispatcher(&m_ReaderQueue, &m_WriterQueue),
+	  m_SoapListener(&m_HtiDispatcher, port),
+  	  m_CommChannelPluginName((*f)->GetName()),
+	  m_Running(true)
+{
+	m_CCLateInit = false;
+
+	m_CommChannelPlugin = *f;
+	if (bufsize > 0)
+	{
+		m_TcpIpBufferSize = bufsize;
+	}
+	else
+	{
+		m_TcpIpBufferSize = g_DataGatewayDefaultTcpIpBufferSize;
+	}
+}
+
+DataGatewayClientThread::~DataGatewayClientThread()
+{
+	Util::Debug("DataGatewayClientThread::~DataGatewayClientThread()");
+	if (m_Running)
+	{
+		Stop();
+	}
+}
+
+/*
+ * Main loop of thread
+ *
+ * Gets Data from incoming queue and forwards it to CommChannelPlugin.
+ * Reads incoming data from CommChannelPlugin and forwards them to outgoing queue
+ */
+void DataGatewayClientThread::Run()
+{
+	DWORD res;
+
+	if (m_CCLateInit)
+	{
+		m_CommChannelPlugin = CommChannelPlugin::Instance(m_CommChannelPluginName);
+		if (m_CommChannelPlugin == NULL)
+		{
+			g_ErrorCode = ERR_DG_COMMCHANNEL;
+			return;
+		}
+		if ((res = m_CommChannelPlugin->Connect()) != NO_ERRORS)
+		{
+			Util::Error("[HtiGateway] Error - Cannot connect to the target.");
+			m_CommChannelPlugin->Disconnect();
+			g_ErrorCode = res;
+			return;
+		}
+		Util::Info("[HtiGateway] Communication Channel Plugin loaded succesfully");
+	}
+
+	m_SoapListener.Start();
+	m_HtiDispatcher.Start();
+
+	// Flush comm input buffer;
+	Data* dummy;
+	while (m_CommChannelPlugin->Receive(&dummy) == NO_ERRORS)
+	{
+		dummy->FreeData();
+		continue;
+	}
+	dummy = NULL;
+
+	while (m_Running)
+	{
+		if (!m_SoapListener.IsRunning() ||
+			!m_HtiDispatcher.IsRunning())
+		{
+			Stop();
+			break;
+		}
+
+		// Receiving from TCP/IP port and
+		// sending to CommChannelPlugin
+		try {
+			Data* d = m_ReaderQueue.front(50);
+			m_ReaderQueue.pop();
+			m_CommChannelPlugin->Send(d);
+			//_RPT2(_CRT_WARN,"DataGateway::Send %x %x\n", d, d->GetData());
+			d = NULL;
+		} catch (TimeoutException te)
+		{
+			//Util::Debug("DataGatewayClientThread::TimeoutException");
+		}
+
+		// Receiving from CommChannelPlugin and
+		// sending data to TCP/IP port. If message
+		// is error or control message it is also
+		// handled here.
+		Data* out;
+
+		if (m_CommChannelPlugin->Receive(&out) != NO_ERRORS) continue;
+		//_RPT2(_CRT_WARN,"DataGateway::Receive %x %x\n", out, out->GetData());
+		//printf(">>>>>>>>>Type %d clt<<<<<<\n", out->GetType());
+		switch (out->GetType())
+		{
+			case Data::EData:
+			{
+
+				//printf("\t\tpush = %d\n", m_WriterQueue.size());
+				m_WriterQueue.push(out);
+				//_RPT0(_CRT_WARN,"DataGateway::Write out NULL\n");
+				out = NULL;
+			}
+			break;
+			case Data::EControl:
+			{
+				Util::Debug("ClientThread: Control Message Received");
+				/*
+				switch (*(BYTE*)out->GetData())
+				{
+					case ControlPhonePowered:
+						{
+							Util::Info("[HtiGateway] Phone powered up");
+						}
+					break;
+				}
+				*/
+				//generate HTI error message for waiting handlers
+				//putting control message content in the detail field
+				HtiMessage* errMsg = HtiMessage::CreateErrorMessage(0, (char*)out->GetData() );
+				out->FreeData();
+				out->SetData( errMsg->HtiData(), errMsg->HtiDataSize(), Data::EData);
+				m_WriterQueue.push(out);
+				out = NULL;
+			}
+			break;
+			case Data::EError:
+			{
+				Util::Debug("ClientThread: Error Message Received");
+				Stop();
+			}
+			break;
+
+			default:
+				{
+					Util::Debug("ClientThread: Unknown Message Received");
+				}
+			break;
+		}
+		delete out;
+		out = NULL;
+	}
+
+	if (m_CCLateInit)
+	{
+		m_CommChannelPlugin->Disconnect();
+		Util::Info("[HtiGateway] Communication Channel Plugin unloaded");
+		m_CommChannelPlugin = NULL;
+	}
+}
+
+void DataGatewayClientThread::Stop()
+{
+	m_Running = false;
+	m_SoapListener.Stop();
+	m_HtiDispatcher.Stop();
+	HANDLE handles[2];
+	handles[0] = m_SoapListener.ThreadHandle();
+	handles[1] = m_HtiDispatcher.ThreadHandle();
+	WaitForMultipleObjects(2, handles, TRUE, g_MaximumShutdownWaitTime);
+}
+
+//**********************************************************************************
+// Class DataGateway
+//
+// Main class/thread of HtiGateway
+//**********************************************************************************
+
+DataGateway::DataGateway(int port,
+						 long bufsize,
+						 const string& commchannel,
+						 bool stayalive,
+						 bool cclateinit)
+	: m_TcpIpPort(port),
+	  m_TcpIpBufferSize(bufsize),
+  	  m_CommChannelPluginName(commchannel),
+	  m_StayAlive(stayalive),
+	  m_CCLateInit(cclateinit),
+	  m_Running(true)
+{
+	m_CommChannelPlugin = NULL;
+}
+
+/*
+ * Main loop of HtiGateway
+ * This loop:
+ * -creates instance of CommChannelPlugin if lateinit isn't set on
+ * -starts DataGatewayClient thread to serve the client
+ */
+void DataGateway::Run()
+{
+	DWORD res;
+
+	try
+	{
+		if (Util::GetVerboseLevel() >= Util::VerboseLevel::info)
+		{
+			char tmp[256];
+			sprintf(tmp, "[HtiGateway] Using TCP/IP port %d", m_TcpIpPort);
+			string s(tmp);
+			Util::Info(s);
+
+			//sprintf(tmp, "[HtiGateway] TCP/IP receive buffer size is %d bytes", m_TcpIpBufferSize);
+			//s.assign(tmp);
+			//Util::Info(s);
+
+			sprintf(tmp, "[HtiGateway] Loading Communication Channel Plugin for [%s]", m_CommChannelPluginName.c_str());
+			s.assign(tmp);
+			Util::Info(s);
+		}
+
+		//SocketServer in(m_TcpIpPort, 1);
+		//Util::Info("[HtiGateway] TCP/IP port opened");
+
+		if (!m_CCLateInit)
+		{
+			m_CommChannelPlugin = CommChannelPlugin::Instance(m_CommChannelPluginName);
+			if (m_CommChannelPlugin == NULL)
+			{
+				throw UtilError("[HtiGateway] Error loading Communication Channel.", ERR_DG_COMMCHANNEL);
+			}
+			if ((res = m_CommChannelPlugin->Connect()) != NO_ERRORS)
+			{
+				m_CommChannelPlugin->Disconnect();
+				throw UtilError("[HtiGateway] Error connecting to the target.", res);
+			}
+			Util::Info("[HtiGateway] Communication Channel Plugin loaded succesfully");
+		}
+		else
+		{
+			Util::Info("[HtiGateway] Communication Channel Plugin uses late initialization.");
+		}
+
+			g_ErrorCode = NO_ERRORS;
+			Util::Info("[HtiGateway] Waiting connection");
+			//Socket* s = in.Accept();
+			Util::Info("[HtiGateway] Connection established");
+			DataGatewayClientThread* client;
+			if (m_CCLateInit)
+			{
+				client = new DataGatewayClientThread(m_TcpIpPort,
+													m_TcpIpBufferSize,
+													m_CommChannelPluginName);
+			}
+			else
+			{
+				client = new DataGatewayClientThread(m_TcpIpPort,
+													m_TcpIpBufferSize,
+													&m_CommChannelPlugin);
+			}
+			client->Start();
+
+			HANDLE handles[2];
+			handles[0] = client->ThreadHandle();
+			handles[1] = m_ShutdownEvent.EventHandle();
+			DWORD dwResult = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
+			switch (dwResult)
+			{
+				case WAIT_OBJECT_0 + 0:
+				{
+					Util::Debug("DataGateway::Run() Client thread stopped");
+				}
+				break;
+				case WAIT_OBJECT_0 + 1:
+				{
+					Util::Debug("DataGateway::Run() Request to shutdown");
+					client->Stop();
+					WaitForSingleObject(client->ThreadHandle(), g_MaximumShutdownWaitTime);
+				}
+				break;
+			}
+			Util::Info("[HtiGateway] Connection closed.");
+			delete client;
+			client = NULL;
+			//if (!m_StayAlive) break;
+		if (!m_CCLateInit)
+		{
+			m_CommChannelPlugin->Disconnect();
+			Util::Info("[HtiGateway] Communication Channel Plugin unloaded");
+			m_CommChannelPlugin = NULL;
+		}
+	} catch (char* s) {
+		char tmp[64];
+		sprintf(tmp, "[HtiGateway] Error opening TCP/IP port - %s", s);
+		Util::Error(tmp);
+		g_ErrorCode = ERR_DG_SOCKET;
+	} catch (UtilError ue) {
+		Util::Error(ue.iError, ue.iResult);
+		g_ErrorCode = ue.iResult;
+	}
+	Util::Info("[HtiGateway] Closed");
+}
+
+void DataGateway::Stop()
+{
+	m_Running = false;
+	m_ShutdownEvent.Set();
+}
+
+bool DataGateway::IsRunning()
+{
+	return m_Running;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/main.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,229 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*    This module contains the UI operations of DataGateway.
+*/
+
+#pragma warning ( disable : 4786 )
+
+#include "Socket.h"
+
+#include <windows.h>
+#include <process.h>
+#include <string>
+#include <map>
+
+#include "util.h"
+#include "datagateway.h"
+#include "common.h"
+
+// GLOBAL DEFINES
+// Command line switches
+#define PARAM_SWITCH_PORT       "-port"
+#define PARAM_SWITCH_BUFSIZE    "-bufsize"
+#define PARAM_SWITCH_COMMPLUGIN "-commchannel"
+#define PARAM_SWITCH_STAYALIVE  "-stayalive"
+#define PARAM_SWITCH_CCLATEINIT "-cclateinit"
+#define PARAM_SWITCH_SWT        "-swt"
+#define PARAM_SWITCH_VERBOSE    "-v"
+#define PARAM_SWITCH_TIMESTAMP  "-t"
+
+#define VERSION "1.68.0"
+#define INFO "HtiGateway %s - Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.\n\n"
+
+// Event object to catch console signal
+Event g_ConsoleCloseEvent;
+
+// Event object to wait datagateway shutdown
+Event g_DataGatewayClosedEvent;
+
+// Maximum time to wait
+extern long g_MaximumShutdownWaitTime;
+
+extern DWORD g_ErrorCode;
+
+// Global parameters to be used in datagateway and all plugins
+map<string, string> g_parameters;
+
+// FUNCTION PROTOTYPES
+// Prints usage of DataGateway
+void usage();
+
+// Initializes phoenixtool default values
+void init(map<string, string>&, map<string, string>&);
+
+// Catches console control signals
+BOOL WINAPI ConsoleControlHandler(DWORD);
+
+int main(int argv, char *args[])
+{
+    printf(INFO, VERSION);
+    if (argv == 2 && strcmp("-h", args[1]) == 0)
+    {
+        usage();
+        return 0;
+    }
+    map<string, string> props;
+
+    try {
+        Util::ReadProperties("HtiGateway.ini", props);
+
+        // Sets values from properties file
+        init(props, g_parameters);
+
+        if (argv > 1)
+        {
+            // Overrides properties file values
+            // if specified in command line
+            Util::ParseCmdLine(argv, args, g_parameters);
+            Util::SetTimestamp(g_parameters[PARAM_SWITCH_TIMESTAMP]);
+        }
+        Util::SetVerboseLevel(g_parameters[PARAM_SWITCH_VERBOSE]);
+
+        bool stayalive = (strcmp("true", g_parameters[PARAM_SWITCH_STAYALIVE].c_str()) == 0
+                            ? true
+                            : false);
+        bool cclateinit = (strcmp("true", g_parameters[PARAM_SWITCH_CCLATEINIT].c_str()) == 0
+                            ? true
+                            : false);
+        int port = atoi(g_parameters[PARAM_SWITCH_PORT].c_str());
+        long bufsize = atol(g_parameters[PARAM_SWITCH_BUFSIZE].c_str());
+        g_MaximumShutdownWaitTime = atol(g_parameters[PARAM_SWITCH_SWT].c_str());
+        string ch = Util::ToUpper(g_parameters[PARAM_SWITCH_COMMPLUGIN]);
+
+        DataGateway dg(port, bufsize, ch, stayalive, cclateinit);
+
+        // Installs console control handler for catching
+        // signals
+        if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleControlHandler, TRUE))
+        {
+            Util::Error("Error registering the console control handler");
+            return ERR_DG_CONSOLEHANDLER;
+        }
+
+        dg.Start();
+        HANDLE handles[2];
+        handles[0] = dg.ThreadHandle();
+        handles[1] = g_ConsoleCloseEvent.EventHandle();
+        DWORD dwResult = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
+        switch (dwResult)
+        {
+            case WAIT_OBJECT_0 + 0:
+            {
+                Util::Debug("main() HtiGateway thread stopped");
+            }
+            break;
+            case WAIT_OBJECT_0 + 1:
+            {
+                dg.Stop();
+                if (g_MaximumShutdownWaitTime > 0)
+                {
+                    Util::Info("[HtiGateway] Waiting HtiGateway to shutdown");
+                    WaitForSingleObject(dg.ThreadHandle(), g_MaximumShutdownWaitTime);
+                }
+            }
+            break;
+        }
+        g_DataGatewayClosedEvent.Set();
+    } catch (UtilError ue) {
+        Util::Error(ue.iError, ue.iResult);
+        g_ErrorCode = ue.iResult;
+    }
+    if (g_ErrorCode != NO_ERRORS)
+    {
+        // Resolve error code to clear text
+        ERROR_LOOKUP(g_ErrorCode);
+    }
+
+    return g_ErrorCode;
+}
+
+void init(map<string, string>& props,
+          map<string, string>& params)
+{
+    // Setting default values from properties file
+    // to parameters
+    params[PARAM_SWITCH_BUFSIZE]    = props["TCPIP_RECV_BUFFER_SIZE"];
+    params[PARAM_SWITCH_PORT]       = props["TCPIP_PORT"];
+    params[PARAM_SWITCH_COMMPLUGIN] = props["DEFAULT_COMM_CHANNEL_PLUGIN"];
+    params[PARAM_SWITCH_SWT]        = props["MAXIMUM_SHUTDOWN_WAITTIME"];
+    params[PARAM_SWITCH_VERBOSE]    = "info";
+    params[PARAM_SWITCH_STAYALIVE]  = "true";
+    params[PARAM_SWITCH_TIMESTAMP]  = "false";
+    params[PARAM_SWITCH_CCLATEINIT] = "false";
+}
+
+void usage()
+{
+    
+	cout << "USAGE: HtiGateway.exe [SWITCHES in form -switch=value]\n\n";
+    cout << "\tSWITCHES:\n";
+    cout << "\t-port         TCP/IP port\n";
+    cout << "\t-bufsize      TCP/IP receive buffer size in bytes\n";
+    cout << "\t-commchannel  Communication Channel Plugin (CCP) name e.g. SERIAL\n";
+    cout << "\t-stayalive    Whether HtiGateway remains when client disconnects\n";
+    cout << "\t              or not\n";
+    cout << "\t-cclateinit   Whether CCP is initialized when client connects or not\n";
+    cout << "\t-swt          Maximum shutdown wait time in milliseconds. 0 means\n";
+    cout << "\t              no waiting.\n";
+    cout << "\t-v            Verbose mode\n";
+    cout << "\t-t            Timestamped output\n\n";
+    cout << "\tBy default these values are defined in HtiGateway.ini file.\n";
+    cout << "\tIf any switches are used those override values from ini file\n\n";
+    cout << "\tSTAYALIVE:\n";
+    cout << "\tfalse      HtiGateway shutdown after client closes connection\n";
+    cout << "\ttrue       HtiGateway remains waiting new connections (*)\n\n";
+    cout << "\tCCLATEINIT:\n";
+    cout << "\tfalse      HtiGateway initializes CCP when started (*)\n";
+    cout << "\ttrue       HtiGateway initializes CCP only when client connects to\n\n";
+    cout << "\tVERBOSE:\n";
+    cout << "\toff        Silent mode\n";
+    cout << "\tresult     Prints only result (no info/errors)\n";
+    cout << "\terror      Prints result and errors (*)\n";
+    cout << "\tinfo       Prints normal output\n";
+    cout << "\tdebug      Prints all\n\n";
+    cout << "\tTIMESTAMPED:\n";
+    cout << "\tfalse      No timestamp (*)\n";
+    cout << "\ttrue       Adds timestamp to output\n\n";
+    cout << "\t(*) means default value\n\n";
+    cout << "\tAll communication channel plugin parameters can also be passed from\n";
+    cout << "\tcommand line just by adding \"-\" to the parameter name. For example:\n";
+	cout << "\t\"-COMPORT=COM3\" or -REMOTE_PORT=3000\n";
+    cout << endl;
+}
+
+BOOL WINAPI ConsoleControlHandler(DWORD dwCtrlType)
+{
+    BOOL bReturnStatus = FALSE;
+    switch (dwCtrlType)
+    {
+        case CTRL_C_EVENT:
+        case CTRL_BREAK_EVENT:
+        case CTRL_CLOSE_EVENT:
+        case CTRL_LOGOFF_EVENT:
+        case CTRL_SHUTDOWN_EVENT:
+        {
+            Util::Info("[HtiGateway] Request to terminate");
+            g_ConsoleCloseEvent.Set();
+
+            // Wait DG shutdown before returning control to system
+            WaitForSingleObject(g_DataGatewayClosedEvent.EventHandle(), g_MaximumShutdownWaitTime);
+        }
+        break;
+    }
+    bReturnStatus = TRUE;
+    return bReturnStatus;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/plugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,135 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the header file of the Plugin, FrontendPlugin,
+*	CommChannelPlugin and CommChannelPluginObserver classes and implementation
+*	of DummyCommObserver.
+*/
+
+// INCLUDES
+#include "plugin.h"
+#include "util.h"
+#include "serialcommplugin.h"
+#include "IPCommPlugin.h"
+
+extern DWORD g_ErrorCode;
+
+//**********************************************************************************
+// Class Plugin
+//
+//**********************************************************************************
+
+Plugin::Plugin()
+{
+	Init();
+}
+
+DWORD Plugin::Init()
+{
+	m_Name = "NULL Plugin";
+	return NO_ERRORS;
+}
+
+const string& Plugin::GetName(string *name)
+{
+	if (name != NULL)
+	{
+		*name = m_Name;
+	}
+	return m_Name;
+}
+
+//**********************************************************************************
+// Class CommChannelPlugin
+//
+// This class is the parent class of all communication channel plugins used
+// in DataGateway.
+//**********************************************************************************
+
+CommChannelPlugin* CommChannelPlugin::m_Self = NULL;
+
+/*
+ * This method creates instance of specified plugin  
+ */
+CommChannelPlugin* CommChannelPlugin::Instance(const string& pluginname,
+											   const CommChannelPluginObserver* observer)
+{
+	if (m_Self == NULL)
+	{
+		if (pluginname.compare("SERIAL") == 0 )
+		{
+			m_Self = new SerialCommPlugin(observer);
+		}
+		else if (pluginname.compare("IPCOMM") == 0 )
+		{
+			m_Self = new IPCommPlugin(observer);
+		}
+		else
+		{
+			string err = "Error when creating communication channel plugin.\n";
+			err += "Unknown plugin '" + pluginname + "'";
+			Util::Error(err);
+			m_Self = NULL;
+			g_ErrorCode = ERR_DG_UNKNOWN_COMMCHANNEL;
+		}
+	}
+	return m_Self;
+}
+
+/*
+ * This method initializes and connects the instance of plugin
+ */
+DWORD CommChannelPlugin::Connect()
+{
+	if (m_Self == NULL) return ERR_DG_UNINITIALISED_COMMCHANNEL;
+	DWORD res;
+	if ((res = m_Self->Init()) != NO_ERRORS) return res;
+	return m_Self->Open();
+}
+
+/*
+ * This method closes and deletes the instance of plugin
+ */
+DWORD CommChannelPlugin::Disconnect()
+{
+	if (m_Self == NULL) return ERR_DG_UNINITIALISED_COMMCHANNEL;
+	Util::Info("[DataGateway] Waiting Communication Channel Plugin to shutdown");
+	m_Self->Close();
+	delete m_Self;
+	m_Self = NULL;
+	return NO_ERRORS;
+}
+
+CommChannelPlugin::CommChannelPlugin(const CommChannelPluginObserver* observer)
+	: Plugin()
+{
+	if (observer == NULL)
+	{
+		m_Observer = new DummyCommObserver;
+	}
+	else
+	{
+		m_Observer = observer;
+	}
+}
+
+DWORD CommChannelPlugin::Init()
+{
+	DWORD res;
+	res = Plugin::Init();
+	m_Open = false;
+	return res;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/safequeue.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*    This file contains implementation of SafeQueue template class popAll method.
+*/
+
+#include "safequeue.h"
+#include "common.h"
+
+/*
+ * This method is used to pop all of the elements in queue and return them in single Data object
+ */
+template <>
+(Data*)& SafeQueue<Data*>::popAll(DWORD timeout)
+	throw (TimeoutException)
+{
+	if (Semaphore::Wait(timeout) == WAIT_TIMEOUT)
+	{
+		throw TimeoutException("queue front timed out");
+	}
+	Mutex::Lock();
+	Data*& first = queue<Data*>::front();
+	queue<Data*>::pop();
+	//add to the first the rest of queue
+	bool s = true;
+	while ( queue<Data*>::size() > 0 && s)
+	{
+		Data*& a = queue<Data*>::front();
+		int len = first->GetLength();
+		first->AppendData( a ); //?????
+		if ( first->GetLength() != len )
+		{
+			queue<Data*>::pop();
+			delete a; //????
+		}
+		else
+		{
+			s = false;
+		}
+	}
+	Mutex::Unlock();
+	return first;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/stdafx.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// stdafx.cpp : source file that includes just the standard includes
+// SimpleStreamAPIClient.pch will be the pre-compiled header
+// stdafx.obj will contain the pre-compiled type information
+
+#include "stdafx.h"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/sync.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains implementation of synchronization objects. These are Mutex, Semaphore and
+*   Event classes.
+*/
+
+// INCLUDES
+#include "sync.h"
+
+//**********************************************************************************
+// Class Mutex
+//
+// This class implements a Mutex using Windows API synchronization mechanism 
+//**********************************************************************************
+
+Mutex::Mutex(void)
+{
+	InitializeCriticalSection(&m_Lock);
+}
+
+Mutex::~Mutex(void)
+{
+}
+
+void Mutex::Lock(void)
+{
+	EnterCriticalSection(&m_Lock);
+}
+
+void Mutex::Unlock(void)
+{
+	LeaveCriticalSection(&m_Lock);
+}
+
+//**********************************************************************************
+// Class Semaphore
+//
+// This class encapsulates Windows API Semaphore functionality
+//**********************************************************************************
+
+Semaphore::Semaphore(void)
+{
+	m_Semaphore = CreateSemaphore(NULL, 0, 0x7FFFFFF, NULL);
+}
+
+Semaphore::Semaphore(int available)
+{
+	m_Semaphore = CreateSemaphore(NULL, available, 0x7FFFFFF, NULL);
+}
+
+Semaphore::~Semaphore(void)
+{
+	CloseHandle(m_Semaphore);
+}
+
+DWORD Semaphore::Wait(DWORD timeout)
+{
+	DWORD dwResult = WaitForSingleObject(m_Semaphore, timeout);
+	switch (dwResult)
+	{
+	case WAIT_OBJECT_0:
+		return 0;
+	case WAIT_TIMEOUT:
+		return WAIT_TIMEOUT;
+	default:
+		return 1;
+	}
+}
+
+void Semaphore::Notify(void)
+{
+	ReleaseSemaphore(m_Semaphore, 1, NULL);
+}
+
+void Semaphore::Notify(int how_many)
+{
+	ReleaseSemaphore(m_Semaphore, how_many, NULL);
+}
+
+//**********************************************************************************
+// Class Event
+//
+// This class encapsulates Windows API Event functionality
+//**********************************************************************************
+
+Event::Event(bool manual_reset)
+{
+	m_Event = CreateEvent(NULL, manual_reset, false, NULL);
+}
+
+Event::~Event(void)
+{
+	CloseHandle(m_Event);
+}
+
+void Event::Set(void)
+{
+	SetEvent(m_Event);
+}
+
+void Event::Reset(void)
+{
+	ResetEvent(m_Event);
+}
+
+DWORD Event::Wait(DWORD timeout)
+{
+	DWORD dwResult = WaitForSingleObject(m_Event, timeout);
+	switch (dwResult)
+	{
+	case WAIT_OBJECT_0:
+		return 0;
+	case WAIT_TIMEOUT:
+		return WAIT_TIMEOUT;
+	default:
+		return 1;
+	}
+}
+
+HANDLE Event::EventHandle() const
+{
+	return m_Event;
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/HtiGateway/src/util.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,739 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This module contains the implementation of Util class member functions. 
+*   Util class provides static utility functions for logging and string
+*	manipulation.
+*/
+
+// INCLUDE FILES
+#include "util.h"
+
+// command line parameters
+extern map<string, string> g_parameters;
+
+//**********************************************************************************
+// Class Util
+//
+// Provides static utility functions for logging and string handling.
+//**********************************************************************************
+
+// The default verbose level for Util output is error
+Util::VerboseLevel Util::iVerbose(Util::error);
+
+// The default output is without timestamp
+int Util::iTimestamp(0);
+
+#ifdef ENABLE_LOG_SYNC 
+	Mutex Util::iCritical;
+#endif
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: SetVerboseLevel
+
+    Description: Sets new verbose level by string:
+	           
+				 "none"
+				 "result"
+				 "error"
+				 "info"
+				 "debug"
+    
+    Parameters: const string& aVerbose : in: Verbose level as string
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::SetVerboseLevel(const string& aVerbose)
+{
+	string verbose(aVerbose);
+	ToLower(verbose);
+	if (verbose.compare("result") == 0)
+	{
+		iVerbose = result;
+	}
+	else if (verbose.compare("error") == 0)
+	{
+		iVerbose = error;
+	}
+	else if (verbose.compare("info") == 0)
+	{
+		iVerbose = info;
+	}
+	else if (verbose.compare("debug") == 0)
+	{
+		iVerbose = debug;
+	}
+	else
+	{
+	 	iVerbose = none;
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: SetVerboseLevel
+
+    Description: Sets new verbose level by enumeration.
+    
+    Parameters: const VerboseLevel aVerbose : in: Verbose level
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::SetVerboseLevel(const VerboseLevel aVerbose)
+{
+	iVerbose = aVerbose;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: GetVerboseLevel
+
+    Description: Returns current verbose level.
+    
+    Parameters: None
+
+    Return Values: VerboseLevel : Current verbose level
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+Util::VerboseLevel Util::GetVerboseLevel()
+{
+	return iVerbose;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: SetTimestamp
+
+    Description: Enables/disables timestamp from output by string "yes" or "no".
+    
+    Parameters: const string& aTimestamp : in : "yes" to enable timestamp, "no" to
+	                                            disable.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::SetTimestamp(const string& aTimestamp)
+{
+	string timestamp(aTimestamp);
+	ToLower(timestamp);
+	if (timestamp.compare("true") == 0)
+	{
+		SetTimestamp(1);
+	}
+	else
+	{
+		SetTimestamp(0);
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: SetTimestamp
+
+    Description: Enables/disables timestamp from output. 0 is disabled.
+    
+    Parameters: const int aTimestamp : in : Enable/disable time stamp
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::SetTimestamp(const int aTimestamp)
+{
+	iTimestamp = aTimestamp;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: ParseCmdLine
+
+    Description: Parses command line parameters to map. The map which is passed
+	             as argument must contain all valid keys (command line swicthes).
+				 Function adds values to map to all keys found from command line.
+				 The command line switch is form <key>=<value>. Default values for
+				 keys can be specified.
+    
+    Parameters: const int aArgc           : in     : The number of arguments
+	            char **aArgs              : in     : Pointer array to arguments
+				map<string, string>& aMap : in/out : Map containing possible command
+				                                     line switches (keys). Values of
+													 switches are returned as values.
+
+    Return Values: None
+
+    Errors/Exceptions: UtilError
+
+-------------------------------------------------------------------------------*/
+void Util::ParseCmdLine(const int aArgc,
+						char **aArgs,
+						map<string, string>& aMap) throw (UtilError)
+{
+	for (int i = 1; i < aArgc; i++)
+	{
+		string p(aArgs[i]);
+		string v;
+		int idx = p.find_first_of("=");
+		if (idx != string::npos)
+		{
+			if ((idx + 1) == p.length())
+			{
+				string err("Parameter '" + p.substr(0, idx) + "' without value");
+				throw UtilError(err, ERR_UTIL_NO_PARAM_VALUE);
+			}
+			v = &aArgs[i][idx + 1];
+			p = p.substr(0, idx);
+		}
+		else
+		{
+			v = "";
+		}
+
+		// 28.03.06 Disabled this "check" to enable parameter passing to plug-ins also
+		//string def;
+		//GetValue(p, aMap, def);
+		aMap[p] = v;
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: GetValue
+
+    Description: Returns value by key from a map.
+    
+    Parameters: const string& aKey        : in  : Key to value 
+				map<string, string>& aMap : in  : Map containing valid keys
+				string& aValue            : out : Value of key
+
+    Return Values: None
+
+    Errors/Exceptions: UtilError
+
+-------------------------------------------------------------------------------*/
+void Util::GetValue(const string& aKey,
+					const map<string,
+					string>& aMap, string& aValue) throw (UtilError)
+{
+	map<string, string>::const_iterator i = aMap.find(aKey);
+	if (i != aMap.end())
+	{
+		aValue = i->second;
+	}
+	else
+	{
+		string err("Unknown parameter '" + aKey + "'");
+		throw UtilError(err, ERR_UTIL_UNKNOWN_PARAM);
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: ReadProperties
+
+    Description: Reads properties from a file to a map. Line beginning with
+	             hash character ('#') are considered as comments. The form
+				 of prooerties in file is <property> = <value>.
+    
+    Parameters: const string& aFilename   : in  : Filename where properties are read
+	            map<string, string>& aMap : out : Map where property values are put
+
+    Return Values: None
+
+    Errors/Exceptions: UtilError
+
+-------------------------------------------------------------------------------*/
+void Util::ReadProperties(const string& aFilename,
+						  map<string, string>& aMap) throw (UtilError)
+{
+	ifstream in(aFilename.c_str());
+	if (!in)
+	{
+		string err("Cannot open properties file '");
+		err += aFilename + "'.";
+		throw UtilError(err, ERR_UTIL_PROPERTIES_NOT_FOUND);
+	}
+	while (in)
+	{
+		char tmp[256];
+		in.getline(tmp, 256);
+		string line(tmp);
+		if (line.length() == 0 || line.find_first_of("#") == 0)
+		{
+			continue;
+		}
+		int idx = line.find_first_of('=');
+		string v, p;
+		if (idx != string::npos)
+		{
+			p = line.substr(0, idx);
+			int r = p.find(" ");
+			while (r != string::npos)
+			{
+				p.replace(r, 1, "");
+				r = p.find(" ");
+			}
+			v = line.substr(idx + 1);
+			string::iterator i = v.begin();
+			int spaces = 0;
+			while (i != v.end() && *i == ' ')
+			{
+				++spaces;
+				++i;
+			}
+			v.erase(0, spaces);
+			if (v.length() == 0)
+			{
+				string err = "Value not specified for parameter '";
+				err += line.substr(0, idx) + "'.";
+				throw UtilError(err, ERR_UTIL_NO_PROPERTY_VALUE);			
+			}
+		}
+		else 
+		{
+			p = line;
+			v = "";
+		}
+		aMap[p] = v;
+	}
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Error
+
+    Description: Prints message to output in error level.
+    
+    Parameters: const string& aMsg : in : Error message to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Error(const string& aMsg)
+{
+	Print(cerr, aMsg, error);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Error
+
+    Description: Prints message to output in error level with error code number.
+    
+    Parameters: const string& aMsg : in : Error message to output
+				const long aCode   : in : Error code to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Error(const string& aMsg, const long aCode)
+{
+	Print(cerr, aMsg, error, aCode);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Log
+
+    Description: Prints message to output in result level.
+    
+    Parameters: const string& aMsg : in : Result message to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Log(const string& aMsg)
+{
+	Print(cout, aMsg, result);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Info
+
+    Description: Prints message to output in info level.
+    
+    Parameters: const string& aMsg : in : Info message to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Info(const string& aMsg)
+{
+	Print(cout, aMsg, info);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Debug
+
+    Description: Prints message to output in debug level.
+    
+    Parameters: const string& aMsg : in : Debug message to output
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Debug(const string& aMsg)
+{
+	Print(cout, aMsg, debug);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Print
+
+    Description: Prints output to a stream.
+    
+    Parameters: ostream& out              : in : Stream where to write
+                const string& aMsg        : in : Message to output
+                const VerboseLevel aLevel : in : Verbose level of message
+				const long aCode          : in : Possible error code if != 0
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Print(ostream& out,
+				 const string& aMsg,
+				 const VerboseLevel aLevel,
+				 const long aCode)
+{
+#ifdef ENABLE_LOG_SYNC 
+	iCritical.Lock();
+#endif
+
+	if (aLevel <= iVerbose)
+	{
+		if (iTimestamp)
+		{
+			char timestamp[128];
+			_strdate(timestamp);
+			char tmp[16];
+			_strtime(tmp);
+			strcat(timestamp, " ");
+			strcat(timestamp, tmp);
+			struct _timeb tb;
+			_ftime(&tb);
+			sprintf(tmp, ".%03d", tb.millitm);
+			strcat(timestamp, tmp);
+			out << "[" << timestamp << "] ";
+		}
+		//out << "[" << GetCurrentThreadId() << "] ";
+		out << aMsg;
+		//if (aLevel == debug)
+		{
+			OutputDebugString(aMsg.c_str());
+			OutputDebugString("\r\n");
+		}
+		if (aCode != 0)
+		{
+			out.setf(ios_base::hex, ios_base::basefield);
+			out << " (error: 0x" << aCode << ")";
+		}
+		out << endl;
+	}
+#ifdef ENABLE_LOG_SYNC 
+	iCritical.Unlock();
+#endif
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: ToLower
+
+    Description: Converts string to lower case.
+    
+    Parameters: string& aString : in/out : String which is converted to lower case
+
+    Return Values: string& : Reference to converted string.
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+string& Util::ToLower(string& aString)
+{
+	string::iterator p = aString.begin();
+	while (p != aString.end())
+	{
+		*p = tolower(*p);
+		++p;
+	}
+	return aString;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: ToUpper
+
+    Description: Converts string to upper case.
+    
+    Parameters: string& aString : in/out : String which is converted to upper case
+
+    Return Values: string& : Reference to converted string.
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+string& Util::ToUpper(string& aString)
+{
+	string::iterator p = aString.begin();
+	while (p != aString.end())
+	{
+		*p = toupper(*p);
+		++p;
+	}
+	return aString;
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Hex
+
+    Description: Prints hex dump of char table to output.
+    
+    Parameters: const char aData[] : in : Data to be output as hex dump
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Hex(const char aData[])
+{
+	string s(aData);
+	Hex(s);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Hex
+
+    Description: Prints hex dump of string to output.
+    
+    Parameters: const string& aMsg : in : Data to be output as hex dump
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Hex(const string& aMsg)
+{
+	Hex((const unsigned char *)aMsg.c_str(), aMsg.length());
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Hex
+
+    Description: Prints hex dump of data to output.
+    
+    Parameters: const unsigned char* aData : in : Pointer to data to be output
+	                                              as hex dump
+                const int aLength          : in : The lenght of data
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Hex(const unsigned char* aData, const int aLength)
+{
+	Hex((void *)aData, aLength);
+}
+
+/*-------------------------------------------------------------------------------
+
+    Class: Util
+
+    Method: Hex
+
+    Description: Prints hex dump of data to output.
+    
+    Parameters: void *aData       : in : Pointer to data to be output as hex dump
+                const int aLength : in : The lenght of data
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------*/
+void Util::Hex(void *aData, const int aLength)
+{
+	Hex(aData, aLength, NULL);
+}
+
+void Util::Hex(void* aData, const int aLength, string* aHexDump)
+{
+#ifdef ENABLE_LOG_SYNC 
+	iCritical.Lock();
+#endif
+
+	char line[16];
+	int line_len = 16;
+	int bytes_to_copy = 0;
+	int printed = 0;
+	bool print_out = (aHexDump == NULL ? true : false);
+	unsigned char *data = (unsigned char *)aData;
+
+	if (print_out)
+	{
+		printf("\n");
+	}
+	else
+	{
+		aHexDump->append("\r\n");
+	}
+	while (printed < aLength)
+	{
+		bytes_to_copy = ((aLength - printed >= line_len ? line_len : (aLength - printed)));
+		memset(line, 0, sizeof(line));
+		memcpy(line, &data[printed], bytes_to_copy);
+		for (int j = 0; j < line_len; j++)
+		{
+			char hex[4];
+			sprintf(hex, "%02X ", (unsigned char)line[j]);
+			if (print_out)
+			{
+				printf("%s", hex);
+			}
+			else
+			{
+				string s(hex);
+				aHexDump->append(s);
+			}
+		}
+		if (print_out) printf(" | ");
+		for (int j = 0; j < line_len; j++)
+		{
+			char c = line[j];
+			if (c >= ' ' && c <= 'z')
+			{
+				if (print_out)
+				{
+					printf("%c", c);
+				}
+				else
+				{
+					char tmp[2];
+					sprintf(tmp, "%c", c);
+					string s(tmp);
+					aHexDump->append(s);
+				}
+			} 
+			else
+			{
+				if (print_out)
+				{
+					printf(".");
+				}
+				else
+				{
+					aHexDump->append(".");
+				}
+			}
+		}
+		if (print_out)
+		{
+			printf("\n");
+		}
+		else
+		{
+			aHexDump->append("\r\n");
+		}
+		if ((printed - line_len) < aLength)
+		{
+			printed += 16;
+		}
+		else
+		{
+			printed = aLength - printed;
+		}
+	}
+	if (print_out) printf("\n");
+
+#ifdef ENABLE_LOG_SYNC 
+	iCritical.Unlock();
+#endif
+}
+
+void Util::CheckCommandlineParam( const string& paramname, string& paramvalue )
+{
+	// Command line parameter overrides ini-file value
+	if ( !g_parameters[paramname].empty() )
+		paramvalue = g_parameters[paramname];
+}
+
+// End of the file
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiApplication.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,818 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiApplicationH.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+#include "hticommon.h"
+
+// Application control commands
+// NOTE: Only unicode versions of commands are used.
+//const int CMD_HTI_START_PROCESS         = 0x02;
+const int CMD_HTI_START_PROCESS_U         = 0x03;
+//const int CMD_HTI_STATUS_PROCESS        = 0x04;
+const int CMD_HTI_STATUS_PROCESS_U        = 0x05;
+const int CMD_HTI_STATUS_PROCESSID        = 0x06;
+const int CMD_HTI_START_PROCESS_RET_VAL_U = 0x07;
+//const int CMD_HTI_STOP_PROCESS          = 0x08;
+const int CMD_HTI_STOP_PROCESS_U          = 0x09;
+const int CMD_HTI_STOP_PROCESSID          = 0x0A;
+const int CMD_HTI_GET_PROCESS_EXIT_CODE   = 0x0B;
+//const int CMD_HTI_LIST_PROCESSES        = 0x0C;
+const int CMD_HTI_LIST_PROCESSES_U        = 0x0D;
+//const int CMD_HTI_START_PROCESS_RET_VAL = 0x0E;
+//const int CMD_HTI_START_APP             = 0x10;
+const int CMD_HTI_START_APP_U             = 0x11;
+//const int CMD_HTI_START_APP_UID         = 0x12;
+const int CMD_HTI_START_APP_UID_U         = 0x13;
+//const int CMD_HTI_START_DOC             = 0x14;
+const int CMD_HTI_START_DOC_U             = 0x15;
+//const int CMD_HTI_STATUS_APP            = 0x16;
+const int CMD_HTI_STATUS_APP_U            = 0x17;
+//const int CMD_HTI_STATUS_DOC            = 0x18;
+const int CMD_HTI_STATUS_DOC_U            = 0x19;
+const int CMD_HTI_STATUS_APP_UID          = 0x1A;
+//const int CMD_HTI_STOP_APP              = 0x1C;
+const int CMD_HTI_STOP_APP_U              = 0x1D;
+//const int CMD_HTI_STOP_DOC              = 0x1E;
+const int CMD_HTI_STOP_DOC_U              = 0x1F;
+const int CMD_HTI_STOP_APP_UID            = 0x20;
+//const int CMD_HTI_LIST_APPS               = 0x24;
+const int CMD_HTI_LIST_APPS_U             = 0x25;
+
+// Application install commands
+//const int CMD_HTI_INSTALL_SOFTWARE        = 0x30;
+const int CMD_HTI_INSTALL_SOFTWARE_U        = 0x31;
+const int CMD_HTI_UNINSTALL_SOFTWARE        = 0x32;
+const int CMD_HTI_UNINSTALL_SOFTWARE_NAME_U = 0x33;
+//const int CMD_HTI_UNINSTALL_SOFTWARE_NAME   = 0x34;
+
+// Application control response codes
+const int CMD_RESP_OK               = 0xF0;
+const int CMD_RESP_NOT_FOUND        = 0xF1;
+const int CMD_RESP_ALREADY_RUNNING  = 0xF2;
+const int CMD_RESP_ALREADY_STOPPED  = 0xF3;
+const int CMD_RESP_RUNNING          = 0xF4;
+const int CMD_RESP_KILLED           = 0xF5;
+const int CMD_RESP_PANIC            = 0xF6;
+
+//**********************************************************************************
+// HELPER FUNCTIONS
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// ResponseCode2String
+//**********************************************************************************
+char* ResponseCode2String(struct soap* soap, BYTE code)
+{
+    char tmp[50]; // 50 should be more than enough
+
+    switch(code)
+    {
+    case CMD_RESP_OK:               sprintf(tmp, "ok"); break;
+    case CMD_RESP_NOT_FOUND:        sprintf(tmp, "not found"); break;
+    case CMD_RESP_ALREADY_RUNNING:  sprintf(tmp, "already running"); break;
+    case CMD_RESP_ALREADY_STOPPED:  sprintf(tmp, "already stopped"); break;
+    case CMD_RESP_RUNNING:          sprintf(tmp, "running"); break;
+    case CMD_RESP_KILLED:           sprintf(tmp, "killed"); break;
+    case CMD_RESP_PANIC:            sprintf(tmp, "panic"); break;
+    default:                        sprintf(tmp, "unknown response code 0x%02x", code);
+    }
+
+    char* text = (char*) soap_malloc(soap, strlen(tmp)+1); // +1 is for null character
+    memcpy(text, tmp, strlen(tmp)+1);
+    return text;
+}
+
+//**********************************************************************************
+// ExitTypeCode2String
+//**********************************************************************************
+char* ExitTypeCode2String(struct soap* soap, BYTE code)
+{
+    char tmp[50]; // 50 should be more than enough
+
+    switch(code)
+    {
+    case 0:  sprintf(tmp, "killed"); break;
+    case 1:  sprintf(tmp, "terminated"); break;
+    case 2:  sprintf(tmp, "panic"); break;
+    case 3:  sprintf(tmp, "running"); break;
+    default: sprintf(tmp, "unknown exit type code 0x%02x", code);
+    }
+
+    char* text = (char*) soap_malloc(soap, strlen(tmp)+1); // +1 is for null character
+    memcpy(text, tmp, strlen(tmp)+1);
+    return text;
+}
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// ns1__startProcess()
+//**********************************************************************************
+int ns1__startProcess(struct soap* soap,
+                      wchar_t *fileName,
+                      wchar_t *args,
+                      struct startProcessResponse &r)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, fileName, "fileName" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_START_PROCESS_U );
+    msg.AddWCStringWithLengthByte( fileName );
+    msg.AddWCStringWithLengthByte( args );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_30_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgMinLen( 1 ) )
+        return SOAP_FAULT;
+
+    r._returnstartProcessResult.status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    if( msg.GetByte( 0 ) == CMD_RESP_OK )
+    {
+        // pid only returned if found
+        if ( msg.CheckMsgExactLen( 5 ) )
+            return SOAP_FAULT;
+        r._returnstartProcessResult.pid = msg.GetInt(1);
+    }
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__stopProcess()
+//**********************************************************************************
+int ns1__stopProcess(struct soap* soap,
+                     wchar_t *matchPattern,
+                     char *&result)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, matchPattern, "matchPattern" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STOP_PROCESS_U );
+    msg.AddWCStringWithLengthByte( matchPattern );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    result = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__stopProcessById()
+//**********************************************************************************
+int ns1__stopProcessById(struct soap* soap,
+                         int pid,
+                         char *&result)
+{
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STOP_PROCESSID );
+    msg.AddInt( pid );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    result = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getProcessStatus()
+//**********************************************************************************
+int ns1__getProcessStatus(struct soap* soap,
+                          wchar_t *matchPattern,
+                          char* &status)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, matchPattern, "matchPattern" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STATUS_PROCESS_U );
+    msg.AddWCStringWithLengthByte( matchPattern );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getProcessStatusById()
+//**********************************************************************************
+int ns1__getProcessStatusById(struct soap* soap,
+                              int pid,
+                              char* &status)
+{
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STATUS_PROCESSID );
+    msg.AddInt( pid );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__startApp()
+//**********************************************************************************
+int ns1__startApp(struct soap* soap,
+                  wchar_t *appName,
+                  wchar_t *docName,
+                  struct startAppResponse &r)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, appName, "appName" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_START_APP_U );
+    msg.AddWCStringWithLengthByte( appName );
+    msg.AddWCStringWithLengthByte( docName );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgMinLen( 1 ) )
+        return SOAP_FAULT;
+
+    r._returnstartAppResult.status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    if( msg.GetByte( 0 ) == CMD_RESP_OK )
+    {
+        // threadId only returned if found
+        if ( msg.CheckMsgExactLen( 5 ) )
+            return SOAP_FAULT;
+        r._returnstartAppResult.threadId = msg.GetInt(1);
+    }
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__startAppByUid()
+//**********************************************************************************
+int ns1__startAppByUid(struct soap* soap,
+                       int uid,
+                       wchar_t *docName,
+                       struct startAppByUidResponse &r)
+{
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_START_APP_UID_U );
+    msg.AddInt( uid );
+    msg.AddWCStringWithLengthByte( docName );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgMinLen( 1 ) )
+        return SOAP_FAULT;
+
+    r._returnstartAppByUidResult.status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    if( msg.GetByte( 0 ) == CMD_RESP_OK )
+    {
+        // threadId only returned if found
+        if ( msg.CheckMsgExactLen( 5 ) )
+            return SOAP_FAULT;
+        r._returnstartAppByUidResult.threadId = msg.GetInt(1);
+    }
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__startDoc()
+//**********************************************************************************
+int ns1__startDoc(struct soap* soap,
+                  wchar_t *docName,
+                  struct startDocResponse &r)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, docName, "docName" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_START_DOC_U );
+    msg.AddWCStringWithLengthByte( docName );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgMinLen( 1 ) )
+        return SOAP_FAULT;
+
+    r._returnstartDocResult.status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    if( msg.GetByte( 0 ) == CMD_RESP_OK )
+    {
+        // threadId only returned if found
+        if ( msg.CheckMsgExactLen( 5 ) )
+            return SOAP_FAULT;
+        r._returnstartDocResult.threadId = msg.GetInt(1);
+    }
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getAppStatus()
+//**********************************************************************************
+int ns1__getAppStatus(struct soap* soap,
+                      wchar_t *appName,
+                      char* &status)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, appName, "appName" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STATUS_APP_U );
+    msg.AddWCStringWithLengthByte( appName );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getAppStatusByUid()
+//**********************************************************************************
+int ns1__getAppStatusByUid(struct soap* soap,
+                           int uid,
+                           char* &status)
+{
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STATUS_APP_UID );
+    msg.AddInt( uid );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getAppStatusByDoc()
+//**********************************************************************************
+int ns1__getAppStatusByDoc(struct soap* soap,
+                           wchar_t *docName,
+                           char* &status)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, docName, "docName" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STATUS_DOC_U );
+    msg.AddWCStringWithLengthByte( docName );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__stopApp()
+//**********************************************************************************
+int ns1__stopApp(struct soap* soap,
+                 wchar_t *appName,
+                 char *&result)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, appName, "appName" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STOP_APP_U );
+    msg.AddWCStringWithLengthByte( appName );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    result = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__stopAppByUid()
+//**********************************************************************************
+int ns1__stopAppByUid(struct soap* soap,
+                      int uid,
+                      char *&result)
+{
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STOP_APP_UID );
+    msg.AddInt( uid );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    result = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__stopAppByDoc()
+//**********************************************************************************
+int ns1__stopAppByDoc(struct soap* soap,
+                      wchar_t *docName,
+                      char *&result)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, docName, "docName" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_STOP_DOC_U );
+    msg.AddWCStringWithLengthByte( docName );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) )
+        return SOAP_FAULT;
+
+    result = ResponseCode2String( soap, msg.GetByte(0) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__listProcesses()
+//**********************************************************************************
+int ns1__listProcesses(struct soap* soap,
+                       wchar_t *matchPattern,
+                       ArrayOfHtiProcess *HtiProcesses)
+{
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_LIST_PROCESSES_U );
+    msg.AddWCStringWithLengthByte( matchPattern );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgMinLen( 1 ) )
+        return SOAP_FAULT;
+
+    if(msg.GetByte(0) != CMD_RESP_OK)
+    {
+        // This sould happen only if message is corrupted somehow...
+        soap->error = soap_receiver_fault_format(soap, "HtiError",
+            "response code error (0x%x)", msg.GetByte(0));
+        return SOAP_FAULT;
+    }
+
+    // Fill & alloc soap stuff
+    HtiProcesses->__size = (int) msg.GetWord(1);
+    HtiProcesses->__ptr = soap_new_ns1__HtiProcess(soap, HtiProcesses->__size);
+
+    // Go through processes
+    int offset = 3;
+    ns1__HtiProcess *process = HtiProcesses->__ptr;
+    for(int i = 0; i < HtiProcesses->__size; i++)
+    {
+        process->processId = msg.GetInt(offset);//pid;
+        process->processStatus = ResponseCode2String(soap, msg.GetByte(offset+4));
+
+        // Get processname
+        char* tmp = (char*) msg.GetMsgBody();
+        tmp += offset+6;
+        int processNameLen = msg.GetByte(offset+5);
+        process->processName = (char*) soap_malloc(soap, processNameLen+1);
+        memcpy(process->processName, tmp, processNameLen);
+        process->processName[processNameLen] = 0x0; //  add null
+
+        // for the next iteration
+        offset += 4+1+1+processNameLen;
+        process++;
+    }
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__startProcessRetVal()
+//**********************************************************************************
+int ns1__startProcessRetVal(struct soap* soap,
+                            wchar_t *fileName,
+                            wchar_t *args,
+                            struct startProcessResponse &r)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter( soap, fileName, "fileName" ) )
+        return SOAP_FAULT;
+
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_START_PROCESS_RET_VAL_U );
+    msg.AddWCStringWithLengthByte( fileName );
+    msg.AddWCStringWithLengthByte( args );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_30_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgMinLen( 1 ) )
+        return SOAP_FAULT;
+
+    r._returnstartProcessResult.status = ResponseCode2String( soap, msg.GetByte(0) );
+
+    if( msg.GetByte( 0 ) == CMD_RESP_OK )
+    {
+        // pid only returned if found
+        if ( msg.CheckMsgExactLen( 5 ) )
+            return SOAP_FAULT;
+        r._returnstartProcessResult.pid = msg.GetInt(1);
+    }
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getProcessExitCode()
+//**********************************************************************************
+int ns1__getProcessExitCode(struct soap* soap,
+                            int pid,
+                            struct getProcessExitCodeResponse &r)
+{
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_GET_PROCESS_EXIT_CODE );
+    msg.AddInt( pid );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgMinLen( 7 ) )
+        return SOAP_FAULT;
+    if ( msg.GetByte( 0 ) != CMD_RESP_OK )
+        return SOAP_FAULT;
+
+    r._returngetProcessExitCodeResult.exitType = ExitTypeCode2String( soap, msg.GetByte( 1 ) );
+    r._returngetProcessExitCodeResult.exitReason = msg.GetInt( 2 );
+    r._returngetProcessExitCodeResult.exitCategory = msg.GetSoapString( 7, (int) msg.GetByte( 6 ) );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__installSoftware()
+//**********************************************************************************
+int ns1__installSoftware(struct soap* soap,
+                         wchar_t *installPackagePath,
+                         bool upgrade,
+                         bool optionalItems,
+                         bool ocsp,
+                         bool ignoreOCSPWarnings,
+                         bool installUntrusted,
+                         bool allowPackageInfo,
+                         bool grantUserCapabilities,
+                         bool killApp,
+                         bool overwrite,
+                         bool download,
+                         wchar_t *username,
+                         wchar_t *password,
+                         char *drive,
+                         unsigned char language,
+                         bool usePhoneLanguage,
+                         bool upgradeData,
+                         struct ns1__installSoftwareResponse *out)
+{
+    // Check parameters
+    if ( check_mandatory_wcstring_parameter(
+             soap, installPackagePath, "installPackagePath" ) )
+        return SOAP_FAULT;
+    if ( check_mandatory_string_parameter( soap, drive, "drive" ) )
+        return SOAP_FAULT;
+
+    // Construct HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_INSTALL_SOFTWARE_U );
+    msg.AddWCStringWithLengthByte( installPackagePath );
+    msg.AddByte( upgrade );
+    msg.AddByte( optionalItems );
+    msg.AddByte( ocsp );
+    msg.AddByte( ignoreOCSPWarnings );
+    msg.AddByte( installUntrusted );
+    msg.AddByte( allowPackageInfo );
+    msg.AddByte( grantUserCapabilities );
+    msg.AddByte( killApp );
+    msg.AddByte( overwrite );
+    msg.AddByte( download );
+    msg.AddWCStringWithLengthByteZero( username );
+    msg.AddWCStringWithLengthByteZero( password );
+    msg.AddString( drive );
+    msg.AddByte( language );
+    msg.AddByte( usePhoneLanguage );
+    msg.AddByte( upgradeData );
+
+    // Send message
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_60_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) != SOAP_OK )
+        return SOAP_FAULT;
+    if ( msg.GetByte( 0 ) != CMD_RESP_OK )
+        return SOAP_FAULT;
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__uninstallSoftware()
+//**********************************************************************************
+int ns1__uninstallSoftware(struct soap* soap,
+                           int uid,
+                           bool killApp,
+                           bool breakDependency,
+                           enum ns1__mimeType  mimeType,
+                           struct ns1__uninstallSoftwareResponse *out)
+{
+    // Construct HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_UNINSTALL_SOFTWARE );
+    msg.AddInt( uid );
+    msg.AddByte( killApp );
+    msg.AddByte( breakDependency );
+    msg.AddByte( mimeType );
+
+    // Send message
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_60_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) != SOAP_OK )
+        return SOAP_FAULT;
+    if ( msg.GetByte( 0 ) != CMD_RESP_OK )
+        return SOAP_FAULT;
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__uninstallSoftwareByName()
+//**********************************************************************************
+int ns1__uninstallSoftwareByName(struct soap* soap,
+                                 wchar_t *packageName,
+                                 bool killApp,
+                                 bool breakDependency,
+                                 enum ns1__mimeType  mimeType,
+                                 struct ns1__uninstallSoftwareByNameResponse *out)
+{
+    if ( check_mandatory_wcstring_parameter(
+             soap, packageName, "packageName" ) )
+        return SOAP_FAULT;
+
+    // Construct HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_UNINSTALL_SOFTWARE_NAME_U );
+    msg.AddWCStringWithLengthByte( packageName );
+    msg.AddByte( killApp );
+    msg.AddByte( breakDependency );
+    msg.AddByte( mimeType );
+
+    // Send message
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_60_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgExactLen( 1 ) != SOAP_OK )
+        return SOAP_FAULT;
+    if ( msg.GetByte( 0 ) != CMD_RESP_OK )
+        return SOAP_FAULT;
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__listRunningApps()
+//**********************************************************************************
+int ns1__listRunningApps(struct soap* soap,
+                         bool includeHidden,
+                         bool includeSystem,
+                         ArrayOfHtiRunningApp *htiApps)
+{
+    // Construct & send HTI message
+    HtiMsgHelper msg( soap, HTI_APPLICATION_UID, CMD_HTI_LIST_APPS_U );
+    msg.AddByte( includeHidden );
+    msg.AddByte( includeSystem );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    // Check response
+    if ( msg.CheckMsgMinLen( 3 ) )
+        return SOAP_FAULT;
+
+    if ( msg.GetByte(0) != CMD_RESP_OK )
+    {
+        // This sould happen only if message is corrupted somehow...
+        soap->error = soap_receiver_fault_format(soap, "HtiError",
+            "response code error (0x%x)", msg.GetByte(0));
+        return SOAP_FAULT;
+    }
+
+    // Fill & alloc soap stuff
+    htiApps->__size = (int) msg.GetWord( 1 );
+    htiApps->__ptr = soap_new_ns1__HtiRunningApp( soap, htiApps->__size );
+
+    // Go through apps
+    int offset = 3;
+    ns1__HtiRunningApp *app = htiApps->__ptr;
+    for ( int i = 0; i < htiApps->__size; i++ )
+    {
+        // App UID
+        app->uid = msg.GetInt( offset );
+        offset += 4;
+
+        // Caption
+        int captionLen = msg.GetByte( offset );
+        offset++;
+        app->caption = msg.GetSoapWCString( offset, captionLen );
+        offset += captionLen * 2;
+
+        // Document name
+        int docLen = msg.GetByte( offset );
+        offset++;
+        app->document = msg.GetSoapWCString( offset, docLen );
+        offset += docLen * 2;
+
+        // Flags
+        app->hidden = msg.GetByte( offset );
+        offset++;
+        app->system = msg.GetByte( offset );
+        offset++;
+        app->ready = msg.GetByte( offset );
+        offset++;
+        app->busy = msg.GetByte( offset );
+        offset++;
+        app->closable = msg.GetByte( offset );
+        offset++;   
+
+        // Advance the array pointer for the next iteration
+        app++;
+    }
+
+    return SOAP_OK;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiApplication.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,253 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiApplication
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char*		    xsd__string;
+typedef wchar_t *	    xsd__string_;
+typedef int			    xsd__int;
+typedef bool            xsd__boolean;
+typedef unsigned char	xsd__unsignedByte;
+
+enum ns1__mimeType { sisx, sis, pip, jad, jar, java, jarx };
+
+struct ns1__startProcessResult
+{
+	xsd__string		status;
+	xsd__int		pid;
+};
+
+struct ns1__startAppByUidResult
+{
+	xsd__string		status;
+	xsd__int 		threadId;
+};
+
+struct ns1__startDocResult
+{
+	xsd__string		status;
+	xsd__int 		threadId;
+};
+
+struct ns1__startAppResult
+{
+	xsd__string		status;
+	xsd__int 		threadId;
+};
+
+struct ns1__getProcessExitCodeResult
+{
+    xsd__string     exitType;
+    xsd__int        exitReason;
+    xsd__string     exitCategory;
+};
+
+class ns1__HtiProcess
+{
+public:
+	xsd__int		processId;
+	xsd__string		processName;
+	xsd__string		processStatus;
+};
+
+class ArrayOfHtiProcess
+{
+public:
+    ns1__HtiProcess *__ptr;
+    int				__size;
+};
+
+class ns1__HtiRunningApp
+{
+public:
+    xsd__int        uid;
+    xsd__string_    caption;
+    xsd__string_    document;
+    xsd__boolean    hidden;
+    xsd__boolean    system;
+    xsd__boolean    ready;
+    xsd__boolean    busy;
+    xsd__boolean    closable;
+};
+
+class ArrayOfHtiRunningApp
+{
+public:
+    ns1__HtiRunningApp     *__ptr;
+    int             __size;
+};
+
+struct startProcessResponse{struct ns1__startProcessResult _returnstartProcessResult;};
+//gsoap ns1 service method-action: startProcess "HtiApplication"
+int ns1__startProcess(
+	xsd__string_	fileName,
+	xsd__string_	args,
+	struct startProcessResponse &r
+);
+
+//gsoap ns1 service method-action: stopProcess "HtiApplication"
+int ns1__stopProcess(
+	xsd__string_	matchPattern,
+	xsd__string		&result
+);
+
+//gsoap ns1 service method-action: stopProcessById "HtiApplication"
+int ns1__stopProcessById(
+	xsd__int		pid,
+	xsd__string		&result
+);
+
+//gsoap ns1 service method-action: getProcessStatus "HtiApplication"
+int ns1__getProcessStatus(
+	xsd__string_	matchPattern,
+	xsd__string		&status
+);
+
+//gsoap ns1 service method-action: getProcessStatusById "HtiApplication"
+int ns1__getProcessStatusById(
+	xsd__int		pid,
+	xsd__string		&status
+);
+
+struct startAppResponse{struct ns1__startAppResult _returnstartAppResult;};
+//gsoap ns1 service method-action: startApp "HtiApplication"
+int ns1__startApp(
+	xsd__string_	appName,
+	xsd__string_	docName,
+	struct startAppResponse& r
+);
+
+struct startAppByUidResponse{struct ns1__startAppByUidResult _returnstartAppByUidResult;};
+//gsoap ns1 service method-action: startAppByUid "HtiApplication"
+int ns1__startAppByUid(
+	xsd__int		uid,
+	xsd__string_	docName,
+	struct startAppByUidResponse& r
+);
+
+struct startDocResponse{struct ns1__startDocResult _returnstartDocResult;};
+//gsoap ns1 service method-action: startDoc "HtiApplication"
+int ns1__startDoc(
+	xsd__string_	docName,
+	struct startDocResponse& r
+);
+
+//gsoap ns1 service method-action: getAppStatus "HtiApplication"
+int ns1__getAppStatus(
+	xsd__string_	appName,
+	xsd__string		&status
+);
+
+//gsoap ns1 service method-action: getAppStatusByUid "HtiApplication"
+int ns1__getAppStatusByUid(
+	xsd__int		uid,
+	xsd__string		&status
+);
+
+//gsoap ns1 service method-action: getAppStatusByDoc "HtiApplication"
+int ns1__getAppStatusByDoc(
+	xsd__string_	docName,
+	xsd__string		&status
+);
+
+//gsoap ns1 service method-action: stopApp "HtiApplication"
+int ns1__stopApp(
+	xsd__string_	appName,
+	xsd__string		&result
+);
+
+//gsoap ns1 service method-action: stopAppByUid "HtiApplication"
+int ns1__stopAppByUid(
+	xsd__int		uid,
+	xsd__string		&result
+);
+
+//gsoap ns1 service method-action: stopAppByDoc "HtiApplication"
+int ns1__stopAppByDoc(
+	xsd__string_	docName,
+	xsd__string		&result
+);
+
+//gsoap ns1 service method-action: listProcesses "HtiApplication"
+int ns1__listProcesses(
+	xsd__string_	matchPattern,
+	ArrayOfHtiProcess *HtiProcesses
+);
+
+//gsoap ns1 service method-action: startProcessRetVal "HtiApplication"
+int ns1__startProcessRetVal(
+	xsd__string_	fileName,
+	xsd__string_	args,
+	struct startProcessResponse &r
+);
+
+struct getProcessExitCodeResponse{struct ns1__getProcessExitCodeResult _returngetProcessExitCodeResult;};
+//gsoap ns1 service method-action: getProcessExitCode "HtiApplication"
+int ns1__getProcessExitCode(
+	xsd__int        pid,
+	struct getProcessExitCodeResponse &r
+);
+
+//gsoap ns1 service method-action: installSoftware "HtiApplication"
+int ns1__installSoftware(
+    xsd__string_    installPackagePath,
+    xsd__boolean    upgrade,
+    xsd__boolean    optionalItems,
+    xsd__boolean    ocsp,
+    xsd__boolean    ignoreOCSPWarnings,
+    xsd__boolean    installUntrusted,
+    xsd__boolean    allowPackageInfo,
+    xsd__boolean    grantUserCapabilities,
+    xsd__boolean    killApp,
+    xsd__boolean    overwrite,
+    xsd__boolean    download,
+    xsd__string_    username,
+    xsd__string_    password,
+    xsd__string     drive,
+    xsd__unsignedByte language,
+    xsd__boolean    usePhoneLanguage,
+    xsd__boolean    upgradeData,
+    struct ns1__installSoftwareResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: uninstallSoftware "HtiApplication"
+int ns1__uninstallSoftware(
+    xsd__int            uid,
+    xsd__boolean        killApp,
+    xsd__boolean        breakDependency,
+    enum ns1__mimeType  mimeType,
+    struct ns1__uninstallSoftwareResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: uninstallSoftwareByName "HtiApplication"
+int ns1__uninstallSoftwareByName(
+    xsd__string_        packageName,
+    xsd__boolean        killApp,
+    xsd__boolean        breakDependency,
+    enum ns1__mimeType  mimeType,
+    struct ns1__uninstallSoftwareByNameResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: listRunningApps "HtiApplication"
+int ns1__listRunningApps(
+	xsd__boolean           includeHidden,
+    xsd__boolean           includeSystem,
+	ArrayOfHtiRunningApp   *htiApps
+);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiApplication.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,248 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiApplication"
+	ProjectGUID="{B474C5F8-3653-4D69-A0A2-B85B9F31DCAA}"
+	RootNamespace="HtiApplication"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiApplication.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiApplicationServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiApplication.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiApplication.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiApplicationH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiApplicationStub.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiApplication.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,685 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiApplication"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <simpleType name="mimeType">
+   <restriction base="xsd:string">
+    <enumeration value="sisx"/>
+    <enumeration value="sis"/>
+    <enumeration value="pip"/>
+    <enumeration value="jad"/>
+    <enumeration value="jar"/>
+    <enumeration value="java"/>
+    <enumeration value="jarx"/>
+   </restriction>
+  </simpleType>
+  <complexType name="startProcessResult">
+   <sequence>
+     <element name="status" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="pid" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="startAppByUidResult">
+   <sequence>
+     <element name="status" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="threadId" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="startDocResult">
+   <sequence>
+     <element name="status" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="threadId" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="startAppResult">
+   <sequence>
+     <element name="status" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="threadId" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="getProcessExitCodeResult">
+   <sequence>
+     <element name="exitType" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="exitReason" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="exitCategory" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="HtiProcess">
+   <sequence>
+     <element name="processId" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="processName" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="processStatus" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfHtiProcess">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="ns1:HtiProcess" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ns1:HtiProcess[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <complexType name="HtiRunningApp">
+   <sequence>
+     <element name="uid" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="caption" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="document" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="hidden" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+     <element name="system" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+     <element name="ready" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+     <element name="busy" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+     <element name="closable" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfHtiRunningApp">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="ns1:HtiRunningApp" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ns1:HtiRunningApp[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <!-- operation request element -->
+  <element name="fileName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="args" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="returnstartProcessResult" type="ns1:startProcessResult"/>
+  <!-- operation request element -->
+  <element name="matchPattern" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="result" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="pid" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="status" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="appName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="docName" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="returnstartAppResult" type="ns1:startAppResult"/>
+  <!-- operation request element -->
+  <element name="uid" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="returnstartAppByUidResult" type="ns1:startAppByUidResult"/>
+  <!-- operation response element -->
+  <element name="returnstartDocResult" type="ns1:startDocResult"/>
+  <!-- operation response element -->
+  <element name="HtiProcesses" type="ns1:ArrayOfHtiProcess"/>
+  <!-- operation response element -->
+  <element name="returngetProcessExitCodeResult" type="ns1:getProcessExitCodeResult"/>
+  <!-- operation request element -->
+  <element name="installPackagePath" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="upgrade" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="optionalItems" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="ocsp" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="ignoreOCSPWarnings" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="installUntrusted" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="allowPackageInfo" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="grantUserCapabilities" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="killApp" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="overwrite" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="download" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="username" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="password" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="drive" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="language" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="usePhoneLanguage" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="upgradeData" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="breakDependency" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="mimeType" type="ns1:mimeType"/>
+  <!-- operation request element -->
+  <element name="packageName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="includeHidden" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="includeSystem" type="xsd:boolean"/>
+  <!-- operation response element -->
+  <element name="htiApps" type="ns1:ArrayOfHtiRunningApp"/>
+ </schema>
+
+</types>
+
+<message name="startProcess">
+ <part name="fileName" element="ns1:fileName"/>
+ <part name="args" element="ns1:args"/>
+</message>
+
+<message name="startProcessResponse">
+ <part name="returnstartProcessResult" element="ns1:returnstartProcessResult"/>
+</message>
+
+<message name="stopProcessRequest">
+ <part name="matchPattern" element="ns1:matchPattern"/>
+</message>
+
+<message name="stopProcessResponse">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<message name="stopProcessByIdRequest">
+ <part name="pid" element="ns1:pid"/>
+</message>
+
+<message name="stopProcessByIdResponse">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<message name="getProcessStatusRequest">
+ <part name="matchPattern" element="ns1:matchPattern"/>
+</message>
+
+<message name="getProcessStatusResponse">
+ <part name="status" element="ns1:status"/>
+</message>
+
+<message name="getProcessStatusByIdRequest">
+ <part name="pid" element="ns1:pid"/>
+</message>
+
+<message name="getProcessStatusByIdResponse">
+ <part name="status" element="ns1:status"/>
+</message>
+
+<message name="startApp">
+ <part name="appName" element="ns1:appName"/>
+ <part name="docName" element="ns1:docName"/>
+</message>
+
+<message name="startAppResponse">
+ <part name="returnstartAppResult" element="ns1:returnstartAppResult"/>
+</message>
+
+<message name="startAppByUid">
+ <part name="uid" element="ns1:uid"/>
+ <part name="docName" element="ns1:docName"/>
+</message>
+
+<message name="startAppByUidResponse">
+ <part name="returnstartAppByUidResult" element="ns1:returnstartAppByUidResult"/>
+</message>
+
+<message name="startDoc">
+ <part name="docName" element="ns1:docName"/>
+</message>
+
+<message name="startDocResponse">
+ <part name="returnstartDocResult" element="ns1:returnstartDocResult"/>
+</message>
+
+<message name="getAppStatusRequest">
+ <part name="appName" element="ns1:appName"/>
+</message>
+
+<message name="getAppStatusResponse">
+ <part name="status" element="ns1:status"/>
+</message>
+
+<message name="getAppStatusByUidRequest">
+ <part name="uid" element="ns1:uid"/>
+</message>
+
+<message name="getAppStatusByUidResponse">
+ <part name="status" element="ns1:status"/>
+</message>
+
+<message name="getAppStatusByDocRequest">
+ <part name="docName" element="ns1:docName"/>
+</message>
+
+<message name="getAppStatusByDocResponse">
+ <part name="status" element="ns1:status"/>
+</message>
+
+<message name="stopAppRequest">
+ <part name="appName" element="ns1:appName"/>
+</message>
+
+<message name="stopAppResponse">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<message name="stopAppByUidRequest">
+ <part name="uid" element="ns1:uid"/>
+</message>
+
+<message name="stopAppByUidResponse">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<message name="stopAppByDocRequest">
+ <part name="docName" element="ns1:docName"/>
+</message>
+
+<message name="stopAppByDocResponse">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<message name="listProcessesRequest">
+ <part name="matchPattern" element="ns1:matchPattern"/>
+</message>
+
+<message name="listProcessesResponse">
+ <part name="HtiProcesses" element="ns1:HtiProcesses"/>
+</message>
+
+<message name="startProcessRetVal">
+ <part name="fileName" element="ns1:fileName"/>
+ <part name="args" element="ns1:args"/>
+</message>
+
+<message name="getProcessExitCode">
+ <part name="pid" element="ns1:pid"/>
+</message>
+
+<message name="getProcessExitCodeResponse">
+ <part name="returngetProcessExitCodeResult" element="ns1:returngetProcessExitCodeResult"/>
+</message>
+
+<message name="installSoftware">
+ <part name="installPackagePath" element="ns1:installPackagePath"/>
+ <part name="upgrade" element="ns1:upgrade"/>
+ <part name="optionalItems" element="ns1:optionalItems"/>
+ <part name="ocsp" element="ns1:ocsp"/>
+ <part name="ignoreOCSPWarnings" element="ns1:ignoreOCSPWarnings"/>
+ <part name="installUntrusted" element="ns1:installUntrusted"/>
+ <part name="allowPackageInfo" element="ns1:allowPackageInfo"/>
+ <part name="grantUserCapabilities" element="ns1:grantUserCapabilities"/>
+ <part name="killApp" element="ns1:killApp"/>
+ <part name="overwrite" element="ns1:overwrite"/>
+ <part name="download" element="ns1:download"/>
+ <part name="username" element="ns1:username"/>
+ <part name="password" element="ns1:password"/>
+ <part name="drive" element="ns1:drive"/>
+ <part name="language" element="ns1:language"/>
+ <part name="usePhoneLanguage" element="ns1:usePhoneLanguage"/>
+ <part name="upgradeData" element="ns1:upgradeData"/>
+</message>
+
+<message name="installSoftwareResponse">
+</message>
+
+<message name="uninstallSoftware">
+ <part name="uid" element="ns1:uid"/>
+ <part name="killApp" element="ns1:killApp"/>
+ <part name="breakDependency" element="ns1:breakDependency"/>
+ <part name="mimeType" element="ns1:mimeType"/>
+</message>
+
+<message name="uninstallSoftwareResponse">
+</message>
+
+<message name="uninstallSoftwareByName">
+ <part name="packageName" element="ns1:packageName"/>
+ <part name="killApp" element="ns1:killApp"/>
+ <part name="breakDependency" element="ns1:breakDependency"/>
+ <part name="mimeType" element="ns1:mimeType"/>
+</message>
+
+<message name="uninstallSoftwareByNameResponse">
+</message>
+
+<message name="listRunningAppsRequest">
+ <part name="includeHidden" element="ns1:includeHidden"/>
+ <part name="includeSystem" element="ns1:includeSystem"/>
+</message>
+
+<message name="listRunningAppsResponse">
+ <part name="htiApps" element="ns1:htiApps"/>
+</message>
+
+<portType name="HtiApplicationPortType">
+ <operation name="startProcess">
+  <documentation>Service definition of function ns1__startProcess</documentation>
+  <input message="tns:startProcess"/>
+  <output message="tns:startProcessResponse"/>
+ </operation>
+ <operation name="stopProcess">
+  <documentation>Service definition of function ns1__stopProcess</documentation>
+  <input message="tns:stopProcessRequest"/>
+  <output message="tns:stopProcessResponse"/>
+ </operation>
+ <operation name="stopProcessById">
+  <documentation>Service definition of function ns1__stopProcessById</documentation>
+  <input message="tns:stopProcessByIdRequest"/>
+  <output message="tns:stopProcessByIdResponse"/>
+ </operation>
+ <operation name="getProcessStatus">
+  <documentation>Service definition of function ns1__getProcessStatus</documentation>
+  <input message="tns:getProcessStatusRequest"/>
+  <output message="tns:getProcessStatusResponse"/>
+ </operation>
+ <operation name="getProcessStatusById">
+  <documentation>Service definition of function ns1__getProcessStatusById</documentation>
+  <input message="tns:getProcessStatusByIdRequest"/>
+  <output message="tns:getProcessStatusByIdResponse"/>
+ </operation>
+ <operation name="startApp">
+  <documentation>Service definition of function ns1__startApp</documentation>
+  <input message="tns:startApp"/>
+  <output message="tns:startAppResponse"/>
+ </operation>
+ <operation name="startAppByUid">
+  <documentation>Service definition of function ns1__startAppByUid</documentation>
+  <input message="tns:startAppByUid"/>
+  <output message="tns:startAppByUidResponse"/>
+ </operation>
+ <operation name="startDoc">
+  <documentation>Service definition of function ns1__startDoc</documentation>
+  <input message="tns:startDoc"/>
+  <output message="tns:startDocResponse"/>
+ </operation>
+ <operation name="getAppStatus">
+  <documentation>Service definition of function ns1__getAppStatus</documentation>
+  <input message="tns:getAppStatusRequest"/>
+  <output message="tns:getAppStatusResponse"/>
+ </operation>
+ <operation name="getAppStatusByUid">
+  <documentation>Service definition of function ns1__getAppStatusByUid</documentation>
+  <input message="tns:getAppStatusByUidRequest"/>
+  <output message="tns:getAppStatusByUidResponse"/>
+ </operation>
+ <operation name="getAppStatusByDoc">
+  <documentation>Service definition of function ns1__getAppStatusByDoc</documentation>
+  <input message="tns:getAppStatusByDocRequest"/>
+  <output message="tns:getAppStatusByDocResponse"/>
+ </operation>
+ <operation name="stopApp">
+  <documentation>Service definition of function ns1__stopApp</documentation>
+  <input message="tns:stopAppRequest"/>
+  <output message="tns:stopAppResponse"/>
+ </operation>
+ <operation name="stopAppByUid">
+  <documentation>Service definition of function ns1__stopAppByUid</documentation>
+  <input message="tns:stopAppByUidRequest"/>
+  <output message="tns:stopAppByUidResponse"/>
+ </operation>
+ <operation name="stopAppByDoc">
+  <documentation>Service definition of function ns1__stopAppByDoc</documentation>
+  <input message="tns:stopAppByDocRequest"/>
+  <output message="tns:stopAppByDocResponse"/>
+ </operation>
+ <operation name="listProcesses">
+  <documentation>Service definition of function ns1__listProcesses</documentation>
+  <input message="tns:listProcessesRequest"/>
+  <output message="tns:listProcessesResponse"/>
+ </operation>
+ <operation name="startProcessRetVal">
+  <documentation>Service definition of function ns1__startProcessRetVal</documentation>
+  <input message="tns:startProcessRetVal"/>
+  <output message="tns:startProcessResponse"/>
+ </operation>
+ <operation name="getProcessExitCode">
+  <documentation>Service definition of function ns1__getProcessExitCode</documentation>
+  <input message="tns:getProcessExitCode"/>
+  <output message="tns:getProcessExitCodeResponse"/>
+ </operation>
+ <operation name="installSoftware">
+  <documentation>Service definition of function ns1__installSoftware</documentation>
+  <input message="tns:installSoftware"/>
+  <output message="tns:installSoftwareResponse"/>
+ </operation>
+ <operation name="uninstallSoftware">
+  <documentation>Service definition of function ns1__uninstallSoftware</documentation>
+  <input message="tns:uninstallSoftware"/>
+  <output message="tns:uninstallSoftwareResponse"/>
+ </operation>
+ <operation name="uninstallSoftwareByName">
+  <documentation>Service definition of function ns1__uninstallSoftwareByName</documentation>
+  <input message="tns:uninstallSoftwareByName"/>
+  <output message="tns:uninstallSoftwareByNameResponse"/>
+ </operation>
+ <operation name="listRunningApps">
+  <documentation>Service definition of function ns1__listRunningApps</documentation>
+  <input message="tns:listRunningAppsRequest"/>
+  <output message="tns:listRunningAppsResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiApplication" type="tns:HtiApplicationPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="startProcess">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="stopProcess">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="stopProcessById">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getProcessStatus">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getProcessStatusById">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="startApp">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="startAppByUid">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="startDoc">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getAppStatus">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getAppStatusByUid">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getAppStatusByDoc">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="stopApp">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="stopAppByUid">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="stopAppByDoc">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="listProcesses">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="startProcessRetVal">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getProcessExitCode">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="installSoftware">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="uninstallSoftware">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="uninstallSoftwareByName">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="listRunningApps">
+  <SOAP:operation style="rpc" soapAction="HtiApplication"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiApplication">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiApplication" binding="tns:HtiApplication">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiApplication/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+//additional export functions requried for an hti-plugin
+#define HTI_APPLICATION_SOAP_ACTION "HtiApplication"
+#define HTI_APPLICATION_UID 0x1020DEC7
+
+#include "HtiApplication.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_APPLICATION_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_APPLICATION_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+/**
+*
+*/
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiAudio.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,726 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiAudioH.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+
+#include <iosfwd>
+#include <sstream>
+
+// Command codes
+const unsigned char CMD_LIST_AUDIOFILES	= 0x01;
+const unsigned char CMD_PLAY_FILE		= 0x02;
+const unsigned char CMD_PLAY_TONE		= 0x03;
+const unsigned char CMD_PLAY_DTMF		= 0x04;
+const unsigned char CMD_STOP			= 0x05;
+const unsigned char CMD_GET_DURATION	= 0x06;
+const unsigned char CMD_GET_MAXVOLUME	= 0x07;
+const unsigned char CMD_SET_VOLUME		= 0x08;
+
+// enums
+enum PlayState {
+	EStopped,
+	EPlaying,
+	EError
+};
+
+enum PlayCommand {
+	EPlayAudioFile = 0,
+	EPlayTone,
+	EPlayDtmf,
+	ENrOfPlayCommands
+};
+
+// global variable(s)
+int g_PlayCommandState[ENrOfPlayCommands] = { EStopped, EStopped, EStopped };
+
+
+// predeclarations
+bool handle_async_msg(HtiSoapHandlerInterface* handler);
+void SetSoapFaultFromReceivedHtiAudioError(struct soap *soap,
+										   BYTE *receivedMsgBody,
+										   int receivedMsgBodyLen);
+
+//**********************************************************************************
+// HELPER CLASSES
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// CLASS HtiAudioMsg
+//**********************************************************************************
+class HtiAudioMsg : public HtiMsgHelper
+{
+public:
+	HtiAudioMsg( struct soap *soap );
+	HtiAudioMsg( struct soap *soap, DWORD serviceId, BYTE command );
+	int ReceiveMsgWithAsyncHandler( int timeout );
+	int SendReceiveMsgWithAsyncHandler( int timeout );
+
+public: // from HtiMsgHelper
+	// We need to use SetSoapFaultFromReceivedHtiAudioError handler
+	int ReceiveMsg( int timeout );
+};
+
+//**********************************************************************************
+// HtiAudioMsg::HtiAudioMsg
+//**********************************************************************************
+HtiAudioMsg::HtiAudioMsg( struct soap *soap ) : HtiMsgHelper( soap )
+{
+}
+
+//**********************************************************************************
+// HtiAudioMsg::HtiAudioMsg
+//**********************************************************************************
+HtiAudioMsg::HtiAudioMsg( struct soap *soap, DWORD serviceId, BYTE command )
+                          : HtiMsgHelper( soap, serviceId, command )
+{
+}
+
+//**********************************************************************************
+// HtiAudioMsg::ReceiveMsg
+//**********************************************************************************
+int HtiAudioMsg::ReceiveMsg( int timeout )
+{
+	// Clean these up for received HTI message
+	if(m_msgBody)
+	{
+		delete m_msgBody;
+		m_msgBody = NULL;
+		m_msgBodyLen = 0;
+	}
+
+	HtiSoapHandlerInterface* handler =
+		static_cast<HtiSoapHandlerInterface*>(m_soap->user);
+
+	// Wait for OK or error msg
+	if (handler->WaitForHtiMessage(timeout))
+	{
+		// (handler has ownership of the message body)
+		m_msgBody = (BYTE*) handler->ReceivedHtiMessageBody();
+		m_msgBodyLen = handler->ReceivedHtiMessageBodySize();
+
+		if ( !handler->IsReceivedHtiError() )
+		{
+			// Get received message
+			return SOAP_OK;
+		}
+		else
+		{
+			/// Fill the error description
+			SetSoapFaultFromReceivedHtiAudioError(
+					m_soap, m_msgBody, m_msgBodyLen);
+				return SOAP_FAULT;
+		}
+	}
+	// ...or timeout
+	else
+	{
+		m_soap->error = soap_receiver_fault(m_soap,
+			"HtiGateway", "No response from symbian side");
+		return SOAP_FAULT;
+	}
+}
+
+//**********************************************************************************
+// HtiAudioMsg::SendReceiveMsg
+//**********************************************************************************
+int HtiAudioMsg::SendReceiveMsgWithAsyncHandler( int timeout )
+{
+	SendMsg();
+	return ReceiveMsgWithAsyncHandler( timeout );
+}
+
+//**********************************************************************************
+// HtiAudioMsg::ReceiveMsgWithAsyncHandler
+//**********************************************************************************
+int HtiAudioMsg::ReceiveMsgWithAsyncHandler( int timeout )
+{
+	// Clean these up for to be received HTI message
+	if( m_msgBody )
+	{
+		delete m_msgBody;
+		m_msgBody = NULL;
+		m_msgBodyLen = 0;
+	}
+
+	HtiSoapHandlerInterface* handler =
+		static_cast<HtiSoapHandlerInterface*>( m_soap->user );
+
+	while(1)
+	{
+		if ( handler->WaitForHtiMessage( timeout ) )
+		{
+			// NOTE: this will be destroyed by gateway
+			m_msgBody = (BYTE*) handler->ReceivedHtiMessageBody();
+			m_msgBodyLen = handler->ReceivedHtiMessageBodySize();
+
+			if ( handle_async_msg( handler ) )
+				continue; // async msg received wait for next msg
+			else
+			{
+				// error msg received ?
+				if( handler->IsReceivedHtiError() )
+				{
+					SetSoapFaultFromReceivedHtiAudioError(
+						m_soap, m_msgBody, m_msgBodyLen );
+					return SOAP_FAULT;
+				}
+				return SOAP_OK;
+			}
+		}
+		else
+		{
+			// timeout
+			m_soap->error = soap_receiver_fault(m_soap,
+				"HtiGateway", "No response from symbian side");
+			return SOAP_FAULT;
+		}
+	}
+}
+
+
+//**********************************************************************************
+// HELPER FUNCTIONS
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// isAudioPlaying
+//**********************************************************************************
+bool isAudioPlaying(struct soap *soap)
+{
+	if( (g_PlayCommandState[EPlayAudioFile] == EPlaying) ||
+	    (g_PlayCommandState[EPlayTone] == EPlaying) ||
+	    (g_PlayCommandState[EPlayDtmf] == EPlaying) )
+	{
+		soap->error = soap_receiver_fault(soap,
+			"HtiGateway", "already playing audio");
+		return TRUE;
+	}
+	return FALSE;
+}
+
+//**********************************************************************************
+// SetSoapFaultFromReceivedHtiAudioError
+//**********************************************************************************
+void SetSoapFaultFromReceivedHtiAudioError(struct soap *soap,
+										   BYTE *receivedMsgBody,
+										   int receivedMsgBodyLen)
+{
+	
+	if( receivedMsgBodyLen == 10 )
+	{
+		// This is a standard error message
+		// (eg. not authenticated)
+		HtiSoapHandlerInterface* handler =
+			static_cast<HtiSoapHandlerInterface*>(soap->user);
+		handler->SendSoapFaultFromReceivedHtiError();
+		return;
+	}
+
+
+	// Get error codes
+	int frameworkErrorCode = *((BYTE*)(receivedMsgBody + 1));
+	int serviceErrorCode = *((DWORD*)(receivedMsgBody + 2));
+
+	// Get error description
+	// NOTE: first byte is skipped because it contains the command code
+	int serviceErrorDescLen = receivedMsgBodyLen - 11;
+	char* serviceErrorDesc = new char[receivedMsgBodyLen - 11 + 1];
+	memcpy(serviceErrorDesc, receivedMsgBody+11, serviceErrorDescLen);
+	serviceErrorDesc[serviceErrorDescLen] = 0x0;
+
+	// Fill the xml struct
+	std::stringstream s;
+	s<<"<htiError xmlns=\'urn:hti/fault\'><frameworkErrorCode>";
+	s<<frameworkErrorCode;
+	s<<"</frameworkErrorCode><serviceErrorCode>";
+	s<<serviceErrorCode;
+	s<<"</serviceErrorCode><serviceErrorDescription>";
+	s<<serviceErrorDesc;
+    s<<"</serviceErrorDescription>";
+	s<<"</htiError>";
+
+	soap->error = soap_receiver_fault(soap, "HtiError", s.str().c_str() );
+
+	delete serviceErrorDesc;
+}
+
+
+//**********************************************************************************
+// handle_async_msg
+// Will return TRUE if message is handled
+//**********************************************************************************
+bool handle_async_msg( HtiSoapHandlerInterface* handler )
+{
+	// Get message
+	BYTE *msgBody = (BYTE*) handler->ReceivedHtiMessageBody();
+	int msgBodyLen = handler->ReceivedHtiMessageBodySize();
+
+	if(handler->IsReceivedHtiError())
+	{
+		// First byte of service error description is the command it concers
+		int serviceErrorDesPos = 1+1+4+4;
+		switch(msgBody[serviceErrorDesPos])
+		{
+		case CMD_PLAY_FILE:
+			g_PlayCommandState[EPlayAudioFile] = EError;
+			return TRUE;
+
+		case CMD_PLAY_TONE:
+			g_PlayCommandState[EPlayTone] = EError;
+			return TRUE;
+
+		case CMD_PLAY_DTMF:
+			g_PlayCommandState[EPlayDtmf] = EError;
+			return TRUE;
+
+		default:
+			return FALSE;
+		}
+	}
+
+	switch(msgBody[0])
+	{
+	// Received from symbian side to indicate playing is complete
+	case CMD_PLAY_FILE:
+		g_PlayCommandState[EPlayAudioFile] = EStopped;
+		return TRUE;
+
+	case CMD_PLAY_TONE:
+		g_PlayCommandState[EPlayTone] = EStopped;
+		return TRUE;
+
+	case CMD_PLAY_DTMF:
+		g_PlayCommandState[EPlayDtmf] = EStopped;
+		return TRUE;
+
+	default:
+		return FALSE;
+	}
+
+	// Should never come here
+	return FALSE;
+}
+
+//**********************************************************************************
+// EXPORTED FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// hti_serve()
+//**********************************************************************************
+int hti_serve(HtiSoapHandlerInterface* handler)
+{
+	handle_async_msg( handler );
+	return 0;
+}
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// ns1__listAudioFiles()
+//**********************************************************************************
+int ns1__listAudioFiles(struct soap* soap,
+						char *directory, // optional
+                        struct ArrayOfAudioFiles *audiofiles)
+{
+	// construct & send & receive HTI message
+	HtiAudioMsg msg( soap, HTI_AUDIO_UID, CMD_LIST_AUDIOFILES );
+	msg.AddStringWithLengthByte( directory );
+	if ( msg.SendReceiveMsgWithAsyncHandler( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	// Check CommandCode
+	if ( msg.CheckCommandCode( CMD_LIST_AUDIOFILES ) )
+		return SOAP_FAULT;
+
+	// get size of array & alloc space for pointers
+	audiofiles->__size  = (int) msg.GetWord(1);
+	audiofiles->__ptr = (char**) soap_malloc(soap, sizeof(char**)*audiofiles->__size);
+
+	// read files
+	int offset = 3;
+	for ( int i = 0; i < audiofiles->__size; i++ )
+	{
+		int fileNameLen = msg.GetByte(offset);
+		offset += 1;
+		audiofiles->__ptr[i] = (char*) soap_malloc( soap, fileNameLen+1 ); // +1 for nul
+		memcpy( audiofiles->__ptr[i], msg.GetMsgBody()+offset, fileNameLen );
+		( audiofiles->__ptr[i] )[fileNameLen] = 0x0; // add nul
+		offset += fileNameLen;
+	}
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__startPlayAudioFile()
+//**********************************************************************************
+int ns1__startPlayAudioFile(struct soap* soap,
+							char *fileName,
+							unsigned char volume,
+							int startPosition,
+							int stopPosition,
+							unsigned char nrOfRepeats,
+							int silenceBetweenRepeats,
+							char *audioSettings,
+                            struct ns1__startPlayAudioFileResponse *out)
+{
+	if( check_mandatory_string_parameter(soap, fileName, "fileName") ||
+		check_mandatory_string_parameter(soap, audioSettings, "audioSettings") )
+		return SOAP_FAULT;
+
+	if( isAudioPlaying( soap ) )
+		return SOAP_FAULT;
+
+	// construct & send HTI message
+	HtiAudioMsg msg( soap, HTI_AUDIO_UID, CMD_PLAY_FILE );
+	msg.AddStringWithLengthByte( fileName );
+	msg.AddByte( volume );
+	msg.AddInt( startPosition );
+	msg.AddInt( stopPosition );
+	msg.AddByte( nrOfRepeats );
+	msg.AddInt( silenceBetweenRepeats );
+	if(!strcmp("Default", audioSettings))
+		msg.AddByte( 0x00 );
+	else if(!strcmp("General Music", audioSettings))
+		msg.AddByte( 0x01 );
+	else if(!strcmp("Ring Tone Preview", audioSettings))
+		msg.AddByte( 0x02 );
+	else
+	{
+		soap->error = soap_receiver_fault(soap, "HtiGateway", "unknown audio setting");
+		return SOAP_FAULT;
+	}
+	msg.SendMsg();
+
+	g_PlayCommandState[EPlayAudioFile] = EPlaying;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__playAudioFile()
+//**********************************************************************************
+int ns1__playAudioFile(struct soap* soap,
+					   char *fileName,
+					   unsigned char volume,
+					   int startPosition,
+					   int stopPosition,
+					   unsigned char nrOfRepeats,
+					   int silenceBetweenRepeats,
+					   char *audioSettings,
+					   int timeout,
+                       struct ns1__playAudioFileResponse *out)
+{
+	// Start playing
+	if( ns1__startPlayAudioFile(soap,
+		                        fileName,
+                                volume,
+    	                        startPosition,
+	     					    stopPosition,
+		     				    nrOfRepeats,
+		 	    			    silenceBetweenRepeats,
+		 		    		    audioSettings,
+		 					    NULL) )
+	{
+		return SOAP_FAULT;
+	}
+
+	// Set stopped immidietly as this is synchronous call
+	g_PlayCommandState[EPlayAudioFile] = EStopped;
+
+	// get response
+	HtiAudioMsg msg( soap );
+	if ( msg.ReceiveMsg( timeout ) )
+		return SOAP_FAULT;
+
+	return msg.CheckCommandCode( CMD_PLAY_FILE );
+}
+
+//**********************************************************************************
+// ns1__startPlayTone()
+//**********************************************************************************
+int ns1__startPlayTone(struct soap* soap,
+					   unsigned short frequency,
+					   int duration,
+					   unsigned char volume,
+					   unsigned char nrOfRepeats,
+					   int silenceBetweenRepeats,
+                       struct ns1__startPlayToneResponse *out)
+{
+	if( isAudioPlaying( soap ) )
+		return SOAP_FAULT;
+
+	HtiAudioMsg msg( soap, HTI_AUDIO_UID, CMD_PLAY_TONE );
+	msg.AddWord( frequency );
+	msg.AddInt( duration );
+	msg.AddByte( volume );
+	msg.AddByte( nrOfRepeats );
+	msg.AddInt( silenceBetweenRepeats );
+	msg.SendMsg();
+
+	g_PlayCommandState[EPlayTone] = EPlaying;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__playTone()
+//**********************************************************************************
+int ns1__playTone(struct soap* soap,
+				  unsigned short frequency,
+				  int duration,
+				  unsigned char volume,
+				  unsigned char nrOfRepeats,
+				  int silenceBetweenRepeats,
+                  struct ns1__playToneResponse *out)
+{
+	// Start playing
+	if(ns1__startPlayTone(soap,
+		                  frequency,
+						  duration,
+						  volume,nrOfRepeats,
+						  silenceBetweenRepeats,
+						  NULL))
+		return SOAP_FAULT;
+
+	// Calculate timeout (in milliseconds)
+	int timeout = duration/1000 +
+		          duration/1000*nrOfRepeats +
+				  silenceBetweenRepeats*nrOfRepeats +
+				  HTIMSG_TIMEOUT_10_SECONDS;
+
+	// Set stopped immidietly as this is synchronous call
+	g_PlayCommandState[EPlayTone] = EStopped;
+
+	// get response
+	HtiAudioMsg msg( soap );
+	if ( msg.ReceiveMsg( timeout ) )
+		return SOAP_FAULT;
+
+	return msg.CheckCommandCode( CMD_PLAY_TONE );
+}
+
+//**********************************************************************************
+// ns1__startPlayDtmf()
+//**********************************************************************************
+int ns1__startPlayDtmf(struct soap* soap,
+					   char *dtmfString,
+					   int toneLength,
+					   int gapLength,
+					   unsigned char volume,
+					   unsigned char nrOfRepeats,
+					   int silenceBetweenRepeats,
+                       struct ns1__startPlayDtmfResponse *out)
+{
+	if(check_mandatory_string_parameter(soap, dtmfString, "dtmfString"))
+		return SOAP_FAULT;
+
+	if(isAudioPlaying(soap))
+		return SOAP_FAULT;
+
+	HtiAudioMsg msg( soap, HTI_AUDIO_UID, CMD_PLAY_DTMF );
+	msg.AddStringWithLengthByte( dtmfString );
+	msg.AddInt( toneLength );
+	msg.AddInt( gapLength );
+	msg.AddByte( volume );
+	msg.AddByte( nrOfRepeats );
+	msg.AddInt( silenceBetweenRepeats );
+	msg.SendMsg();
+
+	g_PlayCommandState[EPlayDtmf] = EPlaying;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__playDtmf()
+//**********************************************************************************
+int ns1__playDtmf(struct soap* soap,
+				  char *dtmfString,
+				  int toneLength,
+				  int gapLength,
+				  unsigned char volume,
+				  unsigned char nrOfRepeats,
+				  int silenceBetweenRepeats,
+                  struct ns1__playDtmfResponse *out)
+{
+	// Start playing
+	if(ns1__startPlayDtmf(soap,
+		                  dtmfString,
+						  toneLength,
+						  gapLength,
+						  volume,
+						  nrOfRepeats,
+						  silenceBetweenRepeats,
+						  NULL))
+		return SOAP_FAULT;
+
+	// Calculate timeout
+	int nrOfTones = (int) strlen(dtmfString);
+	int timeout = toneLength/1000*nrOfTones +
+		          gapLength/1000*nrOfTones +
+				  toneLength/1000*nrOfTones*nrOfRepeats +
+		          gapLength/1000*nrOfTones*nrOfRepeats +
+				  silenceBetweenRepeats/1000*nrOfRepeats +
+				  HTIMSG_TIMEOUT_10_SECONDS;
+
+	// Set stopped immidietly as this is synchronous call
+	g_PlayCommandState[EPlayDtmf] = EStopped;
+
+	// get response
+	HtiAudioMsg msg( soap );
+	if ( msg.ReceiveMsg( timeout ) )
+		return SOAP_FAULT;
+
+	return msg.CheckCommandCode( CMD_PLAY_DTMF );
+}
+
+//**********************************************************************************
+// ns1__getPlayStatus()
+//**********************************************************************************
+int ns1__getPlayStatus(struct soap* soap,
+					   char* type,
+					   char* &status)
+{
+	PlayCommand command;
+
+	if( !strcmp(type, "audiofile") )
+		command = EPlayAudioFile;
+	else if( !strcmp(type, "tone") )
+		command = EPlayTone;
+	else if( !strcmp(type, "dtmf") )
+		command = EPlayDtmf;
+	else
+	{
+		soap->error = soap_receiver_fault(soap, "HtiGateway", "unknown type");
+		return SOAP_FAULT;
+	}
+
+	switch(g_PlayCommandState[command])
+	{
+	case EStopped:
+		status = (char*) soap_malloc(soap, strlen("stopped")+1); // +1 for nul char
+		strcpy(status, "stopped");
+		break;
+
+	case EPlaying:
+		status = (char*) soap_malloc(soap, strlen("playing")+1); // +1 for nul char
+		strcpy(status, "playing");
+		break;
+
+	case EError:
+		g_PlayCommandState[command] = EStopped;
+		status = (char*) soap_malloc(soap, strlen("error")+1); // +1 for nul char
+		strcpy(status, "error");
+		break;
+
+	default:
+		// should not happen ever
+		soap->error = soap_receiver_fault(soap, "HtiGateway", "unknown state");
+		return SOAP_FAULT;
+	}
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__stopPlayback()
+//**********************************************************************************
+int ns1__stopPlayback(struct soap* soap,
+					  void *_,
+                      struct ns1__stopPlaybackResponse *out)
+{
+	for(int i=0; i < ENrOfPlayCommands; i++)
+        g_PlayCommandState[i] = EStopped;
+
+	HtiAudioMsg msg( soap, HTI_AUDIO_UID, CMD_STOP );
+	if ( msg.SendReceiveMsgWithAsyncHandler( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckCommandCode( CMD_STOP ) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getDuration()
+//**********************************************************************************
+int ns1__getDuration(struct soap* soap,
+					 char *fileName, // optional
+					 int &duration)
+{
+	HtiAudioMsg msg( soap, HTI_AUDIO_UID, CMD_GET_DURATION );
+	msg.AddStringWithLengthByte( fileName );
+	if ( msg.SendReceiveMsgWithAsyncHandler( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckCommandCode( CMD_GET_DURATION ) )
+		return SOAP_FAULT;
+
+	duration = msg.GetInt(1);
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getMaxVolume()
+//**********************************************************************************
+int ns1__getMaxVolume(struct soap* soap,
+					  char *fileName, // optional
+					  unsigned char &volume)
+{
+	HtiAudioMsg msg( soap, HTI_AUDIO_UID, CMD_GET_MAXVOLUME );
+	msg.AddStringWithLengthByte( fileName );
+	if ( msg.SendReceiveMsgWithAsyncHandler( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckCommandCode( CMD_GET_MAXVOLUME ) )
+		return SOAP_FAULT;
+
+	volume = msg.GetByte(1);
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__setVolume()
+//**********************************************************************************
+int ns1__setVolume(struct soap* soap,
+				   unsigned char volume,
+				   unsigned char &volumeSet)
+{
+	HtiAudioMsg msg( soap, HTI_AUDIO_UID, CMD_SET_VOLUME );
+	msg.AddByte( volume );
+	if ( msg.SendReceiveMsgWithAsyncHandler( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckCommandCode( CMD_SET_VOLUME ) )
+		return SOAP_FAULT;
+
+	volumeSet = msg.GetByte(1);
+
+	return SOAP_OK;
+}
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiAudio.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,137 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiAudio
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char*			xsd__string;
+typedef wchar_t*		xsd__string_;
+typedef int				xsd__int;
+typedef unsigned char	xsd__unsignedByte;
+typedef unsigned short	xsd__unsignedShort;
+
+
+struct ArrayOfAudioFiles
+{
+    xsd__string	*__ptr;
+    xsd__int	__size;
+};
+//gsoap ns1 service method-action: listAudioFiles "HtiAudio"
+int ns1__listAudioFiles(
+    xsd__string					directory,
+    struct ArrayOfAudioFiles	*audiofiles
+);
+
+//enum ns__audioSettings {Default, GeneralMusic, RingTonePreview};
+
+// synchronous service
+//gsoap ns1 service method-action: playAudioFile "HtiAudio"
+int ns1__playAudioFile(
+    xsd__string				fileName,
+    xsd__unsignedByte		volume,
+    xsd__int				startPosition,
+    xsd__int				stopPosition,
+    xsd__unsignedByte		nrOfRepeats,
+    xsd__int				silenceBetweenRepeats,
+	xsd__string				audioSettings,
+	xsd__int				timeout, // we cannot calculate timeout from file/parameters in all cases
+    struct ns1__playAudioFileResponse{} *out // empty response
+);
+// asynchronous service
+//gsoap ns1 service method-action: startPlayAudioFile "HtiAudio"
+int ns1__startPlayAudioFile(
+    xsd__string				fileName,
+    xsd__unsignedByte		volume,
+    xsd__int				startPosition,
+    xsd__int				stopPosition,
+    xsd__unsignedByte		nrOfRepeats,
+    xsd__int				silenceBetweenRepeats,
+	xsd__string				audioSettings,
+    struct ns1__startPlayAudioFileResponse{} *out // empty response
+);
+
+// synchronous service
+//gsoap ns1 service method-action: playTone "HtiAudio"
+int ns1__playTone(
+    xsd__unsignedShort		frequency,
+    xsd__int				duration,
+    xsd__unsignedByte		volume,
+    xsd__unsignedByte		nrOfRepeats,
+    xsd__int				silenceBetweenRepeats,
+    struct ns1__playToneResponse{} *out // empty response
+);
+// asynchronous service
+//gsoap ns1 service method-action: startPlayTone "HtiAudio"
+int ns1__startPlayTone(
+    xsd__unsignedShort		frequency,
+    xsd__int				duration,
+    xsd__unsignedByte		volume,
+    xsd__unsignedByte		nrOfRepeats,
+    xsd__int				silenceBetweenRepeats,
+    struct ns1__startPlayToneResponse{} *out // empty response
+);
+
+// synchronous service
+//gsoap ns1 service method-action: playDtmf "HtiAudio"
+int ns1__playDtmf(
+    xsd__string				dtmfString,
+    xsd__int				toneLength,
+    xsd__int				gapLength,
+    xsd__unsignedByte		volume,
+    xsd__unsignedByte		nrOfRepeats,
+    xsd__int				silenceBetweenRepeats,
+    struct ns1__playDtmfResponse{} *out // empty response
+);
+// asynchronous service
+//gsoap ns1 service method-action: startPlayDtmf "HtiAudio"
+int ns1__startPlayDtmf(
+    xsd__string				dtmfString,
+    xsd__int				toneLength,
+    xsd__int				gapLength,
+    xsd__unsignedByte		volume,
+    xsd__unsignedByte		nrOfRepeats,
+    xsd__int				silenceBetweenRepeats,
+    struct ns1__startPlayDtmfResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: getPlayStatus "HtiAudio"
+int ns1__getPlayStatus(
+    xsd__string		type,
+	xsd__string		&status
+);
+//gsoap ns1 service method-action: stopPlayback "HtiAudio"
+int ns1__stopPlayback(
+    void *_, // no parameters
+    struct ns1__stopPlaybackResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: getDuration "HtiAudio"
+int ns1__getDuration(
+    xsd__string			fileName,
+    xsd__int			&duration
+);
+//gsoap ns1 service method-action: getMaxVolume "HtiAudio"
+int ns1__getMaxVolume(
+    xsd__string			fileName,
+    xsd__unsignedByte	&volume
+);
+//gsoap ns1 service method-action: setVolume "HtiAudio"
+int ns1__setVolume(
+    xsd__unsignedByte	volume,
+    xsd__unsignedByte	&volumeSet
+);
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiAudio.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,250 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiAudio"
+	ProjectGUID="{0F3127D8-45F8-4E0D-8A81-7B3545C245D6}"
+	RootNamespace="HtiAudio"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiAudio.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiAudioServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiAudio.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiAudio.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiAudioH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiAudioStub.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiAudio.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,379 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiAudio"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <complexType name="ArrayOfstring">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="xsd:string[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <!-- operation request element -->
+  <element name="directory" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="audiofiles" type="ns1:ArrayOfstring"/>
+  <!-- operation request element -->
+  <element name="fileName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="volume" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="startPosition" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="stopPosition" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="nrOfRepeats" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="silenceBetweenRepeats" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="audioSettings" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="timeout" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="frequency" type="xsd:unsignedShort"/>
+  <!-- operation request element -->
+  <element name="duration" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="dtmfString" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="toneLength" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="gapLength" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="type" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="status" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="volumeSet" type="xsd:unsignedByte"/>
+ </schema>
+
+</types>
+
+<message name="listAudioFilesRequest">
+ <part name="directory" element="ns1:directory"/>
+</message>
+
+<message name="listAudioFilesResponse">
+ <part name="audiofiles" element="ns1:audiofiles"/>
+</message>
+
+<message name="playAudioFile">
+ <part name="fileName" element="ns1:fileName"/>
+ <part name="volume" element="ns1:volume"/>
+ <part name="startPosition" element="ns1:startPosition"/>
+ <part name="stopPosition" element="ns1:stopPosition"/>
+ <part name="nrOfRepeats" element="ns1:nrOfRepeats"/>
+ <part name="silenceBetweenRepeats" element="ns1:silenceBetweenRepeats"/>
+ <part name="audioSettings" element="ns1:audioSettings"/>
+ <part name="timeout" element="ns1:timeout"/>
+</message>
+
+<message name="playAudioFileResponse">
+</message>
+
+<message name="startPlayAudioFile">
+ <part name="fileName" element="ns1:fileName"/>
+ <part name="volume" element="ns1:volume"/>
+ <part name="startPosition" element="ns1:startPosition"/>
+ <part name="stopPosition" element="ns1:stopPosition"/>
+ <part name="nrOfRepeats" element="ns1:nrOfRepeats"/>
+ <part name="silenceBetweenRepeats" element="ns1:silenceBetweenRepeats"/>
+ <part name="audioSettings" element="ns1:audioSettings"/>
+</message>
+
+<message name="startPlayAudioFileResponse">
+</message>
+
+<message name="playTone">
+ <part name="frequency" element="ns1:frequency"/>
+ <part name="duration" element="ns1:duration"/>
+ <part name="volume" element="ns1:volume"/>
+ <part name="nrOfRepeats" element="ns1:nrOfRepeats"/>
+ <part name="silenceBetweenRepeats" element="ns1:silenceBetweenRepeats"/>
+</message>
+
+<message name="playToneResponse">
+</message>
+
+<message name="startPlayTone">
+ <part name="frequency" element="ns1:frequency"/>
+ <part name="duration" element="ns1:duration"/>
+ <part name="volume" element="ns1:volume"/>
+ <part name="nrOfRepeats" element="ns1:nrOfRepeats"/>
+ <part name="silenceBetweenRepeats" element="ns1:silenceBetweenRepeats"/>
+</message>
+
+<message name="startPlayToneResponse">
+</message>
+
+<message name="playDtmf">
+ <part name="dtmfString" element="ns1:dtmfString"/>
+ <part name="toneLength" element="ns1:toneLength"/>
+ <part name="gapLength" element="ns1:gapLength"/>
+ <part name="volume" element="ns1:volume"/>
+ <part name="nrOfRepeats" element="ns1:nrOfRepeats"/>
+ <part name="silenceBetweenRepeats" element="ns1:silenceBetweenRepeats"/>
+</message>
+
+<message name="playDtmfResponse">
+</message>
+
+<message name="startPlayDtmf">
+ <part name="dtmfString" element="ns1:dtmfString"/>
+ <part name="toneLength" element="ns1:toneLength"/>
+ <part name="gapLength" element="ns1:gapLength"/>
+ <part name="volume" element="ns1:volume"/>
+ <part name="nrOfRepeats" element="ns1:nrOfRepeats"/>
+ <part name="silenceBetweenRepeats" element="ns1:silenceBetweenRepeats"/>
+</message>
+
+<message name="startPlayDtmfResponse">
+</message>
+
+<message name="getPlayStatusRequest">
+ <part name="type" element="ns1:type"/>
+</message>
+
+<message name="getPlayStatusResponse">
+ <part name="status" element="ns1:status"/>
+</message>
+
+<message name="stopPlayback">
+</message>
+
+<message name="stopPlaybackResponse">
+</message>
+
+<message name="getDurationRequest">
+ <part name="fileName" element="ns1:fileName"/>
+</message>
+
+<message name="getDurationResponse">
+ <part name="duration" element="ns1:duration"/>
+</message>
+
+<message name="getMaxVolumeRequest">
+ <part name="fileName" element="ns1:fileName"/>
+</message>
+
+<message name="getMaxVolumeResponse">
+ <part name="volume" element="ns1:volume"/>
+</message>
+
+<message name="setVolumeRequest">
+ <part name="volume" element="ns1:volume"/>
+</message>
+
+<message name="setVolumeResponse">
+ <part name="volumeSet" element="ns1:volumeSet"/>
+</message>
+
+<portType name="HtiAudioPortType">
+ <operation name="listAudioFiles">
+  <documentation>Service definition of function ns1__listAudioFiles</documentation>
+  <input message="tns:listAudioFilesRequest"/>
+  <output message="tns:listAudioFilesResponse"/>
+ </operation>
+ <operation name="playAudioFile">
+  <documentation>Service definition of function ns1__playAudioFile</documentation>
+  <input message="tns:playAudioFile"/>
+  <output message="tns:playAudioFileResponse"/>
+ </operation>
+ <operation name="startPlayAudioFile">
+  <documentation>Service definition of function ns1__startPlayAudioFile</documentation>
+  <input message="tns:startPlayAudioFile"/>
+  <output message="tns:startPlayAudioFileResponse"/>
+ </operation>
+ <operation name="playTone">
+  <documentation>Service definition of function ns1__playTone</documentation>
+  <input message="tns:playTone"/>
+  <output message="tns:playToneResponse"/>
+ </operation>
+ <operation name="startPlayTone">
+  <documentation>Service definition of function ns1__startPlayTone</documentation>
+  <input message="tns:startPlayTone"/>
+  <output message="tns:startPlayToneResponse"/>
+ </operation>
+ <operation name="playDtmf">
+  <documentation>Service definition of function ns1__playDtmf</documentation>
+  <input message="tns:playDtmf"/>
+  <output message="tns:playDtmfResponse"/>
+ </operation>
+ <operation name="startPlayDtmf">
+  <documentation>Service definition of function ns1__startPlayDtmf</documentation>
+  <input message="tns:startPlayDtmf"/>
+  <output message="tns:startPlayDtmfResponse"/>
+ </operation>
+ <operation name="getPlayStatus">
+  <documentation>Service definition of function ns1__getPlayStatus</documentation>
+  <input message="tns:getPlayStatusRequest"/>
+  <output message="tns:getPlayStatusResponse"/>
+ </operation>
+ <operation name="stopPlayback">
+  <documentation>Service definition of function ns1__stopPlayback</documentation>
+  <input message="tns:stopPlayback"/>
+  <output message="tns:stopPlaybackResponse"/>
+ </operation>
+ <operation name="getDuration">
+  <documentation>Service definition of function ns1__getDuration</documentation>
+  <input message="tns:getDurationRequest"/>
+  <output message="tns:getDurationResponse"/>
+ </operation>
+ <operation name="getMaxVolume">
+  <documentation>Service definition of function ns1__getMaxVolume</documentation>
+  <input message="tns:getMaxVolumeRequest"/>
+  <output message="tns:getMaxVolumeResponse"/>
+ </operation>
+ <operation name="setVolume">
+  <documentation>Service definition of function ns1__setVolume</documentation>
+  <input message="tns:setVolumeRequest"/>
+  <output message="tns:setVolumeResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiAudio" type="tns:HtiAudioPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="listAudioFiles">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="playAudioFile">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="startPlayAudioFile">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="playTone">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="startPlayTone">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="playDtmf">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="startPlayDtmf">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getPlayStatus">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="stopPlayback">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getDuration">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getMaxVolume">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setVolume">
+  <SOAP:operation style="rpc" soapAction="HtiAudio"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiAudio">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiAudio" binding="tns:HtiAudio">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiAudio/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+#include "HtiAudio.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+//additional export functions requried for an hti-plugin
+#define HTI_SOAP_ACTION "HtiAudio"
+#define HTI_AUDIO_UID 0x10210CCB
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_AUDIO_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*);
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiEcho.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiechoH.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// ns1__echo()
+//**********************************************************************************
+int ns1__echo(struct soap* soap, char *echo, char **result)
+{
+	HtiMsgHelper msg( soap, HTI_UID );
+	msg.AddString( echo );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_30_SECONDS ) )
+		return SOAP_FAULT;
+	
+	*result = msg.GetSoapString( 0, msg.GetMsgLen() );
+
+	return SOAP_OK; 
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiEcho.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiEcho
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char * xsd__string;
+//gsoap ns1 service method-action: echo "HtiEcho"
+int ns1__echo(xsd__string ping, xsd__string* result);
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiEcho.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,248 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiEcho"
+	ProjectGUID="{A7B882D2-75CF-4720-9C80-86021A6C9714}"
+	RootNamespace="HtiEcho"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiEcho.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiEchoServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiEcho.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiEcho.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiEchoH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiEchoStub.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiEcho.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiEcho"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <!-- operation request element -->
+  <element name="ping" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="result" type="xsd:string"/>
+ </schema>
+
+</types>
+
+<message name="echoRequest">
+ <part name="ping" element="ns1:ping"/>
+</message>
+
+<message name="echoResponse">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<portType name="HtiEchoPortType">
+ <operation name="echo">
+  <documentation>Service definition of function ns1__echo</documentation>
+  <input message="tns:echoRequest"/>
+  <output message="tns:echoResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiEcho" type="tns:HtiEchoPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="echo">
+  <SOAP:operation style="rpc" soapAction="HtiEcho"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiEcho">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiEcho" binding="tns:HtiEcho">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiEcho/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+#include "HtiEcho.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+//additional export functions requried for an hti-plugin
+#define HTI_SOAP_ACTION "HtiEcho"
+#define HTI_UID 0x1020DEBF
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiFtp.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,790 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiFtpH.h"
+
+#include "HtiPlugin.h"
+#include <string.h>
+
+#include "HtiSoapHandlerInterface.h"
+
+const unsigned char CMD_FTP_STOR	    = 0x03;
+const unsigned char CMD_FTP_RETR	    = 0x05;
+const unsigned char CMD_FTP_LIST	    = 0x07;
+const unsigned char CMD_FTP_LISTDIR	    = 0x11;
+const unsigned char CMD_FTP_LISTSIZE    = 0x13;
+const unsigned char CMD_FTP_LISTDRIVES  = 0x15;
+const unsigned char CMD_FTP_MKD		    = 0x09;
+const unsigned char CMD_FTP_RMD	    	= 0x0B;
+const unsigned char CMD_FTP_DELE	    = 0x0D;
+const unsigned char CMD_FTP_CANCEL	    = 0x0E;
+const unsigned char CMD_FTP_FILESIZE    = 0x0F;
+
+const unsigned char CMD_FTP_SETFORCE	= 0x20;
+const unsigned char CMD_FTP_CHECKSUM	= 0x30;
+const unsigned char CMD_FTP_CHECKSUM_U	= 0x31;
+const unsigned char CMD_FTP_FORMAT      = 0x40;
+
+const unsigned char CMD_FTP_OK		= 0xF0;
+const unsigned char CONTROL_PRIORITY = 2;
+
+const int MAX_HTI_MSG_SIZE = 8192;
+
+char fileMimeType[] = "application/octet-stream"; //??
+
+const static int g_ftpHtiTimeoutControl = 10000;
+const static int g_ftpHtiTimeoutData = 60*60000;
+
+int sendHtiMessage(struct soap *soap,
+				   const char cmd,
+				   const wchar_t* arg )
+{
+	int resultCode = SOAP_OK;
+	
+	int textLen = 0;
+	int bodyLen = 0;
+	if ( arg )
+	{
+		textLen = (int)wcslen( arg );
+		if ( textLen > 0xFF )
+		{
+			soap->error = soap_sender_fault(soap, "Invalid arguments", NULL);
+			resultCode = SOAP_FAULT;
+			return resultCode;
+		}
+		bodyLen = 2*textLen + 2;
+	}
+	else
+	{
+        bodyLen = 1;
+	}
+
+	BYTE* msgBody = new BYTE[ bodyLen ];
+	msgBody[0] = cmd;
+
+	if ( arg )
+	{
+		msgBody[1] = textLen;
+		memcpy( msgBody + 2, arg, 2*textLen );
+	}
+
+	HtiSoapHandlerInterface* handler = static_cast<HtiSoapHandlerInterface*>(soap->user);
+
+	handler->SendHtiMessage(HTI_UID, msgBody, bodyLen, CONTROL_PRIORITY );
+
+	delete[] msgBody;
+	return resultCode;
+}
+
+int receiveFtpOk( struct soap *soap, DWORD waitTimeout )
+{
+	int resultCode = SOAP_OK;
+	
+	HtiSoapHandlerInterface* handler = static_cast<HtiSoapHandlerInterface*>(soap->user);
+
+	if ( handler->WaitForHtiMessage( waitTimeout ) )
+	{
+		if ( !handler->IsReceivedHtiError() )
+		{
+			DWORD bodySize = handler->ReceivedHtiMessageBodySize();
+			BYTE* body = (BYTE*)(handler->ReceivedHtiMessageBody());
+
+			if ( ! ( bodySize == 1 && body[0] == CMD_FTP_OK ) )
+			{
+				soap->error = soap_receiver_fault(soap,
+												"Received invalid hti message", NULL);
+				resultCode = SOAP_FAULT;
+			}
+		}
+		else
+		{
+			handler->SendSoapFaultFromReceivedHtiError();
+			resultCode = SOAP_FAULT;
+		}
+	}
+	else
+	{
+		soap->error = soap_receiver_fault(soap,
+										  "Failed receive hti message", NULL);
+		resultCode = SOAP_FAULT;
+	}
+	
+	return resultCode;
+}
+
+int sendHtiMessageAndReceiveOK(struct soap *soap,
+							   const char cmd,
+							   const wchar_t* arg )
+{
+	if ( arg == NULL )
+	{
+		soap->error = soap_sender_fault(soap, "Invalid arguments", NULL);
+		return SOAP_FAULT;
+	}
+	int resultCode = sendHtiMessage( soap, cmd, arg );
+	if ( resultCode != SOAP_OK )
+	{
+		return resultCode;
+	}
+	
+	return receiveFtpOk(soap, g_ftpHtiTimeoutControl);
+}
+
+int sendHtiMessageAndReceiveStringArray(struct soap *soap,
+										const char cmd,
+										const wchar_t* arg,
+										struct ArrayOfStrings &array )
+{
+	if ( arg == NULL )
+	{
+		soap->error = soap_sender_fault(soap, "Invalid arguments", NULL);
+		return SOAP_FAULT;
+	}
+
+	int resultCode = SOAP_OK;
+	resultCode = sendHtiMessage( soap, cmd, arg );
+	if ( resultCode != SOAP_OK )
+	{
+		return resultCode;
+	}
+	
+	HtiSoapHandlerInterface* handler = static_cast<HtiSoapHandlerInterface*>(soap->user);
+
+	if (handler->WaitForHtiMessage(g_ftpHtiTimeoutData) )
+	{
+		if ( !handler->IsReceivedHtiError() )
+		{
+            DWORD bodySize = handler->ReceivedHtiMessageBodySize();
+			BYTE* body = (BYTE*)(handler->ReceivedHtiMessageBody());
+			//check that body size is valid
+			if ( bodySize > 0 )
+			{
+				//calculate number of elements
+				DWORD i = 0;
+				int numOfElements = 0;
+				while ( i < bodySize )
+				{
+                    ++numOfElements;
+					i += 2*body[i] + 1;
+				}
+
+				//printf("strings: %d\n", numOfElements);
+
+				if ( i != bodySize )
+				{
+					soap->error = soap_receiver_fault(soap,
+													"Invalid hti message", NULL);
+					resultCode = SOAP_FAULT;
+				}
+				else
+				{
+					array.__size = numOfElements;
+					array.__ptr = (wchar_t**)soap_malloc(soap, sizeof(wchar_t*)*array.__size );
+					int j;
+					for( j=0, i=0; j<array.__size; ++j, i += 2*body[i] + 1)
+					{
+						//printf("%d size=%d ", j, body[i]);
+						array.__ptr[j] = (wchar_t*)soap_malloc(soap, 2*body[i] + 2 );
+						memcpy(array.__ptr[j],
+								body + i + 1,
+								2*body[i] );
+						(array.__ptr[j])[body[i]] = 0; //null char
+						int strLen = (int)wcslen( array.__ptr[j] );
+
+						//wprintf(L">%S<\n", array.__ptr[j] );
+						//printf("\n");
+					}
+				}
+			}
+			else
+			{
+				array.__size = 0;
+				array.__ptr = 0;
+			}
+		}
+		else
+		{
+			handler->SendSoapFaultFromReceivedHtiError();
+			resultCode = SOAP_FAULT;
+		}
+	}
+	else
+	{
+		soap->error = soap_receiver_fault(soap,
+										  "Failed receive hti message", NULL);
+		resultCode = SOAP_FAULT;
+	}
+	
+	return resultCode;
+}
+
+int sendHtiMessageAndReceiveHtiFileInfoArray(struct soap *soap,
+										const char cmd,
+										const wchar_t* arg,
+										struct ArrayOfHtiFileInfos &array )
+{
+	if ( arg == NULL )
+	{
+		soap->error = soap_sender_fault(soap, "Invalid arguments", NULL);
+		return SOAP_FAULT;
+	}
+
+	int resultCode = SOAP_OK;
+	resultCode = sendHtiMessage( soap, cmd, arg );
+	if ( resultCode != SOAP_OK )
+	{
+		return resultCode;
+	}
+	
+	HtiSoapHandlerInterface* handler =
+        static_cast<HtiSoapHandlerInterface*>(soap->user);
+
+	if (handler->WaitForHtiMessage(g_ftpHtiTimeoutData) )
+	{
+		if ( !handler->IsReceivedHtiError() )
+		{
+            DWORD bodySize = handler->ReceivedHtiMessageBodySize();
+			BYTE* body = (BYTE*)(handler->ReceivedHtiMessageBody());
+			//check that body size is valid
+			if ( bodySize > 0 )
+			{
+				//calculate number of elements
+				DWORD i = 0;
+				int numOfElements = 0;
+				while ( i < bodySize )
+				{
+                    ++numOfElements;
+					i += 2*body[i] + 1 + 4;
+				}
+
+                if ( i != bodySize )
+				{
+					soap->error = soap_receiver_fault(soap,
+											"Invalid hti message", NULL);
+					resultCode = SOAP_FAULT;
+				}
+				else
+				{
+					array.__size = numOfElements;
+					array.__ptr = (ns1__HtiFileInfo*) soap_malloc(
+                            soap, sizeof(ns1__HtiFileInfo)*array.__size );
+					int j;
+					for( j=0, i=0; j<array.__size; ++j, i += 2*body[i] + 1 + 4)
+					{
+						array.__ptr[j].fileName =
+                            (wchar_t*)soap_malloc(soap, 2*body[i] + 2 );
+						memcpy(array.__ptr[j].fileName, body + i + 1, 2*body[i]);
+                        (array.__ptr[j].fileName)[body[i]] = 0; //null char
+                        // the file size bytes
+                        array.__ptr[j].fileSize = *(int*)(body + i + 2*body[i] + 1);
+                    }
+                }
+            }
+			else
+			{
+				array.__size = 0;
+				array.__ptr = 0;
+			}
+		}
+		else
+		{
+			handler->SendSoapFaultFromReceivedHtiError();
+			resultCode = SOAP_FAULT;
+		}
+	}
+	else
+	{
+		soap->error = soap_receiver_fault(soap,
+										  "Failed receive hti message", NULL);
+		resultCode = SOAP_FAULT;
+	}
+
+    return resultCode;
+}
+
+int sendHtiMessageAndReceiveHtiDriveInfoArray(struct soap *soap,
+                                        const char cmd,
+                                        struct ArrayOfHtiDriveInfos &array )
+{
+	int resultCode = SOAP_OK;
+	resultCode = sendHtiMessage( soap, cmd, NULL );
+	if ( resultCode != SOAP_OK )
+	{
+		return resultCode;
+	}
+	
+	HtiSoapHandlerInterface* handler =
+        static_cast<HtiSoapHandlerInterface*>(soap->user);
+
+	if (handler->WaitForHtiMessage(g_ftpHtiTimeoutData) )
+	{
+		if (!handler->IsReceivedHtiError())
+		{
+			array.__size = 0;
+			array.__ptr = 0;
+            DWORD bodySize = handler->ReceivedHtiMessageBodySize();
+			BYTE* body = (BYTE*)(handler->ReceivedHtiMessageBody());
+            int offset = 0;
+			//first byte is the number of elements
+			int numOfElements = body[offset];
+            offset++;
+
+            array.__size = numOfElements;
+			array.__ptr = (ns1__HtiDriveInfo*) soap_malloc(
+                    soap, sizeof(ns1__HtiDriveInfo)*array.__size );
+
+			int i;
+			for(i=0; i<array.__size; ++i)
+			{
+                int rootPathLength = body[offset];
+                offset++;
+				array.__ptr[i].rootPath =
+                    (wchar_t*)soap_malloc(soap, 2*rootPathLength + 2);
+				memcpy(array.__ptr[i].rootPath, body + offset, 2*rootPathLength);
+                (array.__ptr[i].rootPath)[rootPathLength] = 0; //null char
+                offset += 2*rootPathLength;
+                array.__ptr[i].mediaType = (ns1__driveMediaType)body[offset];
+                offset++;
+                array.__ptr[i].uniqueID = *(int*)(body + offset);
+                offset += sizeof(int);
+                array.__ptr[i].driveSize = *(ULONG64*)(body + offset);
+                offset += sizeof(ULONG64);
+                array.__ptr[i].freeSpace = *(ULONG64*)(body + offset);
+                offset += sizeof(ULONG64);
+                int nameLength = body[offset];
+                offset++;
+                array.__ptr[i].driveName = 
+                    (wchar_t*)soap_malloc(soap, 2*nameLength + 2);
+                memcpy(array.__ptr[i].driveName, body + offset, 2*nameLength);
+                (array.__ptr[i].driveName)[nameLength] = 0; //null char
+                offset += 2*nameLength;
+            }
+		}
+		else
+		{
+			handler->SendSoapFaultFromReceivedHtiError();
+			resultCode = SOAP_FAULT;
+		}
+	}
+	else
+	{
+		soap->error = soap_receiver_fault(soap,
+										  "Failed receive hti message", NULL);
+		resultCode = SOAP_FAULT;
+	}
+
+    return resultCode;
+}
+
+int sendBinary(struct soap *soap, char* data, const DWORD dataSize )
+{
+	HtiSoapHandlerInterface* handler = static_cast<HtiSoapHandlerInterface*>(soap->user);
+
+	DWORD offset = 0;
+
+    // dataSize == 0 means that uploading empty file - we need to send one
+    // empty data message, so needs to go to following while once
+	while( offset < dataSize || ( offset == 0 && dataSize == 0 ) )
+	{
+		handler->SendHtiMessage( HTI_UID,
+					data + offset,
+					offset + MAX_HTI_MSG_SIZE > dataSize ? dataSize - offset : MAX_HTI_MSG_SIZE
+					);
+		offset += MAX_HTI_MSG_SIZE;
+		//check for error messages
+		if (handler->WaitForHtiMessage(0) ) 
+		{
+			if ( handler->IsReceivedHtiError() )
+			{
+				handler->SendSoapFaultFromReceivedHtiError();
+			}
+			else
+			{
+				soap->error = soap_receiver_fault(soap,
+												"Not expected hti message", NULL);
+			}
+			return SOAP_FAULT;
+		}
+	}
+
+	return SOAP_OK;
+}
+
+int sendSTOR(struct soap *soap,
+             const wchar_t* arg,
+			 const DWORD fileSize )
+{
+	int resultCode = SOAP_OK;
+	
+	int textLen = (int)wcslen( arg );
+
+	if ( !arg || textLen > 0xFF )
+	{
+		soap->error = soap_sender_fault(soap, "Invalid arguments", NULL);
+		resultCode = SOAP_FAULT;
+		return resultCode;
+	}
+
+	int	bodyLen = 2*textLen + 6;
+
+	BYTE* msgBody = new BYTE[ bodyLen ];
+	msgBody[0] = CMD_FTP_STOR;
+	*((DWORD*)(msgBody + 1)) = fileSize;
+	msgBody[5] = textLen;
+	memcpy( msgBody + 6, arg, 2*textLen );
+
+	HtiSoapHandlerInterface* handler = static_cast<HtiSoapHandlerInterface*>(soap->user);
+
+	handler->SendHtiMessage(HTI_UID, msgBody, bodyLen, CONTROL_PRIORITY );
+
+	delete[] msgBody;
+	return resultCode;
+}
+
+int ns1__putFile(struct soap* soap,
+				 struct ns1__HtiSoapAttachment *file,
+				 wchar_t *targetPath,
+				 struct ns1__putFileResponse *out)
+{
+	int resultCode;
+	//send attachment as several hti ftp data messages
+	if ( file == NULL || targetPath == NULL )
+	{
+		soap->error = soap_sender_fault(soap, "Invalid arguments", NULL);
+		return SOAP_FAULT;
+	}
+	else if ( file->href != NULL )
+	{
+		for (soap_multipart::iterator attachment = (*soap).dime.begin();
+				attachment != (*soap).dime.end(); ++attachment) 
+		{
+			if ( (*attachment).id && strcmp((*attachment).id, file->href)==0 )
+			{
+				resultCode = sendSTOR(soap, targetPath, (*attachment).size );
+				if ( resultCode != SOAP_OK )
+				{
+					return resultCode;
+				}
+				resultCode = receiveFtpOk(soap, g_ftpHtiTimeoutControl);
+				if ( resultCode != SOAP_OK )
+				{
+					return resultCode;
+				}
+				resultCode = sendBinary( soap, (*attachment).ptr, (*attachment).size );
+				if ( resultCode != SOAP_OK )
+				{
+					return resultCode;
+				}
+				return receiveFtpOk(soap, g_ftpHtiTimeoutData); 
+			}
+		} 
+	}
+	else
+	{
+		soap->error = soap_sender_fault(soap, "Invalid arguments", NULL);
+		return SOAP_FAULT;
+	}
+
+	soap->error = soap_sender_fault(soap, "Invalid attachment", NULL);
+	resultCode = SOAP_FAULT;
+
+	return resultCode;
+}
+
+int ns1__getFile(struct soap* soap,
+				 wchar_t *filePath,
+				 struct ns1__getFileResponse &r)
+{
+	int resultCode = SOAP_OK;
+
+	if ( filePath == NULL )
+	{
+		soap->error = soap_sender_fault(soap, "Invalid arguments", NULL);
+		return SOAP_FAULT;
+	}
+
+	resultCode = sendHtiMessage( soap, CMD_FTP_RETR, filePath );
+
+	HtiSoapHandlerInterface* handler = static_cast<HtiSoapHandlerInterface*>(soap->user);
+
+    //receive FILESIZE message
+	DWORD fileSize = 0;
+	if (handler->WaitForHtiMessage(g_ftpHtiTimeoutControl) )
+	{
+		if ( !handler->IsReceivedHtiError() )
+		{
+			DWORD bodySize = handler->ReceivedHtiMessageBodySize();
+			BYTE* body = (BYTE*)(handler->ReceivedHtiMessageBody());
+
+			if ( bodySize == 5 && body[0] == CMD_FTP_FILESIZE )
+			{
+				fileSize = *((DWORD*)(body + 1));
+			}
+			else
+			{
+				soap->error = soap_receiver_fault(soap,
+												"Received invalid hti message", NULL);
+				return SOAP_FAULT;
+			}
+		}
+		else
+		{
+			handler->SendSoapFaultFromReceivedHtiError();
+			return SOAP_FAULT;
+		}
+	}
+	else
+	{
+		soap->error = soap_receiver_fault(soap,
+										  "Failed receive hti message", NULL);
+		return SOAP_FAULT;
+	}
+	
+	//receive data messages
+	DWORD receivedFile = 0;
+	char* body = (char*)soap_malloc(soap, fileSize );
+
+	while ( receivedFile < fileSize )
+	{
+		if (handler->WaitForHtiMessage(g_ftpHtiTimeoutData) )
+		{
+			if ( !handler->IsReceivedHtiError() )
+			{
+				//extract response
+				DWORD bodySize = handler->ReceivedHtiMessageBodySize();
+				memcpy( body + receivedFile,
+					   (char*)(handler->ReceivedHtiMessageBody()),
+					   bodySize );
+				receivedFile += bodySize;
+			}
+			else
+			{
+				handler->SendSoapFaultFromReceivedHtiError();
+				return SOAP_FAULT;
+			}
+		}
+		else
+		{
+			soap->error = soap_receiver_fault(soap,
+											"Failed receive hti message", NULL);
+			return SOAP_FAULT;
+		}
+	}
+
+	//create attachment
+	int pLen = (int)wcslen(filePath)+1;
+	r._return.href = (char*)soap_malloc(soap, pLen );
+	WideCharToMultiByte(CP_ACP, 0, filePath, -1, r._return.href, pLen, NULL, NULL);
+
+	r._return.mimeType = (char*)soap_malloc(soap, strlen(fileMimeType)+1 );
+	strcpy( r._return.mimeType, fileMimeType );
+
+	//pass result as DIME attachment
+	soap_set_dime(soap);
+	resultCode = soap_set_dime_attachment(soap,
+								body,
+								fileSize,
+								r._return.mimeType,
+								r._return.href,
+								0, NULL);
+	if (  resultCode != SOAP_OK )
+	{
+		//Util::Debug("soap_set_dime_attachment failed");
+		soap_clr_dime(soap);
+		soap->error = soap_receiver_fault(soap,
+								"Failed create DIME attachment", NULL);
+	}
+	
+	return resultCode;
+}
+
+int ns1__cancelFileTransfer(struct soap* soap,
+							void *_,
+							struct ns1__cancelFileTransferResponse *out)
+{
+	int resultCode = sendHtiMessage( soap, CMD_FTP_CANCEL, NULL );
+	if ( resultCode != SOAP_OK )
+	{
+		return resultCode;
+	}
+	
+	return receiveFtpOk(soap, g_ftpHtiTimeoutControl);
+}
+
+int ns1__listFiles(struct soap* soap,
+				   wchar_t *targetDir,
+				   struct ArrayOfStrings &dirs)
+{
+	return sendHtiMessageAndReceiveStringArray( soap, CMD_FTP_LIST, targetDir, dirs );
+}
+
+int ns1__listFilesSizes(struct soap* soap,
+                        wchar_t *targetDir,
+                        struct ArrayOfHtiFileInfos &fileInfos)
+{
+    return sendHtiMessageAndReceiveHtiFileInfoArray( soap, CMD_FTP_LISTSIZE,
+                                                     targetDir, fileInfos );
+}
+
+int ns1__listDirs(struct soap* soap,
+				  wchar_t *targetDir,
+				  struct ArrayOfStrings &files)
+{
+	return sendHtiMessageAndReceiveStringArray( soap, CMD_FTP_LISTDIR, targetDir, files );
+}
+
+int ns1__createDir(struct soap* soap,
+				   wchar_t *targetDir,
+				   struct ns1__createDirResponse *out)
+{
+	return sendHtiMessageAndReceiveOK( soap, CMD_FTP_MKD, targetDir );
+}
+
+int ns1__deleteDir(struct soap* soap,
+				   wchar_t *targetDir,
+				   struct ns1__deleteDirResponse *out)
+{
+	return sendHtiMessageAndReceiveOK( soap, CMD_FTP_RMD, targetDir );
+}
+
+int ns1__deleteFile(struct soap* soap,
+					wchar_t *targetFile,
+					struct ns1__deleteFileResponse *out)
+{
+	return sendHtiMessageAndReceiveOK( soap, CMD_FTP_DELE, targetFile );
+}
+
+
+int send_receive_htimessage(struct soap* soap, BYTE **msgBody, int &msgBodyLen, int timeout)
+{
+	// Send the message to symbian side
+	HtiSoapHandlerInterface* handler = static_cast<HtiSoapHandlerInterface*>(soap->user);
+	handler->SendHtiMessage(HTI_UID, *msgBody, msgBodyLen, CONTROL_PRIORITY);
+
+	// Clean these up for received HTI message
+	delete *msgBody;
+	*msgBody = NULL;
+	msgBodyLen = 0;
+
+	// ...and wait for OK or error msg
+	if (handler->WaitForHtiMessage(timeout))
+	{
+		if ( !handler->IsReceivedHtiError() )
+		{
+			// Get received message
+			*msgBody = (BYTE*) handler->ReceivedHtiMessageBody();
+			msgBodyLen = handler->ReceivedHtiMessageBodySize();
+			return ERROR_SUCCESS;
+		}
+		else
+		{
+			handler->SendSoapFaultFromReceivedHtiError();
+			return ERROR_GEN_FAILURE;
+		}
+	}
+	// ...or timeout
+	else
+	{
+		soap->error = soap_receiver_fault(soap, "HtiGateway", "No response from symbian side");
+		return WAIT_TIMEOUT;
+	}
+}
+
+int ns1__setForcedOperations(struct soap* soap,
+							 bool state, 
+                             struct ns1__setForcedOperationsResponse *out)
+{
+	int msgBodyLen = 1+1;
+	BYTE *msgBody = new BYTE[msgBodyLen];
+	msgBody[0] = CMD_FTP_SETFORCE;
+	msgBody[1] = (BYTE) state;
+
+	if( send_receive_htimessage(soap, &msgBody, msgBodyLen, g_ftpHtiTimeoutControl) 
+        != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	if(msgBody[0] != CMD_FTP_OK)
+	{
+		soap->error = soap_receiver_fault(soap, "HtiError", "Operation failed. Response code not ok.");
+		return SOAP_FAULT;
+	}
+
+	return SOAP_OK;
+}
+
+int ns1__fileChecksum(struct soap* soap, 
+					  unsigned char algorithmId, 
+					  wchar_t *targetFile, 
+                      struct ArrayOfBytes &checksumByteArray)
+{
+	int targetFileLen = targetFile ? (int) wcslen(targetFile) : 0;
+	if(targetFileLen == 0)
+	{
+		soap->error = soap_receiver_fault(soap, "HtiGateway", "targetFile parameter missing");
+		return SOAP_FAULT;
+	}
+
+	int msgBodyLen = 1+1+1+targetFileLen*2;
+	BYTE *msgBody = new BYTE[msgBodyLen];
+	msgBody[0] = CMD_FTP_CHECKSUM_U;
+	msgBody[1] = algorithmId;
+	msgBody[2] = targetFileLen;
+	memcpy(msgBody+3, targetFile, targetFileLen*2);
+
+	if( send_receive_htimessage(soap, &msgBody, msgBodyLen, g_ftpHtiTimeoutControl) 
+        != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	checksumByteArray.__size = msgBodyLen;
+	checksumByteArray.__ptr = (BYTE*)soap_malloc(soap, sizeof(BYTE)*checksumByteArray.__size );
+
+	memcpy(checksumByteArray.__ptr, msgBody, msgBodyLen);
+
+	return SOAP_OK;
+}
+
+int ns1__format(struct soap* soap,
+				unsigned char drive, 
+                unsigned char formatMode,
+                struct ns1__formatResponse *out)
+{
+	int msgBodyLen = 3;
+	BYTE *msgBody = new BYTE[msgBodyLen];
+	msgBody[0] = CMD_FTP_FORMAT;
+	msgBody[1] = (BYTE) drive;
+    msgBody[2] = (BYTE) formatMode;
+
+    // might take long with large memory cards
+	if( send_receive_htimessage(soap, &msgBody, msgBodyLen, g_ftpHtiTimeoutData) 
+        != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	if(msgBody[0] != CMD_FTP_OK)
+	{
+		soap->error = soap_receiver_fault(soap, "HtiError", "Operation failed. Response code not ok.");
+		return SOAP_FAULT;
+	}
+
+	return SOAP_OK;
+}
+
+int ns1__listDrives(struct soap* soap,
+                    void *_,
+                    struct ArrayOfHtiDriveInfos &driveInfos)
+{
+    return sendHtiMessageAndReceiveHtiDriveInfoArray( soap, CMD_FTP_LISTDRIVES,
+                                                     driveInfos );
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiFtp.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,149 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiFtp
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char * xsd__string;
+typedef wchar_t * xsd__string_;
+typedef bool xsd__boolean;
+typedef unsigned char xsd__unsignedByte;
+typedef int xsd__int;
+typedef unsigned int xsd__unsignedInt;
+typedef ULONG64	xsd__unsignedLong;
+
+enum ns1__driveMediaType { NotPresent, UnknownType, Floppy, HardDisk, CDROM,
+                           RAM, Flash, ROM, Remote, NANDFlash, RotatingMedia };
+
+struct ns1__HtiSoapAttachment
+{
+	//@xsd__string href;
+	xsd__string href;
+	xsd__string mimeType;
+};
+
+struct ArrayOfStrings
+{
+	xsd__string_* __ptr;
+	int __size;
+};
+
+struct ArrayOfBytes
+{
+	xsd__unsignedByte* __ptr;
+	int __size;
+};
+
+struct ns1__HtiFileInfo
+{
+	xsd__string_     fileName;
+    xsd__unsignedInt fileSize;
+};
+
+struct ArrayOfHtiFileInfos
+{
+	struct ns1__HtiFileInfo* __ptr;
+	int __size;
+};
+
+struct ns1__HtiDriveInfo
+{
+    xsd__string_ rootPath;
+    enum ns1__driveMediaType mediaType;
+    xsd__unsignedInt uniqueID;
+    xsd__unsignedLong driveSize;
+    xsd__unsignedLong freeSpace;
+    xsd__string_ driveName;
+};
+
+struct ArrayOfHtiDriveInfos
+{
+	struct ns1__HtiDriveInfo* __ptr;
+	int __size;
+};
+
+//gsoap ns1 service method-action: putFile "HtiFtp"
+int ns1__putFile(
+	struct ns1__HtiSoapAttachment *file,
+    xsd__string_ targetPath,
+	struct ns1__putFileResponse{} *out
+);
+struct ns1__getFileResponse{struct ns1__HtiSoapAttachment _return;};
+//gsoap ns1 service method-action: getFile "HtiFtp"
+int ns1__getFile(
+	xsd__string_ filePath,
+	struct ns1__getFileResponse &r
+);
+//gsoap ns1 service method-action: cancelFileTransfer "HtiFtp"
+int ns1__cancelFileTransfer(
+	void*_ ,
+	struct ns1__cancelFileTransferResponse{} *out
+);
+//gsoap ns1 service method-action: listFiles "HtiFtp"
+int ns1__listFiles(
+	xsd__string_ targetDir,
+	struct ArrayOfStrings &dirs
+);
+//gsoap ns1 service method-action: listFilesSizes "HtiFtp"
+int ns1__listFilesSizes(
+	xsd__string_ targetDir,
+	struct ArrayOfHtiFileInfos &fileInfos
+);
+//gsoap ns1 service method-action: listDirs "HtiFtp"
+int ns1__listDirs(
+	xsd__string_ targetDir,
+	struct ArrayOfStrings &files
+);
+//gsoap ns1 service method-action: createDir "HtiFtp"
+int ns1__createDir(
+	xsd__string_ targetDir,
+	struct ns1__createDirResponse{} *out
+);
+//gsoap ns1 service method-action: deleteDir "HtiFtp"
+int ns1__deleteDir(
+	xsd__string_ targetDir,
+	struct ns1__deleteDirResponse{} *out
+);
+//gsoap ns1 service method-action: deleteFile "HtiFtp"
+int ns1__deleteFile(
+	xsd__string_ targetFile,
+	struct ns1__deleteFileResponse{} *out
+);
+//gsoap ns1 service method-action: setForcedOperations "HtiFtp"
+int ns1__setForcedOperations(
+	xsd__boolean state,
+	struct ns1__setForcedOperationsResponse{} *out
+);
+//gsoap ns1 service method-action: fileChecksum "HtiFtp"
+int ns1__fileChecksum(
+	xsd__unsignedByte algorithmId,
+	xsd__string_ targetFile,
+	struct ArrayOfBytes &checksumByteArray
+);
+//gsoap ns1 service method-action: format "HtiFtp"
+int ns1__format(
+	xsd__unsignedByte drive,
+	xsd__unsignedByte formatMode,
+  	struct ns1__formatResponse{} *out
+);
+//gsoap ns1 service method-action: listDrives "HtiFtp"
+int ns1__listDrives(
+	void*_ ,
+	struct ArrayOfHtiDriveInfos &driveInfos
+);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiFtp.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,250 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiFtp"
+	ProjectGUID="{5BBEEEA4-34D8-4F56-AFEA-8EC04151245F}"
+	RootNamespace="HtiFtp"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiFtp.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiFtpServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiFtp.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiFtp.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiFtpH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiFtpStub.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiFtp.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,433 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiFtp"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <simpleType name="driveMediaType">
+   <restriction base="xsd:string">
+    <enumeration value="NotPresent"/>
+    <enumeration value="UnknownType"/>
+    <enumeration value="Floppy"/>
+    <enumeration value="HardDisk"/>
+    <enumeration value="CDROM"/>
+    <enumeration value="RAM"/>
+    <enumeration value="Flash"/>
+    <enumeration value="ROM"/>
+    <enumeration value="Remote"/>
+    <enumeration value="NANDFlash"/>
+    <enumeration value="RotatingMedia"/>
+   </restriction>
+  </simpleType>
+  <complexType name="HtiSoapAttachment">
+   <sequence>
+     <element name="href" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="mimeType" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfstring">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="xsd:string[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <complexType name="ArrayOfunsignedByte">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="xsd:unsignedByte" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="xsd:unsignedByte[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <complexType name="HtiFileInfo">
+   <sequence>
+     <element name="fileName" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="fileSize" type="xsd:unsignedInt" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfHtiFileInfo">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="ns1:HtiFileInfo" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ns1:HtiFileInfo[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <complexType name="HtiDriveInfo">
+   <sequence>
+     <element name="rootPath" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="mediaType" type="ns1:driveMediaType" minOccurs="1" maxOccurs="1"/>
+     <element name="uniqueID" type="xsd:unsignedInt" minOccurs="1" maxOccurs="1"/>
+     <element name="driveSize" type="xsd:unsignedLong" minOccurs="1" maxOccurs="1"/>
+     <element name="freeSpace" type="xsd:unsignedLong" minOccurs="1" maxOccurs="1"/>
+     <element name="driveName" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfHtiDriveInfo">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="ns1:HtiDriveInfo" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ns1:HtiDriveInfo[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <!-- operation request element -->
+  <element name="file" type="ns1:HtiSoapAttachment"/>
+  <!-- operation request element -->
+  <element name="targetPath" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="filePath" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="return" type="ns1:HtiSoapAttachment"/>
+  <!-- operation request element -->
+  <element name="targetDir" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="dirs" type="ns1:ArrayOfstring"/>
+  <!-- operation response element -->
+  <element name="fileInfos" type="ns1:ArrayOfHtiFileInfo"/>
+  <!-- operation response element -->
+  <element name="files" type="ns1:ArrayOfstring"/>
+  <!-- operation request element -->
+  <element name="targetFile" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="state" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="algorithmId" type="xsd:unsignedByte"/>
+  <!-- operation response element -->
+  <element name="checksumByteArray" type="ns1:ArrayOfunsignedByte"/>
+  <!-- operation request element -->
+  <element name="drive" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="formatMode" type="xsd:unsignedByte"/>
+  <!-- operation response element -->
+  <element name="driveInfos" type="ns1:ArrayOfHtiDriveInfo"/>
+ </schema>
+
+</types>
+
+<message name="putFile">
+ <part name="file" element="ns1:file"/>
+ <part name="targetPath" element="ns1:targetPath"/>
+</message>
+
+<message name="putFileResponse">
+</message>
+
+<message name="getFile">
+ <part name="filePath" element="ns1:filePath"/>
+</message>
+
+<message name="getFileResponse">
+ <part name="return" element="ns1:return"/>
+</message>
+
+<message name="cancelFileTransfer">
+</message>
+
+<message name="cancelFileTransferResponse">
+</message>
+
+<message name="listFilesRequest">
+ <part name="targetDir" element="ns1:targetDir"/>
+</message>
+
+<message name="listFilesResponse">
+ <part name="dirs" element="ns1:dirs"/>
+</message>
+
+<message name="listFilesSizesRequest">
+ <part name="targetDir" element="ns1:targetDir"/>
+</message>
+
+<message name="listFilesSizesResponse">
+ <part name="fileInfos" element="ns1:fileInfos"/>
+</message>
+
+<message name="listDirsRequest">
+ <part name="targetDir" element="ns1:targetDir"/>
+</message>
+
+<message name="listDirsResponse">
+ <part name="files" element="ns1:files"/>
+</message>
+
+<message name="createDir">
+ <part name="targetDir" element="ns1:targetDir"/>
+</message>
+
+<message name="createDirResponse">
+</message>
+
+<message name="deleteDir">
+ <part name="targetDir" element="ns1:targetDir"/>
+</message>
+
+<message name="deleteDirResponse">
+</message>
+
+<message name="deleteFile">
+ <part name="targetFile" element="ns1:targetFile"/>
+</message>
+
+<message name="deleteFileResponse">
+</message>
+
+<message name="setForcedOperations">
+ <part name="state" element="ns1:state"/>
+</message>
+
+<message name="setForcedOperationsResponse">
+</message>
+
+<message name="fileChecksumRequest">
+ <part name="algorithmId" element="ns1:algorithmId"/>
+ <part name="targetFile" element="ns1:targetFile"/>
+</message>
+
+<message name="fileChecksumResponse">
+ <part name="checksumByteArray" element="ns1:checksumByteArray"/>
+</message>
+
+<message name="format">
+ <part name="drive" element="ns1:drive"/>
+ <part name="formatMode" element="ns1:formatMode"/>
+</message>
+
+<message name="formatResponse">
+</message>
+
+<message name="listDrivesRequest">
+</message>
+
+<message name="listDrivesResponse">
+ <part name="driveInfos" element="ns1:driveInfos"/>
+</message>
+
+<portType name="HtiFtpPortType">
+ <operation name="putFile">
+  <documentation>Service definition of function ns1__putFile</documentation>
+  <input message="tns:putFile"/>
+  <output message="tns:putFileResponse"/>
+ </operation>
+ <operation name="getFile">
+  <documentation>Service definition of function ns1__getFile</documentation>
+  <input message="tns:getFile"/>
+  <output message="tns:getFileResponse"/>
+ </operation>
+ <operation name="cancelFileTransfer">
+  <documentation>Service definition of function ns1__cancelFileTransfer</documentation>
+  <input message="tns:cancelFileTransfer"/>
+  <output message="tns:cancelFileTransferResponse"/>
+ </operation>
+ <operation name="listFiles">
+  <documentation>Service definition of function ns1__listFiles</documentation>
+  <input message="tns:listFilesRequest"/>
+  <output message="tns:listFilesResponse"/>
+ </operation>
+ <operation name="listFilesSizes">
+  <documentation>Service definition of function ns1__listFilesSizes</documentation>
+  <input message="tns:listFilesSizesRequest"/>
+  <output message="tns:listFilesSizesResponse"/>
+ </operation>
+ <operation name="listDirs">
+  <documentation>Service definition of function ns1__listDirs</documentation>
+  <input message="tns:listDirsRequest"/>
+  <output message="tns:listDirsResponse"/>
+ </operation>
+ <operation name="createDir">
+  <documentation>Service definition of function ns1__createDir</documentation>
+  <input message="tns:createDir"/>
+  <output message="tns:createDirResponse"/>
+ </operation>
+ <operation name="deleteDir">
+  <documentation>Service definition of function ns1__deleteDir</documentation>
+  <input message="tns:deleteDir"/>
+  <output message="tns:deleteDirResponse"/>
+ </operation>
+ <operation name="deleteFile">
+  <documentation>Service definition of function ns1__deleteFile</documentation>
+  <input message="tns:deleteFile"/>
+  <output message="tns:deleteFileResponse"/>
+ </operation>
+ <operation name="setForcedOperations">
+  <documentation>Service definition of function ns1__setForcedOperations</documentation>
+  <input message="tns:setForcedOperations"/>
+  <output message="tns:setForcedOperationsResponse"/>
+ </operation>
+ <operation name="fileChecksum">
+  <documentation>Service definition of function ns1__fileChecksum</documentation>
+  <input message="tns:fileChecksumRequest"/>
+  <output message="tns:fileChecksumResponse"/>
+ </operation>
+ <operation name="format">
+  <documentation>Service definition of function ns1__format</documentation>
+  <input message="tns:format"/>
+  <output message="tns:formatResponse"/>
+ </operation>
+ <operation name="listDrives">
+  <documentation>Service definition of function ns1__listDrives</documentation>
+  <input message="tns:listDrivesRequest"/>
+  <output message="tns:listDrivesResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiFtp" type="tns:HtiFtpPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="putFile">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getFile">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="cancelFileTransfer">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="listFiles">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="listFilesSizes">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="listDirs">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="createDir">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteDir">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteFile">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setForcedOperations">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="fileChecksum">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="format">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="listDrives">
+  <SOAP:operation style="rpc" soapAction="HtiFtp"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiFtp">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiFtp" binding="tns:HtiFtp">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiFtp/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+#include "HtiFtp.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+//additional export functions requried for an hti-plugin
+#define HTI_SOAP_ACTION "HtiFtp"
+#define HTI_UID 0x1020DEC5
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiKeyEvent.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,246 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiKeyEventH.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+
+const unsigned char CMD_SINGLE_KEY_PRESS   = 0x01;
+const unsigned char CMD_KEY_DOWN           = 0x02;
+const unsigned char CMD_KEY_UP             = 0x03;
+const unsigned char CMD_TYPE_TEXT          = 0x04;
+const unsigned char CMD_LONG_KEY_PRESS     = 0x05;
+const unsigned char CMD_TYPE_TEXT_PASSWORD = 0x06;
+const unsigned char CMD_KEY_PRESS_SEQUENCE = 0x07;
+const unsigned char CMD_TAP_SCREEN         = 0x10;
+const unsigned char CMD_TAP_AND_DRAG       = 0x11;
+const unsigned char CMD_TAP_AND_DRAG_MULTI = 0x12;
+const unsigned char CMD_POINTER_DOWN       = 0x13;
+const unsigned char CMD_POINTER_UP         = 0x14;
+
+const unsigned char KEY_EVENT_OK = 0xFF;
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// ns1__pressKey()
+//**********************************************************************************
+int ns1__pressKey(struct soap* soap,
+				  short key,
+                  struct ns1__pressKeyResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_SINGLE_KEY_PRESS );
+	msg.AddWord( key );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__holdKey()
+//**********************************************************************************
+int ns1__holdKey(struct soap* soap,
+				 short key,
+                 struct ns1__holdKeyResponse *out )
+{
+	HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_KEY_DOWN );
+	msg.AddWord( key );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__releaseKey()
+//**********************************************************************************
+int ns1__releaseKey(struct soap* soap, 
+					short key,
+                    struct ns1__releaseKeyResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_KEY_UP );
+	msg.AddWord( key );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__longKeyPress()
+//**********************************************************************************
+int ns1__longKeyPress(struct soap* soap,
+					  short key,
+					  short time,
+                      struct ns1__longKeyPressResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_LONG_KEY_PRESS );
+	msg.AddWord( key );
+	msg.AddWord( time );
+	return msg.SendReceiveMsg( time + HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__typeText()
+//**********************************************************************************
+int ns1__typeText(struct soap* soap, 
+				  wchar_t *text, 
+                  struct ns1__typeTextResponse *out)
+{
+	if(check_mandatory_wcstring_parameter(soap, text, "text"))
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_TYPE_TEXT );
+	msg.AddWCString( text );
+
+	// Set timeout for ok message
+	// Assume that writing 100 characters takes 10 seconds (should be more than enough)
+	// = 10s/100char = 0.1s/char = 100ms/char
+	int timeout = (int) wcslen(text)*100;
+	timeout+= HTIMSG_TIMEOUT_10_SECONDS; // add extra 10 seconds for lag
+	return msg.SendReceiveMsg( timeout );
+}
+
+//**********************************************************************************
+// ns1__typeTextPassword()
+//**********************************************************************************
+int ns1__typeTextPassword(struct soap* soap, 
+						  wchar_t *text, 
+                          struct ns1__typeTextPasswordResponse *out)
+{
+	if(check_mandatory_wcstring_parameter(soap, text, "text"))
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_TYPE_TEXT_PASSWORD );
+	msg.AddWCString( text );
+
+	// Set timeout for ok message
+	// Assume that writing 100 characters takes 10 seconds (should be more than enough)
+	// = 10s/100char = 0.1s/char = 100ms/char
+	int timeout = (int) wcslen(text)*100;
+	timeout+= HTIMSG_TIMEOUT_10_SECONDS; // add extra 10 seconds for lag
+	return msg.SendReceiveMsg( timeout );
+}
+
+//**********************************************************************************
+// ns1__keyPressSequence()
+//**********************************************************************************
+int ns1__keyPressSequence(struct soap* soap,
+                          short time,
+                          short interval,
+                          struct ns1__arrayOfKeyCodes keyCodes,
+                       	  struct ns1__keyPressSequenceResponse *out)
+{
+    HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_KEY_PRESS_SEQUENCE );
+    msg.AddWord( time );
+    msg.AddWord( interval );
+ 	for ( int i = 0; i < keyCodes.__size; i++ )
+	{
+		msg.AddWord( keyCodes.__ptrKeyCode[i] );
+    }
+    int timeout = keyCodes.__size * ( time + interval );
+    timeout += HTIMSG_TIMEOUT_10_SECONDS;
+    return msg.SendReceiveMsg( timeout );
+}
+
+//**********************************************************************************
+// ns1__tapScreen()
+//**********************************************************************************
+int ns1__tapScreen(struct soap* soap,
+				   struct ns1__HtiPoint tapPoint,
+				   short timeToHold,
+				   short tapCount,
+                   short pauseBetweenTaps,
+                   struct ns1__tapScreenResponse *out)
+{
+    HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_TAP_SCREEN );
+    msg.AddWord( tapPoint.xCoordinate );
+	msg.AddWord( tapPoint.yCoordinate );
+    msg.AddWord( timeToHold );
+    msg.AddWord( tapCount );
+    msg.AddWord( pauseBetweenTaps );
+    int timeout = tapCount * ( timeToHold + pauseBetweenTaps );
+    timeout += HTIMSG_TIMEOUT_10_SECONDS;
+	return msg.SendReceiveMsg( timeout );
+}
+
+//**********************************************************************************
+// ns1__tapAndDrag()
+//**********************************************************************************
+int ns1__tapAndDrag(struct soap* soap,
+                    struct ns1__HtiPoint pointDown,
+                    struct ns1__HtiPoint pointUp,
+                    short dragTime,
+                    struct ns1__tapAndDragResponse *out)
+{
+    HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_TAP_AND_DRAG );
+    msg.AddWord( pointDown.xCoordinate );
+    msg.AddWord( pointDown.yCoordinate );
+    msg.AddWord( pointUp.xCoordinate );
+    msg.AddWord( pointUp.yCoordinate );
+    msg.AddWord( dragTime );
+    return msg.SendReceiveMsg( dragTime + HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__tapAndDragMultipoint()
+//**********************************************************************************
+int ns1__tapAndDragMultipoint(struct soap* soap,
+                              short timeBetweenPoints,
+                              short timeBetweenLines,
+                              struct ns1__arrayOfLines lines,
+                              struct ns1__tapAndDragMultipointResponse *out)
+{
+    HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_TAP_AND_DRAG_MULTI );
+    msg.AddWord( timeBetweenPoints );
+    msg.AddWord( timeBetweenLines );
+    int pointCount = 0;
+    for ( int i = 0; i < lines.__size; i++ )
+    {
+        int pointsInLine = lines.__ptrLine[i].__size;
+        pointCount += pointsInLine;
+        msg.AddWord( pointsInLine );
+        for ( int j = 0; j < pointsInLine; j++ )
+        {
+            msg.AddWord( lines.__ptrLine[i].__ptrPoint[j].xCoordinate );
+            msg.AddWord( lines.__ptrLine[i].__ptrPoint[j].yCoordinate );
+        }
+    }
+
+    int timeout = ( pointCount * timeBetweenPoints ) +
+                  ( lines.__size * timeBetweenLines );
+    timeout += HTIMSG_TIMEOUT_10_SECONDS;
+    return msg.SendReceiveMsg( timeout );
+}
+
+//**********************************************************************************
+// ns1__pointerDown()
+//**********************************************************************************
+int ns1__pointerDown(struct soap* soap,
+				     struct ns1__HtiPoint pointDown,
+                     struct ns1__pointerDownResponse *out )
+{
+    HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_POINTER_DOWN );
+    msg.AddWord( pointDown.xCoordinate );
+    msg.AddWord( pointDown.yCoordinate );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__pointerUp()
+//**********************************************************************************
+int ns1__pointerUp(struct soap* soap,
+				   struct ns1__HtiPoint pointUp,
+                   struct ns1__pointerUpResponse *out )
+{
+    HtiMsgHelper msg( soap, HTI_KEYEVENT_UID, CMD_POINTER_UP );
+    msg.AddWord( pointUp.xCoordinate );
+    msg.AddWord( pointUp.yCoordinate );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiKeyEvent.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,121 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiKeyEvent
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char*		xsd__string;
+typedef wchar_t*	xsd__string_;
+typedef int         xsd__int;
+typedef short		xsd__short;
+
+struct ns1__HtiPoint
+{
+    xsd__short xCoordinate;
+    xsd__short yCoordinate;
+};
+
+struct ns1__arrayOfKeyCodes
+{
+    xsd__short* __ptrKeyCode;
+    xsd__int    __size;
+};
+
+struct ns1__arrayOfPoints // = line
+{
+    struct ns1__HtiPoint* __ptrPoint;
+    int __size;    
+};
+
+struct ns1__arrayOfLines
+{
+    struct ns1__arrayOfPoints* __ptrLine;
+    int __size;
+};
+
+//gsoap ns1 service method-action: pressKey "HtiKeyEvent" 
+int ns1__pressKey(
+    xsd__short    key,
+	struct ns1__pressKeyResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: holdKey "HtiKeyEvent" 
+int ns1__holdKey(
+	xsd__short    key,
+	struct ns1__holdKeyResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: releaseKey "HtiKeyEvent" 
+int ns1__releaseKey(
+	xsd__short    key,
+	struct ns1__releaseKeyResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: longKeyPress "HtiKeyEvent" 
+int ns1__longKeyPress(
+	xsd__short    key,
+	xsd__short    time,
+	struct ns1__longKeyPressResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: typeText "HtiKeyEvent" 
+int ns1__typeText(
+	xsd__string_    text,
+	struct ns1__typeTextResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: typeTextPassword "HtiKeyEvent" 
+int ns1__typeTextPassword(
+	xsd__string_    text,
+	struct ns1__typeTextPasswordResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: keyPressSequence "HtiKeyEvent" 
+int ns1__keyPressSequence(
+	xsd__short    time,
+    xsd__short    interval,
+    struct ns1__arrayOfKeyCodes keyCodes,
+	struct ns1__keyPressSequenceResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: tapScreen "HtiKeyEvent" 
+int ns1__tapScreen(
+    struct ns1__HtiPoint tapPoint,
+    xsd__short    timeToHold,
+    xsd__short    tapCount,
+    xsd__short    pauseBetweenTaps,
+    struct ns1__tapScreenResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: tapAndDrag "HtiKeyEvent" 
+int ns1__tapAndDrag(
+    struct ns1__HtiPoint pointDown,
+    struct ns1__HtiPoint pointUp,
+    xsd__short    dragTime,
+    struct ns1__tapAndDragResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: tapAndDragMultipoint "HtiKeyEvent" 
+int ns1__tapAndDragMultipoint(
+    xsd__short    timeBetweenPoints,
+    xsd__short    timeBetweenLines,
+    struct ns1__arrayOfLines lines,
+    struct ns1__tapAndDragMultipointResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: pointerDown "HtiKeyEvent" 
+int ns1__pointerDown(
+    struct ns1__HtiPoint pointDown,
+    struct ns1__pointerDownResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: pointerUp "HtiKeyEvent" 
+int ns1__pointerUp(
+    struct ns1__HtiPoint pointUp,
+    struct ns1__pointerUpResponse{} *out // empty response
+);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiKeyEvent.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,248 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiKeyEvent"
+	ProjectGUID="{17A20053-2D4E-448A-9B2F-FE8E5A81FF24}"
+	RootNamespace="HtiKeyEvent"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiKeyEvent.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiKeyEventServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiKeyEvent.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiKeyEvent.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiKeyEventH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiKeyEventStub.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiKeyEvent.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,359 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiKeyEvent"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <complexType name="HtiPoint">
+   <sequence>
+     <element name="xCoordinate" type="xsd:short" minOccurs="1" maxOccurs="1"/>
+     <element name="yCoordinate" type="xsd:short" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="arrayOfKeyCodes">
+   <sequence>
+    <element name="KeyCode" type="xsd:short" minOccurs="0" maxOccurs="unbounded" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="arrayOfPoints">
+   <sequence>
+    <element name="Point" type="ns1:HtiPoint" minOccurs="0" maxOccurs="unbounded" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="arrayOfLines">
+   <sequence>
+    <element name="Line" type="ns1:arrayOfPoints" minOccurs="0" maxOccurs="unbounded" nillable="true"/>
+   </sequence>
+  </complexType>
+  <!-- operation request element -->
+  <element name="key" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="time" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="text" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="interval" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="keyCodes" type="ns1:arrayOfKeyCodes"/>
+  <!-- operation request element -->
+  <element name="tapPoint" type="ns1:HtiPoint"/>
+  <!-- operation request element -->
+  <element name="timeToHold" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="tapCount" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="pauseBetweenTaps" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="pointDown" type="ns1:HtiPoint"/>
+  <!-- operation request element -->
+  <element name="pointUp" type="ns1:HtiPoint"/>
+  <!-- operation request element -->
+  <element name="dragTime" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="timeBetweenPoints" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="timeBetweenLines" type="xsd:short"/>
+  <!-- operation request element -->
+  <element name="lines" type="ns1:arrayOfLines"/>
+ </schema>
+
+</types>
+
+<message name="pressKey">
+ <part name="key" element="ns1:key"/>
+</message>
+
+<message name="pressKeyResponse">
+</message>
+
+<message name="holdKey">
+ <part name="key" element="ns1:key"/>
+</message>
+
+<message name="holdKeyResponse">
+</message>
+
+<message name="releaseKey">
+ <part name="key" element="ns1:key"/>
+</message>
+
+<message name="releaseKeyResponse">
+</message>
+
+<message name="longKeyPress">
+ <part name="key" element="ns1:key"/>
+ <part name="time" element="ns1:time"/>
+</message>
+
+<message name="longKeyPressResponse">
+</message>
+
+<message name="typeText">
+ <part name="text" element="ns1:text"/>
+</message>
+
+<message name="typeTextResponse">
+</message>
+
+<message name="typeTextPassword">
+ <part name="text" element="ns1:text"/>
+</message>
+
+<message name="typeTextPasswordResponse">
+</message>
+
+<message name="keyPressSequence">
+ <part name="time" element="ns1:time"/>
+ <part name="interval" element="ns1:interval"/>
+ <part name="keyCodes" element="ns1:keyCodes"/>
+</message>
+
+<message name="keyPressSequenceResponse">
+</message>
+
+<message name="tapScreen">
+ <part name="tapPoint" element="ns1:tapPoint"/>
+ <part name="timeToHold" element="ns1:timeToHold"/>
+ <part name="tapCount" element="ns1:tapCount"/>
+ <part name="pauseBetweenTaps" element="ns1:pauseBetweenTaps"/>
+</message>
+
+<message name="tapScreenResponse">
+</message>
+
+<message name="tapAndDrag">
+ <part name="pointDown" element="ns1:pointDown"/>
+ <part name="pointUp" element="ns1:pointUp"/>
+ <part name="dragTime" element="ns1:dragTime"/>
+</message>
+
+<message name="tapAndDragResponse">
+</message>
+
+<message name="tapAndDragMultipoint">
+ <part name="timeBetweenPoints" element="ns1:timeBetweenPoints"/>
+ <part name="timeBetweenLines" element="ns1:timeBetweenLines"/>
+ <part name="lines" element="ns1:lines"/>
+</message>
+
+<message name="tapAndDragMultipointResponse">
+</message>
+
+<message name="pointerDown">
+ <part name="pointDown" element="ns1:pointDown"/>
+</message>
+
+<message name="pointerDownResponse">
+</message>
+
+<message name="pointerUp">
+ <part name="pointUp" element="ns1:pointUp"/>
+</message>
+
+<message name="pointerUpResponse">
+</message>
+
+<portType name="HtiKeyEventPortType">
+ <operation name="pressKey">
+  <documentation>Service definition of function ns1__pressKey</documentation>
+  <input message="tns:pressKey"/>
+  <output message="tns:pressKeyResponse"/>
+ </operation>
+ <operation name="holdKey">
+  <documentation>Service definition of function ns1__holdKey</documentation>
+  <input message="tns:holdKey"/>
+  <output message="tns:holdKeyResponse"/>
+ </operation>
+ <operation name="releaseKey">
+  <documentation>Service definition of function ns1__releaseKey</documentation>
+  <input message="tns:releaseKey"/>
+  <output message="tns:releaseKeyResponse"/>
+ </operation>
+ <operation name="longKeyPress">
+  <documentation>Service definition of function ns1__longKeyPress</documentation>
+  <input message="tns:longKeyPress"/>
+  <output message="tns:longKeyPressResponse"/>
+ </operation>
+ <operation name="typeText">
+  <documentation>Service definition of function ns1__typeText</documentation>
+  <input message="tns:typeText"/>
+  <output message="tns:typeTextResponse"/>
+ </operation>
+ <operation name="typeTextPassword">
+  <documentation>Service definition of function ns1__typeTextPassword</documentation>
+  <input message="tns:typeTextPassword"/>
+  <output message="tns:typeTextPasswordResponse"/>
+ </operation>
+ <operation name="keyPressSequence">
+  <documentation>Service definition of function ns1__keyPressSequence</documentation>
+  <input message="tns:keyPressSequence"/>
+  <output message="tns:keyPressSequenceResponse"/>
+ </operation>
+ <operation name="tapScreen">
+  <documentation>Service definition of function ns1__tapScreen</documentation>
+  <input message="tns:tapScreen"/>
+  <output message="tns:tapScreenResponse"/>
+ </operation>
+ <operation name="tapAndDrag">
+  <documentation>Service definition of function ns1__tapAndDrag</documentation>
+  <input message="tns:tapAndDrag"/>
+  <output message="tns:tapAndDragResponse"/>
+ </operation>
+ <operation name="tapAndDragMultipoint">
+  <documentation>Service definition of function ns1__tapAndDragMultipoint</documentation>
+  <input message="tns:tapAndDragMultipoint"/>
+  <output message="tns:tapAndDragMultipointResponse"/>
+ </operation>
+ <operation name="pointerDown">
+  <documentation>Service definition of function ns1__pointerDown</documentation>
+  <input message="tns:pointerDown"/>
+  <output message="tns:pointerDownResponse"/>
+ </operation>
+ <operation name="pointerUp">
+  <documentation>Service definition of function ns1__pointerUp</documentation>
+  <input message="tns:pointerUp"/>
+  <output message="tns:pointerUpResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiKeyEvent" type="tns:HtiKeyEventPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="pressKey">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="holdKey">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="releaseKey">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="longKeyPress">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="typeText">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="typeTextPassword">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="keyPressSequence">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="tapScreen">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="tapAndDrag">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="tapAndDragMultipoint">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="pointerDown">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="pointerUp">
+  <SOAP:operation style="rpc" soapAction="HtiKeyEvent"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiKeyEvent">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiKeyEvent" binding="tns:HtiKeyEvent">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiKeyEvent/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,49 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+//additional export functions requried for an hti-plugin
+#define HTI_KEYEVENT_SOAP_ACTION "HtiKeyEvent"
+#define HTI_KEYEVENT_UID 0x1020DEC1
+
+#include "HtiKeyEvent.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_KEYEVENT_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_KEYEVENT_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+/**
+* 
+*/
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiMessages.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,603 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiMessagesH.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+
+//**********************************************************************************
+// CONSTANTS
+//
+//**********************************************************************************
+
+// commands
+const unsigned char CMD_ADD_SMS_TO_INDOX        = 0x01;
+const unsigned char CMD_ADD_MMS_TO_INDOX        = 0x02;
+const unsigned char CMD_ADD_EMAIL               = 0x03;
+const unsigned char CMD_ADD_IR_MESSAGE          = 0x04;
+const unsigned char CMD_ADD_BT_MESSAGE          = 0x05;
+const unsigned char CMD_ADD_SMART_MESSAGE       = 0x06;
+const unsigned char CMD_ADD_AUDIO_MESSAGE       = 0x07;
+const unsigned char CMD_DELETE_MESSAGE          = 0x10;
+const unsigned char CMD_DELETE_ALL_FROM_FOLDER  = 0x11;
+const unsigned char CMD_CREATE_MAILBOX          = 0x20;
+const unsigned char CMD_DELETE_MAILBOX          = 0x21;
+const unsigned char CMD_CREATE_ACCESS_POINT     = 0x30;
+const unsigned char CMD_DELETE_ACCESS_POINT     = 0x31;
+const unsigned char CMD_CREATE_DESTINATION      = 0x32;
+const unsigned char CMD_DELETE_DESTINATION      = 0x33;
+const unsigned char CMD_ADD_TO_DESTINATION      = 0x34;
+const unsigned char CMD_REMOVE_FROM_DESTINATION = 0x35;
+const unsigned char CMD_SET_DEFAULT_SMS_CENTER  = 0x40;
+const unsigned char CMD_DELETE_SMS_CENTER       = 0x41;
+const unsigned char CMD_SET_SMS_SETTINGS        = 0x42;
+const unsigned char CMD_SET_MMS_SETTINGS        = 0x45;
+
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// ns1__addSMS
+//**********************************************************************************
+int ns1__addSMS(struct soap* soap,
+                char *fromField,
+                char *description,
+                char *messageBody,
+                bool isNewFlag,
+                bool isUnreadFlag,
+                enum ns1__folder folder,
+                int &messageId)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_ADD_SMS_TO_INDOX );
+    msg.AddStringWithLengthByteZero( fromField );
+    msg.AddStringWithLengthByteZero( description );
+    msg.AddStringWithLengthWordZero( messageBody );
+    msg.AddByte( isNewFlag );
+    msg.AddByte( isUnreadFlag );
+    msg.AddByte( folder );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    if ( msg.CheckMsgExactLen( 5 ) )
+        return SOAP_FAULT;
+
+    messageId = msg.GetInt( 1 );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__addMMS
+//**********************************************************************************
+int ns1__addMMS(struct soap* soap,
+                char *fromField,
+                char *description,
+                char *messageBody,
+                char *attachmentPath,
+                bool isNewFlag,
+                bool isUnreadFlag,
+                enum ns1__folder folder,
+                int &messageId)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_ADD_MMS_TO_INDOX );
+    msg.AddStringWithLengthByteZero( fromField );
+    msg.AddStringWithLengthByteZero( description );
+    msg.AddStringWithLengthWordZero( messageBody );
+    msg.AddStringWithLengthByteZero( attachmentPath );
+    msg.AddByte( isNewFlag );
+    msg.AddByte( isUnreadFlag );
+    msg.AddByte( folder );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    if ( msg.CheckMsgExactLen( 5 ) )
+        return SOAP_FAULT;
+
+    messageId = msg.GetInt( 1 );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__addEMail
+//**********************************************************************************
+int ns1__addEMail(struct soap* soap,
+                  char *fromField,
+                  char *description,
+                  char *messageBody,
+                  char *attachmentPath,
+                  bool isNewFlag,
+                  bool isUnreadFlag,
+                  enum ns1__folder folder,
+                  int &messageId)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_ADD_EMAIL );
+    msg.AddStringWithLengthByteZero( fromField );
+    msg.AddStringWithLengthByteZero( description );
+    msg.AddStringWithLengthWordZero( messageBody );
+    msg.AddStringWithLengthByteZero( attachmentPath );
+    msg.AddByte( isNewFlag );
+    msg.AddByte( isUnreadFlag );
+    msg.AddByte( folder );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    if ( msg.CheckMsgExactLen( 5 ) )
+        return SOAP_FAULT;
+
+    messageId = msg.GetInt( 1 );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__addIRMessage
+//**********************************************************************************
+int ns1__addIRMessage(struct soap* soap,
+                      char *fromField,
+                      char *description,
+                      char *attachmentPath,
+                      bool isNewFlag,
+                      bool isUnreadFlag,
+                      enum ns1__folder folder,
+                      int &messageId)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_ADD_IR_MESSAGE );
+    msg.AddStringWithLengthByteZero( fromField );
+    msg.AddStringWithLengthByteZero( description );
+    msg.AddStringWithLengthByteZero( attachmentPath );
+    msg.AddByte( isNewFlag );
+    msg.AddByte( isUnreadFlag );
+    msg.AddByte( folder );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    if ( msg.CheckMsgExactLen( 5 ) )
+        return SOAP_FAULT;
+
+    messageId = msg.GetInt( 1 );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__addBTMessage
+//**********************************************************************************
+int ns1__addBTMessage(struct soap* soap,
+                      char *fromField,
+                      char *description,
+                      char *attachmentPath,
+                      bool isNewFlag,
+                      bool isUnreadFlag,
+                      enum ns1__folder folder,
+                      int &messageId)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_ADD_BT_MESSAGE );
+    msg.AddStringWithLengthByteZero( fromField );
+    msg.AddStringWithLengthByteZero( description );
+    msg.AddStringWithLengthByteZero( attachmentPath );
+    msg.AddByte( isNewFlag );
+    msg.AddByte( isUnreadFlag );
+    msg.AddByte( folder );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    if ( msg.CheckMsgExactLen( 5 ) )
+        return SOAP_FAULT;
+
+    messageId = msg.GetInt( 1 );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__addSmartMessage
+//**********************************************************************************
+int ns1__addSmartMessage(struct soap* soap,
+                         char *fromField,
+                         char *description,
+                         char *messageBody,
+                         bool isNewFlag,
+                         bool isUnreadFlag,
+                         enum ns1__folder folder,
+                         int BIOmessageType,
+                         int &messageId)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_ADD_SMART_MESSAGE );
+    msg.AddStringWithLengthByteZero( fromField );
+    msg.AddStringWithLengthByteZero( description );
+    msg.AddStringWithLengthWordZero( messageBody );
+    msg.AddByte( isNewFlag );
+    msg.AddByte( isUnreadFlag );
+    msg.AddByte( folder );
+    msg.AddInt( BIOmessageType );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    if ( msg.CheckMsgExactLen( 5 ) )
+        return SOAP_FAULT;
+
+    messageId = msg.GetInt( 1 );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__addAudioMessage
+//**********************************************************************************
+int ns1__addAudioMessage(struct soap* soap,
+                         char *fromField,
+                         char *description,
+                         char *attachmentPath,
+                         bool isNewFlag,
+                         bool isUnreadFlag,
+                         enum ns1__folder folder,
+                         int &messageId)
+{
+    if ( check_mandatory_string_parameter( soap, attachmentPath, "attachmentPath" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_ADD_AUDIO_MESSAGE );
+    msg.AddStringWithLengthByteZero( fromField );
+    msg.AddStringWithLengthByteZero( description );
+    msg.AddStringWithLengthByteZero( attachmentPath );
+    msg.AddByte( isNewFlag );
+    msg.AddByte( isUnreadFlag );
+    msg.AddByte( folder );
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    if ( msg.CheckMsgExactLen( 5 ) )
+        return SOAP_FAULT;
+
+    messageId = msg.GetInt( 1 );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__deleteMessage
+//**********************************************************************************
+int ns1__deleteMessage(struct soap* soap,
+                       int messageId,
+                       struct ns1__deleteMessageResponse *out)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_MESSAGE );
+    msg.AddInt( messageId );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__deleteMessage
+//**********************************************************************************
+int ns1__deleteAllFromFolder(struct soap* soap,
+                             enum ns1__messageType type,
+                             enum ns1__folder folder,
+                             struct ns1__deleteAllFromFolderResponse *out)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_ALL_FROM_FOLDER );
+    msg.AddByte( folder );
+    msg.AddByte( type );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__createAccessPoint
+//**********************************************************************************
+int ns1__createAccessPoint(struct soap* soap,
+                           enum ns1__bearerType bearer,
+                           char *apName,
+                           struct ArrayOfHtiAPSettingFields APSettings,
+                           int &entryId)
+{
+    if ( check_mandatory_string_parameter( soap, apName, "apName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_CREATE_ACCESS_POINT );
+    msg.AddByte( bearer );
+    msg.AddStringWithLengthByte( apName );
+    msg.AddByte( (BYTE) APSettings.__size );
+
+    // Loop through setting fields
+    for ( int i = 0; i < APSettings.__size; i++ )
+    {
+        msg.AddByte( APSettings.__ptrHtiAPSettingField[i].fieldType );
+
+        // fieldData cannot be empty
+        if ( check_mandatory_string_parameter( soap,
+               APSettings.__ptrHtiAPSettingField[i].fieldData,
+               "HtiAPSettingField.fieldData" ) )
+               return SOAP_FAULT;
+
+        msg.AddStringWithLengthByte( APSettings.__ptrHtiAPSettingField[i].fieldData );
+    }
+
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+        return SOAP_FAULT;
+
+    if ( msg.CheckCommandCode( 0xFF ) || msg.CheckMsgExactLen( 5 ) )
+        return SOAP_FAULT;
+
+    entryId = msg.GetInt( 1 );
+
+    return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__deleteAccessPoint
+//**********************************************************************************
+int ns1__deleteAccessPoint(struct soap* soap,
+                           char *apName,
+                           struct ns1__deleteAccessPointResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, apName, "apName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_ACCESS_POINT );
+    msg.AddStringWithLengthByte( apName );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__createMailbox
+//**********************************************************************************
+int ns1__createMailbox(struct soap* soap,
+                       enum ns1__mailboxType mailboxType,
+                       char *mailboxName,
+                       char *incomingServer,
+                       char *incomingAccessPoint,
+                       char *incomingUsername,
+                       char *incomingPassword,
+                       enum ns1__securitySetting incomingSecurity,
+                       unsigned short incomingPort,
+                       bool aPopSecureLogin,
+                       char *outgoingServer,
+                       char *outgoingAccessPoint,
+                       char *outgoingUsername,
+                       char *outgoingPassword,
+                       enum ns1__securitySetting outgoingSecurity,
+                       unsigned short outgoingPort,
+                       char *ownMailAddress,
+                       char *ownName,
+                       enum ns1__sendOption sendOption,
+                       enum ns1__copyToOwn copyToOwnAddress,
+                       char *signatureText,
+                       bool newMailIndicators,
+                       enum ns1__retrievedParts retrievedParts,
+                       unsigned short retrieveSizeLimit,
+                       unsigned short emailsToRetrieve,
+                       char *imap4FolderPath,
+                       enum ns1__automaticUpdate automaticUpdate,
+                       bool setAsDefault,
+                       struct ns1__createMailboxResponse *out)
+{
+    // Check for mandatory stuff
+    if ( check_mandatory_string_parameter( soap, mailboxName, "mailboxName" ) )
+        return SOAP_FAULT;
+
+    if ( check_mandatory_string_parameter( soap, incomingServer, "incomingServer" ) )
+        return SOAP_FAULT;
+
+    if ( check_mandatory_string_parameter( soap, outgoingServer, "outgoingServer" ) )
+        return SOAP_FAULT;
+
+    if ( check_mandatory_string_parameter( soap, ownMailAddress, "ownMailAddress" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_CREATE_MAILBOX );
+    msg.AddByte( mailboxType );
+    msg.AddStringWithLengthByte( mailboxName );
+    msg.AddStringWithLengthByte( incomingServer );
+    msg.AddStringWithLengthByteZero( incomingAccessPoint );
+    msg.AddStringWithLengthByteZero( incomingUsername );
+    msg.AddStringWithLengthByteZero( incomingPassword );
+    msg.AddByte( incomingSecurity );
+    msg.AddWord( incomingPort );
+    msg.AddByte( aPopSecureLogin );
+    msg.AddStringWithLengthByte( outgoingServer );
+    msg.AddStringWithLengthByteZero( outgoingAccessPoint );
+    msg.AddStringWithLengthByteZero( outgoingUsername );
+    msg.AddStringWithLengthByteZero( outgoingPassword );
+    msg.AddByte( outgoingSecurity );
+    msg.AddWord( outgoingPort );
+    msg.AddStringWithLengthByte( ownMailAddress );
+    msg.AddStringWithLengthByteZero( ownName );
+    msg.AddByte( sendOption );
+    msg.AddByte( copyToOwnAddress );
+    msg.AddStringWithLengthWordZero( signatureText );
+    msg.AddByte( newMailIndicators );
+    msg.AddByte( retrievedParts );
+    msg.AddWord( retrieveSizeLimit );
+    msg.AddWord( emailsToRetrieve );
+    msg.AddStringWithLengthByteZero( imap4FolderPath );
+    msg.AddByte( automaticUpdate );
+    msg.AddByte( setAsDefault );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__deleteMailbox
+//**********************************************************************************
+int ns1__deleteMailbox(struct soap* soap,
+                       char *mailboxName,
+                       struct ns1__deleteMailboxResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, mailboxName, "mailboxName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_MAILBOX );
+    msg.AddStringWithLengthByte( mailboxName );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__setDefaultSmsCenter
+//**********************************************************************************
+int ns1__setDefaultSmsCenter(struct soap* soap,
+                             char *smsCenterName,
+                             char *smsCenterNumber,
+                             struct ns1__setDefaultSmsCenterResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, smsCenterName, "smsCenterName" ) )
+        return SOAP_FAULT;
+    if ( check_mandatory_string_parameter( soap, smsCenterNumber, "smsCenterNumber" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_SET_DEFAULT_SMS_CENTER );
+    msg.AddStringWithLengthByte( smsCenterName );
+    msg.AddStringWithLengthByte( smsCenterNumber );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__deleteSmsCenter
+//**********************************************************************************
+int ns1__deleteSmsCenter(struct soap* soap,
+                         char *smsCenterName,
+                         struct ns1__deleteSmsCenterResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, smsCenterName, "smsCenterName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_SMS_CENTER );
+    msg.AddStringWithLengthByte( smsCenterName );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__setSmsSettings
+//**********************************************************************************
+int ns1__setSmsSettings(struct soap* soap,
+                        enum ns1__smsCharacterSupport characterSupport,
+                        bool requestDeliveryReport,
+                        enum ns1__msgValidity validityPeriod,
+                        enum ns1__smsMessageConversion messageConversion,
+                        enum ns1__smsPreferredConnection preferredConnection,
+                        bool replyViaSameCenter,
+                        struct ns1__setSmsSettingsResponse *out)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_SET_SMS_SETTINGS );
+    msg.AddByte( characterSupport );
+    msg.AddByte( requestDeliveryReport );
+    msg.AddByte( validityPeriod );
+    msg.AddByte( messageConversion );
+    msg.AddByte( preferredConnection );
+    msg.AddByte( replyViaSameCenter );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__setMmsSettings
+//**********************************************************************************
+int ns1__setMmsSettings(struct soap* soap,
+                        char *accessPointName,
+					    enum ns1__mmsCreationMode creationMode,
+					    enum ns1__mmsImageSize imageSize,
+					    enum ns1__mmsReception reception,
+					    bool receiveAnonymous,
+					    bool receiveAdvertisements,
+					    bool requestDeliveryReports,
+					    bool sendDeliveryReports,
+ 					    enum ns1__msgValidity validityPeriod,
+                        struct ns1__setMmsSettingsResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, accessPointName, "accessPointName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_SET_MMS_SETTINGS );
+    msg.AddStringWithLengthByte( accessPointName );
+    msg.AddByte( creationMode );
+    msg.AddByte( imageSize );
+    msg.AddByte( reception );
+    msg.AddByte( receiveAnonymous );
+    msg.AddByte( receiveAdvertisements );
+    msg.AddByte( requestDeliveryReports );
+    msg.AddByte( sendDeliveryReports );
+    msg.AddByte( validityPeriod );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__createDestination
+//**********************************************************************************
+int ns1__createDestination(struct soap* soap,
+                           char *destinationName,
+                           struct ns1__createDestinationResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, destinationName, "destinationName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_CREATE_DESTINATION );
+    msg.AddStringWithLengthByte( destinationName );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__deleteDestination
+//**********************************************************************************
+int ns1__deleteDestination(struct soap* soap,
+                           char *destinationName,
+                           struct ns1__deleteDestinationResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, destinationName, "destinationName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_DESTINATION );
+    msg.AddStringWithLengthByte( destinationName );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__addToDestination
+//**********************************************************************************
+int ns1__addToDestination(struct soap* soap,
+                          char *accessPointName,
+                          char *destinationName,
+                          struct ns1__addToDestinationResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, accessPointName, "accessPointName" ) )
+        return SOAP_FAULT;
+
+    if ( check_mandatory_string_parameter( soap, destinationName, "destinationName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_ADD_TO_DESTINATION );
+    msg.AddStringWithLengthByte( accessPointName );
+    msg.AddStringWithLengthByte( destinationName );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__removeFromDestination
+//**********************************************************************************
+int ns1__removeFromDestination(struct soap* soap,
+                               char *accessPointName,
+                               char *destinationName,
+                               struct ns1__removeFromDestinationResponse *out)
+{
+    if ( check_mandatory_string_parameter( soap, accessPointName, "accessPointName" ) )
+        return SOAP_FAULT;
+
+    if ( check_mandatory_string_parameter( soap, destinationName, "destinationName" ) )
+        return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_REMOVE_FROM_DESTINATION );
+    msg.AddStringWithLengthByte( accessPointName );
+    msg.AddStringWithLengthByte( destinationName );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiMessages.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,271 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiMessages
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef int             xsd__int;
+typedef char*           xsd__string;
+typedef bool            xsd__boolean;
+typedef unsigned char   xsd__unsignedByte;
+typedef unsigned short  xsd__unsignedShort;
+
+enum ns1__folder      { AllFolders, Indox, Drafts, Sent, Outbox };
+enum ns1__messageType { AllMessages, SMS, MMS, SmartMsg, Email, IRmsg, BTmsg, AudioMsg };
+
+enum ns1__bearerType      { CSD = 1, GPRS = 2, HSCSD = 4, CDMA = 16, WLAN = 32 };
+enum ns1__mailboxType     { POP3, IMAP4 };
+enum ns1__securitySetting { Off, TLS, SSL };
+enum ns1__sendOption      { Immediately, NextConnection, OnRequest };
+enum ns1__copyToOwn       { NoCopy, ToField, CcField, BccField };
+enum ns1__retrievedParts  { OnlyHeaders, LessThanSize, BodyAndAttachments };
+enum ns1__automaticUpdate { AlwaysOn, InHomeNetwork, NotEnabled };
+
+enum ns1__mmsCreationMode { Restricted, Guided, Free };
+enum ns1__mmsImageSize    { Small, Large, Original };
+enum ns1__mmsReception    { AlwaysAutomatic, AutomaticInHomeNetwork,
+                            AlwaysManual, Disabled };
+enum ns1__msgValidity     { Maximum, OneHour, SixHours, TwentyFourHours,
+							ThreeDays, OneWeek };
+
+enum ns1__smsCharacterSupport    { Full, Reduced };
+enum ns1__smsMessageConversion   { None, Fax, Paging, EMail };
+enum ns1__smsPreferredConnection { GSM, PacketData };
+
+struct ns1__HtiAPSettingField
+{
+    xsd__unsignedByte    fieldType;
+    xsd__string          fieldData;
+};
+
+struct ArrayOfHtiAPSettingFields
+{
+    struct ns1__HtiAPSettingField* __ptrHtiAPSettingField;
+    int __size;
+};
+
+
+//gsoap ns1 service method-action: addSMS "HtiMessages"
+int ns1__addSMS(
+    xsd__string      fromField,
+    xsd__string      description,
+    xsd__string      messageBody,
+    xsd__boolean     isNewFlag,
+    xsd__boolean     isUnreadFlag,
+    enum ns1__folder folder,
+    xsd__int         &messageId
+);
+
+//gsoap ns1 service method-action: addMMS "HtiMessages"
+int ns1__addMMS(
+    xsd__string      fromField,
+    xsd__string      description,
+    xsd__string      messageBody,
+    xsd__string      attachmentPath,
+    xsd__boolean     isNewFlag,
+    xsd__boolean     isUnreadFlag,
+    enum ns1__folder folder,
+    xsd__int         &messageId
+);
+
+//gsoap ns1 service method-action: addEMail "HtiMessages"
+int ns1__addEMail(
+    xsd__string      fromField,
+    xsd__string      description,
+    xsd__string      messageBody,
+    xsd__string      attachmentPath,
+    xsd__boolean     isNewFlag,
+    xsd__boolean     isUnreadFlag,
+    enum ns1__folder folder,
+    xsd__int         &messageId
+);
+
+//gsoap ns1 service method-action: addIRMessage "HtiMessages"
+int ns1__addIRMessage(
+    xsd__string      fromField,
+    xsd__string      description,
+    xsd__string      attachmentPath,
+    xsd__boolean     isNewFlag,
+    xsd__boolean     isUnreadFlag,
+    enum ns1__folder folder,
+    xsd__int         &messageId
+);
+
+//gsoap ns1 service method-action: addBTMessage "HtiMessages"
+int ns1__addBTMessage(
+    xsd__string      fromField,
+    xsd__string      description,
+    xsd__string      attachmentPath,
+    xsd__boolean     isNewFlag,
+    xsd__boolean     isUnreadFlag,
+    enum ns1__folder folder,
+    xsd__int         &messageId
+);
+
+//gsoap ns1 service method-action: addSmartMessage "HtiMessages"
+int ns1__addSmartMessage(
+    xsd__string      fromField,
+    xsd__string      description,
+    xsd__string      messageBody,
+    xsd__boolean     isNewFlag,
+    xsd__boolean     isUnreadFlag,
+    enum ns1__folder folder,
+    xsd__int         BIOmessageUID,
+    xsd__int         &messageId
+);
+
+//gsoap ns1 service method-action: addAudioMessage "HtiMessages"
+int ns1__addAudioMessage(
+    xsd__string      fromField,
+    xsd__string      description,
+    xsd__string      attachmentPath,
+    xsd__boolean     isNewFlag,
+    xsd__boolean     isUnreadFlag,
+    enum ns1__folder folder,
+    xsd__int         &messageId
+);
+
+//gsoap ns1 service method-action: deleteMessage "HtiMessages"
+int ns1__deleteMessage(
+    xsd__int         messageId,
+    struct ns1__deleteMessageResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: deleteAllFromFolder "HtiMessages"
+int ns1__deleteAllFromFolder(
+    enum ns1__messageType    type,
+    enum ns1__folder         folder,
+    struct ns1__deleteAllFromFolderResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: createAccessPoint "HtiMessages"
+int ns1__createAccessPoint(
+    enum ns1__bearerType    bearer,
+    xsd__string             apName,
+    struct ArrayOfHtiAPSettingFields    APSettings,
+    xsd__int                            &apId
+);
+
+//gsoap ns1 service method-action: deleteAccessPoint "HtiMessages"
+int ns1__deleteAccessPoint(
+    xsd__string apName,
+    struct ns1__deleteAccessPointResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: createMailbox "HtiMessages"
+int ns1__createMailbox(
+    enum ns1__mailboxType mailboxType,
+    xsd__string mailboxName,
+    xsd__string incomingServer,
+    xsd__string incomingAccessPoint,
+    xsd__string incomingUsername,
+    xsd__string incomingPassword,
+    enum ns1__securitySetting incomingSecurity,
+    xsd__unsignedShort incomingPort,
+    xsd__boolean aPopSecureLogin,
+    xsd__string outgoingServer,
+    xsd__string outgoingAccessPoint,
+    xsd__string outgoingUsername,
+    xsd__string outgoingPassword,
+    enum ns1__securitySetting outgoingSecurity,
+    xsd__unsignedShort outgoingPort,
+    xsd__string ownMailAddress,
+    xsd__string ownName,
+    enum ns1__sendOption sendOption,
+    enum ns1__copyToOwn copyToOwnAddress,
+    xsd__string signatureText,
+    xsd__boolean newMailIndicators,
+    enum ns1__retrievedParts retrievedParts,
+    xsd__unsignedShort retrieveSizeLimit,
+    xsd__unsignedShort emailsToRetrieve,
+    xsd__string imap4FolderPath,
+    enum ns1__automaticUpdate automaticUpdate,
+    xsd__boolean setAsDefault,
+    struct ns1__createMailboxResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: deleteMailbox "HtiMessages"
+int ns1__deleteMailbox(
+    xsd__string mailboxName,
+    struct ns1__deleteMailboxResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: setDefaultSmsCenter "HtiMessages"
+int ns1__setDefaultSmsCenter(
+    xsd__string smsCenterName,
+    xsd__string smsCenterNumber,
+    struct ns1__setDefaultSmsCenterResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: deleteSmsCenter "HtiMessages"
+int ns1__deleteSmsCenter(
+    xsd__string smsCenterName,
+    struct ns1__deleteSmsCenterResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: setSmsSettings "HtiMessages"
+int ns1__setSmsSettings(
+    enum ns1__smsCharacterSupport characterSupport,
+    xsd__boolean requestDeliveryReport,
+    enum ns1__msgValidity validityPeriod,
+    enum ns1__smsMessageConversion messageConversion,
+    enum ns1__smsPreferredConnection preferredConnection,
+    xsd__boolean replyViaSameCenter,
+    struct ns1__setSmsSettingsResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: setMmsSettings "HtiMessages"
+int ns1__setMmsSettings(
+	xsd__string accessPointName,
+    enum ns1__mmsCreationMode creationMode,
+    enum ns1__mmsImageSize imageSize,
+    enum ns1__mmsReception reception,
+    xsd__boolean receiveAnonymous,
+    xsd__boolean receiveAdvertisements,
+    xsd__boolean requestDeliveryReports,
+    xsd__boolean sendDeliveryReports,
+    enum ns1__msgValidity validityPeriod,
+    struct ns1__setMmsSettingsResponse{} *out  //empty response
+);
+
+//gsoap ns1 service method-action: createDestination "HtiMessages"
+int ns1__createDestination(
+    xsd__string destinationName,
+    struct ns1__createDestinationResponse{} *out //empty response
+);
+
+//gsoap ns1 service method-action: deleteDestination "HtiMessages"
+int ns1__deleteDestination(
+    xsd__string destinationName,
+    struct ns1__deleteDestinationResponse{} *out //empty response
+);
+
+//gsoap ns1 service method-action: addToDestination "HtiMessages"
+int ns1__addToDestination(
+    xsd__string accessPointName,
+    xsd__string destinationName,
+    struct ns1__addToDestinationResponse{} *out //empty response
+);
+
+//gsoap ns1 service method-action: removeFromDestination "HtiMessages"
+int ns1__removeFromDestination(
+    xsd__string accessPointName,
+    xsd__string destinationName,
+    struct ns1__removeFromDestinationResponse{} *out //empty response
+);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiMessages.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,250 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiMessages"
+	ProjectGUID="{EF5190F8-0DF0-4514-9212-A22665EBA64D}"
+	RootNamespace="HtiMessages"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiMessages.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiMessagesServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiMessages.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiMessages.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiMessagesH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiMessagesStub.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiMessages.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,834 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiMessages"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <simpleType name="folder">
+   <restriction base="xsd:string">
+    <enumeration value="AllFolders"/>
+    <enumeration value="Indox"/>
+    <enumeration value="Drafts"/>
+    <enumeration value="Sent"/>
+    <enumeration value="Outbox"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="messageType">
+   <restriction base="xsd:string">
+    <enumeration value="AllMessages"/>
+    <enumeration value="SMS"/>
+    <enumeration value="MMS"/>
+    <enumeration value="SmartMsg"/>
+    <enumeration value="Email"/>
+    <enumeration value="IRmsg"/>
+    <enumeration value="BTmsg"/>
+    <enumeration value="AudioMsg"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="bearerType">
+   <restriction base="xsd:string">
+    <enumeration value="CSD"/>
+    <enumeration value="GPRS"/>
+    <enumeration value="HSCSD"/>
+    <enumeration value="CDMA"/>
+    <enumeration value="WLAN"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="mailboxType">
+   <restriction base="xsd:string">
+    <enumeration value="POP3"/>
+    <enumeration value="IMAP4"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="securitySetting">
+   <restriction base="xsd:string">
+    <enumeration value="Off"/>
+    <enumeration value="TLS"/>
+    <enumeration value="SSL"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="sendOption">
+   <restriction base="xsd:string">
+    <enumeration value="Immediately"/>
+    <enumeration value="NextConnection"/>
+    <enumeration value="OnRequest"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="copyToOwn">
+   <restriction base="xsd:string">
+    <enumeration value="NoCopy"/>
+    <enumeration value="ToField"/>
+    <enumeration value="CcField"/>
+    <enumeration value="BccField"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="retrievedParts">
+   <restriction base="xsd:string">
+    <enumeration value="OnlyHeaders"/>
+    <enumeration value="LessThanSize"/>
+    <enumeration value="BodyAndAttachments"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="automaticUpdate">
+   <restriction base="xsd:string">
+    <enumeration value="AlwaysOn"/>
+    <enumeration value="InHomeNetwork"/>
+    <enumeration value="NotEnabled"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="mmsCreationMode">
+   <restriction base="xsd:string">
+    <enumeration value="Restricted"/>
+    <enumeration value="Guided"/>
+    <enumeration value="Free"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="mmsImageSize">
+   <restriction base="xsd:string">
+    <enumeration value="Small"/>
+    <enumeration value="Large"/>
+    <enumeration value="Original"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="mmsReception">
+   <restriction base="xsd:string">
+    <enumeration value="AlwaysAutomatic"/>
+    <enumeration value="AutomaticInHomeNetwork"/>
+    <enumeration value="AlwaysManual"/>
+    <enumeration value="Disabled"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="msgValidity">
+   <restriction base="xsd:string">
+    <enumeration value="Maximum"/>
+    <enumeration value="OneHour"/>
+    <enumeration value="SixHours"/>
+    <enumeration value="TwentyFourHours"/>
+    <enumeration value="ThreeDays"/>
+    <enumeration value="OneWeek"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="smsCharacterSupport">
+   <restriction base="xsd:string">
+    <enumeration value="Full"/>
+    <enumeration value="Reduced"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="smsMessageConversion">
+   <restriction base="xsd:string">
+    <enumeration value="None"/>
+    <enumeration value="Fax"/>
+    <enumeration value="Paging"/>
+    <enumeration value="EMail"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="smsPreferredConnection">
+   <restriction base="xsd:string">
+    <enumeration value="GSM"/>
+    <enumeration value="PacketData"/>
+   </restriction>
+  </simpleType>
+  <complexType name="HtiAPSettingField">
+   <sequence>
+     <element name="fieldType" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="fieldData" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfHtiAPSettingField">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="HtiAPSettingField" type="ns1:HtiAPSettingField" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ns1:HtiAPSettingField[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <!-- operation request element -->
+  <element name="fromField" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="description" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="messageBody" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="isNewFlag" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="isUnreadFlag" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="folder" type="ns1:folder"/>
+  <!-- operation response element -->
+  <element name="messageId" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="attachmentPath" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="BIOmessageUID" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="type" type="ns1:messageType"/>
+  <!-- operation request element -->
+  <element name="bearer" type="ns1:bearerType"/>
+  <!-- operation request element -->
+  <element name="apName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="APSettings" type="ns1:ArrayOfHtiAPSettingField"/>
+  <!-- operation response element -->
+  <element name="apId" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="mailboxType" type="ns1:mailboxType"/>
+  <!-- operation request element -->
+  <element name="mailboxName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="incomingServer" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="incomingAccessPoint" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="incomingUsername" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="incomingPassword" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="incomingSecurity" type="ns1:securitySetting"/>
+  <!-- operation request element -->
+  <element name="incomingPort" type="xsd:unsignedShort"/>
+  <!-- operation request element -->
+  <element name="aPopSecureLogin" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="outgoingServer" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="outgoingAccessPoint" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="outgoingUsername" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="outgoingPassword" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="outgoingSecurity" type="ns1:securitySetting"/>
+  <!-- operation request element -->
+  <element name="outgoingPort" type="xsd:unsignedShort"/>
+  <!-- operation request element -->
+  <element name="ownMailAddress" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="ownName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="sendOption" type="ns1:sendOption"/>
+  <!-- operation request element -->
+  <element name="copyToOwnAddress" type="ns1:copyToOwn"/>
+  <!-- operation request element -->
+  <element name="signatureText" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="newMailIndicators" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="retrievedParts" type="ns1:retrievedParts"/>
+  <!-- operation request element -->
+  <element name="retrieveSizeLimit" type="xsd:unsignedShort"/>
+  <!-- operation request element -->
+  <element name="emailsToRetrieve" type="xsd:unsignedShort"/>
+  <!-- operation request element -->
+  <element name="imap4FolderPath" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="automaticUpdate" type="ns1:automaticUpdate"/>
+  <!-- operation request element -->
+  <element name="setAsDefault" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="smsCenterName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="smsCenterNumber" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="characterSupport" type="ns1:smsCharacterSupport"/>
+  <!-- operation request element -->
+  <element name="requestDeliveryReport" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="validityPeriod" type="ns1:msgValidity"/>
+  <!-- operation request element -->
+  <element name="messageConversion" type="ns1:smsMessageConversion"/>
+  <!-- operation request element -->
+  <element name="preferredConnection" type="ns1:smsPreferredConnection"/>
+  <!-- operation request element -->
+  <element name="replyViaSameCenter" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="accessPointName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="creationMode" type="ns1:mmsCreationMode"/>
+  <!-- operation request element -->
+  <element name="imageSize" type="ns1:mmsImageSize"/>
+  <!-- operation request element -->
+  <element name="reception" type="ns1:mmsReception"/>
+  <!-- operation request element -->
+  <element name="receiveAnonymous" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="receiveAdvertisements" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="requestDeliveryReports" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="sendDeliveryReports" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="destinationName" type="xsd:string"/>
+ </schema>
+
+</types>
+
+<message name="addSMSRequest">
+ <part name="fromField" element="ns1:fromField"/>
+ <part name="description" element="ns1:description"/>
+ <part name="messageBody" element="ns1:messageBody"/>
+ <part name="isNewFlag" element="ns1:isNewFlag"/>
+ <part name="isUnreadFlag" element="ns1:isUnreadFlag"/>
+ <part name="folder" element="ns1:folder"/>
+</message>
+
+<message name="addSMSResponse">
+ <part name="messageId" element="ns1:messageId"/>
+</message>
+
+<message name="addMMSRequest">
+ <part name="fromField" element="ns1:fromField"/>
+ <part name="description" element="ns1:description"/>
+ <part name="messageBody" element="ns1:messageBody"/>
+ <part name="attachmentPath" element="ns1:attachmentPath"/>
+ <part name="isNewFlag" element="ns1:isNewFlag"/>
+ <part name="isUnreadFlag" element="ns1:isUnreadFlag"/>
+ <part name="folder" element="ns1:folder"/>
+</message>
+
+<message name="addMMSResponse">
+ <part name="messageId" element="ns1:messageId"/>
+</message>
+
+<message name="addEMailRequest">
+ <part name="fromField" element="ns1:fromField"/>
+ <part name="description" element="ns1:description"/>
+ <part name="messageBody" element="ns1:messageBody"/>
+ <part name="attachmentPath" element="ns1:attachmentPath"/>
+ <part name="isNewFlag" element="ns1:isNewFlag"/>
+ <part name="isUnreadFlag" element="ns1:isUnreadFlag"/>
+ <part name="folder" element="ns1:folder"/>
+</message>
+
+<message name="addEMailResponse">
+ <part name="messageId" element="ns1:messageId"/>
+</message>
+
+<message name="addIRMessageRequest">
+ <part name="fromField" element="ns1:fromField"/>
+ <part name="description" element="ns1:description"/>
+ <part name="attachmentPath" element="ns1:attachmentPath"/>
+ <part name="isNewFlag" element="ns1:isNewFlag"/>
+ <part name="isUnreadFlag" element="ns1:isUnreadFlag"/>
+ <part name="folder" element="ns1:folder"/>
+</message>
+
+<message name="addIRMessageResponse">
+ <part name="messageId" element="ns1:messageId"/>
+</message>
+
+<message name="addBTMessageRequest">
+ <part name="fromField" element="ns1:fromField"/>
+ <part name="description" element="ns1:description"/>
+ <part name="attachmentPath" element="ns1:attachmentPath"/>
+ <part name="isNewFlag" element="ns1:isNewFlag"/>
+ <part name="isUnreadFlag" element="ns1:isUnreadFlag"/>
+ <part name="folder" element="ns1:folder"/>
+</message>
+
+<message name="addBTMessageResponse">
+ <part name="messageId" element="ns1:messageId"/>
+</message>
+
+<message name="addSmartMessageRequest">
+ <part name="fromField" element="ns1:fromField"/>
+ <part name="description" element="ns1:description"/>
+ <part name="messageBody" element="ns1:messageBody"/>
+ <part name="isNewFlag" element="ns1:isNewFlag"/>
+ <part name="isUnreadFlag" element="ns1:isUnreadFlag"/>
+ <part name="folder" element="ns1:folder"/>
+ <part name="BIOmessageUID" element="ns1:BIOmessageUID"/>
+</message>
+
+<message name="addSmartMessageResponse">
+ <part name="messageId" element="ns1:messageId"/>
+</message>
+
+<message name="addAudioMessageRequest">
+ <part name="fromField" element="ns1:fromField"/>
+ <part name="description" element="ns1:description"/>
+ <part name="attachmentPath" element="ns1:attachmentPath"/>
+ <part name="isNewFlag" element="ns1:isNewFlag"/>
+ <part name="isUnreadFlag" element="ns1:isUnreadFlag"/>
+ <part name="folder" element="ns1:folder"/>
+</message>
+
+<message name="addAudioMessageResponse">
+ <part name="messageId" element="ns1:messageId"/>
+</message>
+
+<message name="deleteMessage">
+ <part name="messageId" element="ns1:messageId"/>
+</message>
+
+<message name="deleteMessageResponse">
+</message>
+
+<message name="deleteAllFromFolder">
+ <part name="type" element="ns1:type"/>
+ <part name="folder" element="ns1:folder"/>
+</message>
+
+<message name="deleteAllFromFolderResponse">
+</message>
+
+<message name="createAccessPointRequest">
+ <part name="bearer" element="ns1:bearer"/>
+ <part name="apName" element="ns1:apName"/>
+ <part name="APSettings" element="ns1:APSettings"/>
+</message>
+
+<message name="createAccessPointResponse">
+ <part name="apId" element="ns1:apId"/>
+</message>
+
+<message name="deleteAccessPoint">
+ <part name="apName" element="ns1:apName"/>
+</message>
+
+<message name="deleteAccessPointResponse">
+</message>
+
+<message name="createMailbox">
+ <part name="mailboxType" element="ns1:mailboxType"/>
+ <part name="mailboxName" element="ns1:mailboxName"/>
+ <part name="incomingServer" element="ns1:incomingServer"/>
+ <part name="incomingAccessPoint" element="ns1:incomingAccessPoint"/>
+ <part name="incomingUsername" element="ns1:incomingUsername"/>
+ <part name="incomingPassword" element="ns1:incomingPassword"/>
+ <part name="incomingSecurity" element="ns1:incomingSecurity"/>
+ <part name="incomingPort" element="ns1:incomingPort"/>
+ <part name="aPopSecureLogin" element="ns1:aPopSecureLogin"/>
+ <part name="outgoingServer" element="ns1:outgoingServer"/>
+ <part name="outgoingAccessPoint" element="ns1:outgoingAccessPoint"/>
+ <part name="outgoingUsername" element="ns1:outgoingUsername"/>
+ <part name="outgoingPassword" element="ns1:outgoingPassword"/>
+ <part name="outgoingSecurity" element="ns1:outgoingSecurity"/>
+ <part name="outgoingPort" element="ns1:outgoingPort"/>
+ <part name="ownMailAddress" element="ns1:ownMailAddress"/>
+ <part name="ownName" element="ns1:ownName"/>
+ <part name="sendOption" element="ns1:sendOption"/>
+ <part name="copyToOwnAddress" element="ns1:copyToOwnAddress"/>
+ <part name="signatureText" element="ns1:signatureText"/>
+ <part name="newMailIndicators" element="ns1:newMailIndicators"/>
+ <part name="retrievedParts" element="ns1:retrievedParts"/>
+ <part name="retrieveSizeLimit" element="ns1:retrieveSizeLimit"/>
+ <part name="emailsToRetrieve" element="ns1:emailsToRetrieve"/>
+ <part name="imap4FolderPath" element="ns1:imap4FolderPath"/>
+ <part name="automaticUpdate" element="ns1:automaticUpdate"/>
+ <part name="setAsDefault" element="ns1:setAsDefault"/>
+</message>
+
+<message name="createMailboxResponse">
+</message>
+
+<message name="deleteMailbox">
+ <part name="mailboxName" element="ns1:mailboxName"/>
+</message>
+
+<message name="deleteMailboxResponse">
+</message>
+
+<message name="setDefaultSmsCenter">
+ <part name="smsCenterName" element="ns1:smsCenterName"/>
+ <part name="smsCenterNumber" element="ns1:smsCenterNumber"/>
+</message>
+
+<message name="setDefaultSmsCenterResponse">
+</message>
+
+<message name="deleteSmsCenter">
+ <part name="smsCenterName" element="ns1:smsCenterName"/>
+</message>
+
+<message name="deleteSmsCenterResponse">
+</message>
+
+<message name="setSmsSettings">
+ <part name="characterSupport" element="ns1:characterSupport"/>
+ <part name="requestDeliveryReport" element="ns1:requestDeliveryReport"/>
+ <part name="validityPeriod" element="ns1:validityPeriod"/>
+ <part name="messageConversion" element="ns1:messageConversion"/>
+ <part name="preferredConnection" element="ns1:preferredConnection"/>
+ <part name="replyViaSameCenter" element="ns1:replyViaSameCenter"/>
+</message>
+
+<message name="setSmsSettingsResponse">
+</message>
+
+<message name="setMmsSettings">
+ <part name="accessPointName" element="ns1:accessPointName"/>
+ <part name="creationMode" element="ns1:creationMode"/>
+ <part name="imageSize" element="ns1:imageSize"/>
+ <part name="reception" element="ns1:reception"/>
+ <part name="receiveAnonymous" element="ns1:receiveAnonymous"/>
+ <part name="receiveAdvertisements" element="ns1:receiveAdvertisements"/>
+ <part name="requestDeliveryReports" element="ns1:requestDeliveryReports"/>
+ <part name="sendDeliveryReports" element="ns1:sendDeliveryReports"/>
+ <part name="validityPeriod" element="ns1:validityPeriod"/>
+</message>
+
+<message name="setMmsSettingsResponse">
+</message>
+
+<message name="createDestination">
+ <part name="destinationName" element="ns1:destinationName"/>
+</message>
+
+<message name="createDestinationResponse">
+</message>
+
+<message name="deleteDestination">
+ <part name="destinationName" element="ns1:destinationName"/>
+</message>
+
+<message name="deleteDestinationResponse">
+</message>
+
+<message name="addToDestination">
+ <part name="accessPointName" element="ns1:accessPointName"/>
+ <part name="destinationName" element="ns1:destinationName"/>
+</message>
+
+<message name="addToDestinationResponse">
+</message>
+
+<message name="removeFromDestination">
+ <part name="accessPointName" element="ns1:accessPointName"/>
+ <part name="destinationName" element="ns1:destinationName"/>
+</message>
+
+<message name="removeFromDestinationResponse">
+</message>
+
+<portType name="HtiMessagesPortType">
+ <operation name="addSMS">
+  <documentation>Service definition of function ns1__addSMS</documentation>
+  <input message="tns:addSMSRequest"/>
+  <output message="tns:addSMSResponse"/>
+ </operation>
+ <operation name="addMMS">
+  <documentation>Service definition of function ns1__addMMS</documentation>
+  <input message="tns:addMMSRequest"/>
+  <output message="tns:addMMSResponse"/>
+ </operation>
+ <operation name="addEMail">
+  <documentation>Service definition of function ns1__addEMail</documentation>
+  <input message="tns:addEMailRequest"/>
+  <output message="tns:addEMailResponse"/>
+ </operation>
+ <operation name="addIRMessage">
+  <documentation>Service definition of function ns1__addIRMessage</documentation>
+  <input message="tns:addIRMessageRequest"/>
+  <output message="tns:addIRMessageResponse"/>
+ </operation>
+ <operation name="addBTMessage">
+  <documentation>Service definition of function ns1__addBTMessage</documentation>
+  <input message="tns:addBTMessageRequest"/>
+  <output message="tns:addBTMessageResponse"/>
+ </operation>
+ <operation name="addSmartMessage">
+  <documentation>Service definition of function ns1__addSmartMessage</documentation>
+  <input message="tns:addSmartMessageRequest"/>
+  <output message="tns:addSmartMessageResponse"/>
+ </operation>
+ <operation name="addAudioMessage">
+  <documentation>Service definition of function ns1__addAudioMessage</documentation>
+  <input message="tns:addAudioMessageRequest"/>
+  <output message="tns:addAudioMessageResponse"/>
+ </operation>
+ <operation name="deleteMessage">
+  <documentation>Service definition of function ns1__deleteMessage</documentation>
+  <input message="tns:deleteMessage"/>
+  <output message="tns:deleteMessageResponse"/>
+ </operation>
+ <operation name="deleteAllFromFolder">
+  <documentation>Service definition of function ns1__deleteAllFromFolder</documentation>
+  <input message="tns:deleteAllFromFolder"/>
+  <output message="tns:deleteAllFromFolderResponse"/>
+ </operation>
+ <operation name="createAccessPoint">
+  <documentation>Service definition of function ns1__createAccessPoint</documentation>
+  <input message="tns:createAccessPointRequest"/>
+  <output message="tns:createAccessPointResponse"/>
+ </operation>
+ <operation name="deleteAccessPoint">
+  <documentation>Service definition of function ns1__deleteAccessPoint</documentation>
+  <input message="tns:deleteAccessPoint"/>
+  <output message="tns:deleteAccessPointResponse"/>
+ </operation>
+ <operation name="createMailbox">
+  <documentation>Service definition of function ns1__createMailbox</documentation>
+  <input message="tns:createMailbox"/>
+  <output message="tns:createMailboxResponse"/>
+ </operation>
+ <operation name="deleteMailbox">
+  <documentation>Service definition of function ns1__deleteMailbox</documentation>
+  <input message="tns:deleteMailbox"/>
+  <output message="tns:deleteMailboxResponse"/>
+ </operation>
+ <operation name="setDefaultSmsCenter">
+  <documentation>Service definition of function ns1__setDefaultSmsCenter</documentation>
+  <input message="tns:setDefaultSmsCenter"/>
+  <output message="tns:setDefaultSmsCenterResponse"/>
+ </operation>
+ <operation name="deleteSmsCenter">
+  <documentation>Service definition of function ns1__deleteSmsCenter</documentation>
+  <input message="tns:deleteSmsCenter"/>
+  <output message="tns:deleteSmsCenterResponse"/>
+ </operation>
+ <operation name="setSmsSettings">
+  <documentation>Service definition of function ns1__setSmsSettings</documentation>
+  <input message="tns:setSmsSettings"/>
+  <output message="tns:setSmsSettingsResponse"/>
+ </operation>
+ <operation name="setMmsSettings">
+  <documentation>Service definition of function ns1__setMmsSettings</documentation>
+  <input message="tns:setMmsSettings"/>
+  <output message="tns:setMmsSettingsResponse"/>
+ </operation>
+ <operation name="createDestination">
+  <documentation>Service definition of function ns1__createDestination</documentation>
+  <input message="tns:createDestination"/>
+  <output message="tns:createDestinationResponse"/>
+ </operation>
+ <operation name="deleteDestination">
+  <documentation>Service definition of function ns1__deleteDestination</documentation>
+  <input message="tns:deleteDestination"/>
+  <output message="tns:deleteDestinationResponse"/>
+ </operation>
+ <operation name="addToDestination">
+  <documentation>Service definition of function ns1__addToDestination</documentation>
+  <input message="tns:addToDestination"/>
+  <output message="tns:addToDestinationResponse"/>
+ </operation>
+ <operation name="removeFromDestination">
+  <documentation>Service definition of function ns1__removeFromDestination</documentation>
+  <input message="tns:removeFromDestination"/>
+  <output message="tns:removeFromDestinationResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiMessages" type="tns:HtiMessagesPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="addSMS">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="addMMS">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="addEMail">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="addIRMessage">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="addBTMessage">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="addSmartMessage">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="addAudioMessage">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteMessage">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteAllFromFolder">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="createAccessPoint">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteAccessPoint">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="createMailbox">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteMailbox">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setDefaultSmsCenter">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteSmsCenter">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setSmsSettings">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setMmsSettings">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="createDestination">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteDestination">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="addToDestination">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="removeFromDestination">
+  <SOAP:operation style="rpc" soapAction="HtiMessages"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiMessages">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiMessages" binding="tns:HtiMessages">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiMessages/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+#include "HtiMessages.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+//additional export functions requried for an hti-plugin
+#define HTI_SOAP_ACTION "HtiMessages"
+#define HTI_UID 0x10210CCF
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPIM.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,413 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiPIMH.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+
+//**********************************************************************************
+// CONSTANTS
+//
+//**********************************************************************************
+
+// commands
+const unsigned char CMD_IMPORT_VCARD               = 0x01;
+const unsigned char CMD_IMPORT_VCALENDAR           = 0x02;
+const unsigned char CMD_DELETE_CONTACT_ENTRIES     = 0x03;
+const unsigned char CMD_DELETE_CALENDAR_ENTRIES    = 0x04;
+const unsigned char CMD_NOTEPAD_ADD_MEMO           = 0x05;
+const unsigned char CMD_NOTEPAD_ADD_MEMO_FROM_FILE = 0x06;
+const unsigned char CMD_NOTEPAD_DELETE_ALL         = 0x07;
+const unsigned char CMD_SIM_CARD_INFORMATION	   = 0x10;
+const unsigned char CMD_IMPORT_SIM_CONTACT	       = 0x11;
+const unsigned char CMD_DELETE_SIM_CONTACT	       = 0x12;
+const unsigned char CMD_CREATE_BOOKMARK	           = 0x1A;
+const unsigned char CMD_DELETE_BOOKMARK	           = 0x1B;
+
+
+//**********************************************************************************
+// UTIL FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// GetSoapDIMEAttachment
+//**********************************************************************************
+int GetSoapDIMEAttachment(struct soap* soap,
+					      char* href,
+					      void*& data,
+					      int &dataLen )
+{
+	struct soap_multipart *attachment;
+	for ( attachment = soap->dime.list; attachment; attachment = attachment->next )
+	{
+		if( !strcmp( (*attachment).id, href ) )
+		{
+			data = attachment->ptr,
+			dataLen = (int) (*attachment).size;
+			return SOAP_OK;
+		}
+	}
+
+	soap->error = soap_receiver_fault_format(soap, "HtiGateway", 
+		"Did not find DIME attachment \"%s\"", href);
+	return SOAP_FAULT;
+}
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// ns1__import_vCard
+//**********************************************************************************
+int ns1__import_vCard(struct soap* soap,
+					  char *vCard,
+					  int &entryId)
+{
+	if(check_mandatory_string_parameter(soap, vCard, "vCard"))
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_UID, CMD_IMPORT_VCARD );
+	msg.AddString( vCard );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckMsgExactLen( 5 ) || msg.CheckCommandCode( 0xFF ) )
+		return SOAP_FAULT;
+
+	entryId = msg.GetInt( 1 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__import_vCardDime
+//**********************************************************************************
+int ns1__import_vCardDime(struct soap* soap,
+                          struct ns1__HtiSoapAttachment *vCardDimeAttachment,
+						  int &entryId)
+{
+	if( check_mandatory_string_parameter( soap, vCardDimeAttachment->href, 
+		                                  "vCardDimeAttachment href" ) )
+		return SOAP_FAULT;
+
+	void* data = NULL;
+	int dataLen = 0;
+	if ( GetSoapDIMEAttachment( soap, vCardDimeAttachment->href, data, dataLen ) )
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_UID, CMD_IMPORT_VCARD );
+	msg.AddData( data, dataLen );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckMsgExactLen( 5 ) || msg.CheckCommandCode( 0xFF ) )
+		return SOAP_FAULT;
+
+	entryId = msg.GetInt( 1 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__import_vCalendar
+//**********************************************************************************
+int ns1__import_vCalendar(struct soap* soap,
+						  char *vCal, 
+						  int &entryId)
+{
+	if(check_mandatory_string_parameter(soap, vCal, "vCalendar"))
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_UID, CMD_IMPORT_VCALENDAR );
+	msg.AddString( vCal );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckMsgExactLen( 5 ) || msg.CheckCommandCode( 0xFF ) )
+		return SOAP_FAULT;
+
+	entryId = msg.GetInt( 1 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__import_vCalendarDime
+//**********************************************************************************
+int ns1__import_vCalendarDime(struct soap* soap,
+                              struct ns1__HtiSoapAttachment *vCalendarDimeAttachment,
+							  int &entryId)
+{
+	if(check_mandatory_string_parameter(soap, vCalendarDimeAttachment->href, 
+		                                "vCalendarDimeAttachment href"))
+		return SOAP_FAULT;
+
+	void* data = NULL;
+	int dataLen = 0;
+	if ( GetSoapDIMEAttachment( soap, vCalendarDimeAttachment->href, data, dataLen ) )
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_UID, CMD_IMPORT_VCALENDAR );
+	msg.AddData( data, dataLen );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckMsgExactLen( 5 ) || msg.CheckCommandCode( 0xFF ) )
+		return SOAP_FAULT;
+
+	entryId = msg.GetInt( 1 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__deleteContactEntry
+//**********************************************************************************
+int ns1__deleteContactEntry(struct soap* soap,
+							int entryId,
+                            struct ns1__deleteContactEntryResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_CONTACT_ENTRIES );
+	msg.AddInt( entryId );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__deleteAllContactEntries
+//**********************************************************************************
+int ns1__deleteAllContactEntries(struct soap* soap,
+								 void *_,
+                                 struct ns1__deleteAllContactEntriesResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_CONTACT_ENTRIES );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__deleteCalendarEntry
+//**********************************************************************************
+int ns1__deleteCalendarEntry(struct soap* soap,
+							 int entryId,
+                             struct ns1__deleteCalendarEntryResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_CALENDAR_ENTRIES );
+	msg.AddInt( entryId );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__deleteAllCalendarEntries
+//**********************************************************************************
+int ns1__deleteAllCalendarEntries(struct soap* soap,
+								  void *_,
+                                  struct ns1__deleteAllCalendarEntriesResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_CALENDAR_ENTRIES );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__getSIMCardCaps
+//**********************************************************************************
+int ns1__getSIMCardCaps(struct soap* soap,
+						void *_,
+                        struct ns1__getSIMCardCapsResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SIM_CARD_INFORMATION );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+	
+	if ( msg.CheckCommandCode( 0xFF ) || msg.CheckMsgExactLen( 13 ) )
+		return SOAP_FAULT;
+
+	r._returnHtiSIMCardCaps.maxNumOfSecondNames			= msg.GetByte( 1 );
+	r._returnHtiSIMCardCaps.maxNumOfAdditionalNums		= msg.GetByte( 2 );
+	r._returnHtiSIMCardCaps.maxNumOfEmails				= msg.GetByte( 3 );
+	r._returnHtiSIMCardCaps.maxLengthOfName				= msg.GetByte( 4 );
+	r._returnHtiSIMCardCaps.maxLengthOfNumber			= msg.GetByte( 5 );
+	r._returnHtiSIMCardCaps.maxLengthOfSecondName		= msg.GetByte( 6 );
+	r._returnHtiSIMCardCaps.maxLengthOfAdditionalNum	= msg.GetByte( 7 );
+	r._returnHtiSIMCardCaps.maxLenghtOfEmail			= msg.GetByte( 8 );
+	r._returnHtiSIMCardCaps.totalSlots					= msg.GetWord( 9 );
+	r._returnHtiSIMCardCaps.usedSlots					= msg.GetWord( 11 );
+	
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__importSIMContact
+//**********************************************************************************
+int ns1__importSIMContact(struct soap* soap,
+                          struct ArrayOfHtiSIMContactFields SIMContacts,
+						  int &entryId)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_IMPORT_SIM_CONTACT );
+
+	// Only one byte for number of contacts
+	if ( SIMContacts.__size > 0xFF )
+	{
+		soap->error = soap_receiver_fault( soap, "HtiGateway", 
+			"Too many contacts" );
+		return SOAP_FAULT;
+	}
+	msg.AddByte( (BYTE) SIMContacts.__size );
+
+	// Loop through contacts
+	for ( int i = 0; i < SIMContacts.__size; i++ )
+	{
+		msg.AddByte( SIMContacts.__ptrHtiSIMContactField[i].fieldType );
+		
+		// fieldData cannot be empty
+		if ( check_mandatory_string_parameter( soap, 
+			   SIMContacts.__ptrHtiSIMContactField[i].fieldData,
+			   "HtiSIMContactField.fieldData" ) )
+			   return SOAP_FAULT;
+		
+		msg.AddStringWithLengthByte( SIMContacts.__ptrHtiSIMContactField[i].fieldData );
+	}
+
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckCommandCode( 0xFF ) || msg.CheckMsgExactLen( 5 ) )
+		return SOAP_FAULT;
+
+	entryId = msg.GetInt( 1 );
+
+    return SOAP_OK;	
+}
+
+//**********************************************************************************
+// ns1__deleteSIMContact
+//**********************************************************************************
+int ns1__deleteSIMContact(struct soap* soap,
+						  int entryId,
+                          struct ns1__deleteSIMContactResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_SIM_CONTACT );
+	msg.AddInt( entryId );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__deleteAllSIMContacts
+//**********************************************************************************
+int ns1__deleteAllSIMContacts(struct soap* soap,
+							  void *_,
+                              struct ns1__deleteAllSIMContactsResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_SIM_CONTACT );
+	// 60 second timeout maybe not enough(?)
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_60_SECONDS ); 
+}
+
+//**********************************************************************************
+// ns1__notepadAddMemo
+//**********************************************************************************
+int ns1__notepadAddMemo(struct soap* soap,
+						char *text,
+                        struct ns1__notepadAddMemoResponse *out)
+{
+	if( check_mandatory_string_parameter( soap, text, "text" ) )
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_UID, CMD_NOTEPAD_ADD_MEMO );
+	msg.AddString( text );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+//**********************************************************************************
+// ns1__notepadAddMemoFromFile
+//**********************************************************************************
+int ns1__notepadAddMemoFromFile(struct soap* soap,
+						        char *filePath,
+                                struct ns1__notepadAddMemoFromFileResponse *out)
+{
+	if( check_mandatory_string_parameter( soap, filePath, "filePath" ) )
+		return SOAP_FAULT;
+	
+	HtiMsgHelper msg( soap, HTI_UID, CMD_NOTEPAD_ADD_MEMO_FROM_FILE );
+	msg.AddString( filePath );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__notepadDeleteAll
+//**********************************************************************************
+int ns1__notepadDeleteAll(struct soap* soap,
+						  void *_,
+                          struct ns1__notepadDeleteAllResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_NOTEPAD_DELETE_ALL );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__createBookmark
+//**********************************************************************************
+int ns1__createBookmark(struct soap* soap,
+					    char *folderName,
+                        char *bookmarkName,
+                        char *url,
+                        char *accessPointName,
+                        char *userName,
+                        char *password,
+                        int  &createdItemCount)
+{
+    if( check_mandatory_string_parameter( soap, bookmarkName, "bookmarkName" ) )
+		return SOAP_FAULT;
+    if( check_mandatory_string_parameter( soap, url, "url" ) )
+		return SOAP_FAULT;
+
+    HtiMsgHelper msg( soap, HTI_UID, CMD_CREATE_BOOKMARK );
+    msg.AddStringWithLengthByteZero( folderName );
+    msg.AddStringWithLengthByte( bookmarkName );
+    msg.AddStringWithLengthWordZero( url );
+    msg.AddStringWithLengthByteZero( accessPointName );
+    msg.AddStringWithLengthByteZero( userName );
+    msg.AddStringWithLengthByteZero( password );
+
+ 	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+    if ( msg.CheckCommandCode( 0xFF ) || msg.CheckMsgExactLen( 2 ) )
+        return SOAP_FAULT;
+
+    createdItemCount = msg.GetByte( 1 );
+
+	return SOAP_OK;
+}
+//**********************************************************************************
+// ns1__deleteBookmark
+//**********************************************************************************
+int ns1__deleteBookmark(struct soap* soap,
+					    char *folderName,
+                        char *bookmarkName,
+                        int  &deletedItemCount)
+{
+    HtiMsgHelper msg( soap, HTI_UID, CMD_DELETE_BOOKMARK );
+    msg.AddStringWithLengthByteZero( folderName );
+    msg.AddStringWithLengthByteZero( bookmarkName );
+
+ 	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+    if ( msg.CheckCommandCode( 0xFF ) || msg.CheckMsgExactLen( 2 ) )
+        return SOAP_FAULT;
+
+    deletedItemCount = msg.GetByte( 1 );
+
+	return SOAP_OK;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPIM.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,165 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiPIM
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char*			xsd__string;
+typedef wchar_t*		_xsd__string;
+typedef int				xsd__int;
+typedef unsigned char	xsd__unsignedByte;
+typedef unsigned short	xsd__unsignedShort;
+
+struct ns1__HtiSoapAttachment
+{
+	xsd__string href;
+	xsd__string mimeType;
+};
+
+enum SIMContactFieldType
+{
+	FieldTypeName = 1,
+	FieldTypeSecondName,
+	FieldTypeNumber,
+	FieldTypeEmail,
+	FieldTypeAdditionalNumber
+};
+
+struct ns1__HtiSIMContactField
+{
+	enum SIMContactFieldType	fieldType;
+	xsd__string					fieldData;
+};
+
+struct ArrayOfHtiSIMContactFields
+{
+	struct ns1__HtiSIMContactField* __ptrHtiSIMContactField;
+	int __size;
+};
+
+struct ns1__HtiSIMCardCaps
+{
+	xsd__unsignedByte	maxNumOfSecondNames;
+	xsd__unsignedByte	maxNumOfAdditionalNums;
+	xsd__unsignedByte	maxNumOfEmails;
+	xsd__unsignedByte	maxLengthOfName;
+	xsd__unsignedByte	maxLengthOfNumber;
+	xsd__unsignedByte	maxLengthOfSecondName;
+	xsd__unsignedByte	maxLengthOfAdditionalNum;
+	xsd__unsignedByte	maxLenghtOfEmail;
+	xsd__unsignedShort	totalSlots;
+	xsd__unsignedShort	usedSlots;
+};
+
+
+// String versions
+//gsoap ns1 service method-action: import_vCard "HtiPIM"
+int ns1__import_vCard(
+    xsd__string		vCard,
+    xsd__int		&entryId
+);
+//gsoap ns1 service method-action: import_vCalendar "HtiPIM"
+int ns1__import_vCalendar(
+    xsd__string		vCal,
+    xsd__int		&entryId
+);
+// DIME versions
+//gsoap ns1 service method-action: import_vCardDime "HtiPIM"
+int ns1__import_vCardDime(
+    struct ns1__HtiSoapAttachment		*vCardDimeAttachment,
+    xsd__int							&entryId
+);
+//gsoap ns1 service method-action: import_vCalendarDime "HtiPIM"
+int ns1__import_vCalendarDime(
+    struct ns1__HtiSoapAttachment		*vCalendarDimeAttachment,
+    xsd__int							&entryId
+);
+
+//gsoap ns1 service method-action: deleteContactEntry "HtiPIM"
+int ns1__deleteContactEntry(
+    xsd__int		entryId,
+    struct ns1__deleteContactEntryResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: deleteAllContactEntries "HtiPIM"
+int ns1__deleteAllContactEntries(
+    void *_, // no 'in' parameter
+    struct ns1__deleteAllContactEntriesResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: deleteCalendarEntry "HtiPIM"
+int ns1__deleteCalendarEntry(
+    xsd__int		entryId,
+    struct ns1__deleteCalendarEntryResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: deleteAllCalendarEntries "HtiPIM"
+int ns1__deleteAllCalendarEntries(
+    void *_, // no 'in' parameter
+    struct ns1__deleteAllCalendarEntriesResponse{} *out // empty response
+);
+struct ns1__getSIMCardCapsResponse { struct ns1__HtiSIMCardCaps _returnHtiSIMCardCaps; };
+//gsoap ns1 service method-action: getSIMCardCaps "HtiPIM"
+int ns1__getSIMCardCaps(
+    void *_, // no 'in' parameter
+    struct ns1__getSIMCardCapsResponse &r
+);
+//gsoap ns1 service method-action: importSIMContact "HtiPIM"
+int ns1__importSIMContact(
+    struct ArrayOfHtiSIMContactFields 	SIMContact,
+    xsd__int							&entryId
+);
+//gsoap ns1 service method-action: deleteSIMContact "HtiPIM"
+int ns1__deleteSIMContact(
+    xsd__int	entryId,
+	struct ns1__deleteSIMContactResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: deleteAllSIMContacts "HtiPIM"
+int ns1__deleteAllSIMContacts(
+    void *_, // no 'in' parameter
+	struct ns1__deleteAllSIMContactsResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: notepadAddMemo "HtiPIM"
+int ns1__notepadAddMemo(
+    xsd__string		text,
+    struct ns1__notepadAddMemoResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: notepadAddMemoFromFile "HtiPIM"
+int ns1__notepadAddMemoFromFile(
+    xsd__string		filePath,
+    struct ns1__notepadAddMemoFromFileResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: notepadDeleteAll "HtiPIM"
+int ns1__notepadDeleteAll(
+    void *_, // no 'in' parameter
+    struct ns1__notepadDeleteAllResponse{} *out // empty response
+);
+//gsoap ns1 service method-action: createBookmark "HtiPIM"
+int ns1__createBookmark(
+    xsd__string folderName,
+    xsd__string bookmarkName,
+    xsd__string url,
+    xsd__string accessPointName,
+    xsd__string userName,
+    xsd__string password,
+    xsd__int    &createdItemCount
+);
+//gsoap ns1 service method-action: deleteBookmark "HtiPIM"
+int ns1__deleteBookmark(
+    xsd__string folderName,
+    xsd__string bookmarkName,
+    xsd__int    &deletedItemCount
+);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPIM.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,250 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiPIM"
+	ProjectGUID="{3BEB953A-E3DA-440A-8E1C-C5AE8D376E85}"
+	RootNamespace="HtiPIM"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiPIM.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPIMServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiPIM.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiPIM.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPIMH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPIMStub.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPIM.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,491 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiPIM"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <simpleType name="SIMContactFieldType">
+   <restriction base="xsd:string">
+    <enumeration value="FieldTypeName"/>
+    <enumeration value="FieldTypeSecondName"/>
+    <enumeration value="FieldTypeNumber"/>
+    <enumeration value="FieldTypeEmail"/>
+    <enumeration value="FieldTypeAdditionalNumber"/>
+   </restriction>
+  </simpleType>
+  <complexType name="HtiSoapAttachment">
+   <sequence>
+     <element name="href" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="mimeType" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="HtiSIMContactField">
+   <sequence>
+     <element name="fieldType" type="ns1:SIMContactFieldType" minOccurs="1" maxOccurs="1"/>
+     <element name="fieldData" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfHtiSIMContactField">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="HtiSIMContactField" type="ns1:HtiSIMContactField" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ns1:HtiSIMContactField[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <complexType name="HtiSIMCardCaps">
+   <sequence>
+     <element name="maxNumOfSecondNames" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="maxNumOfAdditionalNums" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="maxNumOfEmails" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="maxLengthOfName" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="maxLengthOfNumber" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="maxLengthOfSecondName" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="maxLengthOfAdditionalNum" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="maxLenghtOfEmail" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="totalSlots" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="usedSlots" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <!-- operation request element -->
+  <element name="vCard" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="entryId" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="vCal" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="vCardDimeAttachment" type="ns1:HtiSoapAttachment"/>
+  <!-- operation request element -->
+  <element name="vCalendarDimeAttachment" type="ns1:HtiSoapAttachment"/>
+  <!-- operation response element -->
+  <element name="returnHtiSIMCardCaps" type="ns1:HtiSIMCardCaps"/>
+  <!-- operation request element -->
+  <element name="SIMContact" type="ns1:ArrayOfHtiSIMContactField"/>
+  <!-- operation request element -->
+  <element name="text" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="filePath" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="folderName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="bookmarkName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="url" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="accessPointName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="userName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="password" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="createdItemCount" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="deletedItemCount" type="xsd:int"/>
+ </schema>
+
+</types>
+
+<message name="import-vCardRequest">
+ <part name="vCard" element="ns1:vCard"/>
+</message>
+
+<message name="import-vCardResponse">
+ <part name="entryId" element="ns1:entryId"/>
+</message>
+
+<message name="import-vCalendarRequest">
+ <part name="vCal" element="ns1:vCal"/>
+</message>
+
+<message name="import-vCalendarResponse">
+ <part name="entryId" element="ns1:entryId"/>
+</message>
+
+<message name="import-vCardDimeRequest">
+ <part name="vCardDimeAttachment" element="ns1:vCardDimeAttachment"/>
+</message>
+
+<message name="import-vCardDimeResponse">
+ <part name="entryId" element="ns1:entryId"/>
+</message>
+
+<message name="import-vCalendarDimeRequest">
+ <part name="vCalendarDimeAttachment" element="ns1:vCalendarDimeAttachment"/>
+</message>
+
+<message name="import-vCalendarDimeResponse">
+ <part name="entryId" element="ns1:entryId"/>
+</message>
+
+<message name="deleteContactEntry">
+ <part name="entryId" element="ns1:entryId"/>
+</message>
+
+<message name="deleteContactEntryResponse">
+</message>
+
+<message name="deleteAllContactEntries">
+</message>
+
+<message name="deleteAllContactEntriesResponse">
+</message>
+
+<message name="deleteCalendarEntry">
+ <part name="entryId" element="ns1:entryId"/>
+</message>
+
+<message name="deleteCalendarEntryResponse">
+</message>
+
+<message name="deleteAllCalendarEntries">
+</message>
+
+<message name="deleteAllCalendarEntriesResponse">
+</message>
+
+<message name="getSIMCardCaps">
+</message>
+
+<message name="getSIMCardCapsResponse">
+ <part name="returnHtiSIMCardCaps" element="ns1:returnHtiSIMCardCaps"/>
+</message>
+
+<message name="importSIMContactRequest">
+ <part name="SIMContact" element="ns1:SIMContact"/>
+</message>
+
+<message name="importSIMContactResponse">
+ <part name="entryId" element="ns1:entryId"/>
+</message>
+
+<message name="deleteSIMContact">
+ <part name="entryId" element="ns1:entryId"/>
+</message>
+
+<message name="deleteSIMContactResponse">
+</message>
+
+<message name="deleteAllSIMContacts">
+</message>
+
+<message name="deleteAllSIMContactsResponse">
+</message>
+
+<message name="notepadAddMemo">
+ <part name="text" element="ns1:text"/>
+</message>
+
+<message name="notepadAddMemoResponse">
+</message>
+
+<message name="notepadAddMemoFromFile">
+ <part name="filePath" element="ns1:filePath"/>
+</message>
+
+<message name="notepadAddMemoFromFileResponse">
+</message>
+
+<message name="notepadDeleteAll">
+</message>
+
+<message name="notepadDeleteAllResponse">
+</message>
+
+<message name="createBookmarkRequest">
+ <part name="folderName" element="ns1:folderName"/>
+ <part name="bookmarkName" element="ns1:bookmarkName"/>
+ <part name="url" element="ns1:url"/>
+ <part name="accessPointName" element="ns1:accessPointName"/>
+ <part name="userName" element="ns1:userName"/>
+ <part name="password" element="ns1:password"/>
+</message>
+
+<message name="createBookmarkResponse">
+ <part name="createdItemCount" element="ns1:createdItemCount"/>
+</message>
+
+<message name="deleteBookmarkRequest">
+ <part name="folderName" element="ns1:folderName"/>
+ <part name="bookmarkName" element="ns1:bookmarkName"/>
+</message>
+
+<message name="deleteBookmarkResponse">
+ <part name="deletedItemCount" element="ns1:deletedItemCount"/>
+</message>
+
+<portType name="HtiPIMPortType">
+ <operation name="import-vCard">
+  <documentation>Service definition of function ns1__import_vCard</documentation>
+  <input message="tns:import-vCardRequest"/>
+  <output message="tns:import-vCardResponse"/>
+ </operation>
+ <operation name="import-vCalendar">
+  <documentation>Service definition of function ns1__import_vCalendar</documentation>
+  <input message="tns:import-vCalendarRequest"/>
+  <output message="tns:import-vCalendarResponse"/>
+ </operation>
+ <operation name="import-vCardDime">
+  <documentation>Service definition of function ns1__import_vCardDime</documentation>
+  <input message="tns:import-vCardDimeRequest"/>
+  <output message="tns:import-vCardDimeResponse"/>
+ </operation>
+ <operation name="import-vCalendarDime">
+  <documentation>Service definition of function ns1__import_vCalendarDime</documentation>
+  <input message="tns:import-vCalendarDimeRequest"/>
+  <output message="tns:import-vCalendarDimeResponse"/>
+ </operation>
+ <operation name="deleteContactEntry">
+  <documentation>Service definition of function ns1__deleteContactEntry</documentation>
+  <input message="tns:deleteContactEntry"/>
+  <output message="tns:deleteContactEntryResponse"/>
+ </operation>
+ <operation name="deleteAllContactEntries">
+  <documentation>Service definition of function ns1__deleteAllContactEntries</documentation>
+  <input message="tns:deleteAllContactEntries"/>
+  <output message="tns:deleteAllContactEntriesResponse"/>
+ </operation>
+ <operation name="deleteCalendarEntry">
+  <documentation>Service definition of function ns1__deleteCalendarEntry</documentation>
+  <input message="tns:deleteCalendarEntry"/>
+  <output message="tns:deleteCalendarEntryResponse"/>
+ </operation>
+ <operation name="deleteAllCalendarEntries">
+  <documentation>Service definition of function ns1__deleteAllCalendarEntries</documentation>
+  <input message="tns:deleteAllCalendarEntries"/>
+  <output message="tns:deleteAllCalendarEntriesResponse"/>
+ </operation>
+ <operation name="getSIMCardCaps">
+  <documentation>Service definition of function ns1__getSIMCardCaps</documentation>
+  <input message="tns:getSIMCardCaps"/>
+  <output message="tns:getSIMCardCapsResponse"/>
+ </operation>
+ <operation name="importSIMContact">
+  <documentation>Service definition of function ns1__importSIMContact</documentation>
+  <input message="tns:importSIMContactRequest"/>
+  <output message="tns:importSIMContactResponse"/>
+ </operation>
+ <operation name="deleteSIMContact">
+  <documentation>Service definition of function ns1__deleteSIMContact</documentation>
+  <input message="tns:deleteSIMContact"/>
+  <output message="tns:deleteSIMContactResponse"/>
+ </operation>
+ <operation name="deleteAllSIMContacts">
+  <documentation>Service definition of function ns1__deleteAllSIMContacts</documentation>
+  <input message="tns:deleteAllSIMContacts"/>
+  <output message="tns:deleteAllSIMContactsResponse"/>
+ </operation>
+ <operation name="notepadAddMemo">
+  <documentation>Service definition of function ns1__notepadAddMemo</documentation>
+  <input message="tns:notepadAddMemo"/>
+  <output message="tns:notepadAddMemoResponse"/>
+ </operation>
+ <operation name="notepadAddMemoFromFile">
+  <documentation>Service definition of function ns1__notepadAddMemoFromFile</documentation>
+  <input message="tns:notepadAddMemoFromFile"/>
+  <output message="tns:notepadAddMemoFromFileResponse"/>
+ </operation>
+ <operation name="notepadDeleteAll">
+  <documentation>Service definition of function ns1__notepadDeleteAll</documentation>
+  <input message="tns:notepadDeleteAll"/>
+  <output message="tns:notepadDeleteAllResponse"/>
+ </operation>
+ <operation name="createBookmark">
+  <documentation>Service definition of function ns1__createBookmark</documentation>
+  <input message="tns:createBookmarkRequest"/>
+  <output message="tns:createBookmarkResponse"/>
+ </operation>
+ <operation name="deleteBookmark">
+  <documentation>Service definition of function ns1__deleteBookmark</documentation>
+  <input message="tns:deleteBookmarkRequest"/>
+  <output message="tns:deleteBookmarkResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiPIM" type="tns:HtiPIMPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="import-vCard">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="import-vCalendar">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="import-vCardDime">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="import-vCalendarDime">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteContactEntry">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteAllContactEntries">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteCalendarEntry">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteAllCalendarEntries">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getSIMCardCaps">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="importSIMContact">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteSIMContact">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteAllSIMContacts">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="notepadAddMemo">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="notepadAddMemoFromFile">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="notepadDeleteAll">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="createBookmark">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deleteBookmark">
+  <SOAP:operation style="rpc" soapAction="HtiPIM"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiPIM">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiPIM" binding="tns:HtiPIM">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiPIM/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+#include "HtiPIM.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+//additional export functions requried for an hti-plugin
+#define HTI_SOAP_ACTION "HtiPIM"
+#define HTI_UID 0x10210CCD
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+#include "HtiScreenshot.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+//additional export functions requried for an hti-plugin
+#define HTI_SOAP_ACTION "HtiScreenshot"
+#define HTI_UID 0x1020DEC3
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiScreenshot.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,665 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiScreenshotH.h"
+
+#include "hticommon.h"
+#include "HtiPlugin.h"
+#include <string.h>
+
+#include "HtiSoapHandlerInterface.h"
+
+// Command codes
+const unsigned char CMD_SCR_FULL		= 0x01;
+const unsigned char CMD_SCR_REGION		= 0x02;
+const unsigned char CMD_SCR_FULL_ZIP	= 0x03;
+const unsigned char CMD_SCR_REGION_ZIP	= 0x04;
+
+const unsigned char CMD_TEXT_RCG_U		= 0x11;
+const unsigned char CMD_TEXT_IMG_U		= 0x13;
+
+const unsigned char CMD_SCR_FULL_SERIES	      = 0x21;
+const unsigned char CMD_SCR_REGION_SERIES	  = 0x22;
+const unsigned char CMD_SCR_FULL_ZIP_SERIES	  = 0x23;
+const unsigned char CMD_SCR_REGION_ZIP_SERIES = 0x24;
+
+const unsigned char CMD_CHANGE_SCREEN = 0x30;
+
+const unsigned char CMD_SCREEN_MODE = 0x3A;
+
+const unsigned char CMD_DELTA_SCR_FULL              = 0x81;
+const unsigned char CMD_DELTA_SCR_REGION            = 0x82;
+const unsigned char CMD_DELTA_SCR_FULL_ZIP          = 0x83;
+const unsigned char CMD_DELTA_SCR_REGION_ZIP        = 0x84;
+const unsigned char CMD_DELTA_SCR_RESET             = 0x85;
+const unsigned char CMD_DELTA_SCR_FULL_SERIES       = 0xA1;
+const unsigned char CMD_DELTA_SCR_REGION_SERIES     = 0xA2;
+const unsigned char CMD_DELTA_SCR_FULL_ZIP_SERIES   = 0xA3;
+const unsigned char CMD_DELTA_SCR_REGION_ZIP_SERIES = 0xA4;
+
+
+const unsigned char HTI_FONT_BOLD	= 0x01;
+const unsigned char HTI_FONT_ITALIC	= 0x02;
+const unsigned char HTI_FONT_NOTAA	= 0x04;
+const unsigned char HTI_FONT_SUPER	= 0x08;
+const unsigned char HTI_FONT_SUB	= 0x18;
+
+const unsigned char TXT_RCG_OK	= 0xF0;
+const unsigned char TXT_RCG_NOK	= 0xF1;
+
+const int MAX_HREF_LEN = 128;
+
+char zipMimeType[] = "application/octet-stream"; //??
+
+const static int g_ScreenHtiTimeoutImage = 120000;
+const static int g_ScreenHtiTimeoutRecongition = 60000;
+
+//**********************************************************************************
+// HELPER FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// AddHtiFont
+//**********************************************************************************
+void AddHtiFont(HtiMsgHelper &msg, struct ns1__HtiFont &font)
+{
+	msg.AddWCStringWithLengthByte( font.fontName );
+	msg.AddWord( font.fontHeight );
+
+	BYTE fontStyle = 0x0;
+
+	// These can be combined
+	if( font.isBold )
+		fontStyle |= HTI_FONT_BOLD;
+	if( font.isItalic )
+		fontStyle |= HTI_FONT_ITALIC;
+	if( font.isNotAntialiased )
+		fontStyle |= HTI_FONT_NOTAA;
+
+	// And these cannot
+	if( font.position == 1 )
+		fontStyle |= HTI_FONT_SUPER;
+	else if( font.position == 2 )
+		fontStyle |= HTI_FONT_SUB;
+
+	msg.AddByte( fontStyle );
+}
+
+//**********************************************************************************
+// GetHref
+//**********************************************************************************
+void GetHref(char* str, const unsigned char cmd)
+{
+	sprintf(str, "htiSs%x%d", cmd, clock() );
+}
+
+//**********************************************************************************
+// SetScreenCaptureAttachment
+//**********************************************************************************
+int SetScreenCaptureAttachment(struct soap* soap,
+							   BYTE* data,
+							   int dataSize,
+                               BYTE command,
+							   char* mimeType,
+                               struct ns1__captureScreenResponse &r)
+{
+	// alloc soap memory for attachment
+	char* soapAttachment = (char*)soap_malloc(soap, dataSize );
+	memcpy( soapAttachment, data, dataSize );
+
+	// get & set href for attachment
+	char href[MAX_HREF_LEN];
+	GetHref(href, command);
+	r._returnAttachment.href = (char*)soap_malloc(soap, strlen(href)+1 );
+	strcpy( r._returnAttachment.href, href );
+
+	// default mimetype is bmp
+	if ( !( mimeType ? strlen( mimeType ) : 0 ) )
+        mimeType = "image/bmp";
+
+	// set mimetype
+	r._returnAttachment.mimeType = (char*)soap_malloc(soap, strlen(mimeType)+1 );
+	strcpy( r._returnAttachment.mimeType, mimeType );
+
+	// set the attahcment
+	soap_set_dime(soap);
+	return soap_set_dime_attachment(soap, soapAttachment, dataSize,
+	                                mimeType, href, 0, NULL);
+}
+
+//**********************************************************************************
+// SetDeltaScreenCaptureAttachment
+//**********************************************************************************
+int SetDeltaScreenCaptureAttachment(struct soap* soap,
+							        BYTE* data,
+							        int dataSize,
+                                    BYTE command,
+							        char* mimeType,
+                                    struct ns1__captureDeltaScreenResponse &r)
+{
+	// Set rectangle
+	r._returnDeltaAttachment.rect.topLeftX     = *(WORD*)data; data+=2;
+	r._returnDeltaAttachment.rect.topLeftY     = *(WORD*)data; data+=2;
+	r._returnDeltaAttachment.rect.bottomRightX = *(WORD*)data; data+=2;
+	r._returnDeltaAttachment.rect.bottomRightY = *(WORD*)data; data+=2;
+	dataSize -= 2*4;
+
+	// No attachment?
+	if ( dataSize == 0 )
+		return SOAP_OK;
+
+	// alloc soap memory for attachment
+	char* soapAttachment = (char*)soap_malloc(soap, dataSize );
+	memcpy( soapAttachment, data, dataSize );
+
+	// get & set href for attachment
+	char href[MAX_HREF_LEN];
+	GetHref(href, command);
+	r._returnDeltaAttachment.href = (char*)soap_malloc(soap, strlen(href)+1 );
+	strcpy( r._returnDeltaAttachment.href, href );
+
+	// default mimetype is bmp
+	if ( !( mimeType ? strlen( mimeType ) : 0 ) )
+        mimeType = "image/bmp";
+
+	// set mimetype
+	r._returnDeltaAttachment.mimeType = (char*)soap_malloc(soap, strlen(mimeType)+1 );
+	strcpy( r._returnDeltaAttachment.mimeType, mimeType );
+
+	// set the attahcment
+	soap_set_dime(soap);
+	return soap_set_dime_attachment(soap, soapAttachment, dataSize,
+	                                mimeType, href, 0, NULL);
+}
+
+//**********************************************************************************
+// GetSerieShotFiles
+//**********************************************************************************
+int GetSerieShotFiles(struct soap* soap,
+						HtiMsgHelper &msg,
+                        struct ArrayOfFiles *files )
+{
+	// list of screenshot files is returned
+	char** tmp_array_ptr = NULL;
+	int i = 0;
+	files->__size = 0;
+	while( i < msg.GetMsgLen() )
+	{
+		int fileNameLen = msg.GetMsgBody()[i++];
+		tmp_array_ptr = (char**) realloc(tmp_array_ptr,
+		                                 (files->__size+1)*sizeof(char**));
+		tmp_array_ptr[files->__size++] = msg.GetSoapString( i, fileNameLen );
+		i += fileNameLen;
+	}
+
+	if ( files->__size == 0 )
+	{
+		soap->error = soap_receiver_fault( soap, "HtiError",
+			"No screenshot files returned");
+		return SOAP_FAULT;
+	}
+
+	// alloc (soap) space for pointers & copy data from tmp_array_ptr
+	files->__ptr = (char**) soap_malloc(soap, sizeof(char**)*files->__size);
+	memcpy(files->__ptr, tmp_array_ptr, sizeof(char**)*files->__size);
+	free(tmp_array_ptr);
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// ns1__captureFullScreen
+//**********************************************************************************
+int ns1__captureFullScreen(struct soap* soap,
+						   unsigned char colorDepth,
+						   char *imageMimeType,
+						   struct ns1__captureScreenResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCR_FULL );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+    return SetScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_SCR_FULL, imageMimeType ,r );
+}
+
+//**********************************************************************************
+// ns1__captureFullScreenZip
+//**********************************************************************************
+int ns1__captureFullScreenZip(struct soap* soap,
+							  unsigned char colorDepth,
+							  char *imageMimeType,
+							  struct ns1__captureScreenResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCR_FULL_ZIP );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+    return SetScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_SCR_FULL_ZIP, zipMimeType ,r );
+}
+
+//**********************************************************************************
+// ns1__captureRegion
+//**********************************************************************************
+int ns1__captureRegion(struct soap* soap,
+					   struct ns1__HtiRect rect,
+					   unsigned char colorDepth,
+					   char *imageMimeType,
+					   struct ns1__captureScreenResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCR_REGION );
+	msg.AddWord( rect.topLeftX );
+	msg.AddWord( rect.topLeftY );
+	msg.AddWord( rect.bottomRightX );
+	msg.AddWord( rect.bottomRightY );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+    return SetScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_SCR_REGION, imageMimeType ,r );
+}
+
+//**********************************************************************************
+// ns1__captureRegionZip
+//**********************************************************************************
+int ns1__captureRegionZip(struct soap* soap,
+						  struct ns1__HtiRect rect,
+						  unsigned char colorDepth,
+						  char *imageMimeType,
+						  struct ns1__captureScreenResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCR_REGION_ZIP );
+	msg.AddWord( rect.topLeftX );
+	msg.AddWord( rect.topLeftY );
+	msg.AddWord( rect.bottomRightX );
+	msg.AddWord( rect.bottomRightY );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+    return SetScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_SCR_REGION_ZIP, zipMimeType ,r );
+}
+
+//**********************************************************************************
+// ns1__recognizeText
+//**********************************************************************************
+int ns1__recognizeText(struct soap* soap,
+					   wchar_t *text,
+					   struct ArrayOfHtiFonts* array,
+					   struct ns1__recognizeTextResponse &r)
+{
+	// check text parameter
+	if ( check_mandatory_wcstring_parameter( soap, text, "text" ) )
+		return SOAP_FAULT;
+	else if ( wcslen( text ) > 0xff )
+	{
+		soap->error = soap_sender_fault(soap, "HtiGateway", "Text too long");
+		return SOAP_FAULT;
+	}
+
+	// check array parameter
+	if ( array == NULL )
+	{
+		soap->error = soap_sender_fault( soap, "HtiGateway",
+		                                 "No font array parameter" );
+		return SOAP_FAULT;
+	}
+	else if ( array->__size < 0 )
+	{
+		soap->error = soap_sender_fault( soap, "HtiGateway", "Font array empty" );
+		return SOAP_FAULT;
+	}
+	else if ( array->__size > 0xff )
+	{
+		soap->error = soap_sender_fault( soap, "HtiGateway", "Too many fonts" );
+		return SOAP_FAULT;
+	}
+	for ( int i = 0; i < array->__size; i++ )
+	{
+		char tmp[20];
+		sprintf(tmp, "HtiFont[%d]", i);
+		if ( check_mandatory_wcstring_parameter( soap,
+			            array->__ptrHtiFont[i].fontName, tmp ) )
+			return SOAP_FAULT;
+	}
+
+	// construct and send the message
+	HtiMsgHelper msg( soap, HTI_UID, CMD_TEXT_RCG_U );
+	msg.AddWCStringWithLengthByte( text );
+	msg.AddByte( array->__size );
+	for( int i = 0; i < array->__size; i++ )
+		AddHtiFont( msg, array->__ptrHtiFont[i] );
+
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutRecongition ) )
+		return SOAP_FAULT;
+
+	// Check response
+	if ( msg.CheckMsgExactLen( 6 ) )
+		return SOAP_FAULT;
+
+	switch( msg.GetByte(0) )
+	{
+	case TXT_RCG_OK:
+		r._returnText.found = true;
+		r._returnText.x = msg.GetWord( 1 );
+		r._returnText.y = msg.GetWord( 3 );
+		r._returnText.fontIndex = msg.GetByte( 5 );
+		break;
+
+	case TXT_RCG_NOK:
+		r._returnText.found = false;
+		break;
+
+	default:
+		soap->error = soap_receiver_fault_format(soap, "HtiError",
+			"Invalid response command code 0x%x", msg.GetByte(0) );
+		return SOAP_FAULT;
+	}
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__createTextImage
+//**********************************************************************************
+int ns1__createTextImage(struct soap* soap,
+						 unsigned char colorDepth,
+						 char *imageMimeType,
+						 wchar_t *text,
+						 struct ns1__HtiFont* font,
+						 struct ns1__HtiRGB    fgColor,
+						 struct ns1__HtiRGB    bgColor,
+						 struct ns1__captureScreenResponse &r)
+{
+	// check text & imageMimeType parameters
+	if ( check_mandatory_wcstring_parameter( soap, text, "text" ) ||
+		 check_mandatory_string_parameter( soap, imageMimeType, "imageMimeType" ) )
+		return SOAP_FAULT;
+	else if ( wcslen( text ) > 0xff )
+	{
+		soap->error = soap_sender_fault(soap, "HtiGateway", "Text too long");
+		return SOAP_FAULT;
+	}
+
+	// check font parameter
+	if ( font == NULL )
+	{
+		soap->error = soap_sender_fault( soap, "HtiGateway", "No font parameter" );
+		return SOAP_FAULT;
+	}
+	if ( check_mandatory_wcstring_parameter( soap, font->fontName, "fontName" ) )
+		return SOAP_FAULT;
+
+	// construct and send the message
+	HtiMsgHelper msg( soap, HTI_UID, CMD_TEXT_IMG_U );
+	msg.AddByte( colorDepth );
+	msg.AddStringWithLengthByte( imageMimeType );
+	msg.AddWCStringWithLengthByte( text );
+	AddHtiFont( msg, *font );
+	msg.AddByte( fgColor.red ); // note little endian encoding
+	msg.AddByte( fgColor.green );
+	msg.AddByte( fgColor.blue );
+	msg.AddByte( 0x00 );
+	msg.AddByte( bgColor.red );
+	msg.AddByte( bgColor.green );
+	msg.AddByte( bgColor.blue );
+	msg.AddByte( 0x00 );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+	// get response
+	return SetScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_TEXT_IMG_U, imageMimeType ,r );
+}
+
+
+
+//**********************************************************************************
+// ns1__captureFullScreenSeries
+//**********************************************************************************
+int ns1__captureFullScreenSeries(struct soap* soap,
+								 int duration,
+								 int interval,
+								 unsigned char colorDepth,
+								 char *imageMimeType,
+                                 struct ArrayOfFiles *files)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCR_FULL_SERIES );
+	msg.AddInt( duration );
+	msg.AddInt( interval );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	int timeout = HTIMSG_TIMEOUT_10_SECONDS + duration/1000; // duration is in us
+	if ( msg.SendReceiveMsg( timeout ) )
+		return SOAP_FAULT;
+
+	return GetSerieShotFiles( soap, msg, files );
+}
+
+//**********************************************************************************
+// ns1__captureFullScreenZipSeries
+//**********************************************************************************
+int ns1__captureFullScreenZipSeries(struct soap* soap,
+									int duration,
+									int interval,
+									unsigned char colorDepth,
+									char *imageMimeType,
+                                    struct ArrayOfFiles *files)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCR_FULL_ZIP_SERIES );
+	msg.AddInt( duration );
+	msg.AddInt( interval );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	int timeout = HTIMSG_TIMEOUT_10_SECONDS + duration/1000; // duration is in us
+	if ( msg.SendReceiveMsg( timeout ) )
+		return SOAP_FAULT;
+
+	return GetSerieShotFiles( soap, msg, files );
+}
+
+//**********************************************************************************
+// ns1__captureRegionSeries
+//**********************************************************************************
+int ns1__captureRegionSeries(struct soap* soap,
+							 int duration,
+							 int interval,
+							 unsigned char colorDepth,
+							 struct ns1__HtiRect rect,
+							 char *imageMimeType,
+                             struct ArrayOfFiles *files)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCR_REGION_SERIES );
+	msg.AddInt( duration );
+	msg.AddInt( interval );
+	msg.AddByte( colorDepth );
+	msg.AddWord( rect.topLeftX );
+	msg.AddWord( rect.topLeftY );
+	msg.AddWord( rect.bottomRightX );
+	msg.AddWord( rect.bottomRightY );
+	msg.AddString( imageMimeType );
+	int timeout = HTIMSG_TIMEOUT_10_SECONDS + duration/1000; // duration is in us
+	if ( msg.SendReceiveMsg( timeout ) )
+		return SOAP_FAULT;
+
+	return GetSerieShotFiles( soap, msg, files );
+}
+
+//**********************************************************************************
+// ns1__captureRegionZipSeries
+//**********************************************************************************
+int ns1__captureRegionZipSeries(struct soap* soap,
+								int duration,
+								int interval,
+								unsigned char colorDepth,
+								struct ns1__HtiRect rect,
+								char *imageMimeType,
+                                struct ArrayOfFiles *files)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCR_REGION_ZIP_SERIES );
+	msg.AddInt( duration );
+	msg.AddInt( interval );
+	msg.AddByte( colorDepth );
+	msg.AddWord( rect.topLeftX );
+	msg.AddWord( rect.topLeftY );
+	msg.AddWord( rect.bottomRightX );
+	msg.AddWord( rect.bottomRightY );
+	msg.AddString( imageMimeType );
+	int timeout = HTIMSG_TIMEOUT_10_SECONDS + duration/1000; // duration is in us
+	if ( msg.SendReceiveMsg( timeout ) )
+		return SOAP_FAULT;
+
+	return GetSerieShotFiles( soap, msg, files );
+}
+
+//**********************************************************************************
+// ns1__captureDeltaFullScreen
+//**********************************************************************************
+int ns1__captureDeltaFullScreen(struct soap* soap,
+								unsigned char colorDepth,
+								char *imageMimeType,
+                                struct ns1__captureDeltaScreenResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELTA_SCR_FULL );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+    return SetDeltaScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_DELTA_SCR_FULL, imageMimeType ,r );
+}
+//**********************************************************************************
+// ns1__captureDeltaFullScreenZip
+//**********************************************************************************
+int ns1__captureDeltaFullScreenZip(struct soap* soap,
+								   unsigned char colorDepth,
+								   char *imageMimeType,
+                                   struct ns1__captureDeltaScreenResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELTA_SCR_FULL_ZIP );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+    return SetDeltaScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_DELTA_SCR_FULL_ZIP, zipMimeType ,r );
+}
+//**********************************************************************************
+// ns1__captureDeltaRegion
+//**********************************************************************************
+int ns1__captureDeltaRegion(struct soap* soap,
+                            struct ns1__HtiRect rect,
+							unsigned char colorDepth,
+							char *imageMimeType,
+							struct ns1__captureDeltaScreenResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELTA_SCR_REGION );
+	msg.AddWord( rect.topLeftX );
+	msg.AddWord( rect.topLeftY );
+	msg.AddWord( rect.bottomRightX );
+	msg.AddWord( rect.bottomRightY );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+    return SetDeltaScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_DELTA_SCR_REGION, imageMimeType ,r );
+}
+//**********************************************************************************
+// ns1__captureDeltaRegionZip
+//**********************************************************************************
+int ns1__captureDeltaRegionZip(struct soap* soap,
+                               struct ns1__HtiRect rect,
+							   unsigned char colorDepth,
+							   char *imageMimeType,
+							   struct ns1__captureDeltaScreenResponse &r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELTA_SCR_REGION_ZIP );
+	msg.AddWord( rect.topLeftX );
+	msg.AddWord( rect.topLeftY );
+	msg.AddWord( rect.bottomRightX );
+	msg.AddWord( rect.bottomRightY );
+	msg.AddByte( colorDepth );
+	msg.AddString( imageMimeType );
+	if ( msg.SendReceiveMsg( g_ScreenHtiTimeoutImage ) )
+		return SOAP_FAULT;
+
+    return SetDeltaScreenCaptureAttachment( soap, msg.GetMsgBody(), msg.GetMsgLen(),
+		CMD_DELTA_SCR_REGION_ZIP, zipMimeType ,r );
+}
+
+//**********************************************************************************
+// ns1__selectScreen
+//**********************************************************************************
+int ns1__selectScreen(struct soap* soap,
+					  unsigned char screenNr,
+                      struct ns1__selectScreenResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_CHANGE_SCREEN );
+	msg.AddByte( screenNr );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__resetDeltaScreen
+//**********************************************************************************
+int ns1__resetDeltaScreen(struct soap* soap,
+                          void *_,
+                          struct ns1__resetDeltaScreenResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_DELTA_SCR_RESET );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__screenMode
+//**********************************************************************************
+int ns1__screenMode(struct soap* soap,
+                    void *_,
+                    struct ns1__screenModeResponse& r)
+{
+	HtiMsgHelper msg( soap, HTI_UID, CMD_SCREEN_MODE );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+    
+	// Check response
+	if ( msg.CheckMsgExactLen( 8 ) )
+		return SOAP_FAULT;
+
+    r._returnScreenMode.screenNumber = msg.GetByte( 0 );
+    r._returnScreenMode.screenWidth = msg.GetWord( 1 );
+    r._returnScreenMode.screenHeight = msg.GetWord( 3 );
+    r._returnScreenMode.screenRotation = (ns1__screenOrientation)msg.GetByte( 5 );
+    r._returnScreenMode.displayMode = msg.GetByte( 6 );
+    r._returnScreenMode.focusScreenNumber = msg.GetByte( 7 );
+
+    return SOAP_OK;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiScreenshot.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,245 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiScreenshot
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char * xsd__string;
+typedef wchar_t * xsd__string_;
+typedef int xsd__int;
+typedef unsigned char xsd__unsignedByte;
+typedef unsigned short xsd__unsignedShort;
+typedef bool xsd__boolean;
+
+enum ns1__screenOrientation { Rotated0, Rotated90, Rotated180, Rotated270 };
+
+struct ns1__HtiSoapAttachment
+{
+	//@xsd__string href;
+	xsd__string href;
+	xsd__string mimeType;
+};
+
+struct ns1__HtiFont
+{
+	xsd__string_ fontName;
+	xsd__unsignedShort fontHeight;
+	xsd__boolean isBold;
+	xsd__boolean isItalic;
+	xsd__boolean isNotAntialiased;
+	xsd__unsignedByte position;
+};
+
+struct ArrayOfHtiFonts
+{
+	struct ns1__HtiFont* __ptrHtiFont;
+	int __size;
+};
+
+struct ns1__HtiRecognizeTextResult
+{
+	xsd__boolean found;
+	xsd__unsignedShort x;
+	xsd__unsignedShort y;
+	xsd__unsignedShort fontIndex;
+};
+
+struct ns1__HtiRect
+{
+	xsd__unsignedShort topLeftX;
+	xsd__unsignedShort topLeftY;
+	xsd__unsignedShort bottomRightX;
+	xsd__unsignedShort bottomRightY;
+};
+
+struct ns1__HtiRGB
+{
+	xsd__unsignedByte	red;
+	xsd__unsignedByte	green;
+	xsd__unsignedByte	blue;
+};
+
+struct ns1__HtiDeltaCaptureAttachment
+{
+	xsd__string href;
+	xsd__string mimeType;
+	struct ns1__HtiRect rect;
+};
+
+struct ns1__HtiScreenModeResult
+{
+    xsd__unsignedByte screenNumber;
+    xsd__unsignedShort screenWidth;
+    xsd__unsignedShort screenHeight;
+    enum ns1__screenOrientation screenRotation;
+    xsd__unsignedByte displayMode;
+    xsd__unsignedByte focusScreenNumber;
+};
+
+struct ns1__captureScreenResponse{ struct ns1__HtiSoapAttachment _returnAttachment;};
+
+struct ns1__captureDeltaScreenResponse{
+	//struct ns1__HtiSoapAttachment _returnAttachment;
+	//struct ns1__HtiRect rect;
+	struct ns1__HtiDeltaCaptureAttachment _returnDeltaAttachment;
+};
+
+struct ns1__recognizeTextResponse{ struct ns1__HtiRecognizeTextResult _returnText;};
+
+struct ArrayOfFiles
+{
+    xsd__string	*__ptr;
+    xsd__int	__size;
+};
+
+struct ns1__screenModeResponse{ struct ns1__HtiScreenModeResult _returnScreenMode;};
+
+//gsoap ns1 service method-action: captureFullScreen "HtiScreenshot"
+int ns1__captureFullScreen(
+	xsd__unsignedByte	colorDepth,
+	xsd__string			imageMimeType,
+	struct ns1__captureScreenResponse& r
+);
+
+//gsoap ns1 service method-action: captureFullScreenZip "HtiScreenshot"
+int ns1__captureFullScreenZip(
+	xsd__unsignedByte	colorDepth,
+	xsd__string			imageMimeType,
+	struct ns1__captureScreenResponse& r
+);
+
+//gsoap ns1 service method-action: captureRegion "HtiScreenshot"
+int ns1__captureRegion(
+	struct ns1__HtiRect    rect,
+	xsd__unsignedByte	colorDepth,
+	xsd__string			imageMimeType,
+   struct ns1__captureScreenResponse& r
+);
+
+//gsoap ns1 service method-action: captureRegionZip "HtiScreenshot"
+int ns1__captureRegionZip(
+	struct ns1__HtiRect    rect,
+	xsd__unsignedByte	colorDepth,
+	xsd__string			imageMimeType,
+	struct ns1__captureScreenResponse& r
+);
+
+//gsoap ns1 service method-action: recognizeText "HtiScreenshot"
+int ns1__recognizeText(
+	xsd__string_		text,
+	struct ArrayOfHtiFonts* array,
+	struct ns1__recognizeTextResponse& r
+);
+
+//gsoap ns1 service method-action: createTextImage "HtiScreenshot"
+int ns1__createTextImage(
+	xsd__unsignedByte		colorDepth,
+	xsd__string				imageMimeType,
+	xsd__string_			text,
+	struct ns1__HtiFont*	font,
+	struct ns1__HtiRGB    fgColor,
+	struct ns1__HtiRGB    bgColor,
+	struct ns1__captureScreenResponse& r
+);
+
+//gsoap ns1 service method-action: captureFullScreenSeries "HtiScreenshot"
+int ns1__captureFullScreenSeries(
+	xsd__int			duration,
+	xsd__int			interval,
+	xsd__unsignedByte	colorDepth,
+    xsd__string			imageMimeType,
+	struct ArrayOfFiles *files
+);
+
+//gsoap ns1 service method-action: captureFullScreenZipSeries "HtiScreenshot"
+int ns1__captureFullScreenZipSeries(
+	xsd__int			duration,
+	xsd__int			interval,
+	xsd__unsignedByte	colorDepth,
+    xsd__string			imageMimeType,
+	struct ArrayOfFiles *files
+);
+
+//gsoap ns1 service method-action: captureRegionSeries "HtiScreenshot"
+int ns1__captureRegionSeries(
+	xsd__int			duration,
+	xsd__int			interval,
+	xsd__unsignedByte	colorDepth,
+	struct ns1__HtiRect    rect,
+	xsd__string			imageMimeType,
+	struct ArrayOfFiles *files
+);
+
+//gsoap ns1 service method-action: captureRegionZipSeries "HtiScreenshot"
+int ns1__captureRegionZipSeries(
+	xsd__int			duration,
+	xsd__int			interval,
+	xsd__unsignedByte	colorDepth,
+	struct ns1__HtiRect    rect,
+	xsd__string			imageMimeType,
+	struct ArrayOfFiles *files
+);
+
+//gsoap ns1 service method-action: captureDeltaFullScreen "HtiScreenshot"
+int ns1__captureDeltaFullScreen(
+	xsd__unsignedByte	colorDepth,
+	xsd__string			imageMimeType,
+	struct ns1__captureDeltaScreenResponse& r
+);
+
+//gsoap ns1 service method-action: captureDeltaFullScreenZip "HtiScreenshot"
+int ns1__captureDeltaFullScreenZip(
+	xsd__unsignedByte	colorDepth,
+	xsd__string			imageMimeType,
+	struct ns1__captureDeltaScreenResponse& r
+);
+
+//gsoap ns1 service method-action: captureDeltaRegion "HtiScreenshot"
+int ns1__captureDeltaRegion(
+	struct ns1__HtiRect    rect,
+	xsd__unsignedByte	colorDepth,
+	xsd__string			imageMimeType,
+    struct ns1__captureDeltaScreenResponse& r
+);
+
+//gsoap ns1 service method-action: captureDeltaRegionZip "HtiScreenshot"
+int ns1__captureDeltaRegionZip(
+	struct ns1__HtiRect    rect,
+	xsd__unsignedByte	colorDepth,
+	xsd__string			imageMimeType,
+	struct ns1__captureDeltaScreenResponse& r
+);
+
+//gsoap ns1 service method-action: selectScreen "HtiScreenshot"
+int ns1__selectScreen(
+	xsd__unsignedByte	screenNr,
+	struct ns1__selectScreenResponse{} *out
+);
+
+//gsoap ns1 service method-action: resetDeltaScreen "HtiScreenshot"
+int ns1__resetDeltaScreen(
+    void *_, // no in parameter,
+	struct ns1__resetDeltaScreenResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: screenMode "HtiScreenshot"
+int ns1__screenMode(
+    void *_, // no in parameter,
+	struct ns1__screenModeResponse& r
+);
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiScreenshot.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,250 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiScreenshot"
+	ProjectGUID="{13091F20-7FB9-4A32-8D35-596317F29465}"
+	RootNamespace="HtiScreenshot"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiScreenshot.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiScreenshotServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiScreenshot.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiScreenshot.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiScreenshotH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiScreenshotStub.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiScreenshot/HtiScreenshot.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,536 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiScreenshot"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <simpleType name="screenOrientation">
+   <restriction base="xsd:string">
+    <enumeration value="Rotated0"/>
+    <enumeration value="Rotated90"/>
+    <enumeration value="Rotated180"/>
+    <enumeration value="Rotated270"/>
+   </restriction>
+  </simpleType>
+  <complexType name="HtiSoapAttachment">
+   <sequence>
+     <element name="href" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="mimeType" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="HtiFont">
+   <sequence>
+     <element name="fontName" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="fontHeight" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="isBold" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+     <element name="isItalic" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+     <element name="isNotAntialiased" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+     <element name="position" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfHtiFont">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="HtiFont" type="ns1:HtiFont" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ns1:HtiFont[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <complexType name="HtiRecognizeTextResult">
+   <sequence>
+     <element name="found" type="xsd:boolean" minOccurs="1" maxOccurs="1"/>
+     <element name="x" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="y" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="fontIndex" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="HtiRect">
+   <sequence>
+     <element name="topLeftX" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="topLeftY" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="bottomRightX" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="bottomRightY" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="HtiRGB">
+   <sequence>
+     <element name="red" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="green" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="blue" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="HtiDeltaCaptureAttachment">
+   <sequence>
+     <element name="href" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="mimeType" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="rect" type="ns1:HtiRect" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="HtiScreenModeResult">
+   <sequence>
+     <element name="screenNumber" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="screenWidth" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="screenHeight" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="screenRotation" type="ns1:screenOrientation" minOccurs="1" maxOccurs="1"/>
+     <element name="displayMode" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="focusScreenNumber" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfstring">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="xsd:string[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <!-- operation request element -->
+  <element name="colorDepth" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="imageMimeType" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="returnAttachment" type="ns1:HtiSoapAttachment"/>
+  <!-- operation request element -->
+  <element name="rect" type="ns1:HtiRect"/>
+  <!-- operation request element -->
+  <element name="text" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="array" type="ns1:ArrayOfHtiFont"/>
+  <!-- operation response element -->
+  <element name="returnText" type="ns1:HtiRecognizeTextResult"/>
+  <!-- operation request element -->
+  <element name="font" type="ns1:HtiFont"/>
+  <!-- operation request element -->
+  <element name="fgColor" type="ns1:HtiRGB"/>
+  <!-- operation request element -->
+  <element name="bgColor" type="ns1:HtiRGB"/>
+  <!-- operation request element -->
+  <element name="duration" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="interval" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="files" type="ns1:ArrayOfstring"/>
+  <!-- operation response element -->
+  <element name="returnDeltaAttachment" type="ns1:HtiDeltaCaptureAttachment"/>
+  <!-- operation request element -->
+  <element name="screenNr" type="xsd:unsignedByte"/>
+  <!-- operation response element -->
+  <element name="returnScreenMode" type="ns1:HtiScreenModeResult"/>
+ </schema>
+
+</types>
+
+<message name="captureFullScreen">
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureScreenResponse">
+ <part name="returnAttachment" element="ns1:returnAttachment"/>
+</message>
+
+<message name="captureFullScreenZip">
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureRegion">
+ <part name="rect" element="ns1:rect"/>
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureRegionZip">
+ <part name="rect" element="ns1:rect"/>
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="recognizeText">
+ <part name="text" element="ns1:text"/>
+ <part name="array" element="ns1:array"/>
+</message>
+
+<message name="recognizeTextResponse">
+ <part name="returnText" element="ns1:returnText"/>
+</message>
+
+<message name="createTextImage">
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+ <part name="text" element="ns1:text"/>
+ <part name="font" element="ns1:font"/>
+ <part name="fgColor" element="ns1:fgColor"/>
+ <part name="bgColor" element="ns1:bgColor"/>
+</message>
+
+<message name="captureFullScreenSeriesRequest">
+ <part name="duration" element="ns1:duration"/>
+ <part name="interval" element="ns1:interval"/>
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureFullScreenSeriesResponse">
+ <part name="files" element="ns1:files"/>
+</message>
+
+<message name="captureFullScreenZipSeriesRequest">
+ <part name="duration" element="ns1:duration"/>
+ <part name="interval" element="ns1:interval"/>
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureFullScreenZipSeriesResponse">
+ <part name="files" element="ns1:files"/>
+</message>
+
+<message name="captureRegionSeriesRequest">
+ <part name="duration" element="ns1:duration"/>
+ <part name="interval" element="ns1:interval"/>
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="rect" element="ns1:rect"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureRegionSeriesResponse">
+ <part name="files" element="ns1:files"/>
+</message>
+
+<message name="captureRegionZipSeriesRequest">
+ <part name="duration" element="ns1:duration"/>
+ <part name="interval" element="ns1:interval"/>
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="rect" element="ns1:rect"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureRegionZipSeriesResponse">
+ <part name="files" element="ns1:files"/>
+</message>
+
+<message name="captureDeltaFullScreen">
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureDeltaScreenResponse">
+ <part name="returnDeltaAttachment" element="ns1:returnDeltaAttachment"/>
+</message>
+
+<message name="captureDeltaFullScreenZip">
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureDeltaRegion">
+ <part name="rect" element="ns1:rect"/>
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="captureDeltaRegionZip">
+ <part name="rect" element="ns1:rect"/>
+ <part name="colorDepth" element="ns1:colorDepth"/>
+ <part name="imageMimeType" element="ns1:imageMimeType"/>
+</message>
+
+<message name="selectScreen">
+ <part name="screenNr" element="ns1:screenNr"/>
+</message>
+
+<message name="selectScreenResponse">
+</message>
+
+<message name="resetDeltaScreen">
+</message>
+
+<message name="resetDeltaScreenResponse">
+</message>
+
+<message name="screenMode">
+</message>
+
+<message name="screenModeResponse">
+ <part name="returnScreenMode" element="ns1:returnScreenMode"/>
+</message>
+
+<portType name="HtiScreenshotPortType">
+ <operation name="captureFullScreen">
+  <documentation>Service definition of function ns1__captureFullScreen</documentation>
+  <input message="tns:captureFullScreen"/>
+  <output message="tns:captureScreenResponse"/>
+ </operation>
+ <operation name="captureFullScreenZip">
+  <documentation>Service definition of function ns1__captureFullScreenZip</documentation>
+  <input message="tns:captureFullScreenZip"/>
+  <output message="tns:captureScreenResponse"/>
+ </operation>
+ <operation name="captureRegion">
+  <documentation>Service definition of function ns1__captureRegion</documentation>
+  <input message="tns:captureRegion"/>
+  <output message="tns:captureScreenResponse"/>
+ </operation>
+ <operation name="captureRegionZip">
+  <documentation>Service definition of function ns1__captureRegionZip</documentation>
+  <input message="tns:captureRegionZip"/>
+  <output message="tns:captureScreenResponse"/>
+ </operation>
+ <operation name="recognizeText">
+  <documentation>Service definition of function ns1__recognizeText</documentation>
+  <input message="tns:recognizeText"/>
+  <output message="tns:recognizeTextResponse"/>
+ </operation>
+ <operation name="createTextImage">
+  <documentation>Service definition of function ns1__createTextImage</documentation>
+  <input message="tns:createTextImage"/>
+  <output message="tns:captureScreenResponse"/>
+ </operation>
+ <operation name="captureFullScreenSeries">
+  <documentation>Service definition of function ns1__captureFullScreenSeries</documentation>
+  <input message="tns:captureFullScreenSeriesRequest"/>
+  <output message="tns:captureFullScreenSeriesResponse"/>
+ </operation>
+ <operation name="captureFullScreenZipSeries">
+  <documentation>Service definition of function ns1__captureFullScreenZipSeries</documentation>
+  <input message="tns:captureFullScreenZipSeriesRequest"/>
+  <output message="tns:captureFullScreenZipSeriesResponse"/>
+ </operation>
+ <operation name="captureRegionSeries">
+  <documentation>Service definition of function ns1__captureRegionSeries</documentation>
+  <input message="tns:captureRegionSeriesRequest"/>
+  <output message="tns:captureRegionSeriesResponse"/>
+ </operation>
+ <operation name="captureRegionZipSeries">
+  <documentation>Service definition of function ns1__captureRegionZipSeries</documentation>
+  <input message="tns:captureRegionZipSeriesRequest"/>
+  <output message="tns:captureRegionZipSeriesResponse"/>
+ </operation>
+ <operation name="captureDeltaFullScreen">
+  <documentation>Service definition of function ns1__captureDeltaFullScreen</documentation>
+  <input message="tns:captureDeltaFullScreen"/>
+  <output message="tns:captureDeltaScreenResponse"/>
+ </operation>
+ <operation name="captureDeltaFullScreenZip">
+  <documentation>Service definition of function ns1__captureDeltaFullScreenZip</documentation>
+  <input message="tns:captureDeltaFullScreenZip"/>
+  <output message="tns:captureDeltaScreenResponse"/>
+ </operation>
+ <operation name="captureDeltaRegion">
+  <documentation>Service definition of function ns1__captureDeltaRegion</documentation>
+  <input message="tns:captureDeltaRegion"/>
+  <output message="tns:captureDeltaScreenResponse"/>
+ </operation>
+ <operation name="captureDeltaRegionZip">
+  <documentation>Service definition of function ns1__captureDeltaRegionZip</documentation>
+  <input message="tns:captureDeltaRegionZip"/>
+  <output message="tns:captureDeltaScreenResponse"/>
+ </operation>
+ <operation name="selectScreen">
+  <documentation>Service definition of function ns1__selectScreen</documentation>
+  <input message="tns:selectScreen"/>
+  <output message="tns:selectScreenResponse"/>
+ </operation>
+ <operation name="resetDeltaScreen">
+  <documentation>Service definition of function ns1__resetDeltaScreen</documentation>
+  <input message="tns:resetDeltaScreen"/>
+  <output message="tns:resetDeltaScreenResponse"/>
+ </operation>
+ <operation name="screenMode">
+  <documentation>Service definition of function ns1__screenMode</documentation>
+  <input message="tns:screenMode"/>
+  <output message="tns:screenModeResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiScreenshot" type="tns:HtiScreenshotPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="captureFullScreen">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureFullScreenZip">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureRegion">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureRegionZip">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="recognizeText">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="createTextImage">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureFullScreenSeries">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureFullScreenZipSeries">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureRegionSeries">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureRegionZipSeries">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureDeltaFullScreen">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureDeltaFullScreenZip">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureDeltaRegion">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="captureDeltaRegionZip">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="selectScreen">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="resetDeltaScreen">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="screenMode">
+  <SOAP:operation style="rpc" soapAction="HtiScreenshot"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiScreenshot">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiScreenshot" binding="tns:HtiScreenshot">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+#include "HtiStif.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+//additional export functions requried for an hti-plugin
+#define HTI_SOAP_ACTION "HtiStif"
+#define HTI_STIF_UID 0x10210CC3
+                 
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_STIF_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*);
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStif.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1047 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiStifH.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+#include "../../htigateway/inc/DllModule.h"
+
+
+#include <iosfwd>
+#include <sstream>
+
+
+//**********************************************************************************
+// CONSTANTS
+//
+//**********************************************************************************
+
+// commands
+const BYTE CMD_STIF_OPEN				= 0x01;
+const BYTE CMD_STIF_CLOSE				= 0x02;
+const BYTE CMD_STIF_LOAD_MODULE			= 0x03;
+const BYTE CMD_STIF_UNLOAD_MODULE		= 0x04;
+const BYTE CMD_STIF_LIST_CASES			= 0x05;
+const BYTE CMD_STIF_START_CASE			= 0x06;
+const BYTE CMD_STIF_CANCEL_CASE			= 0x07;
+const BYTE CMD_STIF_PAUSE_CASE			= 0x08;
+const BYTE CMD_STIF_RESUME_CASE			= 0x09;
+const BYTE CMD_STIF_ADD_CASE_FILE		= 0x0A;
+const BYTE CMD_STIF_REMOVE_CASE_FILE	= 0x0B;
+const BYTE CMD_STIF_CASE_MESSAGE		= 0x0C;
+const BYTE CMD_STIF_SET_DEVICEID		= 0x0D;
+const BYTE CMD_STIF_TEST_COMPLETED		= 0x0E;
+const BYTE CMD_STIF_ATS_MESSAGE			= 0x0F;
+const BYTE CMD_STIF_SET_ATTRIBUTE		= 0x10;
+
+// timeouts
+const int TIMEOUT_10_SECONDS = 10000;
+
+// soap-action for this plugin
+const char soapAction[] = "HtiStif";
+
+// error codes for handle_received_message()
+#define HTI_RECV_ASYNC_CALL_SERVICED      1
+#define HTI_RECV_OK                       0
+#define HTI_RECV_GEN_ERROR                -1
+#define HTI_RECV_ERROR_MESSAGE            -2
+#define HTI_RECV_TIMEOUT                  -3
+#define HTI_RECV_ASYNC_CALL_SERVICE_ERROR -4
+#define HTI_RECV_ROUGUE_MESSAGE           -5
+#define HTI_RECV_UNKOWN_MESSAGE           -6
+
+//**********************************************************************************
+// FORWARD DECLARATIONS
+//
+//**********************************************************************************
+
+class HtiStifMsg;
+class HtiStifClients;
+class HtiStifSenderDll;
+//class HtiStifResults
+
+//int GetParameters(char* in, int inLen, char** parameters, int &size);
+int handle_received_message(HtiSoapHandlerInterface* handler, BOOL isSoapCallActive);
+void SetSoapFaultFromReceivedHtiError(struct soap *soap, BYTE *receivedMsgBody, int receivedMsgBodyLen);
+
+
+//**********************************************************************************
+// GLOBAL VARIABLES
+//
+//**********************************************************************************
+//HtiStifResults g_testCaseResults;
+HtiStifSenderDll *g_HtiStifSenderDll;
+HtiStifClients *g_HtiStifClients;
+
+//**********************************************************************************
+// HELPER FUNCTIONS/CLASSES
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// HtiStifMsg
+//**********************************************************************************
+class HtiStifMsg
+{
+public:
+	HtiStifMsg(BYTE command);
+
+	BYTE* GetMsgBody() { return msgBody; };
+	int GetMsgLen() { return msgBodyLen; };
+
+	void AddString(char* string);
+	void AddIntAsString(int value);
+	void AddByte(BYTE byte);
+	void AddParameterSeparator();
+
+	int CheckResponseCommandCode(struct soap *soap, BYTE commandCode);
+
+	int SendReceiveMsg(struct soap *soap, int timeout);
+
+private:
+	void IncBodySize(int size);
+	BYTE *msgBody; // NOTE: deleted when sent or by gateway when received
+	int msgBodyLen;
+};
+
+HtiStifMsg::HtiStifMsg(BYTE command)
+{
+	msgBody = new BYTE[1];
+	msgBody[0] = command;
+	msgBodyLen = 1;
+}
+
+void HtiStifMsg::IncBodySize(int size)
+{
+	BYTE *newMsgBody = new BYTE[msgBodyLen+size];
+	memcpy(newMsgBody, msgBody, msgBodyLen);
+	delete msgBody;
+	msgBody = newMsgBody;
+	msgBodyLen += size;
+}
+
+void HtiStifMsg::AddString(char* string)
+{
+	int stringLen = (int) strlen(string);
+	int writePos = msgBodyLen;
+	IncBodySize(stringLen);
+	memcpy(msgBody+writePos, string, stringLen);
+}
+
+void HtiStifMsg::AddIntAsString(int value)
+{
+	char buf[50];
+	_itoa(value, buf, 10);
+	AddString(buf);
+}
+
+void HtiStifMsg::AddByte(BYTE byte)
+{
+	int writePos = msgBodyLen;
+	IncBodySize(1);
+	msgBody[writePos] = byte;
+}
+
+void HtiStifMsg::AddParameterSeparator()
+{
+	AddByte('|');
+}
+
+int HtiStifMsg::SendReceiveMsg(struct soap* soap, int timeout)
+{
+	//dump(msgBody, msgBodyLen);
+
+	BYTE commandCode = msgBody[0];
+
+	// Send the message to symbian side
+	HtiSoapHandlerInterface* handler = static_cast<HtiSoapHandlerInterface*>(soap->user);
+	handler->SendHtiMessage(HTI_STIF_UID, msgBody, msgBodyLen);
+
+	// Clean these up for received HTI message
+	delete msgBody;
+	msgBody = NULL;
+	msgBodyLen = 0;
+
+	while(1)
+	{
+		if (handler->WaitForHtiMessage(timeout))
+		{
+			int err = handle_received_message(handler, TRUE);
+
+			// NOTE: this will be destroyed by gateway
+			msgBody = (BYTE*) handler->ReceivedHtiMessageBody();
+			msgBodyLen = handler->ReceivedHtiMessageBodySize();
+			
+			// Received a HTI initiated msg
+			// Start waiting again
+			if( (err == HTI_RECV_ASYNC_CALL_SERVICED) || 
+				(err == HTI_RECV_ASYNC_CALL_SERVICE_ERROR) )
+			{
+                continue;
+			}
+
+			if( err == HTI_RECV_ERROR_MESSAGE )
+				SetSoapFaultFromReceivedHtiError(soap, msgBody, msgBodyLen);
+
+			return err;
+		}
+		else
+		{
+			// timeout
+			soap->error = soap_receiver_fault(soap, "HtiGateway", "No response from symbian side");
+			return HTI_RECV_TIMEOUT;
+		}
+	}
+}
+
+int HtiStifMsg::CheckResponseCommandCode(struct soap *soap, BYTE commandCode)
+{
+	int result = SOAP_OK;
+	
+	if( msgBody[0] != commandCode )
+	{
+		char msg[] = "incorrect response CommandCode (expected 0x%x, got 0x%x)";
+		int msgLen = _scprintf(msg, commandCode, msgBody[0])+1; // +1 for nul char
+		char *buf = new char[msgLen];
+		sprintf(buf, msg, commandCode, msgBody[0]);
+		soap->error = soap_receiver_fault(soap, "HtiError", buf);
+		delete buf;
+		result = SOAP_FAULT;
+	}
+
+	return result;
+}
+
+//**********************************************************************************
+// HtiStifClients
+//**********************************************************************************
+class HtiStifClients
+{
+public:
+	HtiStifClients() {m_size = 0; m_clients = NULL;};
+	~HtiStifClients();
+	int Add(char* host);
+	int Remove(char* host);
+	int NrOfClients() {return m_size;};
+	const char* Get(int index) {return m_clients[index];};
+private:
+	int m_size;
+	char **m_clients;
+};
+
+HtiStifClients::~HtiStifClients()
+{
+	for(int i=0; i<m_size; i++)
+		delete m_clients[i];
+	free(m_clients);
+	m_size = 0;
+}
+
+int HtiStifClients::Add(char* host)
+{
+	// check if host already exist
+	for(int i=0; i<m_size; i++)
+	{
+		if(!strcmp(m_clients[i], host))
+			return -1;
+	}
+
+	// alloc space for new pointer array
+	char **new_clients = (char**) malloc(sizeof(char*)*(m_size+1));
+	
+	// copy data
+	for(int i=0; i<m_size; i++)
+		new_clients[i] = m_clients[i];
+
+	// free previous pointer array & set new one
+	free(m_clients);
+	m_clients = new_clients;
+
+	// alloc space for host
+	char* buf = new char[strlen(host)+1]; // +1 for nul
+	strcpy(buf, host);
+	new_clients[m_size] = buf;
+
+	// update size
+	m_size += 1;
+
+	return 0;
+}
+
+int HtiStifClients::Remove(char* host)
+{
+	int err = -1;
+
+	// alloc a smaller pointer array
+	char **new_clients = (char**) malloc(sizeof(char*)*(m_size-1));
+	
+	// copy data except removed
+	int j=0;
+	for(int i=0; i<m_size; i++)
+	{
+		if(!strcmp(m_clients[i],host))
+		{
+			delete m_clients[i]; // delete removed host
+			err = 0;
+			continue;
+		}
+
+		new_clients[j] = m_clients[i];
+		j++;
+	}
+
+	// did not find host?
+	if(err != 0)
+	{
+		free(new_clients);
+		return err;
+	}
+
+	// free previous pointer array & set new one
+	free(m_clients);
+	m_clients = new_clients;
+
+	// update size
+	m_size -= 1;
+
+	return err;
+}
+
+
+
+//**********************************************************************************
+// HtiStifSenderDll
+//**********************************************************************************
+class HtiStifSenderDll : public CDLLModule
+{
+public:
+
+	DECLARE_DLL_FUNCTION(int, __cdecl,
+						soap_send_ns1__stifMessage, (soap *, const char *, const char *, char *, void *))
+	DECLARE_DLL_FUNCTION(int, __cdecl,
+						soap_send_ns1__stifResult, (soap *, const char *, const char *, ns1__HtiStifResult, void *))
+
+    BEGIN_DLL_INIT()
+		INIT_DLL_FUNCTION(int, __cdecl,
+			 soap_send_ns1__stifMessage, (soap *, const char *, const char *, char *, void *), "soap_send_ns1__stifMessage")
+		INIT_DLL_FUNCTION(int, __cdecl,
+			 soap_send_ns1__stifResult, (soap *, const char *, const char *, ns1__HtiStifResult, void *), "soap_send_ns1__stifResult")
+	END_DLL_INIT()
+};
+
+void SetSoapFaultFromReceivedHtiError(struct soap *soap, BYTE *receivedMsgBody, int receivedMsgBodyLen)
+{
+	if( receivedMsgBodyLen == 10 )
+	{
+		// This is a standard error message
+		// (eg. not authenticated)
+		HtiSoapHandlerInterface* handler =
+			static_cast<HtiSoapHandlerInterface*>(soap->user);
+		handler->SendSoapFaultFromReceivedHtiError();
+		return;
+	}
+
+	// Get error codes
+	int frameworkErrorCode = *((BYTE*)(receivedMsgBody + 1));
+	int serviceErrorCode = *((DWORD*)(receivedMsgBody + 2));
+
+	// Get error description
+	// NOTE: first byte is skipped because it contains the command code
+	int serviceErrorDescLen = receivedMsgBodyLen - 11;
+	char* serviceErrorDesc = new char[receivedMsgBodyLen - 11 + 1];
+	memcpy(serviceErrorDesc, receivedMsgBody+11, serviceErrorDescLen);
+	serviceErrorDesc[serviceErrorDescLen] = 0x0;
+
+	// Fill the xml struct
+	std::stringstream s;
+	s<<"<htiError xmlns=\'urn:hti/fault\'><frameworkErrorCode>";
+	s<<frameworkErrorCode;
+	s<<"</frameworkErrorCode><serviceErrorCode>";
+	s<<serviceErrorCode;
+	s<<"</serviceErrorCode><serviceErrorDescription>";
+	s<<serviceErrorDesc;
+    s<<"</serviceErrorDescription>";
+	s<<"</htiError>";
+	
+	soap->error = soap_receiver_fault(soap, "HtiError", s.str().c_str() );
+
+	delete serviceErrorDesc;
+}
+
+//**********************************************************************************
+// handle_received_message
+//**********************************************************************************
+int handle_received_message(HtiSoapHandlerInterface* handler, BOOL isSoapCallActive)
+{
+	if(handler->IsReceivedHtiError())
+		return HTI_RECV_ERROR_MESSAGE;
+
+	// Get message
+	BYTE *msgBody = (BYTE*) handler->ReceivedHtiMessageBody();
+	int msgBodyLen = handler->ReceivedHtiMessageBodySize();
+
+	switch(msgBody[0])
+	{
+	// Initiated by SOAP
+	case CMD_STIF_OPEN:
+	case CMD_STIF_CLOSE:		
+	case CMD_STIF_LOAD_MODULE:
+	case CMD_STIF_UNLOAD_MODULE:
+	case CMD_STIF_LIST_CASES:
+	case CMD_STIF_START_CASE:
+	case CMD_STIF_CANCEL_CASE:
+	case CMD_STIF_PAUSE_CASE:
+	case CMD_STIF_RESUME_CASE:
+	case CMD_STIF_ADD_CASE_FILE:
+	case CMD_STIF_REMOVE_CASE_FILE:
+	case CMD_STIF_CASE_MESSAGE:
+	case CMD_STIF_SET_DEVICEID:
+	case CMD_STIF_SET_ATTRIBUTE:
+		if(isSoapCallActive)
+			return HTI_RECV_OK;
+		else
+		{
+			printf("HtiStif: Received a known but unexpected message (command code 0x%x)\n", msgBody[0]);
+			return HTI_RECV_ROUGUE_MESSAGE;
+		}
+        break;
+
+	// Initiated by HTI
+	case CMD_STIF_TEST_COMPLETED:
+		{
+			// Make copy of parameters
+			char *params = new char[msgBodyLen];
+			memcpy(params, msgBody+1, msgBodyLen-1);
+			params[msgBodyLen-1] = 0x0; // add nul to make strtok easier
+			
+			// Get data from params
+			char *testCaseId = strtok(params, "|");
+			char *testResult = strtok(NULL, "|");
+			char *testExecutionResult = strtok(NULL, "|");
+			char *resultDescription = strtok(NULL, "|");
+
+			// Check if all is there
+			if( !testCaseId || !testResult || !testExecutionResult)
+			{
+				printf("HtiStif: Received incomplete testcase result\n" );
+				delete params;
+				return HTI_RECV_ASYNC_CALL_SERVICE_ERROR;
+			}
+			
+			// Get soap env
+			struct soap soap;
+			soap_init(&soap);
+			soap.namespaces = namespaces;
+
+			// Fill HtiStifResult
+			struct ns1__HtiStifResult result;
+			result.caseId = atoi(testCaseId);
+			result.caseResult = atoi(testResult);
+			result.executionResult = atoi(testExecutionResult);
+			if(resultDescription)
+			{
+				result.resultDescription = (char*) soap_malloc( &soap, strlen(resultDescription)+1 );
+				strcpy(result.resultDescription, resultDescription);
+			}
+			else
+				result.resultDescription = NULL;
+			
+			delete params; // not needed anymore
+			
+			// Send the HtiStifResult to registered clients
+			for(int i=0; i<g_HtiStifClients->NrOfClients(); i++)
+			{
+				if(g_HtiStifSenderDll->soap_send_ns1__stifResult(&soap, g_HtiStifClients->Get(i), soapAction, result, NULL) != SOAP_OK)
+					printf("HtiStif: error sending stifResult to %s\n", g_HtiStifClients->Get(i) );
+			}
+			soap_destroy(&soap);
+			soap_end(&soap);
+			soap_done(&soap);
+
+			return HTI_RECV_ASYNC_CALL_SERVICED;
+		}
+		break;
+
+	case CMD_STIF_ATS_MESSAGE:
+		{
+			// Get soap env
+			struct soap soap;
+			soap_init(&soap);
+			soap.namespaces = namespaces;
+
+			// Get message
+			// NOTE: messages are in string format so they don't have nul-characters
+			// This might change in the future and then xsd__string will no do for this task.
+			char* msg = (char*) soap_malloc(&soap, msgBodyLen);
+			memcpy(msg, msgBody+1, msgBodyLen-1);
+			msg[msgBodyLen-1] = 0x0; // add nul
+
+			// Send the HtiStifResult to registered clients
+			for(int i=0; i<g_HtiStifClients->NrOfClients(); i++)
+			{
+				if(g_HtiStifSenderDll->soap_send_ns1__stifMessage(&soap, g_HtiStifClients->Get(i), soapAction, msg, NULL) != SOAP_OK)
+					printf("HtiStif: error sending stifMessage to %s\n", g_HtiStifClients->Get(i) );
+			}
+			soap_destroy(&soap);
+			soap_end(&soap);
+			soap_done(&soap);
+			
+			return HTI_RECV_ASYNC_CALL_SERVICED;
+		}
+		break;
+
+
+	default:
+		printf("HtiStif: Received an unkown message (command code 0x%x, sync call active %d)\n", msgBody[0], isSoapCallActive);
+		return HTI_RECV_UNKOWN_MESSAGE;
+		break;
+	}
+
+	// Should never come here
+	return HTI_RECV_GEN_ERROR;
+}
+
+
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// ns1__openStif()
+//**********************************************************************************
+int ns1__openStif(struct soap* soap, char *iniFile, struct ns1__openStifResponse *out)
+{
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_OPEN);
+	if(iniFile != NULL)
+	{
+		if(strlen(iniFile) != 0)
+			msg.AddString(iniFile);
+	}
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_OPEN) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__closeStif()
+//**********************************************************************************
+int ns1__closeStif(struct soap* soap, void *_, struct ns1__closeStifResponse *out)
+{
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_CLOSE);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_CLOSE) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+
+//**********************************************************************************
+// ns1__loadStifTestModule()
+//**********************************************************************************
+int ns1__loadStifTestModule(struct soap* soap, char *moduleName, char *iniFile, char *&moduleNameLoaded)
+{
+	// Parameter check
+	if(check_mandatory_string_parameter(soap, moduleName, "moduleName"))
+		return SOAP_FAULT;
+
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_LOAD_MODULE);
+	msg.AddString(moduleName);
+	if(iniFile != NULL)
+	{
+		if(strlen(iniFile) != 0)
+		{
+			msg.AddParameterSeparator();
+			msg.AddString(iniFile);
+		}
+	}
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check CommandCode
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_LOAD_MODULE) )
+		return SOAP_FAULT;
+
+	int moduleNameLoadedLen = msg.GetMsgLen()-1; // remaining msgBody
+	moduleNameLoaded = (char*) soap_malloc(soap, moduleNameLoadedLen+1); // +1 for nul char
+	memcpy(moduleNameLoaded, msg.GetMsgBody()+1, moduleNameLoadedLen);
+	moduleNameLoaded[moduleNameLoadedLen] = 0x0; // add nul char
+	
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__unloadStifTestModule()
+//**********************************************************************************
+int ns1__unloadStifTestModule(struct soap* soap, char *moduleName, char *&moduleNameUnloaded)
+{
+	// Parameter check
+	if(check_mandatory_string_parameter(soap, moduleName, "moduleName"))
+		return SOAP_FAULT;
+
+		// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_UNLOAD_MODULE);
+	msg.AddString(moduleName);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check CommandCode
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_UNLOAD_MODULE) )
+		return SOAP_FAULT;
+
+	int moduleNameUnloadedLen = msg.GetMsgLen()-1; // remaining msgBody
+	moduleNameUnloaded = (char*) soap_malloc(soap, moduleNameUnloadedLen+1); // +1 for nul char
+	memcpy(moduleNameUnloaded, msg.GetMsgBody()+1, moduleNameUnloadedLen);
+	moduleNameUnloaded[moduleNameUnloadedLen] = 0x0; // add nul char
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__listStifTestCases()
+//**********************************************************************************
+int ns1__listStifTestCases(struct soap* soap, char *moduleName, struct ArrayOfTestCases *testCases)
+{
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_LIST_CASES);
+	if(moduleName != NULL)
+	{
+		if(strlen(moduleName) != 0)
+			msg.AddString(moduleName);
+	}
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check CommandCode
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_LIST_CASES) )
+		return SOAP_FAULT;
+
+	// No testcases found
+	if(msg.GetMsgLen() <= 1)
+		return SOAP_OK;
+
+	// make a copy of the list
+	char* testCaseTitleList = new char[msg.GetMsgLen()];
+	memcpy(testCaseTitleList, msg.GetMsgBody()+1, msg.GetMsgLen());
+	testCaseTitleList[msg.GetMsgLen()-1] = 0x0; //add nul to make life easier
+
+	// Get number of testcases
+	char* testcase = strtok( testCaseTitleList, "|" );
+
+	// Only one testcase ?
+	if(testcase == NULL)
+	{
+		testCases->__size = 1;
+		testCases->__ptr = (char**) soap_malloc(soap, sizeof(char**));
+		testCases->__ptr[0] = (char*) soap_malloc(soap, msg.GetMsgLen());
+		memcpy(testCases->__ptr[0], testCaseTitleList, msg.GetMsgLen()); // (remember we added nul)	
+		delete testCaseTitleList;
+		return SOAP_OK;
+	}
+
+	// ..no! we have at least two
+	while(testcase != NULL)
+	{
+		testCases->__size++;
+		testcase = strtok( NULL, "|" ); // continue with testCaseTitleList
+	}
+	
+	// Now that we know the number of testcases title we can alloc soap space for 
+	// pointers and copy testcase titles to soap space.
+	testCases->__ptr = (char**) soap_malloc(soap, sizeof(char**)*testCases->__size);
+
+	// reset testCaseTitleList from previous strtok
+	memcpy(testCaseTitleList, msg.GetMsgBody()+1, msg.GetMsgLen());
+	testCaseTitleList[msg.GetMsgLen()-1] = 0x0; //add nul to make life easier
+
+	int i = 0;
+	testcase = strtok( testCaseTitleList, "|" );
+	while(testcase != NULL)
+	{
+		int testCaseLen = (int) strlen(testcase);
+		testCases->__ptr[i] = (char*) soap_malloc(soap, testCaseLen+1);
+		memcpy(testCases->__ptr[i], testcase, testCaseLen);
+		testCases->__ptr[i][testCaseLen] = 0x0; // add nul char
+		i++;
+		testcase = strtok( NULL, "|" );
+	}
+	delete testCaseTitleList;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__startStifTestCase()
+//**********************************************************************************
+int ns1__startStifTestCase(struct soap* soap, char *moduleName, int testCaseIndex, int &testCaseId)
+{
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_START_CASE);
+
+	if(moduleName != NULL)
+	{
+		if(strlen(moduleName) != 0)
+		{
+			msg.AddString(moduleName);
+			msg.AddParameterSeparator();
+		}
+	}
+    msg.AddIntAsString(testCaseIndex);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_START_CASE) )
+		return SOAP_FAULT;
+
+	// Get testCaseId
+	char* tmp = new char[msg.GetMsgLen()];
+	memcpy(tmp, msg.GetMsgBody()+1, msg.GetMsgLen()-1);
+	tmp[msg.GetMsgLen()-1] = 0x0; // add nul
+	testCaseId = atoi(tmp);
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__cancelStifTestCase()
+//**********************************************************************************
+int ns1__cancelStifTestCase(struct soap* soap, int testCaseId, struct ns1__cancelStifTestCaseResponse *out)
+{
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_CANCEL_CASE);
+	msg.AddIntAsString(testCaseId);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_CANCEL_CASE) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__pauseStifTestCase()
+//**********************************************************************************
+int ns1__pauseStifTestCase(struct soap* soap, int testCaseId, struct ns1__pauseStifTestCaseResponse *out)
+{
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_PAUSE_CASE);
+	msg.AddIntAsString(testCaseId);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_PAUSE_CASE) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__resumeStifTestCase()
+//**********************************************************************************
+int ns1__resumeStifTestCase(struct soap* soap, int testCaseId, struct ns1__resumeStifTestCaseResponse *out)
+{
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_RESUME_CASE);
+	msg.AddIntAsString(testCaseId);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_RESUME_CASE) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__addStifTestCaseFile()
+//**********************************************************************************
+int ns1__addStifTestCaseFile(struct soap* soap, char *moduleName, char *testCaseFile, struct ns1__addStifTestCaseFileResponse *out)
+{
+	// Parameter check
+	if( check_mandatory_string_parameter(soap, moduleName, "moduleName") ||
+		check_mandatory_string_parameter(soap, testCaseFile, "testCaseFile") )
+		return SOAP_FAULT;
+
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_ADD_CASE_FILE);
+	msg.AddString(moduleName);
+	msg.AddParameterSeparator();
+	msg.AddString(testCaseFile);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_ADD_CASE_FILE) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__removeStifTestCaseFile()
+//**********************************************************************************
+int ns1__removeStifTestCaseFile(struct soap* soap, char *moduleName, char *testCaseFile, struct ns1__removeStifTestCaseFileResponse *out)
+{
+	// Parameter check
+	if( check_mandatory_string_parameter(soap, moduleName, "moduleName") ||
+		check_mandatory_string_parameter(soap, testCaseFile, "testCaseFile") )
+		return SOAP_FAULT;
+
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_REMOVE_CASE_FILE);
+	msg.AddString(moduleName);
+	msg.AddParameterSeparator();
+	msg.AddString(testCaseFile);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_REMOVE_CASE_FILE) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__setDeviceId()
+//**********************************************************************************
+int ns1__setDeviceId(struct soap* soap, int deviceId, struct ns1__setDeviceIdResponse *out)
+{
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_SET_DEVICEID);
+	msg.AddIntAsString(deviceId);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_SET_DEVICEID) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__queryStifTestCaseResult()
+//**********************************************************************************
+int ns1__queryStifTestCaseResult(struct soap* soap, int testCaseId, queryStifTestCaseResultResponse &r)
+{
+	soap->error = soap_receiver_fault(soap, "HtiGateway", "queryStifTestCaseResult: not supported");
+	return SOAP_FAULT;
+}
+
+//**********************************************************************************
+// ns1__runStifTestCase()
+//**********************************************************************************
+int ns1__runStifTestCase(struct soap* soap, char *moduleName, int testCaseIndex, struct runStifTestCaseResponse &r)
+{
+	soap->error = soap_receiver_fault(soap, "HtiGateway", "runStifTestCase: not supported");
+	return SOAP_FAULT;
+}
+
+//**********************************************************************************
+// ns1__register()
+//**********************************************************************************
+int ns1__register(struct soap* soap, char *host, struct ns1__registerResponse *out)
+{
+	if(check_mandatory_string_parameter(soap, host, "host"))
+		return SOAP_FAULT;
+
+	if(g_HtiStifClients->Add(host) != 0)
+	{
+		soap->error = soap_receiver_fault(soap, "HtiGateway", "register: host already registered");
+		return SOAP_FAULT;
+	}
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__deregister()
+//**********************************************************************************
+int ns1__deregister(struct soap* soap, char *host, struct ns1__deregisterResponse *out)
+{
+	if(check_mandatory_string_parameter(soap, host, "host"))
+		return SOAP_FAULT;
+
+	if(g_HtiStifClients->Remove(host) != 0)
+	{
+		soap->error = soap_receiver_fault(soap, "HtiGateway", "deregister: did not find host");
+        return SOAP_FAULT;
+	}
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__stifMessage()
+//**********************************************************************************
+int ns1__stifMessage(struct soap* soap, char *message, struct ns1__stifMessageResponse *out)
+{
+	// Parameter check
+	if( check_mandatory_string_parameter(soap, message, "message") )
+		return SOAP_FAULT;
+
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_CASE_MESSAGE);
+	msg.AddString(message);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_CASE_MESSAGE) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__setAttribute()
+//**********************************************************************************
+int ns1__setAttribute(struct soap* soap, 
+					  char *attribute, 
+					  char *value, 
+                      struct ns1__SetAttributeResponse *out)
+{
+	// Parameter check
+	if( check_mandatory_string_parameter(soap, attribute, "attribute") ||
+		check_mandatory_string_parameter(soap, value, "value") )
+		return SOAP_FAULT;
+
+	// Assemble HTI message
+	HtiStifMsg msg(CMD_STIF_SET_ATTRIBUTE);
+	msg.AddString(attribute);
+	msg.AddParameterSeparator();
+	msg.AddString(value);
+
+	// Send msg and receive response
+	if( msg.SendReceiveMsg(soap, TIMEOUT_10_SECONDS) != ERROR_SUCCESS )
+		return SOAP_FAULT;
+
+	// Check response command code
+	if( msg.CheckResponseCommandCode(soap, CMD_STIF_SET_ATTRIBUTE) )
+		return SOAP_FAULT;
+
+	return SOAP_OK;
+}
+
+
+//**********************************************************************************
+// EXPORTED FUNCTIONS
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// DllMain
+//**********************************************************************************
+BOOL WINAPI DllMain(
+    HINSTANCE hinstDLL,  // handle to DLL module
+    DWORD fdwReason,     // reason for calling function
+    LPVOID lpReserved )  // reserved
+{
+    switch( fdwReason ) 
+    { 
+        case DLL_PROCESS_ATTACH:
+
+			g_HtiStifClients = new HtiStifClients;
+			
+			// Load HtiStifSender
+			g_HtiStifSenderDll = new HtiStifSenderDll;
+			if( g_HtiStifSenderDll->Init("serviceplugins/HtiStifSender.dll") != TRUE)
+			{
+				printf("HtiStif: could not load HtiStifSender.dll");
+				return FALSE;
+			}
+			
+			// Check exported functions
+			if( !g_HtiStifSenderDll->soap_send_ns1__stifMessage )
+			{
+				printf("HtiStif: HtiStifSender.dll - exported function soap_send_ns1__stifMessage() not found");
+				return FALSE;
+			}
+
+			if( !g_HtiStifSenderDll->soap_send_ns1__stifResult )
+			{
+				printf("HtiStif: HtiStifSender.dll - exported function soap_send_ns1__stifResult() not found");
+				return FALSE;
+			}
+	        break;
+
+        case DLL_PROCESS_DETACH:
+
+			// Delete HtiStifSender
+ 			delete g_HtiStifSenderDll;
+
+			delete g_HtiStifClients;
+
+            break;
+    }
+    return TRUE;
+}
+
+//**********************************************************************************
+// hti_serve
+//**********************************************************************************
+int hti_serve(HtiSoapHandlerInterface* handler)
+{
+	return handle_received_message(handler, FALSE);
+}
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStif.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,155 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiStif
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char*			xsd__string;
+typedef wchar_t *		xsd__string_;
+typedef int				xsd__int;
+
+struct ns1__HtiStifResult
+{
+    xsd__int		caseId;
+    xsd__int		caseResult;
+    xsd__int		executionResult;
+	xsd__string		resultDescription;
+};
+
+struct ArrayOfTestCases
+{
+    xsd__string	*__ptr;
+    xsd__int	__size;
+};
+
+//gsoap ns1 service method-action: openStif "HtiStif"
+int ns1__openStif(
+    xsd__string		iniFile,
+    struct ns1__openStifResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: closeStif "HtiStif"
+int ns1__closeStif(
+    void *_, // no in parameter
+	struct ns1__closeStifResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: loadStifTestModule "HtiStif"
+int ns1__loadStifTestModule(
+    xsd__string		moduleName,
+	xsd__string		iniFile,
+	xsd__string		&moduleNameLoaded
+);
+
+//gsoap ns1 service method-action: unloadStifTestModule "HtiStif"
+int ns1__unloadStifTestModule(
+    xsd__string		moduleName,
+	xsd__string		&moduleNameUnloaded
+);
+
+//gsoap ns1 service method-action: listStifTestCases "HtiStif"
+int ns1__listStifTestCases(
+    xsd__string		moduleName,
+    struct ArrayOfTestCases *testCases
+);
+
+//gsoap ns1 service method-action: startStifTestCase "HtiStif"
+int ns1__startStifTestCase(
+    xsd__string		moduleName,
+	xsd__int		testCaseIndex,
+	xsd__int		&testCaseId
+);
+
+//gsoap ns1 service method-action: cancelStifTestCase "HtiStif"
+int ns1__cancelStifTestCase(
+    xsd__int		testCaseId,
+	struct ns1__cancelStifTestCaseResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: pauseStifTestCase "HtiStif"
+int ns1__pauseStifTestCase(
+    xsd__int		testCaseId,
+	struct ns1__pauseStifTestCaseResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: resumeStifTestCase "HtiStif"
+int ns1__resumeStifTestCase(
+    xsd__int		testCaseId,
+	struct ns1__resumeStifTestCaseResponse{} *out  // empty response
+);
+
+struct queryStifTestCaseResultResponse{struct ns1__HtiStifResult _returnHtiStifResult;};
+//gsoap ns1 service method-action: queryStifTestCaseResult "HtiStif"
+int ns1__queryStifTestCaseResult(
+    xsd__int		testCaseId,
+	struct queryStifTestCaseResultResponse& r
+);
+
+struct runStifTestCaseResponse{struct ns1__HtiStifResult _returnHtiStifResult;};
+//gsoap ns1 service method-action: runStifTestCase "HtiStif"
+int ns1__runStifTestCase(
+    xsd__string		moduleName,
+	xsd__int		testCaseIndex,
+	struct runStifTestCaseResponse& r
+);
+
+//gsoap ns1 service method-action: addStifTestCaseFile "HtiStif"
+int ns1__addStifTestCaseFile(
+    xsd__string		moduleName,
+	xsd__string		testCaseFile,
+    struct ns1__addStifTestCaseFileResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: removeStifTestCaseFile "HtiStif"
+int ns1__removeStifTestCaseFile(
+    xsd__string		moduleName,
+	xsd__string		testCaseFile,
+    struct ns1__removeStifTestCaseFileResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: setDeviceId "HtiStif"
+int ns1__setDeviceId(
+    xsd__int		deviceId,
+	struct ns1__setDeviceIdResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: register "HtiStif"
+int ns1__register(
+    xsd__string		host,
+    struct ns1__registerResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: deregister "HtiStif"
+int ns1__deregister(
+    xsd__string		host,
+    struct ns1__deregisterResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: stifMessage "HtiStif"
+int ns1__stifMessage(
+	xsd__string		message,
+    struct ns1__stifMessageResponse{} *out  // empty response
+);
+
+//gsoap ns1 service method-action: SetAttribute "HtiStif"
+int ns1__setAttribute(
+	xsd__string		attribute,
+	xsd__string		value,
+    struct ns1__SetAttributeResponse{} *out  // empty response
+);
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStif.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,250 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiStif"
+	ProjectGUID="{3343A534-2AB9-4543-8396-7BC94B96E8F4}"
+	RootNamespace="HtiStif"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiStif.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiStifServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiStif.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiStif.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiStifH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiStifStub.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStif.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,481 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiStif"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <complexType name="HtiStifResult">
+   <sequence>
+     <element name="caseId" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="caseResult" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="executionResult" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="resultDescription" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfstring">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="item" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="xsd:string[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <!-- operation request element -->
+  <element name="iniFile" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="moduleName" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="moduleNameLoaded" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="moduleNameUnloaded" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="testCases" type="ns1:ArrayOfstring"/>
+  <!-- operation request element -->
+  <element name="testCaseIndex" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="testCaseId" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="returnHtiStifResult" type="ns1:HtiStifResult"/>
+  <!-- operation request element -->
+  <element name="testCaseFile" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="deviceId" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="host" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="message" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="attribute" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="value" type="xsd:string"/>
+ </schema>
+
+</types>
+
+<message name="openStif">
+ <part name="iniFile" element="ns1:iniFile"/>
+</message>
+
+<message name="openStifResponse">
+</message>
+
+<message name="closeStif">
+</message>
+
+<message name="closeStifResponse">
+</message>
+
+<message name="loadStifTestModuleRequest">
+ <part name="moduleName" element="ns1:moduleName"/>
+ <part name="iniFile" element="ns1:iniFile"/>
+</message>
+
+<message name="loadStifTestModuleResponse">
+ <part name="moduleNameLoaded" element="ns1:moduleNameLoaded"/>
+</message>
+
+<message name="unloadStifTestModuleRequest">
+ <part name="moduleName" element="ns1:moduleName"/>
+</message>
+
+<message name="unloadStifTestModuleResponse">
+ <part name="moduleNameUnloaded" element="ns1:moduleNameUnloaded"/>
+</message>
+
+<message name="listStifTestCasesRequest">
+ <part name="moduleName" element="ns1:moduleName"/>
+</message>
+
+<message name="listStifTestCasesResponse">
+ <part name="testCases" element="ns1:testCases"/>
+</message>
+
+<message name="startStifTestCaseRequest">
+ <part name="moduleName" element="ns1:moduleName"/>
+ <part name="testCaseIndex" element="ns1:testCaseIndex"/>
+</message>
+
+<message name="startStifTestCaseResponse">
+ <part name="testCaseId" element="ns1:testCaseId"/>
+</message>
+
+<message name="cancelStifTestCase">
+ <part name="testCaseId" element="ns1:testCaseId"/>
+</message>
+
+<message name="cancelStifTestCaseResponse">
+</message>
+
+<message name="pauseStifTestCase">
+ <part name="testCaseId" element="ns1:testCaseId"/>
+</message>
+
+<message name="pauseStifTestCaseResponse">
+</message>
+
+<message name="resumeStifTestCase">
+ <part name="testCaseId" element="ns1:testCaseId"/>
+</message>
+
+<message name="resumeStifTestCaseResponse">
+</message>
+
+<message name="queryStifTestCaseResult">
+ <part name="testCaseId" element="ns1:testCaseId"/>
+</message>
+
+<message name="queryStifTestCaseResultResponse">
+ <part name="returnHtiStifResult" element="ns1:returnHtiStifResult"/>
+</message>
+
+<message name="runStifTestCase">
+ <part name="moduleName" element="ns1:moduleName"/>
+ <part name="testCaseIndex" element="ns1:testCaseIndex"/>
+</message>
+
+<message name="runStifTestCaseResponse">
+ <part name="returnHtiStifResult" element="ns1:returnHtiStifResult"/>
+</message>
+
+<message name="addStifTestCaseFile">
+ <part name="moduleName" element="ns1:moduleName"/>
+ <part name="testCaseFile" element="ns1:testCaseFile"/>
+</message>
+
+<message name="addStifTestCaseFileResponse">
+</message>
+
+<message name="removeStifTestCaseFile">
+ <part name="moduleName" element="ns1:moduleName"/>
+ <part name="testCaseFile" element="ns1:testCaseFile"/>
+</message>
+
+<message name="removeStifTestCaseFileResponse">
+</message>
+
+<message name="setDeviceId">
+ <part name="deviceId" element="ns1:deviceId"/>
+</message>
+
+<message name="setDeviceIdResponse">
+</message>
+
+<message name="register">
+ <part name="host" element="ns1:host"/>
+</message>
+
+<message name="registerResponse">
+</message>
+
+<message name="deregister">
+ <part name="host" element="ns1:host"/>
+</message>
+
+<message name="deregisterResponse">
+</message>
+
+<message name="stifMessage">
+ <part name="message" element="ns1:message"/>
+</message>
+
+<message name="stifMessageResponse">
+</message>
+
+<message name="setAttribute">
+ <part name="attribute" element="ns1:attribute"/>
+ <part name="value" element="ns1:value"/>
+</message>
+
+<message name="SetAttributeResponse">
+</message>
+
+<portType name="HtiStifPortType">
+ <operation name="openStif">
+  <documentation>Service definition of function ns1__openStif</documentation>
+  <input message="tns:openStif"/>
+  <output message="tns:openStifResponse"/>
+ </operation>
+ <operation name="closeStif">
+  <documentation>Service definition of function ns1__closeStif</documentation>
+  <input message="tns:closeStif"/>
+  <output message="tns:closeStifResponse"/>
+ </operation>
+ <operation name="loadStifTestModule">
+  <documentation>Service definition of function ns1__loadStifTestModule</documentation>
+  <input message="tns:loadStifTestModuleRequest"/>
+  <output message="tns:loadStifTestModuleResponse"/>
+ </operation>
+ <operation name="unloadStifTestModule">
+  <documentation>Service definition of function ns1__unloadStifTestModule</documentation>
+  <input message="tns:unloadStifTestModuleRequest"/>
+  <output message="tns:unloadStifTestModuleResponse"/>
+ </operation>
+ <operation name="listStifTestCases">
+  <documentation>Service definition of function ns1__listStifTestCases</documentation>
+  <input message="tns:listStifTestCasesRequest"/>
+  <output message="tns:listStifTestCasesResponse"/>
+ </operation>
+ <operation name="startStifTestCase">
+  <documentation>Service definition of function ns1__startStifTestCase</documentation>
+  <input message="tns:startStifTestCaseRequest"/>
+  <output message="tns:startStifTestCaseResponse"/>
+ </operation>
+ <operation name="cancelStifTestCase">
+  <documentation>Service definition of function ns1__cancelStifTestCase</documentation>
+  <input message="tns:cancelStifTestCase"/>
+  <output message="tns:cancelStifTestCaseResponse"/>
+ </operation>
+ <operation name="pauseStifTestCase">
+  <documentation>Service definition of function ns1__pauseStifTestCase</documentation>
+  <input message="tns:pauseStifTestCase"/>
+  <output message="tns:pauseStifTestCaseResponse"/>
+ </operation>
+ <operation name="resumeStifTestCase">
+  <documentation>Service definition of function ns1__resumeStifTestCase</documentation>
+  <input message="tns:resumeStifTestCase"/>
+  <output message="tns:resumeStifTestCaseResponse"/>
+ </operation>
+ <operation name="queryStifTestCaseResult">
+  <documentation>Service definition of function ns1__queryStifTestCaseResult</documentation>
+  <input message="tns:queryStifTestCaseResult"/>
+  <output message="tns:queryStifTestCaseResultResponse"/>
+ </operation>
+ <operation name="runStifTestCase">
+  <documentation>Service definition of function ns1__runStifTestCase</documentation>
+  <input message="tns:runStifTestCase"/>
+  <output message="tns:runStifTestCaseResponse"/>
+ </operation>
+ <operation name="addStifTestCaseFile">
+  <documentation>Service definition of function ns1__addStifTestCaseFile</documentation>
+  <input message="tns:addStifTestCaseFile"/>
+  <output message="tns:addStifTestCaseFileResponse"/>
+ </operation>
+ <operation name="removeStifTestCaseFile">
+  <documentation>Service definition of function ns1__removeStifTestCaseFile</documentation>
+  <input message="tns:removeStifTestCaseFile"/>
+  <output message="tns:removeStifTestCaseFileResponse"/>
+ </operation>
+ <operation name="setDeviceId">
+  <documentation>Service definition of function ns1__setDeviceId</documentation>
+  <input message="tns:setDeviceId"/>
+  <output message="tns:setDeviceIdResponse"/>
+ </operation>
+ <operation name="register">
+  <documentation>Service definition of function ns1__register</documentation>
+  <input message="tns:register"/>
+  <output message="tns:registerResponse"/>
+ </operation>
+ <operation name="deregister">
+  <documentation>Service definition of function ns1__deregister</documentation>
+  <input message="tns:deregister"/>
+  <output message="tns:deregisterResponse"/>
+ </operation>
+ <operation name="stifMessage">
+  <documentation>Service definition of function ns1__stifMessage</documentation>
+  <input message="tns:stifMessage"/>
+  <output message="tns:stifMessageResponse"/>
+ </operation>
+ <operation name="setAttribute">
+  <documentation>Service definition of function ns1__setAttribute</documentation>
+  <input message="tns:setAttribute"/>
+  <output message="tns:SetAttributeResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiStif" type="tns:HtiStifPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="openStif">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="closeStif">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="loadStifTestModule">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="unloadStifTestModule">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="listStifTestCases">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="startStifTestCase">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="cancelStifTestCase">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="pauseStifTestCase">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="resumeStifTestCase">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="queryStifTestCaseResult">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="runStifTestCase">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="addStifTestCaseFile">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="removeStifTestCaseFile">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setDeviceId">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="register">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="deregister">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="stifMessage">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setAttribute">
+  <SOAP:operation style="rpc" soapAction=""/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiStif">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiStif" binding="tns:HtiStif">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStifSender.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiStif
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char*			xsd__string;
+typedef int				xsd__int;
+
+struct ns1__HtiStifResult
+{
+    xsd__int		caseId;
+    xsd__int		caseResult;
+    xsd__int		executionResult;
+	xsd__string		resultDescription;
+};
+
+//gsoap ns1 service method-action: stifMessage "HtiStif"
+int ns1__stifMessage(
+	xsd__string		message,
+    void dummy // One-Way Message Passing
+);
+
+//gsoap ns1 service method-action: stifResult "HtiStif"
+int ns1__stifResult(
+    struct ns1__HtiStifResult result,
+    void dummy // One-Way Message Passing
+);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStifSender.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,242 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiStifSender"
+	ProjectGUID="{F8039331-BC43-4091-8C3C-BE19B4FF1674}"
+	RootNamespace="HtiStifSender"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiStifSenderClientLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiStifSender.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Cx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Cx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiStifSender.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiStifSenderH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiStifSenderStub.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiStif/HtiStifSender.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,86 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiStif"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <complexType name="HtiStifResult">
+   <sequence>
+     <element name="caseId" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="caseResult" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="executionResult" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+     <element name="resultDescription" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+   </sequence>
+  </complexType>
+  <!-- operation request element -->
+  <element name="message" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="result" type="ns1:HtiStifResult"/>
+ </schema>
+
+</types>
+
+<message name="stifMessage">
+ <part name="message" element="ns1:message"/>
+</message>
+
+<message name="stifResult">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<portType name="HtiStifPortType">
+ <operation name="stifMessage">
+  <documentation>Service definition of function ns1__stifMessage</documentation>
+  <input message="tns:stifMessage"/>
+ </operation>
+ <operation name="stifResult">
+  <documentation>Service definition of function ns1__stifResult</documentation>
+  <input message="tns:stifResult"/>
+ </operation>
+</portType>
+
+<binding name="HtiStif" type="tns:HtiStifPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="stifMessage">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+ </operation>
+ <operation name="stifResult">
+  <SOAP:operation style="rpc" soapAction="HtiStif"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+ </operation>
+</binding>
+
+<service name="HtiStif">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiStif" binding="tns:HtiStif">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+#include "HtiSysInfo.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+//additional export functions requried for an hti-plugin
+#define HTI_SOAP_ACTION "HtiSysInfo"
+#define HTI_SYSINFO_UID 0x10210CC7
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_SYSINFO_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiSysInfo.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,787 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiSysInfoH.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+
+const unsigned char CMD_HAL					 = 0x01;
+const unsigned char CMD_IMEI				 = 0x02;
+const unsigned char CMD_SW_VERSION			 = 0x03;
+const unsigned char CMD_LANG_VERSION		 = 0x04;
+const unsigned char CMD_SW_LANG_VERSION		 = 0x05;
+const unsigned char CMD_USERAGENT_STRING	 = 0x06;
+const unsigned char CMD_GET_FREE_RAM		 = 0x07;
+const unsigned char CMD_GET_USED_RAM		 = 0x08;
+const unsigned char CMD_GET_TOTAL_RAM		 = 0x09;
+const unsigned char CMD_EAT_RAM				 = 0x0A;
+const unsigned char CMD_RELEASE_RAM			 = 0x0B;
+const unsigned char CMD_GET_FREE_DISKSPACE	 = 0x0C;
+const unsigned char CMD_GET_USED_DISKSPACE	 = 0x0D;
+const unsigned char CMD_GET_TOTAL_DISKSPACE	 = 0x0E;
+const unsigned char CMD_EAT_DISKSPACE		 = 0x0F;
+const unsigned char CMD_RELEASE_DISKSPACE	 = 0x10;
+const unsigned char CMD_SET_HOMETIME		 = 0x20;
+const unsigned char CMD_GET_HOMETIME		 = 0x21;
+const unsigned char CMD_SET_DATE_TIME_FORMAT = 0x22;
+const unsigned char CMD_LIGHT_STATUS	 	 = 0x30;
+const unsigned char CMD_LIGHT_ON			 = 0x31;
+const unsigned char CMD_LIGHT_OFF			 = 0x32;
+const unsigned char CMD_LIGHT_BLINK			 = 0x33;
+const unsigned char CMD_LIGHT_RELEASE		 = 0x3A;
+const unsigned char CMD_SCREENSAVER_DISABLE	 = 0x40;
+const unsigned char CMD_SCREENSAVER_ENABLE	 = 0x41;
+const unsigned char CMD_SCREENSAVER_TIMEOUT	 = 0x42;
+const unsigned char CMD_GET_NETWORK_MODE	 = 0x50;
+const unsigned char CMD_SET_NETWORK_MODE	 = 0x51;
+const unsigned char CMD_SET_NETWORK_MODE_NO_REBOOT = 0x52;
+const unsigned char CMD_HSDPA_ENABLE_DISABLE = 0x53;
+const unsigned char CMD_IR_ACTIVATE          = 0x5A;
+const unsigned char CMD_BT_POWER_STATE       = 0x5B;
+const unsigned char CMD_BT_SETTINGS          = 0x5C;
+const unsigned char CMD_BT_DELETE_PAIRINGS   = 0x5D;
+const unsigned char CMD_KEY_LOCK_TOGGLE      = 0x60;
+const unsigned char CMD_AUTO_KEY_LOCK_TIME   = 0x61;
+const unsigned char CMD_EMPTY_DRM_RIGHTS_DB  = 0x65;
+const unsigned char CMD_BATTERY_STATUS       = 0x70;
+const unsigned char CMD_SIGNAL_STRENGTH      = 0x71;
+const unsigned char CMD_UPDATE_MEDIA_GALLERY = 0x7A;
+const unsigned char CMD_ACTIVATE_SKIN        = 0x80;
+
+//const unsigned char CMD_LIGHT_SUCCESS		= 0x00;
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+
+//**********************************************************************************
+// ns1__getHalAttribute()
+//**********************************************************************************
+int ns1__getHalAttribute(struct soap* soap,
+						 int attribute,
+						 int &halAttribute)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_HAL );
+	msg.AddInt( attribute );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckMsgExactLen( 4 ) )
+		return SOAP_FAULT;
+
+	halAttribute = msg.GetInt( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getImei()
+//**********************************************************************************
+int ns1__getImei(struct soap* soap,
+				 void *_,
+				 char *&imei)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_IMEI );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	imei = msg.GetSoapString( 0, msg.GetMsgLen() );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getSwVersion()
+//**********************************************************************************
+int ns1__getSwVersion(struct soap* soap,
+					  void *_,
+					  wchar_t *&SwVersion)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SW_VERSION );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	// UCS-2 encoded string size must always be even
+	if( msg.GetMsgLen() % 2 )
+	{
+		soap->error = soap_receiver_fault(soap, "HtiError",
+			"response message size not even");
+		return SOAP_FAULT;
+	}
+
+	// SwVersion returned as UCS-2 encoded text
+	SwVersion = msg.GetSoapWCString( 0, msg.GetMsgLen()/2 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getLangVersion()
+//**********************************************************************************
+int ns1__getLangVersion(struct soap* soap,
+						void *_,
+						wchar_t *&langVersion)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_LANG_VERSION );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	// UCS-2 encoded string size must always be even
+	if( msg.GetMsgLen() % 2 )
+	{
+		soap->error = soap_receiver_fault(soap, "HtiError",
+			"response message size not even");
+		return SOAP_FAULT;
+	}
+
+	// LangVersion returned as UCS-2 encoded text
+	langVersion = msg.GetSoapWCString( 0, msg.GetMsgLen()/2 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getSwLangVersion()
+//**********************************************************************************
+int ns1__getSwLangVersion(struct soap* soap,
+						  void *_,
+						  wchar_t *&swLangVersion)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SW_LANG_VERSION );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	// UCS-2 encoded string size must always be even
+	if( msg.GetMsgLen() % 2 )
+	{
+		soap->error = soap_receiver_fault(soap, "HtiError",
+			"response message size not even");
+		return SOAP_FAULT;
+	}
+
+	// swLangVersion returned as UCS-2 encoded text
+	swLangVersion = msg.GetSoapWCString( 0, msg.GetMsgLen()/2 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getUserAgentString()
+//**********************************************************************************
+int ns1__getUserAgentString(struct soap* soap,
+							void *_,
+							char *&userAgentString)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_USERAGENT_STRING );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	userAgentString = msg.GetSoapString( 0, msg.GetMsgLen() );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__setHomeTime()
+//**********************************************************************************
+int ns1__setHomeTime(struct soap* soap,
+                     struct ns1__HtiTime * time,
+					 struct ns1__setHomeTimeResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SET_HOMETIME );
+	msg.AddWord( time->year );
+	msg.AddByte( time->month );
+	msg.AddByte( time->day );
+	msg.AddByte( time->hour );
+	msg.AddByte( time->minute );
+	msg.AddByte( time->second );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__getHomeTime()
+//**********************************************************************************
+int ns1__getHomeTime(struct soap* soap,
+					 void *_,
+                     struct getHomeTimeResponse& r)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_GET_HOMETIME );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckMsgExactLen( 7 ) )
+		return SOAP_FAULT;
+
+	r._returnHtiTime.year   = msg.GetWord( 0 );
+	r._returnHtiTime.month  = msg.GetByte( 2 );
+	r._returnHtiTime.day    = msg.GetByte( 3 );
+	r._returnHtiTime.hour   = msg.GetByte( 4 );
+	r._returnHtiTime.minute = msg.GetByte( 5 );
+	r._returnHtiTime.second = msg.GetByte( 6 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__setDateTimeFormat()
+//**********************************************************************************
+int ns1__setDateTimeFormat(struct soap* soap,
+                           enum DateFormat dateFormat,
+                           unsigned char dateSeparator,
+                           enum TimeFormat timeFormat,
+                           unsigned char timeSeparator,
+                           enum ClockFormat  clockFormat,
+					       struct ns1__setDateTimeFormatResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SET_DATE_TIME_FORMAT );
+	msg.AddByte( dateFormat );
+	msg.AddByte( dateSeparator );
+	msg.AddByte( timeFormat );
+	msg.AddByte( timeSeparator );
+	msg.AddByte( clockFormat );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__getFreeRAM()
+//**********************************************************************************
+int ns1__getFreeRAM(struct soap* soap,
+					void *_,
+					unsigned int &freeRAM)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_GET_FREE_RAM );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	freeRAM = (unsigned int) msg.GetInt( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getUsedRAM()
+//**********************************************************************************
+int ns1__getUsedRAM(struct soap* soap,
+					void *_,
+					unsigned int &usedRAM)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_GET_USED_RAM );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	usedRAM = (unsigned int) msg.GetInt( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getTotalRAM()
+//**********************************************************************************
+int ns1__getTotalRAM(struct soap* soap,
+					 void *_,
+					 unsigned int &totalRAM)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_GET_TOTAL_RAM );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	totalRAM = (unsigned int) msg.GetInt( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__eatRAM()
+//**********************************************************************************
+int ns1__eatRAM(struct soap* soap,
+				unsigned int RAMToBeLeftOver,
+				unsigned int &freeRAM)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_EAT_RAM );
+	msg.AddInt( RAMToBeLeftOver );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	freeRAM = (unsigned int) msg.GetInt( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__releaseRAM()
+//**********************************************************************************
+int ns1__releaseRAM(struct soap* soap,
+					void *_,
+					unsigned int &freeRAM)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_RELEASE_RAM );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	freeRAM = (unsigned int) msg.GetInt( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getFreeDiskSpace()
+//**********************************************************************************
+int ns1__getFreeDiskSpace(struct soap* soap,
+						  char *driveLetter,
+						  ULONG64 &freeDiskSpace)
+{
+	if ( check_mandatory_string_parameter( soap, driveLetter, "driveLetter" ) )
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_GET_FREE_DISKSPACE );
+	msg.AddByte( driveLetter[0] );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	freeDiskSpace = *(ULONG64*) msg.GetMsgBody();
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getUsedDiskSpace()
+//**********************************************************************************
+int ns1__getUsedDiskSpace(struct soap* soap,
+						  char *driveLetter,
+						  ULONG64 &usedDiskSpace)
+{
+	if ( check_mandatory_string_parameter( soap, driveLetter, "driveLetter" ) )
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_GET_USED_DISKSPACE );
+	msg.AddByte( driveLetter[0] );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	usedDiskSpace = *(ULONG64*) msg.GetMsgBody();
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__getTotalDiskSpace()
+//**********************************************************************************
+int ns1__getTotalDiskSpace(struct soap* soap,
+						   char *driveLetter,
+						   ULONG64 &totalDiskSpace)
+{
+	if ( check_mandatory_string_parameter( soap, driveLetter, "driveLetter" ) )
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_GET_TOTAL_DISKSPACE );
+	msg.AddByte( driveLetter[0] );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	totalDiskSpace = *(ULONG64*) msg.GetMsgBody();
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__eatDiskSpace()
+//**********************************************************************************
+int ns1__eatDiskSpace(struct soap* soap,
+					  char *driveLetter,
+					  ULONG64 diskSpaceToBeLeftOver,
+					  ULONG64 &freeDiskSpace)
+{
+	if ( check_mandatory_string_parameter( soap, driveLetter, "driveLetter" ) )
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_EAT_DISKSPACE );
+	msg.AddByte( driveLetter[0] );
+	msg.AddUInt64( diskSpaceToBeLeftOver );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	freeDiskSpace = *(ULONG64*) msg.GetMsgBody();
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__releaseDiskSpace()
+//**********************************************************************************
+int ns1__releaseDiskSpace(struct soap* soap,
+						  char *driveLetter,
+						  ULONG64 &freeDiskSpace)
+{
+	if ( check_mandatory_string_parameter( soap, driveLetter, "driveLetter" ) )
+		return SOAP_FAULT;
+
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_RELEASE_DISKSPACE );
+	msg.AddByte( driveLetter[0] );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	freeDiskSpace = *(ULONG64*) msg.GetMsgBody();
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__lightStatus()
+//**********************************************************************************
+int ns1__lightStatus(struct soap* soap,
+					 unsigned char lightTarget,
+					 unsigned char &lightStatus)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_LIGHT_STATUS );
+	msg.AddByte( lightTarget );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	lightStatus = msg.GetByte( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__lightOn()
+//**********************************************************************************
+int ns1__lightOn(struct soap* soap,
+				 unsigned char lightTarget,
+				 unsigned short duration,
+				 unsigned char intensity,
+				 unsigned char fadeIn,
+                 struct ns1__lightOnResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_LIGHT_ON );
+	msg.AddByte( lightTarget );
+	msg.AddWord( duration );
+	msg.AddByte( intensity );
+	msg.AddByte( fadeIn );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__lightOff()
+//**********************************************************************************
+int ns1__lightOff(struct soap* soap,
+				  unsigned char lightTarget,
+				  unsigned short duration,
+				  unsigned char fadeOut,
+                  struct ns1__lightOffResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_LIGHT_OFF );
+	msg.AddByte( lightTarget );
+	msg.AddWord( duration );
+	msg.AddByte( fadeOut );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__lightBlink()
+//**********************************************************************************
+int ns1__lightBlink(struct soap* soap,
+					unsigned char lightTarget,
+					unsigned short duration,
+					unsigned short onDuration,
+					unsigned short offDuration,
+					unsigned char intensity,
+                    struct ns1__lightBlinkResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_LIGHT_BLINK );
+	msg.AddByte( lightTarget );
+	msg.AddWord( duration );
+	msg.AddWord( onDuration );
+	msg.AddWord( offDuration );
+	msg.AddByte( intensity );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__lightRelease()
+//**********************************************************************************
+int ns1__lightRelease(struct soap* soap,
+					  void *_,
+                      struct ns1__lightReleaseResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_LIGHT_RELEASE );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__screenSaverDisable()
+//**********************************************************************************
+int ns1__screenSaverDisable(struct soap* soap,
+							void *_,
+                            struct ns1__screenSaverDisableResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SCREENSAVER_DISABLE );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__screenSaverEnable()
+//**********************************************************************************
+int ns1__screenSaverEnable(struct soap* soap,
+						   void *_,
+                           struct ns1__screenSaverEnableResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SCREENSAVER_ENABLE );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__screenSaverTimeout()
+//**********************************************************************************
+int ns1__screenSaverTimeout(struct soap* soap,
+						    unsigned char timeout,
+                            struct ns1__screenSaverTimeoutResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SCREENSAVER_TIMEOUT );
+    msg.AddByte( timeout );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__getNetworkMode()
+//**********************************************************************************
+int ns1__getNetworkMode(struct soap* soap,
+					void *_,
+                    enum NetworkMode &mode)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_GET_NETWORK_MODE );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckCommandCode( CMD_GET_NETWORK_MODE ) )
+		return SOAP_FAULT;
+
+	mode = (NetworkMode) msg.GetInt( 1 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__setNetworkMode()
+//**********************************************************************************
+int ns1__setNetworkMode(struct soap* soap,
+					enum NetworkMode mode,
+                    struct ns1__setNetworkModeResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SET_NETWORK_MODE );
+	msg.AddInt( mode );
+	msg.SendMsg();
+
+	HtiSoapHandlerInterface* handler = 
+		static_cast<HtiSoapHandlerInterface*>( soap->user );
+
+	// Wait a while if there is an error message. If there is no 
+	// response it is assumed that the command has succeeded.
+	handler->WaitForHtiMessage( HTIMSG_TIMEOUT_10_SECONDS );
+	if ( handler->IsReceivedHtiError() )
+	{
+		handler->SendSoapFaultFromReceivedHtiError();
+		return SOAP_FAULT;
+	}
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__setNetworkModeNoReboot()
+//**********************************************************************************
+int ns1__setNetworkModeNoReboot(struct soap* soap,
+					            enum NetworkMode mode,
+                                struct ns1__setNetworkModeNoRebootResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SET_NETWORK_MODE_NO_REBOOT );
+	msg.AddInt( mode );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__setHsdpaStatus()
+//**********************************************************************************
+int ns1__setHsdpaStatus(struct soap* soap,
+					    enum HsdpaStatus status,
+                        struct ns1__setHsdpaStatusResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_HSDPA_ENABLE_DISABLE );
+	msg.AddInt( status );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__irActivate()
+//**********************************************************************************
+int ns1__irActivate(struct soap* soap,
+		            void *_,
+                    struct ns1__irActivateResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_IR_ACTIVATE );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__btPowerState()
+//**********************************************************************************
+int ns1__btPowerState(struct soap* soap,
+                      bool btOn,
+                      bool force,
+                      struct ns1__btPowerStateResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_BT_POWER_STATE );
+    msg.AddByte( btOn );
+    msg.AddByte( force );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__btSettings()
+//**********************************************************************************
+int ns1__btSettings(struct soap* soap,
+                    bool discoverable,
+                    bool enableSAP,
+                    char *btName,
+                    struct ns1__btSettingsResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_BT_SETTINGS );
+    msg.AddByte( discoverable );
+    msg.AddByte( enableSAP );
+    msg.AddStringWithLengthByteZero( btName );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__btDeletePairings()
+//**********************************************************************************
+int ns1__btDeletePairings(struct soap* soap,
+                          bool closeConnections,
+                          char *btName,
+                          int &deleteCount)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_BT_DELETE_PAIRINGS );
+    msg.AddByte( closeConnections );
+    msg.AddStringWithLengthByteZero( btName );
+
+    if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+    	return SOAP_FAULT;
+
+    if ( msg.CheckMsgExactLen( 1 ) )
+		return SOAP_FAULT;
+
+    deleteCount = msg.GetByte( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__keyLockToggle()
+//**********************************************************************************
+int ns1__keyLockToggle(struct soap* soap,
+                       bool keyLockOn,
+                       bool showNote,
+                       struct ns1__keyLockToggleResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_KEY_LOCK_TOGGLE );
+    msg.AddByte( keyLockOn );
+    msg.AddByte( showNote );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__autoKeyLockTime()
+//**********************************************************************************
+int ns1__autoKeyLockTime(struct soap* soap,
+                         int seconds,
+                         struct ns1__autoKeyLockTimeResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_AUTO_KEY_LOCK_TIME );
+    msg.AddWord( seconds );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__emptyDrmRightsDb()
+//**********************************************************************************
+int ns1__emptyDrmRightsDb(struct soap* soap,
+		                  void *_,
+                          struct ns1__emptyDrmRightsDbResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_EMPTY_DRM_RIGHTS_DB );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__batteryStatus()
+//**********************************************************************************
+int ns1__batteryStatus(struct soap* soap,
+					   void *_,
+                       struct batteryStatusResponse& r)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_BATTERY_STATUS );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckMsgExactLen( 2 ) )
+		return SOAP_FAULT;
+
+	r._returnHtiBatteryStatus.batteryBars = msg.GetByte( 0 );
+	r._returnHtiBatteryStatus.chargingStatus = msg.GetByte( 1 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__signalStrength()
+//**********************************************************************************
+int ns1__signalStrength(struct soap* soap,
+					    void *_,
+                        int &signalBars)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_SIGNAL_STRENGTH );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+
+	if ( msg.CheckMsgExactLen( 1 ) )
+		return SOAP_FAULT;
+    
+    signalBars = msg.GetByte( 0 );
+
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__updateMediaGallery()
+//**********************************************************************************
+int ns1__updateMediaGallery(struct soap* soap,
+					        char* filePath,
+                            struct ns1__updateMediaGalleryResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_UPDATE_MEDIA_GALLERY );
+    msg.AddStringWithLengthByteZero( filePath );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_30_SECONDS );
+}
+
+//**********************************************************************************
+// ns1__activateSkin()
+//**********************************************************************************
+int ns1__activateSkin(struct soap* soap,
+					  char* skinName,
+                      struct ns1__activateSkinResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSINFO_UID, CMD_ACTIVATE_SKIN );
+    msg.AddStringWithLengthByteZero( skinName );
+	return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiSysInfo.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,344 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiSysInfo
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char*			xsd__string;
+typedef wchar_t *		xsd__string_;
+typedef unsigned char	xsd__unsignedByte;
+typedef unsigned short	xsd__unsignedShort;
+typedef int				xsd__int;
+typedef unsigned int	xsd__unsignedInt;
+typedef ULONG64			xsd__unsignedLong;
+typedef bool            xsd__boolean;
+
+struct ns1__HtiTime
+{
+	xsd__unsignedShort	year;
+	xsd__unsignedByte	month;
+	xsd__unsignedByte	day;
+	xsd__unsignedByte	hour;
+	xsd__unsignedByte	minute;
+	xsd__unsignedByte	second;
+};
+
+struct ns1__HtiBatteryStatus
+{
+    xsd__unsignedByte batteryBars;
+    xsd__unsignedByte chargingStatus;
+};
+
+enum NetworkMode {
+	NetworkModeGsm     = 0x01,
+	NetworkModeUmts    = 0x02,
+	NetworkModeDual    = 0x04
+};
+
+enum DateFormat {
+    DateFormatAmerican = 0x00,
+    DateFormatEuropean = 0x01,
+    DateFormatJapanese = 0x02
+};
+
+enum TimeFormat {
+    TimeFormat12h = 0x00,
+    TimeFormat24h = 0x01
+};
+
+enum ClockFormat {
+    ClockFormatAnalogue = 0x00,
+    ClockFormatDigital  = 0x01
+};
+
+enum HsdpaStatus {
+    HsdpaDisabled = 0x00,
+    HsdpaEnabled  = 0x01
+};
+
+//gsoap ns1 service method-action: getHalAttribute "HtiSysInfo"
+int ns1__getHalAttribute(
+    xsd__int		attribute,
+    xsd__int		&halAttribute
+);
+//gsoap ns1 service method-action: getImei "HtiSysInfo"
+int ns1__getImei(
+    void *_, // no in parameter
+    xsd__string		&imei
+);
+//gsoap ns1 service method-action: getSwVersion "HtiSysInfo"
+int ns1__getSwVersion(
+    void *_, // no in parameter
+    xsd__string_	&swVersion
+);
+//gsoap ns1 service method-action: getLangVersion "HtiSysInfo"
+int ns1__getLangVersion(
+    void *_, // no in parameter
+    xsd__string_	&langVersion
+);
+//gsoap ns1 service method-action: getSwLangVersion "HtiSysInfo"
+int ns1__getSwLangVersion(
+    void *_, // no in parameter
+    xsd__string_	&swLangVersion
+);
+//gsoap ns1 service method-action: getUserAgentString "HtiSysInfo"
+int ns1__getUserAgentString(
+    void *_, // no in parameter
+    xsd__string		&userAgentString
+);
+
+//gsoap ns1 service method-action: setHomeTime "HtiSysInfo"
+int ns1__setHomeTime(
+	struct ns1__HtiTime* time,
+	struct ns1__setHomeTimeResponse{} *out  // empty response
+);
+
+struct getHomeTimeResponse{struct ns1__HtiTime _returnHtiTime;};
+//gsoap ns1 service method-action: getHomeTime "HtiSysInfo"
+int ns1__getHomeTime(
+    void *_, // no in parameter
+	struct getHomeTimeResponse& r
+);
+
+//gsoap ns1 service method-action: setDateTimeFormat "HtiSysInfo"
+int ns1__setDateTimeFormat(
+	enum DateFormat   dateFormat,
+	xsd__unsignedByte dateSeparator,
+	enum TimeFormat   timeFormat,
+	xsd__unsignedByte timeSeparator,
+	enum ClockFormat  clockFormat,
+	struct ns1__setDateTimeFormatResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: getFreeRAM "HtiSysInfo"
+int ns1__getFreeRAM(
+	void *_, // no in parameter
+	xsd__unsignedInt		&freeRAM
+);
+
+//gsoap ns1 service method-action: getUsedRAM "HtiSysInfo"
+int ns1__getUsedRAM(
+	void *_, // no in parameter
+	xsd__unsignedInt		&usedRAM
+);
+
+//gsoap ns1 service method-action: getTotalRAM "HtiSysInfo"
+int ns1__getTotalRAM(
+	void *_, // no in parameter
+	xsd__unsignedInt		&totalRAM
+);
+
+//gsoap ns1 service method-action: eatRAM "HtiSysInfo"
+int ns1__eatRAM(
+	xsd__unsignedInt		RAMToBeLeftOver,
+	xsd__unsignedInt		&freeRAM
+);
+
+//gsoap ns1 service method-action: releaseRAM "HtiSysInfo"
+int ns1__releaseRAM(
+	void *_, // no in parameter
+	xsd__unsignedInt		&freeRAM
+);
+
+//gsoap ns1 service method-action: getFreeDiskSpace "HtiSysInfo"
+int ns1__getFreeDiskSpace(
+	xsd__string				driveLetter,
+	xsd__unsignedLong		&freeDiskSpace
+);
+
+//gsoap ns1 service method-action: getUsedDiskSpace "HtiSysInfo"
+int ns1__getUsedDiskSpace(
+	xsd__string				driveLetter,
+	xsd__unsignedLong		&usedDiskSpace
+);
+
+//gsoap ns1 service method-action: getTotalDiskSpace "HtiSysInfo"
+int ns1__getTotalDiskSpace(
+	xsd__string				driveLetter,
+	xsd__unsignedLong		&totalDiskSpace
+);
+
+//gsoap ns1 service method-action: eatDiskSpace "HtiSysInfo"
+int ns1__eatDiskSpace(
+	xsd__string				driveLetter,
+	xsd__unsignedLong		diskSpaceToBeLeftOver,
+	xsd__unsignedLong		&freeDiskSpace
+);
+
+//gsoap ns1 service method-action: releaseDiskSpace "HtiSysInfo"
+int ns1__releaseDiskSpace(
+	xsd__string				driveLetter,
+	xsd__unsignedLong		&freeDiskSpace
+);
+
+//gsoap ns1 service method-action: lightStatus "HtiSysInfo"
+int ns1__lightStatus(
+	xsd__unsignedByte		lightTarget,
+	xsd__unsignedByte		&lightStatus
+);
+
+//gsoap ns1 service method-action: lightOn "HtiSysInfo"
+int ns1__lightOn(
+	xsd__unsignedByte		lightTarget,
+	xsd__unsignedShort		duration,
+	xsd__unsignedByte		intensity,
+	xsd__unsignedByte		fadeIn,
+	struct ns1__lightOnResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: lightOff "HtiSysInfo"
+int ns1__lightOff(
+	xsd__unsignedByte		lightTarget,
+	xsd__unsignedShort		duration,
+	xsd__unsignedByte		fadeOut,
+	struct ns1__lightOffResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: lightBlink "HtiSysInfo"
+int ns1__lightBlink(
+	xsd__unsignedByte		lightTarget,
+	xsd__unsignedShort		duration,
+	xsd__unsignedShort		onDuration,
+	xsd__unsignedShort		offDuration,
+	xsd__unsignedByte		intensity,
+	struct ns1__lightBlinkResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: lightRelease "HtiSysInfo"
+int ns1__lightRelease(
+	void *_, // no in parameter
+	struct ns1__lightReleaseResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: screenSaverDisable "HtiSysInfo"
+int ns1__screenSaverDisable(
+	void *_, // no in parameter
+	struct ns1__screenSaverDisableResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: screenSaverEnable "HtiSysInfo"
+int ns1__screenSaverEnable(
+	void *_, // no in parameter
+	struct ns1__screenSaverEnableResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: screenSaverTimeout "HtiSysInfo"
+int ns1__screenSaverTimeout(
+	xsd__unsignedByte timeout,
+	struct ns1__screenSaverTimeoutResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: getNetworkMode "HtiSysInfo"
+int ns1__getNetworkMode(
+	void *_, // no in parameter
+	enum NetworkMode &mode
+);
+
+//gsoap ns1 service method-action: setNetworkMode "HtiSysInfo"
+int ns1__setNetworkMode(
+	enum NetworkMode mode,
+	struct ns1__setNetworkModeResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: setNetworkModeNoReboot "HtiSysInfo"
+int ns1__setNetworkModeNoReboot(
+	enum NetworkMode mode,
+	struct ns1__setNetworkModeNoRebootResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: setHsdpaStatus "HtiSysInfo"
+int ns1__setHsdpaStatus(
+	enum HsdpaStatus status,
+	struct ns1__setHsdpaStatusResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: irActivate "HtiSysInfo"
+int ns1__irActivate(
+	void *_, // no in parameter,
+	struct ns1__irActivateResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: btPowerState "HtiSysInfo"
+int ns1__btPowerState(
+	xsd__boolean btOn,
+    xsd__boolean force,
+	struct ns1__btPowerStateResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: btSettings "HtiSysInfo"
+int ns1__btSettings(
+	xsd__boolean discoverable,
+    xsd__boolean enableSAP,
+    xsd__string  btName,
+	struct ns1__btSettingsResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: btDeletePairings "HtiSysInfo"
+int ns1__btDeletePairings(
+	xsd__boolean closeConnections,
+    xsd__string  btName,
+	xsd__int     &deleteCount
+);
+
+//gsoap ns1 service method-action: keyLockToggle "HtiSysInfo"
+int ns1__keyLockToggle(
+	xsd__boolean keyLockOn,
+    xsd__boolean showNote,
+	struct ns1__keyLockToggleResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: autoKeyLockTime "HtiSysInfo"
+int ns1__autoKeyLockTime(
+    xsd__int seconds,
+	struct ns1__autoKeyLockTimeResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: emptyDrmRightsDb "HtiSysInfo"
+int ns1__emptyDrmRightsDb(
+	void *_, // no in parameter,
+	struct ns1__emptyDrmRightsDbResponse{} *out // empty response
+);
+
+struct batteryStatusResponse
+{
+    struct ns1__HtiBatteryStatus _returnHtiBatteryStatus;
+};
+//gsoap ns1 service method-action: batteryStatus "HtiSysInfo"
+int ns1__batteryStatus(
+    void *_, // no in parameter
+	struct batteryStatusResponse& r
+);
+
+//gsoap ns1 service method-action: signalStrength "HtiSysInfo"
+int ns1__signalStrength(
+	void *_, // no in parameter
+	xsd__int &signalBars
+);
+
+//gsoap ns1 service method-action: updateMediaGallery "HtiSysInfo"
+int ns1__updateMediaGallery(
+	xsd__string filePath,
+    struct ns1__updateMediaGalleryResponse{} *out // empty response
+);
+
+//gsoap ns1 service method-action: activateSkin "HtiSysInfo"
+int ns1__activateSkin(
+	xsd__string skinName,
+    struct ns1__activateSkinResponse{} *out // empty response
+);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiSysInfo.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,250 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiSysInfo"
+	ProjectGUID="{0BD9D472-8DA9-4025-9FF7-A7DE5FD2B652}"
+	RootNamespace="HtiSysInfo"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_ECHO_EXPORTS"
+				RuntimeLibrary="2"
+				TreatWChar_tAsBuiltInType="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiSysInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSysInfoServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSysInfo.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiSysInfo.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSysInfoH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSysInfoStub.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSysInfo/HtiSysInfo.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1095 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiSysInfo"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <simpleType name="NetworkMode">
+   <restriction base="xsd:string">
+    <enumeration value="NetworkModeGsm"/>
+    <enumeration value="NetworkModeUmts"/>
+    <enumeration value="NetworkModeDual"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="DateFormat">
+   <restriction base="xsd:string">
+    <enumeration value="DateFormatAmerican"/>
+    <enumeration value="DateFormatEuropean"/>
+    <enumeration value="DateFormatJapanese"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="TimeFormat">
+   <restriction base="xsd:string">
+    <enumeration value="TimeFormat12h"/>
+    <enumeration value="TimeFormat24h"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="ClockFormat">
+   <restriction base="xsd:string">
+    <enumeration value="ClockFormatAnalogue"/>
+    <enumeration value="ClockFormatDigital"/>
+   </restriction>
+  </simpleType>
+  <simpleType name="HsdpaStatus">
+   <restriction base="xsd:string">
+    <enumeration value="HsdpaDisabled"/>
+    <enumeration value="HsdpaEnabled"/>
+   </restriction>
+  </simpleType>
+  <complexType name="HtiTime">
+   <sequence>
+     <element name="year" type="xsd:unsignedShort" minOccurs="1" maxOccurs="1"/>
+     <element name="month" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="day" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="hour" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="minute" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="second" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="HtiBatteryStatus">
+   <sequence>
+     <element name="batteryBars" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+     <element name="chargingStatus" type="xsd:unsignedByte" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <!-- operation request element -->
+  <element name="attribute" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="halAttribute" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="imei" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="swVersion" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="langVersion" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="swLangVersion" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="userAgentString" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="time" type="ns1:HtiTime"/>
+  <!-- operation response element -->
+  <element name="returnHtiTime" type="ns1:HtiTime"/>
+  <!-- operation request element -->
+  <element name="dateFormat" type="ns1:DateFormat"/>
+  <!-- operation request element -->
+  <element name="dateSeparator" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="timeFormat" type="ns1:TimeFormat"/>
+  <!-- operation request element -->
+  <element name="timeSeparator" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="clockFormat" type="ns1:ClockFormat"/>
+  <!-- operation response element -->
+  <element name="freeRAM" type="xsd:unsignedInt"/>
+  <!-- operation response element -->
+  <element name="usedRAM" type="xsd:unsignedInt"/>
+  <!-- operation response element -->
+  <element name="totalRAM" type="xsd:unsignedInt"/>
+  <!-- operation request element -->
+  <element name="RAMToBeLeftOver" type="xsd:unsignedInt"/>
+  <!-- operation request element -->
+  <element name="driveLetter" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="freeDiskSpace" type="xsd:unsignedLong"/>
+  <!-- operation response element -->
+  <element name="usedDiskSpace" type="xsd:unsignedLong"/>
+  <!-- operation response element -->
+  <element name="totalDiskSpace" type="xsd:unsignedLong"/>
+  <!-- operation request element -->
+  <element name="diskSpaceToBeLeftOver" type="xsd:unsignedLong"/>
+  <!-- operation request element -->
+  <element name="lightTarget" type="xsd:unsignedByte"/>
+  <!-- operation response element -->
+  <element name="lightStatus" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="duration" type="xsd:unsignedShort"/>
+  <!-- operation request element -->
+  <element name="intensity" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="fadeIn" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="fadeOut" type="xsd:unsignedByte"/>
+  <!-- operation request element -->
+  <element name="onDuration" type="xsd:unsignedShort"/>
+  <!-- operation request element -->
+  <element name="offDuration" type="xsd:unsignedShort"/>
+  <!-- operation request element -->
+  <element name="timeout" type="xsd:unsignedByte"/>
+  <!-- operation response element -->
+  <element name="mode" type="ns1:NetworkMode"/>
+  <!-- operation request element -->
+  <element name="status" type="ns1:HsdpaStatus"/>
+  <!-- operation request element -->
+  <element name="btOn" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="force" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="discoverable" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="enableSAP" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="btName" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="closeConnections" type="xsd:boolean"/>
+  <!-- operation response element -->
+  <element name="deleteCount" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="keyLockOn" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="showNote" type="xsd:boolean"/>
+  <!-- operation request element -->
+  <element name="seconds" type="xsd:int"/>
+  <!-- operation response element -->
+  <element name="returnHtiBatteryStatus" type="ns1:HtiBatteryStatus"/>
+  <!-- operation response element -->
+  <element name="signalBars" type="xsd:int"/>
+  <!-- operation request element -->
+  <element name="filePath" type="xsd:string"/>
+  <!-- operation request element -->
+  <element name="skinName" type="xsd:string"/>
+ </schema>
+
+</types>
+
+<message name="getHalAttributeRequest">
+ <part name="attribute" element="ns1:attribute"/>
+</message>
+
+<message name="getHalAttributeResponse">
+ <part name="halAttribute" element="ns1:halAttribute"/>
+</message>
+
+<message name="getImeiRequest">
+</message>
+
+<message name="getImeiResponse">
+ <part name="imei" element="ns1:imei"/>
+</message>
+
+<message name="getSwVersionRequest">
+</message>
+
+<message name="getSwVersionResponse">
+ <part name="swVersion" element="ns1:swVersion"/>
+</message>
+
+<message name="getLangVersionRequest">
+</message>
+
+<message name="getLangVersionResponse">
+ <part name="langVersion" element="ns1:langVersion"/>
+</message>
+
+<message name="getSwLangVersionRequest">
+</message>
+
+<message name="getSwLangVersionResponse">
+ <part name="swLangVersion" element="ns1:swLangVersion"/>
+</message>
+
+<message name="getUserAgentStringRequest">
+</message>
+
+<message name="getUserAgentStringResponse">
+ <part name="userAgentString" element="ns1:userAgentString"/>
+</message>
+
+<message name="setHomeTime">
+ <part name="time" element="ns1:time"/>
+</message>
+
+<message name="setHomeTimeResponse">
+</message>
+
+<message name="getHomeTime">
+</message>
+
+<message name="getHomeTimeResponse">
+ <part name="returnHtiTime" element="ns1:returnHtiTime"/>
+</message>
+
+<message name="setDateTimeFormat">
+ <part name="dateFormat" element="ns1:dateFormat"/>
+ <part name="dateSeparator" element="ns1:dateSeparator"/>
+ <part name="timeFormat" element="ns1:timeFormat"/>
+ <part name="timeSeparator" element="ns1:timeSeparator"/>
+ <part name="clockFormat" element="ns1:clockFormat"/>
+</message>
+
+<message name="setDateTimeFormatResponse">
+</message>
+
+<message name="getFreeRAMRequest">
+</message>
+
+<message name="getFreeRAMResponse">
+ <part name="freeRAM" element="ns1:freeRAM"/>
+</message>
+
+<message name="getUsedRAMRequest">
+</message>
+
+<message name="getUsedRAMResponse">
+ <part name="usedRAM" element="ns1:usedRAM"/>
+</message>
+
+<message name="getTotalRAMRequest">
+</message>
+
+<message name="getTotalRAMResponse">
+ <part name="totalRAM" element="ns1:totalRAM"/>
+</message>
+
+<message name="eatRAMRequest">
+ <part name="RAMToBeLeftOver" element="ns1:RAMToBeLeftOver"/>
+</message>
+
+<message name="eatRAMResponse">
+ <part name="freeRAM" element="ns1:freeRAM"/>
+</message>
+
+<message name="releaseRAMRequest">
+</message>
+
+<message name="releaseRAMResponse">
+ <part name="freeRAM" element="ns1:freeRAM"/>
+</message>
+
+<message name="getFreeDiskSpaceRequest">
+ <part name="driveLetter" element="ns1:driveLetter"/>
+</message>
+
+<message name="getFreeDiskSpaceResponse">
+ <part name="freeDiskSpace" element="ns1:freeDiskSpace"/>
+</message>
+
+<message name="getUsedDiskSpaceRequest">
+ <part name="driveLetter" element="ns1:driveLetter"/>
+</message>
+
+<message name="getUsedDiskSpaceResponse">
+ <part name="usedDiskSpace" element="ns1:usedDiskSpace"/>
+</message>
+
+<message name="getTotalDiskSpaceRequest">
+ <part name="driveLetter" element="ns1:driveLetter"/>
+</message>
+
+<message name="getTotalDiskSpaceResponse">
+ <part name="totalDiskSpace" element="ns1:totalDiskSpace"/>
+</message>
+
+<message name="eatDiskSpaceRequest">
+ <part name="driveLetter" element="ns1:driveLetter"/>
+ <part name="diskSpaceToBeLeftOver" element="ns1:diskSpaceToBeLeftOver"/>
+</message>
+
+<message name="eatDiskSpaceResponse">
+ <part name="freeDiskSpace" element="ns1:freeDiskSpace"/>
+</message>
+
+<message name="releaseDiskSpaceRequest">
+ <part name="driveLetter" element="ns1:driveLetter"/>
+</message>
+
+<message name="releaseDiskSpaceResponse">
+ <part name="freeDiskSpace" element="ns1:freeDiskSpace"/>
+</message>
+
+<message name="lightStatusRequest">
+ <part name="lightTarget" element="ns1:lightTarget"/>
+</message>
+
+<message name="lightStatusResponse">
+ <part name="lightStatus" element="ns1:lightStatus"/>
+</message>
+
+<message name="lightOn">
+ <part name="lightTarget" element="ns1:lightTarget"/>
+ <part name="duration" element="ns1:duration"/>
+ <part name="intensity" element="ns1:intensity"/>
+ <part name="fadeIn" element="ns1:fadeIn"/>
+</message>
+
+<message name="lightOnResponse">
+</message>
+
+<message name="lightOff">
+ <part name="lightTarget" element="ns1:lightTarget"/>
+ <part name="duration" element="ns1:duration"/>
+ <part name="fadeOut" element="ns1:fadeOut"/>
+</message>
+
+<message name="lightOffResponse">
+</message>
+
+<message name="lightBlink">
+ <part name="lightTarget" element="ns1:lightTarget"/>
+ <part name="duration" element="ns1:duration"/>
+ <part name="onDuration" element="ns1:onDuration"/>
+ <part name="offDuration" element="ns1:offDuration"/>
+ <part name="intensity" element="ns1:intensity"/>
+</message>
+
+<message name="lightBlinkResponse">
+</message>
+
+<message name="lightRelease">
+</message>
+
+<message name="lightReleaseResponse">
+</message>
+
+<message name="screenSaverDisable">
+</message>
+
+<message name="screenSaverDisableResponse">
+</message>
+
+<message name="screenSaverEnable">
+</message>
+
+<message name="screenSaverEnableResponse">
+</message>
+
+<message name="screenSaverTimeout">
+ <part name="timeout" element="ns1:timeout"/>
+</message>
+
+<message name="screenSaverTimeoutResponse">
+</message>
+
+<message name="getNetworkModeRequest">
+</message>
+
+<message name="getNetworkModeResponse">
+ <part name="mode" element="ns1:mode"/>
+</message>
+
+<message name="setNetworkMode">
+ <part name="mode" element="ns1:mode"/>
+</message>
+
+<message name="setNetworkModeResponse">
+</message>
+
+<message name="setNetworkModeNoReboot">
+ <part name="mode" element="ns1:mode"/>
+</message>
+
+<message name="setNetworkModeNoRebootResponse">
+</message>
+
+<message name="setHsdpaStatus">
+ <part name="status" element="ns1:status"/>
+</message>
+
+<message name="setHsdpaStatusResponse">
+</message>
+
+<message name="irActivate">
+</message>
+
+<message name="irActivateResponse">
+</message>
+
+<message name="btPowerState">
+ <part name="btOn" element="ns1:btOn"/>
+ <part name="force" element="ns1:force"/>
+</message>
+
+<message name="btPowerStateResponse">
+</message>
+
+<message name="btSettings">
+ <part name="discoverable" element="ns1:discoverable"/>
+ <part name="enableSAP" element="ns1:enableSAP"/>
+ <part name="btName" element="ns1:btName"/>
+</message>
+
+<message name="btSettingsResponse">
+</message>
+
+<message name="btDeletePairingsRequest">
+ <part name="closeConnections" element="ns1:closeConnections"/>
+ <part name="btName" element="ns1:btName"/>
+</message>
+
+<message name="btDeletePairingsResponse">
+ <part name="deleteCount" element="ns1:deleteCount"/>
+</message>
+
+<message name="keyLockToggle">
+ <part name="keyLockOn" element="ns1:keyLockOn"/>
+ <part name="showNote" element="ns1:showNote"/>
+</message>
+
+<message name="keyLockToggleResponse">
+</message>
+
+<message name="autoKeyLockTime">
+ <part name="seconds" element="ns1:seconds"/>
+</message>
+
+<message name="autoKeyLockTimeResponse">
+</message>
+
+<message name="emptyDrmRightsDb">
+</message>
+
+<message name="emptyDrmRightsDbResponse">
+</message>
+
+<message name="batteryStatus">
+</message>
+
+<message name="batteryStatusResponse">
+ <part name="returnHtiBatteryStatus" element="ns1:returnHtiBatteryStatus"/>
+</message>
+
+<message name="signalStrengthRequest">
+</message>
+
+<message name="signalStrengthResponse">
+ <part name="signalBars" element="ns1:signalBars"/>
+</message>
+
+<message name="updateMediaGallery">
+ <part name="filePath" element="ns1:filePath"/>
+</message>
+
+<message name="updateMediaGalleryResponse">
+</message>
+
+<message name="activateSkin">
+ <part name="skinName" element="ns1:skinName"/>
+</message>
+
+<message name="activateSkinResponse">
+</message>
+
+<portType name="HtiSysInfoPortType">
+ <operation name="getHalAttribute">
+  <documentation>Service definition of function ns1__getHalAttribute</documentation>
+  <input message="tns:getHalAttributeRequest"/>
+  <output message="tns:getHalAttributeResponse"/>
+ </operation>
+ <operation name="getImei">
+  <documentation>Service definition of function ns1__getImei</documentation>
+  <input message="tns:getImeiRequest"/>
+  <output message="tns:getImeiResponse"/>
+ </operation>
+ <operation name="getSwVersion">
+  <documentation>Service definition of function ns1__getSwVersion</documentation>
+  <input message="tns:getSwVersionRequest"/>
+  <output message="tns:getSwVersionResponse"/>
+ </operation>
+ <operation name="getLangVersion">
+  <documentation>Service definition of function ns1__getLangVersion</documentation>
+  <input message="tns:getLangVersionRequest"/>
+  <output message="tns:getLangVersionResponse"/>
+ </operation>
+ <operation name="getSwLangVersion">
+  <documentation>Service definition of function ns1__getSwLangVersion</documentation>
+  <input message="tns:getSwLangVersionRequest"/>
+  <output message="tns:getSwLangVersionResponse"/>
+ </operation>
+ <operation name="getUserAgentString">
+  <documentation>Service definition of function ns1__getUserAgentString</documentation>
+  <input message="tns:getUserAgentStringRequest"/>
+  <output message="tns:getUserAgentStringResponse"/>
+ </operation>
+ <operation name="setHomeTime">
+  <documentation>Service definition of function ns1__setHomeTime</documentation>
+  <input message="tns:setHomeTime"/>
+  <output message="tns:setHomeTimeResponse"/>
+ </operation>
+ <operation name="getHomeTime">
+  <documentation>Service definition of function ns1__getHomeTime</documentation>
+  <input message="tns:getHomeTime"/>
+  <output message="tns:getHomeTimeResponse"/>
+ </operation>
+ <operation name="setDateTimeFormat">
+  <documentation>Service definition of function ns1__setDateTimeFormat</documentation>
+  <input message="tns:setDateTimeFormat"/>
+  <output message="tns:setDateTimeFormatResponse"/>
+ </operation>
+ <operation name="getFreeRAM">
+  <documentation>Service definition of function ns1__getFreeRAM</documentation>
+  <input message="tns:getFreeRAMRequest"/>
+  <output message="tns:getFreeRAMResponse"/>
+ </operation>
+ <operation name="getUsedRAM">
+  <documentation>Service definition of function ns1__getUsedRAM</documentation>
+  <input message="tns:getUsedRAMRequest"/>
+  <output message="tns:getUsedRAMResponse"/>
+ </operation>
+ <operation name="getTotalRAM">
+  <documentation>Service definition of function ns1__getTotalRAM</documentation>
+  <input message="tns:getTotalRAMRequest"/>
+  <output message="tns:getTotalRAMResponse"/>
+ </operation>
+ <operation name="eatRAM">
+  <documentation>Service definition of function ns1__eatRAM</documentation>
+  <input message="tns:eatRAMRequest"/>
+  <output message="tns:eatRAMResponse"/>
+ </operation>
+ <operation name="releaseRAM">
+  <documentation>Service definition of function ns1__releaseRAM</documentation>
+  <input message="tns:releaseRAMRequest"/>
+  <output message="tns:releaseRAMResponse"/>
+ </operation>
+ <operation name="getFreeDiskSpace">
+  <documentation>Service definition of function ns1__getFreeDiskSpace</documentation>
+  <input message="tns:getFreeDiskSpaceRequest"/>
+  <output message="tns:getFreeDiskSpaceResponse"/>
+ </operation>
+ <operation name="getUsedDiskSpace">
+  <documentation>Service definition of function ns1__getUsedDiskSpace</documentation>
+  <input message="tns:getUsedDiskSpaceRequest"/>
+  <output message="tns:getUsedDiskSpaceResponse"/>
+ </operation>
+ <operation name="getTotalDiskSpace">
+  <documentation>Service definition of function ns1__getTotalDiskSpace</documentation>
+  <input message="tns:getTotalDiskSpaceRequest"/>
+  <output message="tns:getTotalDiskSpaceResponse"/>
+ </operation>
+ <operation name="eatDiskSpace">
+  <documentation>Service definition of function ns1__eatDiskSpace</documentation>
+  <input message="tns:eatDiskSpaceRequest"/>
+  <output message="tns:eatDiskSpaceResponse"/>
+ </operation>
+ <operation name="releaseDiskSpace">
+  <documentation>Service definition of function ns1__releaseDiskSpace</documentation>
+  <input message="tns:releaseDiskSpaceRequest"/>
+  <output message="tns:releaseDiskSpaceResponse"/>
+ </operation>
+ <operation name="lightStatus">
+  <documentation>Service definition of function ns1__lightStatus</documentation>
+  <input message="tns:lightStatusRequest"/>
+  <output message="tns:lightStatusResponse"/>
+ </operation>
+ <operation name="lightOn">
+  <documentation>Service definition of function ns1__lightOn</documentation>
+  <input message="tns:lightOn"/>
+  <output message="tns:lightOnResponse"/>
+ </operation>
+ <operation name="lightOff">
+  <documentation>Service definition of function ns1__lightOff</documentation>
+  <input message="tns:lightOff"/>
+  <output message="tns:lightOffResponse"/>
+ </operation>
+ <operation name="lightBlink">
+  <documentation>Service definition of function ns1__lightBlink</documentation>
+  <input message="tns:lightBlink"/>
+  <output message="tns:lightBlinkResponse"/>
+ </operation>
+ <operation name="lightRelease">
+  <documentation>Service definition of function ns1__lightRelease</documentation>
+  <input message="tns:lightRelease"/>
+  <output message="tns:lightReleaseResponse"/>
+ </operation>
+ <operation name="screenSaverDisable">
+  <documentation>Service definition of function ns1__screenSaverDisable</documentation>
+  <input message="tns:screenSaverDisable"/>
+  <output message="tns:screenSaverDisableResponse"/>
+ </operation>
+ <operation name="screenSaverEnable">
+  <documentation>Service definition of function ns1__screenSaverEnable</documentation>
+  <input message="tns:screenSaverEnable"/>
+  <output message="tns:screenSaverEnableResponse"/>
+ </operation>
+ <operation name="screenSaverTimeout">
+  <documentation>Service definition of function ns1__screenSaverTimeout</documentation>
+  <input message="tns:screenSaverTimeout"/>
+  <output message="tns:screenSaverTimeoutResponse"/>
+ </operation>
+ <operation name="getNetworkMode">
+  <documentation>Service definition of function ns1__getNetworkMode</documentation>
+  <input message="tns:getNetworkModeRequest"/>
+  <output message="tns:getNetworkModeResponse"/>
+ </operation>
+ <operation name="setNetworkMode">
+  <documentation>Service definition of function ns1__setNetworkMode</documentation>
+  <input message="tns:setNetworkMode"/>
+  <output message="tns:setNetworkModeResponse"/>
+ </operation>
+ <operation name="setNetworkModeNoReboot">
+  <documentation>Service definition of function ns1__setNetworkModeNoReboot</documentation>
+  <input message="tns:setNetworkModeNoReboot"/>
+  <output message="tns:setNetworkModeNoRebootResponse"/>
+ </operation>
+ <operation name="setHsdpaStatus">
+  <documentation>Service definition of function ns1__setHsdpaStatus</documentation>
+  <input message="tns:setHsdpaStatus"/>
+  <output message="tns:setHsdpaStatusResponse"/>
+ </operation>
+ <operation name="irActivate">
+  <documentation>Service definition of function ns1__irActivate</documentation>
+  <input message="tns:irActivate"/>
+  <output message="tns:irActivateResponse"/>
+ </operation>
+ <operation name="btPowerState">
+  <documentation>Service definition of function ns1__btPowerState</documentation>
+  <input message="tns:btPowerState"/>
+  <output message="tns:btPowerStateResponse"/>
+ </operation>
+ <operation name="btSettings">
+  <documentation>Service definition of function ns1__btSettings</documentation>
+  <input message="tns:btSettings"/>
+  <output message="tns:btSettingsResponse"/>
+ </operation>
+ <operation name="btDeletePairings">
+  <documentation>Service definition of function ns1__btDeletePairings</documentation>
+  <input message="tns:btDeletePairingsRequest"/>
+  <output message="tns:btDeletePairingsResponse"/>
+ </operation>
+ <operation name="keyLockToggle">
+  <documentation>Service definition of function ns1__keyLockToggle</documentation>
+  <input message="tns:keyLockToggle"/>
+  <output message="tns:keyLockToggleResponse"/>
+ </operation>
+ <operation name="autoKeyLockTime">
+  <documentation>Service definition of function ns1__autoKeyLockTime</documentation>
+  <input message="tns:autoKeyLockTime"/>
+  <output message="tns:autoKeyLockTimeResponse"/>
+ </operation>
+ <operation name="emptyDrmRightsDb">
+  <documentation>Service definition of function ns1__emptyDrmRightsDb</documentation>
+  <input message="tns:emptyDrmRightsDb"/>
+  <output message="tns:emptyDrmRightsDbResponse"/>
+ </operation>
+ <operation name="batteryStatus">
+  <documentation>Service definition of function ns1__batteryStatus</documentation>
+  <input message="tns:batteryStatus"/>
+  <output message="tns:batteryStatusResponse"/>
+ </operation>
+ <operation name="signalStrength">
+  <documentation>Service definition of function ns1__signalStrength</documentation>
+  <input message="tns:signalStrengthRequest"/>
+  <output message="tns:signalStrengthResponse"/>
+ </operation>
+ <operation name="updateMediaGallery">
+  <documentation>Service definition of function ns1__updateMediaGallery</documentation>
+  <input message="tns:updateMediaGallery"/>
+  <output message="tns:updateMediaGalleryResponse"/>
+ </operation>
+ <operation name="activateSkin">
+  <documentation>Service definition of function ns1__activateSkin</documentation>
+  <input message="tns:activateSkin"/>
+  <output message="tns:activateSkinResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiSysInfo" type="tns:HtiSysInfoPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="getHalAttribute">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getImei">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getSwVersion">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getLangVersion">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getSwLangVersion">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getUserAgentString">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setHomeTime">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getHomeTime">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setDateTimeFormat">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getFreeRAM">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getUsedRAM">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getTotalRAM">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="eatRAM">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="releaseRAM">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getFreeDiskSpace">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getUsedDiskSpace">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getTotalDiskSpace">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="eatDiskSpace">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="releaseDiskSpace">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="lightStatus">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="lightOn">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="lightOff">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="lightBlink">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="lightRelease">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="screenSaverDisable">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="screenSaverEnable">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="screenSaverTimeout">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getNetworkMode">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setNetworkMode">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setNetworkModeNoReboot">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="setHsdpaStatus">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="irActivate">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="btPowerState">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="btSettings">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="btDeletePairings">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="keyLockToggle">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="autoKeyLockTime">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="emptyDrmRightsDb">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="batteryStatus">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="signalStrength">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="updateMediaGallery">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="activateSkin">
+  <SOAP:operation style="rpc" soapAction="HtiSysInfo"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiSysInfo">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiSysInfo" binding="tns:HtiSysInfo">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*   This file contains the headers of HtiSoapHandlerInterface
+*/
+#ifndef __HTI_PLUGIN_DEF__
+#define __HTI_PLUGIN_DEF__
+
+//additional export functions requried for an hti-plugin
+#define HTI_SYSTEM_SOAP_ACTION "HtiSystem"
+#define HTI_SYSTEM_UID 0x1020DEB6
+
+#include "HtiSystem.nsmap" //generated static namespaces struct
+
+class HtiSoapHandlerInterface;
+
+/**
+* Return the name that is used to redirect SOAP request
+* to the plugin by comparing it to soapAction header
+**/
+extern "C" __declspec(dllexport) char* soapActionName(){return HTI_SYSTEM_SOAP_ACTION;};
+
+/**
+* Returns service UID of corresponding symbian side service used
+* in HTI messages. It's used for redirection of the messages from HTI
+**/
+extern "C" __declspec(dllexport) int serviceUID(){return HTI_SYSTEM_UID;};
+
+/**
+* Returns service namespace list
+**/
+extern "C" __declspec(dllexport) Namespace* serviceNamespaces(){return namespaces;};
+
+/**
+* 
+*/
+extern "C" __declspec(dllexport) int hti_serve(HtiSoapHandlerInterface*){return 0;};
+
+#endif //__HTI_PLUGIN_DEF__
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiSystem.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,196 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#include "HtiSystemH.h"
+#include "hticommon.h"
+#include "HtiPlugin.h"
+#include "HtiSoapHandlerInterface.h"
+
+// Command codes
+const int CMD_HTI_AUTH = 0x01;
+const int CMD_HTI_VERSION =      0x02;
+const int CMD_HTI_SERVICE_LIST = 0x03;
+const int CMD_HTI_STOP =         0x04;
+const int CMD_HTI_REBOOT =       0x05;
+const int CMD_HTI_FORMAT =       0x06;
+const int CMD_HTI_RESET =        0x07;
+const int CMD_HTI_SHOW_CONSOLE = 0x08;
+const int CMD_HTI_HIDE_CONSOLE = 0x09;
+const int CMD_HTI_INSTANCE_ID =  0x0A;
+const int CMD_HTI_DEBUG_PRINT =  0x0B;
+const int CMD_HTI_ERROR =        0xFF;
+
+const int SERVICE_NAME_LEN = 124;
+const int SERVICE_UID_LEN = 4;
+const int SERVICE_DESCR_LEN = SERVICE_NAME_LEN + SERVICE_UID_LEN;
+
+//**********************************************************************************
+// SOAP FUNCTIONS
+//
+//**********************************************************************************
+//**********************************************************************************
+// ns1__authentication()
+//**********************************************************************************
+int ns1__authentication(struct soap *soap,
+						char* securityToken,
+						char** result)
+{
+	// Construct & send & receive HTI message
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_AUTH );
+	msg.AddString( securityToken );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_30_SECONDS ) )
+		return SOAP_FAULT;
+
+	// Check response
+	if ( msg.CheckCommandCode( CMD_HTI_AUTH ) )
+		return SOAP_FAULT;
+
+	*result = msg.GetSoapString( 1, msg.GetMsgLen() - 1 );
+
+	return SOAP_OK;
+}
+//**********************************************************************************
+// ns1__getVersion()
+//**********************************************************************************
+int ns1__getVersion(struct soap* soap,
+					void *_,
+					char **result)
+{
+	// Construct & send & receive HTI message
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_VERSION );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_30_SECONDS ) )
+		return SOAP_FAULT;
+
+	// Fill version string
+	*result = (char*)soap_malloc(soap, 8 );
+	sprintf(*result, "%u.%u", msg.GetByte(0), msg.GetByte(1));
+
+	return SOAP_OK;	
+}
+//**********************************************************************************
+// ns1__stop()
+//**********************************************************************************
+int ns1__stop(struct soap* soap,
+			  void *_,
+              struct ns1__stopResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_STOP );
+	msg.SendMsg();
+	return SOAP_OK;
+}
+
+//**********************************************************************************
+// ns1__reset()
+//**********************************************************************************
+int ns1__reset(struct soap* soap,
+			   void *_,
+               struct ns1__resetResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_RESET );
+	msg.SendMsg();
+	return SOAP_OK;
+}
+//**********************************************************************************
+// ns1__reboot()
+//**********************************************************************************
+int ns1__reboot(struct soap* soap,
+				void *_,
+                struct ns1__rebootResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_REBOOT );
+	msg.SendMsg();
+	return SOAP_OK;
+}
+//**********************************************************************************
+// ns1__listServices()
+//**********************************************************************************
+int ns1__listServices(struct soap* soap,
+					  void *_,
+                      struct ArrayOfHtiService &array)
+{
+	// Construct & send & receive HTI message
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_SERVICE_LIST );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_30_SECONDS ) )
+		return SOAP_FAULT;
+
+	// get services
+	array.__size = msg.GetMsgLen()/SERVICE_DESCR_LEN;
+	array.__ptrHtiService = 
+		(ns1__HtiService*)soap_malloc( soap, sizeof(ns1__HtiService)*array.__size );
+	for( int i=0; i<array.__size; ++i)
+	{
+		array.__ptrHtiService[i].serviceUid = msg.GetDWord( i*SERVICE_DESCR_LEN );
+		array.__ptrHtiService[i].serviceName = 
+			msg.GetSoapString( i*SERVICE_DESCR_LEN + SERVICE_UID_LEN, SERVICE_NAME_LEN );
+	}	
+
+	return SOAP_OK;
+}
+//**********************************************************************************
+// ns1__restoreFactorySettings()
+//**********************************************************************************
+int ns1__restoreFactorySettings(struct soap* soap,
+								enum ns1__restoreMode mode,
+                                struct ns1__restoreFactorySettingsResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_FORMAT );
+	msg.AddByte( mode );
+	msg.SendMsg();
+	return SOAP_OK;
+}
+//**********************************************************************************
+// ns1__restoreFactorySettings()
+//**********************************************************************************
+int ns1__instanceID(struct soap* soap,
+					void *_,
+                    unsigned int &instanceID)
+{
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_INSTANCE_ID );
+	if ( msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS ) )
+		return SOAP_FAULT;
+    instanceID = (unsigned int) msg.GetInt( 0 );
+	return SOAP_OK;
+}
+//**********************************************************************************
+// ns1__showConsole()
+//**********************************************************************************
+int ns1__showConsole(struct soap* soap,
+			         void *_,
+                     struct ns1__showConsoleResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_SHOW_CONSOLE );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+//**********************************************************************************
+// ns1__hideConsole()
+//**********************************************************************************
+int ns1__hideConsole(struct soap* soap,
+			         void *_,
+                     struct ns1__hideConsoleResponse *out)
+{
+	HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_HIDE_CONSOLE );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
+//**********************************************************************************
+// ns1__debugPrint()
+//**********************************************************************************
+int ns1__debugPrint(struct soap* soap,
+			        char* debugMessage,
+                    struct ns1__debugPrintResponse *out)
+{
+    HtiMsgHelper msg( soap, HTI_SYSTEM_UID, CMD_HTI_DEBUG_PRINT );
+	msg.AddString( debugMessage );
+    return msg.SendReceiveMsg( HTIMSG_TIMEOUT_10_SECONDS );
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiSystem.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+// HTI service functions
+//gsoap ns1 service name: HtiSystem
+//gsoap ns1 service namespace: urn:hti
+//gsoap ns1 service style: rpc
+//gsoap ns1 service encoding: literal
+//gsoap ns1 service location: http://localhost:2000
+
+typedef char* xsd__string;
+typedef long xsd__int;
+typedef unsigned int xsd__unsignedInt;
+
+struct ns1__HtiService
+{
+	xsd__string serviceName;
+	xsd__int serviceUid;
+};
+
+struct ArrayOfHtiService
+{
+	struct ns1__HtiService *__ptrHtiService;
+	int __size;
+};
+
+enum ns1__restoreMode { ModeNormal, ModeDeep };
+
+//gsoap ns1 service method-action: authentication "HtiSystem"
+int ns1__authentication(
+	xsd__string securityToken,
+	xsd__string* result
+);
+//gsoap ns1 service method-action: getVersion "HtiSystem"
+int ns1__getVersion(
+	void*_ ,
+	xsd__string* result
+);
+//gsoap ns1 service method-action: stop "HtiSystem"
+int ns1__stop(
+	void*_ ,
+	struct ns1__stopResponse{} *out
+);
+//gsoap ns1 service method-action: reset "HtiSystem"
+int ns1__reset(
+	void*_ ,
+	struct ns1__resetResponse{} *out
+);
+//gsoap ns1 service method-action: reboot "HtiSystem"
+int ns1__reboot(
+	void*_ ,
+	struct ns1__rebootResponse{} *out
+);
+//gsoap ns1 service method-action: listServices "HtiSystem"
+int ns1__listServices(
+	void*_ ,
+	struct ArrayOfHtiService& array
+);
+//gsoap ns1 service method-action: restoreFactorySettings "HtiSystem"
+int ns1__restoreFactorySettings(
+	enum ns1__restoreMode mode,
+	struct ns1__restoreFactorySettingsResponse{} *out
+);
+//gsoap ns1 service method-action: instanceID "HtiSystem"
+int ns1__instanceID(
+	void*_ ,
+	xsd__unsignedInt &instanceID
+);
+//gsoap ns1 service method-action: showConsole "HtiSystem"
+int ns1__showConsole(
+	void*_ ,
+	struct ns1__showConsoleResponse{} *out
+);
+//gsoap ns1 service method-action: hideConsole "HtiSystem"
+int ns1__hideConsole(
+	void*_ ,
+	struct ns1__hideConsoleResponse{} *out
+);
+//gsoap ns1 service method-action: debugPrint "HtiSystem"
+int ns1__debugPrint(
+	xsd__string debugMessage,
+	struct ns1__debugPrintResponse{} *out
+);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiSystem.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,252 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="HtiSystem"
+	ProjectGUID="{B776DCEA-BDAC-4FCF-BB72-D05DCDA09316}"
+	RootNamespace="HtiSystem"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)Debug/ServicePlugins"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WS_HTI_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2D.lib $(SolutionDir)Libs\HtiCommonD.lib"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)Release/ServicePlugins"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DSOAP_FMAC5=&quot;extern \&quot;C\&quot; __declspec(dllexport)&quot; -DSOAP_CMAC=&quot;__declspec(dllexport)&quot;"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)Libs&quot;"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;WS_HTI_EXPORTS"
+				RuntimeLibrary="2"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="$(SolutionDir)Libs\stdsoap2.lib $(SolutionDir)Libs\HtiCommon.lib"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\HtiSystem.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSystemServerLib.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\HtiPlugin.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSystem.h"
+				DeploymentContent="true"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						CommandLine="$(SolutionDir)stdsoap/soapcpp2.exe -Sx -p$(TargetName) $(InputFileName)&#x0D;&#x0A;"
+						Outputs="$(TargetName)lLib.cpp $(TargetName)H.h $(TargetName)Stub.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath=".\HtiSystem.wsdl"
+				DeploymentContent="true"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSystemH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\HtiSystemStub.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+		<File
+			RelativePath=".\ReadMe.txt"
+			>
+		</File>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/ServicePlugins/HtiSystem/HtiSystem.wsdl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,307 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<definitions name="HtiSystem"
+ targetNamespace="urn:hti"
+ xmlns:tns="urn:hti"
+ xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:ns1="urn:hti"
+ xmlns:SOAP="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:MIME="http://schemas.xmlsoap.org/wsdl/mime/"
+ xmlns:DIME="http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/"
+ xmlns:WSDL="http://schemas.xmlsoap.org/wsdl/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+<types>
+
+ <schema targetNamespace="urn:hti"
+  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
+  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+  xmlns:ns1="urn:hti"
+  xmlns="http://www.w3.org/2001/XMLSchema"
+  elementFormDefault="unqualified"
+  attributeFormDefault="unqualified">
+  <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+  <simpleType name="restoreMode">
+   <restriction base="xsd:string">
+    <enumeration value="ModeNormal"/>
+    <enumeration value="ModeDeep"/>
+   </restriction>
+  </simpleType>
+  <complexType name="HtiService">
+   <sequence>
+     <element name="serviceName" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
+     <element name="serviceUid" type="xsd:int" minOccurs="1" maxOccurs="1"/>
+   </sequence>
+  </complexType>
+  <complexType name="ArrayOfHtiService">
+   <complexContent>
+    <restriction base="SOAP-ENC:Array">
+     <sequence>
+      <element name="HtiService" type="ns1:HtiService" minOccurs="0" maxOccurs="unbounded"/>
+     </sequence>
+     <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ns1:HtiService[]"/>
+    </restriction>
+   </complexContent>
+  </complexType>
+  <!-- operation request element -->
+  <element name="securityToken" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="result" type="xsd:string"/>
+  <!-- operation response element -->
+  <element name="array" type="ns1:ArrayOfHtiService"/>
+  <!-- operation request element -->
+  <element name="mode" type="ns1:restoreMode"/>
+  <!-- operation response element -->
+  <element name="instanceID" type="xsd:unsignedInt"/>
+  <!-- operation request element -->
+  <element name="debugMessage" type="xsd:string"/>
+ </schema>
+
+</types>
+
+<message name="authenticationRequest">
+ <part name="securityToken" element="ns1:securityToken"/>
+</message>
+
+<message name="authenticationResponse">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<message name="getVersionRequest">
+</message>
+
+<message name="getVersionResponse">
+ <part name="result" element="ns1:result"/>
+</message>
+
+<message name="stop">
+</message>
+
+<message name="stopResponse">
+</message>
+
+<message name="reset">
+</message>
+
+<message name="resetResponse">
+</message>
+
+<message name="reboot">
+</message>
+
+<message name="rebootResponse">
+</message>
+
+<message name="listServicesRequest">
+</message>
+
+<message name="listServicesResponse">
+ <part name="array" element="ns1:array"/>
+</message>
+
+<message name="restoreFactorySettings">
+ <part name="mode" element="ns1:mode"/>
+</message>
+
+<message name="restoreFactorySettingsResponse">
+</message>
+
+<message name="instanceIDRequest">
+</message>
+
+<message name="instanceIDResponse">
+ <part name="instanceID" element="ns1:instanceID"/>
+</message>
+
+<message name="showConsole">
+</message>
+
+<message name="showConsoleResponse">
+</message>
+
+<message name="hideConsole">
+</message>
+
+<message name="hideConsoleResponse">
+</message>
+
+<message name="debugPrint">
+ <part name="debugMessage" element="ns1:debugMessage"/>
+</message>
+
+<message name="debugPrintResponse">
+</message>
+
+<portType name="HtiSystemPortType">
+ <operation name="authentication">
+  <documentation>Service definition of function ns1__authentication</documentation>
+  <input message="tns:authenticationRequest"/>
+  <output message="tns:authenticationResponse"/>
+ </operation>
+ <operation name="getVersion">
+  <documentation>Service definition of function ns1__getVersion</documentation>
+  <input message="tns:getVersionRequest"/>
+  <output message="tns:getVersionResponse"/>
+ </operation>
+ <operation name="stop">
+  <documentation>Service definition of function ns1__stop</documentation>
+  <input message="tns:stop"/>
+  <output message="tns:stopResponse"/>
+ </operation>
+ <operation name="reset">
+  <documentation>Service definition of function ns1__reset</documentation>
+  <input message="tns:reset"/>
+  <output message="tns:resetResponse"/>
+ </operation>
+ <operation name="reboot">
+  <documentation>Service definition of function ns1__reboot</documentation>
+  <input message="tns:reboot"/>
+  <output message="tns:rebootResponse"/>
+ </operation>
+ <operation name="listServices">
+  <documentation>Service definition of function ns1__listServices</documentation>
+  <input message="tns:listServicesRequest"/>
+  <output message="tns:listServicesResponse"/>
+ </operation>
+ <operation name="restoreFactorySettings">
+  <documentation>Service definition of function ns1__restoreFactorySettings</documentation>
+  <input message="tns:restoreFactorySettings"/>
+  <output message="tns:restoreFactorySettingsResponse"/>
+ </operation>
+ <operation name="instanceID">
+  <documentation>Service definition of function ns1__instanceID</documentation>
+  <input message="tns:instanceIDRequest"/>
+  <output message="tns:instanceIDResponse"/>
+ </operation>
+ <operation name="showConsole">
+  <documentation>Service definition of function ns1__showConsole</documentation>
+  <input message="tns:showConsole"/>
+  <output message="tns:showConsoleResponse"/>
+ </operation>
+ <operation name="hideConsole">
+  <documentation>Service definition of function ns1__hideConsole</documentation>
+  <input message="tns:hideConsole"/>
+  <output message="tns:hideConsoleResponse"/>
+ </operation>
+ <operation name="debugPrint">
+  <documentation>Service definition of function ns1__debugPrint</documentation>
+  <input message="tns:debugPrint"/>
+  <output message="tns:debugPrintResponse"/>
+ </operation>
+</portType>
+
+<binding name="HtiSystem" type="tns:HtiSystemPortType">
+ <SOAP:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+ <operation name="authentication">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="getVersion">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="stop">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="reset">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="reboot">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="listServices">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="restoreFactorySettings">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="instanceID">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="showConsole">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="hideConsole">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+ <operation name="debugPrint">
+  <SOAP:operation style="rpc" soapAction="HtiSystem"/>
+  <input>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </input>
+  <output>
+     <SOAP:body parts="parameters" use="literal" namespace="urn:hti"/>
+  </output>
+ </operation>
+</binding>
+
+<service name="HtiSystem">
+ <documentation>gSOAP 2.7.6b generated service definition</documentation>
+ <port name="HtiSystem" binding="tns:HtiSystem">
+  <SOAP:address location="http://localhost:2000"/>
+ </port>
+</service>
+
+</definitions>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/build.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,16 @@
+rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+rem All rights reserved.
+rem This component and the accompanying materials are made available
+rem under the terms of "Eclipse Public License v1.0"
+rem which accompanies this distribution, and is available
+rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+rem 
+rem Initial Contributors:
+rem Nokia Corporation - initial contribution.
+rem 
+rem Contributors:
+rem 
+rem Description:
+rem 
+del build.log
+devenv.exe /out build.log /rebuild Release HtiGateway.sln
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/env.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,15 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/envC.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1053 @@
+/* envC.cpp
+   Generated by gSOAP 2.7.6b from env.h
+   Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc. All Rights Reserved.
+   This part of the software is released under one of the following licenses:
+   GPL, the gSOAP public license, or Genivia's license for commercial use.
+*/
+
+#include "envH.h"
+
+SOAP_SOURCE_STAMP("@(#) envC.cpp ver 2.7.6b 2005-09-27 12:23:39 GMT")
+
+
+#ifndef WITH_NOGLOBAL
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serializeheader(struct soap *soap)
+{
+	if (soap->header)
+		soap_serialize_SOAP_ENV__Header(soap, soap->header);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_putheader(struct soap *soap)
+{
+	if (soap->header)
+	{	soap->part = SOAP_IN_HEADER;
+		soap_out_SOAP_ENV__Header(soap, "SOAP-ENV:Header", 0, soap->header, NULL);
+		soap->part = SOAP_END_HEADER;
+	}
+	return SOAP_OK;
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_getheader(struct soap *soap)
+{
+	soap->part = SOAP_IN_HEADER;
+	soap->header = soap_in_SOAP_ENV__Header(soap, "SOAP-ENV:Header", NULL, NULL);
+	soap->part = SOAP_END_HEADER;
+	return soap->header == NULL;
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_fault(struct soap *soap)
+{
+	if (!soap->fault)
+	{	soap->fault = (struct SOAP_ENV__Fault*)soap_malloc(soap, sizeof(struct SOAP_ENV__Fault));
+		soap_default_SOAP_ENV__Fault(soap, soap->fault);
+	}
+	if (soap->version == 2 && !soap->fault->SOAP_ENV__Code)
+	{	soap->fault->SOAP_ENV__Code = (struct SOAP_ENV__Code*)soap_malloc(soap, sizeof(struct SOAP_ENV__Code));
+		soap_default_SOAP_ENV__Code(soap, soap->fault->SOAP_ENV__Code);
+	}
+	if (soap->version == 2 && !soap->fault->SOAP_ENV__Reason)
+	{	soap->fault->SOAP_ENV__Reason = (struct SOAP_ENV__Reason*)soap_malloc(soap, sizeof(struct SOAP_ENV__Reason));
+		soap_default_SOAP_ENV__Reason(soap, soap->fault->SOAP_ENV__Reason);
+	}
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serializefault(struct soap *soap)
+{
+	if (soap->fault)
+		soap_serialize_SOAP_ENV__Fault(soap, soap->fault);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_putfault(struct soap *soap)
+{
+	if (soap->fault)
+		return soap_put_SOAP_ENV__Fault(soap, soap->fault, "SOAP-ENV:Fault", NULL);
+	return SOAP_OK;
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_getfault(struct soap *soap)
+{
+	return (soap->fault = soap_get_SOAP_ENV__Fault(soap, NULL, "SOAP-ENV:Fault", NULL)) == NULL;
+}
+
+SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultcode(struct soap *soap)
+{
+	soap_fault(soap);
+	if (soap->version == 2)
+		return (const char**)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Value;
+	return (const char**)&soap->fault->faultcode;
+}
+
+SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultsubcode(struct soap *soap)
+{
+	soap_fault(soap);
+	if (soap->version == 2)
+	{	if (!soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode)
+		{	soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode = (struct SOAP_ENV__Code*)soap_malloc(soap, sizeof(struct SOAP_ENV__Code));
+			soap_default_SOAP_ENV__Code(soap, soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode);
+		}
+		return (const char**)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode->SOAP_ENV__Value;
+	}
+	return (const char**)&soap->fault->faultcode;
+}
+
+SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultstring(struct soap *soap)
+{
+	soap_fault(soap);
+	if (soap->version == 2)
+		return (const char**)&soap->fault->SOAP_ENV__Reason->SOAP_ENV__Text;
+	return (const char**)&soap->fault->faultstring;
+}
+
+SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultdetail(struct soap *soap)
+{
+	soap_fault(soap);
+	if (soap->version == 1)
+	{	if (!soap->fault->detail)
+		{	soap->fault->detail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
+			soap_default_SOAP_ENV__Detail(soap, soap->fault->detail);
+		}
+		return (const char**)&soap->fault->detail->__any;
+	}
+	if (!soap->fault->SOAP_ENV__Detail)
+	{	soap->fault->SOAP_ENV__Detail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
+		soap_default_SOAP_ENV__Detail(soap, soap->fault->SOAP_ENV__Detail);
+	}
+	return (const char**)&soap->fault->SOAP_ENV__Detail->__any;
+}
+
+#endif
+
+#ifndef WITH_NOIDREF
+SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap *soap)
+{
+	int t;
+	for (;;)
+		if (!soap_getelement(soap, &t))
+			if (soap->error || soap_ignore_element(soap))
+				break;
+	if (soap->error == SOAP_NO_TAG || soap->error == SOAP_EOF)
+		soap->error = SOAP_OK;
+	return soap->error;
+}
+#endif
+
+#ifndef WITH_NOIDREF
+SOAP_FMAC3 void * SOAP_FMAC4 soap_getelement(struct soap *soap, int *type)
+{
+	if (soap_peek_element(soap))
+		return NULL;
+	if (!*soap->id || !(*type = soap_lookup_type(soap, soap->id)))
+		*type = soap_lookup_type(soap, soap->href);
+	switch (*type)
+	{
+	case SOAP_TYPE_byte:
+		return soap_in_byte(soap, NULL, NULL, "xsd:byte");
+	case SOAP_TYPE_int:
+		return soap_in_int(soap, NULL, NULL, "xsd:int");
+	case SOAP_TYPE_SOAP_ENV__Reason:
+		return soap_in_SOAP_ENV__Reason(soap, NULL, NULL, "SOAP-ENV:Reason");
+	case SOAP_TYPE_PointerToSOAP_ENV__Reason:
+		return soap_in_PointerToSOAP_ENV__Reason(soap, NULL, NULL, "SOAP-ENV:Reason");
+	case SOAP_TYPE__QName:
+	{	char **s;
+		s = soap_in__QName(soap, NULL, NULL, "QName");
+		return s ? *s : NULL;
+	}
+	case SOAP_TYPE_string:
+	{	char **s;
+		s = soap_in_string(soap, NULL, NULL, "xsd:string");
+		return s ? *s : NULL;
+	}
+	default:
+	{	const char *t = soap->type;
+		if (!*t)
+			t = soap->tag;
+		if (!soap_match_tag(soap, t, "xsd:byte"))
+		{	*type = SOAP_TYPE_byte;
+			return soap_in_byte(soap, NULL, NULL, NULL);
+		}
+		if (!soap_match_tag(soap, t, "xsd:int"))
+		{	*type = SOAP_TYPE_int;
+			return soap_in_int(soap, NULL, NULL, NULL);
+		}
+		if (!soap_match_tag(soap, t, "SOAP-ENV:Reason"))
+		{	*type = SOAP_TYPE_SOAP_ENV__Reason;
+			return soap_in_SOAP_ENV__Reason(soap, NULL, NULL, NULL);
+		}
+		if (!soap_match_tag(soap, t, "QName"))
+		{	char **s;
+			*type = SOAP_TYPE__QName;
+			s = soap_in__QName(soap, NULL, NULL, NULL);
+			return s ? *s : NULL;
+		}
+		if (!soap_match_tag(soap, t, "xsd:string"))
+		{	char **s;
+			*type = SOAP_TYPE_string;
+			s = soap_in_string(soap, NULL, NULL, NULL);
+			return s ? *s : NULL;
+		}
+	}
+	}
+	soap->error = SOAP_TAG_MISMATCH;
+	return NULL;
+}
+#endif
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_ignore_element(struct soap *soap)
+{
+	if (!soap_peek_element(soap))
+	{	int t;
+		if (soap->mustUnderstand && !soap->other)
+			return soap->error = SOAP_MUSTUNDERSTAND;
+		if (((soap->mode & SOAP_XML_STRICT) && soap->part != SOAP_IN_HEADER) || !soap_match_tag(soap, soap->tag, "SOAP-ENV:"))
+			return soap->error = SOAP_TAG_MISMATCH;
+		if (!*soap->id || !soap_getelement(soap, &t))
+		{	soap->peeked = 0;
+			DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unknown element '%s' (level=%u, %d)\n", soap->tag, soap->level, soap->body));
+			if (soap->fignore)
+				soap->error = soap->fignore(soap, soap->tag);
+			else
+				soap->error = SOAP_OK;
+			DBGLOG(TEST, if (!soap->error) SOAP_MESSAGE(fdebug, "IGNORING element '%s'\n", soap->tag));
+			if (!soap->error && soap->body)
+			{	soap->level++;
+				while (!soap_ignore_element(soap))
+					;
+				if (soap->error == SOAP_NO_TAG)
+					soap->error = soap_element_end_in(soap, NULL);
+			}
+		}
+	}
+	return soap->error;
+}
+
+#ifndef WITH_NOIDREF
+SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap *soap)
+{
+	int i;
+	struct soap_plist *pp;
+	if (soap->version == 1 && soap->encodingStyle && !(soap->mode & (SOAP_XML_TREE | SOAP_XML_GRAPH)))
+		for (i = 0; i < SOAP_PTRHASH; i++)
+			for (pp = soap->pht[i]; pp; pp = pp->next)
+				if (pp->mark1 == 2 || pp->mark2 == 2)
+					if (soap_putelement(soap, pp->ptr, "id", pp->id, pp->type))
+						return soap->error;
+	return SOAP_OK;
+}
+#endif
+
+#ifndef WITH_NOIDREF
+SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap *soap, const void *ptr, const char *tag, int id, int type)
+{
+	switch (type)
+	{
+	case SOAP_TYPE_byte:
+		return soap_out_byte(soap, tag, id, (const char *)ptr, "xsd:byte");
+	case SOAP_TYPE_int:
+		return soap_out_int(soap, tag, id, (const int *)ptr, "xsd:int");
+	case SOAP_TYPE_SOAP_ENV__Reason:
+		return soap_out_SOAP_ENV__Reason(soap, tag, id, (const struct SOAP_ENV__Reason *)ptr, "SOAP-ENV:Reason");
+	case SOAP_TYPE_PointerToSOAP_ENV__Reason:
+		return soap_out_PointerToSOAP_ENV__Reason(soap, tag, id, (struct SOAP_ENV__Reason *const*)ptr, "SOAP-ENV:Reason");
+	case SOAP_TYPE__QName:
+		return soap_out_string(soap, "QName", id, (char**)&ptr, NULL);
+	case SOAP_TYPE_string:
+		return soap_out_string(soap, tag, id, (char**)&ptr, "xsd:string");
+	}
+	return SOAP_OK;
+}
+#endif
+
+#ifndef WITH_NOIDREF
+SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap *soap, const void *ptr, int type)
+{
+	(void)soap; (void)ptr; (void)type; /* appease -Wall -Werror */
+	switch (type)
+	{
+	case SOAP_TYPE_SOAP_ENV__Reason:
+		soap_serialize_SOAP_ENV__Reason(soap, (const struct SOAP_ENV__Reason *)ptr);
+		break;
+	case SOAP_TYPE_PointerToSOAP_ENV__Reason:
+		soap_serialize_PointerToSOAP_ENV__Reason(soap, (struct SOAP_ENV__Reason *const*)ptr);
+		break;
+	case SOAP_TYPE__QName:
+		soap_serialize_string(soap, (char**)&ptr);
+		break;
+	case SOAP_TYPE_string:
+		soap_serialize_string(soap, (char**)&ptr);
+		break;
+	}
+}
+#endif
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap *soap, char *a)
+{
+(void)soap; /* appease -Wall -Werror */
+#ifdef SOAP_DEFAULT_byte
+	*a = SOAP_DEFAULT_byte;
+#else
+	*a = (char)0;
+#endif
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_byte(struct soap *soap, const char *a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_byte);
+	if (soap_out_byte(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap *soap, const char *tag, int id, const char *a, const char *type)
+{
+	return soap_outbyte(soap, tag, id, a, type, SOAP_TYPE_byte);
+}
+
+SOAP_FMAC3 char * SOAP_FMAC4 soap_get_byte(struct soap *soap, char *p, const char *tag, const char *type)
+{
+	if ((p = soap_in_byte(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 char * SOAP_FMAC4 soap_in_byte(struct soap *soap, const char *tag, char *a, const char *type)
+{
+	return soap_inbyte(soap, tag, a, type, SOAP_TYPE_byte);
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap *soap, int *a)
+{
+(void)soap; /* appease -Wall -Werror */
+#ifdef SOAP_DEFAULT_int
+	*a = SOAP_DEFAULT_int;
+#else
+	*a = (int)0;
+#endif
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_int(struct soap *soap, const int *a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_int);
+	if (soap_out_int(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap *soap, const char *tag, int id, const int *a, const char *type)
+{
+	return soap_outint(soap, tag, id, a, type, SOAP_TYPE_int);
+}
+
+SOAP_FMAC3 int * SOAP_FMAC4 soap_get_int(struct soap *soap, int *p, const char *tag, const char *type)
+{
+	if ((p = soap_in_int(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 int * SOAP_FMAC4 soap_in_int(struct soap *soap, const char *tag, int *a, const char *type)
+{
+	return soap_inint(soap, tag, a, type, SOAP_TYPE_int);
+}
+
+#ifndef WITH_NOGLOBAL
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap *soap, const struct SOAP_ENV__Fault *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	soap_serialize__QName(soap, &a->faultcode);
+	soap_serialize_string(soap, &a->faultstring);
+	soap_serialize_string(soap, &a->faultactor);
+	soap_serialize_PointerToSOAP_ENV__Detail(soap, &a->detail);
+	soap_serialize_PointerToSOAP_ENV__Code(soap, &a->SOAP_ENV__Code);
+	soap_serialize_PointerToSOAP_ENV__Reason(soap, &a->SOAP_ENV__Reason);
+	soap_serialize_string(soap, &a->SOAP_ENV__Node);
+	soap_serialize_string(soap, &a->SOAP_ENV__Role);
+	soap_serialize_PointerToSOAP_ENV__Detail(soap, &a->SOAP_ENV__Detail);
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	soap_default__QName(soap, &a->faultcode);
+	soap_default_string(soap, &a->faultstring);
+	soap_default_string(soap, &a->faultactor);
+	a->detail = NULL;
+	a->SOAP_ENV__Code = NULL;
+	a->SOAP_ENV__Reason = NULL;
+	soap_default_string(soap, &a->SOAP_ENV__Node);
+	soap_default_string(soap, &a->SOAP_ENV__Role);
+	a->SOAP_ENV__Detail = NULL;
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Fault(struct soap *soap, const struct SOAP_ENV__Fault *a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Fault);
+	if (soap_out_SOAP_ENV__Fault(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Fault *a, const char *type)
+{
+	const char *soap_tmp_faultcode = soap_QName2s(soap, a->faultcode);
+	soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Fault), type);
+	soap_out__QName(soap, "faultcode", -1, (char*const*)&soap_tmp_faultcode, "");
+	soap_out_string(soap, "faultstring", -1, &a->faultstring, "");
+	soap_out_string(soap, "faultactor", -1, &a->faultactor, "");
+	soap_out_PointerToSOAP_ENV__Detail(soap, "detail", -1, &a->detail, "");
+	soap_out_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Code", -1, &a->SOAP_ENV__Code, "");
+	soap_out_PointerToSOAP_ENV__Reason(soap, "SOAP-ENV:Reason", -1, &a->SOAP_ENV__Reason, "");
+	soap_out_string(soap, "SOAP-ENV:Node", -1, &a->SOAP_ENV__Node, "");
+	soap_out_string(soap, "SOAP-ENV:Role", -1, &a->SOAP_ENV__Role, "");
+	soap_out_PointerToSOAP_ENV__Detail(soap, "SOAP-ENV:Detail", -1, &a->SOAP_ENV__Detail, "");
+	soap_element_end_out(soap, tag);
+	return SOAP_OK;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_get_SOAP_ENV__Fault(struct soap *soap, struct SOAP_ENV__Fault *p, const char *tag, const char *type)
+{
+	if ((p = soap_in_SOAP_ENV__Fault(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_in_SOAP_ENV__Fault(struct soap *soap, const char *tag, struct SOAP_ENV__Fault *a, const char *type)
+{
+	short soap_flag_faultcode = 1, soap_flag_faultstring = 1, soap_flag_faultactor = 1, soap_flag_detail = 1, soap_flag_SOAP_ENV__Code = 1, soap_flag_SOAP_ENV__Reason = 1, soap_flag_SOAP_ENV__Node = 1, soap_flag_SOAP_ENV__Role = 1, soap_flag_SOAP_ENV__Detail = 1;
+	if (soap_element_begin_in(soap, tag, 0))
+		return NULL;
+	if (*soap->type && soap_match_tag(soap, soap->type, type))
+	{	soap->error = SOAP_TYPE;
+		return NULL;
+	}
+	a = (struct SOAP_ENV__Fault *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Fault, sizeof(struct SOAP_ENV__Fault), 0, NULL, NULL, NULL);
+	if (!a)
+		return NULL;
+	soap_default_SOAP_ENV__Fault(soap, a);
+	if (soap->body && !*soap->href)
+	{
+		for (;;)
+		{	soap->error = SOAP_TAG_MISMATCH;
+			if (soap_flag_faultcode && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG))
+				if (soap_in__QName(soap, "faultcode", &a->faultcode, ""))
+				{	soap_flag_faultcode--;
+					continue;
+				}
+			if (soap_flag_faultstring && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG))
+				if (soap_in_string(soap, "faultstring", &a->faultstring, "xsd:string"))
+				{	soap_flag_faultstring--;
+					continue;
+				}
+			if (soap_flag_faultactor && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG))
+				if (soap_in_string(soap, "faultactor", &a->faultactor, "xsd:string"))
+				{	soap_flag_faultactor--;
+					continue;
+				}
+			if (soap_flag_detail && soap->error == SOAP_TAG_MISMATCH)
+				if (soap_in_PointerToSOAP_ENV__Detail(soap, "detail", &a->detail, ""))
+				{	soap_flag_detail--;
+					continue;
+				}
+			if (soap_flag_SOAP_ENV__Code && soap->error == SOAP_TAG_MISMATCH)
+				if (soap_in_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Code", &a->SOAP_ENV__Code, ""))
+				{	soap_flag_SOAP_ENV__Code--;
+					continue;
+				}
+			if (soap_flag_SOAP_ENV__Reason && soap->error == SOAP_TAG_MISMATCH)
+				if (soap_in_PointerToSOAP_ENV__Reason(soap, "SOAP-ENV:Reason", &a->SOAP_ENV__Reason, ""))
+				{	soap_flag_SOAP_ENV__Reason--;
+					continue;
+				}
+			if (soap_flag_SOAP_ENV__Node && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG))
+				if (soap_in_string(soap, "SOAP-ENV:Node", &a->SOAP_ENV__Node, "xsd:string"))
+				{	soap_flag_SOAP_ENV__Node--;
+					continue;
+				}
+			if (soap_flag_SOAP_ENV__Role && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG))
+				if (soap_in_string(soap, "SOAP-ENV:Role", &a->SOAP_ENV__Role, "xsd:string"))
+				{	soap_flag_SOAP_ENV__Role--;
+					continue;
+				}
+			if (soap_flag_SOAP_ENV__Detail && soap->error == SOAP_TAG_MISMATCH)
+				if (soap_in_PointerToSOAP_ENV__Detail(soap, "SOAP-ENV:Detail", &a->SOAP_ENV__Detail, ""))
+				{	soap_flag_SOAP_ENV__Detail--;
+					continue;
+				}
+			if (soap->error == SOAP_TAG_MISMATCH)
+				soap->error = soap_ignore_element(soap);
+			if (soap->error == SOAP_NO_TAG)
+				break;
+			if (soap->error)
+				return NULL;
+		}
+		if (soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	else
+	{	a = (struct SOAP_ENV__Fault *)soap_id_forward(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Fault, 0, sizeof(struct SOAP_ENV__Fault), 0, NULL);
+		if (soap->body && soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	return a;
+}
+
+#endif
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap *soap, const struct SOAP_ENV__Reason *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	soap_serialize_string(soap, &a->SOAP_ENV__Text);
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	soap_default_string(soap, &a->SOAP_ENV__Text);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Reason(struct soap *soap, const struct SOAP_ENV__Reason *a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Reason);
+	if (soap_out_SOAP_ENV__Reason(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Reason *a, const char *type)
+{
+	soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Reason), type);
+	soap_out_string(soap, "SOAP-ENV:Text", -1, &a->SOAP_ENV__Text, "");
+	soap_element_end_out(soap, tag);
+	return SOAP_OK;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_get_SOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *p, const char *tag, const char *type)
+{
+	if ((p = soap_in_SOAP_ENV__Reason(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_in_SOAP_ENV__Reason(struct soap *soap, const char *tag, struct SOAP_ENV__Reason *a, const char *type)
+{
+	short soap_flag_SOAP_ENV__Text = 1;
+	if (soap_element_begin_in(soap, tag, 0))
+		return NULL;
+	if (*soap->type && soap_match_tag(soap, soap->type, type))
+	{	soap->error = SOAP_TYPE;
+		return NULL;
+	}
+	a = (struct SOAP_ENV__Reason *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), 0, NULL, NULL, NULL);
+	if (!a)
+		return NULL;
+	soap_default_SOAP_ENV__Reason(soap, a);
+	if (soap->body && !*soap->href)
+	{
+		for (;;)
+		{	soap->error = SOAP_TAG_MISMATCH;
+			if (soap_flag_SOAP_ENV__Text && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG))
+				if (soap_in_string(soap, "SOAP-ENV:Text", &a->SOAP_ENV__Text, "xsd:string"))
+				{	soap_flag_SOAP_ENV__Text--;
+					continue;
+				}
+			if (soap->error == SOAP_TAG_MISMATCH)
+				soap->error = soap_ignore_element(soap);
+			if (soap->error == SOAP_NO_TAG)
+				break;
+			if (soap->error)
+				return NULL;
+		}
+		if (soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	else
+	{	a = (struct SOAP_ENV__Reason *)soap_id_forward(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Reason, 0, sizeof(struct SOAP_ENV__Reason), 0, NULL);
+		if (soap->body && soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	return a;
+}
+
+#ifndef WITH_NOGLOBAL
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap *soap, const struct SOAP_ENV__Detail *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	soap_markelement(soap, a->fault, a->__type);
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	a->__type = 0;
+	a->fault = NULL;
+	a->__any = NULL;
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Detail(struct soap *soap, const struct SOAP_ENV__Detail *a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Detail);
+	if (soap_out_SOAP_ENV__Detail(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Detail *a, const char *type)
+{
+	soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Detail), type);
+	soap_putelement(soap, a->fault, "fault", -1, a->__type);
+	soap_outliteral(soap, "-any", &a->__any);
+	soap_element_end_out(soap, tag);
+	return SOAP_OK;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_get_SOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *p, const char *tag, const char *type)
+{
+	if ((p = soap_in_SOAP_ENV__Detail(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_in_SOAP_ENV__Detail(struct soap *soap, const char *tag, struct SOAP_ENV__Detail *a, const char *type)
+{
+	short soap_flag_fault = 1, soap_flag___any = 1;
+	if (soap_element_begin_in(soap, tag, 0))
+		return NULL;
+	if (*soap->type && soap_match_tag(soap, soap->type, type))
+	{	soap->error = SOAP_TYPE;
+		return NULL;
+	}
+	a = (struct SOAP_ENV__Detail *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), 0, NULL, NULL, NULL);
+	if (!a)
+		return NULL;
+	soap_default_SOAP_ENV__Detail(soap, a);
+	if (soap->body && !*soap->href)
+	{
+		for (;;)
+		{	soap->error = SOAP_TAG_MISMATCH;
+			if (soap_flag_fault && soap->error == SOAP_TAG_MISMATCH)
+				if ((a->fault = soap_getelement(soap, &a->__type)))
+				{	soap_flag_fault = 0;
+					continue;
+				}
+			if (soap_flag___any && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG))
+				if (soap_inliteral(soap, "-any", &a->__any))
+				{	soap_flag___any--;
+					continue;
+				}
+			if (soap->error == SOAP_TAG_MISMATCH)
+				soap->error = soap_ignore_element(soap);
+			if (soap->error == SOAP_NO_TAG)
+				break;
+			if (soap->error)
+				return NULL;
+		}
+		if (soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	else
+	{	a = (struct SOAP_ENV__Detail *)soap_id_forward(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Detail, 0, sizeof(struct SOAP_ENV__Detail), 0, NULL);
+		if (soap->body && soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	return a;
+}
+
+#endif
+
+#ifndef WITH_NOGLOBAL
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap *soap, const struct SOAP_ENV__Code *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	soap_serialize__QName(soap, &a->SOAP_ENV__Value);
+	soap_serialize_PointerToSOAP_ENV__Code(soap, &a->SOAP_ENV__Subcode);
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	soap_default__QName(soap, &a->SOAP_ENV__Value);
+	a->SOAP_ENV__Subcode = NULL;
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Code(struct soap *soap, const struct SOAP_ENV__Code *a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Code);
+	if (soap_out_SOAP_ENV__Code(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Code *a, const char *type)
+{
+	const char *soap_tmp_SOAP_ENV__Value = soap_QName2s(soap, a->SOAP_ENV__Value);
+	soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Code), type);
+	soap_out__QName(soap, "SOAP-ENV:Value", -1, (char*const*)&soap_tmp_SOAP_ENV__Value, "");
+	soap_out_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Subcode", -1, &a->SOAP_ENV__Subcode, "");
+	soap_element_end_out(soap, tag);
+	return SOAP_OK;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_get_SOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *p, const char *tag, const char *type)
+{
+	if ((p = soap_in_SOAP_ENV__Code(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_in_SOAP_ENV__Code(struct soap *soap, const char *tag, struct SOAP_ENV__Code *a, const char *type)
+{
+	short soap_flag_SOAP_ENV__Value = 1, soap_flag_SOAP_ENV__Subcode = 1;
+	if (soap_element_begin_in(soap, tag, 0))
+		return NULL;
+	if (*soap->type && soap_match_tag(soap, soap->type, type))
+	{	soap->error = SOAP_TYPE;
+		return NULL;
+	}
+	a = (struct SOAP_ENV__Code *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), 0, NULL, NULL, NULL);
+	if (!a)
+		return NULL;
+	soap_default_SOAP_ENV__Code(soap, a);
+	if (soap->body && !*soap->href)
+	{
+		for (;;)
+		{	soap->error = SOAP_TAG_MISMATCH;
+			if (soap_flag_SOAP_ENV__Value && (soap->error == SOAP_TAG_MISMATCH || soap->error == SOAP_NO_TAG))
+				if (soap_in__QName(soap, "SOAP-ENV:Value", &a->SOAP_ENV__Value, ""))
+				{	soap_flag_SOAP_ENV__Value--;
+					continue;
+				}
+			if (soap_flag_SOAP_ENV__Subcode && soap->error == SOAP_TAG_MISMATCH)
+				if (soap_in_PointerToSOAP_ENV__Code(soap, "SOAP-ENV:Subcode", &a->SOAP_ENV__Subcode, ""))
+				{	soap_flag_SOAP_ENV__Subcode--;
+					continue;
+				}
+			if (soap->error == SOAP_TAG_MISMATCH)
+				soap->error = soap_ignore_element(soap);
+			if (soap->error == SOAP_NO_TAG)
+				break;
+			if (soap->error)
+				return NULL;
+		}
+		if (soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	else
+	{	a = (struct SOAP_ENV__Code *)soap_id_forward(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Code, 0, sizeof(struct SOAP_ENV__Code), 0, NULL);
+		if (soap->body && soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	return a;
+}
+
+#endif
+
+#ifndef WITH_NOGLOBAL
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap *soap, const struct SOAP_ENV__Header *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	/* transient dummy skipped */
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *a)
+{
+	(void)soap; (void)a; /* appease -Wall -Werror */
+	/* transient dummy skipped */
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Header(struct soap *soap, const struct SOAP_ENV__Header *a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_SOAP_ENV__Header);
+	if (soap_out_SOAP_ENV__Header(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Header *a, const char *type)
+{
+	soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Header), type);
+	/* transient dummy skipped */
+	soap_element_end_out(soap, tag);
+	return SOAP_OK;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_get_SOAP_ENV__Header(struct soap *soap, struct SOAP_ENV__Header *p, const char *tag, const char *type)
+{
+	if ((p = soap_in_SOAP_ENV__Header(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_in_SOAP_ENV__Header(struct soap *soap, const char *tag, struct SOAP_ENV__Header *a, const char *type)
+{;
+	if (soap_element_begin_in(soap, tag, 0))
+		return NULL;
+	if (*soap->type && soap_match_tag(soap, soap->type, type))
+	{	soap->error = SOAP_TYPE;
+		return NULL;
+	}
+	a = (struct SOAP_ENV__Header *)soap_id_enter(soap, soap->id, a, SOAP_TYPE_SOAP_ENV__Header, sizeof(struct SOAP_ENV__Header), 0, NULL, NULL, NULL);
+	if (!a)
+		return NULL;
+	soap_default_SOAP_ENV__Header(soap, a);
+	if (soap->body && !*soap->href)
+	{
+		for (;;)
+		{	soap->error = SOAP_TAG_MISMATCH;
+		/* transient dummy skipped */
+			if (soap->error == SOAP_TAG_MISMATCH)
+				soap->error = soap_ignore_element(soap);
+			if (soap->error == SOAP_NO_TAG)
+				break;
+			if (soap->error)
+				return NULL;
+		}
+		if (soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	else
+	{	a = (struct SOAP_ENV__Header *)soap_id_forward(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Header, 0, sizeof(struct SOAP_ENV__Header), 0, NULL);
+		if (soap->body && soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	return a;
+}
+
+#endif
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *const*a)
+{
+	if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Reason))
+		soap_serialize_SOAP_ENV__Reason(soap, *a);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason *const*a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Reason);
+	if (soap_out_PointerToSOAP_ENV__Reason(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Reason(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Reason *const*a, const char *type)
+{
+	id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Reason);
+	if (id < 0)
+		return soap->error;
+	return soap_out_SOAP_ENV__Reason(soap, tag, id, *a, type);
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Reason(struct soap *soap, struct SOAP_ENV__Reason **p, const char *tag, const char *type)
+{
+	if ((p = soap_in_PointerToSOAP_ENV__Reason(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reason(struct soap *soap, const char *tag, struct SOAP_ENV__Reason **a, const char *type)
+{
+	if (soap_element_begin_in(soap, tag, 1))
+		return NULL;
+	if (!a)
+		if (!(a = (struct SOAP_ENV__Reason **)soap_malloc(soap, sizeof(struct SOAP_ENV__Reason *))))
+			return NULL;
+	*a = NULL;
+	if (!soap->null && *soap->href != '#')
+	{	soap_revert(soap);
+		if (!(*a = soap_in_SOAP_ENV__Reason(soap, tag, *a, type)))
+			return NULL;
+	}
+	else
+	{	a = (struct SOAP_ENV__Reason **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Reason, sizeof(struct SOAP_ENV__Reason), 0);
+		if (soap->body && soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	return a;
+}
+
+#ifndef WITH_NOGLOBAL
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *const*a)
+{
+	if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Detail))
+		soap_serialize_SOAP_ENV__Detail(soap, *a);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail *const*a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Detail);
+	if (soap_out_PointerToSOAP_ENV__Detail(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Detail(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Detail *const*a, const char *type)
+{
+	id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Detail);
+	if (id < 0)
+		return soap->error;
+	return soap_out_SOAP_ENV__Detail(soap, tag, id, *a, type);
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Detail(struct soap *soap, struct SOAP_ENV__Detail **p, const char *tag, const char *type)
+{
+	if ((p = soap_in_PointerToSOAP_ENV__Detail(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Detail(struct soap *soap, const char *tag, struct SOAP_ENV__Detail **a, const char *type)
+{
+	if (soap_element_begin_in(soap, tag, 1))
+		return NULL;
+	if (!a)
+		if (!(a = (struct SOAP_ENV__Detail **)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail *))))
+			return NULL;
+	*a = NULL;
+	if (!soap->null && *soap->href != '#')
+	{	soap_revert(soap);
+		if (!(*a = soap_in_SOAP_ENV__Detail(soap, tag, *a, type)))
+			return NULL;
+	}
+	else
+	{	a = (struct SOAP_ENV__Detail **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Detail, sizeof(struct SOAP_ENV__Detail), 0);
+		if (soap->body && soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	return a;
+}
+
+#endif
+
+#ifndef WITH_NOGLOBAL
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *const*a)
+{
+	if (!soap_reference(soap, *a, SOAP_TYPE_SOAP_ENV__Code))
+		soap_serialize_SOAP_ENV__Code(soap, *a);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code *const*a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_PointerToSOAP_ENV__Code);
+	if (soap_out_PointerToSOAP_ENV__Code(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Code(struct soap *soap, const char *tag, int id, struct SOAP_ENV__Code *const*a, const char *type)
+{
+	id = soap_element_id(soap, tag, id, *a, NULL, 0, type, SOAP_TYPE_SOAP_ENV__Code);
+	if (id < 0)
+		return soap->error;
+	return soap_out_SOAP_ENV__Code(soap, tag, id, *a, type);
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Code(struct soap *soap, struct SOAP_ENV__Code **p, const char *tag, const char *type)
+{
+	if ((p = soap_in_PointerToSOAP_ENV__Code(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(struct soap *soap, const char *tag, struct SOAP_ENV__Code **a, const char *type)
+{
+	if (soap_element_begin_in(soap, tag, 1))
+		return NULL;
+	if (!a)
+		if (!(a = (struct SOAP_ENV__Code **)soap_malloc(soap, sizeof(struct SOAP_ENV__Code *))))
+			return NULL;
+	*a = NULL;
+	if (!soap->null && *soap->href != '#')
+	{	soap_revert(soap);
+		if (!(*a = soap_in_SOAP_ENV__Code(soap, tag, *a, type)))
+			return NULL;
+	}
+	else
+	{	a = (struct SOAP_ENV__Code **)soap_id_lookup(soap, soap->href, (void**)a, SOAP_TYPE_SOAP_ENV__Code, sizeof(struct SOAP_ENV__Code), 0);
+		if (soap->body && soap_element_end_in(soap, tag))
+			return NULL;
+	}
+	return a;
+}
+
+#endif
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default__QName(struct soap *soap, char **a)
+{	soap_default_string(soap, a);
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize__QName(struct soap *soap, char *const*a)
+{	soap_serialize_string(soap, a);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put__QName(struct soap *soap, char *const*a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE__QName);
+	if (soap_out__QName(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out__QName(struct soap *soap, const char *tag, int id, char *const*a, const char *type)
+{
+	return soap_outstring(soap, tag, id, a, type, SOAP_TYPE__QName);
+}
+
+SOAP_FMAC3 char ** SOAP_FMAC4 soap_get__QName(struct soap *soap, char **p, const char *tag, const char *type)
+{
+	if ((p = soap_in__QName(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 char * * SOAP_FMAC4 soap_in__QName(struct soap *soap, const char *tag, char **a, const char *type)
+{
+	return soap_instring(soap, tag, a, type, SOAP_TYPE__QName, 2, -1, -1);
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_string(struct soap *soap, char **a)
+{
+(void)soap; /* appease -Wall -Werror */
+#ifdef SOAP_DEFAULT_string
+	*a = SOAP_DEFAULT_string;
+#else
+	*a = (char *)0;
+#endif
+}
+
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_string(struct soap *soap, char *const*a)
+{
+	soap_reference(soap, *a, SOAP_TYPE_string);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_string(struct soap *soap, char *const*a, const char *tag, const char *type)
+{
+	register int id = soap_embed(soap, (void*)a, NULL, 0, tag, SOAP_TYPE_string);
+	if (soap_out_string(soap, tag, id, a, type))
+		return soap->error;
+	return soap_putindependent(soap);
+}
+
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_string(struct soap *soap, const char *tag, int id, char *const*a, const char *type)
+{
+	return soap_outstring(soap, tag, id, a, type, SOAP_TYPE_string);
+}
+
+SOAP_FMAC3 char ** SOAP_FMAC4 soap_get_string(struct soap *soap, char **p, const char *tag, const char *type)
+{
+	if ((p = soap_in_string(soap, tag, p, type)))
+		soap_getindependent(soap);
+	return p;
+}
+
+SOAP_FMAC3 char * * SOAP_FMAC4 soap_in_string(struct soap *soap, const char *tag, char **a, const char *type)
+{
+	return soap_instring(soap, tag, a, type, SOAP_TYPE_string, 1, -1, -1);
+}
+
+/* End of envC.cpp */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/envClient.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,12 @@
+/* envClient.cpp
+   Generated by gSOAP 2.7.6b from env.h
+   Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc. All Rights Reserved.
+   This part of the software is released under one of the following licenses:
+   GPL, the gSOAP public license, or Genivia's license for commercial use.
+*/
+#include "envH.h"
+
+SOAP_SOURCE_STAMP("@(#) envClient.cpp ver 2.7.6b 2005-09-27 12:23:39 GMT")
+
+
+/* End of envClient.cpp */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/envClientLib.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,14 @@
+/* envClientLib.cpp
+   Generated by gSOAP 2.7.6b from env.h
+   Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc. All Rights Reserved.
+   This part of the software is released under one of the following licenses:
+   GPL, the gSOAP public license, or Genivia's license for commercial use.
+*/
+#ifndef WITH_NOGLOBAL
+#define WITH_NOGLOBAL
+#endif
+#define SOAP_FMAC3 static
+#include "envC.cpp"
+#include "envClient.cpp"
+
+/* End of envClientLib.cpp */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/envH.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,161 @@
+/* envH.h
+   Generated by gSOAP 2.7.6b from env.h
+   Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc. All Rights Reserved.
+   This part of the software is released under one of the following licenses:
+   GPL, the gSOAP public license, or Genivia's license for commercial use.
+*/
+
+#ifndef envH_H
+#define envH_H
+#include "envStub.h"
+SOAP_FMAC3 int SOAP_FMAC4 soap_ignore_element(struct soap*);
+#ifndef WITH_NOIDREF
+SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap*);
+SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap*, const void*, int);
+SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap*, const void*, const char*, int, int);
+SOAP_FMAC3 void * SOAP_FMAC4 soap_getelement(struct soap*, int*);
+#endif
+
+#ifndef SOAP_TYPE_byte
+#define SOAP_TYPE_byte (2)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap*, char *);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_byte(struct soap*, const char *, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap*, const char*, int, const char *, const char*);
+SOAP_FMAC3 char * SOAP_FMAC4 soap_get_byte(struct soap*, char *, const char*, const char*);
+SOAP_FMAC3 char * SOAP_FMAC4 soap_in_byte(struct soap*, const char*, char *, const char*);
+
+#ifndef SOAP_TYPE_int
+#define SOAP_TYPE_int (1)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap*, int *);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_int(struct soap*, const int *, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap*, const char*, int, const int *, const char*);
+SOAP_FMAC3 int * SOAP_FMAC4 soap_get_int(struct soap*, int *, const char*, const char*);
+SOAP_FMAC3 int * SOAP_FMAC4 soap_in_int(struct soap*, const char*, int *, const char*);
+
+#ifndef WITH_NOGLOBAL
+
+#ifndef SOAP_TYPE_SOAP_ENV__Fault
+#define SOAP_TYPE_SOAP_ENV__Fault (13)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap*, const struct SOAP_ENV__Fault *);
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault *);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Fault(struct soap*, const struct SOAP_ENV__Fault *, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap*, const char*, int, const struct SOAP_ENV__Fault *, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_get_SOAP_ENV__Fault(struct soap*, struct SOAP_ENV__Fault *, const char*, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Fault * SOAP_FMAC4 soap_in_SOAP_ENV__Fault(struct soap*, const char*, struct SOAP_ENV__Fault *, const char*);
+
+#endif
+
+#ifndef SOAP_TYPE_SOAP_ENV__Reason
+#define SOAP_TYPE_SOAP_ENV__Reason (12)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap*, const struct SOAP_ENV__Reason *);
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Reason(struct soap*, const struct SOAP_ENV__Reason *, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap*, const char*, int, const struct SOAP_ENV__Reason *, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_get_SOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *, const char*, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Reason * SOAP_FMAC4 soap_in_SOAP_ENV__Reason(struct soap*, const char*, struct SOAP_ENV__Reason *, const char*);
+
+#ifndef WITH_NOGLOBAL
+
+#ifndef SOAP_TYPE_SOAP_ENV__Detail
+#define SOAP_TYPE_SOAP_ENV__Detail (11)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap*, const struct SOAP_ENV__Detail *);
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Detail(struct soap*, const struct SOAP_ENV__Detail *, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap*, const char*, int, const struct SOAP_ENV__Detail *, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_get_SOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *, const char*, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Detail * SOAP_FMAC4 soap_in_SOAP_ENV__Detail(struct soap*, const char*, struct SOAP_ENV__Detail *, const char*);
+
+#endif
+
+#ifndef WITH_NOGLOBAL
+
+#ifndef SOAP_TYPE_SOAP_ENV__Code
+#define SOAP_TYPE_SOAP_ENV__Code (9)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap*, const struct SOAP_ENV__Code *);
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Code(struct soap*, const struct SOAP_ENV__Code *, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap*, const char*, int, const struct SOAP_ENV__Code *, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_get_SOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *, const char*, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Code * SOAP_FMAC4 soap_in_SOAP_ENV__Code(struct soap*, const char*, struct SOAP_ENV__Code *, const char*);
+
+#endif
+
+#ifndef WITH_NOGLOBAL
+
+#ifndef SOAP_TYPE_SOAP_ENV__Header
+#define SOAP_TYPE_SOAP_ENV__Header (8)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap*, const struct SOAP_ENV__Header *);
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header *);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_SOAP_ENV__Header(struct soap*, const struct SOAP_ENV__Header *, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap*, const char*, int, const struct SOAP_ENV__Header *, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_get_SOAP_ENV__Header(struct soap*, struct SOAP_ENV__Header *, const char*, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Header * SOAP_FMAC4 soap_in_SOAP_ENV__Header(struct soap*, const char*, struct SOAP_ENV__Header *, const char*);
+
+#endif
+
+#ifndef SOAP_TYPE_PointerToSOAP_ENV__Reason
+#define SOAP_TYPE_PointerToSOAP_ENV__Reason (15)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *const*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason *const*, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Reason(struct soap*, const char *, int, struct SOAP_ENV__Reason *const*, const char *);
+SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Reason(struct soap*, struct SOAP_ENV__Reason **, const char*, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reason(struct soap*, const char*, struct SOAP_ENV__Reason **, const char*);
+
+#ifndef WITH_NOGLOBAL
+
+#ifndef SOAP_TYPE_PointerToSOAP_ENV__Detail
+#define SOAP_TYPE_PointerToSOAP_ENV__Detail (14)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *const*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail *const*, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Detail(struct soap*, const char *, int, struct SOAP_ENV__Detail *const*, const char *);
+SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Detail(struct soap*, struct SOAP_ENV__Detail **, const char*, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Detail(struct soap*, const char*, struct SOAP_ENV__Detail **, const char*);
+
+#endif
+
+#ifndef WITH_NOGLOBAL
+
+#ifndef SOAP_TYPE_PointerToSOAP_ENV__Code
+#define SOAP_TYPE_PointerToSOAP_ENV__Code (10)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *const*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code *const*, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_PointerToSOAP_ENV__Code(struct soap*, const char *, int, struct SOAP_ENV__Code *const*, const char *);
+SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_get_PointerToSOAP_ENV__Code(struct soap*, struct SOAP_ENV__Code **, const char*, const char*);
+SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(struct soap*, const char*, struct SOAP_ENV__Code **, const char*);
+
+#endif
+
+#ifndef SOAP_TYPE__QName
+#define SOAP_TYPE__QName (5)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_default__QName(struct soap*, char **);
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize__QName(struct soap*, char *const*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put__QName(struct soap*, char *const*, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out__QName(struct soap*, const char*, int, char*const*, const char*);
+SOAP_FMAC3 char ** SOAP_FMAC4 soap_get__QName(struct soap*, char **, const char*, const char*);
+SOAP_FMAC3 char * * SOAP_FMAC4 soap_in__QName(struct soap*, const char*, char **, const char*);
+
+#ifndef SOAP_TYPE_string
+#define SOAP_TYPE_string (3)
+#endif
+SOAP_FMAC3 void SOAP_FMAC4 soap_default_string(struct soap*, char **);
+SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_string(struct soap*, char *const*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_put_string(struct soap*, char *const*, const char*, const char*);
+SOAP_FMAC3 int SOAP_FMAC4 soap_out_string(struct soap*, const char*, int, char*const*, const char*);
+SOAP_FMAC3 char ** SOAP_FMAC4 soap_get_string(struct soap*, char **, const char*, const char*);
+SOAP_FMAC3 char * * SOAP_FMAC4 soap_in_string(struct soap*, const char*, char **, const char*);
+
+#endif
+
+/* End of envH.h */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/envServer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,78 @@
+/* envServer.cpp
+   Generated by gSOAP 2.7.6b from env.h
+   Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc. All Rights Reserved.
+   This part of the software is released under one of the following licenses:
+   GPL, the gSOAP public license, or Genivia's license for commercial use.
+*/
+#include "envH.h"
+
+SOAP_SOURCE_STAMP("@(#) envServer.cpp ver 2.7.6b 2005-09-27 12:23:39 GMT")
+
+
+SOAP_FMAC5 int SOAP_FMAC6 soap_serve(struct soap *soap)
+{
+#ifndef WITH_FASTCGI
+	unsigned int k = soap->max_keep_alive;
+#endif
+
+	do
+	{
+#ifdef WITH_FASTCGI
+		if (FCGI_Accept() < 0)
+		{
+			soap->error = SOAP_EOF;
+			return soap_send_fault(soap);
+		}
+#endif
+
+		soap_begin(soap);
+
+#ifndef WITH_FASTCGI
+		if (!--k)
+			soap->keep_alive = 0;
+#endif
+
+		if (soap_begin_recv(soap))
+		{	if (soap->error < SOAP_STOP)
+			{
+#ifdef WITH_FASTCGI
+				soap_send_fault(soap);
+#else 
+				return soap_send_fault(soap);
+#endif
+			}
+			soap_closesock(soap);
+
+			continue;
+		}
+
+		if (soap_envelope_begin_in(soap)
+		 || soap_recv_header(soap)
+		 || soap_body_begin_in(soap)
+		 || soap_serve_request(soap)
+		 || (soap->fserveloop && soap->fserveloop(soap)))
+		{
+#ifdef WITH_FASTCGI
+			soap_send_fault(soap);
+#else
+			return soap_send_fault(soap);
+#endif
+		}
+
+#ifdef WITH_FASTCGI
+	} while (1);
+#else
+	} while (soap->keep_alive);
+#endif
+	return SOAP_OK;
+}
+
+#ifndef WITH_NOSERVEREQUEST
+SOAP_FMAC5 int SOAP_FMAC6 soap_serve_request(struct soap *soap)
+{
+	soap_peek_element(soap);
+	return soap->error = SOAP_NO_METHOD;
+}
+#endif
+
+/* End of envServer.cpp */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/envServerLib.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,14 @@
+/* envServerLib.cpp
+   Generated by gSOAP 2.7.6b from env.h
+   Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc. All Rights Reserved.
+   This part of the software is released under one of the following licenses:
+   GPL, the gSOAP public license, or Genivia's license for commercial use.
+*/
+#ifndef WITH_NOGLOBAL
+#define WITH_NOGLOBAL
+#endif
+#define SOAP_FMAC3 static
+#include "envC.cpp"
+#include "envServer.cpp"
+
+/* End of envServerLib.cpp */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/envStub.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,145 @@
+/* envStub.h
+   Generated by gSOAP 2.7.6b from env.h
+   Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc. All Rights Reserved.
+   This part of the software is released under one of the following licenses:
+   GPL, the gSOAP public license, or Genivia's license for commercial use.
+*/
+#ifndef envStub_H
+#define envStub_H
+#include ".\stdsoap2.h"
+
+/******************************************************************************\
+ *                                                                            *
+ * Enumerations                                                               *
+ *                                                                            *
+\******************************************************************************/
+
+
+/******************************************************************************\
+ *                                                                            *
+ * Classes and Structs                                                        *
+ *                                                                            *
+\******************************************************************************/
+
+
+#ifndef SOAP_TYPE_SOAP_ENV__Header
+#define SOAP_TYPE_SOAP_ENV__Header (8)
+/* SOAP Header: */
+struct SOAP_ENV__Header
+{
+	void *dummy;	/* transient */
+};
+#endif
+
+#ifndef SOAP_TYPE_SOAP_ENV__Code
+#define SOAP_TYPE_SOAP_ENV__Code (9)
+/* SOAP Fault Code: */
+struct SOAP_ENV__Code
+{
+	char *SOAP_ENV__Value;	/* optional element of type QName */
+	struct SOAP_ENV__Code *SOAP_ENV__Subcode;	/* optional element of type SOAP-ENV:Code */
+};
+#endif
+
+#ifndef SOAP_TYPE_SOAP_ENV__Detail
+#define SOAP_TYPE_SOAP_ENV__Detail (11)
+/* SOAP-ENV:Detail */
+struct SOAP_ENV__Detail
+{
+	int __type;	/* any type of element <fault> (defined below) */
+	void *fault;	/* transient */
+	char *__any;
+};
+#endif
+
+#ifndef SOAP_TYPE_SOAP_ENV__Reason
+#define SOAP_TYPE_SOAP_ENV__Reason (12)
+/* SOAP-ENV:Reason */
+struct SOAP_ENV__Reason
+{
+	char *SOAP_ENV__Text;	/* optional element of type xsd:string */
+};
+#endif
+
+#ifndef SOAP_TYPE_SOAP_ENV__Fault
+#define SOAP_TYPE_SOAP_ENV__Fault (13)
+/* SOAP Fault: */
+struct SOAP_ENV__Fault
+{
+	char *faultcode;	/* optional element of type QName */
+	char *faultstring;	/* optional element of type xsd:string */
+	char *faultactor;	/* optional element of type xsd:string */
+	struct SOAP_ENV__Detail *detail;	/* optional element of type SOAP-ENV:Detail */
+	struct SOAP_ENV__Code *SOAP_ENV__Code;	/* optional element of type SOAP-ENV:Code */
+	struct SOAP_ENV__Reason *SOAP_ENV__Reason;	/* optional element of type SOAP-ENV:Reason */
+	char *SOAP_ENV__Node;	/* optional element of type xsd:string */
+	char *SOAP_ENV__Role;	/* optional element of type xsd:string */
+	struct SOAP_ENV__Detail *SOAP_ENV__Detail;	/* optional element of type SOAP-ENV:Detail */
+};
+#endif
+
+/******************************************************************************\
+ *                                                                            *
+ * Types with Custom Serializers                                              *
+ *                                                                            *
+\******************************************************************************/
+
+
+/******************************************************************************\
+ *                                                                            *
+ * Typedefs                                                                   *
+ *                                                                            *
+\******************************************************************************/
+
+#ifndef SOAP_TYPE__XML
+#define SOAP_TYPE__XML (4)
+typedef char *_XML;
+#endif
+
+#ifndef SOAP_TYPE__QName
+#define SOAP_TYPE__QName (5)
+typedef char *_QName;
+#endif
+
+
+/******************************************************************************\
+ *                                                                            *
+ * Typedef Synonyms                                                           *
+ *                                                                            *
+\******************************************************************************/
+
+
+/******************************************************************************\
+ *                                                                            *
+ * Externals                                                                  *
+ *                                                                            *
+\******************************************************************************/
+
+
+/******************************************************************************\
+ *                                                                            *
+ * Service Operations                                                         *
+ *                                                                            *
+\******************************************************************************/
+
+
+/******************************************************************************\
+ *                                                                            *
+ * Stubs                                                                      *
+ *                                                                            *
+\******************************************************************************/
+
+
+/******************************************************************************\
+ *                                                                            *
+ * Skeletons                                                                  *
+ *                                                                            *
+\******************************************************************************/
+
+SOAP_FMAC5 int SOAP_FMAC6 soap_serve(struct soap*);
+
+SOAP_FMAC5 int SOAP_FMAC6 soap_serve_request(struct soap*);
+
+#endif
+
+/* End of envStub.h */
Binary file hti/PC_Tools/HTIGateway/stdsoap/soapcpp2.exe has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/soapdefs.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,17 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*/
+#define SOAP_FMAC1 __declspec(dllexport) 
+#define SOAP_FMAC3 __declspec(dllexport)
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/stdsoap.vcproj	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,228 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="stdsoap2"
+	ProjectGUID="{F194912E-201A-4C25-9F86-87076D8985C0}"
+	RootNamespace="stdsoap"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\Libs"
+			IntermediateDirectory="Debug"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DWITH_NONAMESPACES -DWITH_SOAPDEFS_H"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;ENV_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="ws2_32.lib"
+				OutputFile="$(OutDir)/stdsoap2D.dll"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				ImportLibrary="$(OutDir)/stdsoap2D.lib"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(ProjectDir)stdsoap2.h $(TargetDir)"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\Libs"
+			IntermediateDirectory="Release"
+			ConfigurationType="2"
+			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				AdditionalOptions="-DWITH_NONAMESPACES -DWITH_SOAPDEFS_H"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;ENV_EXPORTS"
+				RuntimeLibrary="2"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				Detect64BitPortabilityProblems="true"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="ws2_32.lib"
+				OutputFile="$(OutDir)/stdsoap2.dll"
+				LinkIncremental="1"
+				GenerateDebugInformation="false"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				ImportLibrary="$(OutDir)/stdsoap2.lib"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy $(ProjectDir)stdsoap2.h $(TargetDir)"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\envC.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\stdsoap2.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\env.h"
+				>
+			</File>
+			<File
+				RelativePath=".\envH.h"
+				>
+			</File>
+			<File
+				RelativePath=".\envStub.h"
+				>
+			</File>
+			<File
+				RelativePath=".\stdsoap2.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/stdsoap2.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,13110 @@
+/*
+
+stdsoap2.c[pp] 2.7.6b
+
+gSOAP runtime
+
+gSOAP XML Web services tools
+Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc., All Rights Reserved.
+This part of the software is released under one of the following licenses:
+GPL, the gSOAP public license, or Genivia's license for commercial use.
+--------------------------------------------------------------------------------
+Contributors:
+
+Wind River Systems, Inc., for the following additions:
+  - vxWorks compatible
+--------------------------------------------------------------------------------
+gSOAP public license.
+
+The contents of this file are subject to the gSOAP Public License Version 1.3
+(the "License"); you may not use this file except in compliance with the
+License. You may obtain a copy of the License at
+http://www.cs.fsu.edu/~engelen/soaplicense.html
+Software distributed under the License is distributed on an "AS IS" basis,
+WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+for the specific language governing rights and limitations under the License.
+
+The Initial Developer of the Original Code is Robert A. van Engelen.
+Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc., All Rights Reserved.
+--------------------------------------------------------------------------------
+GPL license.
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place, Suite 330, Boston, MA 02111-1307 USA
+
+Author contact information:
+engelen@genivia.com / engelen@acm.org
+--------------------------------------------------------------------------------
+A commercial use license is available from Genivia, Inc., contact@genivia.com
+--------------------------------------------------------------------------------
+
+Installation note:
+
+Win32 build needs winsock.dll (Visual C++ "wsock32.lib")
+To do this in Visual C++ 6.0, go to "Project", "settings", select the "Link"
+tab (the project file needs to be selected in the file view) and add
+"wsock32.lib" to the "Object/library modules" entry
+
+On Mac OS X with gcc (GCC) 3.1 20020420 (prerelease) you MUST compile with
+-fstack_check when using -O2 because gcc 3.1 has a bug that smashes the stack
+when locally allocated data exceeds 64K.
+
+*/
+
+#include "stdsoap2.h"
+
+#ifdef __cplusplus
+SOAP_SOURCE_STAMP("@(#) stdsoap2.cpp ver 2.7.6b 2005-08-26 12:00:00 GMT")
+extern "C" {
+#else
+SOAP_SOURCE_STAMP("@(#) stdsoap2.c ver 2.7.6b 2005-08-26 12:00:00 GMT")
+#endif
+
+/* 8bit character representing unknown/nonrepresentable character data (e.g. not supported by current locale with multibyte support enabled) */
+#ifndef SOAP_UNKNOWN_CHAR
+#define SOAP_UNKNOWN_CHAR (127)
+#endif
+
+/*      EOF=-1 */
+#define SOAP_LT (soap_wchar)(-2) /* XML character '<' */
+#define SOAP_TT (soap_wchar)(-3) /* XML character '</' */
+#define SOAP_GT (soap_wchar)(-4) /* XML character '>' */
+#define SOAP_QT (soap_wchar)(-5) /* XML character '"' */
+#define SOAP_AP (soap_wchar)(-6) /* XML character ''' */
+
+#define SOAP_BOM (soap_wchar)(0xFEFF) /* UTF BOM is Unicode FEFF */
+
+#define soap_blank(c)		((c) >= 0 && (c) <= 32)
+#define soap_notblank(c)	((c) > 32)
+#define soap_hash_ptr(p)	(((unsigned long)(p) >> 3) & (SOAP_PTRHASH - 1))
+
+static int soap_isxdigit(int);
+static soap_wchar soap_char(struct soap*);
+
+#ifndef WITH_NOIDREF
+static void soap_update_ptrs(struct soap*, char*, char*, long);
+static int soap_has_copies(struct soap*, const char*, const char*);
+static void soap_init_iht(struct soap*);
+static void soap_free_iht(struct soap*);
+static void soap_init_pht(struct soap*);
+static void soap_free_pht(struct soap*);
+#endif
+
+#ifdef SOAP_DEBUG
+static void soap_init_logs(struct soap*);
+static void soap_close_logfile(struct soap*, int);
+static void soap_set_logfile(struct soap*, int, const char*);
+static void soap_free_mht(struct soap*);
+static void soap_track_unlink(struct soap*, const void*);
+#endif
+
+static int soap_set_error(struct soap*, const char*, const char*, const char*, const char*, int);
+static int soap_copy_fault(struct soap*, const char*, const char*, const char*, const char*);
+static int soap_getattrval(struct soap*, char*, size_t, soap_wchar);
+static void *fplugin(struct soap*, const char*);
+
+#ifndef WITH_LEAN
+static const char *soap_set_validation_fault(struct soap*, const char*, const char*);
+static int soap_isnumeric(struct soap*, const char*);
+static time_t soap_timegm(struct tm*);
+static struct soap_nlist *soap_lookup_ns(struct soap *soap, const char *tag, size_t n);
+static struct soap_nlist *soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized);
+static void soap_pop_ns(struct soap *soap);
+static void soap_utilize_ns(struct soap *soap, const char *tag, size_t n);
+#endif
+
+#ifndef WITH_LEANER
+static struct soap_multipart *soap_new_multipart(struct soap*, struct soap_multipart**, struct soap_multipart**, char*, size_t);
+static int soap_putdimefield(struct soap*, const char*, size_t);
+static char *soap_getdimefield(struct soap*, size_t);
+static void soap_select_mime_boundary(struct soap*);
+static int soap_valid_mime_boundary(struct soap*);
+static int soap_match_cid(const char*, const char*);
+static void soap_resolve_attachment(struct soap*, struct soap_multipart*);
+#endif
+
+#ifdef WITH_GZIP
+static int soap_getgziphdr(struct soap*);
+#endif
+
+#ifdef WITH_OPENSSL
+static void ssl_init();
+static int ssl_auth_init(struct soap*);
+static int ssl_verify_callback(int, X509_STORE_CTX*);
+static int ssl_password(char*, int, int, void *);
+static const char *ssl_error(struct soap*, int);
+/* This callback is included for future references. It should not be deleted
+static DH *ssl_tmp_dh(SSL*, int, int);
+*/
+#endif
+
+#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER)
+static const char *soap_decode(char*, size_t, const char*, const char*);
+#endif
+
+#ifndef WITH_NOHTTP
+static soap_wchar soap_getchunkchar(struct soap*);
+static const char *http_error(struct soap*, int);
+static int http_post(struct soap*, const char*, const char*, int, const char*, const char*, size_t);
+static int http_get(struct soap*);
+static int http_send_header(struct soap*, const char*);
+static int http_post_header(struct soap*, const char*, const char*);
+static int http_response(struct soap*, int, size_t);
+static int http_parse(struct soap*);
+static int http_parse_header(struct soap*, const char*, const char*);
+#endif
+
+#ifndef WITH_NOIO
+static int fsend(struct soap*, const char*, size_t);
+static size_t frecv(struct soap*, char*, size_t);
+static int tcp_init(struct soap*);
+static const char *tcp_error(struct soap*);
+#ifndef WITH_IPV6
+static int tcp_gethost(struct soap*, const char *addr, struct in_addr *inaddr);
+#endif
+static int tcp_connect(struct soap*, const char *endpoint, const char *host, int port);
+static int tcp_accept(struct soap*, int, struct sockaddr*, int*);
+static int tcp_disconnect(struct soap*);
+static int tcp_closesocket(struct soap*, SOAP_SOCKET);
+static int tcp_shutdownsocket(struct soap*, SOAP_SOCKET, int);
+static const char *soap_strerror(struct soap*);
+#endif
+
+#ifdef VXWORKS
+static int vx_nonblocking = TRUE; /* ioctl argument */
+#endif
+
+#if defined(PALM) && !defined(PALM_2)
+unsigned short errno;
+#endif
+
+#ifndef PALM_1
+static const char soap_env1[42] = "http://schemas.xmlsoap.org/soap/envelope/";
+static const char soap_enc1[42] = "http://schemas.xmlsoap.org/soap/encoding/";
+static const char soap_env2[40] = "http://www.w3.org/2003/05/soap-envelope";
+static const char soap_enc2[40] = "http://www.w3.org/2003/05/soap-encoding";
+static const char soap_rpc[35] = "http://www.w3.org/2003/05/soap-rpc";
+#endif
+
+#ifndef PALM_1
+const struct soap_double_nan soap_double_nan = {0xFFFFFFFF, 0xFFFFFFFF};
+static const char soap_base64o[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+static const char soap_base64i[81] = "\76XXX\77\64\65\66\67\70\71\72\73\74\75XXXXXXX\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31XXXXXX\32\33\34\35\36\37\40\41\42\43\44\45\46\47\50\51\52\53\54\55\56\57\60\61\62\63";
+#endif
+
+#ifndef WITH_LEAN
+static const char soap_indent[11] = "\n\t\t\t\t\t\t\t\t\t";
+/* Alternative indentation form for SOAP_XML_INDENT:
+static const char soap_indent[21] = "\n                   ";
+*/
+#endif
+
+static const char soap_padding[3] = "\0\0";
+#define SOAP_STR_PADDING (soap_padding)
+#define SOAP_STR_EOS (soap_padding)
+#define SOAP_NON_NULL (soap_padding)
+
+#ifndef WITH_LEAN
+static const struct soap_code_map html_entity_codes[] = /* entities for XHTML parsing */
+{ { 160, "nbsp" },
+  { 161, "iexcl" },
+  { 162, "cent" },
+  { 163, "pound" },
+  { 164, "curren" },
+  { 165, "yen" },
+  { 166, "brvbar" },
+  { 167, "sect" },
+  { 168, "uml" },
+  { 169, "copy" },
+  { 170, "ordf" },
+  { 171, "laquo" },
+  { 172, "not" },
+  { 173, "shy" },
+  { 174, "reg" },
+  { 175, "macr" },
+  { 176, "deg" },
+  { 177, "plusmn" },
+  { 178, "sup2" },
+  { 179, "sup3" },
+  { 180, "acute" },
+  { 181, "micro" },
+  { 182, "para" },
+  { 183, "middot" },
+  { 184, "cedil" },
+  { 185, "sup1" },
+  { 186, "ordm" },
+  { 187, "raquo" },
+  { 188, "frac14" },
+  { 189, "frac12" },
+  { 190, "frac34" },
+  { 191, "iquest" },
+  { 192, "Agrave" },
+  { 193, "Aacute" },
+  { 194, "Acirc" },
+  { 195, "Atilde" },
+  { 196, "Auml" },
+  { 197, "Aring" },
+  { 198, "AElig" },
+  { 199, "Ccedil" },
+  { 200, "Egrave" },
+  { 201, "Eacute" },
+  { 202, "Ecirc" },
+  { 203, "Euml" },
+  { 204, "Igrave" },
+  { 205, "Iacute" },
+  { 206, "Icirc" },
+  { 207, "Iuml" },
+  { 208, "ETH" },
+  { 209, "Ntilde" },
+  { 210, "Ograve" },
+  { 211, "Oacute" },
+  { 212, "Ocirc" },
+  { 213, "Otilde" },
+  { 214, "Ouml" },
+  { 215, "times" },
+  { 216, "Oslash" },
+  { 217, "Ugrave" },
+  { 218, "Uacute" },
+  { 219, "Ucirc" },
+  { 220, "Uuml" },
+  { 221, "Yacute" },
+  { 222, "THORN" },
+  { 223, "szlig" },
+  { 224, "agrave" },
+  { 225, "aacute" },
+  { 226, "acirc" },
+  { 227, "atilde" },
+  { 228, "auml" },
+  { 229, "aring" },
+  { 230, "aelig" },
+  { 231, "ccedil" },
+  { 232, "egrave" },
+  { 233, "eacute" },
+  { 234, "ecirc" },
+  { 235, "euml" },
+  { 236, "igrave" },
+  { 237, "iacute" },
+  { 238, "icirc" },
+  { 239, "iuml" },
+  { 240, "eth" },
+  { 241, "ntilde" },
+  { 242, "ograve" },
+  { 243, "oacute" },
+  { 244, "ocirc" },
+  { 245, "otilde" },
+  { 246, "ouml" },
+  { 247, "divide" },
+  { 248, "oslash" },
+  { 249, "ugrave" },
+  { 250, "uacute" },
+  { 251, "ucirc" },
+  { 252, "uuml" },
+  { 253, "yacute" },
+  { 254, "thorn" },
+  { 255, "yuml" },
+  {   0, NULL }
+};
+#endif
+
+#ifndef WITH_NOIO
+#ifndef WITH_LEAN
+static const struct soap_code_map h_error_codes[] =
+{
+#ifdef HOST_NOT_FOUND   
+  { HOST_NOT_FOUND, "Host not found" },
+#endif
+#ifdef TRY_AGAIN
+  { TRY_AGAIN, "Try Again" },
+#endif
+#ifdef NO_RECOVERY  
+  { NO_RECOVERY, "No Recovery" },
+#endif
+#ifdef NO_DATA
+  { NO_DATA, "No Data" },
+#endif
+#ifdef NO_ADDRESS
+  { NO_ADDRESS, "No Address" },
+#endif
+  { 0, NULL }
+};
+#endif
+#endif
+
+#ifndef WITH_NOHTTP
+#ifndef WITH_LEAN
+static const struct soap_code_map h_http_error_codes[] =
+{ { 201, "Created" },
+  { 202, "Accepted" },
+  { 203, "Non-Authoritative Information" },
+  { 204, "No Content" },
+  { 205, "Reset Content" },
+  { 206, "Partial Content" },
+  { 300, "Multiple Choices" },
+  { 301, "Moved Permanently" },
+  { 302, "Found" },
+  { 303, "See Other" },
+  { 304, "Not Modified" },
+  { 305, "Use Proxy" },
+  { 307, "Temporary Redirect" },
+  { 400, "Bad Request" },
+  { 401, "Unauthorized" },
+  { 402, "Payment Required" },
+  { 403, "Forbidden" },
+  { 404, "Not Found" },
+  { 405, "Method Not Allowed" },
+  { 406, "Not Acceptable" },
+  { 407, "Proxy Authentication Required" },
+  { 408, "Request Time-out" },
+  { 409, "Conflict" },
+  { 410, "Gone" },
+  { 411, "Length Required" },
+  { 412, "Precondition Failed" },
+  { 413, "Request Entity Too Large" },
+  { 414, "Request-URI Too Large" },
+  { 415, "Unsupported Media Type" },
+  { 416, "Requested range not satisfiable" },
+  { 417, "Expectation Failed" },
+  { 500, "Internal Server Error" },
+  { 501, "Not Implemented" },
+  { 502, "Bad Gateway" },
+  { 503, "Service Unavailable" },
+  { 504, "Gateway Time-out" },
+  { 505, "HTTP Version not supported" },
+  {   0, NULL }
+};
+#endif
+#endif
+
+#ifdef WITH_OPENSSL
+static const struct soap_code_map h_ssl_error_codes[] =
+{
+#define _SSL_ERROR(e) { e, #e }
+  _SSL_ERROR(SSL_ERROR_SSL),
+  _SSL_ERROR(SSL_ERROR_ZERO_RETURN),
+  _SSL_ERROR(SSL_ERROR_WANT_READ),
+  _SSL_ERROR(SSL_ERROR_WANT_WRITE),
+  _SSL_ERROR(SSL_ERROR_WANT_CONNECT),
+  _SSL_ERROR(SSL_ERROR_WANT_X509_LOOKUP),
+  _SSL_ERROR(SSL_ERROR_SYSCALL),
+  { 0, NULL }
+};
+#endif
+
+#ifndef WITH_LEANER
+static const struct soap_code_map mime_codes[] =
+{ { SOAP_MIME_7BIT,		"7bit" },
+  { SOAP_MIME_8BIT,		"8bit" },
+  { SOAP_MIME_BINARY,		"binary" },
+  { SOAP_MIME_QUOTED_PRINTABLE, "quoted-printable" },
+  { SOAP_MIME_BASE64,		"base64" },
+  { SOAP_MIME_IETF_TOKEN,	"ietf-token" },
+  { SOAP_MIME_X_TOKEN,		"x-token" },
+  { 0,				NULL }
+};
+#endif
+
+#ifdef WIN32
+static int tcp_done = 0;
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static int
+fsend(struct soap *soap, const char *s, size_t n)
+{ register int nwritten;
+#if defined(__cplusplus) && !defined(WITH_LEAN)
+  if (soap->os)
+  { soap->os->write(s, n);
+    if (soap->os->good())
+      return SOAP_OK;
+    return SOAP_EOF;
+  }
+#endif
+  while (n)
+  { if (soap_valid_socket(soap->socket))
+    { 
+#ifndef WITH_LEAN
+      if (soap->send_timeout)
+      { struct timeval timeout;
+        fd_set fd;
+        if (soap->send_timeout > 0)
+        { timeout.tv_sec = soap->send_timeout;
+          timeout.tv_usec = 0;
+        }
+        else
+        { timeout.tv_sec = -soap->send_timeout/1000000;
+          timeout.tv_usec = -soap->send_timeout%1000000;
+        }
+        FD_ZERO(&fd);
+        FD_SET((SOAP_SOCKET)soap->socket, &fd);
+        for (;;)
+        { register int r = select((SOAP_SOCKET)(soap->socket + 1), NULL, &fd, &fd, &timeout);
+          if (r > 0)
+            break;
+          if (!r)
+          { soap->errnum = 0;
+            return SOAP_EOF;
+          }
+          if (soap_socket_errno != SOAP_EINTR && soap_socket_errno != SOAP_EAGAIN)
+          { soap->errnum = soap_socket_errno;
+            return SOAP_EOF;
+          }
+        }
+      }
+#endif
+#ifdef WITH_OPENSSL
+      if (soap->ssl)
+        nwritten = SSL_write(soap->ssl, s, n);
+      else if (soap->bio)
+        nwritten = BIO_write(soap->bio, s, n);
+      else
+#endif
+#ifdef WITH_UDP
+      if ((soap->omode & SOAP_IO_UDP))
+      { if (soap->peerlen)
+	  nwritten = sendto((SOAP_SOCKET)soap->socket, s, n, soap->socket_flags, (struct sockaddr*)&soap->peer, soap->peerlen);
+        else
+	  nwritten = send((SOAP_SOCKET)soap->socket, s, n, soap->socket_flags);
+	/* retry and back-off algorithm */
+	/* TODO: this is not very clear from specs so verify and limit conditions under which we should loop (e.g. ENOBUFS) */
+	if (nwritten < 0)
+        { struct timeval timeout;
+          fd_set fd;
+	  int udp_repeat;
+	  int udp_delay;
+          if ((soap->connect_flags & SO_BROADCAST))
+	    udp_repeat = 3; /* SOAP-over-UDP MULTICAST_UDP_REPEAT - 1 */
+          else
+	    udp_repeat = 1; /* SOAP-over-UDP UNICAST_UDP_REPEAT - 1 */
+	  udp_delay = (soap_random % 201) + 50; /* UDP_MIN_DELAY .. UDP_MAX_DELAY */
+	  do
+          { timeout.tv_sec = 0;
+            timeout.tv_usec = 1000 * udp_delay; /* ms */
+            FD_ZERO(&fd);
+            FD_SET((SOAP_SOCKET)soap->socket, &fd);
+            select((SOAP_SOCKET)(soap->socket + 1), NULL, NULL, &fd, &timeout);
+	    if (soap->peerlen)
+	      nwritten = sendto((SOAP_SOCKET)soap->socket, s, n, soap->socket_flags, (struct sockaddr*)&soap->peer, soap->peerlen);
+            else
+	      nwritten = send((SOAP_SOCKET)soap->socket, s, n, soap->socket_flags);
+	    udp_delay <<= 1;
+	    if (udp_delay > 500) /* UDP_UPPER_DELAY */
+	      udp_delay = 500;
+	  }
+	  while (nwritten < 0 && --udp_repeat > 0);
+	}
+      }
+      else
+#endif
+#ifndef PALM
+        nwritten = send((SOAP_SOCKET)soap->socket, s, n, soap->socket_flags);
+#else
+        nwritten = send((SOAP_SOCKET)soap->socket, (void*)s, n, soap->socket_flags);
+#endif
+      if (nwritten <= 0)
+      {
+#ifdef WITH_OPENSSL
+	int err;
+        if (soap->ssl && (err = SSL_get_error(soap->ssl, nwritten)) != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE)
+          return SOAP_EOF;
+#endif
+        if (soap_socket_errno != SOAP_EINTR && soap_socket_errno != SOAP_EWOULDBLOCK && soap_socket_errno != SOAP_EAGAIN)
+        { soap->errnum = soap_socket_errno;
+          return SOAP_EOF;
+        }
+        nwritten = 0; /* and call write() again */
+      }
+    }
+    else
+    {
+#ifdef WITH_FASTCGI
+      nwritten = fwrite((void*)s, 1, n, stdout);
+      fflush(stdout);
+#else
+#ifdef UNDER_CE
+      nwritten = fwrite(s, 1, n, soap->sendfd);
+#else
+#ifdef VXWORKS
+#ifdef WMW_RPM_IO
+      if (soap->rpmreqid)
+        nwritten = (httpBlockPut(soap->rpmreqid, s, n) == 0) ? n : -1; 
+      else
+        nwritten = fwrite(s, sizeof(char), n, fdopen(soap->sendfd, "w"));
+#else
+      nwritten = fwrite(s, sizeof(char), n, fdopen(soap->sendfd, "w"));
+#endif /* WMW_RPM_IO */
+#else
+      nwritten = write((SOAP_SOCKET)soap->sendfd, s, n);
+#endif
+#endif
+#endif
+      if (nwritten <= 0)
+      { if (soap_errno != SOAP_EINTR && soap_errno != SOAP_EWOULDBLOCK && soap_errno != SOAP_EAGAIN)
+        { soap->errnum = soap_errno;
+          return SOAP_EOF;
+        }
+        nwritten = 0; /* and call write() again */
+      }
+    }
+    n -= nwritten;
+    s += nwritten;
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_send_raw(struct soap *soap, const char *s, size_t n)
+{ if (!n)
+    return SOAP_OK;
+  if (soap->mode & SOAP_IO_LENGTH)
+  { soap->count += n;
+#ifndef WITH_LEANER
+    if (soap->fpreparesend && (soap->mode & SOAP_IO) != SOAP_IO_STORE)
+      return soap->error = soap->fpreparesend(soap, s, n);
+#endif
+    return SOAP_OK;
+  }
+  if (soap->mode & SOAP_IO)
+  { register size_t i = SOAP_BUFLEN - soap->bufidx;
+    while (n >= i)
+    { memcpy(soap->buf + soap->bufidx, s, i);
+      soap->bufidx = SOAP_BUFLEN;
+      if (soap_flush(soap))
+        return soap->error;
+      s += i;
+      n -= i;
+      i = SOAP_BUFLEN;
+    }
+    memcpy(soap->buf + soap->bufidx, s, n);
+    soap->bufidx += n;
+    return SOAP_OK;
+  }
+  return soap_flush_raw(soap, s, n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_flush(struct soap *soap)
+{ register int n = soap->bufidx;
+  if (n)
+  { soap->bufidx = 0;
+#ifdef WITH_ZLIB
+    if (soap->mode & SOAP_ENC_ZLIB)
+    { soap->d_stream.next_in = (Byte*)soap->buf;
+      soap->d_stream.avail_in = (unsigned int)n;
+#ifdef WITH_GZIP
+      soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)n);
+#endif
+      do
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflating %u bytes\n", soap->d_stream.avail_in));
+        if (deflate(&soap->d_stream, Z_NO_FLUSH) != Z_OK)
+        { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to deflate: %s\n", soap->d_stream.msg?soap->d_stream.msg:""));
+          return soap->error = SOAP_ZLIB_ERROR;
+        }
+        if (!soap->d_stream.avail_out)
+        { if (soap_flush_raw(soap, soap->z_buf, SOAP_BUFLEN))
+            return soap->error;
+          soap->d_stream.next_out = (Byte*)soap->z_buf;
+          soap->d_stream.avail_out = SOAP_BUFLEN;
+        }
+      } while (soap->d_stream.avail_in);
+    }
+    else
+#endif
+      return soap_flush_raw(soap, soap->buf, n);
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_flush_raw(struct soap *soap, const char *s, size_t n)
+{ if ((soap->mode & SOAP_IO) == SOAP_IO_STORE)
+  { register char *t;
+    if (!(t = (char*)soap_push_block(soap, n)))
+      return soap->error = SOAP_EOM;
+    memcpy(t, s, n);
+#ifndef WITH_LEANER
+    if (soap->fpreparesend)
+      return soap->error = soap->fpreparesend(soap, s, n);
+#endif
+    return SOAP_OK;
+  }
+#ifndef WITH_LEANER
+  if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK)
+  { char t[16];
+    sprintf(t, "\r\n%lX\r\n" + (soap->chunksize ? 0 : 2), (unsigned long)n);
+    DBGMSG(SENT, t, strlen(t));
+    if ((soap->error = soap->fsend(soap, t, strlen(t))))
+      return soap->error;
+    soap->chunksize += n;
+  }
+  DBGMSG(SENT, s, n);
+#endif
+  return soap->error = soap->fsend(soap, s, n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_send(struct soap *soap, const char *s)
+{ if (s)
+    return soap_send_raw(soap, s, strlen(s));
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_send2(struct soap *soap, const char *s1, const char *s2)
+{ if (soap_send(soap, s1))
+    return soap->error;
+  return soap_send(soap, s2);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_send3(struct soap *soap, const char *s1, const char *s2, const char *s3)
+{ if (soap_send(soap, s1)
+   || soap_send(soap, s2))
+    return soap->error;
+  return soap_send(soap, s3);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static size_t
+frecv(struct soap *soap, char *s, size_t n)
+{ register int r;
+  soap->errnum = 0;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "frecv\n"));
+#if defined(__cplusplus) && !defined(WITH_LEAN)
+  if (soap->is)
+  { if (soap->is->good())
+      return soap->is->read(s, n).gcount();
+    return 0;
+  }
+#endif
+  if (soap_valid_socket(soap->socket))
+  { for (;;)
+    { 
+#ifndef WITH_LEAN
+      if (soap->recv_timeout)
+      { struct timeval timeout;
+        fd_set fd;
+        if (soap->recv_timeout > 0)
+        { timeout.tv_sec = soap->recv_timeout;
+          timeout.tv_usec = 0;
+        }
+        else
+        { timeout.tv_sec = -soap->recv_timeout/1000000;
+          timeout.tv_usec = -soap->recv_timeout%1000000;
+        }
+        FD_ZERO(&fd);
+        FD_SET((SOAP_SOCKET)soap->socket, &fd);
+		DBGLOG(TEST, SOAP_MESSAGE(fdebug, "select\n"));
+        for (;;)
+        { r = select((SOAP_SOCKET)(soap->socket + 1), &fd, NULL, &fd, &timeout);
+		DBGLOG(TEST, SOAP_MESSAGE(fdebug, "r=%d\n", r));
+          if (r > 0)
+            break;
+          if (!r)
+	  { soap->errnum = 0;
+            return 0;
+          }
+	  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Socket err %d\n", soap_socket_errno));
+          if (soap_socket_errno != SOAP_EINTR && soap_socket_errno != SOAP_EAGAIN)
+	  { soap->errnum = soap_socket_errno;
+            return 0;
+          }
+        }
+		DBGLOG(TEST, SOAP_MESSAGE(fdebug, "select end\n"));
+      }
+#endif
+#ifdef WITH_OPENSSL
+      if (soap->ssl)
+      { int err;
+	r = SSL_read(soap->ssl, s, n);
+        if (r > 0)
+          return (size_t)r;
+	err = SSL_get_error(soap->ssl, r);
+	if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE)
+          return 0;
+      }
+      else if (soap->bio)
+      { r = BIO_read(soap->bio, s, n);
+        if (r > 0)
+          return (size_t)r;
+        return 0;
+      }
+      else
+#endif
+      { 
+#ifdef WITH_UDP
+        if ((soap->omode & SOAP_IO_UDP))
+        { SOAP_SOCKLEN_T k = (SOAP_SOCKLEN_T)sizeof(soap->peer);
+	  memset((void*)&soap->peer, 0, sizeof(soap->peer));
+          r = recvfrom((SOAP_SOCKET)soap->socket, s, n, soap->socket_flags, (struct sockaddr*)&soap->peer, &k);	/* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */
+	  soap->peerlen = (size_t)k;
+#ifndef WITH_IPV6
+          soap->ip = ntohl(soap->peer.sin_addr.s_addr);
+          soap->port = (int)ntohs(soap->peer.sin_port);
+#endif
+        }
+	else
+#endif
+		DBGLOG(TEST, SOAP_MESSAGE(fdebug, "recv\n"));
+          r = recv((SOAP_SOCKET)soap->socket, s, n, soap->socket_flags);
+		  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "r=%d\n", r));
+        if (r >= 0)
+          return (size_t)r;
+		DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Socket err %d\n", soap_socket_errno));
+        if (soap_socket_errno != SOAP_EINTR && soap_socket_errno != SOAP_EAGAIN && soap_socket_errno != SOAP_EWOULDBLOCK)
+        { soap->errnum = soap_socket_errno;
+          return 0;
+        }
+      }
+#ifndef WITH_LEAN
+      { struct timeval timeout;
+        fd_set fd;
+        timeout.tv_sec = 0;
+        timeout.tv_usec = 10000;
+        FD_ZERO(&fd);
+        FD_SET((SOAP_SOCKET)soap->socket, &fd);
+#ifdef WITH_OPENSSL
+        if (soap->ssl && SSL_get_error(soap->ssl, r) == SSL_ERROR_WANT_WRITE)
+          r = select((SOAP_SOCKET)(soap->socket + 1), NULL, &fd, &fd, &timeout);
+        else
+          r = select((SOAP_SOCKET)(soap->socket + 1), &fd, NULL, &fd, &timeout);
+#else
+        r = select((SOAP_SOCKET)(soap->socket + 1), &fd, NULL, &fd, &timeout);
+#endif
+        if (r < 0 && soap_socket_errno != SOAP_EINTR)
+        { soap->errnum = soap_socket_errno;
+          return 0;
+        }
+      }
+#endif
+    }
+  }
+#ifdef WITH_FASTCGI
+  return fread(s, 1, n, stdin);
+#else
+#ifdef UNDER_CE
+  return fread(s, 1, n, soap->recvfd);
+#else
+#ifdef WMW_RPM_IO
+  if (soap->rpmreqid)
+    r = httpBlockRead(soap->rpmreqid, s, n);
+#endif
+  r = read((SOAP_SOCKET)soap->recvfd, s, n);
+  if (r >= 0)
+    return (size_t)r;
+  soap->errnum = soap_errno;
+  return 0;
+#endif
+#endif
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static soap_wchar
+soap_getchunkchar(struct soap *soap)
+{ if (soap->bufidx < soap->buflen)
+    return soap->buf[soap->bufidx++];
+  soap->bufidx = 0;
+  soap->buflen = soap->chunkbuflen = soap->frecv(soap, soap->buf, SOAP_BUFLEN);
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes from socket %d\n", (unsigned int)soap->buflen, soap->socket));
+  DBGMSG(RECV, soap->buf, soap->buflen);
+  if (soap->buflen)
+    return soap->buf[soap->bufidx++];
+  return EOF;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+static int
+soap_isxdigit(int c)
+{ return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_recv_raw(struct soap *soap)
+{ register size_t ret;
+#ifdef WITH_ZLIB
+  if (soap->mode & SOAP_ENC_ZLIB)
+  { if (soap->d_stream.next_out == Z_NULL)
+      return EOF;
+    if (soap->d_stream.avail_in || !soap->d_stream.avail_out)
+    { register int r;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflating\n"));
+      soap->d_stream.next_out = (Byte*)soap->buf;
+      soap->d_stream.avail_out = SOAP_BUFLEN;
+      r = inflate(&soap->d_stream, Z_NO_FLUSH);
+      if (r == Z_OK || r == Z_STREAM_END)
+      { soap->bufidx = 0;
+        soap->buflen = SOAP_BUFLEN - soap->d_stream.avail_out;
+        if (soap->zlib_in == SOAP_ZLIB_GZIP)
+          soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)soap->buflen);
+        if (r == Z_STREAM_END)
+        { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated %lu->%lu bytes\n", soap->d_stream.total_in, soap->d_stream.total_out));
+          soap->z_ratio_in = (float)soap->d_stream.total_in / (float)soap->d_stream.total_out;
+          soap->d_stream.next_out = Z_NULL;
+        }
+        if (soap->buflen)
+        { soap->count += soap->buflen;
+          return SOAP_OK;
+        }
+      }
+      else if (r != Z_BUF_ERROR)
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflate error: %s\n", soap->d_stream.msg?soap->d_stream.msg:""));
+        soap->d_stream.next_out = Z_NULL;
+	soap->error = SOAP_ZLIB_ERROR;
+        return EOF;
+      }
+    }
+zlib_again:
+    if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK && !soap->chunksize)
+    { memcpy(soap->buf, soap->z_buf, SOAP_BUFLEN);
+      soap->buflen = soap->z_buflen;
+    }
+  }
+#endif
+#ifndef WITH_NOHTTP
+  if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) /* read HTTP chunked transfer */
+  { 
+chunk_again:
+    if (soap->chunksize)
+    { soap->buflen = ret = soap->frecv(soap, soap->buf, soap->chunksize > SOAP_BUFLEN ? SOAP_BUFLEN : soap->chunksize);
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting chunk: read %u bytes\n", (unsigned int)ret));
+      DBGMSG(RECV, soap->buf, ret);
+      soap->bufidx = 0;
+      soap->chunksize -= ret;
+    }
+    else
+    { register soap_wchar c;
+      char *t, tmp[8];
+      t = tmp;
+      if (!soap->chunkbuflen)
+      { soap->chunkbuflen = ret = soap->frecv(soap, soap->buf, SOAP_BUFLEN);
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes (chunked) from socket %d\n", (unsigned int)ret, soap->socket));
+        DBGMSG(RECV, soap->buf, ret);
+        soap->bufidx = 0;
+        if (!ret)
+          return soap->ahead = EOF;
+      }
+      else
+        soap->bufidx = soap->buflen;
+      soap->buflen = soap->chunkbuflen;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting chunk size (idx=%u len=%u)\n", (unsigned int)soap->bufidx, (unsigned int)soap->buflen));
+      while (!soap_isxdigit((int)(c = soap_getchunkchar(soap))))
+        if ((int)c == EOF)
+	  return soap->ahead = EOF;
+      do
+        *t++ = (char)c;
+      while (soap_isxdigit((int)(c = soap_getchunkchar(soap))) && t - tmp < 7);
+      while ((int)c != EOF && c != '\n')
+        c = soap_getchunkchar(soap);
+      if ((int)c == EOF)
+        return soap->ahead = EOF;
+      *t = '\0';
+      soap->chunksize = soap_strtoul(tmp, &t, 16);
+      if (!soap->chunksize)
+      { soap->chunkbuflen = 0;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of chunked message\n"));
+	while ((int)c != EOF && c != '\n')
+          c = soap_getchunkchar(soap);
+        return soap->ahead = EOF;
+      }
+      soap->buflen = soap->bufidx + soap->chunksize;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Moving buf len to idx=%u len=%u (%s)\n", (unsigned int)soap->bufidx, (unsigned int)soap->buflen, tmp));
+      if (soap->buflen > soap->chunkbuflen)
+      { soap->buflen = soap->chunkbuflen;
+        soap->chunksize -= soap->buflen - soap->bufidx;
+        soap->chunkbuflen = 0;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Passed end of buffer for chunked HTTP (%u bytes left)\n", (unsigned int)(soap->buflen - soap->bufidx)));
+      }
+      else if (soap->chunkbuflen)
+        soap->chunksize = 0;
+      ret = soap->buflen - soap->bufidx;
+      if (!ret)
+        goto chunk_again;
+    }
+  }
+  else
+#endif
+  { soap->bufidx = 0;
+    soap->buflen = ret = soap->frecv(soap, soap->buf, SOAP_BUFLEN);
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Read %u bytes from socket %d\n", (unsigned int)ret, soap->socket));
+    DBGMSG(RECV, soap->buf, ret);
+  }
+#ifndef WITH_LEANER
+  if (soap->fpreparerecv && (soap->error = soap->fpreparerecv(soap, soap->buf, ret)))
+    return soap->error;
+#endif
+#ifdef WITH_ZLIB
+  if (soap->mode & SOAP_ENC_ZLIB)
+  { register int r;
+    memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN);
+    soap->d_stream.next_in = (Byte*)(soap->z_buf + soap->bufidx);
+    soap->d_stream.avail_in = (unsigned int)ret;
+    soap->d_stream.next_out = (Byte*)soap->buf;
+    soap->d_stream.avail_out = SOAP_BUFLEN;
+    r = inflate(&soap->d_stream, Z_NO_FLUSH);
+    if (r == Z_OK || r == Z_STREAM_END)
+    { soap->bufidx = 0;
+      soap->z_buflen = soap->buflen;
+      soap->buflen = ret = SOAP_BUFLEN - soap->d_stream.avail_out;
+      if (soap->zlib_in == SOAP_ZLIB_GZIP)
+        soap->z_crc = crc32(soap->z_crc, (Byte*)soap->buf, (unsigned int)soap->buflen);
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated %u bytes\n", (unsigned int)ret));
+      if (!ret)
+        goto zlib_again;
+      if (r == Z_STREAM_END)
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflated %lu->%lu bytes\n", soap->d_stream.total_in, soap->d_stream.total_out));
+        soap->z_ratio_in = (float)soap->d_stream.total_in / (float)soap->d_stream.total_out;
+        soap->d_stream.next_out = Z_NULL;
+      }
+    }
+    else
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to inflate: (%d) %s\n", r, soap->d_stream.msg?soap->d_stream.msg:""));
+      soap->d_stream.next_out = Z_NULL;
+      soap->error = SOAP_ZLIB_ERROR;
+      return EOF;
+    }
+  }
+#endif
+  soap->count += ret;
+  return !ret;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_recv(struct soap *soap)
+{ 
+#ifndef WITH_LEANER
+  if (soap->mode & SOAP_ENC_DIME)
+  { if (soap->dime.buflen)
+    { char *s;
+      int i;
+      unsigned char tmp[12];
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME hdr for chunked DIME is in buffer\n"));
+      soap->count += soap->dime.buflen - soap->buflen;
+      soap->buflen = soap->dime.buflen;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Skip padding (%ld bytes)\n", -(long)soap->dime.size&3));
+      for (i = -(long)soap->dime.size&3; i > 0; i--)
+      { soap->bufidx++;
+        if (soap->bufidx >= soap->buflen)
+          if (soap_recv_raw(soap))
+            return EOF;
+      }
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME hdr for next chunk\n"));
+      s = (char*)tmp;
+      for (i = 12; i > 0; i--)
+      { *s++ = soap->buf[soap->bufidx++];
+        if (soap->bufidx >= soap->buflen)
+          if (soap_recv_raw(soap))
+            return EOF;
+      }
+      soap->dime.flags = tmp[0] & 0x7;
+      soap->dime.size = ((size_t)tmp[8] << 24) | ((size_t)tmp[9] << 16) | ((size_t)tmp[10] << 8) | ((size_t)tmp[11]);
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME chunk (%u bytes)\n", (unsigned int)soap->dime.size));
+      if (soap->dime.flags & SOAP_DIME_CF)
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "More chunking\n"));
+        soap->dime.chunksize = soap->dime.size;
+        if (soap->buflen - soap->bufidx >= soap->dime.size)
+        { soap->dime.buflen = soap->buflen;
+          soap->buflen = soap->bufidx + soap->dime.chunksize;
+        }
+        else
+          soap->dime.chunksize -= soap->buflen - soap->bufidx;
+      }
+      else
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Last chunk\n"));
+        soap->dime.buflen = 0;
+        soap->dime.chunksize = 0;
+      }
+      soap->count = soap->buflen - soap->bufidx;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%u bytes remaining\n", (unsigned int)soap->count));
+      return SOAP_OK;
+    }
+    if (soap->dime.chunksize)
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get next DIME hdr for chunked DIME (%u bytes chunk)\n", (unsigned int)soap->dime.chunksize));
+      if (soap_recv_raw(soap))
+        return EOF;
+      if (soap->buflen - soap->bufidx >= soap->dime.chunksize)
+      { soap->dime.buflen = soap->buflen;
+        soap->count -= soap->buflen - soap->bufidx - soap->dime.chunksize;
+        soap->buflen = soap->bufidx + soap->dime.chunksize;
+      }
+      else
+        soap->dime.chunksize -= soap->buflen - soap->bufidx;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%lu bytes remaining, count=%u\n", (unsigned long)(soap->buflen-soap->bufidx), (unsigned int)soap->count));
+      return SOAP_OK;
+    }
+  }
+#endif
+  return soap_recv_raw(soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+soap_wchar
+SOAP_FMAC2
+soap_getchar(struct soap *soap)
+{ register soap_wchar c;
+  c = soap->ahead;
+  if (c)
+  { if (c != EOF)
+      soap->ahead = 0;
+    return c;
+  }
+  return soap_get1(soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+const struct soap_code_map*
+SOAP_FMAC2
+soap_code(const struct soap_code_map *map, const char *str)
+{ if (str)
+  { while (map->string)
+    { if (!strcmp(str, map->string)) /* case sensitive */
+        return map;
+      map++;
+    }
+  }
+  return NULL;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+long
+SOAP_FMAC2
+soap_int_code(const struct soap_code_map *map, const char *str, long other)
+{ while (map->string)
+  { if (!soap_tag_cmp(str, map->string)) /* case insensitive */
+      return map->code;
+    map++;
+  }
+  return other;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_str_code(const struct soap_code_map *map, long code)
+{ while (map->code != code && map->string)
+    map++;
+  return map->string;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+static soap_wchar
+soap_char(struct soap *soap)
+{ char tmp[8];
+  register int i;
+  register soap_wchar c;
+  register char *s = tmp;
+  for (i = 0; i < 7; i++)
+  { c = soap_get1(soap);
+    if (c == ';' || (int)c == EOF)
+      break;
+    *s++ = (char)c;
+  }
+  *s = '\0';
+  if (*tmp == '#')
+  { if (tmp[1] == 'x' || tmp[1] == 'X')
+      return soap_strtol(tmp + 2, NULL, 16);
+    return atol(tmp + 1);
+  }
+  if (!strcmp(tmp, "lt"))
+    return '<';
+  if (!strcmp(tmp, "gt"))
+    return '>';
+  if (!strcmp(tmp, "amp"))
+    return '&';
+  if (!strcmp(tmp, "quot"))
+    return '"';
+  if (!strcmp(tmp, "apos"))
+    return '\'';
+#ifndef WITH_LEAN
+  return (soap_wchar)soap_int_code(html_entity_codes, tmp, SOAP_UNKNOWN_CHAR);
+#else
+  return SOAP_UNKNOWN_CHAR; /* use this to represent unknown code */
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifdef WITH_LEAN
+soap_wchar
+soap_get0(struct soap *soap)
+{ if (soap->bufidx >= soap->buflen && soap_recv(soap))
+    return EOF;
+  return (unsigned char)soap->buf[soap->bufidx];
+}
+#endif
+
+/******************************************************************************/
+#ifdef WITH_LEAN
+soap_wchar
+soap_get1(struct soap *soap)
+{ if (soap->bufidx >= soap->buflen && soap_recv(soap))
+    return EOF;
+  return (unsigned char)soap->buf[soap->bufidx++];
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+soap_wchar
+SOAP_FMAC2
+soap_get(struct soap *soap)
+{ register soap_wchar c;
+  c = soap->ahead;
+  if (c)
+  { if (c != EOF)
+      soap->ahead = 0;
+  }
+  else
+    c = soap_get1(soap);
+  for (;;)
+  { if (soap->cdata)
+    { if (c == ']')
+      { c = soap_get1(soap);
+        if (c == ']')
+        { soap->cdata = 0;
+          soap_get1(soap); /* skip > */
+          c = soap_get1(soap);
+        }
+	else
+        { soap_revget1(soap);
+          return ']';
+        }
+      }
+      else
+        return c;
+    }
+    switch (c)
+    { case '<':
+        do c = soap_get1(soap);
+        while (soap_blank(c));
+        if (c == '!' || c == '?' || c == '%')
+        { register int k = 1;
+	  if (c == '!')
+          { c = soap_get1(soap);
+            if (c == '[')
+            { do c = soap_get1(soap);
+              while ((int)c != EOF && c != '[');
+              if ((int)c == EOF)
+                break;
+              soap->cdata = 1;
+              c = soap_get1(soap);
+	      continue;
+            }
+            if (c == '-' && (c = soap_get1(soap)) == '-')
+            { do
+              { c = soap_get1(soap);
+                if (c == '-' && (c = soap_get1(soap)) == '-')
+                  break;
+              } while ((int)c != EOF);
+            }
+          }
+          while ((int)c != EOF)
+          { if (c == '<')
+	      k++;
+	    else if (c == '>')
+	    { if (--k <= 0)
+	        break;
+	    }
+	    c = soap_get1(soap);
+	  }
+	  if ((int)c == EOF)
+	    break;
+          c = soap_get1(soap);
+          continue;
+        }
+        if (c == '/')
+          return SOAP_TT;
+        soap_revget1(soap);
+        return SOAP_LT;
+      case '>':
+        return SOAP_GT;
+      case '"':
+        return SOAP_QT;
+      case '\'':
+        return SOAP_AP;
+      case '&':
+        return soap_char(soap) | 0x80000000;
+    }
+    break;
+  }
+  return c;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_move(struct soap *soap, long n)
+{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Moving %ld bytes forward\n", (long)n));
+  for (; n > 0; n--)
+    if ((int)soap_getchar(soap) == EOF)
+      return SOAP_EOF;
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+size_t
+SOAP_FMAC2
+soap_tell(struct soap *soap)
+{ return soap->count - soap->buflen + soap->bufidx - (soap->ahead != 0);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_pututf8(struct soap *soap, register unsigned long c)
+{ char tmp[16];
+  if (c > 0 && c < 0x80)
+  { *tmp = (char)c;
+    return soap_send_raw(soap, tmp, 1);
+  }
+#ifndef WITH_LEAN
+  if (soap->mode & SOAP_XML_CANONICAL)
+  { register char *t = tmp;
+    if (c < 0x0800)
+      *t++ = (char)(0xC0 | ((c >> 6) & 0x1F));
+    else
+    { if (c < 0x010000)
+        *t++ = (char)(0xE0 | ((c >> 12) & 0x0F));
+      else
+      { if (c < 0x200000)
+          *t++ = (char)(0xF0 | ((c >> 18) & 0x07));
+        else
+        { if (c < 0x04000000)
+            *t++ = (char)(0xF8 | ((c >> 24) & 0x03));
+          else
+          { *t++ = (char)(0xFC | ((c >> 30) & 0x01));
+            *t++ = (char)(0x80 | ((c >> 24) & 0x3F));
+          }
+          *t++ = (char)(0x80 | ((c >> 18) & 0x3F));
+        }     
+        *t++ = (char)(0x80 | ((c >> 12) & 0x3F));
+      }
+      *t++ = (char)(0x80 | ((c >> 6) & 0x3F));
+    }
+    *t++ = (char)(0x80 | (c & 0x3F));
+    *t = '\0';
+  }
+  else
+#endif
+    sprintf(tmp, "&#%lu;", c);
+  return soap_send(soap, tmp);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+soap_wchar
+SOAP_FMAC2
+soap_getutf8(struct soap *soap)
+{ register soap_wchar c, c1, c2, c3, c4;
+  c = soap_get(soap);
+  if (c < 0x80 || (soap->mode & SOAP_ENC_LATIN))
+    return c;
+  c1 = soap_get(soap);
+  if (c1 < 0x80)
+  { soap_unget(soap, c1);
+    return c;
+  }
+  c1 &= 0x3F;
+  if (c < 0xE0)
+    return ((soap_wchar)(c & 0x1F) << 6) | c1;
+  c2 = (soap_wchar)soap_get1(soap) & 0x3F;
+  if (c < 0xF0)
+    return ((soap_wchar)(c & 0x0F) << 12) | (c1 << 6) | c2;
+  c3 = (soap_wchar)soap_get1(soap) & 0x3F;
+  if (c < 0xF8)
+    return ((soap_wchar)(c & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
+  c4 = (soap_wchar)soap_get1(soap) & 0x3F;
+  if (c < 0xFC)
+    return ((soap_wchar)(c & 0x03) << 24) | (c1 << 18) | (c2 << 12) | (c3 << 6) | c4;
+  return ((soap_wchar)(c & 0x01) << 30) | (c1 << 24) | (c2 << 18) | (c3 << 12) | (c4 << 6) | (soap_wchar)(soap_get1(soap) & 0x3F);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_puthex(struct soap *soap, const unsigned char *s, int n)
+{ char d[2];
+  register int i;
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { if (!(soap->dom->data = soap_s2hex(soap, s, NULL, n)))
+      return soap->error;
+    return SOAP_OK;
+  }
+#endif
+  for (i = 0; i < n; i++)
+  { register int m = *s++;
+    d[0] = (char)((m >> 4) + (m > 159 ? '7' : '0'));
+    m &= 0x0F;
+    d[1] = (char)(m + (m > 9 ? '7' : '0'));
+    if (soap_send_raw(soap, d, 2))
+      return soap->error;
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+unsigned char*
+SOAP_FMAC2
+soap_gethex(struct soap *soap, int *n)
+{
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { soap->dom->data = soap_string_in(soap, 0, -1, -1);
+    return (unsigned char*)soap_hex2s(soap, soap->dom->data, NULL, 0, n);
+  }
+#endif
+#ifdef WITH_FAST
+  soap->labidx = 0;
+  for (;;)
+  { register char *s;
+    register int i, k;
+    if (soap_append_lab(soap, NULL, 0))
+      return NULL;
+    s = soap->labbuf + soap->labidx;
+    k = soap->lablen - soap->labidx;
+    soap->labidx = soap->lablen;
+    for (i = 0; i < k; i++)
+    { register char d1, d2;
+      register soap_wchar c;
+      c = soap_get(soap);
+      if (soap_isxdigit(c))
+      { d1 = (char)c;
+        c = soap_get(soap); 
+	if (soap_isxdigit(c))
+          d2 = (char)c;
+        else 
+        { soap->error = SOAP_TYPE;
+          return NULL;
+        }
+      }
+      else
+      { unsigned char *p;
+        soap_unget(soap, c);
+        if (n)
+          *n = (int)(soap->lablen - k + i);
+        p = (unsigned char*)soap_malloc(soap, soap->lablen - k + i);
+	if (p)
+	  memcpy(p, soap->labbuf, soap->lablen - k + i);
+        return p;
+      }
+      *s++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0');
+    }
+  }
+#else
+  if (soap_new_block(soap))
+    return NULL;
+  for (;;)
+  { register int i;
+    register char *s = (char*)soap_push_block(soap, SOAP_BLKLEN);
+    if (!s)
+    { soap_end_block(soap);
+      return NULL;
+    }
+    for (i = 0; i < SOAP_BLKLEN; i++)
+    { register char d1, d2;
+      register soap_wchar c = soap_get(soap);
+      if (soap_isxdigit(c))
+      { d1 = (char)c;
+        c = soap_get(soap); 
+	if (soap_isxdigit(c))
+          d2 = (char)c;
+        else 
+        { soap_end_block(soap);
+	  soap->error = SOAP_TYPE;
+          return NULL;
+        }
+      }
+      else
+      { unsigned char *p;
+        soap_unget(soap, c);
+        if (n)
+          *n = soap_size_block(soap, i);
+        p = (unsigned char*)soap_save_block(soap, NULL, 0);
+        return p;
+      }
+      *s++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0');
+    }
+  }
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_putbase64(struct soap *soap, const unsigned char *s, int n)
+{ register int i;
+  register unsigned long m;
+  char d[4];
+  if (!s)
+    return SOAP_OK;
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { if (!(soap->dom->data = soap_s2base64(soap, s, NULL, n)))
+      return soap->error;
+    return SOAP_OK;
+  }
+#endif
+  for (; n > 2; n -= 3, s += 3)
+  { m = s[0];
+    m = (m << 8) | s[1];
+    m = (m << 8) | s[2];
+    for (i = 4; i > 0; m >>= 6)
+      d[--i] = soap_base64o[m & 0x3F];
+    if (soap_send_raw(soap, d, 4))
+      return soap->error;
+  }
+  if (n > 0)
+  { m = 0;
+    for (i = 0; i < n; i++)
+      m = (m << 8) | *s++;
+    for (; i < 3; i++)
+      m <<= 8;
+    for (i++; i > 0; m >>= 6)
+      d[--i] = soap_base64o[m & 0x3F];
+    for (i = 3; i > n; i--)
+      d[i] = '=';
+    if (soap_send_raw(soap, d, 4))
+      return soap->error;
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+unsigned char*
+SOAP_FMAC2
+soap_getbase64(struct soap *soap, int *n, int malloc_flag)
+{ 
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { soap->dom->data = soap_string_in(soap, 0, -1, -1);
+    return (unsigned char*)soap_base642s(soap, soap->dom->data, NULL, 0, n);
+  }
+#endif
+#ifdef WITH_FAST
+  soap->labidx = 0;
+  for (;;)
+  { register int i, k;
+    register char *s;
+    if (soap_append_lab(soap, NULL, 2))
+      return NULL;
+    s = soap->labbuf + soap->labidx;
+    k = 3 * ((soap->lablen - soap->labidx) / 3);
+    soap->labidx = 3 * (soap->lablen / 3);
+    if (!s)
+      return NULL;
+    for (i = 0; i < k; i += 3)
+    { register unsigned long m = 0;
+      register int j = 0;
+      do
+      { register soap_wchar c = soap_get(soap);
+        if (c == '=' || c < 0)
+        { unsigned char *p;
+          switch (j)
+          { case 2:
+              *s++ = (char)((m >> 4) & 0xFF);
+              i++;
+              break;
+            case 3:
+              *s++ = (char)((m >> 10) & 0xFF);
+              *s++ = (char)((m >> 2) & 0xFF);
+              i += 2;
+          }
+          if (n)
+            *n = (int)(soap->lablen - k + i - 1);
+          p = (unsigned char*)soap_malloc(soap, soap->lablen - k + i - 1);
+	  if (p)
+	    memcpy(p, soap->labbuf, soap->lablen - k + i - 1);
+          if (c >= 0)
+          { while ((int)((c = soap_get(soap)) != EOF) && c != SOAP_LT && c != SOAP_TT)
+              ;
+	  }
+          soap_unget(soap, c);
+          return p;
+        }
+        c -= '+';
+        if (c >= 0 && c <= 79)
+        { m = (m << 6) + soap_base64i[c];
+          j++;
+        }
+      } while (j < 4);
+      *s++ = (char)((m >> 16) & 0xFF);
+      *s++ = (char)((m >> 8) & 0xFF);
+      *s++ = (char)(m & 0xFF);
+    }
+  }
+#else
+  if (soap_new_block(soap))
+    return NULL;
+  for (;;)
+  { register int i;
+    register char *s = (char*)soap_push_block(soap, 3 * SOAP_BLKLEN); /* must be multiple of 3 */
+    if (!s)
+    { soap_end_block(soap);
+      return NULL;
+    }
+    for (i = 0; i < SOAP_BLKLEN; i++)
+    { register unsigned long m = 0;
+      register int j = 0;
+      do
+      { register soap_wchar c = soap_get(soap);
+        if (c == '=' || c < 0)
+        { unsigned char *p;
+          i *= 3;
+          switch (j)
+          { case 2:
+              *s++ = (char)((m >> 4) & 0xFF);
+              i++;
+              break;
+            case 3:
+              *s++ = (char)((m >> 10) & 0xFF);
+              *s++ = (char)((m >> 2) & 0xFF);
+              i += 2;
+          }
+          if (n)
+	    *n = (int)soap_size_block(soap, i);
+          p = (unsigned char*)soap_save_block(soap, NULL, 0);
+          if (c >= 0)
+          { while ((int)((c = soap_get(soap)) != EOF) && c != SOAP_LT && c != SOAP_TT)
+              ;
+	  }
+          soap_unget(soap, c);
+          return p;
+        }
+        c -= '+';
+        if (c >= 0 && c <= 79)
+        { m = (m << 6) + soap_base64i[c];
+          j++;
+        }
+      } while (j < 4);
+      *s++ = (char)((m >> 16) & 0xFF);
+      *s++ = (char)((m >> 8) & 0xFF);
+      *s++ = (char)(m & 0xFF);
+    }
+  }
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_xop_forward(struct soap *soap, unsigned char **ptr, int *size, char **id, char **type, char **options)
+{ /* Check MTOM xop:Include element (within hex/base64Binary) */
+  /* TODO: this code to be obsoleted with new import/xop.h conventions */
+  int body = soap->body; /* should save type too? */
+  if (!soap_peek_element(soap))
+  { if (!soap_element_begin_in(soap, "xop:Include", 0) && *soap->href)
+    { if (soap_dime_forward(soap, ptr, size, id, type, options))
+        return soap->error;
+    }
+    if (soap->body && soap_element_end_in(soap, NULL))
+      return soap->error;
+  }
+  soap->body = body;
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_dime_forward(struct soap *soap, unsigned char **ptr, int *size, char **id, char **type, char **options)
+{ struct soap_xlist *xp = (struct soap_xlist*)SOAP_MALLOC(soap, sizeof(struct soap_xlist));
+  *ptr = NULL;
+  *size = 0;
+  *id = soap_strdup(soap, soap->href);
+  *type = NULL;
+  *options = NULL;
+  if (!xp)
+    return soap->error = SOAP_EOM;
+  xp->next = soap->xlist;
+  xp->ptr = ptr;
+  xp->size = size;
+  xp->id = *id;
+  xp->type = type;
+  xp->options = options;
+  soap->xlist = xp;
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_strdup(struct soap *soap, const char *s)
+{ char *t = NULL;
+  if (s && (t = (char*)soap_malloc(soap, strlen(s) + 1)))
+    strcpy(t, s);
+  return t;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_new_block(struct soap *soap)
+{ struct soap_blist *p;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "New block sequence (prev=%p)\n", soap->blist));
+  if (!(p = (struct soap_blist*)SOAP_MALLOC(soap, sizeof(struct soap_blist))))
+    return SOAP_EOM;   
+  p->next = soap->blist; 
+  p->ptr = NULL;
+  p->size = 0;
+  soap->blist = p;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void*
+SOAP_FMAC2
+soap_push_block(struct soap *soap, size_t n)
+{ char *p;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push block of %u bytes (%u bytes total)\n", (unsigned int)n, (unsigned int)soap->blist->size + (unsigned int)n));
+  if (!(p = (char*)SOAP_MALLOC(soap, n + sizeof(char*) + sizeof(size_t))))
+  { soap->error = SOAP_EOM;
+    return NULL;
+  }
+  *(char**)p = soap->blist->ptr;
+  *(size_t*)(p + sizeof(char*)) = n;
+  soap->blist->ptr = p;
+  soap->blist->size += n;
+  return p + sizeof(char*) + sizeof(size_t);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_pop_block(struct soap *soap)
+{ char *p;
+  if (!soap->blist->ptr)
+    return;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pop block\n"));
+  p = soap->blist->ptr;
+  soap->blist->size -= *(size_t*)(p + sizeof(char*));
+  soap->blist->ptr = *(char**)p;
+  SOAP_FREE(soap, p);
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_1
+static void
+soap_update_ptrs(struct soap *soap, char *start, char *end, long offset)
+{ int i;
+  register struct soap_ilist *ip;
+  register struct soap_flist *fp;
+#ifndef WITH_LEANER
+  register struct soap_xlist *xp;
+#endif
+  register void *p, **q;
+  for (i = 0; i < SOAP_IDHASH; i++)
+  { for (ip = soap->iht[i]; ip; ip = ip->next)
+    { if (ip->ptr && (char*)ip->ptr >= start && (char*)ip->ptr < end)
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update id='%s' %p -> %p\n", ip->id, ip->ptr, (char*)ip->ptr + offset));
+        ip->ptr = (char*)ip->ptr + offset;
+      }
+      for (q = &ip->link; q; q = (void**)p)
+      { p = *q;
+        if (p && (char*)p >= start && (char*)p < end)
+        { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Link update id='%s' %p\n", ip->id, p));
+          *q = (char*)p + offset;
+        }
+      }
+      for (q = &ip->copy; q; q = (void**)p)
+      { p = *q;
+        if (p && (char*)p >= start && (char*)p < end)
+        { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy chain update id='%s' %p\n", ip->id, p));
+          *q = (char*)p + offset;
+        }
+      }
+      for (fp = ip->flist; fp; fp = fp->next)
+      { if ((char*)fp->ptr >= start && (char*)fp->ptr < end)
+        { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy list update id='%s' %p\n", ip->id, fp));
+          fp->ptr = (char*)fp->ptr + offset;
+        }
+      }
+    }
+  }
+#ifndef WITH_LEANER
+  for (xp = soap->xlist; xp; xp = xp->next)
+  { if (xp->ptr && (char*)xp->ptr >= start && (char*)xp->ptr < end)
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update id='%s' %p -> %p\n", xp->id?xp->id:"", xp->ptr, (char*)xp->ptr + offset));
+      xp->ptr = (unsigned char**)((char*)xp->ptr + offset);
+      xp->size = (int*)((char*)xp->size + offset);
+      xp->type = (char**)((char*)xp->type + offset);
+      xp->options = (char**)((char*)xp->options + offset);
+    }
+  }
+#endif
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_1
+static int
+soap_has_copies(struct soap *soap, register const char *start, register const char *end)
+{ register int i;
+  register struct soap_ilist *ip;
+  register struct soap_flist *fp;
+  register const char *p;
+  for (i = 0; i < SOAP_IDHASH; i++)
+  { for (ip = soap->iht[i]; ip; ip = ip->next)
+    { for (p = (const char*)ip->copy; p; p = *(const char**)p)
+        if (p >= start && p < end)
+          return SOAP_ERR;
+      for (fp = ip->flist; fp; fp = fp->next)
+        if ((const char*)fp->ptr >= start && (const char*)fp->ptr < end)
+	  return SOAP_ERR;
+    }
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_resolve(struct soap *soap)
+{ register int i;
+  register struct soap_ilist *ip;
+  register struct soap_flist *fp;
+  short flag;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving forwarded data\n"));
+  for (i = 0; i < SOAP_IDHASH; i++)
+  { for (ip = soap->iht[i]; ip; ip = ip->next)
+    { if (ip->ptr)
+      { register void *p, **q, *r;
+        q = (void**)ip->link;
+        ip->link = NULL;
+        r = ip->ptr;
+        DBGLOG(TEST, if (q) SOAP_MESSAGE(fdebug, "Traversing link chain to resolve id='%s'\n", ip->id));
+        while (q)
+        { p = *q;
+          *q = r;
+          DBGLOG(TEST,SOAP_MESSAGE(fdebug, "... link %p -> %p\n", q, r));
+          q = (void**)p;
+        }
+      }
+      else if (*ip->id == '#')
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Missing data for id='%s'\n", ip->id));
+        strcpy(soap->id, ip->id + 1);
+        return soap->error = SOAP_MISSING_ID;
+      }
+    }
+  }
+  do
+  { flag = 0;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution phase\n"));
+    for (i = 0; i < SOAP_IDHASH; i++)
+    { for (ip = soap->iht[i]; ip; ip = ip->next)
+      { if (ip->ptr && !soap_has_copies(soap, (const char*)ip->ptr, (const char*)ip->ptr + ip->size))
+        { if (ip->copy)
+          { register void *p, **q = (void**)ip->copy;
+            DBGLOG(TEST, if (q) SOAP_MESSAGE(fdebug, "Traversing copy chain to resolve id='%s'\n", ip->id));
+            ip->copy = NULL;
+            do
+            { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "... copy %p -> %p (%u bytes)\n", ip->ptr, q, (unsigned int)ip->size));
+	      p = *q;
+              memcpy(q, ip->ptr, ip->size);
+              q = (void**)p;
+            } while (q);
+	    flag = 1;
+	  }
+          for (fp = ip->flist; fp; fp = ip->flist)
+          { register unsigned int k = fp->level;
+	    register void *p = ip->ptr;
+            DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving forwarded data type=%d location=%p level=%u,%u id='%s'\n", ip->type, p, ip->level, fp->level, ip->id));
+	    while (ip->level < k)
+            { register void **q = (void**)soap_malloc(soap, sizeof(void*));  
+	      if (!q)
+	        return soap->error;
+	      *q = p;
+              DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level, new location=%p holds=%p...\n", q, *q));
+              p = (void*)q;
+              k--;
+            }
+	    if (fp->fcopy)
+	      fp->fcopy(soap, ip->type, fp->type, fp->ptr, p, ip->size);
+	    else
+	      soap_fcopy(soap, ip->type, fp->type, fp->ptr, p, ip->size);
+	    ip->flist = fp->next;
+	    SOAP_FREE(soap, fp);
+	    flag = 1;
+	  }
+        }
+      }
+    }
+  } while (flag);
+#ifdef SOAP_DEBUG
+  for (i = 0; i < SOAP_IDHASH; i++)
+  { for (ip = soap->iht[i]; ip; ip = ip->next)
+    { if (ip->copy || ip->flist)
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution error: forwarded data for id='%s' could not be propagated, please report this problem to the developers\n", ip->id));
+      }
+    }
+  }
+#endif
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolution done\n"));
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+size_t
+SOAP_FMAC2
+soap_size_block(struct soap *soap, size_t n)
+{ if (soap->blist->ptr)
+  { soap->blist->size -= *(size_t*)(soap->blist->ptr + sizeof(char*)) - n;
+    *(size_t*)(soap->blist->ptr + sizeof(char*)) = n;
+  }
+  return soap->blist->size;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+char*
+SOAP_FMAC2
+soap_first_block(struct soap *soap)
+{ char *p, *q, *r;
+  p = soap->blist->ptr;
+  if (!p)
+    return NULL;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "First block\n"));
+  r = NULL;
+  do
+  { q = *(char**)p;
+    *(char**)p = r;
+    r = p;
+    p = q;
+  } while (p);
+  soap->blist->ptr = r;
+  return r + sizeof(char*) + sizeof(size_t);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+char*
+SOAP_FMAC2
+soap_next_block(struct soap *soap)
+{ char *p;
+  p = soap->blist->ptr;
+  if (p)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Next block\n"));
+    soap->blist->ptr = *(char**)p;
+    SOAP_FREE(soap, p);
+    if (soap->blist->ptr)
+      return soap->blist->ptr + sizeof(char*) + sizeof(size_t);
+  }
+  return NULL;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+size_t
+SOAP_FMAC2
+soap_block_size(struct soap *soap)
+{ return *(size_t*)(soap->blist->ptr + sizeof(char*));
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_end_block(struct soap *soap)
+{ struct soap_blist *bp;
+  char *p, *q;
+  bp = soap->blist;
+  if (bp)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of block sequence, free all remaining blocks\n"));
+    for (p = bp->ptr; p; p = q)
+    { q = *(char**)p;
+      SOAP_FREE(soap, p);
+    }
+    soap->blist = bp->next;
+    SOAP_FREE(soap, bp);
+  }
+  DBGLOG(TEST, if (soap->blist) SOAP_MESSAGE(fdebug, "Restore previous block sequence\n"));
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+char*
+SOAP_FMAC2
+soap_save_block(struct soap *soap, char *p, int flag)
+{ register size_t n;
+  register char *q, *s;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Save all blocks in contiguous memory space of %u bytes (%p->%p)\n", (unsigned int)soap->blist->size, soap->blist->ptr, p));
+  if (soap->blist->size)
+  { if (!p)
+      p = (char*)soap_malloc(soap, soap->blist->size);
+    if (p)
+    { for (s = p, q = soap_first_block(soap); q; q = soap_next_block(soap))
+      { n = soap_block_size(soap);
+#ifndef WITH_NOIDREF
+        if (flag)
+	  soap_update_ptrs(soap, q, q + n, (long)s - (long)q); /* pointers s and q may or may not be related */
+#endif
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy %u bytes from %p to %p\n", (unsigned int)n, q, s));
+        memcpy(s, q, n);
+        s += n;
+      }
+    }
+    else
+      soap->error = SOAP_EOM;
+  }
+  soap_end_block(soap);
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_putsize(struct soap *soap, const char *type, int size)
+{ return soap_putsizes(soap, type, &size, 1);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_putsizes(struct soap *soap, const char *type, const int *size, int dim)
+{ return soap_putsizesoffsets(soap, type, size, NULL, dim);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_putsizesoffsets(struct soap *soap, const char *type, const int *size, const int *offset, int dim)
+{ int i;
+  if (!type)
+    return NULL;
+  if (soap->version == 2)
+  { sprintf(soap->type, "%s[%d", type, size[0]);
+    for (i = 1; i < dim; i++)
+      sprintf(soap->type + strlen(soap->type), " %d", size[i]);
+  }
+  else
+  { if (offset)
+    { sprintf(soap->type, "%s[%d", type, size[0] + offset[0]);
+      for (i = 1; i < dim; i++)
+        sprintf(soap->type + strlen(soap->type), ",%d", size[i] + offset[i]);
+    }
+    else
+    { sprintf(soap->type, "%s[%d", type, size[0]);
+      for (i = 1; i < dim; i++)
+        sprintf(soap->type + strlen(soap->type), ",%d", size[i]);
+    }
+    strcat(soap->type, "]");
+  }
+  return soap->type;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_putoffset(struct soap *soap, int offset)
+{ return soap_putoffsets(soap, &offset, 1);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_putoffsets(struct soap *soap, const int *offset, int dim)
+{ register int i;
+  sprintf(soap->arrayOffset, "[%d", offset[0]);
+  for (i = 1; i < dim; i++)
+    sprintf(soap->arrayOffset + strlen(soap->arrayOffset), ",%d", offset[i]);
+  strcat(soap->arrayOffset, "]");
+  return soap->arrayOffset;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_size(const int *size, int dim)
+{ register int i, n = size[0];
+  for (i = 1; i < dim; i++)
+    n *= size[i];
+  return n;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getoffsets(const char *attr, const int *size, int *offset, int dim)
+{ register int i, j = 0;
+  if (offset)
+    for (i = 0; i < dim && attr && *attr; i++)
+    { attr++;
+      j *= size[i];
+      j += offset[i] = (int)atol(attr);
+      attr = strchr(attr, ',');
+    }
+  else
+    for (i = 0; i < dim && attr && *attr; i++)
+    { attr++;
+      j *= size[i];
+      j += (int)atol(attr);
+      attr = strchr(attr, ',');
+    }
+  return j;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getsize(const char *attr1, const char *attr2, int *j)
+{ register int n, k;
+  char *s;
+  *j = 0;
+  if (!*attr1)
+    return -1;
+  if (*attr1 == '[')
+    attr1++;
+  n = 1;
+  for (;;)
+  { k = (int)soap_strtol(attr1, &s, 10);
+    n *= k;
+    if (k < 0 || n > SOAP_MAXARRAYSIZE || s == attr1)
+      return -1;
+    attr1 = strchr(s, ',');
+    if (!attr1)
+      attr1 = strchr(s, ' ');
+    if (attr2 && *attr2)
+    { attr2++;
+      *j *= k;
+      k = (int)soap_strtol(attr2, &s, 10);
+      *j += k;
+      if (k < 0)
+        return -1;
+      attr2 = s;
+    }
+    if (!attr1)
+      break;
+    attr1++;
+  }
+  return n - *j;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getsizes(const char *attr, int *size, int dim)
+{ register int i, k, n;
+  if (!*attr)
+    return -1;
+  i = strlen(attr);
+  n = 1;
+  do
+  { for (i = i-1; i >= 0; i--)
+      if (attr[i] == '[' || attr[i] == ',' || attr[i] == ' ')
+        break;
+    k = (int)atol(attr + i + 1);
+    n *= size[--dim] = k;
+    if (k < 0 || n > SOAP_MAXARRAYSIZE)
+      return -1;
+  } while (i >= 0 && attr[i] != '[');
+  return n;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getposition(const char *attr, int *pos)
+{ register int i, n;
+  if (!*attr)
+    return -1;
+  n = 0;
+  i = 1;
+  do
+  { pos[n++] = (int)atol(attr + i);
+    while (attr[i] && attr[i] != ',' && attr[i] != ']')
+      i++;
+    if (attr[i] == ',')
+      i++;
+  } while (n < SOAP_MAXDIMS && attr[i] && attr[i] != ']');
+  return n;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_push_namespace(struct soap *soap, const char *id, const char *ns)
+{ register struct soap_nlist *np;
+  register struct Namespace *p;
+  register short i = -1;
+  register size_t n, k;
+  n = strlen(id);
+  k = strlen(ns) + 1;
+  p = soap->local_namespaces;
+  if (p)
+  { for (i = 0; p->id; p++, i++)
+    { if (p->ns && !strcmp(ns, p->ns))
+      { if (p->out)
+        { SOAP_FREE(soap, p->out);
+          p->out = NULL;
+        }
+        break;
+      }
+      if (p->out)
+      { if (!strcmp(ns, p->out))
+          break;
+      }
+      else if (p->in)
+      { if (!soap_tag_cmp(ns, p->in))
+        { if ((p->out = (char*)SOAP_MALLOC(soap, k)))
+            strcpy(p->out, ns);
+          break;
+        }
+      }
+    }
+    if (!p || !p->id)
+      i = -1;
+  }
+  if (i >= 0)
+    k = 0;
+  np = (struct soap_nlist*)SOAP_MALLOC(soap, sizeof(struct soap_nlist) + n + k);
+  if (!np)
+    return soap->error = SOAP_EOM;
+  np->next = soap->nlist;
+  soap->nlist = np;
+  np->level = soap->level;
+  np->index = i;
+  strcpy(np->id, id);
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push namespace binding (level=%u) '%s' '%s'\n", soap->level, id, ns));
+  if (i < 0)
+  { np->ns = np->id + n + 1;
+    strcpy(np->ns, ns);
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push NOT OK: no match found for '%s' in namespace mapping table (added to stack anyway)\n", ns));
+  }
+  else
+  { np->ns = NULL;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push OK ('%s' matches '%s' in namespace table)\n", id, p->id));
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_pop_namespace(struct soap *soap)
+{ register struct soap_nlist *np;
+  while (soap->nlist && soap->nlist->level >= soap->level)
+  { np = soap->nlist->next;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Popped namespace binding (level=%u) '%s'\n", soap->level, soap->nlist->id));
+    SOAP_FREE(soap, soap->nlist);
+    soap->nlist = np;
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_match_namespace(struct soap *soap, const char *id1, const char *id2, int n1, int n2) 
+{ register struct soap_nlist *np = soap->nlist;
+  while (np && (strncmp(np->id, id1, n1) || np->id[n1]))
+    np = np->next;
+  if (np)
+  { if (np->index < 0
+     || (soap->local_namespaces[np->index].id
+      && (strncmp(soap->local_namespaces[np->index].id, id2, n2)
+       || soap->local_namespaces[np->index].id[n2])))
+      return SOAP_NAMESPACE;
+    return SOAP_OK;
+  }
+  if (n1 == 3 && n1 == n2 && !strcmp(id1, "xml") && !strcmp(id1, id2))
+    return SOAP_OK;
+  return SOAP_SYNTAX_ERROR; 
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_tag_cmp(const char *s, const char *t)
+{ for (;;)
+  { register int c1 = *s;
+    register int c2 = *t;
+    if (!c1 || c1 == '"')
+      break;
+    if (c2 != '-')
+    { if (c1 != c2)
+      { if (c1 >= 'A' && c1 <= 'Z')
+          c1 += 'a' - 'A';
+        if (c2 >= 'A' && c2 <= 'Z')
+          c2 += 'a' - 'A';
+      }
+      if (c1 != c2)
+      { if (c2 != '*')
+          return 1;
+	c2 = *++t;
+        if (!c2)
+	  return 0;
+        if (c2 >= 'A' && c2 <= 'Z')
+          c2 += 'a' - 'A';
+        for (;;)
+        { c1 = *s;
+	  if (!c1 || c1 == '"')
+	    break;
+	  if (c1 >= 'A' && c1 <= 'Z')
+            c1 += 'a' - 'A';
+          if (c1 == c2 && !soap_tag_cmp(s + 1, t + 1))
+            return 0;
+	  s++;
+        }
+        break;
+      }
+    }
+    s++;
+    t++;
+  }
+  if (*t == '*' && !t[1])
+    return 0;
+  return *t;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_match_tag(struct soap *soap, const char *tag1, const char *tag2)
+{ register const char *s, *t;
+  if (!tag1 || !tag2 || !*tag2)
+    return SOAP_OK;
+  s = strchr(tag1, ':');
+  t = strchr(tag2, ':');
+  if (t)
+  { if (s)
+    { if (t[1] && SOAP_STRCMP(s + 1, t + 1))
+        return SOAP_TAG_MISMATCH;
+      if (t != tag2 && soap_match_namespace(soap, tag1, tag2, s - tag1, t - tag2))
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags '%s' and '%s' match but namespaces differ\n", tag1, tag2));
+        return SOAP_TAG_MISMATCH;
+      }
+    } 
+    else if (SOAP_STRCMP(tag1, t + 1))
+      return SOAP_TAG_MISMATCH;
+    else if (t != tag2 && soap_match_namespace(soap, tag1, tag2, 0, t - tag2))
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags '%s' and '%s' match but namespaces differ\n", tag1, tag2));
+      return SOAP_TAG_MISMATCH;
+    }
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags and (default) namespaces match: '%s' '%s'\n", tag1, tag2));
+    return SOAP_OK;
+  }
+  if (s)
+  { if (SOAP_STRCMP(s + 1, tag2))
+      return SOAP_TAG_MISMATCH;
+  }
+  else if (SOAP_STRCMP(tag1, tag2))
+    return SOAP_TAG_MISMATCH;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Tags match: '%s' '%s'\n", tag1, tag2));
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_match_array(struct soap *soap, const char *type)
+{ if (*soap->arrayType)
+    if (soap_match_tag(soap, soap->arrayType, type)
+     && soap_match_tag(soap, soap->arrayType, "xsd:anyType")
+     && soap_match_tag(soap, soap->arrayType, "xsd:ur-type")
+    )
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array type mismatch: '%s' '%s'\n", soap->arrayType, type));
+      return SOAP_TAG_MISMATCH;
+    }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+
+#ifdef WITH_OPENSSL
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_rand()
+{ unsigned char buf[4];
+  ssl_init();
+  RAND_pseudo_bytes(buf, 4);
+  return *(int*)buf;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_ssl_server_context(struct soap *soap, unsigned short flags, const char *keyfile, const char *password, const char *cafile, const char *capath, const char *dhfile, const char *randfile, const char *sid)
+{ int err;
+  soap->keyfile = keyfile;
+  soap->password = password;
+  soap->cafile = cafile;
+  soap->capath = capath;
+  if (dhfile)
+  { soap->dhfile = dhfile;
+    soap->rsa = 0;
+  }
+  else
+  { soap->dhfile = NULL;
+    soap->rsa = 1;
+  }
+  soap->randfile = randfile;
+  soap->require_client_auth = (flags & SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION);
+  if (!(err = soap->fsslauth(soap)))
+    if (sid)
+      SSL_CTX_set_session_id_context(soap->ctx, (unsigned char*)sid, strlen(sid));
+  return err; 
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_ssl_client_context(struct soap *soap, unsigned short flags, const char *keyfile, const char *password, const char *cafile, const char *capath, const char *randfile)
+{ soap->keyfile = keyfile;
+  soap->password = password;
+  soap->cafile = cafile;
+  soap->capath = capath;
+  soap->dhfile = NULL;
+  soap->rsa = 0;
+  soap->randfile = randfile;
+  soap->require_server_auth = (flags & SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION);
+  return soap->fsslauth(soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+static void
+ssl_init()
+{ static int done = 0;
+  if (!done)
+  { done = 1;
+    SSL_library_init();
+#ifndef WITH_LEAN
+    SSL_load_error_strings();
+#endif
+    if (!RAND_load_file("/dev/urandom", 1024))
+    { char buf[1024];
+      RAND_seed(buf, sizeof(buf));
+      while (!RAND_status())
+      { int r = rand();
+        RAND_seed(&r, sizeof(int));
+      }
+    }
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+static const char *
+ssl_error(struct soap *soap, int ret)
+{ int err = SSL_get_error(soap->ssl, ret);
+  const char *msg = soap_str_code(h_ssl_error_codes, err);
+  if (msg)
+    strcpy(soap->msgbuf, msg);
+  else
+    return ERR_error_string(err, soap->msgbuf);
+  if (ERR_peek_error())
+  { unsigned long r;
+    strcat(soap->msgbuf, "\n");
+    while ((r = ERR_get_error()))
+      ERR_error_string_n(r, soap->msgbuf + strlen(soap->msgbuf), sizeof(soap->msgbuf) - strlen(soap->msgbuf));
+  } 
+  else
+  { switch (ret)
+    { case 0:
+        strcpy(soap->msgbuf, "EOF was observed that violates the protocol. The client probably provided invalid authentication information.");
+        break;
+      case -1:
+        sprintf(soap->msgbuf, "Error observed by underlying BIO: %s", strerror(errno));  
+        break;
+    }
+  }
+  return soap->msgbuf;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+static int
+ssl_password(char *buf, int num, int rwflag, void *userdata)
+{ if (num < (int)strlen((char*)userdata) + 1)
+    return 0;
+  return strlen(strcpy(buf, (char*)userdata));
+}
+#endif
+
+/******************************************************************************/
+/* This callback is included for future references. It should not be deleted
+#ifndef PALM_2
+static DH *
+ssl_tmp_dh(SSL *ssl, int is_export, int keylength)
+{ static DH *dh512 = NULL;
+  static DH *dh1024 = NULL;
+  DH *dh;
+  switch (keylength)
+  { case 512:
+      if (!dh512)
+      { BIO *bio = BIO_new_file("dh512.pem", "r");
+        if (bio)
+        { dh512 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
+          BIO_free(bio);
+          return dh512;
+        }
+      }
+      else
+        return dh512;
+    default:
+      if (!dh1024)
+      { BIO *bio = BIO_new_file("dh1024.pem", "r");
+        if (bio)
+        { dh1024 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
+          BIO_free(bio);
+        }
+      }
+      dh = dh1024;
+  }
+  return dh;
+}
+#endif
+*/
+
+/******************************************************************************/
+#ifndef PALM_1
+static int
+ssl_auth_init(struct soap *soap)
+{ ssl_init();
+  if (!soap->ctx)
+  { if (!(soap->ctx = SSL_CTX_new(SSLv23_method())))
+      return soap_set_receiver_error(soap, "SSL error", "Can't setup context", SOAP_SSL_ERROR);
+  }
+  if (soap->randfile)
+  { if (!RAND_load_file(soap->randfile, -1))
+      return soap_set_receiver_error(soap, "SSL error", "Can't load randomness", SOAP_SSL_ERROR);
+  }
+  if (soap->cafile || soap->capath)
+  { if (!SSL_CTX_load_verify_locations(soap->ctx, soap->cafile, soap->capath))
+      return soap_set_receiver_error(soap, "SSL error", "Can't read CA file and directory", SOAP_SSL_ERROR);
+  }
+  if (!SSL_CTX_set_default_verify_paths(soap->ctx))
+    return soap_set_receiver_error(soap, "SSL error", "Can't read default CA file and/or directory", SOAP_SSL_ERROR);
+/* See below */
+  if (soap->keyfile)
+  { if (!SSL_CTX_use_certificate_chain_file(soap->ctx, soap->keyfile))
+      return soap_set_receiver_error(soap, "SSL error", "Can't read certificate key file", SOAP_SSL_ERROR);
+    if (soap->password)
+    { SSL_CTX_set_default_passwd_cb_userdata(soap->ctx, (void*)soap->password);
+      SSL_CTX_set_default_passwd_cb(soap->ctx, ssl_password);
+    }
+    if (!SSL_CTX_use_PrivateKey_file(soap->ctx, soap->keyfile, SSL_FILETYPE_PEM))
+      return soap_set_receiver_error(soap, "SSL error", "Can't read key file", SOAP_SSL_ERROR);
+  }
+/* Suggested alternative approach to check cafile first before the key file:
+  if (soap->password)
+  { SSL_CTX_set_default_passwd_cb_userdata(soap->ctx, (void*)soap->password);
+    SSL_CTX_set_default_passwd_cb(soap->ctx, ssl_password);
+  }
+  if (!soap->cafile || !SSL_CTX_use_certificate_chain_file(soap->ctx, soap->cafile))
+  { if (soap->keyfile)
+    { if (!SSL_CTX_use_certificate_chain_file(soap->ctx, soap->keyfile))
+        return soap_set_receiver_error(soap, "SSL error", "Can't read certificate or key file", SOAP_SSL_ERROR);
+      if (!SSL_CTX_use_PrivateKey_file(soap->ctx, soap->keyfile, SSL_FILETYPE_PEM))
+        return soap_set_receiver_error(soap, "SSL error", "Can't read key file", SOAP_SSL_ERROR);
+    }
+  }
+*/
+  if (soap->rsa)
+  { RSA *rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
+    if (!SSL_CTX_set_tmp_rsa(soap->ctx, rsa))
+    { if (rsa)
+        RSA_free(rsa);
+      return soap_set_receiver_error(soap, "SSL error", "Can't set RSA key", SOAP_SSL_ERROR);
+    }
+    RSA_free(rsa);
+  }
+  else if (soap->dhfile)
+  { DH *dh = 0;
+    BIO *bio;
+    bio = BIO_new_file(soap->dhfile, "r");
+    if (!bio)
+      return soap_set_receiver_error(soap, "SSL error", "Can't read DH file", SOAP_SSL_ERROR);
+    dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
+    BIO_free(bio);
+    if (SSL_CTX_set_tmp_dh(soap->ctx, dh) < 0)
+    { if (dh)
+        DH_free(dh);
+      return soap_set_receiver_error(soap, "SSL error", "Can't set DH parameters", SOAP_SSL_ERROR);
+    }
+    DH_free(dh);
+  }
+  SSL_CTX_set_options(soap->ctx, SSL_OP_ALL | SSL_OP_NO_SSLv2);
+  SSL_CTX_set_verify(soap->ctx, soap->require_client_auth ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT) : soap->require_server_auth ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, soap->fsslverify);
+#if (OPENSSL_VERSION_NUMBER < 0x00905100L)
+  SSL_CTX_set_verify_depth(soap->ctx, 1); 
+#else
+  SSL_CTX_set_verify_depth(soap->ctx, 9); 
+#endif  
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+static int
+ssl_verify_callback(int ok, X509_STORE_CTX *store)
+{
+#ifdef SOAP_DEBUG
+  if (!ok) 
+  { char data[256];
+    X509 *cert = X509_STORE_CTX_get_current_cert(store);
+    fprintf(stderr, "SSL verify error or warning with certificate at depth %d: %s\n", X509_STORE_CTX_get_error_depth(store), X509_verify_cert_error_string(X509_STORE_CTX_get_error(store)));
+    X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
+    fprintf(stderr, "certificate issuer %s\n", data);
+    X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
+    fprintf(stderr, "certificate subject %s\n", data);
+  }
+#endif
+  /* Note: return 1 to continue, but unsafe progress will be terminated by SSL */
+  return ok;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_ssl_accept(struct soap *soap)
+{ BIO *bio;
+  int i, r;
+  if (!soap_valid_socket(soap->socket))
+    return soap_set_receiver_error(soap, "SSL error", "No socket in soap_ssl_accept()", SOAP_SSL_ERROR);
+  if (!soap->ctx && (soap->error = soap->fsslauth(soap)))
+    return SOAP_INVALID_SOCKET;
+  if (!soap->ssl)
+  { soap->ssl = SSL_new(soap->ctx);
+    if (!soap->ssl)
+      return soap_set_receiver_error(soap, "SSL error", "SSL_new() failed in soap_ssl_accept()", SOAP_SSL_ERROR);
+  }
+  else
+    SSL_clear(soap->ssl);
+  soap->imode |= SOAP_ENC_SSL;
+  soap->omode |= SOAP_ENC_SSL;
+#ifdef WIN32
+  { u_long nonblocking = 1;
+    ioctlsocket((SOAP_SOCKET)soap->socket, FIONBIO, &nonblocking);
+  }
+#else
+  fcntl((SOAP_SOCKET)soap->socket, F_SETFL, fcntl((SOAP_SOCKET)soap->socket, F_GETFL)|O_NONBLOCK);
+#endif
+  bio = BIO_new_socket((SOAP_SOCKET)soap->socket, BIO_NOCLOSE);
+  SSL_set_bio(soap->ssl, bio, bio);
+  i = 100; /* 100 * 0.1 ms retries */
+  while ((r = SSL_accept(soap->ssl)) <= 0)
+  { int err = SSL_get_error(soap->ssl, r);
+    if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)
+    { struct timeval timeout;
+      fd_set fd;
+      if (i-- <= 0)
+        break;
+      timeout.tv_sec = 0;
+      timeout.tv_usec = 100000;
+      FD_ZERO(&fd);
+      FD_SET((SOAP_SOCKET)soap->socket, &fd);
+      r = select((SOAP_SOCKET)(soap->socket + 1), &fd, NULL, &fd, &timeout);
+      if (r < 0 && soap_socket_errno != SOAP_EINTR)
+      { soap->errnum = soap_socket_errno;
+        return SOAP_EOF;
+      }
+    }
+    else
+    { soap->errnum = err;
+      break;
+    }
+  }
+#ifdef WIN32
+  { u_long blocking = 0;
+    ioctlsocket((SOAP_SOCKET)soap->socket, FIONBIO, &blocking);
+  }
+#else
+  fcntl((SOAP_SOCKET)soap->socket, F_SETFL, fcntl((SOAP_SOCKET)soap->socket, F_GETFL)&~O_NONBLOCK);
+#endif
+  if (r <= 0)
+  { soap_set_receiver_error(soap, ssl_error(soap, r), "SSL_accept() failed in soap_ssl_accept()", SOAP_SSL_ERROR);
+    soap_closesock(soap);
+    return SOAP_SSL_ERROR;
+  }
+  if (soap->require_client_auth)
+  { X509 *peer;
+    int err;
+    if ((err = SSL_get_verify_result(soap->ssl)) != X509_V_OK)
+    { soap_closesock(soap);
+      return soap_set_sender_error(soap, X509_verify_cert_error_string(err), "SSL certificate presented by peer cannot be verified in soap_ssl_accept()", SOAP_SSL_ERROR);
+    }
+    peer = SSL_get_peer_certificate(soap->ssl);
+    if (!peer)
+    { soap_closesock(soap);
+      return soap_set_sender_error(soap, "SSL error", "No SSL certificate was presented by the peer in soap_ssl_accept()", SOAP_SSL_ERROR);
+    }
+    X509_free(peer);
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#endif /* WITH_OPENSSL */
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static int
+tcp_init(struct soap *soap)
+{ soap->errmode = 1;
+#ifdef WIN32
+  if (tcp_done)
+    return 0;
+  else
+  { WSADATA w;
+    if (WSAStartup(MAKEWORD(1, 1), &w))
+      return -1;
+    tcp_done = 1;
+  }
+#endif
+  return 0;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_done(struct soap *soap)
+{ 
+#ifdef SOAP_DEBUG
+  int i;
+#endif
+  soap_free(soap);
+  while (soap->clist)
+  { struct soap_clist *p = soap->clist->next;
+    SOAP_FREE(soap, soap->clist);
+    soap->clist = p;
+  }
+  soap->keep_alive = 0; /* to force close the socket */
+  soap_closesock(soap);
+#ifdef WITH_COOKIES
+  soap_free_cookies(soap);
+#endif
+  while (soap->plugins)
+  { register struct soap_plugin *p = soap->plugins->next;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Removing plugin '%s'\n", soap->plugins->id));
+    if (soap->plugins->fcopy || !soap->copy)
+      soap->plugins->fdelete(soap, soap->plugins);
+    SOAP_FREE(soap, soap->plugins);
+    soap->plugins = p;
+  }
+  soap->fplugin = fplugin;
+#ifndef WITH_NOHTTP
+  soap->fpost = http_post;
+  soap->fget = http_get;
+  soap->fform = NULL;
+  soap->fposthdr = http_post_header;
+  soap->fresponse = http_response;
+  soap->fparse = http_parse;
+  soap->fparsehdr = http_parse_header;
+#endif
+#ifndef WITH_NOIO
+#ifndef WITH_IPV6
+  soap->fresolve = tcp_gethost;
+#else
+  soap->fresolve = NULL;
+#endif
+  soap->faccept = tcp_accept;
+  soap->fopen = tcp_connect;
+  soap->fclose = tcp_disconnect;
+  soap->fclosesocket = tcp_closesocket;
+  soap->fshutdownsocket = tcp_shutdownsocket;
+  soap->fsend = fsend;
+  soap->frecv = frecv;
+  soap->fpoll = soap_poll;
+#else
+  soap->fopen = NULL;
+  soap->fclose = NULL;
+  soap->fpoll = NULL;
+#endif
+#ifndef WITH_LEANER
+  soap->fprepareinit = NULL;
+  soap->fpreparesend = NULL;
+  soap->fpreparerecv = NULL;
+  soap->fpreparefinal = NULL;
+#endif
+  soap->fseterror = NULL;
+  soap->fignore = NULL;
+  soap->fserveloop = NULL;
+#ifdef WITH_OPENSSL
+  if (soap->session)
+  { SSL_SESSION_free(soap->session);
+    soap->session = NULL;
+  }
+#endif
+  if (!soap->copy)
+  { if (soap_valid_socket(soap->master))
+    { soap->fclosesocket(soap, (SOAP_SOCKET)soap->master);
+      soap->master = SOAP_INVALID_SOCKET;
+    }
+#ifdef WITH_OPENSSL
+    if (soap->ctx)
+    { SSL_CTX_free(soap->ctx);
+      soap->ctx = NULL;
+    }
+#endif
+  }
+#ifdef SOAP_DEBUG
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free logfiles\n"));
+  for (i = 0; i < SOAP_MAXLOGS; i++)
+  { if (soap->logfile[i])
+    { SOAP_FREE(soap, (void*)soap->logfile[i]);
+      soap->logfile[i] = NULL;
+    }
+    soap_close_logfile(soap, i);
+  }
+  soap_free_mht(soap);
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_cleanup(struct soap *soap)
+{ soap_done(soap);
+#ifdef WIN32
+  if (!tcp_done)
+    return;
+  tcp_done = 0;
+  WSACleanup();
+#endif
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static const char*
+tcp_error(struct soap *soap)
+{ register const char *msg = NULL;
+  switch (soap->errmode)
+  { case 0:
+      msg = soap_strerror(soap);
+      break;
+    case 1:
+      msg = "WSAStartup failed";
+      break;
+    case 2:
+    {
+#ifndef WITH_LEAN
+      msg = soap_str_code(h_error_codes, soap->errnum);
+      if (!msg)
+#endif
+      { sprintf(soap->msgbuf, "TCP/UDP IP error %d", soap->errnum);
+        msg = soap->msgbuf;
+      }
+    }
+  }
+  return msg;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static const char*
+http_error(struct soap *soap, int status)
+{ register const char *msg = SOAP_STR_EOS;
+#ifndef WITH_LEAN
+  msg = soap_str_code(h_http_error_codes, status);
+  if (!msg)
+    msg = SOAP_STR_EOS;
+#endif
+  return msg;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_IPV6
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static int
+tcp_gethost(struct soap *soap, const char *addr, struct in_addr *inaddr)
+{ soap_int32 iadd = -1;
+  struct hostent hostent, *host = &hostent;
+#ifdef VXWORKS
+  int hostint;
+  char *addrcopy = (char*)SOAP_MALLOC(soap, strlen(addr) + 1); /*copy of addr. */
+  /* inet_addr(), and hostGetByName() expect "char *"; addr is a "const char *". */
+  strncpy(addrcopy, addr, strlen(addr)+1);
+  iadd = inet_addr(addrcopy);
+#else
+#if defined(_AIXVERSION_431) || defined(TRU64)
+  struct hostent_data ht_data;
+#endif
+  iadd = inet_addr(addr);
+#endif
+  if (iadd != -1)
+  { memcpy(inaddr, &iadd, sizeof(iadd));
+#ifdef VXWORKS
+    SOAP_FREE(soap, addrcopy);
+#endif
+    return SOAP_OK;
+  }
+#if defined(__GLIBC__)
+  if (gethostbyname_r(addr, &hostent, soap->buf, SOAP_BUFLEN, &host, &soap->errnum) < 0)
+    host = NULL;
+#elif defined(_AIXVERSION_431) || defined(TRU64)
+  memset((void*)&ht_data, 0, sizeof(ht_data));
+  if (gethostbyname_r(addr, &hostent, &ht_data) < 0)
+  { host = NULL;
+    soap->errnum = h_errno;
+  }
+#elif defined(HAVE_GETHOSTBYNAME_R)
+  host = gethostbyname_r(addr, &hostent, soap->buf, SOAP_BUFLEN, &soap->errnum);
+#elif defined(VXWORKS)
+  /* If the DNS resolver library resolvLib has been configured in the vxWorks
+   * image, a query for the host IP address is sent to the DNS server, if the
+   * name was not found in the local host table. */
+  hostint = hostGetByName(addrcopy);
+  if (hostint == ERROR)
+  { host = NULL;
+    soap->errnum = soap_errno; 
+  }
+  SOAP_FREE(soap, addrcopy);  /*free() is placed after the error checking to assure that
+		    * errno captured is that from hostGetByName() */
+#else
+  if (!(host = gethostbyname(addr)))
+    soap->errnum = h_errno;
+#endif
+  if (!host)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Host name not found\n"));
+    return SOAP_ERR;
+  }
+#ifdef VXWORKS
+  inaddr->s_addr = hostint;
+#else
+  memcpy(inaddr, host->h_addr, host->h_length);
+#endif
+  return SOAP_OK;
+}
+#endif
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static int
+tcp_connect(struct soap *soap, const char *endpoint, const char *host, int port)
+{
+#ifdef WITH_IPV6
+  struct addrinfo hints, *res, *ressave;
+  int err;
+#endif
+  register int fd;
+#ifndef WITH_LEAN
+  int len = SOAP_BUFLEN;
+  int set = 1;
+#endif
+  if (soap_valid_socket(soap->socket))
+    soap->fclosesocket(soap, (SOAP_SOCKET)soap->socket);
+  soap->socket = SOAP_INVALID_SOCKET;
+  if (tcp_init(soap))
+  { soap->errnum = 0;
+    soap_set_sender_error(soap, tcp_error(soap), "TCP init failed in tcp_connect()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+  soap->errmode = 0;
+#ifdef WITH_IPV6
+  memset((void*)&hints, 0, sizeof(hints));
+  hints.ai_family = PF_UNSPEC;
+#ifdef WITH_UDP
+  if ((soap->omode & SOAP_IO_UDP))
+    hints.ai_socktype = SOCK_DGRAM;
+  else
+#endif
+    hints.ai_socktype = SOCK_STREAM;
+  soap->errmode = 2;
+  if (soap->proxy_host)
+    err = getaddrinfo(soap->proxy_host, soap_int2s(soap, soap->proxy_port), &hints, &res);
+  else
+    err = getaddrinfo(host, soap_int2s(soap, port), &hints, &res);
+  if (err)
+  { soap_set_sender_error(soap, gai_strerror(err), "getaddrinfo failed in tcp_connect()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+  ressave = res;
+again:
+  fd = (int)socket(res->ai_family, res->ai_socktype, res->ai_protocol);
+  soap->errmode = 0;
+#else
+#ifdef WITH_UDP
+  if ((soap->omode & SOAP_IO_UDP))
+    fd = (int)socket(AF_INET, SOCK_DGRAM, 0);
+  else
+#endif
+    fd = (int)socket(AF_INET, SOCK_STREAM, 0);
+#endif
+  if (fd < 0)
+  { soap->errnum = soap_socket_errno;
+    soap_set_sender_error(soap, tcp_error(soap), "socket failed in tcp_connect()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+#ifdef SOCKET_CLOSE_ON_EXEC
+#ifdef WIN32
+#ifndef UNDER_CE
+  SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0);
+#endif
+#else
+  fcntl(fd, F_SETFD, 1);
+#endif
+#endif
+#ifndef WITH_LEAN
+  if (soap->connect_flags & SO_LINGER)
+  { struct linger linger;
+    memset((void*)&linger, 0, sizeof(linger));
+    linger.l_onoff = 1;
+    linger.l_linger = 0;
+    if (setsockopt((SOAP_SOCKET)fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger)))
+    { soap->errnum = soap_socket_errno;
+      soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in tcp_connect()", SOAP_TCP_ERROR);
+      soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+      return SOAP_INVALID_SOCKET;
+    }
+  }
+  if ((soap->connect_flags & ~SO_LINGER) && setsockopt((SOAP_SOCKET)fd, SOL_SOCKET, soap->connect_flags & ~SO_LINGER, (char*)&set, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_sender_error(soap, tcp_error(soap), "setsockopt failed in tcp_connect()", SOAP_TCP_ERROR);
+    soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+    return SOAP_INVALID_SOCKET;
+  }
+  if (soap->keep_alive && setsockopt((SOAP_SOCKET)fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in tcp_connect()", SOAP_TCP_ERROR);
+    soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+    return SOAP_INVALID_SOCKET;
+  }
+  if (setsockopt((SOAP_SOCKET)fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in tcp_connect()", SOAP_TCP_ERROR);
+    soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+    return SOAP_INVALID_SOCKET;
+  }
+  if (setsockopt((SOAP_SOCKET)fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in tcp_connect()", SOAP_TCP_ERROR);
+    soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+    return SOAP_INVALID_SOCKET;
+  }
+#ifdef TCP_NODELAY
+  if (!(soap->omode & SOAP_IO_UDP) && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in tcp_connect()", SOAP_TCP_ERROR);
+    soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+    return SOAP_INVALID_SOCKET;
+  }
+#endif
+#endif
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Opening socket %d to host='%s' port=%d\n", fd, host, port));
+#ifndef WITH_IPV6
+  soap->peerlen = sizeof(soap->peer);
+  memset((void*)&soap->peer, 0, sizeof(soap->peer));
+  soap->peer.sin_family = AF_INET;
+  soap->errmode = 2;
+  if (soap->proxy_host)
+  { if (soap->fresolve(soap, soap->proxy_host, &soap->peer.sin_addr))
+    { soap_set_sender_error(soap, tcp_error(soap), "get proxy host by name failed in tcp_connect()", SOAP_TCP_ERROR);
+      soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+      return SOAP_INVALID_SOCKET;
+    }
+    soap->peer.sin_port = htons((short)soap->proxy_port);
+  }
+  else
+  { if (soap->fresolve(soap, host, &soap->peer.sin_addr))
+    { soap_set_sender_error(soap, tcp_error(soap), "get host by name failed in tcp_connect()", SOAP_TCP_ERROR);
+      soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+      return SOAP_INVALID_SOCKET;
+    }
+    soap->peer.sin_port = htons((short)port);
+  }
+  soap->errmode = 0;
+  if ((soap->omode & SOAP_IO_UDP))
+    return fd;
+#endif
+#ifndef WITH_LEAN
+  if (soap->connect_timeout)
+#if defined(WIN32)
+  { u_long nonblocking = 1;
+    ioctlsocket((SOAP_SOCKET)fd, FIONBIO, &nonblocking);
+  }
+#elif defined(VXWORKS)
+  { vx_nonblocking = TRUE;
+    ioctl((SOAP_SOCKET)fd, FIONBIO, (int)(&vx_nonblocking)); /* modified to use fd */
+  }
+#else
+    fcntl((SOAP_SOCKET)fd, F_SETFL, fcntl((SOAP_SOCKET)fd, F_GETFL)|O_NONBLOCK);
+#endif
+  else
+#if defined(WIN32)
+  { u_long blocking = 0;
+    ioctlsocket((SOAP_SOCKET)fd, FIONBIO, &blocking);
+  }
+#elif defined(VXWORKS)
+  { vx_nonblocking = FALSE;
+    ioctl((SOAP_SOCKET)fd, FIONBIO, (int)(&vx_nonblocking)); /* modified to use fd */
+  }
+#else
+    fcntl((SOAP_SOCKET)fd, F_SETFL, fcntl((SOAP_SOCKET)fd, F_GETFL)&~O_NONBLOCK);
+#endif
+#endif
+  for (;;)
+  { 
+#ifdef WITH_IPV6
+    if (connect((SOAP_SOCKET)fd, res->ai_addr, res->ai_addrlen))
+#else
+    if (connect((SOAP_SOCKET)fd, (struct sockaddr*)&soap->peer, sizeof(soap->peer)))
+#endif
+    { 
+#ifndef WITH_LEAN
+      if (soap->connect_timeout && (soap_socket_errno == SOAP_EINPROGRESS || soap_socket_errno == SOAP_EWOULDBLOCK))
+      { struct timeval timeout;
+        SOAP_SOCKLEN_T k;
+        fd_set fds;
+        if (soap->connect_timeout > 0)
+        { timeout.tv_sec = soap->connect_timeout;
+          timeout.tv_usec = 0;
+        }
+        else
+        { timeout.tv_sec = -soap->connect_timeout/1000000;
+          timeout.tv_usec = -soap->connect_timeout%1000000;
+        }
+        FD_ZERO(&fds);
+        FD_SET((SOAP_SOCKET)fd, &fds);
+        for (;;)
+        { int r = select((SOAP_SOCKET)(fd + 1), NULL, &fds, NULL, &timeout);
+          if (r > 0)
+	    break;
+          if (!r)
+          { soap->errnum = 0;
+            DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connect timeout\n"));
+            soap_set_sender_error(soap, "Timeout", "connect failed in tcp_connect()", SOAP_TCP_ERROR);
+            soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+            return SOAP_INVALID_SOCKET;
+          }
+          if (soap_socket_errno != SOAP_EINTR)
+          { soap->errnum = soap_socket_errno;
+            DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n"));
+            soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR);
+            soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+            return SOAP_INVALID_SOCKET;
+          }
+        }
+	k = (SOAP_SOCKLEN_T)sizeof(soap->errnum);
+        if (!getsockopt((SOAP_SOCKET)fd, SOL_SOCKET, SO_ERROR, (char*)&soap->errnum, &k) && !soap->errnum)	/* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */
+          break;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n"));
+        soap->errnum = soap_socket_errno;
+        soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR);
+        soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+        return SOAP_INVALID_SOCKET;
+      }
+      else
+#endif
+#ifdef WITH_IPV6
+      if (res->ai_next)
+      { res = res->ai_next;
+        soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+        goto again;
+      }
+      else
+#endif
+      if (soap_socket_errno != SOAP_EINTR)
+      { soap->errnum = soap_socket_errno;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n"));
+        soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR);
+        soap->fclosesocket(soap, (SOAP_SOCKET)fd);
+        return SOAP_INVALID_SOCKET;
+      }
+    }  
+    else
+      break;
+  }
+#ifdef WITH_IPV6
+  soap->peerlen = 0; /* IPv6: already connected so use send() */
+  freeaddrinfo(ressave);
+#endif
+#ifndef WITH_LEAN
+  if (soap->connect_timeout)
+#if defined(WIN32)
+  { u_long blocking = 0;
+    ioctlsocket((SOAP_SOCKET)fd, FIONBIO, &blocking);
+  }
+#elif defined(VXWORKS)
+  { vx_nonblocking = FALSE;
+    ioctl((SOAP_SOCKET)fd, FIONBIO, (int)(&vx_nonblocking)); /* modified to use fd */
+  }
+#else
+    fcntl((SOAP_SOCKET)fd, F_SETFL, fcntl((SOAP_SOCKET)fd, F_GETFL)&~O_NONBLOCK);
+#endif
+#endif
+  soap->socket = fd;
+  soap->imode &= ~SOAP_ENC_SSL;
+  soap->omode &= ~SOAP_ENC_SSL;
+  if (!strncmp(endpoint, "https:", 6))
+  {
+#ifdef WITH_OPENSSL
+    BIO *bio;
+    int r;
+    if (soap->proxy_host)
+    { short v;
+      unsigned int k = soap->omode; /* make sure we only parse HTTP */
+      size_t n = soap->count; /* save the content length */
+      soap->omode &= ~SOAP_ENC; /* mask IO and ENC */
+      soap->omode |= SOAP_IO_BUFFER;
+      soap_begin_send(soap);
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connecting to proxy server\n"));
+      sprintf(soap->tmpbuf, "CONNECT %s:%d HTTP/%s", host, port, soap->http_version);
+      if ((soap->error = soap->fposthdr(soap, soap->tmpbuf, NULL)))
+        return SOAP_INVALID_SOCKET;
+#ifndef WITH_LEAN
+      if (soap->proxy_userid && soap->proxy_passwd && strlen(soap->proxy_userid) + strlen(soap->proxy_passwd) < 761)
+      { sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd);
+        strcpy(soap->tmpbuf, "Basic ");
+        soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, strlen(soap->tmpbuf + 262));
+        if ((soap->error = soap->fposthdr(soap, "Proxy-Authorization", soap->tmpbuf)))
+          return soap->error;
+      }
+#endif
+      if ((soap->error = soap->fposthdr(soap, NULL, NULL))
+       || soap_flush(soap))
+        return SOAP_INVALID_SOCKET;
+      soap->omode = k;
+      k = soap->imode;
+      soap->imode &= ~SOAP_ENC; /* mask IO and ENC */
+      v = soap->version; /* preserve */
+      if (soap_begin_recv(soap))
+        return SOAP_INVALID_SOCKET;
+      soap->version = v; /* restore */
+      soap->imode = k; /* restore */
+      soap->count = n; /* restore */
+      soap_begin_send(soap);
+    }
+    if (!soap->ctx && (soap->error = soap->fsslauth(soap)))
+    { soap_set_sender_error(soap, "SSL error", "SSL authentication failed in tcp_connect(): check password, key file, and ca file.", SOAP_SSL_ERROR);
+      return SOAP_INVALID_SOCKET;
+    }
+    soap->ssl = SSL_new(soap->ctx);
+    if (!soap->ssl)
+    { soap->error = SOAP_SSL_ERROR;
+      return SOAP_INVALID_SOCKET;
+    }
+    if (soap->session)
+    { if (!strcmp(soap->session_host, host) && soap->session_port == port)
+        SSL_set_session(soap->ssl, soap->session);
+      SSL_SESSION_free(soap->session);
+      soap->session = NULL;
+    }
+    soap->imode |= SOAP_ENC_SSL;
+    soap->omode |= SOAP_ENC_SSL;
+    bio = BIO_new_socket((SOAP_SOCKET)fd, BIO_NOCLOSE);
+    SSL_set_bio(soap->ssl, bio, bio);
+#ifndef WITH_LEAN
+    if (soap->connect_timeout)
+#ifdef WIN32
+    { u_long nonblocking = 1;
+      ioctlsocket((SOAP_SOCKET)fd, FIONBIO, &nonblocking);
+    }
+#else
+      fcntl((SOAP_SOCKET)fd, F_SETFL, fcntl((SOAP_SOCKET)fd, F_GETFL)|O_NONBLOCK);
+#endif
+#endif
+    for (;;)
+    { if ((r = SSL_connect(soap->ssl)) <= 0)
+      { int err = SSL_get_error(soap->ssl, r);
+        if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE)
+        { soap_set_sender_error(soap, ssl_error(soap, r), "SSL connect failed in tcp_connect()", SOAP_SSL_ERROR);
+          return SOAP_INVALID_SOCKET;
+        }
+        if (soap->connect_timeout)
+        { struct timeval timeout;
+          fd_set fds;
+          if (soap->connect_timeout > 0)
+          { timeout.tv_sec = soap->connect_timeout;
+            timeout.tv_usec = 0;
+          }
+          else
+          { timeout.tv_sec = -soap->connect_timeout/1000000;
+            timeout.tv_usec = -soap->connect_timeout%1000000;
+          }
+          FD_ZERO(&fds);
+          FD_SET((SOAP_SOCKET)soap->socket, &fds);
+          for (;;)
+          { int r = select((SOAP_SOCKET)(soap->socket + 1), &fds, NULL, &fds, &timeout);
+            if (r > 0)
+	      break;
+            if (!r)
+            { soap->errnum = 0;
+              DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connect timeout\n"));
+              soap_set_sender_error(soap, "Timeout", "connect failed in tcp_connect()", SOAP_TCP_ERROR);
+              return SOAP_INVALID_SOCKET;
+            }
+          }
+	  continue;
+        }
+      }
+      break;
+    }
+#ifndef WITH_LEAN
+    if (soap->connect_timeout)
+#ifdef WIN32
+    { u_long blocking = 0;
+      ioctlsocket((SOAP_SOCKET)fd, FIONBIO, &blocking);
+    }
+#else
+      fcntl((SOAP_SOCKET)fd, F_SETFL, fcntl((SOAP_SOCKET)fd, F_GETFL)&~O_NONBLOCK);
+#endif
+#endif
+    if (soap->require_server_auth)
+    { X509 *peer;
+      int err;
+      if ((err = SSL_get_verify_result(soap->ssl)) != X509_V_OK)
+      { soap_set_sender_error(soap, X509_verify_cert_error_string(err), "SSL certificate presented by peer cannot be verified in tcp_connect()", SOAP_SSL_ERROR);
+        return SOAP_INVALID_SOCKET;
+      }
+      peer = SSL_get_peer_certificate(soap->ssl);
+      if (!peer)
+      { soap_set_sender_error(soap, "SSL error", "No SSL certificate was presented by the peer in tcp_connect()", SOAP_SSL_ERROR);
+        return SOAP_INVALID_SOCKET;
+      }
+      X509_NAME_get_text_by_NID(X509_get_subject_name(peer), NID_commonName, soap->msgbuf, sizeof(soap->msgbuf));
+      X509_free(peer);
+      if (soap_tag_cmp(soap->msgbuf, host))
+      { soap_set_sender_error(soap, "SSL error", "SSL certificate host name mismatch in tcp_connect()", SOAP_SSL_ERROR);
+        return SOAP_INVALID_SOCKET;
+      }
+    }
+#else
+    soap->error = SOAP_SSL_ERROR;
+    return SOAP_INVALID_SOCKET;
+#endif
+  }
+  return fd;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_bind(struct soap *soap, const char *host, int port, int backlog)
+{
+#ifdef WITH_IPV6
+  struct addrinfo *addrinfo;
+  struct addrinfo hints;
+  struct addrinfo res;
+  int err;
+#endif
+#ifndef WITH_LEAN
+  int len = SOAP_BUFLEN;
+  int set = 1;
+#endif
+  if (soap_valid_socket(soap->master))
+  { soap->fclosesocket(soap, (SOAP_SOCKET)soap->master);
+    soap->master = SOAP_INVALID_SOCKET;
+  }
+  soap->socket = SOAP_INVALID_SOCKET;
+  soap->errmode = 1;
+  if (tcp_init(soap))
+  { soap_set_receiver_error(soap, tcp_error(soap), "TCP init failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+#ifdef WITH_IPV6
+  memset((void*)&hints, 0, sizeof(hints));
+  hints.ai_family = PF_UNSPEC;
+#ifdef WITH_UDP
+  if ((soap->omode & SOAP_IO_UDP))
+    hints.ai_socktype = SOCK_DGRAM;
+  else
+#endif
+    hints.ai_socktype = SOCK_STREAM;
+  hints.ai_flags = AI_PASSIVE;
+  soap->errmode = 2;
+  err = getaddrinfo(host, soap_int2s(soap, port), &hints, &addrinfo);
+  if (addrinfo)
+  { res = *addrinfo;
+    soap->peer = *((struct sockaddr_storage*)addrinfo->ai_addr);
+    soap->peerlen = addrinfo->ai_addrlen;
+    res.ai_addr = (struct sockaddr*)&soap->peer;
+    res.ai_addrlen = soap->peerlen;
+    freeaddrinfo(addrinfo);
+  }
+  if (err)
+  { soap_set_receiver_error(soap, gai_strerror(err), "getaddrinfo failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+  soap->master = socket(res.ai_family, res.ai_socktype, res.ai_protocol);
+#else
+#ifdef WITH_UDP
+  if ((soap->omode & SOAP_IO_UDP))
+    soap->master = (int)socket(AF_INET, SOCK_DGRAM, 0);
+  else
+#endif
+    soap->master = (int)socket(AF_INET, SOCK_STREAM, 0);
+#endif
+  soap->errmode = 0;
+  if (!soap_valid_socket(soap->master))
+  { soap->errnum = soap_socket_errno;
+    soap_set_receiver_error(soap, tcp_error(soap), "socket failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+#ifdef WITH_UDP
+  if ((soap->omode & SOAP_IO_UDP))
+    soap->socket = soap->master;
+#endif
+#ifdef SOCKET_CLOSE_ON_EXEC
+#ifdef WIN32
+#ifndef UNDER_CE
+  SetHandleInformation((HANDLE)soap->master, HANDLE_FLAG_INHERIT, 0);
+#endif
+#else
+  fcntl(soap->master, F_SETFD, 1);
+#endif
+#endif
+#ifndef WITH_LEAN
+  if (soap->bind_flags && setsockopt((SOAP_SOCKET)soap->master, SOL_SOCKET, soap->bind_flags, (char*)&set, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+  if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt((SOAP_SOCKET)soap->master, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+  if (setsockopt((SOAP_SOCKET)soap->master, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+  if (setsockopt((SOAP_SOCKET)soap->master, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+#ifdef TCP_NODELAY
+  if (!(soap->omode & SOAP_IO_UDP) && setsockopt((SOAP_SOCKET)soap->master, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
+  { soap->errnum = soap_socket_errno;
+    soap_set_receiver_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+#endif
+#endif
+#ifdef WITH_IPV6
+  soap->errmode = 0;
+  if (bind((SOAP_SOCKET)soap->master, res.ai_addr, res.ai_addrlen))
+  { soap->errnum = soap_socket_errno;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n"));
+    soap_closesock(soap);
+    soap_set_receiver_error(soap, tcp_error(soap), "bind failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }  
+#else
+  soap->peerlen = sizeof(soap->peer);
+  memset((void*)&soap->peer, 0, sizeof(soap->peer));
+  soap->peer.sin_family = AF_INET;
+  soap->errmode = 2;
+  if (host)
+  { if (soap->fresolve(soap, host, &soap->peer.sin_addr))
+    { soap_set_receiver_error(soap, tcp_error(soap), "get host by name failed in soap_bind()", SOAP_TCP_ERROR);
+      return SOAP_INVALID_SOCKET;
+    }
+  }
+  else
+    soap->peer.sin_addr.s_addr = htonl(INADDR_ANY);
+  soap->peer.sin_port = htons((short)port);
+  soap->errmode = 0;
+  if (bind((SOAP_SOCKET)soap->master, (struct sockaddr*)&soap->peer, soap->peerlen))
+  { soap->errnum = soap_socket_errno;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n"));
+    soap_closesock(soap);
+    soap_set_receiver_error(soap, tcp_error(soap), "bind failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+#endif
+  if (!(soap->omode & SOAP_IO_UDP) && listen((SOAP_SOCKET)soap->master, backlog))
+  { soap->errnum = soap_socket_errno;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not bind to host\n"));
+    soap_closesock(soap);
+    soap_set_receiver_error(soap, tcp_error(soap), "listen failed in soap_bind()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }  
+  return soap->master;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_poll(struct soap *soap)
+{ 
+#ifndef WITH_LEAN
+  struct timeval timeout;
+  fd_set rfd, sfd, xfd;
+  int r;
+  timeout.tv_sec = 0;
+  timeout.tv_usec = 0;
+  FD_ZERO(&rfd);
+  FD_ZERO(&sfd);
+  FD_ZERO(&xfd);
+  if (soap_valid_socket(soap->socket))
+  { FD_SET((SOAP_SOCKET)soap->socket, &rfd);
+    FD_SET((SOAP_SOCKET)soap->socket, &sfd);
+    FD_SET((SOAP_SOCKET)soap->socket, &xfd);
+    r = select((SOAP_SOCKET)(soap->socket + 1), &rfd, &sfd, &xfd, &timeout);
+    if (r > 0 && FD_ISSET((SOAP_SOCKET)soap->socket, &xfd))
+      r = -1;
+  }
+  else if (soap_valid_socket(soap->master))
+  { FD_SET((SOAP_SOCKET)soap->master, &sfd);
+    r = select((SOAP_SOCKET)(soap->master + 1), NULL, &sfd, NULL, &timeout);
+  }
+  else
+    return SOAP_OK;
+  if (r > 0)
+  { if (soap_valid_socket(soap->socket)
+     && FD_ISSET((SOAP_SOCKET)soap->socket, &sfd)
+     && (!FD_ISSET((SOAP_SOCKET)soap->socket, &rfd)
+      || recv((SOAP_SOCKET)soap->socket, soap->tmpbuf, 1, MSG_PEEK) > 0))
+      return SOAP_OK;
+  }
+  else if (r < 0)
+  { soap->errnum = soap_socket_errno;
+    if ((soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) && soap_socket_errno != SOAP_EINTR)
+    { soap_set_receiver_error(soap, tcp_error(soap), "select failed in soap_poll()", SOAP_TCP_ERROR);
+      return soap->error = SOAP_TCP_ERROR;
+    }
+  }
+  else
+    soap->errnum = 0;
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Polling: other end down on socket=%d select=%d\n", soap->socket, r));
+  return SOAP_EOF;
+#else
+  return SOAP_OK;
+#endif
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static int
+tcp_accept(struct soap *soap, int s, struct sockaddr *a, int *n)
+{ int fd;
+  fd = (int)accept((SOAP_SOCKET)s, a, (SOAP_SOCKLEN_T*)n);	/* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */
+#ifdef SOCKET_CLOSE_ON_EXEC
+#ifdef WIN32
+#ifndef UNDER_CE
+  SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0);
+#endif
+#else
+  fcntl(fd, F_SETFD, FD_CLOEXEC);
+#endif
+#endif
+  return fd;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_accept(struct soap *soap)
+{ int n = (int)sizeof(soap->peer);
+#ifndef WITH_LEAN
+  int len = SOAP_BUFLEN;
+  int set = 1;
+#endif
+  soap->error = SOAP_OK;
+#ifdef WITH_UDP
+  if ((soap->omode & SOAP_IO_UDP))
+    return soap->socket = soap->master;
+#endif
+  memset((void*)&soap->peer, 0, sizeof(soap->peer));
+  soap->socket = SOAP_INVALID_SOCKET;
+  soap->errmode = 0;
+  soap->keep_alive = 0;
+  if (soap_valid_socket(soap->master))
+  { for (;;)
+    { 
+#ifndef WITH_LEAN
+      if (soap->accept_timeout)
+      { struct timeval timeout;
+        fd_set fd;
+        if (soap->accept_timeout > 0)
+        { timeout.tv_sec = soap->accept_timeout;
+          timeout.tv_usec = 0;
+        }
+        else
+        { timeout.tv_sec = -soap->accept_timeout/1000000;
+          timeout.tv_usec = -soap->accept_timeout%1000000;
+        }
+        FD_ZERO(&fd);
+        FD_SET((SOAP_SOCKET)soap->master, &fd);
+        for (;;)
+        { int r = select((SOAP_SOCKET)(soap->master + 1), &fd, &fd, NULL, &timeout);
+          if (r > 0)
+            break;
+          if (!r)
+          { soap->errnum = 0;
+            soap_set_receiver_error(soap, "Timeout", "accept failed in soap_accept()", SOAP_TCP_ERROR);
+            return SOAP_INVALID_SOCKET;
+          }
+          if (soap_socket_errno != SOAP_EINTR)
+          { soap->errnum = soap_socket_errno;
+            soap_closesock(soap);
+            soap_set_sender_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR);
+            return SOAP_INVALID_SOCKET;
+          }
+        }
+#if defined(WIN32)
+	{ u_long nonblocking = 1;
+          ioctlsocket((SOAP_SOCKET)soap->master, FIONBIO, &nonblocking);
+        }
+#elif defined(VXWORKS)
+        { vx_nonblocking = TRUE;
+          ioctl((SOAP_SOCKET)soap->master, FIONBIO, (int)(&vx_nonblocking));
+        }
+#else
+        fcntl((SOAP_SOCKET)soap->master, F_SETFL, fcntl((SOAP_SOCKET)soap->master, F_GETFL)|O_NONBLOCK);
+#endif
+      }
+      else
+#if defined(WIN32)
+      { u_long blocking = 0;
+        ioctlsocket((SOAP_SOCKET)soap->master, FIONBIO, &blocking);
+      }
+#elif defined(VXWORKS)
+      { vx_nonblocking = FALSE;
+        ioctl((SOAP_SOCKET)soap->master, FIONBIO, (int)(&vx_nonblocking));
+      }
+#else
+        fcntl((SOAP_SOCKET)soap->master, F_SETFL, fcntl((SOAP_SOCKET)soap->master, F_GETFL)&~O_NONBLOCK);
+#endif
+#endif
+      soap->socket = soap->faccept(soap, soap->master, (struct sockaddr*)&soap->peer, &n);
+      soap->peerlen = (size_t)n;
+      if (soap_valid_socket(soap->socket))
+      {
+#ifdef WITH_IPV6
+/* Use soap->host to store the numeric form of the remote host */
+        getnameinfo((struct sockaddr*)&soap->peer, n, soap->host, sizeof(soap->host), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV); 
+        DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d from %s\n", soap->socket, soap->host));
+        soap->ip = 0; /* info stored in soap->peer and soap->host */
+        soap->port = 0; /* info stored in soap->peer and soap->host */
+#else
+        soap->ip = ntohl(soap->peer.sin_addr.s_addr);
+        soap->port = (int)ntohs(soap->peer.sin_port); /* does not return port number on some systems */
+        DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d at port %d from IP %d.%d.%d.%d\n", soap->socket, soap->port, (int)(soap->ip>>24)&0xFF, (int)(soap->ip>>16)&0xFF, (int)(soap->ip>>8)&0xFF, (int)soap->ip&0xFF));
+#endif
+#ifndef WITH_LEAN
+	if (soap->accept_flags & SO_LINGER)
+        { struct linger linger;
+          memset((void*)&linger, 0, sizeof(linger));
+          linger.l_onoff = 1;
+          linger.l_linger = 0;
+	  if (setsockopt((SOAP_SOCKET)soap->socket, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger)))
+          { soap->errnum = soap_socket_errno;
+	    soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in soap_accept()", SOAP_TCP_ERROR);
+	    soap_closesock(soap);
+            return SOAP_INVALID_SOCKET;
+	  }
+        }
+        if ((soap->accept_flags & ~SO_LINGER) && setsockopt((SOAP_SOCKET)soap->socket, SOL_SOCKET, soap->accept_flags & ~SO_LINGER, (char*)&set, sizeof(int)))
+        { soap->errnum = soap_socket_errno;
+          soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_accept()", SOAP_TCP_ERROR);
+	  soap_closesock(soap);
+          return SOAP_INVALID_SOCKET;
+        }
+        if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt((SOAP_SOCKET)soap->socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int)))
+        { soap->errnum = soap_socket_errno;
+          soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_accept()", SOAP_TCP_ERROR);
+	  soap_closesock(soap);
+          return SOAP_INVALID_SOCKET;
+        }
+        if (setsockopt((SOAP_SOCKET)soap->socket, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
+        { soap->errnum = soap_socket_errno;
+          soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in soap_accept()", SOAP_TCP_ERROR);
+	  soap_closesock(soap);
+          return SOAP_INVALID_SOCKET;
+        }
+        if (setsockopt((SOAP_SOCKET)soap->socket, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
+        { soap->errnum = soap_socket_errno;
+          soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in soap_accept()", SOAP_TCP_ERROR);
+	  soap_closesock(soap);
+          return SOAP_INVALID_SOCKET;
+        }
+#ifdef TCP_NODELAY
+        if (!(soap->omode & SOAP_IO_UDP) && setsockopt((SOAP_SOCKET)soap->socket, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
+        { soap->errnum = soap_socket_errno;
+          soap_set_receiver_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in soap_accept()", SOAP_TCP_ERROR);
+	  soap_closesock(soap);
+          return SOAP_INVALID_SOCKET;
+        }
+#endif
+#endif
+        if (soap->accept_timeout)
+        {
+#if defined(WIN32)
+          u_long blocking = 0;
+          ioctlsocket((SOAP_SOCKET)soap->master, FIONBIO, &blocking);
+          ioctlsocket((SOAP_SOCKET)soap->socket, FIONBIO, &blocking);
+#elif defined(VXWORKS)
+          vx_nonblocking = FALSE;
+          ioctl((SOAP_SOCKET)soap->master, FIONBIO, (int)(&vx_nonblocking));
+          ioctl((SOAP_SOCKET)soap->socket, FIONBIO, (int)(&vx_nonblocking));
+#elif defined(PALM)
+          fcntl((SOAP_SOCKET)soap->master, F_SETFL, fcntl((SOAP_SOCKET)soap->master, F_GETFL,0)&~O_NONBLOCK);
+          fcntl((SOAP_SOCKET)soap->socket, F_SETFL, fcntl((SOAP_SOCKET)soap->socket, F_GETFL,0)&~O_NONBLOCK);
+#elif defined(SYMBIAN)
+          long blocking = 0;
+          ioctl((SOAP_SOCKET)soap->master, 0/*FIONBIO*/, &blocking);
+#else
+          fcntl((SOAP_SOCKET)soap->master, F_SETFL, fcntl((SOAP_SOCKET)soap->master, F_GETFL)&~O_NONBLOCK);
+          fcntl((SOAP_SOCKET)soap->socket, F_SETFL, fcntl((SOAP_SOCKET)soap->socket, F_GETFL)&~O_NONBLOCK);
+#endif
+	}
+        soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0);
+        return soap->socket;
+      }
+      if (soap_socket_errno != SOAP_EINTR && soap_socket_errno != SOAP_EAGAIN)
+      { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept failed from %s\n", soap->host));
+        soap->errnum = soap_socket_errno;
+        soap_set_receiver_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR);
+	soap_closesock(soap);
+        return SOAP_INVALID_SOCKET;
+      }
+    }
+  }
+  else
+  { soap->errnum = 0;
+    soap_set_receiver_error(soap, tcp_error(soap), "no master socket in soap_accept()", SOAP_TCP_ERROR);
+    return SOAP_INVALID_SOCKET;
+  }
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static int
+tcp_disconnect(struct soap *soap)
+{
+#ifdef WITH_OPENSSL
+  if (soap->ssl)
+  { int r, s = 0;
+    if (soap->session)
+      SSL_SESSION_free(soap->session);
+    if (*soap->host)
+    { soap->session = SSL_get1_session(soap->ssl);
+      if (soap->session)
+      { strcpy(soap->session_host, soap->host);
+        soap->session_port = soap->port;
+      }
+    }
+    r = SSL_shutdown(soap->ssl);
+    if (r != 1)
+    { s = ERR_get_error();
+      if (s)
+      { if (soap_valid_socket(soap->socket))
+        { soap->fshutdownsocket(soap, (SOAP_SOCKET)soap->socket, 1);
+          soap->socket = SOAP_INVALID_SOCKET;
+        }
+        r = SSL_shutdown(soap->ssl);
+      }
+    }
+    DBGLOG(TEST, if (s) SOAP_MESSAGE(fdebug, "Shutdown failed: %d\n", SSL_get_error(soap->ssl, r)));
+    SSL_free(soap->ssl);
+    soap->ssl = NULL;
+    if (s)
+      return SOAP_SSL_ERROR;
+    ERR_remove_state(0);
+  }
+#endif
+  if (soap_valid_socket(soap->socket) && !(soap->omode & SOAP_IO_UDP))
+  { soap->fshutdownsocket(soap, (SOAP_SOCKET)soap->socket, 2);
+    soap->fclosesocket(soap, (SOAP_SOCKET)soap->socket);
+    soap->socket = SOAP_INVALID_SOCKET;
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static int
+tcp_closesocket(struct soap *soap, SOAP_SOCKET fd)
+{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Close socket %d\n", (int)fd));
+  return closesocket(fd);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static int
+tcp_shutdownsocket(struct soap *soap, SOAP_SOCKET fd, int how)
+{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Shutdown socket %d how=%d\n", (int)fd, how));
+  //return shutdown(fd, how);
+  return how==SD_BOTH?shutdown(fd, how):0;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_closesock(struct soap *soap)
+{ register int status = soap->error;
+  if (status == SOAP_EOF || status == SOAP_TCP_ERROR || status == SOAP_SSL_ERROR || !soap->keep_alive)
+  { if (soap->fclose && (soap->error = soap->fclose(soap)))
+      return soap->error;
+    soap->keep_alive = 0;
+  }
+#ifdef WITH_ZLIB
+  if (soap->zlib_state == SOAP_ZLIB_DEFLATE)
+    deflateEnd(&soap->d_stream);
+  else if (soap->zlib_state == SOAP_ZLIB_INFLATE)
+    inflateEnd(&soap->d_stream);
+  soap->zlib_state = SOAP_ZLIB_NONE;
+#endif
+  return soap->error = status;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+size_t
+SOAP_FMAC2
+soap_hash(register const char *s)
+{ register size_t h = 0;
+  while (*s)
+    h = 65599*h + *s++;
+  return h % SOAP_IDHASH;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_1
+static void
+soap_init_pht(struct soap *soap)
+{ register int i;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing pointer hashtable\n"));
+  soap->pblk = NULL;
+  soap->pidx = 0;
+  for (i = 0; i < (int)SOAP_PTRHASH; i++)
+    soap->pht[i] = NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+struct soap*
+SOAP_FMAC2
+soap_new1(soap_mode mode)
+{ return soap_new2(mode, mode);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+struct soap*
+SOAP_FMAC2
+soap_new()
+{ return soap_new2(SOAP_IO_DEFAULT, SOAP_IO_DEFAULT);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+struct soap*
+SOAP_FMAC2
+soap_new2(soap_mode imode, soap_mode omode)
+{ struct soap *soap = (struct soap*)malloc(sizeof(struct soap));
+  if (soap)
+    soap_init2(soap, imode, omode);
+  return soap;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_1
+static void
+soap_free_pht(struct soap *soap)
+{ register struct soap_pblk *pb, *next;
+  register int i;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free pointer hashtable\n"));
+  for (pb = soap->pblk; pb; pb = next)
+  { next = pb->next;
+    SOAP_FREE(soap, pb);
+  }
+  soap->pblk = NULL;
+  soap->pidx = 0;
+  for (i = 0; i < (int)SOAP_PTRHASH; i++)
+    soap->pht[i] = NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_embed(struct soap *soap, const void *p, const struct soap_array *a, int n, const char *tag, int type)
+{ register int i;
+  struct soap_plist *pp;
+  if (soap->version != 1)
+    soap->encoding = 1;
+  if (a)
+    i = soap_array_pointer_lookup(soap, p, a, n, type, &pp);
+  else
+    i = soap_pointer_lookup(soap, p, type, &pp);
+  if (i)
+  { if (soap_is_embedded(soap, pp)
+     || soap_is_single(soap, pp))
+      return 0;
+    soap_set_embedded(soap, pp);
+  }
+  return i;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_pointer_lookup(struct soap *soap, const void *p, int type, struct soap_plist **ppp)
+{ register struct soap_plist *pp;
+  *ppp = NULL;
+  if (p)
+  { for (pp = soap->pht[soap_hash_ptr(p)]; pp; pp = pp->next)
+    { if (pp->ptr == p && pp->type == type)
+      { *ppp = pp;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup location=%p type=%d id=%d\n", p, type, pp->id));
+        return pp->id;
+      }
+    }
+  }
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup location=%p type=%d: not found\n", p, type));
+  return 0;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_pointer_enter(struct soap *soap, const void *p, const struct soap_array *a, int n, int type, struct soap_plist **ppp)
+{ register int h;
+  register struct soap_plist *pp;
+  if (!soap->pblk || soap->pidx >= SOAP_PTRBLK)
+  { register struct soap_pblk *pb = (struct soap_pblk*)SOAP_MALLOC(soap, sizeof(struct soap_pblk));
+    if (!pb)
+    { soap->error = SOAP_EOM;
+      return 0;
+    }
+    pb->next = soap->pblk;
+    soap->pblk = pb;
+    soap->pidx = 0;
+  }
+  *ppp = pp = &soap->pblk->plist[soap->pidx++];
+  if (a)
+    h = soap_hash_ptr(a->__ptr);
+  else
+    h = soap_hash_ptr(p);
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pointer enter location=%p array=%p size=%d dim=%d type=%d id=%d\n", p, a?a->__ptr:NULL, a?a->__size:0, n, type, soap->idnum+1));
+  pp->next = soap->pht[h];
+  pp->type = type;
+  pp->mark1 = 0;
+  pp->mark2 = 0;
+  pp->ptr = p;
+  pp->array = a;
+  soap->pht[h] = pp;
+  pp->id = ++soap->idnum;
+  return pp->id;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_array_pointer_lookup(struct soap *soap, const void *p, const struct soap_array *a, int n, int type, struct soap_plist **ppp)
+{ register struct soap_plist *pp;
+  *ppp = NULL;
+  if (!p || !a->__ptr)
+    return 0;
+  for (pp = soap->pht[soap_hash_ptr(a->__ptr)]; pp; pp = pp->next)
+  { if (pp->type == type && pp->array && pp->array->__ptr == a->__ptr)
+    { register int i;
+      for (i = 0; i < n; i++)
+        if (((const int*)&pp->array->__size)[i] != ((const int*)&a->__size)[i])
+	  break;
+      if (i == n)
+      { *ppp = pp;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array lookup location=%p type=%d id=%d\n", a->__ptr, type, pp->id));
+        return pp->id;
+      }
+    }
+  }
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array lookup location=%p type=%d: not found\n", a->__ptr, type));
+  return 0;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_begin_count(struct soap *soap)
+{ soap_clr_attr(soap);
+  soap_set_local_namespaces(soap);
+#ifndef WITH_LEANER
+  if ((soap->mode & SOAP_ENC_DIME) || (soap->omode & SOAP_ENC_DIME))
+    soap->mode = soap->omode | SOAP_IO_LENGTH | SOAP_ENC_DIME;
+  else
+#endif
+  { soap->mode = soap->omode;
+    if ((soap->mode & SOAP_IO) == SOAP_IO_STORE
+     || (((soap->mode & SOAP_IO) == SOAP_IO_CHUNK || (soap->mode & SOAP_ENC_XML))
+#ifndef WITH_LEANER
+      && !soap->fpreparesend
+#endif
+      ))
+      soap->mode &= ~SOAP_IO_LENGTH;
+    else
+      soap->mode |= SOAP_IO_LENGTH;
+  }
+#ifdef WITH_ZLIB
+  if ((soap->mode & SOAP_ENC_ZLIB) && (soap->mode & SOAP_IO) == SOAP_IO_FLUSH)
+  { if (!(soap->mode & SOAP_ENC_DIME))
+      soap->mode &= ~SOAP_IO_LENGTH;
+    if (soap->mode & SOAP_ENC_XML)
+      soap->mode |= SOAP_IO_BUFFER;
+    else
+      soap->mode |= SOAP_IO_STORE;
+  }
+#endif
+  if (!soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH))
+    soap->mode |= SOAP_XML_TREE;
+#ifndef WITH_LEANER
+  if ((soap->mode & SOAP_ENC_MTOM) && (soap->mode & SOAP_ENC_DIME))
+    soap->mode |= SOAP_ENC_MIME;
+  else
+    soap->mode &= ~SOAP_ENC_MTOM;
+  if (soap->mode & SOAP_ENC_MIME)
+    soap_select_mime_boundary(soap);
+  soap->dime.list = soap->dime.last;	/* keep track of last DIME attachment */
+#endif
+  soap->count = 0;
+  soap->ns = 0;
+  soap->null = 0;
+  soap->position = 0;
+  soap->mustUnderstand = 0;
+  soap->encoding = 0;
+  soap->part = SOAP_BEGIN;
+  soap->idnum = 0;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin count phase (socket=%d mode=0x%x count=%lu)\n", soap->socket, soap->mode, (unsigned long)soap->count));
+#ifndef WITH_LEANER
+  soap->dime.count = 0; /* count # of attachments */
+  soap->dime.size = 0; /* accumulate total size of attachments */
+  if (soap->fprepareinit && (soap->mode & SOAP_IO) != SOAP_IO_STORE)
+    return soap->error = soap->fprepareinit(soap);   
+#endif
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_end_count(struct soap *soap)
+{ 
+#ifndef WITH_LEANER
+  if (soap->fpreparefinal)
+    return soap->error = soap->fpreparefinal(soap);
+#endif
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of count phase\n"));
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_begin_send(struct soap *soap)
+{ soap->error = SOAP_OK;
+  soap_clr_attr(soap);
+  soap_set_local_namespaces(soap);
+  soap->mode = soap->omode | (soap->mode & (SOAP_IO_LENGTH | SOAP_ENC_DIME));
+#ifdef WITH_ZLIB
+  if ((soap->mode & SOAP_ENC_ZLIB) && (soap->mode & SOAP_IO) == SOAP_IO_FLUSH)
+  { if (soap->mode & SOAP_ENC_XML)
+      soap->mode |= SOAP_IO_BUFFER;
+    else
+      soap->mode |= SOAP_IO_STORE;
+  }
+#endif
+#ifdef WITH_UDP
+  if ((soap->mode & SOAP_IO_UDP))
+  { soap->mode |= SOAP_ENC_XML;
+    if (soap->count > SOAP_BUFLEN)
+      return soap->error = SOAP_UDP_ERROR;
+  }
+#endif
+  if ((soap->mode & SOAP_IO) == SOAP_IO_FLUSH && soap_valid_socket(soap->socket))
+  { if (soap->count || (soap->mode & SOAP_IO_LENGTH) || (soap->mode & SOAP_ENC_XML))
+      soap->mode |= SOAP_IO_BUFFER;
+    else
+      soap->mode |= SOAP_IO_STORE;
+  }
+  soap->mode &= ~SOAP_IO_LENGTH;
+  if ((soap->mode & SOAP_IO) == SOAP_IO_STORE)
+    soap_new_block(soap);
+  if (!(soap->mode & SOAP_IO_KEEPALIVE))
+    soap->keep_alive = 0;
+  if (!soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH))
+    soap->mode |= SOAP_XML_TREE;
+#ifndef WITH_LEANER
+  if ((soap->mode & SOAP_ENC_MTOM) && (soap->mode & SOAP_ENC_DIME))
+  { soap->mode |= SOAP_ENC_MIME;
+    soap->mode &= ~SOAP_ENC_DIME;
+  }
+  else
+    soap->mode &= ~SOAP_ENC_MTOM;
+  if (soap->mode & SOAP_ENC_MIME)
+    soap_select_mime_boundary(soap);
+#ifdef WIN32
+#ifndef UNDER_CE
+#ifndef WITH_FASTCGI
+  if (!soap_valid_socket(soap->socket)) /* Set win32 stdout or soap->sendfd to BINARY, e.g. to support DIME */
+#ifdef __BORLANDC__
+    setmode((SOAP_SOCKET)soap->sendfd, O_BINARY);
+#else
+    _setmode((SOAP_SOCKET)soap->sendfd, _O_BINARY);
+#endif
+#endif
+#endif
+#endif
+#endif
+  if (soap->mode & SOAP_IO)
+  { soap->bufidx = 0;
+    soap->buflen = 0;
+  }
+  soap->chunksize = 0;
+  soap->ns = 0;
+  soap->null = 0;
+  soap->position = 0;
+  soap->mustUnderstand = 0;
+  soap->encoding = 0;
+  soap->idnum = 0;
+  soap->level = 0;
+#ifdef WITH_ZLIB
+  soap->z_ratio_out = 1.0;
+  if ((soap->mode & SOAP_ENC_ZLIB) && soap->zlib_state != SOAP_ZLIB_DEFLATE)
+  {
+#ifdef WITH_GZIP
+    memcpy(soap->z_buf, "\37\213\10\0\0\0\0\0\0\377", 10);
+    soap->d_stream.next_out = (Byte*)soap->z_buf + 10;
+    soap->d_stream.avail_out = SOAP_BUFLEN - 10;
+    soap->z_crc = crc32(0L, NULL, 0);
+    if (deflateInit2(&soap->d_stream, soap->z_level, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY) != Z_OK)
+#else
+    soap->d_stream.next_out = (Byte*)soap->z_buf;
+    soap->d_stream.avail_out = SOAP_BUFLEN;
+    if (deflateInit(&soap->d_stream, soap->z_level) != Z_OK)
+#endif
+      return soap->error = SOAP_ZLIB_ERROR;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflate initialized\n"));
+    soap->zlib_state = SOAP_ZLIB_DEFLATE;
+  }
+#endif
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin send phase (socket=%d mode=0x%x count=%lu)\n", soap->socket, soap->mode, (unsigned long)soap->count));
+  soap->part = SOAP_BEGIN;
+#ifndef WITH_LEANER
+  if (soap->fprepareinit && (soap->mode & SOAP_IO) == SOAP_IO_STORE)
+    soap->fprepareinit(soap);   
+#endif
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_embedded(struct soap *soap, const void *p, int t)
+{ struct soap_plist *pp;
+  if (soap_pointer_lookup(soap, p, t, &pp))
+  { pp->mark1 = 1;
+    pp->mark2 = 1;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded %p type=%d mark set to 1\n", p, t));
+  }
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_reference(struct soap *soap, const void *p, int t)
+{ struct soap_plist *pp;
+  if (!p || (soap->mode & SOAP_XML_TREE))
+    return 1;
+  if (soap_pointer_lookup(soap, p, t, &pp))
+  { if (pp->mark1 == 0)
+    { pp->mark1 = 2;
+      pp->mark2 = 2;
+    }
+  }
+  else if (soap_pointer_enter(soap, p, NULL, 0, t, &pp))
+  { pp->mark1 = 0;
+    pp->mark2 = 0;
+  }
+  else
+    return 1;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Reference %p type=%d (%d %d)\n", p, t, (int)pp->mark1, (int)pp->mark2));
+  return pp->mark1;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_array_reference(struct soap *soap, const void *p, const struct soap_array *a, int n, int t)
+{ register int i;
+  struct soap_plist *pp;
+  if (!p || !a->__ptr)
+    return 1;
+  i = soap_array_pointer_lookup(soap, p, a, n, t, &pp);
+  if (i)
+  { if (pp->mark1 == 0)
+    { pp->mark1 = 2;
+      pp->mark2 = 2;
+    }
+  }
+  else if (!soap_pointer_enter(soap, p, a, n, t, &pp))
+    return 1;
+  else
+  { pp->mark1 = 0;
+    pp->mark2 = 0;
+  }
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Array reference %p ptr=%p dim=%d type=%d (%d %d)\n", p, a->__ptr, n, t, (int)pp->mark1, (int)pp->mark2));
+  return pp->mark1;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_embedded_id(struct soap *soap, int id, const void *p, int t)
+{ struct soap_plist *pp;
+  if (soap->mode & SOAP_XML_TREE)
+    return id;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id %p type=%d id=%d\n", p, t, id));
+  if (soap->version == 1 && soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH) && soap->part != SOAP_IN_HEADER)
+  { if (id < 0)
+    { id = soap_pointer_lookup(soap, p, t, &pp);
+      if (id)
+      { if (soap->mode & SOAP_IO_LENGTH)
+          pp->mark1 = 2;
+        else
+          pp->mark2 = 2;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id multiref id=%d %p type=%d = (%d %d)\n", id, p, t, (int)pp->mark1, (int)pp->mark2));
+      }
+      return -1;
+    }
+    return id;
+  }
+  if (id < 0)
+    id = soap_pointer_lookup(soap, p, t, &pp);
+  else if (id && !soap_pointer_lookup(soap, p, t, &pp))
+    return 0;
+  if (id && pp)
+  { if (soap->mode & SOAP_IO_LENGTH)
+      pp->mark1 = 1;
+    else
+      pp->mark2 = 1;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Embedded_id embedded ref id=%d %p type=%d = (%d %d)\n", id, p, t, (int)pp->mark1, (int)pp->mark2));
+  }
+  return id;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_is_embedded(struct soap *soap, struct soap_plist *pp)
+{ if (!pp)
+    return 0;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Is embedded? %d %d\n", (int)pp->mark1, (int)pp->mark2));
+  if (soap->version == 1 && soap->encodingStyle && !(soap->mode & SOAP_XML_GRAPH) && soap->part != SOAP_IN_HEADER)
+  { if (soap->mode & SOAP_IO_LENGTH)
+      return pp->mark1 != 0;
+    return pp->mark2 != 0;
+  }
+  if (soap->mode & SOAP_IO_LENGTH)
+    return pp->mark1 == 1;
+  return pp->mark2 == 1;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_is_single(struct soap *soap, struct soap_plist *pp)
+{ if (soap->part == SOAP_IN_HEADER)
+    return 1;
+  if (!pp)
+    return 0;
+  if (soap->mode & SOAP_IO_LENGTH)
+    return pp->mark1 == 0;
+  return pp->mark2 == 0;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_embedded(struct soap *soap, struct soap_plist *pp)
+{ if (!pp)
+    return;
+  if (soap->mode & SOAP_IO_LENGTH)
+    pp->mark1 = 1;
+  else
+    pp->mark2 = 1;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_attachment(struct soap *soap, const char *tag, int id, const void *p, const struct soap_array *a, const char *aid, const char *atype, const char *aoptions, int n, const char *type, int t) 
+{ struct soap_plist *pp;
+  int i;
+  if (!p || !a->__ptr || (!aid && !atype))
+    return soap_element_id(soap, tag, id, p, a, n, type, t);
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Attachment tag='%s' id='%s' (%d) type='%s'\n", tag, aid?aid:"", id, atype?atype:""));
+  i = soap_array_pointer_lookup(soap, p, a, n, t, &pp);
+  if (!i)
+  { i = soap_pointer_enter(soap, p, a, n, t, &pp);
+    if (!i)
+    { soap->error = SOAP_EOM;
+      return -1;
+    }
+  }
+  if (id < 0)
+    id = i;
+  if (!aid)
+  { sprintf(soap->tmpbuf, soap->dime_id_format, id);
+    aid = soap_strdup(soap, soap->tmpbuf);
+  }
+  /* Add MTOM xop:Include element when necessary */
+  /* TODO: this code to be obsoleted with new import/xop.h conventions */
+  if ((soap->mode & SOAP_ENC_MTOM) && strcmp(tag, "xop:Include"))
+  { if (soap_element_begin_out(soap, tag, 0, type)
+     || soap_element_href(soap, "xop:Include", 0, "href", aid)
+     || soap_element_end_out(soap, tag))
+      return soap->error;
+  }
+  else if (soap_element_href(soap, tag, 0, "href", aid))
+    return soap->error;
+  if (soap->mode & SOAP_IO_LENGTH)
+  { if (pp->mark1 != 3)
+    { struct soap_multipart *content;
+      if (soap->mode & SOAP_ENC_MTOM)
+        content = soap_new_multipart(soap, &soap->mime.first, &soap->mime.last, (char*)a->__ptr, a->__size);
+      else
+        content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, (char*)a->__ptr, a->__size);
+      if (!content)
+      { soap->error = SOAP_EOM;
+        return -1;
+      }
+      if (!strncmp(aid, "cid:", 4)) /* RFC 2111 */
+      { if (soap->mode & SOAP_ENC_MTOM)
+        { char *s = (char*)soap_malloc(soap, strlen(aid) - 1);
+	  if (s)
+	  { *s = '<';
+	    strcpy(s + 1, aid + 4);
+	    strcat(s, ">");
+	    content->id = s;
+          }
+        }
+        else
+          content->id = aid + 4;
+      }
+      else
+        content->id = aid;
+      content->type = atype;
+      content->options = aoptions;
+      content->encoding = SOAP_MIME_BINARY;
+      pp->mark1 = 3;
+    }
+  }
+  else
+    pp->mark2 = 3;
+  return -1;
+}
+#endif
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_1
+static void
+soap_init_iht(struct soap *soap)
+{ register int i;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing ID hashtable\n"));
+  for (i = 0; i < SOAP_IDHASH; i++)
+    soap->iht[i] = NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_1
+static void
+soap_free_iht(struct soap *soap)
+{ register int i;
+  register struct soap_ilist *ip, *p;
+  register struct soap_flist *fp, *fq;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free ID hashtable\n"));
+  for (i = 0; i < SOAP_IDHASH; i++)
+  { for (ip = soap->iht[i]; ip; ip = p)
+    { for (fp = ip->flist; fp; fp = fq)
+      { fq = fp->next;
+        SOAP_FREE(soap, fp);
+      }
+      p = ip->next;
+      SOAP_FREE(soap, ip);
+    }
+    soap->iht[i] = NULL;
+  }
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+struct soap_ilist *
+SOAP_FMAC2
+soap_lookup(struct soap *soap, const char *id)
+{ register struct soap_ilist *ip;
+  for (ip = soap->iht[soap_hash(id)]; ip; ip = ip->next)
+    if (!strcmp(ip->id, id))
+      return ip;
+  return NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+struct soap_ilist *
+SOAP_FMAC2
+soap_enter(struct soap *soap, const char *id)
+{ register size_t h;
+  register struct soap_ilist *ip;
+  ip = (struct soap_ilist*)SOAP_MALLOC(soap, sizeof(struct soap_ilist) + strlen(id));
+  if (ip)
+  { h = soap_hash(id);
+    strcpy(ip->id, id);
+    ip->next = soap->iht[h];
+    soap->iht[h] = ip;
+    return ip;
+  }
+  return NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void*
+SOAP_FMAC2
+soap_malloc(struct soap *soap, size_t n)
+{ register char *p;
+  if (!n)
+    return (void*)SOAP_NON_NULL;
+  if (!soap)
+    return SOAP_MALLOC(soap, n);
+  n += (-(long)n) & 7;
+  if (!(p = (char*)SOAP_MALLOC(soap, n + sizeof(void*) + sizeof(size_t))))
+  { soap->error = SOAP_EOM;
+    return NULL;
+  }
+  /* keep chain of alloced cells for later destruction */
+  soap->alloced = 1;
+  *(void**)(p + n) = soap->alist;
+  *(size_t*)(p + n + sizeof(void*)) = n;
+  soap->alist = p + n;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+static void
+soap_init_mht(struct soap *soap)
+{ register int i;
+  for (i = 0; i < (int)SOAP_PTRHASH; i++)
+    soap->mht[i] = NULL;
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+static void
+soap_free_mht(struct soap *soap)
+{ register int i;
+  register struct soap_mlist *mp, *mq;
+  for (i = 0; i < (int)SOAP_PTRHASH; i++)
+  { for (mp = soap->mht[i]; mp; mp = mq)
+    { mq = mp->next;
+      if (mp->live)
+        fprintf(stderr, "%s(%d): malloc() = %p not freed (memory leak or forgot to call soap_end()?)\n", mp->file, mp->line, mp->ptr);
+      free(mp);
+    }
+    soap->mht[i] = NULL;
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+SOAP_FMAC1
+void*
+SOAP_FMAC2
+soap_track_malloc(struct soap *soap, const char *file, int line, size_t size)
+{ register void *p = malloc(size);
+  if (soap)
+  { register int h = soap_hash_ptr(p);
+    register struct soap_mlist *mp = (struct soap_mlist*)malloc(sizeof(struct soap_mlist));
+    if (soap->fdebug[SOAP_INDEX_TEST])
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): malloc(%lu) = %p\n", file, line, (unsigned long)size, p));
+    mp->next = soap->mht[h];
+    mp->ptr = p;
+    mp->file = file;
+    mp->line = line;
+    mp->live = 1;
+    soap->mht[h] = mp;
+  }
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_track_free(struct soap *soap, const char *file, int line, void *p)
+{ register int h = soap_hash_ptr(p);
+  register struct soap_mlist *mp;
+  for (mp = soap->mht[h]; mp; mp = mp->next)
+    if (mp->ptr == p)
+      break;
+  if (mp)
+  { if (mp->live)
+    { free(p);
+      if (soap->fdebug[SOAP_INDEX_TEST])
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): free(%p)\n", file, line, p));
+      mp->live = 0;
+    }
+    else
+      fprintf(stderr, "%s(%d): free(%p) double free of pointer malloced at %s(%d)\n", file, line, p, mp->file, mp->line);
+  }
+  else
+    fprintf(stderr, "%s(%d): free(%p) pointer not malloced\n", file, line, p);
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+static void
+soap_track_unlink(struct soap *soap, const void *p)
+{ register int h = soap_hash_ptr(p);
+  register struct soap_mlist *mp;
+  for (mp = soap->mht[h]; mp; mp = mp->next)
+    if (mp->ptr == p)
+      break;
+  if (mp)
+    mp->live = 0;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_dealloc(struct soap *soap, void *p)
+{ if (!soap)
+    return;
+  if (p)
+  { register char **q;
+    for (q = (char**)&soap->alist; *q; q = *(char***)q)
+    { if (p == (void*)(*q - *(size_t*)(*q + sizeof(void*))))
+      { *q = **(char***)q;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Freed data at %p\n", p));
+        SOAP_FREE(soap, p);
+        return;
+      }
+    }
+    soap_delete(soap, p);
+  }
+  else
+  { register char *q;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free all soap_malloc() data\n"));
+    while (soap->alist)
+    { q = (char*)soap->alist;
+      soap->alist = *(void**)q;
+      q -= *(size_t*)(q + sizeof(void*));
+      SOAP_FREE(soap, q);
+    }
+  }
+  /* we must assume these were deallocated: */
+  soap->action = NULL;
+  soap->fault = NULL;
+  soap->header = NULL;
+  soap->userid = NULL;
+  soap->passwd = NULL;
+  soap->authrealm = NULL;
+#ifndef WITH_LEANER
+  soap_clr_mime(soap);
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_delete(struct soap *soap, void *p)
+{ register struct soap_clist **cp = &soap->clist;
+  if (p)
+  { while (*cp)
+    { if (p == (*cp)->ptr)
+      { register struct soap_clist *q = *cp;
+        *cp = q->next;
+        q->fdelete(q);
+        SOAP_FREE(soap, q);
+        return;
+      }
+      cp = &(*cp)->next;
+    }
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not dealloc data %p: address not in list\n", p));
+  }
+  else
+  { while (*cp)
+    { register struct soap_clist *q = *cp;
+      *cp = q->next;
+      if (q->ptr == (void*)soap->fault)
+        soap->fault = NULL; /* this was deallocated */
+      else if (q->ptr == (void*)soap->header)
+        soap->header = NULL; /* this was deallocated */
+      q->fdelete(q);
+      SOAP_FREE(soap, q);
+    }
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+struct soap_clist *
+SOAP_FMAC2
+soap_link(struct soap *soap, void *p, int t, int n, void (*fdelete)(struct soap_clist*))
+{ register struct soap_clist *cp;
+  if ((cp = (struct soap_clist*)SOAP_MALLOC(soap, sizeof(struct soap_clist))))
+  { cp->next = soap->clist;
+    cp->type = t;
+    cp->size = n; 
+    cp->ptr = p;
+    cp->fdelete = fdelete;
+    soap->clist = cp;
+  }
+  return cp;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_unlink(struct soap *soap, const void *p)
+{ register char **q;
+  register struct soap_clist **cp;
+  if (!soap || !p)
+    return;
+  for (q = (char**)&soap->alist; *q; q = *(char***)q)
+  { if (p == (void*)(*q - *(size_t*)(*q + sizeof(void*))))
+    { *q = **(char***)q;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked data %p\n", p));
+#ifdef SOAP_DEBUG
+      soap_track_unlink(soap, p);
+#endif
+      return;
+    }
+  }
+  for (cp = &soap->clist; *cp; cp = &(*cp)->next)
+  { if (p == (*cp)->ptr)
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked class instance %p\n", p));
+      q = (char**)*cp;
+      *cp = (*cp)->next;
+      SOAP_FREE(soap, q);
+      return;
+    }
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_lookup_type(struct soap *soap, const char *id)
+{ register struct soap_ilist *ip;
+  if (id && *id)
+  { ip = soap_lookup(soap, id);
+    if (ip)
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Lookup id='%s' type=%d\n", id, ip->type));
+      return ip->type;
+    }
+  }
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "lookup type id='%s' NOT FOUND! Need to get it from xsi:type\n", id));
+  return 0;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+void*
+SOAP_FMAC2
+soap_id_lookup(struct soap *soap, const char *id, void **p, int t, size_t n, unsigned int k)
+{ struct soap_ilist *ip;
+  void **q;
+  if (!p || !id || !*id)
+    return p;
+  ip = soap_lookup(soap, id); /* lookup pointer to hash table entry for string id */
+  if (!ip)
+  { ip = soap_enter(soap, id); /* new hash table entry for string id */
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding first href='%s' type=%d %p (%u bytes)\n", id, t, p, (unsigned int)n));
+    ip->type = t;
+    ip->size = n; 
+    ip->link = p;
+    ip->copy = NULL;
+    ip->flist = NULL;
+    ip->ptr = NULL;
+    ip->level = k;
+    *p = NULL;
+  }
+  else if (ip->ptr)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolved href='%s' type=%d location=%p (%u bytes)\n", id, t, ip->ptr, (unsigned int)n));
+    if (ip->type != t)
+    { strcpy(soap->id, id);
+      soap->error = SOAP_HREF;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility: id type=%d href type=%d\n", ip->type, t));
+      return NULL;
+    }
+    while (ip->level < k)
+    { q = (void**)soap_malloc(soap, sizeof(void*));  
+      if (!q)
+        return NULL;
+      *p = (void*)q;
+      p = q;
+      k--;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n"));
+    }
+    *p = ip->ptr;
+  }
+  else if (ip->level > k)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving level %u pointers to href='%s'\n", ip->level, id));
+    while (ip->level > k)
+    { void *s, **r = &ip->link;
+      q = (void**)ip->link;
+      while (q)
+      { *r = (void*)soap_malloc(soap, sizeof(void*));
+        s = *q;
+        *q = *r;
+        r = (void**)*r;
+        q = (void**)s;
+      }
+      *r = NULL;
+      ip->size = n; 
+      ip->copy = NULL;
+      ip->level = ip->level - 1;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n"));
+    }
+    q = (void**)ip->link;
+    ip->link = p;
+    *p = (void*)q;
+  }
+  else
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarded href='%s' type=%d location=%p (%u bytes)\n", id, t, p, (unsigned int)n));
+    while (ip->level < k)
+    { q = (void**)soap_malloc(soap, sizeof(void*));  
+      *p = q;
+      p = q;
+      k--;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Descending one level...\n"));
+    }
+    q = (void**)ip->link;
+    ip->link = p;
+    *p = (void*)q;
+  }
+  return p;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIDREF
+#ifndef PALM_2
+SOAP_FMAC1
+void*
+SOAP_FMAC2
+soap_id_forward(struct soap *soap, const char *href, void *p, int st, int tt, size_t n, unsigned int k, void (*fcopy)(struct soap*, int, int, void*, const void*, size_t))
+{ struct soap_ilist *ip;
+  if (!p || !href || !*href)
+    return p;
+  ip = soap_lookup(soap, href); /* lookup pointer to hash table entry for string id */
+  if (!ip)
+  { ip = soap_enter(soap, href); /* new hash table entry for string id */
+    ip->type = st;
+    ip->size = n;
+    ip->link = NULL;
+    ip->copy = NULL;
+    ip->ptr = NULL;
+    ip->level = 0;
+    ip->flist = NULL;
+    DBGLOG(TEST,SOAP_MESSAGE(fdebug, "New entry href='%s' type=%d size=%lu level=%d location=%p\n", href, st, (unsigned long)n, k, p));
+  }
+  else if (ip->type != st || (ip->level == k && ip->size != n))
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility id='%s' expect type=%d size=%lu level=%u got type=%d size=%lu\n", href, ip->type, (unsigned long)ip->size, k, st, (unsigned long)n));
+    strcpy(soap->id, href);
+    soap->error = SOAP_HREF;
+    return NULL;
+  }
+  if (fcopy || n < sizeof(void*) || *href != '#')
+  { register struct soap_flist *fp = (struct soap_flist*)SOAP_MALLOC(soap, sizeof(struct soap_flist));
+    if (!fp)
+    { soap->error = SOAP_EOM;
+      return NULL;
+    }
+    fp->next = ip->flist;
+    fp->type = tt;
+    fp->ptr = p;
+    fp->level = k;
+    if (fcopy)
+      fp->fcopy = fcopy;
+    else
+      fp->fcopy = soap_fcopy;
+    ip->flist = fp;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding type=%d (target type=%d) size=%lu location=%p level=%u href='%s'\n", st, tt, (unsigned long)n, p, k, href));
+  }
+  else
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Forwarding copying address %p for type=%d href='%s'\n", p, st, href));
+    *(void**)p = ip->copy;
+    ip->copy = p;
+  }
+  return p;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void*
+SOAP_FMAC2
+soap_id_enter(struct soap *soap, const char *id, void *p, int t, size_t n, unsigned int k, const char *type, const char *arrayType, void *(*finstantiate)(struct soap*, int, const char*, const char*, size_t*))
+{
+#ifndef WITH_NOIDREF
+  struct soap_ilist *ip;
+#endif
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Enter id='%s' type=%d loc=%p size=%lu level=%u\n", id, t, p, (unsigned long)n, k));
+  soap->alloced = 0;
+  if (!p)
+  { if (finstantiate)
+      p = finstantiate(soap, t, type, arrayType, &n);
+    else
+      p = soap_malloc(soap, n);
+    if (p)
+      soap->alloced = 1;
+  }
+#ifndef WITH_NOIDREF
+  if (!id || !*id)
+#endif
+    return p;
+#ifndef WITH_NOIDREF
+  ip = soap_lookup(soap, id); /* lookup pointer to hash table entry for string id */
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Lookup entry id='%s for location=%p'\n", id, p));
+  if (!ip)
+  { ip = soap_enter(soap, id); /* new hash table entry for string id */
+    ip->type = t;
+    ip->link = NULL;
+    ip->copy = NULL;
+    ip->flist = NULL;
+    ip->size = n;
+    ip->ptr = p;
+    ip->level = k;
+    DBGLOG(TEST,SOAP_MESSAGE(fdebug, "New entry id='%s' type=%d size=%lu level=%u location=%p\n", id, t, (unsigned long)n, k, p));
+  }
+  else if ((ip->type != t || (ip->level == k && ip->size != n)) && (ip->copy || ip->flist))
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Type incompatibility id='%s' expect type=%d size=%lu level=%u got type=%d size=%lu\n", id, ip->type, (unsigned long)ip->size, k, t, (unsigned long)n));
+    strcpy(soap->id, id);
+    soap->error = SOAP_HREF;
+    return NULL;
+  }
+  else if (ip->ptr)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Multiply defined id='%s'\n", id));
+    strcpy(soap->id, id);
+    soap->error = SOAP_DUPLICATE_ID;
+    return NULL;
+  }
+  else 
+  { ip->size = n;
+    ip->ptr = p;
+    ip->level = k;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update entry id='%s' type=%d location=%p size=%lu level=%u\n", id, t, p, (unsigned long)n, k));
+  }
+  return ip->ptr;
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_fcopy(struct soap *soap, int st, int tt, void *p, const void *q, size_t n)
+{ DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Copying data type=%d (target type=%d) %p -> %p (%lu bytes)\n", st, tt, q, p, (unsigned long)n));
+  memcpy(p, q, n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_end_send(struct soap *soap)
+{ 
+#ifndef WITH_LEANER
+  if (soap->dime.list)
+  { /* SOAP body referenced attachments must appear first */
+    soap->dime.last->next = soap->dime.first;
+    soap->dime.first = soap->dime.list->next;
+    soap->dime.list->next = NULL;
+    soap->dime.last = soap->dime.list;
+  }
+  if (soap_putdime(soap) || soap_putmime(soap))
+    return soap->error;
+  soap->mime.list = NULL;
+  soap->mime.first = NULL;
+  soap->mime.last = NULL;
+  soap->dime.list = NULL;
+  soap->dime.first = NULL;
+  soap->dime.last = NULL;
+#endif
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End send\n"));
+  if (soap->mode & SOAP_IO) /* need to flush the remaining data in buffer */
+  { if (soap_flush(soap))
+#ifdef WITH_ZLIB
+    { if (soap->mode & SOAP_ENC_ZLIB && soap->zlib_state == SOAP_ZLIB_DEFLATE)
+      { soap->zlib_state = SOAP_ZLIB_NONE;
+        deflateEnd(&soap->d_stream);
+      }
+      return soap->error;
+    }
+#else
+      return soap->error;
+#endif
+#ifdef WITH_ZLIB
+    if (soap->mode & SOAP_ENC_ZLIB)
+    { int r;
+      soap->d_stream.avail_in = 0;
+      do
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflating remainder\n"));
+        r = deflate(&soap->d_stream, Z_FINISH);
+        if (soap->d_stream.avail_out != SOAP_BUFLEN)
+        { if (soap_flush_raw(soap, soap->z_buf, SOAP_BUFLEN - soap->d_stream.avail_out))
+          { soap->zlib_state = SOAP_ZLIB_NONE;
+            deflateEnd(&soap->d_stream);
+            return soap->error;
+	  }
+          soap->d_stream.next_out = (Byte*)soap->z_buf;
+          soap->d_stream.avail_out = SOAP_BUFLEN;
+        }
+      } while (r == Z_OK);
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflated %lu->%lu bytes\n", soap->d_stream.total_in, soap->d_stream.total_out));
+      soap->z_ratio_out = (float)soap->d_stream.total_out / (float)soap->d_stream.total_in;
+      soap->mode &= ~SOAP_ENC_ZLIB;
+      soap->zlib_state = SOAP_ZLIB_NONE;
+      if (deflateEnd(&soap->d_stream) != Z_OK || r != Z_STREAM_END)
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to end deflate: %s\n", soap->d_stream.msg?soap->d_stream.msg:""));
+        return soap->error = SOAP_ZLIB_ERROR;
+      }
+#ifdef WITH_GZIP
+      soap->z_buf[0] = soap->z_crc & 0xFF;
+      soap->z_buf[1] = (soap->z_crc >> 8) & 0xFF;
+      soap->z_buf[2] = (soap->z_crc >> 16) & 0xFF;
+      soap->z_buf[3] = (soap->z_crc >> 24) & 0xFF;
+      soap->z_buf[4] = soap->d_stream.total_in & 0xFF;
+      soap->z_buf[5] = (soap->d_stream.total_in >> 8) & 0xFF;
+      soap->z_buf[6] = (soap->d_stream.total_in >> 16) & 0xFF;
+      soap->z_buf[7] = (soap->d_stream.total_in >> 24) & 0xFF;
+      if (soap_flush_raw(soap, soap->z_buf, 8))
+        return soap->error;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip crc32=%lu\n", (unsigned long)soap->z_crc));
+#endif
+    }
+#endif
+    if ((soap->mode & SOAP_IO) == SOAP_IO_STORE)
+    { char *p;
+#ifndef WITH_NOHTTP
+      if (!(soap->mode & SOAP_ENC_XML))
+      { soap->mode--;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending buffered message of length %u\n", (unsigned int)soap->blist->size));
+        if (soap->status >= SOAP_POST)
+          soap->error = soap->fpost(soap, soap->endpoint, soap->host, soap->port, soap->path, soap->action, soap->blist->size);
+        else if (soap->status != SOAP_STOP)
+          soap->error = soap->fresponse(soap, soap->status, soap->blist->size);
+        if (soap->error || soap_flush(soap))
+          return soap->error;
+        soap->mode++;
+      }
+#endif
+      for (p = soap_first_block(soap); p; p = soap_next_block(soap))
+      { DBGMSG(SENT, p, soap_block_size(soap));
+        if ((soap->error = soap->fsend(soap, p, soap_block_size(soap))))
+        { soap_end_block(soap);
+          return soap->error;
+        }
+      }
+      soap_end_block(soap);
+    }
+#ifndef WITH_LEANER
+    else if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK)
+    { DBGMSG(SENT, "\r\n0\r\n\r\n", 7);
+      if ((soap->error = soap->fsend(soap, "\r\n0\r\n\r\n", 7)))
+        return soap->error;
+    }
+#endif
+  }
+#ifdef WITH_OPENSSL
+  if (!soap->ssl && soap_valid_socket(soap->socket) && !soap->keep_alive && !(soap->omode & SOAP_IO_UDP))
+    soap->fshutdownsocket(soap, (SOAP_SOCKET)soap->socket, 1); /* Send TCP FIN */
+#else
+  if (soap_valid_socket(soap->socket) && !soap->keep_alive && !(soap->omode & SOAP_IO_UDP))
+    soap->fshutdownsocket(soap, (SOAP_SOCKET)soap->socket, 1); /* Send TCP FIN */
+#endif
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End of send phase\n"));
+  soap->omode &= ~SOAP_XML_SEC;
+  soap->count = 0;
+  soap->part = SOAP_END;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_end_recv(struct soap *soap)
+{ soap->part = SOAP_END;
+#ifndef WITH_LEANER
+  if ((soap->mode & SOAP_ENC_DIME) && soap_getdime(soap))
+    return soap->error;
+  soap->dime.list = soap->dime.first;
+  soap->dime.first = NULL;
+  soap->dime.last = NULL;
+  if ((soap->mode & SOAP_ENC_MIME) && soap_getmime(soap))
+    return soap->error;
+  soap->mime.list = soap->mime.first;
+  soap->mime.first = NULL;
+  soap->mime.last = NULL;
+  soap->mime.boundary = NULL;
+#endif
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "End of receive message ok\n"));
+#ifdef WITH_ZLIB
+  if (soap->mode & SOAP_ENC_ZLIB)
+  { soap->mode &= ~SOAP_ENC_ZLIB;
+    memcpy(soap->buf, soap->z_buf, SOAP_BUFLEN);
+    soap->bufidx = (char*)soap->d_stream.next_in - soap->z_buf;
+    soap->buflen = soap->z_buflen;
+    soap->zlib_state = SOAP_ZLIB_NONE;
+    if (inflateEnd(&soap->d_stream) != Z_OK)
+      return soap->error = SOAP_ZLIB_ERROR;
+#ifdef WITH_GZIP
+    if (soap->zlib_in == SOAP_ZLIB_GZIP)
+    { soap_wchar c;
+      short i;
+      for (i = 0; i < 8; i++)
+      { if ((int)(c = soap_getchar(soap)) == EOF)
+          return soap->error = SOAP_EOF;
+        soap->z_buf[i] = (char)c;
+      }
+      if (soap->z_crc != ((uLong)(unsigned char)soap->z_buf[0] | ((uLong)(unsigned char)soap->z_buf[1] << 8) | ((uLong)(unsigned char)soap->z_buf[2] << 16) | ((uLong)(unsigned char)soap->z_buf[3] << 24)))
+      { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Gzip error: crc check failed, message corrupted? (crc32=%lu)\n", (unsigned long)soap->z_crc));
+        return soap->error = SOAP_ZLIB_ERROR;
+      }
+      if (soap->d_stream.total_out != ((uLong)(unsigned char)soap->z_buf[4] | ((uLong)(unsigned char)soap->z_buf[5] << 8) | ((uLong)(unsigned char)soap->z_buf[6] << 16) | ((uLong)(unsigned char)soap->z_buf[7] << 24)))
+      { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Gzip error: incorrect message length\n"));
+        return soap->error = SOAP_ZLIB_ERROR;
+      }
+    }
+#endif
+  }
+#endif
+  if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK)
+    while ((int)soap_getchar(soap) != EOF) /* advance to last chunk */
+      ;
+  if (soap->fdisconnect && (soap->error = soap->fdisconnect(soap)))
+    return soap->error;
+#ifndef WITH_NOIDREF
+  return soap_resolve(soap);
+#else
+#ifndef WITH_LEANER
+  if (soap->xlist)
+  { if (soap->mode & SOAP_ENC_MTOM)
+      return soap->error = SOAP_MIME_HREF;
+    return soap->error = SOAP_DIME_HREF;
+  }
+#endif
+  return SOAP_OK;
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_free(struct soap *soap)
+{ register struct Namespace *ns;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free namespace stack\n"));
+  while (soap->nlist)
+  { register struct soap_nlist *np = soap->nlist->next;
+    SOAP_FREE(soap, soap->nlist);
+    soap->nlist = np;
+  }
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free any remaining temp blocks\n"));
+  while (soap->blist)
+    soap_end_block(soap);
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free attribute storage\n"));
+  while (soap->attributes)
+  { register struct soap_attribute *tp = soap->attributes->next;
+    if (soap->attributes->value)
+      SOAP_FREE(soap, soap->attributes->value);
+    SOAP_FREE(soap, soap->attributes);
+    soap->attributes = tp;
+  }
+#ifdef WITH_FAST
+  if (soap->labbuf)
+    SOAP_FREE(soap, soap->labbuf);
+  soap->labbuf = NULL;
+  soap->lablen = 0;
+  soap->labidx = 0;
+#endif
+  ns = soap->local_namespaces;
+  if (ns)
+  { for (; ns->id; ns++)
+    { if (ns->out)
+      { if (soap->encodingStyle == ns->out)
+          soap->encodingStyle = SOAP_STR_EOS;
+        SOAP_FREE(soap, ns->out);
+        ns->out = NULL;
+      }
+      if (soap->encodingStyle == ns->ns)
+        soap->encodingStyle = SOAP_STR_EOS;
+    }
+    SOAP_FREE(soap, soap->local_namespaces);
+    soap->local_namespaces = NULL;
+  }
+#ifndef WITH_LEANER
+  while (soap->xlist)
+  { struct soap_xlist *xp = soap->xlist->next;
+    SOAP_FREE(soap, soap->xlist);
+    soap->xlist = xp;
+  }
+#endif
+#ifndef WITH_NOIDREF
+  soap_free_pht(soap);
+  soap_free_iht(soap);
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+static void
+soap_init_logs(struct soap *soap)
+{ int i;
+  for (i = 0; i < SOAP_MAXLOGS; i++)
+  { soap->logfile[i] = NULL;
+    soap->fdebug[i] = NULL;
+  }
+}
+#endif
+
+/******************************************************************************/
+#if !defined(WITH_LEAN) || defined(SOAP_DEBUG)
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_open_logfile(struct soap *soap, int i)
+{ if (soap->logfile[i])
+    soap->fdebug[i] = fopen(soap->logfile[i], i < 2 ? "ab" : "a");
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+static void
+soap_close_logfile(struct soap *soap, int i)
+{ if (soap->fdebug[i])
+  { fclose(soap->fdebug[i]);
+    soap->fdebug[i] = NULL;
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_close_logfiles(struct soap *soap)
+{ int i;
+  for (i = 0; i < SOAP_MAXLOGS; i++)
+    soap_close_logfile(soap, i);
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+static void
+soap_set_logfile(struct soap *soap, int i, const char *logfile)
+{ char *s = NULL;
+  soap_close_logfile(soap, i);
+  if (soap->logfile[i])
+    SOAP_FREE(soap, (void*)soap->logfile[i]);
+  if (logfile)
+    if ((s = (char*)SOAP_MALLOC(soap, strlen(logfile) + 1)))
+      strcpy(s, logfile);
+  soap->logfile[i] = s;
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_recv_logfile(struct soap *soap, const char *logfile)
+{ soap_set_logfile(soap, SOAP_INDEX_RECV, logfile);
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_sent_logfile(struct soap *soap, const char *logfile)
+{ soap_set_logfile(soap, SOAP_INDEX_SENT, logfile);
+}
+#endif
+
+/******************************************************************************/
+#ifdef SOAP_DEBUG
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_test_logfile(struct soap *soap, const char *logfile)
+{ soap_set_logfile(soap, SOAP_INDEX_TEST, logfile);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+struct soap*
+SOAP_FMAC2
+soap_copy(struct soap *soap)
+{ return soap_copy_context((struct soap*)malloc(sizeof(struct soap)), soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+struct soap*
+SOAP_FMAC2
+soap_copy_context(struct soap *copy, struct soap *soap)
+{ if (copy)
+  { register struct soap_plugin *p;
+    memcpy(copy, soap, sizeof(struct soap));
+    copy->copy = 1;
+    copy->user = NULL;
+    copy->error = SOAP_OK;
+    copy->userid = NULL;
+    copy->passwd = NULL;
+    copy->nlist = NULL;
+    copy->blist = NULL;
+    copy->clist = NULL;
+    copy->alist = NULL;
+    copy->attributes = NULL;
+#ifdef WITH_FAST
+    copy->labbuf = NULL;
+    copy->lablen = 0;
+    copy->labidx = 0;
+#endif
+#ifdef SOAP_DEBUG
+    soap_init_mht(copy);
+#endif
+    copy->local_namespaces = NULL;
+#ifndef WITH_NOIDREF
+    soap_init_iht(copy);
+    soap_init_pht(copy);
+#endif
+    copy->header = NULL;
+    copy->fault = NULL;
+    copy->action = NULL;
+    *copy->host = '\0';
+#ifndef WITH_LEAN
+#ifdef WITH_COOKIES
+    copy->cookies = soap_copy_cookies(copy);
+#else
+    copy->cookies = NULL;
+#endif
+#endif
+#ifdef SOAP_DEBUG
+    soap_init_logs(copy);
+    soap_set_recv_logfile(copy, soap->logfile[SOAP_INDEX_RECV]);
+    soap_set_sent_logfile(copy, soap->logfile[SOAP_INDEX_SENT]);
+    soap_set_test_logfile(copy, soap->logfile[SOAP_INDEX_TEST]);
+#endif
+    copy->plugins = NULL;
+    for (p = soap->plugins; p; p = p->next)
+    { register struct soap_plugin *q = (struct soap_plugin*)SOAP_MALLOC(copy, sizeof(struct soap_plugin));
+      if (!q)
+        return NULL;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying plugin '%s'\n", p->id));
+      *q = *p;
+      if (p->fcopy && (soap->error = p->fcopy(copy, q, p)))
+      { SOAP_FREE(copy, q);
+        return NULL;
+      }
+      q->next = copy->plugins;
+      copy->plugins = q;
+    }
+  }
+  else
+    soap->error = SOAP_EOM;
+  return copy;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_init(struct soap *soap)
+{ soap->version = 0;
+  soap_imode(soap, SOAP_IO_DEFAULT);
+  soap_omode(soap, SOAP_IO_DEFAULT);
+  soap->copy = 0;
+  soap->plugins = NULL;
+  soap->user = NULL;
+  soap->userid = NULL;
+  soap->passwd = NULL;
+#ifndef WITH_NOHTTP
+  soap->fpost = http_post;
+  soap->fget = http_get;
+  soap->fform = NULL;
+  soap->fposthdr = http_post_header;
+  soap->fresponse = http_response;
+  soap->fparse = http_parse;
+  soap->fparsehdr = http_parse_header;
+#endif
+  soap->fconnect = NULL;
+  soap->fdisconnect = NULL;
+#ifndef WITH_NOIO
+#ifndef WITH_IPV6
+  soap->fresolve = tcp_gethost;
+#else
+  soap->fresolve = NULL;
+#endif
+  soap->faccept = tcp_accept;
+  soap->fopen = tcp_connect;
+  soap->fclose = tcp_disconnect;
+  soap->fclosesocket = tcp_closesocket;
+  soap->fshutdownsocket = tcp_shutdownsocket;
+  soap->fsend = fsend;
+  soap->frecv = frecv;
+  soap->fpoll = soap_poll;
+#else
+  soap->fopen = NULL;
+  soap->fclose = NULL;
+  soap->fpoll = NULL;
+#endif
+#ifndef WITH_LEANER
+  soap->fprepareinit = NULL;
+  soap->fpreparesend = NULL;
+  soap->fpreparerecv = NULL;
+  soap->fpreparefinal = NULL;
+#endif
+  soap->fseterror = NULL;
+  soap->fignore = NULL;
+  soap->fserveloop = NULL;
+  soap->fplugin = fplugin;
+#ifndef WITH_LEANER
+  soap->fdimereadopen = NULL;
+  soap->fdimewriteopen = NULL;
+  soap->fdimereadclose = NULL;
+  soap->fdimewriteclose = NULL;
+  soap->fdimeread = NULL;
+  soap->fdimewrite = NULL;
+#endif
+  soap->float_format = "%.8g"; /* .8 preserves single FP precision as much as possible, but might not be very efficient */
+  soap->double_format = "%.17lg"; /* .17 preserves double FP precision as much as possible, but might not be very efficient */
+  soap->dime_id_format = "cid:id%d"; /* default DIME id format */
+  soap->http_version = "1.1";
+  soap->actor = NULL;
+  soap->max_keep_alive = SOAP_MAXKEEPALIVE;
+  soap->keep_alive = 0;
+  soap->recv_timeout = 0;
+  soap->send_timeout = 0;
+  soap->connect_timeout = 0;
+  soap->accept_timeout = 0;
+  soap->socket_flags = 0;
+  soap->connect_flags = 0;
+  soap->bind_flags = 0;
+  soap->accept_flags = 0;
+  soap->ip = 0;
+#ifdef WITH_FAST
+  soap->labbuf = NULL;
+  soap->lablen = 0;
+  soap->labidx = 0;
+#endif
+  soap->encodingStyle = SOAP_STR_EOS;
+#ifndef WITH_NONAMESPACES
+  soap->namespaces = namespaces;
+#else
+  soap->namespaces = NULL;
+#endif
+  soap->local_namespaces = NULL;
+  soap->nlist = NULL;
+  soap->blist = NULL;
+  soap->clist = NULL;
+  soap->alist = NULL;
+  soap->attributes = NULL;
+  soap->header = NULL;
+  soap->fault = NULL;
+  soap->master = SOAP_INVALID_SOCKET;
+  soap->socket = SOAP_INVALID_SOCKET;
+  soap->os = NULL;
+  soap->is = NULL;
+#ifndef WITH_LEANER
+  soap->dom = NULL;
+  soap->dime.list = NULL;
+  soap->dime.first = NULL;
+  soap->dime.last = NULL;
+  soap->mime.list = NULL;
+  soap->mime.first = NULL;
+  soap->mime.last = NULL;
+  soap->mime.boundary = NULL;
+  soap->mime.start = NULL;
+  soap->xlist = NULL;
+#endif
+#ifndef UNDER_CE
+  soap->recvfd = 0;
+  soap->sendfd = 1;
+#else
+  soap->recvfd = stdin;
+  soap->sendfd = stdout;
+#endif 
+  soap->host[0] = '\0';
+  soap->port = 0;
+  soap->action = NULL;
+  soap->proxy_host = NULL;
+  soap->proxy_port = 8080;
+  soap->proxy_userid = NULL;
+  soap->proxy_passwd = NULL;
+  soap->authrealm = NULL;
+  soap->prolog = NULL;
+#ifdef WITH_OPENSSL
+  soap->fsslauth = ssl_auth_init;
+  soap->fsslverify = ssl_verify_callback;
+  soap->bio = NULL;
+  soap->ssl = NULL;
+  soap->ctx = NULL;
+  soap->require_server_auth = 0;
+  soap->require_client_auth = 0;
+  soap->rsa = 0;
+  soap->keyfile = NULL;
+  soap->password = NULL;
+  soap->dhfile = NULL;
+  soap->cafile = NULL;
+  soap->capath = NULL;
+  soap->crlfile = NULL;
+  soap->randfile = NULL;
+  soap->session = NULL;
+#endif
+#ifdef WITH_ZLIB
+  soap->zlib_state = SOAP_ZLIB_NONE;
+  soap->zlib_in = SOAP_ZLIB_NONE;
+  soap->zlib_out = SOAP_ZLIB_NONE;
+  soap->d_stream.zalloc = NULL;
+  soap->d_stream.zfree = NULL;
+  soap->d_stream.opaque = NULL;
+  soap->z_level = 6;
+#endif
+#ifndef WITH_LEAN
+  soap->c14ninclude = NULL;
+  soap->c14nexclude = NULL;
+  soap->cookies = NULL;
+  soap->cookie_domain = NULL;
+  soap->cookie_path = NULL;
+  soap->cookie_max = 32;
+#endif
+#ifdef SOAP_DEBUG
+  soap_init_mht(soap);
+  soap_init_logs(soap);
+  soap_set_recv_logfile(soap, "RECV.log");
+  soap_set_sent_logfile(soap, "SENT.log");
+  soap_set_test_logfile(soap, NULL);
+#endif
+#ifdef WMW_RPM_IO
+  soap->rpmreqid = NULL;
+#endif /* WMW_RPM_IO */
+#ifdef PALM
+  palmNetLibOpen();
+#endif
+#ifndef WITH_NOIDREF
+  soap_init_iht(soap);
+  soap_init_pht(soap);
+#endif
+  soap_begin(soap);
+#ifdef SOAP_DEBUG
+  soap_set_test_logfile(soap, "TEST.log");
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_init1(struct soap *soap, soap_mode mode)
+{ soap_init2(soap, mode, mode);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_init2(struct soap *soap, soap_mode imode, soap_mode omode)
+{ soap_init(soap);
+  soap_imode(soap, imode);
+  soap_omode(soap, omode);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_begin(struct soap *soap)
+{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing\n"));
+  if (!soap->keep_alive)
+  { soap->buflen = 0;
+    soap->bufidx = 0;
+  }
+  soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0);
+  soap->null = 0;
+  soap->position = 0;
+  soap->encoding = 0;
+  soap->mustUnderstand = 0;
+  soap->mode = 0;
+  soap->ns = 0;
+  soap->part = SOAP_END;
+  soap->alloced = 0;
+  soap->count = 0;
+  soap->length = 0;
+  soap->cdata = 0;
+  soap->error = SOAP_OK;
+  soap->peeked = 0;
+  soap->ahead = 0;
+  soap->idnum = 0;
+  soap->level = 0;
+  soap->endpoint[0] = '\0';
+#ifndef WITH_LEANER
+  soap->dime.chunksize = 0;
+  soap->dime.buflen = 0;
+#endif
+  soap_free(soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_end(struct soap *soap)
+{ register struct soap_clist *cp;
+  soap_free(soap);
+  soap_dealloc(soap, NULL);
+  while (soap->clist)
+  { cp = soap->clist->next;
+    SOAP_FREE(soap, soap->clist);
+    soap->clist = cp;
+  }
+  soap_closesock(soap);
+#ifdef SOAP_DEBUG
+  soap_close_logfiles(soap);
+#endif
+#ifdef PALM
+  palmNetLibClose();
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_set_namespaces(struct soap *soap, struct Namespace *p)
+{ register struct Namespace *ns = soap->local_namespaces;
+  register struct soap_nlist *np, *nq, *nr;
+  register unsigned int level = soap->level;
+  soap->namespaces = p;
+  soap->local_namespaces = NULL;
+  soap_set_local_namespaces(soap);
+  /* reverse the namespace list */
+  np = soap->nlist;
+  soap->nlist = NULL;
+  if (np)
+  { nq = np->next;
+    np->next = NULL;
+    while (nq)
+    { nr = nq->next;
+      nq->next = np;
+      np = nq;
+      nq = nr;
+    }
+  }
+  /* then push on new stack */
+  while (np)
+  { register const char *s;
+    soap->level = np->level; /* preserve element nesting level */
+    s = np->ns;
+    if (!s && np->index >= 0 && ns)
+    { s = ns[np->index].out;
+      if (!s)
+        s = ns[np->index].ns;
+    }
+    if (s && soap_push_namespace(soap, np->id, s))
+      return soap->error;
+    nq = np;
+    np = np->next;
+    SOAP_FREE(soap, nq);
+  }
+  if (ns)
+  { register int i;
+    for (i = 0; ns[i].id; i++)
+    { if (ns[i].out)
+      { SOAP_FREE(soap, ns[i].out);
+        ns[i].out = NULL;
+      }
+    }
+    SOAP_FREE(soap, ns);
+  }
+  soap->level = level; /* restore level */
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_local_namespaces(struct soap *soap)
+{ if (soap->namespaces && !soap->local_namespaces)
+  { register const struct Namespace *ns1;
+    register struct Namespace *ns2;
+    register size_t n = 1;
+    for (ns1 = soap->namespaces; ns1->id; ns1++)
+      n++;
+    n *= sizeof(struct Namespace);
+    ns2 = (struct Namespace*)SOAP_MALLOC(soap, n);
+    if (ns2)
+    { memcpy(ns2, soap->namespaces, n);
+      if (ns2[0].ns)
+      { if (!strcmp(ns2[0].ns, soap_env1))
+          soap->version = 1;
+        else
+          soap->version = 2;
+      }
+      soap->local_namespaces = ns2;
+    }
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+#ifndef PALM_1
+SOAP_FMAC1
+const char *
+SOAP_FMAC2
+soap_strsearch(const char *big, const char *little)
+{ size_t n = strlen(little);
+  const char *s = big;
+  while (s) 
+  { if (!strncmp(s, little, n) && (s[n] == '\0' || s[n] == ' '))
+      return s;
+    s = strchr(s, ' ');
+    if (s)
+      s++;
+  }
+  return NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+static struct soap_nlist *
+soap_lookup_ns(struct soap *soap, const char *tag, size_t n)
+{ register struct soap_nlist *np;
+  for (np = soap->nlist; np; np = np->next)
+  { if (!strncmp(np->id, tag, n) && !np->id[n])
+      return np;
+  }
+  return NULL;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+static struct soap_nlist *
+soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized)
+{ register struct soap_nlist *np;
+  size_t n, k;
+  if (soap_strsearch(soap->c14nexclude, id))
+    return NULL;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push namespace binding (level=%u) '%s' '%s'\n", soap->level, id, ns?ns:""));
+  if (!utilized)
+  { for (np = soap->nlist; np; np = np->next)
+    { if (!strcmp(np->id, id) && (!np->ns || !strcmp(np->ns, ns)))
+        break;
+    }
+    if (np)
+    { if (np->index == 1)
+        utilized = np->index;
+      else
+        return NULL;
+    }
+  }
+  n = strlen(id);
+  if (ns)
+    k = strlen(ns);
+  else
+    k = 0;
+  np = (struct soap_nlist*)SOAP_MALLOC(soap, sizeof(struct soap_nlist) + n + k + 1);
+  if (!np)
+  { soap->error = SOAP_EOM;
+    return NULL;
+  }
+  np->next = soap->nlist;
+  soap->nlist = np;
+  strcpy(np->id, id);
+  if (ns)
+  { np->ns = np->id + n + 1;
+    strcpy(np->ns, ns);
+  }
+  else
+    np->ns = NULL;
+  np->level = soap->level;
+  np->index = utilized;
+  return np;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+static void
+soap_utilize_ns(struct soap *soap, const char *tag, size_t n)
+{ register struct soap_nlist *np = soap_lookup_ns(soap, tag, n);
+  if (np)
+  { if (np->index == 0)
+      soap_push_ns(soap, np->id, np->ns, 1);
+  }
+  else
+  { strncpy(soap->tmpbuf, tag, n);
+    soap->tmpbuf[n] = '\0';
+    soap_push_ns(soap, soap->tmpbuf, NULL, 1);
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+static void
+soap_pop_ns(struct soap *soap)
+{ soap_pop_namespace(soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element(struct soap *soap, const char *tag, int id, const char *type)
+{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element begin tag='%s' id='%d' type='%s'\n", tag, id, type?type:""));
+#ifdef WITH_DOM
+  if (soap->mode & SOAP_XML_DOM)
+  { register struct soap_dom_element *elt = (struct soap_dom_element*)soap_malloc(soap, sizeof(struct soap_dom_element));
+    if (!elt)
+      return soap->error = SOAP_EOM;
+    elt->soap = soap;
+    elt->next = NULL;
+    elt->prnt = soap->dom;
+    elt->name = soap_strdup(soap, tag);
+    elt->elts = NULL;
+    elt->atts = NULL;
+    elt->nstr = NULL;
+    elt->data = NULL;
+    elt->wide = NULL;
+    elt->node = NULL;
+    elt->type = 0;
+    elt->head = NULL;
+    elt->tail = NULL;
+    if (soap->dom)
+    { struct soap_dom_element *p = soap->dom->elts;
+      if (p)
+      { while (p->next)
+          p = p->next;
+        p->next = elt;
+      }
+      else
+        soap->dom->elts = elt;
+    }
+    soap->dom = elt;
+  }
+  else
+  {
+#endif
+    soap->level++;
+#ifndef WITH_LEAN
+    if (!soap->ns)
+    { if (!(soap->mode & SOAP_XML_CANONICAL)
+       && soap_send(soap, soap->prolog ? soap->prolog : "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"))
+        return soap->error;
+    }
+    else if (soap->mode & SOAP_XML_INDENT)
+    { if (soap->ns == 1 && soap_send_raw(soap, soap_indent, soap->level < sizeof(soap_indent) ? soap->level : sizeof(soap_indent) - 1))
+        return soap->error;
+      soap->body = 1;
+    }
+#endif
+    if (soap_send_raw(soap, "<", 1)
+     || soap_send(soap, tag))
+      return soap->error;
+#ifdef WITH_DOM
+  }
+#endif
+  if (!soap->ns)
+  { struct Namespace *ns;
+    for (ns = soap->local_namespaces; ns && ns->id; ns++)
+    { if (*ns->id && (ns->out || ns->ns))
+      { sprintf(soap->tmpbuf, "xmlns:%s", ns->id);
+        if (soap_attribute(soap, soap->tmpbuf, ns->out ? ns->out : ns->ns))
+          return soap->error;
+      }
+    }   
+  }
+  soap->ns = 1; /* start with 0 or 2, but should be one to continue */
+#ifndef WITH_LEAN
+  if (soap->mode & SOAP_XML_CANONICAL)
+  { const char *s = strchr(tag, ':');
+    if (s)
+      soap_utilize_ns(soap, tag, s - tag);
+  }
+#endif
+  if (id > 0)
+  { sprintf(soap->tmpbuf, "_%d", id);
+    if (soap_attribute(soap, "id", soap->tmpbuf))
+      return soap->error;
+  }
+  if (type && *type)
+  { if (soap_attribute(soap, "xsi:type", type))
+      return soap->error;
+#ifndef WITH_LEAN
+    if (soap->mode & SOAP_XML_CANONICAL)
+    { const char *s = strchr(type, ':');
+      if (s)
+        soap_utilize_ns(soap, type, s - type);
+    }
+#endif
+  }
+  if (soap->null && soap->position > 0)
+  { int i;
+    sprintf(soap->tmpbuf, "[%d", soap->positions[0]);
+    for (i = 1; i < soap->position; i++)
+      sprintf(soap->tmpbuf + strlen(soap->tmpbuf), ",%d", soap->positions[i]);
+    strcat(soap->tmpbuf, "]");
+    if (soap_attribute(soap, "SOAP-ENC:position", soap->tmpbuf))
+      return soap->error;
+  }
+  if (soap->mustUnderstand)
+  { if (soap->actor && *soap->actor)
+    { if (soap_attribute(soap, soap->version == 2 ? "SOAP-ENV:role" : "SOAP-ENV:actor", soap->actor))
+        return soap->error;
+    }
+    if (soap_attribute(soap, "SOAP-ENV:mustUnderstand", soap->version == 2 ? "true" : "1"))
+      return soap->error;
+    soap->mustUnderstand = 0;
+  }
+  if (soap->encoding)
+  { if (soap->encodingStyle && soap->local_namespaces)
+    { if (!*soap->encodingStyle)
+      { if (soap->local_namespaces[1].out)
+          soap->encodingStyle = soap->local_namespaces[1].out;
+        else
+          soap->encodingStyle = soap->local_namespaces[1].ns;
+      }
+      if (soap_attribute(soap, "SOAP-ENV:encodingStyle", soap->encodingStyle))
+        return soap->error;
+    }
+    soap->encoding = 0;
+  }
+  soap->null = 0;
+  soap->position = 0;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_begin_out(struct soap *soap, const char *tag, int id, const char *type)
+{ if (*tag == '-')
+    return SOAP_OK;
+  if (soap_element(soap, tag, id, type))
+    return soap->error;
+  return soap_element_start_end_out(soap, NULL);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+#ifndef HAVE_STRRCHR
+SOAP_FMAC1
+char*
+SOAP_FMAC2
+soap_strrchr(const char *s, int t)
+{ register char *r = NULL;
+  while (*s)
+    if (*s++ == t)
+      r = (char*)s - 1;
+  return r;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+#ifndef HAVE_STRTOL
+SOAP_FMAC1
+long
+SOAP_FMAC2
+soap_strtol(const char *s, char **t, int b)
+{ register long n = 0;
+  register int c;
+  while (*s > 0 && *s <= 32)
+    s++;
+  if (b == 10)
+  { short neg = 0;
+    if (*s == '-')
+    { s++;
+      neg = 1;
+    }
+    else if (*s == '+')
+      s++;
+    while ((c = *s) && c >= '0' && c <= '9')
+    { if (n >= 214748364 && (n > 214748364 || c >= '8'))
+        break;
+      n *= 10;
+      n += c - '0';
+      s++;
+    }
+    if (neg)
+      n = -n;
+  }
+  else /* b == 16 and value is always positive */
+  { while ((c = *s))
+    { if (c >= '0' && c <= '9')
+        c -= '0';
+      else if (c >= 'A' && c <= 'F')
+        c -= 'A' - 10;
+      else if (c >= 'a' && c <= 'f')
+        c -= 'a' - 10;
+      if (n > 0x07FFFFFF)
+        break;
+      n <<= 4;
+      n += c;
+      s++;
+    }
+  }
+  if (t)
+    *t = (char*)s;
+  return n;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+#ifndef HAVE_STRTOUL
+SOAP_FMAC1
+unsigned long
+SOAP_FMAC2
+soap_strtoul(const char *s, char **t, int b)
+{ unsigned long n = 0;
+  register int c;
+  while (*s > 0 && *s <= 32)
+    s++;
+  if (b == 10)
+  { if (*s == '+')
+      s++;
+    while ((c = *s) && c >= '0' && c <= '9')
+    { if (n >= 429496729 && (n > 429496729 || c >= '6'))
+        break;
+      n *= 10;
+      n += c - '0';
+      s++;
+    }
+  }
+  else /* b == 16 */
+  { while ((c = *s))
+    { if (c >= '0' && c <= '9')
+        c -= '0';
+      else if (c >= 'A' && c <= 'F')
+        c -= 'A' - 10;
+      else if (c >= 'a' && c <= 'f')
+        c -= 'a' - 10;
+      if (n > 0x0FFFFFFF)
+        break;
+      n <<= 4;
+      n += c;
+      s++;
+    }
+  }
+  if (t)
+    *t = (char*)s;
+  return n;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_array_begin_out(struct soap *soap, const char *tag, int id, const char *type, const char *offset)
+{ if (soap_element(soap, tag, id, "SOAP-ENC:Array"))
+    return soap->error;
+  if (soap->version == 2)
+  { const char *s;
+    s = soap_strrchr(type, '[');
+    if ((size_t)(s - type) < sizeof(soap->tmpbuf))
+    { strncpy(soap->tmpbuf, type, s - type);
+      soap->tmpbuf[s - type] = '\0';
+      if (type && *type && (soap_attribute(soap, "SOAP-ENC:itemType", soap->tmpbuf)))
+        return soap->error;
+      if (s && (soap_attribute(soap, "SOAP-ENC:arraySize", s + 1)))
+        return soap->error;
+    }
+  }
+  else
+  { if (offset && (soap_attribute(soap, "SOAP-ENC:offset", offset)))
+      return soap->error;
+    if (type && *type && (soap_attribute(soap, "SOAP-ENC:arrayType", type)))
+      return soap->error;
+  }
+#ifndef WITH_LEAN
+  if (type && *type && (soap->mode & SOAP_XML_CANONICAL))
+  { const char *s = strchr(type, ':');
+    if (s)
+      soap_utilize_ns(soap, type, s - type);
+  }
+#endif
+  return soap_element_start_end_out(soap, NULL);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_start_end_out(struct soap *soap, const char *tag)
+{ register struct soap_attribute *tp;
+#ifdef WITH_DOM
+  register struct soap_dom_attribute **att;
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { att = &soap->dom->atts;
+    for (tp = soap->attributes; tp; tp = tp->next)
+    { if (tp->visible)
+      { *att = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute));
+	if (!*att)
+	  return soap->error = SOAP_EOM;
+	(*att)->next = NULL;
+        (*att)->nstr = NULL;
+        (*att)->name = soap_strdup(soap, tp->name);
+        (*att)->data = soap_strdup(soap, tp->value);
+        (*att)->wide = NULL;
+        (*att)->soap = soap;
+        tp->visible = 0;
+      }
+    }
+    return SOAP_OK;
+  }
+#endif
+#ifndef WITH_LEAN
+  if (soap->mode & SOAP_XML_CANONICAL)
+  { struct soap_nlist *np;
+    for (tp = soap->attributes; tp; tp = tp->next)
+    { if (tp->visible && tp->name)
+      { const char *s = strchr(tp->name, ':');
+        if (s)
+          soap_utilize_ns(soap, tp->name, s - tp->name);
+      }
+    }
+    for (np = soap->nlist; np; np = np->next)
+    { if (np->index == 1 && np->ns)
+      { sprintf(soap->tmpbuf, "xmlns:%s", np->id);
+        soap_set_attr(soap, soap->tmpbuf, np->ns);
+        np->index = 2;
+      }
+    }
+  }
+#endif
+  for (tp = soap->attributes; tp; tp = tp->next)
+  { if (tp->visible)
+    { if (soap_send(soap, " ") || soap_send(soap, tp->name))
+        return soap->error;
+      if (tp->visible == 2 && tp->value)
+        if (soap_send_raw(soap, "=\"", 2)
+	 || soap_string_out(soap, tp->value, 1)
+	 || soap_send_raw(soap, "\"", 1))
+          return soap->error;
+      tp->visible = 0;
+    }
+  }
+  if (tag)
+  { 
+#ifndef WITH_LEAN
+    if (soap->mode & SOAP_XML_CANONICAL)
+    { if (soap_send_raw(soap, ">", 1)
+       || soap_element_end_out(soap, tag))
+        return soap->error;
+    }
+    else
+#endif
+    soap->level--;	/* decrement level just before /> */
+    if (soap_send_raw(soap, "/>", 2))
+      return soap->error;
+    return SOAP_OK;
+  }
+  return soap_send_raw(soap, ">", 1);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_end_out(struct soap *soap, const char *tag)
+{ if (*tag == '-')
+    return SOAP_OK;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element ending tag='%s'\n", tag));
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { if (soap->dom->prnt)
+      soap->dom = soap->dom->prnt;
+    return SOAP_OK;
+  }
+#endif
+#ifndef WITH_LEAN
+  if (soap->mode & SOAP_XML_CANONICAL)
+    soap_pop_ns(soap);
+  if (soap->mode & SOAP_XML_INDENT)
+  { if (!soap->body)
+    { if (soap_send_raw(soap, soap_indent, soap->level < sizeof(soap_indent) ? soap->level : sizeof(soap_indent) - 1))
+        return soap->error;
+    }
+    soap->body = 0;
+  }
+#endif
+  if (soap_send_raw(soap, "</", 2)
+   || soap_send(soap, tag))
+    return soap->error;
+  soap->level--;	/* decrement level just before > */
+  return soap_send_raw(soap, ">", 1);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_ref(struct soap *soap, const char *tag, int id, int href)
+{ register int n = 0;
+  if (soap->version == 2)
+    n = 1;
+  sprintf(soap->href, "#_%d", href);
+  return soap_element_href(soap, tag, id, "href" + n, soap->href + n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_href(struct soap *soap, const char *tag, int id, const char *ref, const char *val)
+{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element '%s' reference %s='%s'\n", tag, ref, val));
+  if (soap_element(soap, tag, id, NULL)
+   || soap_attribute(soap, ref, val)
+   || soap_element_start_end_out(soap, tag))
+    return soap->error;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_null(struct soap *soap, const char *tag, int id, const char *type)
+{ struct soap_attribute *tp;
+  for (tp = soap->attributes; tp; tp = tp->next)
+    if (tp->visible)
+      break;
+  if (tp || (soap->version == 2 && soap->position > 0) || id > 0 || (soap->mode & SOAP_XML_NIL))
+  { if (soap_element(soap, tag, id, type))
+      return soap->error;
+    if (soap->part != SOAP_IN_HEADER && soap->encodingStyle)
+      if (soap_attribute(soap, "xsi:nil", "true"))
+        return soap->error;
+    return soap_element_start_end_out(soap, tag);
+  }
+  soap->null = 1;
+  soap->position = 0;
+  soap->mustUnderstand = 0;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_id(struct soap *soap, const char *tag, int id, const void *p, const struct soap_array *a, int n, const char *type, int t) 
+{ if (!p || (a && !a->__ptr))
+  { soap_element_null(soap, tag, id, type);
+    return -1;
+  }
+#ifndef WITH_NOIDREF
+  if (soap->mode & SOAP_XML_TREE)
+    return 0;
+  if (id < 0)
+  { struct soap_plist *pp;
+    if (a)
+      id = soap_array_pointer_lookup(soap, p, a, n, t, &pp);
+    else
+      id = soap_pointer_lookup(soap, p, t, &pp);
+    if (id)
+    { if (soap_is_embedded(soap, pp))
+      { soap_element_ref(soap, tag, 0, id);
+        return -1;
+      }
+      if (soap_is_single(soap, pp))
+        return 0;
+      soap_set_embedded(soap, pp);
+    }
+  }
+  return id;
+#else
+  return 0;
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_result(struct soap *soap, const char *tag)
+{ if (soap->version == 2 && soap->encodingStyle)
+    if (soap_element(soap, "SOAP-RPC:result", 0, NULL)
+     || soap_attribute(soap, "xmlns:SOAP-RPC", soap_rpc)
+     || soap_element_start_end_out(soap, NULL)
+     || soap_string_out(soap, tag, 0)
+     || soap_element_end_out(soap, "SOAP-RPC:result"))
+      return soap->error;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_attribute(struct soap *soap, const char *name, const char *value)
+{ 
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { register struct soap_dom_attribute *a = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute));
+    a->next = soap->dom->atts;
+    a->nstr = NULL;
+    a->name = soap_strdup(soap, name);
+    a->data = soap_strdup(soap, value);
+    a->wide = NULL;
+    a->soap = soap;
+    soap->dom->atts = a;
+    return SOAP_OK;
+  }
+#endif
+#ifndef WITH_LEAN
+  if (soap->mode & SOAP_XML_CANONICAL)
+  { /* TODO: consider using this code to handle default namespace
+    if (!strncmp(name, "xmlns", 5) && (name[5] == ':' || name[5] == '\0'))
+    { if (name[5] == ':')
+        soap_push_ns(soap, name + 6, value, 0);
+      else
+        soap_push_ns(soap, "", value, 0);
+    }
+    */
+    if (!strncmp(name, "xmlns:", 6))
+      soap_push_ns(soap, name + 6, value, 0);
+    else if (soap_set_attr(soap, name, value))
+      return soap->error;
+  }
+  else
+#endif
+  { if (soap_send(soap, " ") || soap_send(soap, name))
+      return soap->error;
+    if (value)
+      if (soap_send_raw(soap, "=\"", 2)
+       || soap_string_out(soap, value, 1)
+       || soap_send_raw(soap, "\"", 1))
+        return soap->error;
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_begin_in(struct soap *soap, const char *tag, int nillable)
+{ if (!soap_peek_element(soap))
+  { if (soap->other)
+      return soap->error = SOAP_TAG_MISMATCH;
+    if (tag && *tag == '-')
+      return SOAP_OK;
+    if (!(soap->error = soap_match_tag(soap, soap->tag, tag)))
+    { soap->peeked = 0;
+      if (soap->body)
+        soap->level++;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag?tag:"" ));
+      if (!nillable && soap->null && (soap->mode & SOAP_XML_STRICT))
+        return soap->error = SOAP_NULL;
+    }
+  }
+  else if (soap->error == SOAP_NO_TAG && tag && *tag == '-')
+    soap->error = SOAP_OK;
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_element_end_in(struct soap *soap, const char *tag)  
+{ register soap_wchar c;
+  register char *s;
+  register const char *t;
+  register int n = 0;
+  if (tag && *tag == '-')
+    return SOAP_OK;
+  soap->level--;
+  soap_pop_namespace(soap);
+#ifdef WITH_DOM
+  /* this whitespace or mixed content is not insignificant for DOM */
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { if (!soap->peeked && !soap_string_in(soap, 3, -1, -1))
+      return soap->error;
+    if (soap->dom->prnt)
+      soap->dom = soap->dom->prnt;
+  }
+#endif
+  if (soap->peeked)
+  { if (soap->error == SOAP_NO_TAG)
+      soap->error = SOAP_OK;
+    if (*soap->tag)
+      n++;
+    soap->peeked = 0;
+  }
+  do
+  { while (((c = soap_get(soap)) != SOAP_TT))
+    { if ((int)c == EOF)
+        return soap->error = SOAP_EOF;
+      if (c == SOAP_LT)
+        n++;
+      else if (c == '/')
+      { c = soap_get(soap);
+        if (c == SOAP_GT)
+	  n--;
+        else
+	  soap_unget(soap, c);
+      }
+    }
+  } while (n--);
+  s = soap->tag;
+  while (soap_notblank(c = soap_getutf8(soap)))
+    *s++ = (char)c;
+  *s = '\0';
+  if ((int)c == EOF)
+    return soap->error = SOAP_EOF;
+  while (soap_blank(c))
+    c = soap_get(soap);
+  if (c != SOAP_GT)
+    return soap->error = SOAP_SYNTAX_ERROR;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag?tag:""));
+  if (!tag || !*tag)
+    return SOAP_OK;
+  if ((s = strchr(soap->tag, ':')))
+    s++;
+  else
+    s = soap->tag;
+  if ((t = strchr(tag, ':')))
+    t++;
+  else
+    t = tag;
+  if (!SOAP_STRCMP(s, t))
+    return SOAP_OK;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element tag name does not match\n"));
+  return soap->error = SOAP_SYNTAX_ERROR;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char *
+SOAP_FMAC2
+soap_attr_value(struct soap *soap, const char *name, int flag)
+{ register struct soap_attribute *tp;
+  for (tp = soap->attributes; tp; tp = tp->next)
+    if (!soap_match_tag(soap, tp->name, name))
+      break;
+  if (tp && tp->visible == 2)
+  { if (flag == 2 && (soap->mode & SOAP_XML_STRICT))
+      soap->error = SOAP_PROHIBITED;
+    else
+      return tp->value;
+  }
+  else if (flag == 1 && (soap->mode & SOAP_XML_STRICT))
+    soap->error = SOAP_REQUIRED;
+  return NULL;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_set_attr(struct soap *soap, const char *name, const char *value)
+{ register struct soap_attribute *tp;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set attribute %s='%s'\n", name, value?value:""));
+  for (tp = soap->attributes; tp; tp = tp->next)
+  { if (!strcmp(tp->name, name))
+      break;
+  }
+  if (!tp)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Allocate attribute %s\n", name));
+    if (!(tp = (struct soap_attribute*)SOAP_MALLOC(soap, sizeof(struct soap_attribute) + strlen(name))))
+      return soap->error = SOAP_EOM;
+    tp->ns = NULL;
+#ifndef WITH_LEAN
+    if (soap->mode & SOAP_XML_CANONICAL)
+    { struct soap_attribute **tpp = &soap->attributes;
+      const char *s = strchr(name, ':');
+      if (!strncmp(name, "xmlns", 5))
+      { for (; *tpp; tpp = &(*tpp)->next)
+          if (strncmp((*tpp)->name, "xmlns", 5) || strcmp((*tpp)->name + 5, name + 5) > 0)
+            break;
+      }
+      else if (!s)
+      { for (; *tpp; tpp = &(*tpp)->next)
+          if (strncmp((*tpp)->name, "xmlns", 5) && ((*tpp)->ns || strcmp((*tpp)->name, name) > 0))
+            break;
+      }
+      else
+      { int k;
+        for (; *tpp; tpp = &(*tpp)->next)
+	{ if (!strncmp((*tpp)->name, "xmlns:", 6) && !strncmp((*tpp)->name + 6, name, s - name) && !(*tpp)->name[6 + s - name])
+	  { if (!tp->ns)
+            { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Canonicalization: prefix %s=%p(%s)\n", name, (*tpp)->ns, (*tpp)->ns));
+	      tp->ns = (*tpp)->ns;
+	    }
+	  }
+          else if (strncmp((*tpp)->name, "xmlns", 5) && (*tpp)->ns && tp->ns && ((k = strcmp((*tpp)->ns, tp->ns)) > 0 || (!k && strcmp((*tpp)->name, name) > 0)))
+            break;
+        }
+      }
+      tp->next = *tpp;
+      *tpp = tp;
+    }
+    else
+#endif
+    { tp->next = soap->attributes;
+      soap->attributes = tp;
+    }
+    strcpy(tp->name, name);
+    tp->value = NULL;
+  }
+  else if (value && tp->value && tp->size <= strlen(value))
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Free attribute value of %s (free %p)\n", name, tp->value));
+    SOAP_FREE(soap, tp->value);
+    tp->value = NULL;
+    tp->ns = NULL;
+  }
+  if (value)
+  { if (!tp->value)
+    { tp->size = strlen(value) + 1;
+      if (!(tp->value = (char*)SOAP_MALLOC(soap, tp->size)))
+        return soap->error = SOAP_EOM;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Allocate attribute value of %s (%p)\n", tp->name, tp->value));
+    }
+    strcpy(tp->value, value);
+    if (!strncmp(tp->name, "xmlns:", 6))
+      tp->ns = tp->value;
+    tp->visible = 2;
+#ifndef WITH_LEAN
+    if (!strcmp(name, "wsu:Id"))
+    { soap->part = SOAP_BEGIN_SECURITY;
+      strncpy(soap->id, value, sizeof(soap->id));
+      soap->id[sizeof(soap->id)-1] = '\0';
+    }
+#endif
+  }
+  else
+    tp->visible = 1;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_clr_attr(struct soap *soap)
+{ register struct soap_attribute *tp;
+#ifndef WITH_LEAN
+  if (soap->mode & SOAP_XML_CANONICAL)
+  { while (soap->attributes)
+    { tp = soap->attributes->next;
+      SOAP_FREE(soap, soap->attributes->value);
+      SOAP_FREE(soap, soap->attributes);
+      soap->attributes = tp;
+    }
+  }
+  else
+#endif
+  { for (tp = soap->attributes; tp; tp = tp->next)
+      tp->visible = 0;
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+static int
+soap_getattrval(struct soap *soap, char *s, size_t n, soap_wchar d)
+{ size_t i;
+  soap_wchar c;
+  for (i = 0; i < n; i++)
+  { c = soap_getutf8(soap);
+    switch (c)
+    {
+    case SOAP_TT:
+      *s++ = '<';
+      soap_unget(soap, '/');
+      break;
+    case SOAP_LT:
+      *s++ = '<';
+      break;
+    case SOAP_GT:
+      if (d == ' ')
+      { soap_unget(soap, c);
+        *s = '\0';
+        return SOAP_OK;
+      }
+      *s++ = '>';
+      break;
+    case SOAP_QT:
+      if (c == d)
+      { *s = '\0';
+        return SOAP_OK;
+      }
+      *s++ = '"';
+      break;
+    case SOAP_AP:
+      if (c == d)
+      { *s = '\0';
+        return SOAP_OK;
+      }
+      *s++ = '\'';
+      break;
+    case '\t':
+    case '\n':
+    case '\r':
+    case ' ':
+    case '/':
+      if (d == ' ')
+      { soap_unget(soap, c);
+        *s = '\0';
+        return SOAP_OK;
+      }
+    default:
+      if ((int)c == EOF)
+        return soap->error = SOAP_EOF;
+      *s++ = (char)c;
+    }
+  }
+  return soap->error = SOAP_EOM;
+}
+#endif
+
+/******************************************************************************/
+#ifdef WITH_FAST
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_store_lab(struct soap *soap, const char *s, size_t n)
+{ soap->labidx = 0;
+  return soap_append_lab(soap, s, n);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifdef WITH_FAST
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_append_lab(struct soap *soap, const char *s, size_t n)
+{ if (soap->labidx + n >= soap->lablen)
+  { register char *t = soap->labbuf;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Enlarging look-aside buffer to append data, old size=%lu", (unsigned long)soap->lablen));
+    if (soap->lablen == 0)
+      soap->lablen = SOAP_LABLEN;
+    while (soap->labidx + n >= soap->lablen)
+      soap->lablen <<= 1;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, ", new size=%lu\n", (unsigned long)soap->lablen));
+    soap->labbuf = (char*)SOAP_MALLOC(soap, soap->lablen);
+    if (!soap->labbuf)
+    { if (t)
+        SOAP_FREE(soap, t);
+      return soap->error = SOAP_EOM;
+    }
+    if (t)
+    { memcpy(soap->labbuf, t, soap->labidx);
+      SOAP_FREE(soap, t);
+    }
+  }
+  if (s)
+  { memcpy(soap->labbuf + soap->labidx, s, n);
+    soap->labidx += n;
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_peek_element(struct soap *soap)
+{
+#ifdef WITH_DOM
+  register struct soap_dom_attribute **att = NULL;
+  register char *lead = NULL;
+#endif
+  register struct soap_attribute *tp;
+  const char *t;
+  register char *s;
+  register soap_wchar c;
+  register int i;
+  if (soap->peeked)
+  { if (!*soap->tag)
+      return soap->error = SOAP_NO_TAG;
+    return SOAP_OK;
+  }
+  soap->peeked = 1;
+  for (;;)
+  { c = soap_getutf8(soap);
+    if (c == SOAP_BOM)
+      c = soap_get(soap);
+#ifdef WITH_DOM
+    /* whitespace leading to start tag is not insignificant for DOM */
+    if (soap_blank(c))
+    { soap->labidx = 0;
+      do
+      { if (soap_append_lab(soap, NULL, 0))
+          return SOAP_EOM;
+        s = soap->labbuf + soap->labidx;
+        i = soap->lablen - soap->labidx;
+        soap->labidx = soap->lablen;
+        while (soap_blank(c) && i--)
+	{ *s++ = c;
+	  c = soap_get(soap);
+	}
+      }
+      while (soap_blank(c));
+      *s = '\0';
+      lead = soap_strdup(soap, soap->labbuf);
+    }
+#else
+    while (soap_blank(c))
+      c = soap_get(soap);
+#endif
+    if (c != SOAP_LT)
+    { *soap->tag = '\0';
+      if ((int)c == EOF)
+        return soap->error = SOAP_EOF;
+      soap_unget(soap, c);
+#ifdef WITH_DOM
+      /* whitespace leading to end tag is not insignificant for DOM */
+      if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+        soap->dom->tail = soap_strdup(soap, lead);
+#endif
+      return soap->error = SOAP_NO_TAG;
+    }
+    s = soap->tag;
+    do c = soap_getutf8(soap);
+    while (soap_blank(c));
+    i = sizeof(soap->tag);
+    while (c != '/' && soap_notblank(c))
+    { if (--i > 0)
+        *s++ = (char)c;
+      c = soap_getutf8(soap);
+    }
+    while (soap_blank(c))
+      c = soap_get(soap);
+    *s = '\0';
+    if (*soap->tag != '?')
+      break;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "XML PI <%s?>\n", soap->tag));
+    while ((int)c != EOF && c != SOAP_GT && c != '?')
+    { s = soap->tmpbuf;
+      i = sizeof(soap->tmpbuf) - 2;
+      while (c != '=' && c != SOAP_GT && c != '?' && soap_notblank(c))
+      { if (--i > 0)
+          *s++ = (char)c;
+        c = soap_get(soap);
+      }
+      while (soap_blank(c))
+        c = soap_get(soap);
+      if (c == '=')
+      { *s++ = '=';
+	do c = soap_get(soap);
+        while (soap_blank(c));
+        if (c != SOAP_QT && c != SOAP_AP)
+        { soap_unget(soap, c);
+          c = ' '; /* blank delimiter */
+        }
+        if (soap_getattrval(soap, s, i, c) == SOAP_EOM)
+	{ while (soap_getattrval(soap, soap->tmpbuf, sizeof(soap->tmpbuf), c) == SOAP_EOM)
+	    ;
+	}
+        else if (!strcmp(soap->tag, "?xml")
+	      && (!soap_tag_cmp(soap->tmpbuf, "encoding=iso-8859-1")
+	       || !soap_tag_cmp(soap->tmpbuf, "encoding=latin1")))
+        { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "XML latin1 encoding\n"));
+          soap->mode |= SOAP_ENC_LATIN;
+        }
+      }
+      do c = soap_get(soap);
+      while (soap_blank(c));
+    }
+  }
+  soap->id[0] = '\0';
+  soap->href[0] = '\0';
+  soap->type[0] = '\0';
+  soap->arrayType[0] = '\0';
+  soap->arraySize[0] = '\0';
+  soap->arrayOffset[0] = '\0';
+  soap->other = 0;
+  soap->root = -1;
+  soap->position = 0;
+  soap->null = 0;
+  soap->mustUnderstand = 0;
+#ifdef WITH_DOM
+  if (soap->mode & SOAP_XML_DOM)
+  { register struct soap_dom_element *elt;
+    elt = (struct soap_dom_element*)soap_malloc(soap, sizeof(struct soap_dom_element));
+    if (!elt)
+      return soap->error = SOAP_EOM;
+    elt->next = NULL;
+    elt->nstr = NULL;
+    elt->name = soap_strdup(soap, soap->tag);
+    elt->prnt = soap->dom;
+    elt->elts = NULL;
+    elt->atts = NULL;
+    elt->data = NULL;
+    elt->wide = NULL;
+    elt->type = 0;
+    elt->node = NULL;
+    elt->head = lead;
+    elt->tail = NULL;
+    elt->soap = soap;
+    if (soap->dom)
+    { struct soap_dom_element *p = soap->dom->elts;
+      if (p)
+      { while (p->next)
+          p = p->next;
+        p->next = elt;
+      }
+      else
+        soap->dom->elts = elt;
+    }
+    soap->dom = elt;
+    att = &elt->atts;
+  }
+#endif
+  for (tp = soap->attributes; tp; tp = tp->next)
+    tp->visible = 0;
+  while ((int)c != EOF && c != SOAP_GT && c != '/')
+  { s = soap->tmpbuf;
+    i = sizeof(soap->tmpbuf);
+    while (c != '=' && c != '/' && soap_notblank(c))
+    { if (--i > 0)
+        *s++ = (char)c;
+      c = soap_get(soap);
+    }
+    *s = '\0';
+    if (i == sizeof(soap->tmpbuf))
+      return soap->error = SOAP_SYNTAX_ERROR;
+#ifdef WITH_DOM
+    /* add attribute name to dom */
+    if (att)
+    { *att = (struct soap_dom_attribute*)soap_malloc(soap, sizeof(struct soap_dom_attribute));
+       if (!*att)
+         return soap->error = SOAP_EOM;
+       (*att)->next = NULL;
+       (*att)->nstr = NULL;
+       (*att)->name = soap_strdup(soap, soap->tmpbuf);
+       (*att)->data = NULL;
+       (*att)->wide = NULL;
+       (*att)->soap = soap;
+    }
+#endif
+    if (!strncmp(soap->tmpbuf, "xmlns", 5))
+    { if (soap->tmpbuf[5] == ':')
+      { soap->tmpbuf[5] = '\0';
+        t = soap->tmpbuf + 6;
+      }
+      else if (soap->tmpbuf[5])
+        t = NULL;
+      else
+        t = SOAP_STR_EOS;
+    }
+    else
+      t = NULL;
+    for (tp = soap->attributes; tp; tp = tp->next)
+    { if (!SOAP_STRCMP(tp->name, soap->tmpbuf))
+        break;
+    }
+    if (!tp)
+    { tp = (struct soap_attribute*)SOAP_MALLOC(soap, sizeof(struct soap_attribute) + strlen(soap->tmpbuf));
+      if (!tp)
+        return soap->error = SOAP_EOM;
+      strcpy(tp->name, soap->tmpbuf);
+      tp->value = NULL;
+      tp->size = 0;
+      tp->next = soap->attributes;
+      soap->attributes = tp;
+    }
+    while (soap_blank(c))
+      c = soap_get(soap);
+    if (c == '=')
+    { do c = soap_get(soap);
+      while (soap_blank(c));
+      if (c != SOAP_QT && c != SOAP_AP)
+      { soap_unget(soap, c);
+        c = ' '; /* blank delimiter */
+      }
+      if (soap_getattrval(soap, tp->value, tp->size, c))
+      {
+#ifdef WITH_FAST
+        if (soap->error != SOAP_EOM)
+          return soap->error;
+        soap->error = SOAP_OK;
+	if (soap_store_lab(soap, tp->value, tp->size))
+	  return soap->error;
+	if (tp->value)
+	  SOAP_FREE(soap, tp->value);
+	for (;;)
+	{ if (soap_getattrval(soap, soap->labbuf + soap->labidx, soap->lablen - soap->labidx, c))
+	  { if (soap->error != SOAP_EOM)
+	      return soap->error;
+            soap->error = SOAP_OK;
+	    soap->labidx = soap->lablen;
+	    if (soap_append_lab(soap, NULL, 0))
+	      return soap->error;
+	  }
+	  else
+	    break;
+	}
+	if (soap->labidx)
+          tp->size = soap->lablen;
+	else
+	{ tp->size = strlen(soap->labbuf) + 1;
+          if (tp->size < SOAP_LABLEN)
+	    tp->size = SOAP_LABLEN;
+        }
+	if (!(tp->value = (char*)SOAP_MALLOC(soap, tp->size)))
+	  return soap->error = SOAP_EOM;
+        strcpy(tp->value, soap->labbuf);
+#else
+	size_t n;
+        if (soap->error != SOAP_EOM)
+          return soap->error;
+        soap->error = SOAP_OK;
+        if (soap_new_block(soap))
+          return soap->error;
+        for (;;)
+        { if (!(s = (char*)soap_push_block(soap, SOAP_BLKLEN)))
+            return soap->error;
+          if (soap_getattrval(soap, s, SOAP_BLKLEN, c))
+          { if (soap->error != SOAP_EOM)
+              return soap->error;
+            soap->error = SOAP_OK;
+          }
+          else
+            break;
+        }
+	n = tp->size + soap->blist->size;
+        if (!(s = (char*)SOAP_MALLOC(soap, n)))
+          return soap->error = SOAP_EOM;
+        if (tp->value)
+        { memcpy(s, tp->value, tp->size);
+          SOAP_FREE(soap, tp->value);
+        }
+        soap_save_block(soap, s + tp->size, 0);
+        tp->value = s;
+        tp->size = n;
+#endif
+      }
+      do c = soap_get(soap);
+      while (soap_blank(c));
+      tp->visible = 2; /* seen this attribute w/ value */
+#ifdef WITH_DOM
+      if (att)
+        (*att)->data = soap_strdup(soap, tp->value);
+#endif
+    }
+    else
+      tp->visible = 1; /* seen this attribute w/o value */
+#ifdef WITH_DOM
+    if (att)
+      att = &(*att)->next;
+#endif
+    if (t && tp->value)
+    { if (soap_push_namespace(soap, t, tp->value))
+        return soap->error;
+      tp->visible = 0;
+    }
+  }
+#ifdef WITH_DOM
+  if (att)
+  { soap->dom->nstr = soap_dom_current_nstr(soap, soap->tag);
+    for (att = &soap->dom->atts; *att; att = &(*att)->next)
+      (*att)->nstr = soap_dom_current_nstr(soap, (*att)->name);
+  }
+#endif
+  if ((int)c == EOF)
+    return soap->error = SOAP_EOF;
+  if (!(soap->body = (c != '/')))
+    do c = soap_get(soap);
+    while (soap_blank(c));
+#ifdef WITH_DOM
+  if (soap->mode & SOAP_XML_DOM)
+  { if (!soap->body && soap->dom->prnt)
+      soap->dom = soap->dom->prnt;
+  }
+#endif
+  for (tp = soap->attributes; tp; tp = tp->next)
+  { if (tp->visible && tp->value)
+    { if (!strcmp(tp->name, "id"))
+      { *soap->id = '#';
+        strncpy(soap->id + 1, tp->value, sizeof(soap->id) - 2);
+        soap->id[sizeof(soap->id)-1] = '\0';
+      }
+      else if (!strcmp(tp->name, "href"))
+      { strncpy(soap->href, tp->value, sizeof(soap->href) - 1);
+        soap->href[sizeof(soap->href)-1] = '\0';
+      }
+      else if ((soap->version == 2 || (soap->mode & SOAP_XML_GRAPH)) && !strcmp(tp->name, "ref"))
+      { *soap->href = '#';
+        strncpy(soap->href + 1, tp->value, sizeof(soap->href) - 2);
+        soap->href[sizeof(soap->href)-1] = '\0';
+      }
+      else if (!soap_match_tag(soap, tp->name, "xsi:type"))
+      { strncpy(soap->type, tp->value, sizeof(soap->type) - 1);
+        soap->type[sizeof(soap->type)-1] = '\0';
+      }
+      else if (soap->version == 1 && !soap_match_tag(soap, tp->name, "SOAP-ENC:arrayType"))
+      { s = soap_strrchr(tp->value, '[');
+        if (s && (size_t)(s - tp->value) < sizeof(soap->arrayType))
+        { strncpy(soap->arrayType, tp->value, s - tp->value);
+          soap->arrayType[s - tp->value] = '\0';
+          strncpy(soap->arraySize, s, sizeof(soap->arraySize) - 1);
+        }
+        else
+          strncpy(soap->arrayType, tp->value, sizeof(soap->arrayType) - 1);
+        soap->arraySize[sizeof(soap->arrayType)-1] = '\0';
+        soap->arrayType[sizeof(soap->arrayType)-1] = '\0';
+      }
+      else if (soap->version == 2 && !soap_match_tag(soap, tp->name, "SOAP-ENC:itemType"))
+        strncpy(soap->arrayType, tp->value, sizeof(soap->arrayType) - 1);
+      else if (soap->version == 2 && !soap_match_tag(soap, tp->name, "SOAP-ENC:arraySize"))
+        strncpy(soap->arraySize, tp->value, sizeof(soap->arraySize) - 1);
+      else if (soap->version == 1 && !soap_match_tag(soap, tp->name, "SOAP-ENC:offset"))
+        strncpy(soap->arrayOffset, tp->value, sizeof(soap->arrayOffset));
+      else if (soap->version == 1 && !soap_match_tag(soap, tp->name, "SOAP-ENC:position"))
+        soap->position = soap_getposition(tp->value, soap->positions);
+      else if (soap->version == 1 && !soap_match_tag(soap, tp->name, "SOAP-ENC:root"))
+        soap->root = ((!strcmp(tp->value, "1") || !strcmp(tp->value, "true")));
+      else if ((soap->version == 1 && !soap_match_tag(soap, tp->name, "SOAP-ENV:actor"))
+            || (soap->version == 2 && !soap_match_tag(soap, tp->name, "SOAP-ENV:role")))
+      { if ((!soap->actor || strcmp(soap->actor, tp->value))
+         && strcmp(tp->value, "http://schemas.xmlsoap.org/soap/actor/next")
+         && strcmp(tp->value, "http://www.w3.org/2003/05/soap-envelope/role/next"))
+          soap->other = 1;
+      }
+      else if (!soap_match_tag(soap, tp->name, "SOAP-ENV:mustUnderstand")
+            && (!strcmp(tp->value, "1") || !strcmp(tp->value, "true")))
+        soap->mustUnderstand = 1;
+      else if ((!soap_match_tag(soap, tp->name, "xsi:null")
+             || !soap_match_tag(soap, tp->name, "xsi:nil"))
+            && (!strcmp(tp->value, "1")
+             || !strcmp(tp->value, "true")))
+        soap->null = 1;
+    }
+  }
+  return soap->error = SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_retry(struct soap *soap)
+{ soap->error = SOAP_OK;
+  soap_revert(soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_revert(struct soap *soap)
+{ if (!soap->peeked)
+  { soap->peeked = 1;
+    if (soap->body)
+      soap->level--;
+  }
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Reverting last element (level=%u)\n", soap->level));
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_string_out(struct soap *soap, const char *s, int flag)
+{ register const char *t;
+  register soap_wchar c;
+  register soap_wchar mask = 0xFFFFFF80UL;
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { soap->dom->data = soap_strdup(soap, s);
+    return SOAP_OK;
+  }
+#endif
+  if (soap->mode & SOAP_C_UTFSTRING)
+    mask = 0;
+  t = s;
+  while ((c = *t++))
+  { switch (c)
+    { 
+    case 9:
+      if (flag)
+      { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&#x9;", 5))
+	  return soap->error;
+        s = t;
+      }
+      break;
+    case 10:
+      if (flag || !(soap->mode & SOAP_XML_CANONICAL))
+      { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&#xA;", 5))
+	  return soap->error;
+        s = t;
+      }
+      break;
+    case 13:
+      if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&#xD;", 5))
+        return soap->error;
+      s = t;
+      break;
+    case '&':
+      if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&amp;", 5))
+        return soap->error;
+      s = t;
+      break;
+    case '<':
+      if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&lt;", 4))
+        return soap->error;
+      s = t;
+      break;
+    case '>':
+      if (!flag)
+      { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&gt;", 4))
+	  return soap->error;
+        s = t;
+      }
+      break;
+    case '"':
+      if (flag)
+      { if (soap_send_raw(soap, s, t - s - 1) || soap_send_raw(soap, "&quot;", 6))
+	  return soap->error;
+        s = t;
+      }
+      break;
+    default:
+#ifndef WITH_LEANER
+#ifdef HAVE_MBTOWC
+      if (soap->mode & SOAP_C_MBSTRING)
+      { wchar_t wc;
+        register int m = mbtowc(&wc, t - 1, MB_CUR_MAX);
+        if (m > 0 && wc != c)
+        { if (soap_send_raw(soap, s, t - s - 1) || soap_pututf8(soap, wc))
+            return soap->error;
+	  s = t += m - 1;
+	  continue;
+        }
+      }
+#endif
+#endif
+      if (c & mask)
+      { if (soap_send_raw(soap, s, t - s - 1) || soap_pututf8(soap, (unsigned char)c))
+          return soap->error;
+        s = t;
+      }
+    }
+  }
+  return soap_send_raw(soap, s, t - s - 1);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_string_in(struct soap *soap, int flag, long minlen, long maxlen)
+{ register char *s;
+  char *t = NULL;
+  register size_t i;
+  register long l = 0;
+  register int n = 0;
+  register int m = 0;
+  register soap_wchar c;
+#if !defined(WITH_LEANER) && defined(HAVE_WCTOMB)
+  char buf[MB_LEN_MAX > 8 ? MB_LEN_MAX : 8];
+#else
+  char buf[8];
+#endif
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Reading string content\n"));
+  if (soap->peeked)
+  { if (!soap->body)
+      return NULL;
+    if (*soap->tag)
+    { n = 1;
+      soap->peeked = 0;
+#ifndef WITH_LEAN
+      t = soap->tmpbuf;
+      t[0] = '<';
+      strncpy(t + 1, soap->tag, sizeof(soap->tmpbuf) - 1);
+      strncat(t, ">", sizeof(soap->tmpbuf));
+      m = strlen(soap->tag) + 2;
+#endif
+    }
+  }
+#ifdef WITH_CDATA
+  if (!flag)
+  { register int state = 0;
+#ifdef WITH_FAST
+    soap->labidx = 0;			/* use look-aside buffer */
+#else
+    if (soap_new_block(soap))
+      return NULL;
+#endif
+    for (;;)
+    { 
+#ifdef WITH_FAST
+      register size_t k;
+      if (soap_append_lab(soap, NULL, 0))	/* allocate more space in look-aside buffer if necessary */
+        return NULL;
+      s = soap->labbuf + soap->labidx;	/* space to populate */
+      k = soap->lablen - soap->labidx;	/* number of bytes available */
+      soap->labidx = soap->lablen;	/* claim this space */
+#else
+      register size_t k = SOAP_BLKLEN;
+      if (!(s = (char*)soap_push_block(soap, k)))
+        return NULL;
+#endif
+      for (i = 0; i < k; i++)
+      { if (m > 0)
+        { *s++ = *t++;	/* copy multibyte characters */
+	  m--;
+          continue;
+        }
+        c = soap_getchar(soap);
+	if ((int)c == EOF)
+          goto end;
+        if (c >= 0x80 && !(soap->mode & SOAP_ENC_LATIN))
+        { soap_unget(soap, c);
+	  c = soap_getutf8(soap);
+	  if (soap->mode & SOAP_C_UTFSTRING)
+          { if ((c & 0x80000000) && c >= -0x7FFFFF80 && c < SOAP_AP)
+            { c &= 0x7FFFFFFF;
+              t = buf;
+              if (c < 0x0800)
+                *t++ = (char)(0xC0 | ((c >> 6) & 0x1F));
+              else
+              { if (c < 0x010000)
+                  *t++ = (char)(0xE0 | ((c >> 12) & 0x0F));
+                else
+                { if (c < 0x200000)
+                    *t++ = (char)(0xF0 | ((c >> 18) & 0x07));
+                  else
+                  { if (c < 0x04000000)
+                      *t++ = (char)(0xF8 | ((c >> 24) & 0x03));
+                    else
+                    { *t++ = (char)(0xFC | ((c >> 30) & 0x01));
+                      *t++ = (char)(0x80 | ((c >> 24) & 0x3F));
+                    }
+                    *t++ = (char)(0x80 | ((c >> 18) & 0x3F));
+                  }     
+                  *t++ = (char)(0x80 | ((c >> 12) & 0x3F));
+                }
+                *t++ = (char)(0x80 | ((c >> 6) & 0x3F));
+              }
+              *t++ = (char)(0x80 | (c & 0x3F));
+	      m = (int)(t - buf) - 1;
+              t = buf;
+              *s++ = *t++;
+              continue;
+	    }
+          }
+        }
+	switch (state)
+        { case 1:
+            if (c == ']')
+	      state = 4;
+	    *s++ = c;
+	    continue;
+	  case 2:
+	    if (c == '-')
+              state = 6;
+	    *s++ = c;
+	    continue;
+	  case 3:
+	    if (c == '?')
+	      state = 8;
+	    *s++ = c;
+	    continue;
+          /* CDATA */
+	  case 4:
+	    if (c == ']')
+              state = 5;
+	    else
+	      state = 1;
+	    *s++ = c;
+	    continue;
+	  case 5:
+	    if (c == '>')
+	      state = 0;
+	    else
+	      state = 1;
+	    *s++ = c;
+	    continue;
+          /* comment */
+          case 6:
+            if (c == '-')
+	      state = 7;
+	    else
+	      state = 2;
+	    *s++ = c;
+	    continue;
+          case 7:
+            if (c == '>')
+	      state = 0;
+	    else
+	      state = 2;
+	    *s++ = c;
+	    continue;
+          /* PI */
+	  case 8:
+            if (c == '>')
+	      state = 0;
+	    else
+	      state = 3;
+	    *s++ = c;
+	    continue;
+        }
+        switch (c)
+        {
+        case '/':
+          if (n > 0)
+          { c = soap_getchar(soap);
+            if (c == '>')
+              n--;
+            soap_unget(soap, c);
+          }
+          *s++ = '/';
+          break;
+        case '<':
+	  c = soap_getchar(soap);
+	  if (c == '/')
+	  { if (n == 0)
+	    { c = SOAP_TT;
+	      goto end;
+	    }
+	    n--;
+	  }
+	  else if (c == '!')
+	  { c = soap_getchar(soap);
+	    if (c == '[')
+            { do c = soap_getchar(soap);
+              while ((int)c != EOF && c != '[');
+              if ((int)c == EOF)
+                 goto end;
+	      t = (char*)"![CDATA[";
+	      m = 8;
+	      state = 1;
+	    }
+            else if (c == '-')
+	    { if ((c = soap_getchar(soap)) == '-')
+	        state = 2;
+	      t = (char*)"!-";
+	      m = 2;
+	      soap_unget(soap, c);
+	    }
+	    else
+	    { t = (char*)"!";
+	      m = 1;
+	      soap_unget(soap, c);
+	    }
+	    *s++ = '<';
+	    break;
+	  }
+	  else if (c == '?')
+	    state = 3;
+	  else
+	    n++;
+          soap_unget(soap, c);
+          *s++ = '<';
+          break;
+        case '>':
+          *s++ = '>';
+          break;
+        case '"':
+          *s++ = '"';
+          break;
+        default:
+#ifndef WITH_LEANER
+#ifdef HAVE_WCTOMB
+          if (soap->mode & SOAP_C_MBSTRING)
+          { m = wctomb(buf, c & 0x7FFFFFFF);
+            if (m >= 1 && m <= (int)MB_CUR_MAX)
+            { t = buf;
+              *s++ = *t++;
+              m--;
+            }
+            else
+            { *s++ = SOAP_UNKNOWN_CHAR;
+	      m = 0;
+	    }
+          }
+          else
+#endif
+#endif
+            *s++ = (char)(c & 0xFF);
+        }
+	l++;
+        if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen)
+        { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen));
+          soap->error = SOAP_LENGTH;
+          return NULL;
+        }
+      }
+    }
+  }
+#endif
+#ifdef WITH_FAST
+  soap->labidx = 0;			/* use look-aside buffer */
+#else
+  if (soap_new_block(soap))
+    return NULL;
+#endif
+  for (;;)
+  { 
+#ifdef WITH_FAST
+    register size_t k;
+    if (soap_append_lab(soap, NULL, 0))	/* allocate more space in look-aside buffer if necessary */
+      return NULL;
+    s = soap->labbuf + soap->labidx;	/* space to populate */
+    k = soap->lablen - soap->labidx;	/* number of bytes available */
+    soap->labidx = soap->lablen;	/* claim this space */
+#else
+    register size_t k = SOAP_BLKLEN;
+    if (!(s = (char*)soap_push_block(soap, k)))
+      return NULL;
+#endif
+    for (i = 0; i < k; i++)
+    { if (m > 0)
+      { *s++ = *t++;	/* copy multibyte characters */
+        m--;
+        continue;
+      }
+      if (soap->mode & SOAP_C_UTFSTRING)
+      { if (((c = soap_get(soap)) & 0x80000000) && c >= -0x7FFFFF80 && c < SOAP_AP)
+        { c &= 0x7FFFFFFF;
+          t = buf;
+          if (c < 0x0800)
+            *t++ = (char)(0xC0 | ((c >> 6) & 0x1F));
+          else
+          { if (c < 0x010000)
+              *t++ = (char)(0xE0 | ((c >> 12) & 0x0F));
+            else
+            { if (c < 0x200000)
+                *t++ = (char)(0xF0 | ((c >> 18) & 0x07));
+              else
+              { if (c < 0x04000000)
+                  *t++ = (char)(0xF8 | ((c >> 24) & 0x03));
+                else
+                { *t++ = (char)(0xFC | ((c >> 30) & 0x01));
+                  *t++ = (char)(0x80 | ((c >> 24) & 0x3F));
+                }
+                *t++ = (char)(0x80 | ((c >> 18) & 0x3F));
+              }     
+              *t++ = (char)(0x80 | ((c >> 12) & 0x3F));
+            }
+            *t++ = (char)(0x80 | ((c >> 6) & 0x3F));
+          }
+          *t++ = (char)(0x80 | (c & 0x3F));
+	  m = (int)(t - buf) - 1;
+          t = buf;
+          *s++ = *t++;
+          continue;
+        }
+      }
+      else
+        c = soap_getutf8(soap);
+      switch (c)
+      {
+      case SOAP_TT:
+        if (n == 0)
+          goto end;
+        n--;
+        *s++ = '<';
+        t = (char*)"/";
+	m = 1;
+        break;
+      case SOAP_LT:
+        n++;
+        *s++ = '<';
+        break;
+      case SOAP_GT:
+        *s++ = '>';
+        break;
+      case SOAP_QT:
+        *s++ = '"';
+        break;
+      case SOAP_AP:
+        *s++ = '\'';
+        break;
+      case '/':
+        if (n > 0)
+        { c = soap_get(soap);
+          if (c == SOAP_GT)
+            n--;
+          soap_unget(soap, c);
+        }
+        *s++ = '/';
+        break;
+      case '<' | 0x80000000:
+        if (flag)
+          *s++ = '<';
+        else
+        { *s++ = '&';
+          t = (char*)"lt;";
+	  m = 3;
+        }
+        break;
+      case '>' | 0x80000000:
+        if (flag)
+          *s++ = '>';
+        else
+        { *s++ = '&';
+          t = (char*)"gt;";
+	  m = 3;
+        }
+        break;
+      case '&' | 0x80000000:
+        if (flag)
+          *s++ = '&';
+        else
+        { *s++ = '&';
+          t = (char*)"amp;";
+	  m = 4;
+        }
+        break;
+      case '"' | 0x80000000:
+        if (flag)
+          *s++ = '"';
+        else
+        { *s++ = '&';
+          t = (char*)"quot;";
+	  m = 5;
+        }
+        break;
+      case '\'' | 0x80000000:
+        if (flag)
+          *s++ = '\'';
+        else
+        { *s++ = '&';
+          t = (char*)"apos;";
+	  m = 5;
+        }
+        break;
+      default:
+        if ((int)c == EOF)
+          goto end;
+#ifndef WITH_LEANER
+#ifdef HAVE_WCTOMB
+        if (soap->mode & SOAP_C_MBSTRING)
+        { m = wctomb(buf, c & 0x7FFFFFFF);
+          if (m >= 1 && m <= (int)MB_CUR_MAX)
+          { t = buf;
+            *s++ = *t++;
+            m--;
+          }
+          else
+          { *s++ = SOAP_UNKNOWN_CHAR;
+	    m = 0;
+	  }
+        }
+        else
+#endif
+#endif
+          *s++ = (char)(c & 0xFF);
+      }
+      l++;
+      if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen)
+      { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen));
+        soap->error = SOAP_LENGTH;
+        return NULL;
+      }
+    }
+  }
+end:
+  soap_unget(soap, c);
+  *s = '\0';
+#ifdef WITH_FAST
+  t = soap_strdup(soap, soap->labbuf);
+#else
+  soap_size_block(soap, i+1);
+  t = soap_save_block(soap, NULL, 0);
+#endif
+  if ((soap->mode & SOAP_XML_STRICT) && l < minlen)
+  { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too short: %ld chars, minlen=%ld\n", l, minlen));
+    soap->error = SOAP_LENGTH;
+    return NULL;
+  }
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { if (flag == 3)
+      soap->dom->tail = t;
+    else
+      soap->dom->data = t;
+  }
+#endif
+  if (flag == 2)
+    if (soap_s2QName(soap, t, &t))
+      return NULL;
+  return t;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_wstring_out(struct soap *soap, const wchar_t *s, int flag)
+{ const char *t;
+  char tmp;
+  register soap_wchar c;
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+  { wchar_t *r = (wchar_t*)s;
+    int n = 1;
+    while (*r++)
+      n++;
+    soap->dom->wide = r = (wchar_t*)soap_malloc(soap, n * sizeof(wchar_t));
+    while (n--)
+      *r++ = *s++;
+    return SOAP_OK;
+  }
+#endif
+  while ((c = *s++))
+  { switch (c)
+    { 
+    case 9:
+      if (flag)
+        t = "&#x9;";
+      else
+        t = "\t";
+      break;
+    case 10:
+      if (flag || !(soap->mode & SOAP_XML_CANONICAL))
+        t = "&#xA;";
+      else
+        t = "\n";
+      break;
+    case 13:
+      t = "&#xD;";
+      break;
+    case '&':
+      t = "&amp;";
+      break;
+    case '<':
+      t = "&lt;";
+      break;
+    case '>':
+      if (flag)
+        t = ">";
+      else
+	t = "&gt;";
+      break;
+    case '"':
+      if (flag)
+        t = "&quot;";
+      else
+        t = "\"";
+      break;
+    default:
+      if (c > 0 && c < 0x80)
+      { tmp = (char)c;
+        if (soap_send_raw(soap, &tmp, 1))
+          return soap->error;
+      }
+      else if (soap_pututf8(soap, (unsigned long)c))
+        return soap->error;
+      continue;
+    }
+    if (soap_send(soap, t))
+      return soap->error;
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_2
+SOAP_FMAC1
+wchar_t *
+SOAP_FMAC2
+soap_wstring_in(struct soap *soap, int flag, long minlen, long maxlen)
+{ wchar_t *s;
+  register int i, n = 0;
+  register long l = 0;
+  register soap_wchar c;
+  const char *t = NULL;
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Reading wide string content\n"));
+  if (soap->peeked)
+  { if (!soap->body)
+      return NULL;
+    if (*soap->tag)
+    { n = 1;
+      soap->peeked = 0;
+    }
+  }
+  if (soap_new_block(soap))
+    return NULL;
+  for (;;)
+  { if (!(s = (wchar_t*)soap_push_block(soap, sizeof(wchar_t)*SOAP_BLKLEN)))
+      return NULL;
+    for (i = 0; i < SOAP_BLKLEN; i++)
+    { if (t)
+      { *s++ = (wchar_t)*t++;
+        if (!*t)
+          t = NULL;
+        continue;
+      }
+      c = soap_getutf8(soap);
+      switch (c)
+      {
+      case SOAP_TT:
+        if (n == 0)
+          goto end;
+        n--;
+        *s++ = '<';
+        soap_unget(soap, '/');
+        break;
+      case SOAP_LT:
+        n++;
+        *s++ = '<';
+        break;
+      case SOAP_GT:
+        *s++ = '>';
+        break;
+      case SOAP_QT:
+        *s++ = '"';
+        break;
+      case SOAP_AP:
+        *s++ = '\'';
+        break;
+      case '/':
+        if (n > 0)
+        { c = soap_getutf8(soap);
+          if (c == SOAP_GT)
+            n--;
+          soap_unget(soap, c);
+        }
+        *s++ = '/';
+        break;
+      case '<':
+        if (flag)
+          *s++ = (soap_wchar)'<';
+        else
+        { *s++ = (soap_wchar)'&';
+          t = "lt;";
+        }
+        break;
+      case '>':
+        if (flag)
+          *s++ = (soap_wchar)'>';
+        else
+        { *s++ = (soap_wchar)'&';
+          t = "gt;";
+        }
+        break;
+      case '"':
+        if (flag)
+          *s++ = (soap_wchar)'"';
+        else
+        { *s++ = (soap_wchar)'&';
+          t = "quot;";
+        }
+        break;
+      default:
+        if ((int)c == EOF)
+          goto end;
+        *s++ = (wchar_t)c & 0x7FFFFFFF;
+      }
+      l++;
+      if ((soap->mode & SOAP_XML_STRICT) && maxlen >= 0 && l > maxlen)
+      { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too long: maxlen=%ld\n", maxlen));
+        soap->error = SOAP_LENGTH;
+        return NULL;
+      }
+    }
+  }
+end:
+  soap_unget(soap, c);
+  *s = '\0';
+  soap_size_block(soap, sizeof(wchar_t) * (i + 1));
+  if ((soap->mode & SOAP_XML_STRICT) && l < minlen)
+  { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "String too short: %ld chars, minlen=%ld\n", l, minlen));
+    soap->error = SOAP_LENGTH;
+    return NULL;
+  }
+  s = (wchar_t*)soap_save_block(soap, NULL, 0);
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+    soap->dom->wide = s;
+#endif
+  return s;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_int2s(struct soap *soap, int n)
+{ return soap_long2s(soap, (long)n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outint(struct soap *soap, const char *tag, int id, const int *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_long2s(soap, (long)*p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2int(struct soap *soap, const char *s, int *p)
+{ if (s)
+  { char *r;
+    *p = (int)soap_strtol(s, &r, 10);
+    if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r
+#ifndef WITH_NOIO
+#ifndef WITH_LEAN
+     || soap_errno == SOAP_ERANGE
+#endif
+#endif
+    )
+      soap->error = SOAP_TYPE;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int *
+SOAP_FMAC2
+soap_inint(struct soap *soap, const char *tag, int *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":int")
+   && soap_match_tag(soap, soap->type, ":short")
+   && soap_match_tag(soap, soap->type, ":byte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (int*)soap_id_enter(soap, soap->id, p, t, sizeof(int), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (int*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(int), 0, NULL);
+  else if (p)
+  { if (soap_s2int(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_long2s(struct soap *soap, long n)
+{ sprintf(soap->tmpbuf, "%ld", n);
+  return soap->tmpbuf;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outlong(struct soap *soap, const char *tag, int id, const long *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_long2s(soap, *p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2long(struct soap *soap, const char *s, long *p)
+{ if (s)
+  { char *r;
+    *p = soap_strtol(s, &r, 10);
+    if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r
+#ifndef WITH_NOIO
+#ifndef WITH_LEAN
+     || soap_errno == SOAP_ERANGE
+#endif
+#endif
+    )
+      soap->error = SOAP_TYPE;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+long *
+SOAP_FMAC2
+soap_inlong(struct soap *soap, const char *tag, long *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":int")
+   && soap_match_tag(soap, soap->type, ":short")
+   && soap_match_tag(soap, soap->type, ":byte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (long*)soap_id_enter(soap, soap->id, p, t, sizeof(long), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (long*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(long), 0, NULL);
+  else if (p)
+  { if (soap_s2long(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_LONG642s(struct soap *soap, LONG64 n)
+{ sprintf(soap->tmpbuf, SOAP_LONG_FORMAT, n);
+  return soap->tmpbuf;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outLONG64(struct soap *soap, const char *tag, int id, const LONG64 *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_LONG642s(soap, *p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2LONG64(struct soap *soap, const char *s, LONG64 *p)
+{ if (s)
+  {
+#ifdef HAVE_STRTOLL
+    char *r;
+    *p = strtoll(s, &r, 10);
+    if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r
+#ifndef WITH_NOIO
+#ifndef WITH_LEAN
+       || soap_errno == SOAP_ERANGE
+#endif
+#endif
+      )
+#else
+# ifdef HAVE_SSCANF
+    if (sscanf(s, SOAP_LONG_FORMAT, p) != 1)
+# endif
+#endif
+      soap->error = SOAP_TYPE;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+LONG64 *
+SOAP_FMAC2
+soap_inLONG64(struct soap *soap, const char *tag, LONG64 *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":integer")
+   && soap_match_tag(soap, soap->type, ":positiveInteger")
+   && soap_match_tag(soap, soap->type, ":negativeInteger")
+   && soap_match_tag(soap, soap->type, ":nonPositiveInteger")
+   && soap_match_tag(soap, soap->type, ":nonNegativeInteger")
+   && soap_match_tag(soap, soap->type, ":long")
+   && soap_match_tag(soap, soap->type, ":int")
+   && soap_match_tag(soap, soap->type, ":short")
+   && soap_match_tag(soap, soap->type, ":byte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (LONG64*)soap_id_enter(soap, soap->id, p, t, sizeof(LONG64), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (LONG64*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(LONG64), 0, NULL);
+  else if (p)
+  { if (soap_s2LONG64(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_byte2s(struct soap *soap, char n)
+{ return soap_long2s(soap, (long)n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outbyte(struct soap *soap, const char *tag, int id, const char *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_long2s(soap, (long)*p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2byte(struct soap *soap, const char *s, char *p)
+{ if (s)
+  { long n;
+    char *r;
+    n = soap_strtol(s, &r, 10);
+    if (s == r || *r || n < -128 || n > 127)
+      soap->error = SOAP_TYPE;
+    *p = (char)n;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_inbyte(struct soap *soap, const char *tag, char *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":byte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (char*)soap_id_enter(soap, soap->id, p, t, sizeof(char), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (char*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(char), 0, NULL);
+  else if (p)
+  { if (soap_s2byte(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_short2s(struct soap *soap, short n)
+{ return soap_long2s(soap, (long)n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outshort(struct soap *soap, const char *tag, int id, const short *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_long2s(soap, (long)*p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2short(struct soap *soap, const char *s, short *p)
+{ if (s)
+  { long n;
+    char *r;
+    n = soap_strtol(s, &r, 10);
+    if (s == r || *r || n < -32768 || n > 32767)
+      soap->error = SOAP_TYPE;
+    *p = (short)n;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+short *
+SOAP_FMAC2
+soap_inshort(struct soap *soap, const char *tag, short *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":short")
+   && soap_match_tag(soap, soap->type, ":byte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (short*)soap_id_enter(soap, soap->id, p, t, sizeof(short), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (short*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(short), 0, NULL);
+  else if (p)
+  { if (soap_s2short(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_float2s(struct soap *soap, float n)
+{ const char *s;
+  if (soap_isnan((double)n))
+    s = "NaN";
+  else if (soap_ispinff(n))
+    s = "INF";
+  else if (soap_isninff(n))
+    s = "-INF";
+  else
+  { sprintf(soap->tmpbuf, soap->float_format, n);
+    s = soap->tmpbuf;
+  }
+  return s;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outfloat(struct soap *soap, const char *tag, int id, const float *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_float2s(soap, *p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2float(struct soap *soap, const char *s, float *p)
+{ if (s)
+  { if (!*s)
+      return soap->error = SOAP_TYPE;
+    if (!soap_tag_cmp(s, "INF"))
+      *p = FLT_PINFTY;
+    else if (!soap_tag_cmp(s, "+INF"))
+      *p = FLT_PINFTY;
+    else if (!soap_tag_cmp(s, "-INF"))
+      *p = FLT_NINFTY;
+    else if (!soap_tag_cmp(s, "NaN"))
+      *p = FLT_NAN;
+    else
+    {
+/* On some systems, strtof appears to be broken or doesn't link: use with caution */
+#if defined(HAVE_STRTOF)
+      char *r;
+      *p = strtof((char*)s, &r);
+      if (*r)
+#elif defined(HAVE_STRTOD)
+      char *r;
+      *p = (float)strtod(s, &r);
+      if (*r)
+#endif
+#ifdef HAVE_SSCANF
+        if (sscanf(s, "%g", p) != 1)
+          soap->error = SOAP_TYPE;
+#else
+        soap->error = SOAP_TYPE;
+#endif
+    }
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+static int soap_isnumeric(struct soap *soap, const char *type)
+{ if (soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":float")
+   && soap_match_tag(soap, soap->type, ":double")
+   && soap_match_tag(soap, soap->type, ":decimal")
+   && soap_match_tag(soap, soap->type, ":integer")
+   && soap_match_tag(soap, soap->type, ":positiveInteger")
+   && soap_match_tag(soap, soap->type, ":negativeInteger")
+   && soap_match_tag(soap, soap->type, ":nonPositiveInteger")
+   && soap_match_tag(soap, soap->type, ":nonNegativeInteger")
+   && soap_match_tag(soap, soap->type, ":long")
+   && soap_match_tag(soap, soap->type, ":int")
+   && soap_match_tag(soap, soap->type, ":short")
+   && soap_match_tag(soap, soap->type, ":byte")
+   && soap_match_tag(soap, soap->type, ":unsignedLong")
+   && soap_match_tag(soap, soap->type, ":unsignedInt")
+   && soap_match_tag(soap, soap->type, ":unsignedShort")
+   && soap_match_tag(soap, soap->type, ":unsignedByte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return SOAP_ERR;
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+float *
+SOAP_FMAC2
+soap_infloat(struct soap *soap, const char *tag, float *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type != '\0' && soap_isnumeric(soap, type))
+    return NULL;
+#endif
+  p = (float*)soap_id_enter(soap, soap->id, p, t, sizeof(float), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (float*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(float), 0, NULL);
+  else if (p)
+  { if (soap_s2float(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_double2s(struct soap *soap, double n)
+{ const char *s;
+  if (soap_isnan(n))
+    s = "NaN";
+  else if (soap_ispinfd(n))
+    s = "INF";
+  else if (soap_isninfd(n))
+    s = "-INF";
+  else
+  { sprintf(soap->tmpbuf, soap->double_format, n);
+    s = soap->tmpbuf;
+  }
+  return s;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outdouble(struct soap *soap, const char *tag, int id, const double *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_double2s(soap, *p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2double(struct soap *soap, const char *s, double *p)
+{ if (s)
+  { if (!*s)
+      return soap->error = SOAP_TYPE;
+    if (!soap_tag_cmp(s, "INF"))
+      *p = DBL_PINFTY;
+    else if (!soap_tag_cmp(s, "+INF"))
+      *p = DBL_PINFTY;
+    else if (!soap_tag_cmp(s, "-INF"))
+      *p = DBL_NINFTY;
+    else if (!soap_tag_cmp(s, "NaN"))
+      *p = DBL_NAN;
+    else
+    {
+#ifdef HAVE_STRTOD
+      char *r;
+      *p = strtod(s, &r);
+      if (*r)
+#endif
+#ifdef HAVE_SSCANF
+        if (sscanf(s, "%lg", p) != 1)
+          soap->error = SOAP_TYPE;
+#else
+        soap->error = SOAP_TYPE;
+#endif
+    }
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+double *
+SOAP_FMAC2
+soap_indouble(struct soap *soap, const char *tag, double *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type != '\0' && soap_isnumeric(soap, type))
+    return NULL;
+#endif
+  p = (double*)soap_id_enter(soap, soap->id, p, t, sizeof(double), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (double*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(double), 0, NULL);
+  else if (p)
+  { if (soap_s2double(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_unsignedByte2s(struct soap *soap, unsigned char n)
+{ return soap_unsignedLong2s(soap, (unsigned long)n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outunsignedByte(struct soap *soap, const char *tag, int id, const unsigned char *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2unsignedByte(struct soap *soap, const char *s, unsigned char *p)
+{ if (s)
+  { unsigned long n;
+    char *r;
+    n = soap_strtoul(s, &r, 10);
+    if (s == r || *r || n > 255)
+      soap->error = SOAP_TYPE;
+    *p = (unsigned char)n;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+unsigned char *
+SOAP_FMAC2
+soap_inunsignedByte(struct soap *soap, const char *tag, unsigned char *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":unsignedByte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (unsigned char*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned char), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (unsigned char*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(unsigned char), 0, NULL);
+  else if (p)
+  { if (soap_s2unsignedByte(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_unsignedShort2s(struct soap *soap, unsigned short n)
+{ return soap_unsignedLong2s(soap, (unsigned long)n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outunsignedShort(struct soap *soap, const char *tag, int id, const unsigned short *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2unsignedShort(struct soap *soap, const char *s, unsigned short *p)
+{ if (s)
+  { unsigned long n;
+    char *r;
+    n = soap_strtoul(s, &r, 10);
+    if (s == r || *r || n > 65535)
+      soap->error = SOAP_TYPE;
+    *p = (unsigned short)n;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+unsigned short *
+SOAP_FMAC2
+soap_inunsignedShort(struct soap *soap, const char *tag, unsigned short *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":unsignedShort")
+   && soap_match_tag(soap, soap->type, ":unsignedByte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (unsigned short*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned short), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (unsigned short*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(unsigned short), 0, NULL);
+  else if (p)
+  { if (soap_s2unsignedShort(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_unsignedInt2s(struct soap *soap, unsigned int n)
+{ return soap_unsignedLong2s(soap, (unsigned long)n);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outunsignedInt(struct soap *soap, const char *tag, int id, const unsigned int *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_unsignedLong2s(soap, (unsigned long)*p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2unsignedInt(struct soap *soap, const char *s, unsigned int *p)
+{ if (s)
+  { char *r;
+    *p = (unsigned int)soap_strtoul(s, &r, 10);
+    if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r
+#ifndef WITH_NOIO
+#ifndef WITH_LEAN
+     || soap_errno == SOAP_ERANGE
+#endif
+#endif
+    )
+      soap->error = SOAP_TYPE;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+unsigned int *
+SOAP_FMAC2
+soap_inunsignedInt(struct soap *soap, const char *tag, unsigned int *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":unsignedInt")
+   && soap_match_tag(soap, soap->type, ":unsignedShort")
+   && soap_match_tag(soap, soap->type, ":unsignedByte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (unsigned int*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned int), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (unsigned int*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(unsigned int), 0, NULL);
+  else if (p)
+  { if (soap_s2unsignedInt(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_unsignedLong2s(struct soap *soap, unsigned long n)
+{ sprintf(soap->tmpbuf, "%lu", n);
+  return soap->tmpbuf;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outunsignedLong(struct soap *soap, const char *tag, int id, const unsigned long *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_unsignedLong2s(soap, *p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2unsignedLong(struct soap *soap, const char *s, unsigned long *p)
+{ if (s)
+  { char *r;
+    *p = soap_strtoul(s, &r, 10);
+    if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r
+#ifndef WITH_NOIO
+#ifndef WITH_LEAN
+     || soap_errno == SOAP_ERANGE
+#endif
+#endif
+    )
+      soap->error = SOAP_TYPE;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+unsigned long *
+SOAP_FMAC2
+soap_inunsignedLong(struct soap *soap, const char *tag, unsigned long *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+#ifndef WITH_LEAN
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":unsignedInt")
+   && soap_match_tag(soap, soap->type, ":unsignedShort")
+   && soap_match_tag(soap, soap->type, ":unsignedByte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+#endif
+  p = (unsigned long*)soap_id_enter(soap, soap->id, p, t, sizeof(unsigned long), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (unsigned long*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(unsigned long), 0, NULL);
+  else if (p)
+  { if (soap_s2unsignedLong(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_ULONG642s(struct soap *soap, ULONG64 n)
+{ sprintf(soap->tmpbuf, SOAP_ULONG_FORMAT, n);
+  return soap->tmpbuf;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outULONG64(struct soap *soap, const char *tag, int id, const ULONG64 *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_ULONG642s(soap, *p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2ULONG64(struct soap *soap, const char *s, ULONG64 *p)
+{ if (s)
+  {
+#ifdef HAVE_STRTOULL
+    char *r;
+    *p = strtoull(s, &r, 10);
+    if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r
+#ifndef WITH_NOIO
+#ifndef WITH_LEAN
+       || soap_errno == SOAP_ERANGE
+#endif
+#endif
+      )
+#else
+# ifdef HAVE_SSCANF
+    if (sscanf(s, SOAP_ULONG_FORMAT, p) != 1)
+# endif
+#endif
+      soap->error = SOAP_TYPE;
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+ULONG64 *
+SOAP_FMAC2
+soap_inULONG64(struct soap *soap, const char *tag, ULONG64 *p, const char *type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":positiveInteger")
+   && soap_match_tag(soap, soap->type, ":nonNegativeInteger")
+   && soap_match_tag(soap, soap->type, ":unsignedLong")
+   && soap_match_tag(soap, soap->type, ":unsignedInt")
+   && soap_match_tag(soap, soap->type, ":unsignedShort")
+   && soap_match_tag(soap, soap->type, ":unsignedByte"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+  p = (ULONG64*)soap_id_enter(soap, soap->id, p, t, sizeof(ULONG64), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (ULONG64*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(ULONG64), 0, NULL);
+  else if (p)
+  { if (soap_s2ULONG64(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2string(struct soap *soap, const char *s, char **t)
+{ *t = NULL;
+  if (s && !(*t = soap_strdup(soap, s)))
+    soap->error = SOAP_EOM;
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2QName(struct soap *soap, const char *s, char **t)
+{ if (s)
+  { struct soap_nlist *np;
+    const char *p;
+    if (!strncmp(s, "xml:", 4))
+    { *t = soap_strdup(soap, s);
+      return SOAP_OK;
+    }
+    np = soap->nlist;
+    p = strchr(s, ':');
+    if (p)
+    { register int n = p - s;
+      while (np && (strncmp(np->id, s, n) || np->id[n]))
+        np = np->next;
+      p++;
+    }
+    else
+    { while (np && *np->id)
+        np = np->next;
+      p = s;
+    }
+    if (np)
+    { if (np->index >= 0 && soap->local_namespaces)
+      { register const char *q = soap->local_namespaces[np->index].id;
+        if (q)
+        { if ((*t = (char*)soap_malloc(soap, strlen(p) + strlen(q) + 2)))
+            sprintf(*t, "%s:%s", q, p);
+          return SOAP_OK;
+        }
+      }
+      if (np->ns)
+      { if ((*t = (char*)soap_malloc(soap, strlen(p) + strlen(np->ns) + 4)))
+          sprintf(*t, "\"%s\":%s", np->ns, p);
+        return SOAP_OK;
+      }
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Namespace prefix of '%s' not defined (index=%d, URI=%s)\n", s, np->index, np->ns?np->ns:""));
+      return soap->error = SOAP_NAMESPACE; 
+    }
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Namespace prefix of '%s' not defined, assuming empty namespace\n", s));
+    if ((*t = (char*)soap_malloc(soap, strlen(p) + 4)))
+      sprintf(*t, "\"\":%s", p);
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_QName2s(struct soap *soap, const char *s)
+{ struct Namespace *p;
+  char *t;
+  int n;
+  if (!s || *s != '"')
+  {
+#ifndef WITH_LEAN
+    if (s && (soap->mode & SOAP_XML_CANONICAL))
+    { t = strchr(const_cast<char*>(s), ':');
+      if (t)
+        soap_utilize_ns(soap, s, t - s);
+    }
+#endif
+    return s;
+  }
+  s++;
+  if ((p = soap->local_namespaces))
+  { for (; p->id; p++)
+    { if (p->ns)
+        if (!soap_tag_cmp(s, p->ns))
+          break;
+      if (p->in)
+        if (!soap_tag_cmp(s, p->in))
+          break;
+    }
+    if (p && p->id)
+    { s = strchr(s, '"');
+      if (s)
+      { t = (char*)soap_malloc(soap, strlen(p->id) + strlen(s));
+        strcpy(t, p->id);
+	strcat(t, s + 1);
+        return t;
+      }
+    }
+  }
+  t = (char*)strchr(s, '"');
+  if (t)
+    n = t - s;
+  else
+    n = 0;
+  t = soap_strdup(soap, s);
+  t[n] = '\0';
+  sprintf(soap->tmpbuf, "xmlns:_%d", soap->idnum++);
+  soap_set_attr(soap, soap->tmpbuf, t);
+  s = strchr(s, '"');
+  if (s)
+  { t = (char*)soap_malloc(soap, strlen(soap->tmpbuf) + strlen(s) - 6);
+    strcpy(t, soap->tmpbuf + 6);
+    strcat(t, s + 1);
+  }
+  return t;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outstring(struct soap *soap, const char *tag, int id, char *const*p, const char *type, int n) 
+{ id = soap_element_id(soap, tag, id, *p, NULL, 0, type, n);
+  if (id < 0
+   || soap_element_begin_out(soap, tag, id, type)
+   || soap_string_out(soap, *p, 0)
+   || soap_element_end_out(soap, tag))
+    return soap->error;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char **
+SOAP_FMAC2
+soap_instring(struct soap *soap, const char *tag, char **p, const char *type, int t, int flag, long minlen, long maxlen)
+{ if (soap_element_begin_in(soap, tag, 1))
+  { if (!tag || *tag != '-' || soap->error != SOAP_NO_TAG)
+      return NULL;
+    soap->error = SOAP_OK;
+  }
+  if (!p)
+    if (!(p = (char**)soap_malloc(soap, sizeof(char*))))
+      return NULL;
+  if (soap->body)
+  { *p = soap_string_in(soap, flag, minlen, maxlen);
+    if (!*p || !(char*)soap_id_enter(soap, soap->id, *p, t, sizeof(char*), 0, NULL, NULL, NULL))
+      return NULL;
+  }
+  else
+    *p = NULL;
+  if (*soap->href)
+    p = (char**)soap_id_lookup(soap, soap->href, (void**)p, t, sizeof(char**), 0);
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outwstring(struct soap *soap, const char *tag, int id, wchar_t *const*p, const char *type, int n) 
+{ id = soap_element_id(soap, tag, id, *p, NULL, 0, type, n);
+  if (id < 0
+   || soap_element_begin_out(soap, tag, id, type)
+   || soap_wstring_out(soap, *p, 0)
+   || soap_element_end_out(soap, tag))
+    return soap->error;
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_2
+SOAP_FMAC1
+wchar_t **
+SOAP_FMAC2
+soap_inwstring(struct soap *soap, const char *tag, wchar_t **p, const char *type, int t, long minlen, long maxlen)
+{ if (soap_element_begin_in(soap, tag, 1))
+  { if (!tag || *tag != '-' || soap->error != SOAP_NO_TAG)
+      return NULL;
+    soap->error = SOAP_OK;
+  }
+  if (!p)
+    if (!(p = (wchar_t**)soap_malloc(soap, sizeof(wchar_t*))))
+      return NULL;
+  if (soap->body)
+  { *p = soap_wstring_in(soap, 1, minlen, maxlen);
+    if (!*p || !(wchar_t*)soap_id_enter(soap, soap->id, *p, t, sizeof(wchar_t*), 0, NULL, NULL, NULL))
+      return NULL;
+  }
+  else
+    *p = NULL;
+  if (*soap->href)
+    p = (wchar_t**)soap_id_lookup(soap, soap->href, (void**)p, t, sizeof(wchar_t**), 0);
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+static time_t
+soap_timegm(struct tm *T)
+{
+#if defined(HAVE_TIMEGM)
+  return timegm(T);
+#else
+  time_t t, g, z;
+#ifdef HAVE_GMTIME_R
+  struct tm tm, *tmp = &tm;
+#else
+  struct tm *tmp;
+#endif
+  t = mktime(T);
+  if (t == -1)
+    return -1;
+#ifdef HAVE_GMTIME_R
+  gmtime_r(&t, tmp);
+#else
+  tmp = gmtime(&t);
+#endif
+  tmp->tm_isdst = 0;
+  g = mktime(tmp);
+  if (g == -1)
+    return -1;
+  z = g - t;
+  return t - z;
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_dateTime2s(struct soap *soap, time_t n)
+{ struct tm T, *pT = &T;
+#if defined(HAVE_GMTIME_R)
+  if (gmtime_r(&n, pT))
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%SZ", pT);
+  /* The following defines were added for VxWorks*/
+#elif defined(HAVE_PGMTIME_R)
+  if (gmtime_r(&n, pT))
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%SZ", pT);
+#elif defined(HAVE_PGMTIME)
+  if (gmtime(&n, pT))
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%SZ", pT);
+#elif defined(HAVE_GMTIME)
+  if ((pT = gmtime(&n)))
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%SZ", pT);
+#elif defined(HAVE_GETTIMEOFDAY)
+  struct timezone tz;
+  memset((void*)&tz, 0, sizeof(tz));
+# if defined(HAVE_LOCALTIME_R)
+  if (localtime_r(&n, pT))
+  { struct timeval tv;
+    gettimeofday(&tv, &tz);
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT);
+    sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -tz.tz_minuteswest/60+(pT->tm_isdst!=0), abs(tz.tz_minuteswest)%60);
+  }
+# else
+  if ((pT = localtime(&n)))
+  { struct timeval tv;
+    gettimeofday(&tv, &tz);
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT);
+    sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -tz.tz_minuteswest/60+(pT->tm_isdst!=0), abs(tz.tz_minuteswest)%60);
+  }
+#endif
+#elif defined(HAVE_FTIME)
+  struct timeb t;
+  memset((void*)&t, 0, sizeof(t));
+# if defined(HAVE_LOCALTIME_R)
+  if (localtime_r(&n, pT))
+  { ftime(&t);
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT);
+    sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -t.timezone/60+(pT->tm_isdst!=0), abs(t.timezone)%60);
+  }
+  /* The following defines were added for VxWorks*/
+# elif defined(HAVE_PLOCALTIME_R)
+  if (localtime_r(&n, pT))
+  { strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT);
+    sprintf(soap->tmpbuf+strlen(soap->tmpbuf), "%+03d:%02d", t.timezone/60, abs(t.timezone)%60);
+  }
+# else
+  if ((pT = localtime(&n)))
+  { ftime(&t);
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT);
+    sprintf(soap->tmpbuf + strlen(soap->tmpbuf), "%+03d:%02d", -t.timezone/60+(pT->tm_isdst!=0), abs(t.timezone)%60);
+  }
+# endif
+#elif defined(HAVE_LOCALTIME_R)
+  if (localtime_r(&n, pT))
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT);
+  /* The following defines were added for VxWorks*/
+#elif defined(HAVE_PLOCALTIME_R)
+  if (localtime_r(&n, pT))
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT);
+#else
+  if ((pT = localtime(&n)))
+    strftime(soap->tmpbuf, sizeof(soap->tmpbuf), "%Y-%m-%dT%H:%M:%S", pT);
+#endif
+  else
+    strcpy(soap->tmpbuf, "1969-12-31T23:59:59Z");
+  return soap->tmpbuf;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outdateTime(struct soap *soap, const char *tag, int id, const time_t *p, const char *type, int n)
+{ if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, p, n), type)
+   || soap_string_out(soap, soap_dateTime2s(soap, *p), 0))
+    return soap->error;
+  return soap_element_end_out(soap, tag);
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_s2dateTime(struct soap *soap, const char *s, time_t *p)
+{ if (s)
+  { struct tm T;
+    char zone[16];
+    const char *t;
+    memset((void*)&T, 0, sizeof(T));
+    zone[sizeof(zone)-1] = '\0';
+    if (strchr(s, '-'))
+      t = "%d-%d-%dT%d:%d:%d%15s";
+    else if (strchr(s, ':'))
+      t = "%4d%2d%2dT%d:%d:%d%15s";
+    else /* parse non-XSD-standard alternative ISO 8601 format */
+      t = "%4d%2d%2dT%2d%2d%2d%15s";
+    sscanf(s, t, &T.tm_year, &T.tm_mon, &T.tm_mday, &T.tm_hour, &T.tm_min, &T.tm_sec, zone);
+    if (T.tm_year == 1)
+      T.tm_year = 70;
+    else
+      T.tm_year -= 1900;
+    T.tm_mon--;
+    if (*zone)
+    { if (*zone == '.')
+      { for (s = zone + 1; *s; s++)
+          if (*s < '0' || *s > '9')
+            break;
+      }
+      else
+        s = zone;
+      if (*s == '+' || *s == '-')
+      { int h = 0, m = 0;
+        if (s[3] == ':')
+	{ sscanf(s, "%d:%d", &h, &m);
+	  if (h < 0)
+	    m = -m;
+	}
+	else
+	{ m = (int)atol(s);
+	  h = m / 100;
+	  m = m % 100;
+	}
+        T.tm_hour -= h;
+        T.tm_min -= m;
+      }
+      *p = soap_timegm(&T);
+    }
+    else
+      *p = mktime(&T); /* no time zone: suppose it is localtime? */
+  }
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+time_t *
+SOAP_FMAC2
+soap_indateTime(struct soap *soap, const char *tag, time_t *p, const char * type, int t)
+{ if (soap_element_begin_in(soap, tag, 0))
+    return NULL;
+  if (*soap->type
+   && soap_match_tag(soap, soap->type, type)
+   && soap_match_tag(soap, soap->type, ":dateTime"))
+  { soap->error = SOAP_TYPE;
+    soap_revert(soap);
+    return NULL;
+  }
+  p = (time_t*)soap_id_enter(soap, soap->id, p, t, sizeof(time_t), 0, NULL, NULL, NULL);
+  if (*soap->href)
+    p = (time_t*)soap_id_forward(soap, soap->href, p, t, 0, sizeof(time_t), 0, NULL);
+  else if (p)
+  { if (soap_s2dateTime(soap, soap_value(soap), p))
+      return NULL;
+  }
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outliteral(struct soap *soap, const char *tag, char *const*p)
+{ int i;
+  const char *t = NULL;
+  if (tag && *tag != '-')
+  { if (soap->local_namespaces && (t = strchr(tag, ':')))
+    { strncpy(soap->tmpbuf, tag, t-tag);
+      soap->tmpbuf[t-tag] = '\0';
+      for (i = 0; soap->local_namespaces[i].id; i++)
+        if (!strcmp(soap->tmpbuf, soap->local_namespaces[i].id))
+          break;
+      t++;
+      sprintf(soap->tmpbuf, "<%s xmlns=\"%s\">", t, soap->local_namespaces[i].ns ? soap->local_namespaces[i].ns : SOAP_STR_EOS);
+    }
+    else
+    { t = tag;
+      sprintf(soap->tmpbuf, "<%s>", tag);
+    }
+    if (soap_send(soap, soap->tmpbuf))
+      return soap->error;
+  }
+  if (p && *p)
+  { if (soap_send(soap, *p))
+      return soap->error;
+  }
+  if (t)
+  { sprintf(soap->tmpbuf, "</%s>", t);
+    return soap_send(soap, soap->tmpbuf);
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+char **
+SOAP_FMAC2
+soap_inliteral(struct soap *soap, const char *tag, char **p)
+{ if (soap_element_begin_in(soap, tag, 1))
+  { if (soap->error != SOAP_NO_TAG || soap_unget(soap, soap_get(soap)) == SOAP_TT)
+      return NULL;
+    soap->error = SOAP_OK;
+  }
+  if (!p)
+    if (!(p = (char**)soap_malloc(soap, sizeof(char*))))
+      return NULL;
+  if (soap->null)
+    *p = NULL;
+  else
+    *p = soap_string_in(soap, 0, -1, -1);
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_outwliteral(struct soap *soap, const char *tag, wchar_t *const*p)
+{ int i;
+  const char *t = NULL;
+  wchar_t c;
+  const wchar_t *s;
+  if (tag && *tag != '-')
+  { if (soap->local_namespaces && (t = strchr(tag, ':')))
+    { strncpy(soap->tmpbuf, tag, t-tag);
+      soap->tmpbuf[t-tag] = '\0';
+      for (i = 0; soap->local_namespaces[i].id; i++)
+        if (!strcmp(soap->tmpbuf, soap->local_namespaces[i].id))
+          break;
+      t++;
+      sprintf(soap->tmpbuf, "<%s xmlns=\"%s\">", t, soap->local_namespaces[i].ns ? soap->local_namespaces[i].ns : SOAP_STR_EOS);
+    }
+    else
+    { t = tag;
+      sprintf(soap->tmpbuf, "<%s>", tag);
+    }
+    if (soap_send(soap, soap->tmpbuf))
+      return soap->error;
+  }
+  if (p)
+  { s = *p;
+    while ((c = *s++))
+      if (soap_pututf8(soap, (unsigned char)c))
+        return soap->error;
+  }
+  if (t)
+  { sprintf(soap->tmpbuf, "</%s>", t);
+    return soap_send(soap, soap->tmpbuf);
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_2
+SOAP_FMAC1
+wchar_t **
+SOAP_FMAC2
+soap_inwliteral(struct soap *soap, const char *tag, wchar_t **p)
+{ if (soap_element_begin_in(soap, tag, 1))
+  { if (soap->error != SOAP_NO_TAG || soap_unget(soap, soap_get(soap)) == SOAP_TT)
+      return NULL;
+    soap->error = SOAP_OK;
+  }
+  if (!p)
+    if (!(p = (wchar_t**)soap_malloc(soap, sizeof(wchar_t*))))
+      return NULL;
+  if (soap->null)
+    *p = NULL;
+  else
+    *p = soap_wstring_in(soap, 0, -1, -1);
+  if (soap->body && soap_element_end_in(soap, tag))
+    return NULL;
+  return p;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char *
+SOAP_FMAC2
+soap_token(struct soap *soap)
+{ register size_t i;
+  register soap_wchar c = 0;
+  register char *s = soap->tmpbuf;
+  if (!soap->body)
+    return SOAP_STR_EOS;
+  do c = soap_get(soap);
+  while (soap_blank(c));
+  for (i = 0; i < sizeof(soap->tmpbuf) - 1; i++)
+  { if (c == SOAP_TT || (int)c == EOF || soap_blank(c))
+      break;
+    *s++ = (char)c;
+    c = soap_get(soap);
+  }
+  if ((int)c == EOF || c == SOAP_TT)
+    soap_unget(soap, c);
+  *s = '\0';
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element content value='%s'\n", soap->tmpbuf));
+  return soap->tmpbuf; /* return non-null pointer */
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+const char *
+SOAP_FMAC2
+soap_value(struct soap *soap)
+{ register size_t i;
+  register soap_wchar c = 0;
+  register char *s = soap->tmpbuf;
+  if (!soap->body)
+    return SOAP_STR_EOS;
+  do c = soap_get(soap);
+  while (soap_blank(c));
+  for (i = 0; i < sizeof(soap->tmpbuf) - 1; i++)
+  { if (c == SOAP_TT || (int)c == EOF)
+      break;
+    *s++ = (char)c;
+    c = soap_get(soap);
+  }
+  for (s--; i > 0; i--, s--)
+    if (!soap_blank(*s))
+      break;
+  s[1] = '\0';
+  if ((int)c == EOF || c == SOAP_TT)
+    soap_unget(soap, c);
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element content value='%s'\n", soap->tmpbuf));
+#ifdef WITH_DOM
+  if ((soap->mode & SOAP_XML_DOM) && soap->dom)
+    soap->dom->data = soap_strdup(soap, soap->tmpbuf);
+#endif
+  return soap->tmpbuf; /* return non-null pointer */
+}
+#endif
+
+/******************************************************************************/
+#if !defined(WITH_LEANER) || !defined(WITH_NOHTTP)
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getline(struct soap *soap, char *s, int len)
+{ int i = len;
+  soap_wchar c = 0;
+  for (;;)
+  { while (--i > 0)
+    { c = soap_getchar(soap);
+      if (c == '\r' || c == '\n')
+        break;
+      if ((int)c == EOF)
+        return soap->error = SOAP_EOF;
+      *s++ = (char)c;
+    }
+    if (c != '\n')
+      c = soap_getchar(soap); /* got \r, now get \n */
+    if (c == '\n')
+    { *s = '\0';
+      if (i+1 == len) /* empty line: end of HTTP/MIME header */
+        break;
+      c = soap_unget(soap, soap_getchar(soap));
+      if (c != ' ' && c != '\t') /* HTTP line continuation? */
+        break;
+    }
+    else if ((int)c == EOF)
+      return soap->error = SOAP_EOF;
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+static size_t
+soap_count_attachments(struct soap *soap)
+{ 
+#ifndef WITH_LEANER
+  register struct soap_multipart *content;
+  register size_t count = soap->count;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the message size with attachments, current count=%lu\n", (unsigned long)count));
+  if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM))
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the size of DIME attachments\n"));
+    for (content = soap->dime.first; content; content = content->next)
+    { count += 12 + ((content->size+3)&(~3));
+      if (content->id)
+        count += ((strlen(content->id)+3)&(~3));
+      if (content->type)
+        count += ((strlen(content->type)+3)&(~3));
+      if (content->options)
+        count += ((((unsigned char)content->options[2] << 8) | ((unsigned char)content->options[3]))+7)&(~3);
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Size of DIME attachment content is %lu bytes\n", (unsigned long)content->size));
+    }
+  }
+  if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary)
+  { register size_t n = strlen(soap->mime.boundary);
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Calculating the size of MIME attachments\n"));
+    for (content = soap->mime.first; content; content = content->next)
+    { register const char *s;
+      /* count \r\n--boundary\r\n */
+      count += 6 + n;
+      /* count Content-Type: ...\r\n */
+      if (content->type)
+        count += 16 + strlen(content->type);
+      /* count Content-Transfer-Encoding: ...\r\n */
+      s = soap_str_code(mime_codes, content->encoding);
+      if (s)
+        count += 29 + strlen(s);
+      /* count Content-ID: ...\r\n */
+      if (content->id)
+        count += 14 + strlen(content->id);
+      /* count Content-Location: ...\r\n */
+      if (content->location)
+        count += 20 + strlen(content->location);
+      /* count Content-Description: ...\r\n */
+      if (content->description)
+        count += 23 + strlen(content->location);
+      /* count \r\n...content */
+      count += 2 + content->size;
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Size of MIME attachment content is %lu bytes\n", (unsigned long)content->size));
+    }
+    /* count \r\n--boundary-- */
+    count += 6 + n;
+  }
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "New count is %lu bytes\n", (unsigned long)count));
+  return count;
+#else
+  return soap->count;
+#endif
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+static int
+soap_putdimefield(struct soap *soap, const char *s, size_t n)
+{ if (soap_send_raw(soap, s, n))
+    return soap->error;
+  return soap_send_raw(soap, SOAP_STR_PADDING, -(long)n&3);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_dime_option(struct soap *soap, unsigned short optype, const char *option)
+{ size_t n;
+  char *s = NULL;
+  if (option)
+  { n = strlen(option);
+    s = (char*)soap_malloc(soap, n + 5);
+    if (s)
+    { s[0] = optype >> 8;
+      s[1] = optype & 0xFF;
+      s[2] = n >> 8;
+      s[3] = n & 0xFF;
+      strcpy(s + 4, option);
+    }
+  }
+  return s;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_putdimehdr(struct soap *soap)
+{ unsigned char tmp[12];
+  size_t optlen = 0, idlen = 0, typelen = 0;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Put DIME header id='%s'\n", soap->dime.id?soap->dime.id:""));
+  if (soap->dime.options)
+    optlen = (((unsigned char)soap->dime.options[2] << 8) | ((unsigned char)soap->dime.options[3])) + 4;
+  if (soap->dime.id)
+    idlen = strlen(soap->dime.id);
+  if (soap->dime.type)
+    typelen = strlen(soap->dime.type);
+  tmp[0] = SOAP_DIME_VERSION | (soap->dime.flags & 0x7);
+  tmp[1] = soap->dime.flags & 0xF0;
+  tmp[2] = optlen >> 8;
+  tmp[3] = optlen & 0xFF;
+  tmp[4] = idlen >> 8;
+  tmp[5] = idlen & 0xFF;
+  tmp[6] = typelen >> 8;
+  tmp[7] = typelen & 0xFF;
+  tmp[8] = soap->dime.size >> 24;
+  tmp[9] = (soap->dime.size >> 16) & 0xFF;
+  tmp[10] = (soap->dime.size >> 8) & 0xFF;
+  tmp[11] = soap->dime.size & 0xFF;
+  if (soap_send_raw(soap, (char*)tmp, 12)
+   || soap_putdimefield(soap, soap->dime.options, optlen)
+   || soap_putdimefield(soap, soap->dime.id, idlen)
+   || soap_putdimefield(soap, soap->dime.type, typelen))
+    return soap->error;
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_putdime(struct soap *soap)
+{ struct soap_multipart *content;
+  if (!(soap->mode & SOAP_ENC_DIME))
+    return SOAP_OK;
+  for (content = soap->dime.first; content; content = content->next)
+  { void *handle;
+    soap->dime.size = content->size;
+    soap->dime.id = content->id;
+    soap->dime.type = content->type;
+    soap->dime.options = content->options;
+    soap->dime.flags = SOAP_DIME_VERSION | SOAP_DIME_MEDIA;
+    if (soap->fdimereadopen && ((handle = soap->fdimereadopen(soap, (void*)content->ptr, content->id, content->type, content->options)) || soap->error))
+    { size_t size = content->size;
+      if (!handle)
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadopen failed\n"));
+        return soap->error;
+      }
+      if (!content->size && ((soap->mode & SOAP_ENC_XML) || (soap->mode & SOAP_IO) == SOAP_IO_CHUNK || (soap->mode & SOAP_IO) == SOAP_IO_STORE))
+      { size_t chunksize = sizeof(soap->tmpbuf);
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunked streaming DIME\n"));
+        do 
+        { size = soap->fdimeread(soap, handle, soap->tmpbuf, chunksize);
+          DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimeread returned %lu bytes\n", (unsigned long)size));
+          if (size < chunksize)
+ 	  { soap->dime.flags &= ~SOAP_DIME_CF;
+            if (!content->next)
+              soap->dime.flags |= SOAP_DIME_ME;
+	  }
+          else
+            soap->dime.flags |= SOAP_DIME_CF;
+	  soap->dime.size = size;
+          if (soap_putdimehdr(soap)
+	   || soap_putdimefield(soap, soap->tmpbuf, size))
+            break;
+          if (soap->dime.id)
+ 	  { soap->dime.flags &= ~(SOAP_DIME_MB | SOAP_DIME_MEDIA);
+            soap->dime.id = NULL;
+            soap->dime.type = NULL;
+            soap->dime.options = NULL;
+          }  
+        } while (size >= chunksize);
+      }
+      else
+      { if (!content->next)
+          soap->dime.flags |= SOAP_DIME_ME;
+        if (soap_putdimehdr(soap))
+          return soap->error;
+        do
+        { size_t bufsize;
+	  if (size < sizeof(soap->tmpbuf))
+            bufsize = size;
+          else
+            bufsize = sizeof(soap->tmpbuf);
+          if (!(bufsize = soap->fdimeread(soap, handle, soap->tmpbuf, bufsize)))
+          { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimeread failed: insufficient data (%lu bytes remaining from %lu bytes)\n", (unsigned long)size, (unsigned long)soap->dime.size));
+            soap->error = SOAP_EOF;
+	    break;
+          }
+          if (soap_send_raw(soap, soap->tmpbuf, bufsize))
+            break;
+          size -= bufsize;
+        } while (size);
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadclose\n"));
+        soap_send_raw(soap, SOAP_STR_PADDING, -(long)soap->dime.size&3);
+      }
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimereadclose\n"));
+      if (soap->fdimereadclose)
+        soap->fdimereadclose(soap, handle);
+    }
+    else
+    { if (!content->next)
+        soap->dime.flags |= SOAP_DIME_ME;
+      if (soap_putdimehdr(soap)
+       || soap_putdimefield(soap, (char*)content->ptr, content->size))
+        return soap->error;
+    }
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+static char *
+soap_getdimefield(struct soap *soap, size_t n)
+{ register soap_wchar c;
+  register int i;
+  register char *s;
+  char *p = NULL;
+  if (n)
+  { p = (char*)soap_malloc(soap, n + 1);
+    if (p)
+    { s = p;
+      for (i = n; i > 0; i--)
+      { if ((int)(c = soap_get1(soap)) == EOF)
+        { soap->error = SOAP_EOF;
+          return NULL;
+        }
+        *s++ = (char)c;
+      }
+      *s = '\0';
+      if ((soap->error = soap_move(soap, -(long)n&3)))
+        return NULL;
+    }
+    else
+      soap->error = SOAP_EOM;
+  }
+  return p;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getdimehdr(struct soap *soap)
+{ register soap_wchar c;
+  register char *s;
+  register int i;
+  unsigned char tmp[12];
+  size_t optlen, idlen, typelen;
+  if (!(soap->mode & SOAP_ENC_DIME))
+    return soap->error = SOAP_DIME_END;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME header\n"));
+  if (soap->dime.buflen || soap->dime.chunksize)
+  { if (soap_move(soap, (long)(soap->dime.size - soap_tell(soap))))
+      return soap->error = SOAP_EOF;
+    soap_unget(soap, soap_getchar(soap)); /* skip padding and get hdr */
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "... From chunked\n"));
+    return SOAP_OK;
+  }
+  s = (char*)tmp;
+  for (i = 12; i > 0; i--)
+  { if ((int)(c = soap_getchar(soap)) == EOF)
+      return soap->error = SOAP_EOF;
+    *s++ = (char)c;
+  }
+  if ((tmp[0] & 0xF8) != SOAP_DIME_VERSION)
+    return soap->error = SOAP_DIME_MISMATCH;
+  soap->dime.flags = (tmp[0] & 0x7) | (tmp[1] & 0xF0);
+  optlen = (tmp[2] << 8) | tmp[3];
+  idlen = (tmp[4] << 8) | tmp[5];
+  typelen = (tmp[6] << 8) | tmp[7];
+  soap->dime.size = (tmp[8] << 24) | (tmp[9] << 16) | (tmp[10] << 8) | tmp[11];
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME size=%lu flags=0x%X\n", (unsigned long)soap->dime.size, soap->dime.flags));
+  if (!(soap->dime.options = soap_getdimefield(soap, optlen)) && soap->error)
+    return soap->error;
+  if (!(soap->dime.id = soap_getdimefield(soap, idlen)) && soap->error)
+    return soap->error;
+  if (!(soap->dime.type = soap_getdimefield(soap, typelen)) && soap->error)
+    return soap->error;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME id=%s, type=%s, options=%s\n", soap->dime.id?soap->dime.id:"", soap->dime.type?soap->dime.type:"", soap->dime.options?soap->dime.options+4:""));
+  if (soap->dime.flags & SOAP_DIME_ME)
+    soap->mode &= ~SOAP_ENC_DIME;
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getdime(struct soap *soap)
+{ while (soap->dime.flags & SOAP_DIME_CF)
+  { if (soap_getdimehdr(soap))
+      return soap->error;
+    if (soap_move(soap, soap->dime.size))
+      return soap->error = SOAP_EOF;
+  }
+  if (soap_move(soap, ((soap->dime.size+3)&(~3))-soap_tell(soap)))
+    return soap->error = SOAP_EOF;
+  for (;;)
+  { register struct soap_multipart *content;
+    if (soap_getdimehdr(soap))
+      break;
+    if (soap->fdimewriteopen && ((soap->dime.ptr = (char*)soap->fdimewriteopen(soap, soap->dime.id, soap->dime.type, soap->dime.options)) || soap->error))
+    { const char *id, *type, *options;
+      size_t size, n;
+      if (!soap->dime.ptr)
+        return soap->error;
+      id = soap->dime.id;
+      type = soap->dime.type;
+      options = soap->dime.options;
+      for (;;)
+      { size = soap->dime.size;
+        for (;;)
+        { n = soap->buflen - soap->bufidx;
+          if (size < n)
+            n = size;
+          if ((soap->error = soap->fdimewrite(soap, (void*)soap->dime.ptr, soap->buf + soap->bufidx, n)))
+            break;
+	  size -= n;
+	  if (!size)
+	  { soap->bufidx += n;
+	    break;
+	  }
+	  if (soap_recv(soap))
+          { soap->error = SOAP_EOF;
+	    goto end;
+          }
+        }
+        if (soap_move(soap, -(long)soap->dime.size&3))
+        { soap->error = SOAP_EOF;
+	  break;
+        }
+        if (!(soap->dime.flags & SOAP_DIME_CF))
+          break;
+        if (soap_getdimehdr(soap))
+          break;
+      }
+end:
+      if (soap->fdimewriteclose)
+        soap->fdimewriteclose(soap, (void*)soap->dime.ptr);
+      soap->dime.size = 0;
+      soap->dime.id = id;
+      soap->dime.type = type;
+      soap->dime.options = options;
+    }
+    else if (soap->dime.flags & SOAP_DIME_CF)
+    { const char *id, *type, *options;
+      register soap_wchar c;
+      register char *s;
+      register int i;
+      id = soap->dime.id;
+      type = soap->dime.type;
+      options = soap->dime.options;
+      if (soap_new_block(soap))
+        return SOAP_EOM;
+      for (;;)
+      { s = (char*)soap_push_block(soap, soap->dime.size);
+        if (!s)
+          return soap->error = SOAP_EOM;
+        for (i = soap->dime.size; i > 0; i--)
+        { if ((int)(c = soap_get1(soap)) == EOF)
+            return soap->error = SOAP_EOF;
+          *s++ = (char)c;
+        }
+        if (soap_move(soap, -(long)soap->dime.size&3))
+          return soap->error = SOAP_EOF;
+        if (!(soap->dime.flags & SOAP_DIME_CF))
+          break;
+        if (soap_getdimehdr(soap))
+          return soap->error;
+      }
+      soap->dime.size = soap->blist->size++; /* allocate one more for '\0' */
+      if (!(soap->dime.ptr = soap_save_block(soap, NULL, 0)))
+        return soap->error;
+      soap->dime.ptr[soap->dime.size] = '\0'; /* force 0-terminated */
+      soap->dime.id = id;
+      soap->dime.type = type;
+      soap->dime.options = options;
+    }
+    else
+      soap->dime.ptr = soap_getdimefield(soap, soap->dime.size);
+    content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, soap->dime.ptr, soap->dime.size);
+    if (!content)
+      return soap->error = SOAP_EOM;
+    content->id = soap->dime.id;
+    content->type = soap->dime.type;
+    content->options = soap->dime.options;
+    soap_resolve_attachment(soap, content);
+    if (soap->error)
+      return soap->error;
+  }
+  if (soap->error != SOAP_DIME_END)
+    return soap->error;
+  return soap->error = SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getmimehdr(struct soap *soap)
+{ struct soap_multipart *content;
+  do
+  { if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf)))
+      return soap->error;
+  }
+  while (!*soap->msgbuf);
+  if (soap->msgbuf[0] == '-' && soap->msgbuf[1] == '-')
+  { char *s = soap->msgbuf + strlen(soap->msgbuf) - 1;
+    /* remove white space */
+    while (soap_blank(*s))
+      s--;
+    s[1] = '\0';
+    if (soap->mime.boundary)
+    { if (strcmp(soap->msgbuf + 2, soap->mime.boundary))
+        return soap->error = SOAP_MIME_ERROR;
+    }
+    else
+      soap->mime.boundary = soap_strdup(soap, soap->msgbuf + 2);
+    if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf)))
+      return soap->error;
+  }
+  if (soap_set_mime_attachment(soap, NULL, 0, SOAP_MIME_NONE, NULL, NULL, NULL, NULL))
+    return soap->error = SOAP_EOM;
+  content = soap->mime.last;
+  for (;;)
+  { register char *key = soap->msgbuf;
+    register char *val;
+    if (!*key)
+      break;
+    DBGLOG(TEST,SOAP_MESSAGE(fdebug, "MIME header: %s\n", key));
+    val = strchr(soap->msgbuf, ':');
+    if (val)
+    { *val = '\0';
+      do val++;
+      while (*val && *val <= 32);
+      if (!soap_tag_cmp(key, "Content-ID"))
+        content->id = soap_strdup(soap, val);
+      else if (!soap_tag_cmp(key, "Content-Location"))
+        content->location = soap_strdup(soap, val);
+      else if (!soap_tag_cmp(key, "Content-Disposition"))
+        content->id = soap_strdup(soap, soap_get_header_attribute(soap, val, "name"));
+      else if (!soap_tag_cmp(key, "Content-Type"))
+        content->type = soap_strdup(soap, val);
+      else if (!soap_tag_cmp(key, "Content-Description"))
+        content->description = soap_strdup(soap, val);
+      else if (!soap_tag_cmp(key, "Content-Transfer-Encoding"))
+        content->encoding = (enum soap_mime_encoding)soap_int_code(mime_codes, val, (long)SOAP_MIME_NONE);
+    }
+    if (soap_getline(soap, key, sizeof(soap->msgbuf)))
+      return soap->error;
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getmime(struct soap *soap)
+{ register soap_wchar c = 0;
+  if (!soap->mime.last)
+    return SOAP_OK;
+  for (;;)
+  { register size_t i, m = 0;
+    register char *s, *t = NULL;
+    struct soap_multipart *content = soap->mime.last;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Parsing MIME content id=%s type=%s\n", content->id?content->id:"", content->type?content->type:""));
+    if (soap_new_block(soap))
+      return soap->error = SOAP_EOM;
+    for (;;)
+    { register short flag = 0;
+      if (!(s = (char*)soap_push_block(soap, SOAP_BLKLEN)))
+        return soap->error = SOAP_EOM;
+      for (i = 0; i < SOAP_BLKLEN; i++)
+      { if (m > 0)
+        { flag = (*t == '\r');
+	  *s++ = *t++;
+	  m--;
+	}
+	else
+        { if (!flag)
+	  { c = soap_get1(soap);
+	    if ((int)c == EOF)
+	      return soap->error = SOAP_EOF;
+	  }
+	  if (flag || c == '\r')
+	  { t = soap->tmpbuf;
+	    memset(t, 0, sizeof(soap->tmpbuf));
+            strcpy(t, "\n--");
+            if (soap->mime.boundary)
+	      strncat(t, soap->mime.boundary, sizeof(soap->tmpbuf)-4);
+	    do c = soap_getchar(soap);
+	    while (c == *t++);
+	    if ((int)c == EOF)
+	      return soap->error = SOAP_EOF;
+	    if (!*--t)
+	      goto end;
+	    *t = (char)c;
+	    m = t - soap->tmpbuf + 1;
+	    t = soap->tmpbuf;
+	    c = '\r';
+	  }
+	  *s++ = (char)c;
+        }
+      }
+    }
+end:
+    *s = '\0'; /* force 0-terminated */
+    content->size = soap_size_block(soap, i+1)-1;
+    content->ptr = soap_save_block(soap, NULL, 0);
+    soap_resolve_attachment(soap, content);
+    if (c == '-' && soap_getchar(soap) == '-')
+      break;
+    while (c != '\r' && (int)c != EOF && soap_blank(c))
+      c = soap_getchar(soap);
+    if (c != '\r' || soap_getchar(soap) != '\n')
+      return soap->error = SOAP_MIME_ERROR;
+    if (soap_getmimehdr(soap))
+      return soap->error;
+  }
+  /*
+  do c = soap_getchar(soap);
+  while ((int)c != EOF && c != '\r' && c != '\n');
+  if ((int)c != '\r' || soap_getchar(soap) != '\n')
+    return soap->error = SOAP_MIME_ERROR;
+  */
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+static int
+soap_match_cid(const char *s, const char *t)
+{ register size_t n;
+  if (!s)
+    return 1;
+  if (!strcmp(s, t))
+    return 0;
+  if (!strncmp(s, "cid:", 4))
+    s += 4;
+  n = strlen(t);
+  if (*t == '<')
+  { t++;
+    n -= 2;
+  }
+  if (!strncmp(s, t, n) && !s[n])
+    return 0;
+  return 1;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+static void
+soap_resolve_attachment(struct soap *soap, struct soap_multipart *content)
+{ if (content->id)
+  { register struct soap_xlist **xp = &soap->xlist;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Resolving attachment data for id=%s\n", content->id));
+    while (*xp)
+    { register struct soap_xlist *xq = *xp;
+      if (!soap_match_cid(xq->id, content->id))
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Found matching attachment %s for content id=%s\n", xq->id, content->id));
+	*xp = xq->next;
+        *xq->ptr = (unsigned char*)content->ptr;
+        *xq->size = (int)content->size;
+        *xq->type = (char*)content->type;
+	if (content->options)
+          *xq->options = (char*)content->options;
+        else
+          *xq->options = (char*)content->description;
+	SOAP_FREE(soap, xq);
+      }
+      else
+        xp = &(*xp)->next;
+    }
+  }
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_putmimehdr(struct soap *soap, struct soap_multipart *content)
+{ const char *s;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "MIME attachment type=%s\n", content->type?content->type:""));
+  if (soap_send3(soap, "\r\n--", soap->mime.boundary, "\r\n"))
+    return soap->error;
+  if (content->type && soap_send3(soap, "Content-Type: ", content->type, "\r\n"))
+    return soap->error;
+  s = soap_str_code(mime_codes, content->encoding);
+  if (s && soap_send3(soap, "Content-Transfer-Encoding: ", s, "\r\n"))
+    return soap->error;
+  if (content->id && soap_send3(soap, "Content-ID: ", content->id, "\r\n"))
+    return soap->error;
+  if (content->location && soap_send3(soap, "Content-Location: ", content->location, "\r\n"))
+    return soap->error;
+  if (content->description && soap_send3(soap, "Content-Description: ", content->description, "\r\n"))
+    return soap->error;
+  return soap_send_raw(soap, "\r\n", 2);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_putmime(struct soap *soap)
+{ struct soap_multipart *content;
+  if (!(soap->mode & SOAP_ENC_MIME) || !soap->mime.boundary)
+    return SOAP_OK;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending MIME attachments\n"));
+  for (content = soap->mime.first; content; content = content->next)
+    if (soap_putmimehdr(soap, content)
+     || soap_send_raw(soap, content->ptr, content->size))
+      return soap->error;
+  return soap_send3(soap, "\r\n--", soap->mime.boundary, "--");
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_dime(struct soap *soap)
+{ soap->omode |= SOAP_ENC_DIME;
+  soap->dime.first = NULL;
+  soap->dime.last = NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_mime(struct soap *soap, const char *boundary, const char *start)
+{ soap->omode |= SOAP_ENC_MIME;
+  soap->mime.first = NULL;
+  soap->mime.last = NULL;
+  soap->mime.boundary = soap_strdup(soap, boundary);
+  soap->mime.start = soap_strdup(soap, start);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_clr_dime(struct soap *soap)
+{ soap->omode &= ~SOAP_ENC_DIME;
+  soap->dime.first = NULL;
+  soap->dime.last = NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_clr_mime(struct soap *soap)
+{ soap->omode &= ~SOAP_ENC_MIME;
+  soap->mime.first = NULL;
+  soap->mime.last = NULL;
+  soap->mime.boundary = NULL;
+  soap->mime.start = NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+static struct soap_multipart*
+soap_new_multipart(struct soap *soap, struct soap_multipart **first, struct soap_multipart **last, char *ptr, size_t size)
+{ struct soap_multipart *content;
+  content = (struct soap_multipart*)soap_malloc(soap, sizeof(struct soap_multipart));
+  if (content)
+  { content->next = NULL;
+    content->ptr = ptr;
+    content->size = size;
+    content->id = NULL;
+    content->type = NULL;
+    content->options = NULL;
+    content->encoding = SOAP_MIME_NONE;
+    content->location = NULL;
+    content->description = NULL;
+    if (!*first)
+      *first = content;
+    if (*last)
+      (*last)->next = content;
+    *last = content;
+  }
+  return content;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_set_dime_attachment(struct soap *soap, char *ptr, size_t size, const char *type, const char *id, unsigned short optype, const char *option)
+{ struct soap_multipart *content = soap_new_multipart(soap, &soap->dime.first, &soap->dime.last, ptr, size);
+  if (!content)
+    return SOAP_EOM;
+  content->id = soap_strdup(soap, id);
+  content->type = soap_strdup(soap, type);
+  content->options = soap_dime_option(soap, optype, option);
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_set_mime_attachment(struct soap *soap, char *ptr, size_t size, enum soap_mime_encoding encoding, const char *type, const char *id, const char *location, const char *description)
+{ struct soap_multipart *content = soap_new_multipart(soap, &soap->mime.first, &soap->mime.last, ptr, size);
+  if (!content)
+    return SOAP_EOM;
+  content->id = soap_strdup(soap, id);
+  content->type = soap_strdup(soap, type);
+  content->encoding = encoding;
+  content->location = soap_strdup(soap, location);
+  content->description = soap_strdup(soap, description);
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+SOAP_FMAC1
+struct soap_multipart*
+SOAP_FMAC2
+soap_next_multipart(struct soap_multipart *content)
+{ if (content)
+    return content->next;
+  return NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+static void
+soap_select_mime_boundary(struct soap *soap)
+{ while (!soap->mime.boundary || soap_valid_mime_boundary(soap))
+  { register char *s = soap->mime.boundary;
+    register size_t n = 0;
+    if (s)
+      n = strlen(s);
+    if (n < 16)
+    { n = 72;
+      s = soap->mime.boundary = (char*)soap_malloc(soap, n + 1);
+      if (!s)
+        return;
+    }
+    strcpy(s, "<>");
+    s += 2;
+    n -= 4;
+    while (n)
+    { *s++ = soap_base64o[soap_random & 0x3F];
+      n--;
+    }
+    strcpy(s, "<>");
+  }
+  if (!soap->mime.start)
+    soap->mime.start = "<SOAP-ENV:Envelope>";
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEANER
+#ifndef PALM_1
+static int
+soap_valid_mime_boundary(struct soap *soap)
+{ register struct soap_multipart *content;
+  register size_t k = strlen(soap->mime.boundary);
+  for (content = soap->mime.first; content; content = content->next)
+  { if (content->ptr && content->size >= k)
+    { register const char *p = (const char*)content->ptr; 
+      register size_t i;
+      for (i = 0; i < content->size - k; i++, p++)
+        if (!strncmp(p, soap->mime.boundary, k))
+          return SOAP_ERR;
+    }
+  }
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+
+#ifdef WITH_COOKIES
+/******************************************************************************/
+SOAP_FMAC1
+size_t
+SOAP_FMAC2
+soap_encode_cookie(const char *s, char *t, size_t len)
+{ register int c;
+  register size_t n = len;
+  while ((c = *s++) && --n > 0)
+  { if (c > ' ' && c < 128 && !strchr("()<>@,;:\\\"/[]?={}", c))
+      *t++ = c;
+    else if (n > 2)
+    { *t++ = '%';
+      *t++ = (c >> 4) + (c > 159 ? '7' : '0');
+      c &= 0xF;
+      *t++ = c + (c > 9 ? '7' : '0');
+      n -= 2;
+    }
+    else
+      break;
+  }
+  *t = '\0';
+  return len - n;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+struct soap_cookie*
+SOAP_FMAC2
+soap_cookie(struct soap *soap, const char *name, const char *domain, const char *path)
+{ struct soap_cookie *p;
+  size_t n;
+  if (!domain)
+    domain = soap->cookie_domain;
+  if (!path)
+    path = soap->cookie_path;
+  if (*path == '/')
+    path++;
+  n = strlen(path);
+  for (p = soap->cookies; p; p = p->next)
+    if (!strcmp(p->name, name)
+     && domain
+     && p->domain
+     && !strcmp(p->domain, domain)
+     && !strncmp(p->path, path, n))
+      break;
+  return p;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+struct soap_cookie*
+SOAP_FMAC2
+soap_set_cookie(struct soap *soap, const char *name, const char *value, const char *domain, const char *path)
+{ struct soap_cookie **p, *q;
+  int n;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set cookie: %s=%s domain=%s path=%s\n", name, value?value:"", domain?domain:"", path?path:""));
+  if (!domain)
+    domain = soap->cookie_domain;
+  if (!path)
+    path = soap->cookie_path;
+  if (!path)
+  { soap_set_receiver_error(soap, "Cookie path not set", NULL, SOAP_HTTP_ERROR);
+    return NULL;
+  }
+  if (*path == '/')
+    path++;
+  q = soap_cookie(soap, name, domain, path);
+  if (!q)
+  { if ((q = (struct soap_cookie*)SOAP_MALLOC(soap, sizeof(struct soap_cookie))))
+    { if ((q->name = (char*)SOAP_MALLOC(soap, strlen(name)+1)))
+        strcpy(q->name, name);
+      q->value = NULL;
+      q->domain = NULL;
+      q->path = NULL;
+      q->expire = -1;
+      q->version = 0;
+      q->secure = 0;
+      q->modified = 0;
+      for (p = &soap->cookies, n = soap->cookie_max; *p && n; p = &(*p)->next, n--)
+        if (!strcmp((*p)->name, name) && (*p)->path && strcmp((*p)->path, path) < 0)
+          break;
+      if (n)
+      { q->next = *p;
+        *p = q;
+      }
+      else
+      { SOAP_FREE(soap, q->name);
+        SOAP_FREE(soap, q);
+        q = NULL;
+      }
+    }
+  }
+  else
+    q->modified = 1;
+  if (q)
+  { if (q->value)
+    { SOAP_FREE(soap, q->value);
+      q->value = NULL;
+    }
+    if (q->domain)
+    { SOAP_FREE(soap, q->domain);
+      q->domain = NULL;
+    }
+    if (q->path)
+    { SOAP_FREE(soap, q->path);
+      q->path = NULL;
+    }
+    if (value && *value && (q->value = (char*)SOAP_MALLOC(soap, strlen(value)+1)))
+      strcpy(q->value, value);
+    if (domain && *domain && (q->domain = (char*)SOAP_MALLOC(soap, strlen(domain)+1)))
+      strcpy(q->domain, domain);
+    if (path && *path && (q->path = (char*)SOAP_MALLOC(soap, strlen(path)+1)))
+      strcpy(q->path, path);
+    q->session = 1;
+    q->env = 0;
+  }
+  return q;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_clr_cookie(struct soap *soap, const char *name, const char *domain, const char *path)
+{ struct soap_cookie **p, *q;
+  if (!domain)
+    domain = soap->cookie_domain;
+  if (!domain)
+  { soap_set_receiver_error(soap, "Cookie domain not set", NULL, SOAP_HTTP_ERROR);
+    return;
+  }
+  if (!path)
+    path = soap->cookie_path;
+  if (!path)
+  { soap_set_receiver_error(soap, "Cookie path not set", NULL, SOAP_HTTP_ERROR);
+    return;
+  }
+  if (*path == '/')
+    path++;
+  for (p = &soap->cookies, q = *p; q; q = *p)
+    if (!strcmp(q->name, name) && !strcmp(q->domain, domain) && !strncmp(q->path, path, strlen(q->path)))
+    { if (q->value)
+        SOAP_FREE(soap, q->value);
+      if (q->domain)
+        SOAP_FREE(soap, q->domain);
+      if (q->path)
+        SOAP_FREE(soap, q->path);
+      *p = q->next;
+      SOAP_FREE(soap, q);
+    }
+    else
+      p = &q->next;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_cookie_value(struct soap *soap, const char *name, const char *domain, const char *path)
+{ struct soap_cookie *p;
+  if ((p = soap_cookie(soap, name, domain, path)))
+    return p->value;
+  return NULL;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+char *
+SOAP_FMAC2
+soap_env_cookie_value(struct soap *soap, const char *name, const char *domain, const char *path)
+{ struct soap_cookie *p;
+  if ((p = soap_cookie(soap, name, domain, path)) && p->env)
+    return p->value;
+  return NULL;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+long
+SOAP_FMAC2
+soap_cookie_expire(struct soap *soap, const char *name, const char *domain, const char *path)
+{ struct soap_cookie *p;
+  if ((p = soap_cookie(soap, name, domain, path)))
+    return p->expire;
+  return -1;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_set_cookie_expire(struct soap *soap, const char *name, long expire, const char *domain, const char *path)
+{ struct soap_cookie *p;
+  if ((p = soap_cookie(soap, name, domain, path)))
+  { p->expire = expire;
+    p->modified = 1;
+    return SOAP_OK;
+  }
+  return SOAP_ERR;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_set_cookie_session(struct soap *soap, const char *name, const char *domain, const char *path)
+{ struct soap_cookie *p;
+  if ((p = soap_cookie(soap, name, domain, path)))
+  { p->session = 1;
+    p->modified = 1;
+    return SOAP_OK;
+  }
+  return SOAP_ERR;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_clr_cookie_session(struct soap *soap, const char *name, const char *domain, const char *path)
+{ struct soap_cookie *p;
+  if ((p = soap_cookie(soap, name, domain, path)))
+  { p->session = 0;
+    p->modified = 1;
+    return SOAP_OK;
+  }
+  return SOAP_ERR;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_putsetcookies(struct soap *soap)
+{ struct soap_cookie *p;
+  char *s, tmp[4096];
+  const char *t;
+  for (p = soap->cookies; p; p = p->next)
+  { if (p->modified || !p->env)
+    { s = tmp;
+      if (p->name)
+        s += soap_encode_cookie(p->name, s, tmp-s+4064);
+      if (p->value && *p->value)
+      { *s++ = '=';
+        s += soap_encode_cookie(p->value, s, tmp-s+4064);
+      }
+      if (p->domain && (int)strlen(p->domain) < tmp-s+4064)
+        sprintf(s, ";Domain=\"%s\"", p->domain);
+      else if (soap->cookie_domain && (int)strlen(soap->cookie_domain) < tmp-s+4064)
+        sprintf(s, ";Domain=\"%s\"", soap->cookie_domain);
+      strcat(s, ";Path=\"/");
+      if (p->path)
+        t = p->path;
+      else
+        t = soap->cookie_path;
+      if (t)
+      { if (*t == '/')
+          t++;
+        if ((int)strlen(t) < tmp-s+4064)
+          strcat(s, t);
+      }
+      s += strlen(s);
+      *s++ = '"';
+      if (p->version > 0)
+        sprintf(s, ";Version=%u", p->version);
+      if (p->expire >= 0)
+        sprintf(s, ";Max-Age=%ld", p->expire);
+      if (p->secure)
+        strcat(s, ";Secure");
+      DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set-Cookie: %s\n", tmp));
+      if ((soap->error = soap->fposthdr(soap, "Set-Cookie", tmp)))
+        return soap->error;
+    }
+  }
+  return SOAP_OK;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_putcookies(struct soap *soap, const char *domain, const char *path, int secure)
+{ struct soap_cookie **p, *q;
+  unsigned int version = 0;
+  time_t now = time(NULL);
+  char *s, tmp[4096];
+  p = &soap->cookies;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending cookies for domain=%s path=%s\n", domain, path));
+  if (*path == '/')
+    path++;
+  while ((q = *p))
+  { if (q->expire && now > q->expire)
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie %s expired\n", q->name));
+      SOAP_FREE(soap, q->name);
+      if (q->value)
+        SOAP_FREE(soap, q->value);
+      if (q->domain)
+        SOAP_FREE(soap, q->domain);
+      if (q->path)
+        SOAP_FREE(soap, q->path);
+      *p = q->next;
+      SOAP_FREE(soap, q);
+    }
+    else
+    { size_t domlen = 0;
+      if (q->domain)
+      { const char *s = strchr(q->domain, ':');
+        if (s)
+	  domlen = s - q->domain;
+	else
+          domlen = strlen(q->domain);
+      }
+      if ((!q->domain || !strncmp(q->domain, domain, domlen))
+          && (!q->path || !strncmp(q->path, path, strlen(q->path)))
+          && (!q->secure || secure))
+      { s = tmp;
+        if (q->version != version)
+        { sprintf(s, "$Version=%u;", q->version);
+          version = q->version;
+        }
+        if (q->name)
+          s += soap_encode_cookie(q->name, s, tmp-s+4080);
+        if (q->value && *q->value)
+        { *s++ = '=';
+          s += soap_encode_cookie(q->value, s, tmp-s+4080);
+        }
+        if (q->path && (int)strlen(q->path) < tmp-s+4080)
+        { sprintf(s, ";$Path=\"/%s\"", (*q->path == '/' ? q->path + 1 : q->path));
+          s += strlen(s);
+        }
+        if (q->domain && (int)strlen(q->domain) < tmp-s+4080)
+          sprintf(s, ";$Domain=\"%s\"", q->domain);
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie: %s\n", tmp));
+        if ((soap->error = soap->fposthdr(soap, "Cookie", tmp)))
+          return soap->error;
+      }
+      p = &q->next;
+    }
+  }
+  return SOAP_OK;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_getcookies(struct soap *soap, const char *val)
+{ struct soap_cookie *p = NULL, *q;
+  const char *s;
+  char *t, tmp[4096]; /* cookie size is up to 4096 bytes [RFC2109] */
+  char *domain = NULL;
+  char *path = NULL;
+  unsigned int version = 0;
+  time_t now = time(NULL);
+  if (!val)
+    return;
+  s = val;
+  while (*s)
+  { s = soap_decode_key(tmp, sizeof(tmp), s);
+    if (!soap_tag_cmp(tmp, "$Version"))
+    { if ((s = soap_decode_val(tmp, sizeof(tmp), s)))
+      { if (p)
+          p->version = (int)atol(tmp);
+        else
+          version = (int)atol(tmp);
+      }
+    }
+    else if (!soap_tag_cmp(tmp, "$Path"))
+    { s = soap_decode_val(tmp, sizeof(tmp), s);
+      if (*tmp)
+      { if ((t = (char*)SOAP_MALLOC(soap, strlen(tmp)+1)))
+          strcpy(t, tmp);
+      }
+      else
+        t = NULL;
+      if (p)
+      { if (p->path)
+          SOAP_FREE(soap, p->path);
+        p->path = t;
+      }
+      else
+      { if (path)
+          SOAP_FREE(soap, path);
+        path = t;
+      }
+    }
+    else if (!soap_tag_cmp(tmp, "$Domain"))
+    { s = soap_decode_val(tmp, sizeof(tmp), s);
+      if (*tmp)
+      { if ((t = (char*)SOAP_MALLOC(soap, strlen(tmp)+1)))
+          strcpy(t, tmp);
+      }
+      else
+        t = NULL;
+      if (p)
+      { if (p->domain)
+          SOAP_FREE(soap, p->domain);
+	p->domain = t;
+      }
+      else
+      { if (domain)
+          SOAP_FREE(soap, domain);
+        domain = t;
+      }
+    }
+    else if (p && !soap_tag_cmp(tmp, "Path"))
+    { if (p->path)
+        SOAP_FREE(soap, p->path);
+      s = soap_decode_val(tmp, sizeof(tmp), s);
+      if (*tmp)
+      { if ((p->path = (char*)SOAP_MALLOC(soap, strlen(tmp)+1)))
+          strcpy(p->path, tmp);
+      }
+      else
+        p->path = NULL;
+    }
+    else if (p && !soap_tag_cmp(tmp, "Domain"))
+    { if (p->domain)
+        SOAP_FREE(soap, p->domain);
+      s = soap_decode_val(tmp, sizeof(tmp), s);
+      if (*tmp)
+      { if ((p->domain = (char*)SOAP_MALLOC(soap, strlen(tmp)+1)))
+          strcpy(p->domain, tmp);
+      }
+      else
+        p->domain = NULL;
+    }
+    else if (p && !soap_tag_cmp(tmp, "Version"))
+    { s = soap_decode_val(tmp, sizeof(tmp), s);
+      p->version = (unsigned int)atol(tmp);
+    }
+    else if (p && !soap_tag_cmp(tmp, "Max-Age"))
+    { s = soap_decode_val(tmp, sizeof(tmp), s);
+      p->expire = now + atol(tmp);
+    }
+    else if (p && !soap_tag_cmp(tmp, "Expires"))
+    { struct tm T;
+      char a[3]; 
+      static const char mns[] = "anebarprayunulugepctovec";
+      s = soap_decode_val(tmp, sizeof(tmp), s);
+      if (strlen(tmp) > 20)
+      { memset((void*)&T, 0, sizeof(T));
+        a[0] = tmp[4];
+        a[1] = tmp[5];
+        a[2] = '\0';
+        T.tm_mday = (int)atol(a);
+        a[0] = tmp[8];
+        a[1] = tmp[9];
+        T.tm_mon = (strstr(mns, a) - mns) / 2;
+        a[0] = tmp[11];
+        a[1] = tmp[12];
+        T.tm_year = 100 + (int)atol(a);
+        a[0] = tmp[13];
+        a[1] = tmp[14];
+        T.tm_hour = (int)atol(a);
+        a[0] = tmp[16];
+        a[1] = tmp[17];
+        T.tm_min = (int)atol(a);
+        a[0] = tmp[19];
+        a[1] = tmp[20];
+        T.tm_sec = (int)atol(a);
+        p->expire = soap_timegm(&T);
+      }
+    }
+    else if (p && !soap_tag_cmp(tmp, "Secure"))
+      p->secure = 1;
+    else
+    { if (p)
+      { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value?p->value:"", p->domain?p->domain:"", p->path?p->path:"", p->expire, p->secure));
+        if ((q = soap_set_cookie(soap, p->name, p->value, p->domain, p->path)))
+        { q->version = p->version;
+          q->expire = p->expire;
+          q->secure = p->secure;
+          q->env = 1;
+        }
+        if (p->name)
+          SOAP_FREE(soap, p->name);
+        if (p->value)
+          SOAP_FREE(soap, p->value);
+        if (p->domain)
+          SOAP_FREE(soap, p->domain);
+        if (p->path)
+          SOAP_FREE(soap, p->path);
+        SOAP_FREE(soap, p);
+      }
+      if ((p = (struct soap_cookie*)SOAP_MALLOC(soap, sizeof(struct soap_cookie))))
+      { p->name = (char*)SOAP_MALLOC(soap, strlen(tmp)+1);
+        strcpy(p->name, tmp);
+        s = soap_decode_val(tmp, sizeof(tmp), s);
+        if (*tmp)
+        { p->value = (char*)SOAP_MALLOC(soap, strlen(tmp)+1);
+          strcpy(p->value, tmp);
+        }
+        else
+          p->value = NULL;
+        p->domain = domain;
+        p->path = path;
+        p->expire = 0;
+        p->secure = 0;
+        p->version = version;
+      }
+    }
+  }
+  if (p)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value?p->value:"", p->domain?p->domain:"", p->path?p->path:"", p->expire, p->secure));
+    if ((q = soap_set_cookie(soap, p->name, p->value, p->domain, p->path)))
+    { q->version = p->version;
+      q->expire = p->expire;
+      q->secure = p->secure;
+      q->env = 1;
+    }
+    if (p->name)
+      SOAP_FREE(soap, p->name);
+    if (p->value)
+      SOAP_FREE(soap, p->value);
+    if (p->domain)
+      SOAP_FREE(soap, p->domain);
+    if (p->path)
+      SOAP_FREE(soap, p->path);
+    SOAP_FREE(soap, p);
+  }
+  if (domain)
+    SOAP_FREE(soap, domain);
+  if (path)
+    SOAP_FREE(soap, path);
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_getenv_cookies(struct soap *soap)
+{ struct soap_cookie *p;
+  const char *s;
+  char key[4096], val[4096]; /* cookie size is up to 4096 bytes [RFC2109] */
+  if (!(s = getenv("HTTP_COOKIE")))
+    return SOAP_ERR;
+  do
+  { s = soap_decode_key(key, sizeof(key), s);
+    s = soap_decode_val(val, sizeof(val), s);
+    p = soap_set_cookie(soap, key, val, NULL, NULL);
+    if (p)
+      p->env = 1;
+  } while (*s);
+  return SOAP_OK;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+struct soap_cookie*
+SOAP_FMAC2
+soap_copy_cookies(struct soap *soap)
+{ struct soap_cookie *p, **q, *r;
+  q = &r;
+  for (p = soap->cookies; p; p = p->next)
+  { if (!(*q = (struct soap_cookie*)SOAP_MALLOC(soap, sizeof(struct soap_cookie))))
+      return r;
+    **q = *p;
+    if (p->name)
+    { if (((*q)->name = (char*)SOAP_MALLOC(soap, strlen(p->name)+1)))
+        strcpy((*q)->name, p->name);
+    }
+    if (p->value)
+    { if (((*q)->value = (char*)SOAP_MALLOC(soap, strlen(p->value)+1)))
+        strcpy((*q)->value, p->value);
+    }
+    if (p->domain)
+    { if (((*q)->domain = (char*)SOAP_MALLOC(soap, strlen(p->domain)+1)))
+        strcpy((*q)->domain, p->domain);
+    }
+    if (p->path)
+    { if (((*q)->path = (char*)SOAP_MALLOC(soap, strlen(p->path)+1)))
+        strcpy((*q)->path, p->path);
+    }
+    q = &(*q)->next;
+  }
+  *q = NULL;
+  return r;
+}
+
+/******************************************************************************/
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_free_cookies(struct soap *soap)
+{ struct soap_cookie *p;
+  for (p = soap->cookies; p; p = soap->cookies)
+  { soap->cookies = p->next;
+    SOAP_FREE(soap, p->name);
+    if (p->value)
+      SOAP_FREE(soap, p->value);
+    if (p->domain)
+      SOAP_FREE(soap, p->domain);
+    if (p->path)
+      SOAP_FREE(soap, p->path);
+    SOAP_FREE(soap, p);
+  }
+}
+
+/******************************************************************************/
+#endif /* WITH_COOKIES */
+
+/******************************************************************************/
+#ifdef WITH_GZIP
+#ifndef PALM_1
+static int
+soap_getgziphdr(struct soap *soap)
+{ int i;
+  soap_wchar c, f = 0;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get gzip header\n"));
+  for (i = 0; i < 9; i++)
+  { if ((int)(c = soap_get1(soap) == EOF))
+      return soap->error = SOAP_EOF;
+    if (i == 2)
+      f = c;
+  }
+  if (f & 0x04) /* FEXTRA */
+  { for (i = soap_get1(soap) | (soap_get1(soap) << 8); i; i--)
+      if ((int)soap_get1(soap) == EOF)
+        return soap->error = SOAP_EOF;
+  }
+  if (f & 0x08) /* FNAME */
+    do
+      c = soap_get1(soap);
+    while (c && (int)c != EOF);
+  if ((int)c != EOF && (f & 0x10)) /* FCOMMENT */
+    do
+      c = soap_get1(soap);
+    while (c && (int)f != EOF);
+  if ((int)c != EOF && (f & 0x01)) /* FHCRC */
+  { if ((int)(c = soap_get1(soap)) != EOF)
+      c = soap_get1(soap);
+  }
+  if ((int)c == EOF)
+    return soap->error = SOAP_EOF;
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_begin_recv(struct soap *soap)
+{ soap_wchar c;
+  soap->error = SOAP_OK;
+  soap_free(soap);
+  soap_set_local_namespaces(soap);
+  soap->version = 0;	/* don't assume we're parsing SOAP content by default */
+#ifndef WITH_NOIDREF
+  soap_free_iht(soap);
+#endif
+  if ((soap->imode & SOAP_IO) == SOAP_IO_CHUNK)
+    soap->omode |= SOAP_IO_CHUNK;
+  soap->imode &= ~SOAP_IO;
+  soap->mode = soap->imode;
+  if (!soap->keep_alive)
+  { soap->buflen = 0;
+    soap->bufidx = 0;
+  }
+  if (!(soap->mode & SOAP_IO_KEEPALIVE))
+    soap->keep_alive = 0;
+  soap->ahead = 0;
+  soap->peeked = 0;
+  soap->level = 0;
+  soap->part = SOAP_BEGIN;
+  soap->alloced = 0;
+  soap->count = 0;
+  soap->length = 0;
+  soap->cdata = 0;
+  *soap->endpoint = '\0';
+  soap->action = NULL;
+#ifndef WITH_LEANER
+  soap->dom = NULL;
+  soap->dime.chunksize = 0;
+  soap->dime.buflen = 0;
+  soap->dime.list = NULL;
+  soap->dime.first = NULL;
+  soap->dime.last = NULL;
+  soap->mime.list = NULL;
+  soap->mime.first = NULL;
+  soap->mime.last = NULL;
+  soap->mime.boundary = NULL;
+  soap->mime.start = NULL;
+  soap->xlist = NULL;
+#endif
+#ifdef WIN32
+#ifndef UNDER_CE
+#ifndef WITH_FASTCGI
+  if (!soap_valid_socket(soap->socket))
+#ifdef __BORLANDC__
+    setmode((SOAP_SOCKET)soap->recvfd, O_BINARY);
+#else
+    _setmode((SOAP_SOCKET)soap->recvfd, _O_BINARY);
+#endif
+#endif
+#endif
+#endif
+#ifdef WITH_ZLIB
+  soap->mode &= ~SOAP_ENC_ZLIB;
+  soap->zlib_in = SOAP_ZLIB_NONE;
+  soap->zlib_out = SOAP_ZLIB_NONE;
+  soap->d_stream.next_in = Z_NULL;
+  soap->d_stream.avail_in = 0;
+  soap->d_stream.next_out = (Byte*)soap->buf;
+  soap->d_stream.avail_out = SOAP_BUFLEN;
+  soap->z_ratio_in = 1.0;
+#endif
+#ifndef WITH_LEANER
+  if (soap->fprepareinit)
+    soap->fprepareinit(soap);
+#endif
+  c = soap_getchar(soap);
+#ifdef WITH_GZIP
+  if (c == 0x1F)
+  { if (soap_getgziphdr(soap))
+      return soap->error;
+    if (inflateInit2(&soap->d_stream, -MAX_WBITS) != Z_OK)
+      return soap->error = SOAP_ZLIB_ERROR;
+    soap->zlib_state = SOAP_ZLIB_INFLATE;
+    soap->mode |= SOAP_ENC_ZLIB;
+    soap->zlib_in = SOAP_ZLIB_GZIP;
+    soap->z_crc = crc32(0L, NULL, 0);
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip initialized\n"));
+    memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN);
+    /* should not chunk over plain transport, so why bother to check? */
+    /* if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK) */
+    /*   soap->z_buflen = soap->bufidx; */
+    /* else */
+    soap->d_stream.next_in = (Byte*)(soap->z_buf + soap->bufidx);
+    soap->d_stream.avail_in = soap->buflen - soap->bufidx;
+    soap->z_buflen = soap->buflen;
+    soap->buflen = soap->bufidx;
+    c = soap_getchar(soap);
+  }  
+#endif
+#ifndef WITH_LEANER
+  if (c == '-' && soap_get0(soap) == '-')
+    soap->mode |= SOAP_ENC_MIME;
+  else if ((c & 0xFFFC) == (SOAP_DIME_VERSION | SOAP_DIME_MB) && (soap_get0(soap) & 0xFFF0) == 0x20)
+    soap->mode |= SOAP_ENC_DIME;
+  else
+#endif
+  { while (soap_blank(c))
+      c = soap_getchar(soap);
+  }
+  if ((int)c == EOF)
+    return soap->error = SOAP_EOF;
+  soap_unget(soap, c);
+#ifndef WITH_NOHTTP
+  /* if not XML or (start of)BOM or MIME/DIME/ZLIB, assume HTTP header */
+  if (c != '<' && c != 0xEF && !(soap->mode & (SOAP_ENC_MIME | SOAP_ENC_DIME | SOAP_ENC_ZLIB)))
+  { soap->mode &= ~SOAP_IO;
+    soap->error = soap->fparse(soap);
+    if (soap->error && soap->error < SOAP_STOP)
+    { soap->keep_alive = 0; /* force close later */
+      return soap->error;
+    }
+    if ((soap->mode & SOAP_IO) == SOAP_IO_CHUNK)
+    { soap->chunkbuflen = soap->buflen;
+      soap->buflen = soap->bufidx;
+      soap->chunksize = 0;
+    }
+#ifndef WITH_LEANER
+    else if (soap->fpreparerecv && soap->buflen != soap->bufidx)
+      soap->fpreparerecv(soap, soap->buf + soap->bufidx, soap->buflen - soap->bufidx);
+#endif
+#ifdef WITH_ZLIB
+    if (soap->zlib_in != SOAP_ZLIB_NONE)
+    { /* fparse should not use soap_unget to push back last char */
+#ifdef WITH_GZIP
+      c = soap_get1(soap);
+      if (c == 0x1F)
+      { if (soap_getgziphdr(soap))
+          return soap->error;
+        if (inflateInit2(&soap->d_stream, -MAX_WBITS) != Z_OK)
+          return soap->error = SOAP_ZLIB_ERROR;
+        soap->zlib_state = SOAP_ZLIB_INFLATE;
+        soap->z_crc = crc32(0L, NULL, 0);
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "gzip initialized\n"));
+      }
+      else
+      { soap_revget1(soap);
+#else
+      {
+#endif
+        if (inflateInit(&soap->d_stream) != Z_OK)
+          return soap->error = SOAP_ZLIB_ERROR;
+        soap->zlib_state = SOAP_ZLIB_INFLATE;
+        DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflate initialized\n"));
+      }
+      soap->mode |= SOAP_ENC_ZLIB;
+      memcpy(soap->z_buf, soap->buf, SOAP_BUFLEN);
+      soap->d_stream.next_in = (Byte*)(soap->z_buf + soap->bufidx);
+      soap->d_stream.avail_in = soap->buflen - soap->bufidx;
+      soap->z_buflen = soap->buflen;
+      soap->buflen = soap->bufidx;
+    }
+#endif
+    if (soap->error)
+    { if (soap->error == SOAP_FORM && soap->fform)
+      { soap->error = soap->fform(soap);
+        if (soap->error == SOAP_OK)
+          soap->error = SOAP_STOP; /* prevents further processing */
+      }
+      return soap->error;
+    }
+  }
+#endif
+#ifndef WITH_LEANER
+  if (soap->mode & SOAP_ENC_MIME)
+  { if (soap_getmimehdr(soap))
+      return soap->error;
+    if (soap_get_header_attribute(soap, soap->mime.first->type, "application/dime"))
+      soap->mode |= SOAP_ENC_DIME;
+  }
+  if (soap->mode & SOAP_ENC_DIME)
+  { if (soap_getdimehdr(soap))
+      return soap->error;
+    if (soap->dime.flags & SOAP_DIME_CF)
+    { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunked DIME SOAP message\n"));
+      soap->dime.chunksize = soap->dime.size;
+      if (soap->buflen - soap->bufidx >= soap->dime.chunksize)
+      { soap->dime.buflen = soap->buflen;
+        soap->buflen = soap->bufidx + soap->dime.chunksize;
+      }
+      else
+        soap->dime.chunksize -= soap->buflen - soap->bufidx;
+    }
+    soap->count = soap->buflen - soap->bufidx;
+  }
+#endif
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static int
+http_parse(struct soap *soap)
+{ char header[SOAP_HDRLEN], *s;
+  unsigned short get = 0, status = 0, k = 0;
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Waiting for HTTP request/response...\n"));
+  *soap->endpoint = '\0';
+  soap->length = 0;
+  soap->userid = NULL;
+  soap->passwd = NULL;
+  soap->action = NULL;
+  soap->authrealm = NULL;
+  do
+  { if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf)))
+      return soap->error;
+    DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP status: %s\n", soap->msgbuf));
+    for (;;)
+    { if (soap_getline(soap, header, SOAP_HDRLEN))
+      { if (soap->error == SOAP_EOF)
+	{ soap->error = SOAP_OK;
+          DBGLOG(TEST,SOAP_MESSAGE(fdebug, "EOF in HTTP header, continue anyway\n"));
+	  break;
+	}
+        return soap->error;
+      }
+      if (!*header)
+        break;
+      DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP header: %s\n", header));
+      s = strchr(header, ':');
+      if (s)
+      { *s = '\0';
+        do s++;
+        while (*s && *s <= 32);
+        if ((soap->error = soap->fparsehdr(soap, header, s)))
+        { if (soap->error < SOAP_STOP)
+	    return soap->error;
+	  status = soap->error;
+	  soap->error = SOAP_OK;
+        }
+      }
+    }
+    if ((s = strchr(soap->msgbuf, ' ')))
+    { k = (unsigned short)soap_strtoul(s, &s, 10);
+      if (!soap_blank(*s))
+        k = 0;
+    }
+    else
+      k = 0;
+  } while (k == 100);
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Finished HTTP header parsing\n"));
+  s = strstr(soap->msgbuf, "HTTP/");
+  if (s && s[7] != '1')
+  { if (soap->keep_alive == 1)
+      soap->keep_alive = 0;
+    if (k == 0 && (soap->omode & SOAP_IO) == SOAP_IO_CHUNK) /* k == 0 for HTTP request */
+    { soap->imode |= SOAP_IO_CHUNK;
+      soap->omode = (soap->omode & ~SOAP_IO) | SOAP_IO_STORE;
+    }
+  }
+  if (soap->keep_alive < 0)
+    soap->keep_alive = 1;
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Keep alive connection = %d\n", soap->keep_alive));
+  if (s && (((get = !strncmp(soap->msgbuf, "GET ", 4))) || !strncmp(soap->msgbuf, "POST ", 5)))
+  { size_t m = strlen(soap->endpoint);
+    size_t n = m + (s - soap->msgbuf) - 5 - (!get);
+    if (n >= sizeof(soap->endpoint))
+      n = sizeof(soap->endpoint) - 1;
+    strncpy(soap->path, soap->msgbuf + 4 + (!get), n - m);
+    soap->path[n - m] = '\0';
+    strcat(soap->endpoint, soap->path);
+    DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Target endpoint='%s'\n", soap->endpoint));
+    if (get)
+    { soap->error = soap->fget(soap);
+      if (soap->error == SOAP_OK)
+        soap->error = SOAP_STOP; /* prevents further processing */
+      return soap->error;
+    }
+    if (status)
+      return soap->error = status;
+    return SOAP_OK;
+  }
+  if (k == 0 || (k >= 200 && k <= 299) || k == 400 || k == 500)
+    return SOAP_OK;
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "HTTP error %d\n", k));
+  return soap_set_receiver_error(soap, "HTTP error", soap->msgbuf, k);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static int
+http_parse_header(struct soap *soap, const char *key, const char *val)
+{ if (!soap_tag_cmp(key, "Host"))
+  { 
+#ifdef WITH_OPENSSL
+    if (soap->imode & SOAP_ENC_SSL)
+      strcpy(soap->endpoint, "https://");
+    else
+#endif
+      strcpy(soap->endpoint, "http://");
+    strncat(soap->endpoint, val, sizeof(soap->endpoint) - 8);
+    soap->endpoint[sizeof(soap->endpoint) - 1] = '\0';
+  }
+#ifndef WITH_LEANER
+  else if (!soap_tag_cmp(key, "Content-Type"))
+  { if (soap_get_header_attribute(soap, val, "application/dime"))
+      soap->mode |= SOAP_ENC_DIME;
+    else if (soap_get_header_attribute(soap, val, "multipart/related")
+          || soap_get_header_attribute(soap, val, "multipart/form-data"))
+    { soap->mime.boundary = soap_strdup(soap, soap_get_header_attribute(soap, val, "boundary"));
+      soap->mime.start = soap_strdup(soap, soap_get_header_attribute(soap, val, "start"));
+      soap->mode |= SOAP_ENC_MIME;
+    }
+  }
+#endif
+  else if (!soap_tag_cmp(key, "Content-Length"))
+    soap->length = soap_strtoul(val, NULL, 10);
+  else if (!soap_tag_cmp(key, "Content-Encoding"))
+  { if (!soap_tag_cmp(val, "deflate"))
+#ifdef WITH_ZLIB
+      soap->zlib_in = SOAP_ZLIB_DEFLATE;
+#else
+      return SOAP_ZLIB_ERROR;
+#endif
+    else if (!soap_tag_cmp(val, "gzip"))
+#ifdef WITH_GZIP
+      soap->zlib_in = SOAP_ZLIB_GZIP;
+#else
+      return SOAP_ZLIB_ERROR;
+#endif
+  }
+#ifdef WITH_ZLIB
+  else if (!soap_tag_cmp(key, "Accept-Encoding"))
+  {
+#ifdef WITH_GZIP
+    if (strchr(val, '*') || soap_get_header_attribute(soap, val, "gzip"))
+      soap->zlib_out = SOAP_ZLIB_GZIP;
+    else
+#endif
+    if (strchr(val, '*') || soap_get_header_attribute(soap, val, "deflate"))
+      soap->zlib_out = SOAP_ZLIB_DEFLATE;
+    else
+      soap->zlib_out = SOAP_ZLIB_NONE;
+  }
+#endif
+  else if (!soap_tag_cmp(key, "Transfer-Encoding"))
+  { soap->mode &= ~SOAP_IO;
+    if (!soap_tag_cmp(val, "chunked"))
+      soap->mode |= SOAP_IO_CHUNK;
+  }
+  else if (!soap_tag_cmp(key, "Connection"))
+  { if (!soap_tag_cmp(val, "keep-alive"))
+      soap->keep_alive = -soap->keep_alive;
+    else if (!soap_tag_cmp(val, "close"))
+      soap->keep_alive = 0;
+  }
+#ifndef WITH_LEAN
+  else if (!soap_tag_cmp(key, "Authorization"))
+  { if (!soap_tag_cmp(val, "Basic *"))
+    { int n;
+      char *s;
+      soap_base642s(soap, val + 6, soap->tmpbuf, sizeof(soap->tmpbuf) - 1, &n);
+      soap->tmpbuf[n] = '\0';
+      if ((s = strchr(soap->tmpbuf, ':')))
+      { *s = '\0';
+	soap->userid = soap_strdup(soap, soap->tmpbuf);
+	soap->passwd = soap_strdup(soap, s + 1);
+      }
+    }
+  }
+  else if (!soap_tag_cmp(key, "WWW-Authenticate"))
+    soap->authrealm = soap_strdup(soap, soap_get_header_attribute(soap, val + 6, "realm"));
+  else if (!soap_tag_cmp(key, "Expect"))
+  { if (!soap_tag_cmp(val, "100-continue"))
+    { if ((soap->error = soap->fposthdr(soap, "HTTP/1.1 100 Continue", NULL))
+       || (soap->error = soap->fposthdr(soap, NULL, NULL)))
+        return soap->error;
+    }
+  }
+#endif
+  else if (!soap_tag_cmp(key, "SOAPAction"))
+  { if (*val == '"')
+    { soap->action = soap_strdup(soap, val + 1);
+      soap->action[strlen(soap->action) - 1] = '\0';
+    }
+  }
+  else if (!soap_tag_cmp(key, "Location"))
+  { strncpy(soap->endpoint, val, sizeof(soap->endpoint));
+    soap->endpoint[sizeof(soap->endpoint) - 1] = '\0';
+  }
+#ifdef WITH_COOKIES
+  else if (!soap_tag_cmp(key, "Cookie") || !soap_tag_cmp(key, "Set-Cookie"))
+    soap_getcookies(soap, val);
+#endif
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER)
+#ifndef PALM_1
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_get_header_attribute(struct soap *soap, const char *line, const char *key)
+{ register const char *s = line;
+  if (s)
+  { while (*s)
+    { register short flag;
+      s = soap_decode_key(soap->tmpbuf, sizeof(soap->tmpbuf), s);
+      flag = soap_tag_cmp(soap->tmpbuf, key);
+      s = soap_decode_val(soap->tmpbuf, sizeof(soap->tmpbuf), s);
+      if (!flag)
+        return soap->tmpbuf;
+    }
+  }
+  return NULL;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER)
+#ifndef PALM_1
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_decode_key(char *buf, size_t len, const char *val)
+{ return soap_decode(buf, len, val, "=,;");
+}
+#endif
+#endif
+
+/******************************************************************************/
+#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER)
+#ifndef PALM_1
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_decode_val(char *buf, size_t len, const char *val)
+{ if (*val != '=')
+  { *buf = '\0';
+    return val;
+  }
+  return soap_decode(buf, len, val + 1, ",;");
+}
+#endif
+#endif
+
+/******************************************************************************/
+#if !defined(WITH_NOHTTP) || !defined(WITH_LEANER)
+#ifndef PALM_1
+static const char*
+soap_decode(char *buf, size_t len, const char *val, const char *sep)
+{ const char *s;
+  char *t = buf;
+  for (s = val; *s; s++)
+    if (*s != ' ' && *s != '\t' && !strchr(sep, *s))
+      break;
+  if (*s == '"')
+  { s++;
+    while (*s && *s != '"' && --len)
+      *t++ = *s++;
+  }
+  else
+  { while (soap_notblank(*s) && !strchr(sep, *s) && --len)
+    { if (*s == '%')
+      { *t++ = ((s[1] >= 'A' ? (s[1] & 0x7) + 9 : s[1] - '0') << 4)
+              + (s[2] >= 'A' ? (s[2] & 0x7) + 9 : s[2] - '0');
+        s += 3;
+      }
+      else
+        *t++ = *s++;
+    }
+  }
+  *t = '\0';
+  while (*s && !strchr(sep, *s))
+    s++;
+  return s;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_envelope_begin_out(struct soap *soap)
+{
+#ifndef WITH_LEANER
+  size_t n = 0;
+  if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary && soap->mime.start)
+  { const char *s;
+    if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM))
+      s = "application/dime";
+    else if (soap->version == 2)
+      s = "application/soap+xml; charset=utf-8";
+    else
+      s = "text/xml; charset=utf-8";
+    sprintf(soap->tmpbuf, "--%s\r\nContent-Type: %s\r\nContent-Transfer-Encoding: binary\r\nContent-ID: %s\r\n\r\n", soap->mime.boundary, s, soap->mime.start);
+    n = strlen(soap->tmpbuf);
+    if (soap_send_raw(soap, soap->tmpbuf, n))
+      return soap->error;
+  }
+  if (soap->mode & SOAP_IO_LENGTH)
+    soap->dime.size = soap->count;	/* DIME in MIME correction */
+  if (!(soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_ENC_DIME))
+  { if (soap_putdimehdr(soap))
+      return soap->error;
+  }
+#endif
+  soap->part = SOAP_IN_ENVELOPE;
+  return soap_element_begin_out(soap, "SOAP-ENV:Envelope", 0, NULL);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_envelope_end_out(struct soap *soap)
+{ if (soap_element_end_out(soap, "SOAP-ENV:Envelope"))
+    return soap->error;
+#ifndef WITH_LEANER
+  if ((soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM))
+  { soap->dime.size = soap->count - soap->dime.size;	/* DIME in MIME correction */
+    sprintf(soap->id, soap->dime_id_format, 0);
+    soap->dime.id = soap->id;
+    if (soap->local_namespaces)
+    { if (soap->local_namespaces[0].out)
+        soap->dime.type = (char*)soap->local_namespaces[0].out;
+      else
+        soap->dime.type = (char*)soap->local_namespaces[0].ns;
+    }
+    soap->dime.options = NULL;
+    soap->dime.flags = SOAP_DIME_MB | SOAP_DIME_ABSURI;
+    if (!soap->dime.first)
+      soap->dime.flags |= SOAP_DIME_ME;
+    soap->count += 12 + ((strlen(soap->dime.id)+3)&(~3)) + ((strlen(soap->dime.type)+3)&(~3));
+  }
+  if ((soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM))
+    return soap_send_raw(soap, SOAP_STR_PADDING, -(long)soap->dime.size&3);
+#endif
+  soap->part = SOAP_END_ENVELOPE;
+  return SOAP_OK;
+} 
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_envelope_begin_in(struct soap *soap)
+{ register struct Namespace *p;
+  soap->part = SOAP_IN_ENVELOPE;
+  if (soap_element_begin_in(soap, "SOAP-ENV:Envelope", 0))
+    return soap->error = SOAP_VERSIONMISMATCH;
+  p = soap->local_namespaces;
+  if (p)
+  { const char *ns = p[0].out;
+    if (!ns)
+      ns = p[0].ns;
+    if (!strcmp(ns, soap_env1))
+    { soap->version = 1; /* make sure we use SOAP 1.1 */
+      if (p[1].out)
+        SOAP_FREE(soap, p[1].out);
+      if ((p[1].out = (char*)SOAP_MALLOC(soap, sizeof(soap_enc1))))
+        strcpy(p[1].out, soap_enc1);
+    }
+    else if (!strcmp(ns, soap_env2))
+    { soap->version = 2; /* make sure we use SOAP 1.2 */
+      if (p[1].out)
+        SOAP_FREE(soap, p[1].out);
+      if ((p[1].out = (char*)SOAP_MALLOC(soap, sizeof(soap_enc2))))
+        strcpy(p[1].out, soap_enc2);
+    }
+  }
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_envelope_end_in(struct soap *soap)
+{ soap->part = SOAP_END_ENVELOPE;
+  return soap_element_end_in(soap, "SOAP-ENV:Envelope");
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_body_begin_out(struct soap *soap)
+{ soap->part = SOAP_IN_BODY;
+  if (soap->version == 1)
+    soap->encoding = 1;
+#ifndef WITH_LEAN
+  if ((soap->mode & SOAP_XML_SEC) && soap_set_attr(soap, "wsu:Id", "Body"))
+    return soap->error;
+#endif
+  if (soap_element(soap, "SOAP-ENV:Body", 0, NULL))
+    return soap->error;
+  return soap_element_start_end_out(soap, NULL);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_body_end_out(struct soap *soap)
+{ if (soap_element_end_out(soap, "SOAP-ENV:Body"))
+    return soap->error;
+  soap->part = SOAP_END_BODY;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_body_begin_in(struct soap *soap)
+{ soap->part = SOAP_IN_BODY;
+  if (soap_element_begin_in(soap, "SOAP-ENV:Body", 0))
+    return soap->error;
+  if (!soap->body)
+    soap->part = SOAP_NO_BODY;
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_body_end_in(struct soap *soap)
+{ if (soap->part == SOAP_NO_BODY)
+    return SOAP_OK;
+  soap->part = SOAP_END_BODY;
+  return soap_element_end_in(soap, "SOAP-ENV:Body");
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_recv_header(struct soap *soap)
+{ if (soap_getheader(soap) && soap->error == SOAP_TAG_MISMATCH)
+    soap->error = SOAP_OK;
+  return soap->error;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_endpoint(struct soap *soap, const char *endpoint)
+{ register const char *s;
+  register size_t i, n;
+  soap->endpoint[0] = '\0';
+  soap->host[0] = '\0';
+  soap->path[0] = '/';
+  soap->path[1] = '\0';
+  soap->port = 80;
+  if (!endpoint || !*endpoint)
+    return;
+  if (!strncmp(endpoint, "https:", 6))
+    soap->port = 443;
+  strncpy(soap->endpoint, endpoint, sizeof(soap->endpoint) - 1);
+  s = strchr(endpoint, ':');
+  if (s && s[1] == '/' && s[2] == '/')
+    s += 3;
+  else
+    s = endpoint;
+  n = strlen(s);
+  if (n >= sizeof(soap->host))
+    n = sizeof(soap->host) - 1;
+#ifdef WITH_IPV6
+  if (s[0] == '[')
+  { s++;
+    for (i = 0; i < n; i++)
+    { soap->host[i] = s[i];
+      if (s[i] == ']')
+      { s++;
+        break; 
+      }
+    }
+  }
+  else
+  { for (i = 0; i < n; i++)
+    { soap->host[i] = s[i];
+      if (s[i] == '/' || s[i] == ':')
+        break; 
+    }
+  }
+#else
+  for (i = 0; i < n; i++)
+  { soap->host[i] = s[i];
+    if (s[i] == '/' || s[i] == ':')
+      break; 
+  }
+#endif
+  soap->host[i] = '\0';
+  if (s[i] == ':')
+  { soap->port = (int)atol(s + i + 1);
+    for (i++; i < n; i++)
+      if (s[i] == '/')
+        break;
+  }
+  if (s[i])
+  { strncpy(soap->path, s + i, sizeof(soap->path));
+    soap->path[sizeof(soap->path) - 1] = '\0';
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_connect(struct soap *soap, const char *endpoint, const char *action)
+{ return soap_connect_command(soap, SOAP_POST, endpoint, action);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_connect_command(struct soap *soap, int http_command, const char *endpoint, const char *action)
+{ char host[sizeof(soap->host)];
+  int port;
+  size_t count;
+  soap->error = SOAP_OK;
+  strcpy(host, soap->host); /* save to compare */
+  port = soap->port; /* save to compare */
+  soap_set_endpoint(soap, endpoint);
+#ifndef WITH_LEANER
+  if (soap->fconnect)
+  { if ((soap->error = soap->fconnect(soap, endpoint, soap->host, soap->port)))
+      return soap->error;
+  }
+  else
+#endif
+  if (soap->fopen && *soap->host)
+  { soap->status = http_command;
+    if (!soap->keep_alive || !soap_valid_socket(soap->socket) || strcmp(soap->host, host) || soap->port != port || !soap->fpoll || soap->fpoll(soap))
+    { soap->keep_alive = 0; /* to force close */
+      soap->omode &= ~SOAP_IO_UDP; /* to force close */
+      soap_closesock(soap);
+      DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Connect/reconnect to host='%s' path='%s' port=%d\n", soap->host, soap->path, soap->port));
+#ifdef WITH_UDP
+      if (!strncmp(endpoint, "soap.udp:", 9))
+        soap->omode |= SOAP_IO_UDP;
+#endif
+      soap->socket = soap->fopen(soap, endpoint, soap->host, soap->port);
+      if (soap->error)
+        return soap->error;
+      soap->keep_alive = ((soap->omode & SOAP_IO_KEEPALIVE) != 0);
+    }
+  }
+  count = soap_count_attachments(soap);
+  if (soap_begin_send(soap))
+    return soap->error;
+#ifndef WITH_NOHTTP
+  if ((soap->mode & SOAP_IO) != SOAP_IO_STORE && !(soap->mode & SOAP_ENC_XML) && endpoint)
+  { unsigned int k = soap->mode;
+    soap->mode &= ~(SOAP_IO | SOAP_ENC_ZLIB);
+    if ((k & SOAP_IO) != SOAP_IO_FLUSH)
+      soap->mode |= SOAP_IO_BUFFER;
+    if ((soap->error = soap->fpost(soap, endpoint, soap->host, soap->port, soap->path, action, count)))
+      return soap->error;
+#ifndef WITH_LEANER
+    if ((k & SOAP_IO) == SOAP_IO_CHUNK)
+    { if (soap_flush(soap))
+        return soap->error;
+    }
+#endif
+    soap->mode = k;
+  }
+  else if (action)
+    soap->action = soap_strdup(soap, action);
+  if (http_command != SOAP_POST)
+    return soap_end_send(soap);
+#endif
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+char*
+SOAP_FMAC2
+soap_s2base64(struct soap *soap, const unsigned char *s, char *t, int n)
+{ register int i;
+  register unsigned long m;
+  register char *p;
+  if (!t)
+    t = (char*)soap_malloc(soap, (n + 2) / 3 * 4 + 1);
+  if (!t)
+  { soap->error = SOAP_EOM;
+    return NULL;
+  }
+  p = t;
+  t[0] = '\0';
+  if (!s)
+    return p;
+  for (; n > 2; n -= 3, s += 3)
+  { m = s[0];
+    m = (m << 8) | s[1];
+    m = (m << 8) | s[2];
+    for (i = 4; i > 0; m >>= 6)
+      t[--i] = soap_base64o[m & 0x3F];
+    t += 4;
+  }
+  t[0] = '\0';
+  if (n > 0)
+  { m = 0;
+    for (i = 0; i < n; i++)
+      m = (m << 8) | *s++;
+    for (; i < 3; i++)
+      m <<= 8;
+    for (i++; i > 0; m >>= 6)
+      t[--i] = soap_base64o[m & 0x3F];
+    for (i = 3; i > n; i--)
+      t[i] = '=';
+    t[4] = '\0';
+  }
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_base642s(struct soap *soap, const char *s, char *t, size_t l, int *n)
+{ register int i, j, c;
+  register unsigned long m;
+  register const char *p;
+  if (!s || !*s)
+  { if (n)
+      *n = 0;
+    if (soap->error)
+      return NULL;
+    return SOAP_NON_NULL;
+  }
+  if (!t)
+  { l = (strlen(s) + 3) / 4 * 3;
+    t = (char*)soap_malloc(soap, l);
+  }
+  if (!t)
+  { soap->error = SOAP_EOM;
+    return NULL;
+  }
+  p = t;
+  if (n)
+    *n = 0;
+  for (;;)
+  { for (i = 0; i < SOAP_BLKLEN; i++)
+    { m = 0;
+      j = 0;
+      while (j < 4)
+      { c = *s++;
+        if (c == '=' || !c)
+        { i *= 3;
+          switch (j)
+          { case 2:
+              *t++ = (char)((m >> 4) & 0xFF);
+              i++;
+              break;
+            case 3:
+              *t++ = (char)((m >> 10) & 0xFF);
+              *t++ = (char)((m >> 2) & 0xFF);
+              i += 2;
+          }
+          if (n)
+	    *n += i;
+          return p;
+        }
+        c -= '+';
+        if (c >= 0 && c <= 79)
+        { m = (m << 6) + soap_base64i[c];
+          j++;
+        }
+      }
+      *t++ = (char)((m >> 16) & 0xFF);
+      *t++ = (char)((m >> 8) & 0xFF);
+      *t++ = (char)(m & 0xFF);
+      if (l < 3)
+      { if (n)
+	  *n += i;
+        return p;
+      }
+      l -= 3;
+    }
+    if (n)
+      *n += 3 * SOAP_BLKLEN;
+  }
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+char*
+SOAP_FMAC2
+soap_s2hex(struct soap *soap, const unsigned char *s, char *t, int n)
+{ register char *p;
+  if (!t)
+    t = (char*)soap_malloc(soap, 2 * n + 1);
+  if (!t)
+  { soap->error = SOAP_EOM;
+    return NULL;
+  }
+  p = t;
+  t[0] = '\0';
+  if (s)
+  { for (; n > 0; n--)
+    { register int m = *s++;
+      *t++ = (char)((m >> 4) + (m > 159 ? 'a' - 10 : '0'));
+      m &= 0x0F;
+      *t++ = (char)(m + (m > 9 ? 'a' - 10 : '0'));
+    }
+  }
+  *t++ = '\0';
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+SOAP_FMAC1
+const char*
+SOAP_FMAC2
+soap_hex2s(struct soap *soap, const char *s, char *t, size_t l, int *n)
+{ register const char *p;
+  if (!s || !*s)
+  { if (n)
+      *n = 0;
+    if (soap->error)
+      return NULL;
+    return SOAP_NON_NULL;
+  }
+  if (!t)
+  { l = strlen(s) / 2;
+    t = (char*)soap_malloc(soap, l);
+  }
+  if (!t)
+  { soap->error = SOAP_EOM;
+    return NULL;
+  }
+  p = t;
+  while (l)
+  { register int d1, d2;
+    d1 = *s++;
+    if (!d1)
+      break;
+    d2 = *s++;
+    if (!d2)
+      break;
+    *t++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0');
+    l--;
+  }
+  if (n)
+    *n = t - p;
+  return p;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_puthttphdr(struct soap *soap, int status, size_t count)
+{ register const char *s;
+#ifndef WITH_LEANER
+  register const char *r = NULL;
+#endif
+  register int err;
+  if (status == SOAP_FILE && soap->http_content)
+    s = soap->http_content;
+  else if (status == SOAP_HTML)
+    s = "text/html; charset=utf-8";
+  else if (soap->version == 2)
+    s = "application/soap+xml; charset=utf-8";
+  else
+    s = "text/xml; charset=utf-8";
+#ifndef WITH_LEANER
+  if (soap->mode & (SOAP_ENC_DIME | SOAP_ENC_MTOM))
+  { if (soap->mode & SOAP_ENC_MTOM)
+    { r = s;
+      s = "application/xop+xml; charset=utf-8";
+    }
+    else
+      s = "application/dime";
+  }
+  if ((soap->mode & SOAP_ENC_MIME) && soap->mime.boundary && soap->status != SOAP_GET)
+  { register const char *t = strchr(s, ';');
+    sprintf(soap->tmpbuf, "multipart/related; boundary=\"%s\"; type=\"", soap->mime.boundary);
+    if (t)
+      strncat(soap->tmpbuf, s, t - s);
+    else
+      strcat(soap->tmpbuf, s);
+    if (soap->mime.start)
+    { strcat(soap->tmpbuf, "\"; start=\"");
+      strcat(soap->tmpbuf, soap->mime.start);
+    }
+    strcat(soap->tmpbuf, "\"");
+    if (r)
+    { strcat(soap->tmpbuf, "; start-info=\"");
+      strcat(soap->tmpbuf, r);
+      strcat(soap->tmpbuf, "\"");
+    }
+    s = soap->tmpbuf;
+  }
+#endif
+  if ((err = soap->fposthdr(soap, "Content-Type", s)))
+    return err;
+#ifdef WITH_ZLIB
+  if (soap->omode & SOAP_ENC_ZLIB)
+  {
+#ifdef WITH_GZIP
+    err = soap->fposthdr(soap, "Content-Encoding", "gzip");
+#else
+    err = soap->fposthdr(soap, "Content-Encoding", "deflate");
+#endif
+    if (err)
+      return err;
+  }
+#endif
+#ifndef WITH_LEANER
+  if ((soap->omode & SOAP_IO) == SOAP_IO_CHUNK)
+    err = soap->fposthdr(soap, "Transfer-Encoding", "chunked");
+  else
+#endif
+  if (count > 0)
+  { sprintf(soap->tmpbuf, "%lu", (unsigned long)count);
+    err = soap->fposthdr(soap, "Content-Length", soap->tmpbuf);
+  }
+  if (err)
+    return err;
+  return soap->fposthdr(soap, "Connection", soap->keep_alive ? "keep-alive" : "close");
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static int
+http_get(struct soap *soap)
+{ return SOAP_GET_METHOD;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static int
+http_post(struct soap *soap, const char *endpoint, const char *host, int port, const char *path, const char *action, size_t count)
+{ register const char *s;
+  register int err;
+  if (soap->status == SOAP_GET)
+  { s = "GET";
+    count = 0;
+  }
+  else
+    s = "POST";
+#ifdef PALM
+  if (!endpoint || (strncmp(endpoint, "http:", 5) && strncmp(endpoint, "https:", 6) && strncmp(endpoint, "httpg:", 6)) && strncmp(endpoint, "_beam:", 6) && strncmp(endpoint, "_local:", 7) && strncmp(endpoint, "_btobex:", 8))
+#else
+  if (!endpoint || (strncmp(endpoint, "http:", 5) && strncmp(endpoint, "https:", 6) && strncmp(endpoint, "httpg:", 6)))
+#endif
+    return SOAP_OK;
+  if (soap->proxy_host && strncmp(endpoint, "https:", 6))
+    sprintf(soap->tmpbuf, "%s %s HTTP/%s", s, endpoint, soap->http_version);
+  else
+    sprintf(soap->tmpbuf, "%s /%s HTTP/%s", s, (*path == '/' ? path + 1 : path), soap->http_version);
+  if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL)))
+    return err;
+  if (port != 80)
+    sprintf(soap->tmpbuf, "%s:%d", host, port);
+  else
+    strcpy(soap->tmpbuf, host); 
+  if ((err = soap->fposthdr(soap, "Host", soap->tmpbuf))
+   || (err = soap->fposthdr(soap, "User-Agent", "gSOAP/2.7"))
+   || (err = soap_puthttphdr(soap, SOAP_OK, count)))
+    return err;
+#ifdef WITH_ZLIB
+#ifdef WITH_GZIP
+  if ((err = soap->fposthdr(soap, "Accept-Encoding", "gzip, deflate")))
+#else
+  if ((err = soap->fposthdr(soap, "Accept-Encoding", "deflate")))
+#endif
+    return err;
+#endif
+#ifndef WITH_LEAN
+  if (soap->userid && soap->passwd && strlen(soap->userid) + strlen(soap->passwd) < 761)
+  { sprintf(soap->tmpbuf + 262, "%s:%s", soap->userid, soap->passwd);
+    strcpy(soap->tmpbuf, "Basic ");
+    soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, strlen(soap->tmpbuf + 262));
+    if ((err = soap->fposthdr(soap, "Authorization", soap->tmpbuf)))
+      return err;
+  }
+  if (soap->proxy_userid && soap->proxy_passwd && strlen(soap->proxy_userid) + strlen(soap->proxy_passwd) < 761)
+  { sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd);
+    strcpy(soap->tmpbuf, "Basic ");
+    soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, strlen(soap->tmpbuf + 262));
+    if ((err = soap->fposthdr(soap, "Proxy-Authorization", soap->tmpbuf)))
+      return err;
+  }
+#endif
+#ifdef WITH_COOKIES
+#ifdef WITH_OPENSSL
+  if (soap_putcookies(soap, host, path, soap->ssl != NULL))
+    return soap->error;
+#else
+  if (soap_putcookies(soap, host, path, 0))
+    return soap->error;
+#endif
+#endif
+  if (action && soap->version == 1)
+  { sprintf(soap->tmpbuf, "\"%s\"", action);
+    if ((err = soap->fposthdr(soap, "SOAPAction", soap->tmpbuf)))
+      return err;
+  }
+  return soap->fposthdr(soap, NULL, NULL);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static int
+http_send_header(struct soap *soap, const char *s)
+{ register const char *t;
+  do
+  { t = strchr(s, '\n'); /* disallow \n in HTTP headers */
+    if (!t)
+      t = s + strlen(s);
+    if (soap_send_raw(soap, s, t - s))
+      return soap->error;
+    s = t + 1;
+  } while (*t);
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static int
+http_post_header(struct soap *soap, const char *key, const char *val)
+{ if (key)
+  { if (http_send_header(soap, key))
+      return soap->error;
+    if (val && (soap_send_raw(soap, ": ", 2) || http_send_header(soap, val)))
+      return soap->error;
+  }
+  return soap_send_raw(soap, "\r\n", 2);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+static int
+http_response(struct soap *soap, int status, size_t count)
+{ register int err;
+#ifdef WMW_RPM_IO
+  if (soap->rpmreqid)
+    httpOutputEnable(soap->rpmreqid);
+#endif  /* WMW_RPM_IO */
+  if (!status || status == SOAP_HTML || status == SOAP_FILE)
+  { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "OK 200\n"));
+#ifdef WMW_RPM_IO
+    if (soap->rpmreqid || soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* RPM behaves as if standalone */
+#else
+    if (soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* standalone application */
+#endif /* WMW_RPM_IO */
+    { sprintf(soap->tmpbuf, "HTTP/%s 200 OK", soap->http_version);
+      if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL)))
+        return err;
+    }
+    else if ((err = soap->fposthdr(soap, "Status", "200 OK")))
+      return err;
+  }
+  else if (status > 200 && status < 600)
+  { sprintf(soap->tmpbuf, "HTTP/%s %d %s", soap->http_version, status, http_error(soap, status));
+    if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL)))
+      return err;
+#ifndef WITH_LEAN 
+    if (status == 401)
+    { sprintf(soap->tmpbuf, "Basic realm=\"%s\"", soap->authrealm ? soap->authrealm : "gSOAP Web Service");
+      if ((err = soap->fposthdr(soap, "WWW-Authenticate", soap->tmpbuf)))
+        return err;
+    }
+    else if ((status >= 301 && status <= 303) || status == 307)
+    { if ((err = soap->fposthdr(soap, "Location", soap->endpoint)))
+        return err;
+    }
+#endif
+  }
+  else
+  { const char *s = *soap_faultcode(soap);
+    if (soap->version == 2 && !strcmp(s, "SOAP-ENV:Sender"))
+      s = "400 Bad Request";
+    else
+      s = "500 Internal Server Error";
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error %s (status=%d)\n", s, status));
+#ifdef WMW_RPM_IO
+    if (soap->rpmreqid || soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* RPM behaves as if standalone */
+#else
+    if (soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* standalone application */
+#endif /* WMW_RPM_IO */
+    { sprintf(soap->tmpbuf, "HTTP/%s %s", soap->http_version, s);
+      if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL)))
+        return err;
+    }
+    else if ((err = soap->fposthdr(soap, "Status", s)))
+      return err;
+  }
+  if ((err = soap->fposthdr(soap, "Server", "gSOAP/2.7"))
+   || (err = soap_puthttphdr(soap, status, count)))
+    return err;
+#ifdef WITH_COOKIES
+  if (soap_putsetcookies(soap))
+    return soap->error;
+#endif
+  return soap->fposthdr(soap, NULL, NULL);
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_response(struct soap *soap, int status)
+{ register size_t count;
+  if (!(soap->omode & (SOAP_ENC_XML | SOAP_IO_STORE /* this tests for chunking too */))
+   && (status == SOAP_HTML || status == SOAP_FILE))
+  { soap->omode &= ~SOAP_IO;
+    soap->omode |= SOAP_IO_STORE;
+  }
+  soap->status = status;
+  count = soap_count_attachments(soap);
+  if (soap_begin_send(soap))
+    return soap->error;
+#ifndef WITH_NOHTTP
+  if ((soap->mode & SOAP_IO) != SOAP_IO_STORE && !(soap->mode & SOAP_ENC_XML))
+  { register int n = soap->mode;
+    soap->mode &= ~(SOAP_IO | SOAP_ENC_ZLIB);
+    if ((n & SOAP_IO) != SOAP_IO_FLUSH)
+      soap->mode |= SOAP_IO_BUFFER;
+    if ((soap->error = soap->fresponse(soap, status, count)))
+      return soap->error;
+#ifndef WITH_LEANER
+    if ((n & SOAP_IO) == SOAP_IO_CHUNK)
+    { if (soap_flush(soap))
+        return soap->error;
+    }
+#endif
+    soap->mode = n;
+  }
+#endif
+  return SOAP_OK;
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_LEAN
+static const char*
+soap_set_validation_fault(struct soap *soap, const char *s, const char *t)
+{ if (*soap->tag)
+    sprintf(soap->msgbuf, "Validation constraint violation: %s%s in element <%s>", s, t?t:SOAP_STR_EOS, soap->tag);
+  else
+    sprintf(soap->msgbuf, "Validation constraint violation: %s%s", s, t?t:SOAP_STR_EOS);
+  return soap->msgbuf;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_set_fault(struct soap *soap)
+{ const char **c = soap_faultcode(soap);
+  const char **s = soap_faultstring(soap);
+  if (!*c && !*s && soap->fseterror)
+    soap->fseterror(soap, c, s);
+  if (!*c)
+  { if (soap->version == 2)
+      *c = "SOAP-ENV:Sender";
+    else
+      *c = "SOAP-ENV:Client";
+  }
+  if (*s)
+    return;
+  switch (soap->error)
+  {
+#ifndef WITH_LEAN
+    case SOAP_CLI_FAULT:
+      *s = "Client fault";
+      break;
+    case SOAP_SVR_FAULT:
+      *s = "Server fault";
+      break;
+    case SOAP_TAG_MISMATCH:
+      *s = soap_set_validation_fault(soap, "tag name or namespace mismatch", NULL);
+      break;
+    case SOAP_TYPE:
+      *s = soap_set_validation_fault(soap, "data type mismatch ", soap->type);
+      break;
+    case SOAP_SYNTAX_ERROR:
+      *s = "Well-formedness violation";
+      break;
+    case SOAP_NO_TAG:
+      *s = "No XML element tag";
+      break;
+    case SOAP_MUSTUNDERSTAND:
+      *c = "SOAP-ENV:MustUnderstand";
+      sprintf(soap->msgbuf, "The data in element '%s' must be understood but cannot be handled", soap->tag);
+      *s = soap->msgbuf;
+      break;
+    case SOAP_VERSIONMISMATCH:
+      *c = "SOAP-ENV:VersionMismatch";
+      *s = "SOAP version mismatch or invalid SOAP message";
+      break;
+    case SOAP_DATAENCODINGUNKNOWN:
+      *c = "SOAP-ENV:DataEncodingUnknown";
+      *s = "Unsupported SOAP data encoding";
+      break;
+    case SOAP_NAMESPACE:
+      *s = soap_set_validation_fault(soap, "namespace mismatch", NULL);
+      break;
+    case SOAP_USER_ERROR:
+      *s = "User error";
+      break;
+    case SOAP_FATAL_ERROR:
+      *s = "Fatal error";
+      break;
+    case SOAP_NO_METHOD:
+      sprintf(soap->msgbuf, "Method '%s' not implemented: method name or namespace not recognized", soap->tag);
+      *s = soap->msgbuf;
+      break;
+    case SOAP_GET_METHOD:
+      *s = "HTTP GET method not implemented";
+      break;
+    case SOAP_EOM:
+      *s = "Out of memory";
+      break;
+    case SOAP_IOB:
+      *s = "Array index out of bounds";
+      break;
+    case SOAP_NULL:
+      *s = soap_set_validation_fault(soap, "nil not allowed", NULL);
+      break;
+    case SOAP_DUPLICATE_ID:
+      *s = soap_set_validation_fault(soap, "multiple definitions of id ", soap->id);
+      if (soap->version == 2)
+        *soap_faultsubcode(soap) = "SOAP-ENC:DuplicateID";
+      break;
+    case SOAP_MISSING_ID:
+      *s = soap_set_validation_fault(soap, "missing id for ref ", soap->id);
+      if (soap->version == 2)
+        *soap_faultsubcode(soap) = "SOAP-ENC:MissingID";
+      break;
+    case SOAP_HREF:
+      *s = soap_set_validation_fault(soap, "incompatible object ref ", soap->id);
+      break;
+    case SOAP_FAULT:
+      break;
+#ifndef WITH_NOIO
+    case SOAP_UDP_ERROR:
+      *s = "Message too large for UDP packet";
+      break;
+    case SOAP_TCP_ERROR:
+      *s = tcp_error(soap);
+      break;
+#endif
+    case SOAP_HTTP_ERROR:
+      *s = "HTTP error";
+      break;
+    case SOAP_SSL_ERROR:
+#ifdef WITH_OPENSSL
+      *s = "SSL error";
+#else
+      *s = "OpenSSL not installed: recompile with -DWITH_OPENSSL";
+#endif
+      break;
+    case SOAP_PLUGIN_ERROR:
+      *s = "Plugin registry error";
+      break;
+    case SOAP_DIME_ERROR:
+      *s = "DIME format error";
+      break;
+    case SOAP_DIME_HREF:
+      *s = "DIME href to missing attachment";
+      break;
+    case SOAP_DIME_MISMATCH:
+      *s = "DIME version/transmission error";
+      break;
+    case SOAP_DIME_END:
+      *s = "End of DIME error";
+      break;
+    case SOAP_MIME_ERROR:
+      *s = "MIME format error";
+      break;
+    case SOAP_MIME_HREF:
+      *s = "MIME href to missing attachment";
+      break;
+    case SOAP_MIME_END:
+      *s = "End of MIME error";
+      break;
+    case SOAP_ZLIB_ERROR:
+#ifdef WITH_ZLIB
+      sprintf(soap->msgbuf, "Zlib/gzip error: '%s'", soap->d_stream.msg?soap->d_stream.msg:"");
+      *s = soap->msgbuf;
+#else
+      *s = "Zlib/gzip not installed for (de)compression: recompile with -DWITH_GZIP";
+#endif
+      break;
+    case SOAP_REQUIRED:
+      *s = soap_set_validation_fault(soap, "missing required attribute", NULL);
+      break;
+    case SOAP_PROHIBITED:
+      *s = soap_set_validation_fault(soap, "prohibited attribute present", NULL);
+      break;
+    case SOAP_OCCURS:
+      *s = soap_set_validation_fault(soap, "min/maxOccurs violation", NULL);
+      break;
+    case SOAP_LENGTH:
+      *s = soap_set_validation_fault(soap, "content length violation", NULL);
+      break;
+    case SOAP_STOP:
+      *s = "Stopped: no response sent";
+      break;
+#endif
+    case SOAP_EOF:
+#ifndef WITH_NOIO
+      sprintf(soap->msgbuf, "End of file or no input: '%s'", soap_strerror(soap));
+      *s = soap->msgbuf;
+      break;
+#else
+      *s = "End of file or no input";
+      break;
+#endif
+    default:
+#ifndef WITH_NOHTTP
+#ifndef WITH_LEAN
+      if (soap->error > 200 && soap->error < 600)
+      { sprintf(soap->msgbuf, "HTTP Error: %d %s", soap->error, http_error(soap, soap->error));
+        *s = soap->msgbuf;
+      }
+      else
+#endif
+#endif
+      { sprintf(soap->msgbuf, "Error %d", soap->error);
+        *s = soap->msgbuf;
+      }
+    }
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_send_fault(struct soap *soap)
+{ register int status = soap->error;
+  int r = 1;
+  if (status == SOAP_STOP)
+    return status;
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Sending back fault struct for error code %d\n", soap->error));
+  soap->keep_alive = 0; /* to terminate connection */
+  soap_set_fault(soap);
+#ifndef WITH_NOIO
+#ifndef WITH_LEAN
+  if (soap_valid_socket(soap->socket))
+  { struct timeval timeout;
+    fd_set rfd, sfd;
+    timeout.tv_sec = 0;
+    timeout.tv_usec = 0;
+    FD_ZERO(&rfd);
+    FD_ZERO(&sfd);
+    FD_SET((SOAP_SOCKET)soap->socket, &rfd);
+    FD_SET((SOAP_SOCKET)soap->socket, &sfd);
+    r = select((SOAP_SOCKET)(soap->socket + 1), &rfd, &sfd, NULL, &timeout);
+    if (r > 0)
+    { if (!FD_ISSET((SOAP_SOCKET)soap->socket, &sfd)
+       || (FD_ISSET((SOAP_SOCKET)soap->socket, &rfd)
+        && recv((SOAP_SOCKET)soap->socket, soap->tmpbuf, 1, MSG_PEEK) < 0))
+        r = 0;
+    }
+  }
+#endif
+#endif
+  if ((status != SOAP_EOF || (!soap->recv_timeout && !soap->send_timeout)) && r > 0)
+  { soap->error = SOAP_OK;
+    soap_serializeheader(soap);
+    soap_serializefault(soap);
+    soap_begin_count(soap);
+    if (soap->mode & SOAP_IO_LENGTH)
+    { soap_envelope_begin_out(soap);
+      soap_putheader(soap);
+      soap_body_begin_out(soap);
+      soap_putfault(soap);
+      soap_body_end_out(soap);
+      soap_envelope_end_out(soap);
+    }
+    soap_end_count(soap);
+    if (soap_response(soap, status)
+     || soap_envelope_begin_out(soap)
+     || soap_putheader(soap)
+     || soap_body_begin_out(soap)
+     || soap_putfault(soap)
+     || soap_body_end_out(soap)
+     || soap_envelope_end_out(soap))
+      return soap_closesock(soap);
+    soap_end_send(soap);
+  }
+  soap->error = status;
+  return soap_closesock(soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_recv_fault(struct soap *soap)
+{ register int status = soap->error;
+  DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Receiving SOAP Fault\n"));
+  soap->error = SOAP_OK;
+  if (soap_getfault(soap))
+  { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Error: soap_get_soapfault() failed. Is this a SOAP message at all?\n"));
+    *soap_faultcode(soap) = (soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client");
+    soap->error = status;
+    soap_set_fault(soap);
+  }
+  else
+  { register const char *s = *soap_faultcode(soap);
+    if (!soap_match_tag(soap, s, "SOAP-ENV:Server") || !soap_match_tag(soap, s, "SOAP-ENV:Receiver"))
+      status = SOAP_SVR_FAULT; 
+    else if (!soap_match_tag(soap, s, "SOAP-ENV:Client") || !soap_match_tag(soap, s, "SOAP-ENV:Sender"))
+      status = SOAP_CLI_FAULT;
+    else if (!soap_match_tag(soap, s, "SOAP-ENV:MustUnderstand"))
+      status = SOAP_MUSTUNDERSTAND;
+    else if (!soap_match_tag(soap, s, "SOAP-ENV:VersionMismatch"))
+      status = SOAP_VERSIONMISMATCH;
+    else
+    { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Fault code %s\n", s));
+      status = SOAP_FAULT;
+    }
+    if (soap_body_end_in(soap)
+     || soap_envelope_end_in(soap)
+     || soap_end_recv(soap))
+      return soap_closesock(soap);
+    soap->error = status;
+  }
+  return soap_closesock(soap);
+}
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_send_empty_response(struct soap *soap)
+{ soap->count = 0;
+  if (soap_response(soap, SOAP_OK) || soap_end_send(soap))
+    return soap_closesock(soap);
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOHTTP
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_recv_empty_response(struct soap *soap)
+{ if (soap_begin_recv(soap) || soap_end_recv(soap))
+    return soap_closesock(soap);
+  return SOAP_OK;
+}
+#endif
+#endif
+
+/******************************************************************************/
+#ifndef WITH_NOIO
+#ifndef PALM_1
+static const char*
+soap_strerror(struct soap *soap)
+{ register int err = soap->errnum;
+  if (err)
+  {
+#ifndef WIN32
+    return strerror(err);
+#else
+    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, 0, (LPTSTR)&soap->errorstr, sizeof(soap->errorstr), NULL);
+    return soap->errorstr;
+#endif
+  }
+  return "Operation interrupted or timed out";
+}
+#endif
+#endif 
+
+/******************************************************************************/
+#ifndef PALM_2
+static int
+soap_set_error(struct soap *soap, const char *faultcode, const char *faultsubcode, const char *faultstring, const char *faultdetail, int soaperror)
+{ *soap_faultcode(soap) = faultcode;
+  if (faultsubcode)
+    *soap_faultsubcode(soap) = faultsubcode;
+  *soap_faultstring(soap) = faultstring;
+  if (faultdetail && *faultdetail)
+  { register const char **s = soap_faultdetail(soap);
+    if (s)
+      *s = faultdetail;
+  }
+  return soap->error = soaperror;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_set_sender_error(struct soap *soap, const char *faultstring, const char *faultdetail, int soaperror)
+{ return soap_set_error(soap, soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client", NULL, faultstring, faultdetail, soaperror);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_set_receiver_error(struct soap *soap, const char *faultstring, const char *faultdetail, int soaperror)
+{ return soap_set_error(soap, soap->version == 2 ? "SOAP-ENV:Receiver" : "SOAP-ENV:Server", NULL, faultstring, faultdetail, soaperror);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+static int
+soap_copy_fault(struct soap *soap, const char *faultcode, const char *faultsubcode, const char *faultstring, const char *faultdetail)
+{ char *r = NULL, *s = NULL, *t = NULL;
+  if (faultsubcode)
+    r = soap_strdup(soap, faultsubcode);
+  if (faultstring)
+    s = soap_strdup(soap, faultstring);
+  if (faultdetail)
+    t = soap_strdup(soap, faultdetail);
+  return soap_set_error(soap, faultcode, r, s, t, SOAP_FAULT);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_sender_fault(struct soap *soap, const char *faultstring, const char *faultdetail)
+{ return soap_sender_fault_subcode(soap, NULL, faultstring, faultdetail);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_sender_fault_subcode(struct soap *soap, const char *faultsubcode, const char *faultstring, const char *faultdetail)
+{ return soap_copy_fault(soap, soap->version == 2 ? "SOAP-ENV:Sender" : "SOAP-ENV:Client", faultsubcode, faultstring, faultdetail);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_receiver_fault(struct soap *soap, const char *faultstring, const char *faultdetail)
+{ return soap_receiver_fault_subcode(soap, NULL, faultstring, faultdetail);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_receiver_fault_subcode(struct soap *soap, const char *faultsubcode, const char *faultstring, const char *faultdetail)
+{ return soap_copy_fault(soap, soap->version == 2 ? "SOAP-ENV:Receiver" : "SOAP-ENV:Server", faultsubcode, faultstring, faultdetail);
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+#ifndef WITH_NOSTDLIB
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_print_fault(struct soap *soap, FILE *fd)
+{ if (soap->error)
+  { const char *c, *v = NULL, *s, **d;
+    d = soap_faultcode(soap);
+    if (!*d)
+      soap_set_fault(soap);
+    c = *d;
+    if (soap->version == 2)
+      v = *soap_faultsubcode(soap);
+    s = *soap_faultstring(soap);
+    d = soap_faultdetail(soap);
+    fprintf(fd, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]");
+  }
+}
+#endif
+#endif
+ 
+/******************************************************************************/
+#ifndef PALM_1
+#ifndef WITH_NOSTDLIB
+SOAP_FMAC1
+void
+SOAP_FMAC2
+soap_print_fault_location(struct soap *soap, FILE *fd)
+{ 
+#ifndef WITH_LEAN
+  int i, j, c1, c2;
+  if (soap->error && soap->buflen > 0)
+  { i = (int)soap->bufidx - 1;
+    if (i <= 0)
+      i = 0;
+    c1 = soap->buf[i];
+    soap->buf[i] = '\0';
+    if ((int)soap->buflen >= i + 1024)
+      j = i + 1023;
+    else
+      j = (int)soap->buflen - 1;
+    c2 = soap->buf[j];
+    soap->buf[j] = '\0';
+    fprintf(fd, "%s%c\n** HERE **\n", soap->buf, c1);
+    if (soap->bufidx < soap->buflen)
+      fprintf(fd, "%s\n", soap->buf + soap->bufidx);
+    soap->buf[i] = c1;
+    soap->buf[j] = c2;
+  }
+#endif
+}
+#endif
+#endif
+ 
+/******************************************************************************/
+#ifndef PALM_1
+SOAP_FMAC1
+int
+SOAP_FMAC2
+soap_register_plugin_arg(struct soap *soap, int (*fcreate)(struct soap*, struct soap_plugin*, void*), void *arg)
+{ register struct soap_plugin *p;
+  register int r;
+  if (!(p = (struct soap_plugin*)SOAP_MALLOC(soap, sizeof(struct soap_plugin))))
+    return soap->error = SOAP_EOM;
+  p->id = NULL;
+  p->data = NULL;
+  p->fcopy = NULL;
+  p->fdelete = NULL;
+  r = fcreate(soap, p, arg);
+  if (!r && p->fdelete)
+  { p->next = soap->plugins;
+    soap->plugins = p;
+    DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Registered '%s' plugin\n", p->id));
+    return SOAP_OK;
+  }
+  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not register plugin '%s': plugin returned error %d (or fdelete callback not set)\n", p->id?p->id:"?", r));
+  SOAP_FREE(soap, p);
+  return r;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_1
+static void *
+fplugin(struct soap *soap, const char *id)
+{ register struct soap_plugin *p;
+  for (p = soap->plugins; p; p = p->next)
+    if (p->id == id || !strcmp(p->id, id))
+      return p->data;
+  return NULL;
+}
+#endif
+
+/******************************************************************************/
+#ifndef PALM_2
+SOAP_FMAC1
+void *
+SOAP_FMAC2
+soap_lookup_plugin(struct soap *soap, const char *id)
+{ return soap->fplugin(soap, id);
+}
+#endif
+
+/******************************************************************************/
+#ifdef __cplusplus
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/PC_Tools/HTIGateway/stdsoap/stdsoap2.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2053 @@
+/*
+
+stdsoap2.h 2.7.6b
+
+gSOAP runtime
+
+gSOAP XML Web services tools
+Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc., All Rights Reserved.
+This part of the software is released under one of the following licenses:
+GPL, the gSOAP public license, or Genivia's license for commercial use.
+--------------------------------------------------------------------------------
+Contributors:
+
+Wind River Systems, Inc., for the following additions (marked WR[...]):
+  - vxWorks compatible
+--------------------------------------------------------------------------------
+gSOAP public license.
+
+The contents of this file are subject to the gSOAP Public License Version 1.3
+(the "License"); you may not use this file except in compliance with the
+License. You may obtain a copy of the License at
+http://www.cs.fsu.edu/~engelen/soaplicense.html
+Software distributed under the License is distributed on an "AS IS" basis,
+WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+for the specific language governing rights and limitations under the License.
+
+The Initial Developer of the Original Code is Robert A. van Engelen.
+Copyright (C) 2000-2005, Robert van Engelen, Genivia Inc., All Rights Reserved.
+--------------------------------------------------------------------------------
+GPL license.
+
+This program is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free Software
+Foundation; either version 2 of the License, or (at your option) any later
+version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License along with
+this program; if not, write to the Free Software Foundation, Inc., 59 Temple
+Place, Suite 330, Boston, MA 02111-1307 USA
+
+Author contact information:
+engelen@genivia.com / engelen@acm.org
+--------------------------------------------------------------------------------
+A commercial use license is available from Genivia, Inc., contact@genivia.com
+--------------------------------------------------------------------------------
+*/
+
+#ifdef WITH_SOAPDEFS_H
+# include "soapdefs.h"		/* include user-defined stuff */
+#endif
+
+#ifndef _THREAD_SAFE
+# define _THREAD_SAFE
+#endif
+
+#ifndef OPENSERVER
+# ifndef _REENTRANT
+#  define _REENTRANT
+# endif
+#endif
+
+#ifndef SOAP_FMAC1	/* stdsoap2.h declaration macro */
+# define SOAP_FMAC1
+#endif
+
+#ifndef SOAP_FMAC2	/* stdsoap2.h declaration macro */
+# define SOAP_FMAC2
+#endif
+
+#ifndef SOAP_FMAC3	/* (de)serializer declaration macro */
+# define SOAP_FMAC3
+#endif
+
+#ifndef SOAP_FMAC3S	/* string converter for (de)serializer declaration macro */
+# define SOAP_FMAC3S SOAP_FMAC3
+#endif
+
+#ifndef SOAP_FMAC4	/* (de)serializer declaration macro */
+# define SOAP_FMAC4
+#endif
+
+#ifndef SOAP_FMAC4S	/* string converter for (de)serializer declaration macro */
+# define SOAP_FMAC4S SOAP_FMAC4
+#endif
+
+#ifndef SOAP_FMAC5	/* stub/skeleton declaration macro */
+# define SOAP_FMAC5
+#endif
+
+#ifndef SOAP_FMAC6	/* stub/skeleton declaration macro */
+# define SOAP_FMAC6
+#endif
+
+#ifndef SOAP_CMAC	/* class declaration macro */
+# define SOAP_CMAC
+#endif
+
+#ifndef SOAP_NMAC	/* namespace table declaration macro */
+# define SOAP_NMAC
+#endif
+
+#ifndef SOAP_SOURCE_STAMP
+# define SOAP_SOURCE_STAMP(str)
+#endif
+
+/* gSOAP 2.7.4 and higher: fast look-aside buffering is stable */
+#ifndef WITH_FAST
+# define WITH_FAST
+#endif
+
+#ifdef WITH_LEANER
+# ifndef WITH_LEAN
+#  define WITH_LEAN
+# endif
+#endif
+
+#ifdef WITH_LEAN
+# ifdef WITH_COOKIES
+#  error "Cannot build WITH_LEAN code WITH_COOKIES enabled"
+# endif
+#endif
+
+#ifndef STDSOAP_H
+#define STDSOAP_H
+
+#if defined(__vxworks) || defined(__VXWORKS__)
+# define VXWORKS
+#endif
+
+#ifdef _WIN32
+# ifndef WIN32
+#  define WIN32
+# endif
+#endif
+
+#ifdef UNDER_CE
+# ifndef WIN32
+#  define WIN32
+# endif
+#endif
+
+#ifdef __BORLANDC__
+# ifdef __WIN32__
+#  ifndef WIN32
+#   define WIN32
+#  endif
+# endif
+#endif
+
+#ifdef __CYGWIN__
+# ifndef CYGWIN
+#  define CYGWIN
+# endif
+#endif
+
+#ifdef __SYMBIAN32__ 
+# define SYMBIAN
+# undef WIN32
+#endif
+
+#if defined(__palmos__) || defined(PALM_GCC) || defined(__PALMOS_TRAPS__)
+# ifndef PALM
+#  define PALM
+# endif
+#endif
+
+#if defined(__hpux)
+# ifndef HP_UX
+#  define HP_UX
+# endif
+#endif
+
+#if defined(__alpha) && !defined(__VMS)
+# ifndef TRU64
+#  define TRU64 
+# endif
+#endif
+
+#ifdef __MVS__
+# ifndef OS390
+#  define OS390
+# endif
+#endif
+
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+# ifdef WITH_OPENSSL
+#  ifndef HAVE_OPENSSL_SSL_H
+#   undef WITH_OPENSSL
+#  endif
+# endif
+#else
+# if defined(UNDER_CE)
+#  define WITH_LEAN
+#  define HAVE_SSCANF
+# elif defined(WIN32)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_FTIME
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+#  define SOAP_LONG_FORMAT "%I64d"
+#  define SOAP_ULONG_FORMAT "%I64u"
+# elif defined(CYGWIN)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_FTIME
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+# elif defined(__APPLE__)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_TIMEGM
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+# elif defined(_AIXVERSION_431)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_FTIME
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+# elif defined(HP_UX)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_FTIME
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+# elif defined(FREEBSD) || defined(__FreeBSD__)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_STRTOLL
+#  define HAVE_STRTOULL
+#  define HAVE_GETTIMEOFDAY
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+#  define SOAP_LONG_FORMAT "%qd"
+#  define SOAP_ULONG_FORMAT "%qu"
+# elif defined(__VMS)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_FTIME
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+# elif defined(__GLIBC__) || defined(__GNU__)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_STRTOLL
+#  define HAVE_STRTOULL
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_FTIME
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_TIMEGM
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+#  define HAVE_ISNAN
+# elif defined(TRU64)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_STRTOLL
+#  define HAVE_STRTOULL
+#  define HAVE_GETTIMEOFDAY
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define __USE_STD_IOSTREAM
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+#  define SOAP_LONG_FORMAT "%ld"
+#  define SOAP_ULONG_FORMAT "%lu"
+# elif defined(MAC_CARBON)
+#  define WITH_NOIO
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_FTIME
+#  define HAVE_RAND_R
+#  define HAVE_GETHOSTBYNAME_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+# elif defined(PALM)
+#  define WITH_LEAN
+#  define HAVE_STRTOD   /* strtod() is defined in palmFunctions.h */
+#  include <stdlib.h>	/* Needs to be included before unix headers */
+#  include <sys_types.h>
+#  define IGNORE_STDIO_STUBS
+#  include <StdIOPalm.h>
+#  define O_NONBLOCK FNONBIO
+#  include <sys_socket.h>
+#  include "palmFunctions.h"
+# elif defined(SYMBIAN)
+#  define WITH_LEAN
+#  define WITH_NONAMESPACES
+#  define HAVE_STRTOD	/* use STRTOD since sscanf doesn't seem to work */
+#  include <e32def.h>
+#  include <sys/ioctl.h>
+# elif defined(VXWORKS)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_PGMTIME_R
+#  define HAVE_PLOCALTIME_R
+#  define HAVE_MKTIME
+# elif defined(OS390)
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_FTIME
+#  define HAVE_RAND_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_WCTOMB
+#  define HAVE_MB
+# else
+/* Default asumptions on supported functions */
+#  define HAVE_STRRCHR
+#  define HAVE_STRTOD
+#  define HAVE_SSCANF
+#  define HAVE_STRTOL
+#  define HAVE_STRTOUL
+#  define HAVE_SYS_TIMEB_H
+#  define HAVE_FTIME
+#  define HAVE_RAND_R
+#  define HAVE_GETHOSTBYNAME_R
+#  define HAVE_GMTIME_R
+#  define HAVE_LOCALTIME_R
+#  define HAVE_WCTOMB
+#  define HAVE_MBTOWC
+# endif
+#endif
+
+/* QNX does not have a working version of strtof */
+#if defined(__QNX__) || defined(QNX)
+# undef HAVE_STRTOF
+#endif
+
+#ifndef SOAP_LONG_FORMAT
+# define SOAP_LONG_FORMAT "%lld"	/* printf format for 64 bit ints */
+#endif
+
+#ifndef SOAP_ULONG_FORMAT
+# define SOAP_ULONG_FORMAT "%llu"	/* printf format for unsigned 64 bit ints */
+#endif
+
+#ifndef WITH_NOSTDLIB
+# include <stdlib.h>
+# ifndef PALM
+#  include <stdio.h>
+#  include <string.h>
+# endif
+# include <ctype.h>
+# include <limits.h>
+#endif
+
+#if defined(__cplusplus) && !defined(WITH_LEAN)
+# include <string>
+# include <iostream>
+#endif
+
+#ifdef WITH_NOHTTP
+# ifndef WITH_NOIO
+#  define WITH_NOIO
+#  undef WITH_COOKIES
+# endif
+#endif
+
+#ifndef UNDER_CE
+# ifndef PALM
+#  ifndef WITH_NOIO
+#   include <errno.h>
+#   include <sys/types.h>
+#  endif
+#  ifndef WITH_LEAN
+#   ifdef HAVE_SYS_TIMEB_H
+#    include <sys/timeb.h>		/* for ftime() */
+#   endif
+#   include <time.h>
+#  endif
+# endif
+#endif
+
+#ifdef OPENSERVER
+# include <sys/socket.h>
+# include <sys/stream.h>
+# include <sys/protosw.h>
+  extern int h_errno;
+#endif
+
+#ifndef WITH_NOIO
+# ifndef WIN32
+#  ifndef PALM
+#   include <sys/socket.h>
+#   ifdef VXWORKS
+#    include <sockLib.h>
+#    include <selectLib.h>
+#   endif
+#   ifndef VXWORKS
+#    ifndef SYMBIAN
+#     include <strings.h>
+#    endif
+#   endif
+#   ifdef SUN_OS
+#    include <sys/stream.h>		/* SUN */
+#    include <sys/socketvar.h>		/* SUN < 2.8 (?) */
+#   endif
+#   ifdef VXWORKS
+#    ifdef _WRS_KERNEL
+#     include <sys/times.h>
+#    endif
+#   else
+#    include <sys/time.h>
+#   endif
+#   include <netinet/in.h>
+#   ifdef OS390
+#    include <netinet/tcp_var.h>
+#   else
+#    include <netinet/tcp.h>          /* TCP_NODELAY */
+#   endif
+#   include <arpa/inet.h>
+#  endif
+# endif
+#endif
+
+#ifdef WITH_FASTCGI
+# include <fcgi_stdio.h>
+#endif
+
+#ifdef WITH_OPENSSL
+# define OPENSSL_NO_KRB5
+# include <openssl/ssl.h>
+# include <openssl/err.h>
+# include <openssl/rand.h>
+# ifndef ALLOW_OLD_VERSIONS
+#  if (OPENSSL_VERSION_NUMBER < 0x00905100L)
+#   error "Must use OpenSSL 0.9.6 or later"
+#  endif
+# endif
+#endif
+
+#ifdef WITH_GZIP
+# ifndef WITH_ZLIB
+#  define WITH_ZLIB
+# endif
+#endif
+
+#ifdef WITH_CASEINSENSITIVETAGS
+# define SOAP_STRCMP soap_tag_cmp	/* case insensitve XML element/attribute names */
+#else
+# define SOAP_STRCMP strcmp		/* case sensitive XML element/attribute names */
+#endif
+
+#ifdef WITH_ZLIB
+# include <zlib.h>
+#endif
+
+#ifndef WITH_NOSTDLIB
+# ifndef PALM
+#  include <math.h>	/* for isnan() */
+# endif
+#endif
+
+//#define DEBUG /* Uncomment to debug sending (in file SENT.log) receiving (in file RECV.log) and messages (in file TEST.log) */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef WIN32
+# ifndef UNDER_CE
+#  include <io.h>
+#  include <fcntl.h>
+# endif
+//# include <winsock.h>
+# include <WinSock2.h> /* Alternative: use winsock2 (not available with eVC) */
+# ifdef WITH_IPV6
+#  include <ws2tcpip.h>
+#  include <wspiapi.h>
+# endif
+#else
+# ifdef VXWORKS
+#  include <hostLib.h>
+#  include <ioctl.h>
+#  include <ioLib.h>
+# endif
+# ifndef WITH_NOIO
+#  ifndef PALM
+#   include <netdb.h>
+#   include <netinet/in.h>
+#   include <unistd.h>
+#   include <fcntl.h>
+#  endif
+# endif
+#endif
+
+/* Portability: define SOAP_SOCKLEN_T */
+#if defined(SOCKLEN_T)
+# define SOAP_SOCKLEN_T SOCKLEN_T
+#elif defined(__socklen_t_defined) || defined(_SOCKLEN_T) || defined(CYGWIN) || defined(FREEBSD) || defined(__FreeBSD__) || defined(__QNX__) || defined(QNX) || defined(_AIX)
+# define SOAP_SOCKLEN_T socklen_t
+#elif defined(IRIX) || defined(WIN32) || defined(__APPLE__) || defined(HP_UX) || defined(SUN_OS) || defined(OPENSERVER) || defined(TRU64) || defined(VXWORKS)
+# define SOAP_SOCKLEN_T int
+#else
+# define SOAP_SOCKLEN_T size_t
+#endif
+
+#ifdef WIN32
+# define SOAP_SOCKET SOCKET
+#else
+# define SOAP_SOCKET int
+# define closesocket(n) close(n)
+#endif
+
+#define SOAP_INVALID_SOCKET (-1)
+#define soap_valid_socket(n) ((n) != SOAP_INVALID_SOCKET)
+
+#if defined(SYMBIAN)
+# define LONG64 long
+# define ULONG64 unsigned LONG64
+#elif !defined(WIN32) || defined(__GLIBC__) || defined(__GNU__)
+# ifndef LONG64
+#  define LONG64 long long
+#  define ULONG64 unsigned LONG64
+# endif
+#elif defined(UNDER_CE)
+# define LONG64 __int64
+# define ULONG64 unsigned LONG64
+#elif defined(__BORLANDC__)
+# define LONG64 __int64
+# define ULONG64 unsigned LONG64
+#endif
+
+#if defined(WIN32)
+# define soap_int32 __int32
+#elif defined(SYMBIAN)
+# define soap_int32 long
+#elif defined(PALM)
+# define soap_int32 Int32
+#else
+# define soap_int32 int32_t
+#endif
+
+#ifdef WIN32
+# define SOAP_ERANGE ERANGE
+# define SOAP_EINTR WSAEINTR
+# define SOAP_EAGAIN WSAEWOULDBLOCK
+# define SOAP_EWOULDBLOCK WSAEWOULDBLOCK
+# define SOAP_EINPROGRESS WSAEINPROGRESS
+#else
+# define SOAP_ERANGE ERANGE
+# define SOAP_EINTR EINTR
+# define SOAP_EAGAIN EAGAIN
+# ifdef SYMBIAN
+#  define SOAP_EWOULDBLOCK 9898
+#  define SOAP_EINPROGRESS 9899
+# else
+#  define SOAP_EWOULDBLOCK EWOULDBLOCK
+#  define SOAP_EINPROGRESS EINPROGRESS
+# endif
+#endif
+
+#ifdef WIN32
+# ifdef UNDER_CE
+#  define soap_errno GetLastError()
+#  define soap_socket_errno GetLastError()
+# else
+#  define soap_errno GetLastError()
+#  define soap_socket_errno WSAGetLastError()
+# endif
+#else
+# ifndef WITH_NOIO
+#  define soap_errno errno
+#  define soap_socket_errno errno
+# else
+#  define soap_errno 0
+#  define soap_socket_errno 0
+# endif
+#endif
+
+#ifndef SOAP_BUFLEN
+# ifdef WITH_UDP
+#  define SOAP_BUFLEN (65536) /* max UDP packet size */
+# else
+#  ifndef WITH_LEAN
+#   define SOAP_BUFLEN (65536) /* buffer length for socket packets, also used by gethostbyname_r so don't make this too small */
+#  else
+#   define SOAP_BUFLEN  (2048)
+#  endif
+# endif
+#endif
+#ifndef SOAP_LABLEN
+# define SOAP_LABLEN     (64) /* initial look-aside buffer length */
+#endif
+#ifndef SOAP_PTRBLK
+# define SOAP_PTRBLK     (32) /* block allocation for pointer hash table chains */
+#endif
+#ifndef SOAP_PTRHASH
+# ifndef WITH_LEAN
+#  define SOAP_PTRHASH (1024) /* size of pointer analysis hash table (must be power of 2) */
+# else
+#  define SOAP_PTRHASH   (32)
+# endif
+#endif
+#ifndef SOAP_IDHASH
+# ifndef WITH_LEAN
+#  define SOAP_IDHASH  (1999) /* prime size of hash table for parsed id/ref */
+# else
+#  define SOAP_IDHASH    (19) /* 19, 199 */
+# endif
+#endif
+#ifndef SOAP_BLKLEN
+# ifndef WITH_LEAN
+#  define SOAP_BLKLEN   (256) /* size of blocks to collect long strings and XML attributes */
+# else
+#  define SOAP_BLKLEN    (32)
+# endif
+#endif
+#ifndef SOAP_TAGLEN
+# ifndef WITH_LEAN
+#  define SOAP_TAGLEN   (256) /* maximum length of XML element tag/attribute name or host/path name + 1 */
+# else
+#  define SOAP_TAGLEN    (64)
+# endif
+#endif
+#ifndef SOAP_HDRLEN
+# ifndef WITH_LEAN
+#  define SOAP_HDRLEN  (8192) /* maximum length of HTTP header line (must be >4096 to read cookies) */
+# else
+#  define SOAP_HDRLEN  (1024)
+# endif
+#endif
+#ifndef SOAP_MAXDIMS
+# ifndef WITH_LEAN
+#  define SOAP_MAXDIMS	 (16) /* maximum array dimensions (array nestings) must be less than 64 to protect soap->tmpbuf */
+# else
+#  define SOAP_MAXDIMS	  (4)
+# endif
+#endif
+
+#ifndef SOAP_MAXLOGS
+# define SOAP_MAXLOGS	  (3) /* max number of debug logs per struct soap environment */
+# define SOAP_INDEX_RECV  (0)
+# define SOAP_INDEX_SENT  (1)
+# define SOAP_INDEX_TEST  (2)
+#endif
+
+#ifndef SOAP_MAXKEEPALIVE
+# define SOAP_MAXKEEPALIVE (100) /* max iterations to keep server connection alive */
+#endif
+
+#ifndef SOAP_MAXARRAYSIZE
+# define SOAP_MAXARRAYSIZE (100000) /* "trusted" max size of inbound SOAP array for compound array allocation */
+#endif
+
+#ifdef VXWORKS
+# ifdef __INCmathh 
+#  include <private/mathP.h>
+#  ifndef HAVE_ISNAN
+#   define HAVE_ISNAN
+#  endif
+#  define soap_isnan(num) isNan(num)
+# endif
+#endif
+
+#ifdef WIN32 
+# include <float.h>
+# ifndef HAVE_ISNAN
+#  define HAVE_ISNAN
+# endif
+# define soap_isnan(num) _isnan(num)
+#endif
+
+#ifdef SUN_OS
+# define soap_isnan(n) isnan(n)
+#endif
+
+#if !defined(HAVE_ISNAN) && (defined(_MATH_H) || defined(_MATH_INCLUDED))
+# define HAVE_ISNAN
+#endif
+
+#ifndef soap_isnan
+# ifdef HAVE_ISNAN
+#  define soap_isnan(n) isnan(n)
+# else
+#  define soap_isnan(_) (0)
+# endif
+#endif
+
+extern const struct soap_double_nan { unsigned int n1, n2; } soap_double_nan;
+
+#ifdef VXWORKS
+# ifndef FLT_MAX
+#  define FLT_MAX _ARCH_FLT_MAX
+# endif
+# ifndef DBL_MAX
+#  define DBL_MAX _ARCH_DBL_MAX
+# endif
+#endif
+
+#ifndef FLT_NAN
+# ifdef HAVE_ISNAN
+#  define FLT_NAN (*(float*)(void*)&soap_double_nan)
+# else
+#  define FLT_NAN (0.0)
+# endif
+#endif
+
+#ifndef FLT_PINFTY
+# if defined(FLT_MAX)
+#  define FLT_PINFTY FLT_MAX
+# elif defined(HUGE_VALF)
+#  define FLT_PINFTY (float)HUGE_VALF
+# elif defined(HUGE_VAL)
+#  define FLT_PINFTY (float)HUGE_VAL
+# elif defined(FLOAT_MAX)
+#  define FLT_PINFTY FLOAT_MAX
+# else
+#  define FLT_PINFTY (3.40282347e+38F)
+# endif
+#endif
+
+#ifndef FLT_NINFTY
+# define FLT_NINFTY (-FLT_PINFTY)
+#endif
+
+#ifndef DBL_NAN
+# ifdef HAVE_ISNAN
+#  define DBL_NAN (*(double*)(void*)&soap_double_nan)
+# else
+#  define DBL_NAN (0.0)
+# endif
+#endif
+
+#ifndef DBL_PINFTY
+# if defined(DBL_MAX)
+#  define DBL_PINFTY DBL_MAX
+# elif defined(HUGE_VALF)
+#  define DBL_PINFTY (double)HUGE_VALF
+# elif defined(HUGE_VAL)
+#  define DBL_PINFTY (double)HUGE_VAL
+# elif defined(DOUBLE_MAX)
+#  define DBL_PINFTY DOUBLE_MAX
+# else
+#  define DBL_PINFTY (1.7976931348623157e+308)
+# endif
+#endif
+
+#ifndef DBL_NINFTY
+# define DBL_NINFTY (-DBL_PINFTY)
+#endif
+
+#define soap_ispinfd(n) ((n) >= DBL_PINFTY)
+#define soap_ispinff(n) ((n) >= FLT_PINFTY)
+#define soap_isninfd(n) ((n) <= DBL_NINFTY)
+#define soap_isninff(n) ((n) <= FLT_NINFTY)
+
+/* gSOAP error codes */
+
+#define SOAP_EOF			EOF
+#define SOAP_ERR			EOF
+#define SOAP_OK				0
+#define SOAP_CLI_FAULT			1
+#define SOAP_SVR_FAULT			2
+#define SOAP_TAG_MISMATCH		3
+#define SOAP_TYPE			4
+#define SOAP_SYNTAX_ERROR		5
+#define SOAP_NO_TAG			6
+#define SOAP_IOB			7
+#define SOAP_MUSTUNDERSTAND		8
+#define SOAP_NAMESPACE			9
+#define SOAP_USER_ERROR			10
+#define SOAP_FATAL_ERROR		11
+#define SOAP_FAULT			12
+#define SOAP_NO_METHOD			13
+#define SOAP_GET_METHOD			14
+#define SOAP_EOM			15
+#define SOAP_NULL			16
+#define SOAP_DUPLICATE_ID		17
+#define SOAP_MISSING_ID			18
+#define SOAP_HREF			19
+#define SOAP_UDP_ERROR			20
+#define SOAP_TCP_ERROR			21
+#define SOAP_HTTP_ERROR			22
+#define SOAP_SSL_ERROR			23
+#define SOAP_ZLIB_ERROR			24
+#define SOAP_DIME_ERROR			25
+#define SOAP_DIME_HREF			26
+#define SOAP_DIME_MISMATCH		27
+#define SOAP_DIME_END			28
+#define SOAP_MIME_ERROR			29
+#define SOAP_MIME_HREF			30
+#define SOAP_MIME_END			31
+#define SOAP_VERSIONMISMATCH		32
+#define SOAP_PLUGIN_ERROR		33
+#define SOAP_DATAENCODINGUNKNOWN	34
+#define SOAP_REQUIRED			35
+#define SOAP_PROHIBITED			36
+#define SOAP_OCCURS			37
+#define SOAP_LENGTH			38
+
+#define soap_xml_error_check(e) ((e) == SOAP_TAG_MISMATCH || (e) == SOAP_TAG_END || (e) == SOAP_SYNTAX_ERROR || (e) == SOAP_NAMESPACE || (e) == SOAP_DUPLICATE_ID || (e) == SOAP_MISSING_ID || (e) == SOAP_REQUIRED || (e) == SOAP_PROHIBITED || (e) == SOAP_OCCURS || (e) == SOAP_LENGTH || (e) == SOAP_NULL || (e) == SOAP_HREF)
+#define soap_soap_error_check(e) ((e) == SOAP_CLI_FAULT || (e) == SOAP_SVR_FAULT || (e) == SOAP_VERSIONMISMATCH || (e) == SOAP_MUSTUNDERSTAND || (e) == SOAP_FAULT || (e) == SOAP_NO_METHOD)
+#define soap_tcp_error_check(e) ((e) == SOAP_EOF || (e) == SOAP_TCP_ERROR)
+#define soap_ssl_error_check(e) ((e) == SOAP_SSL_ERROR)
+#define soap_zlib_error_check(e) ((e) == SOAP_ZLIB_ERROR)
+#define soap_http_error_check(e) ((e) == SOAP_HTTP_ERROR || (e) == SOAP_GET_METHOD || ((e) >= 100 && (e) < 600))
+
+/* gSOAP HTTP response status codes 100 to 599 are reserved */
+
+/* Codes 600 to 999 are user definable */
+
+/* Exceptional gSOAP HTTP response status codes >= 1000 */
+
+#define SOAP_STOP		1000	/* No HTTP response */
+#define SOAP_FORM		1001	/* Form request/response */
+#define SOAP_HTML		1002	/* Custom HTML response */
+#define SOAP_FILE		1003	/* Custom file-based response */
+
+/* gSOAP HTTP method codes */
+
+#define SOAP_POST		2000
+#define SOAP_GET		2001
+
+/* gSOAP DIME */
+
+#define SOAP_DIME_CF		0x01
+#define SOAP_DIME_ME		0x02
+#define SOAP_DIME_MB		0x04
+#define SOAP_DIME_VERSION	0x08 /* DIME version 1 */
+#define SOAP_DIME_MEDIA		0x10
+#define SOAP_DIME_ABSURI	0x20
+
+/* gSOAP ZLIB */
+
+#define SOAP_ZLIB_NONE		0x00
+#define SOAP_ZLIB_DEFLATE	0x01
+#define SOAP_ZLIB_INFLATE	0x02
+#define SOAP_ZLIB_GZIP		0x02
+
+/* gSOAP transport, connection, and content encoding modes */
+
+typedef soap_int32 soap_mode;
+
+#define SOAP_IO			0x00000003	/* IO mask */
+#define SOAP_IO_FLUSH		0x00000000	/* flush output immediately, no buffering */
+#define SOAP_IO_BUFFER		0x00000001	/* buffer output in packets of size SOAP_BUFLEN */
+#define SOAP_IO_STORE		0x00000002	/* store entire output to determine length for transport */
+#define SOAP_IO_CHUNK		0x00000003	/* use HTTP chunked transfer AND buffer packets */
+
+#define SOAP_IO_UDP		0x00000004
+#define SOAP_IO_LENGTH		0x00000008
+#define SOAP_IO_KEEPALIVE	0x00000010
+
+#define SOAP_ENC_LATIN		0x00800020	/* iso-8859-1 encoding */
+#define SOAP_ENC_XML		0x00000040	/* plain XML encoding, no HTTP header */
+#define SOAP_ENC_DIME		0x00000080
+#define SOAP_ENC_MIME		0x00000100
+#define SOAP_ENC_MTOM		0x00000200
+#define SOAP_ENC_ZLIB		0x00000400
+#define SOAP_ENC_SSL		0x00000800
+
+#define SOAP_ENC		0x00000FFF	/* IO and ENC mask */
+
+#define SOAP_XML_STRICT		0x00001000	/* strict validation */
+#define SOAP_XML_INDENT		0x00002000
+#define SOAP_XML_CANONICAL	0x00004000	/* EXC C14N canonical XML */
+#define SOAP_XML_TREE		0x00008000
+#define SOAP_XML_GRAPH		0x00010000
+#define SOAP_XML_NIL		0x00020000
+#define SOAP_XML_DOM		0x00040000
+#define SOAP_XML_SEC		0x00080000	/* reserved for WS security */
+
+#define SOAP_C_NOIOB		0x00100000
+#define SOAP_C_UTFSTRING	0x00200000
+#define SOAP_C_MBSTRING		0x00400000
+
+#define SOAP_DOM_TREE		0x01000000
+#define SOAP_DOM_NODE		0x02000000
+#define SOAP_DOM_ASIS		0x04000000
+
+#define SOAP_IO_DEFAULT		SOAP_IO_FLUSH
+
+/* SSL client/server authentication settings */
+
+#define SOAP_SSL_NO_AUTHENTICATION		0x00	/* for testing purposes */
+#define SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION	0x01	/* client requires server to authenticate */
+#define SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION	0x02	/* server requires client to authenticate */
+
+#define SOAP_SSL_DEFAULT			SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION
+
+/* */
+
+#define SOAP_BEGIN		0
+#define SOAP_IN_ENVELOPE	2
+#define SOAP_IN_HEADER		3
+#define SOAP_END_HEADER		4
+#define SOAP_NO_BODY		5
+#define SOAP_IN_BODY		6
+#define SOAP_END_BODY		7
+#define SOAP_END_ENVELOPE	8
+#define SOAP_END		9
+#define SOAP_BEGIN_SECURITY	10
+#define SOAP_IN_SECURITY	11
+#define SOAP_END_SECURITY	12
+
+/* DEBUG macros */
+
+#ifndef WITH_LEAN
+# ifdef DEBUG
+#  ifndef SOAP_DEBUG
+#   define SOAP_DEBUG
+#  endif
+# endif
+#endif
+
+#ifdef SOAP_DEBUG
+# define SOAP_MALLOC(soap, size) soap_track_malloc(soap, __FILE__, __LINE__, size)
+# define SOAP_FREE(soap, ptr) soap_track_free(soap, __FILE__, __LINE__, ptr)
+#endif
+
+#ifndef SOAP_MALLOC			/* use libc malloc */
+# define SOAP_MALLOC(soap, size) malloc(size)
+#endif
+
+#ifndef SOAP_FREE			/* use libc free */
+# define SOAP_FREE(soap, ptr) free(ptr)
+#endif
+
+#ifdef SOAP_DEBUG
+# ifndef SOAP_MESSAGE
+#  define SOAP_MESSAGE fprintf
+# endif
+# ifndef DBGLOG
+#  define DBGLOG(DBGFILE, CMD) \
+{ if (soap)\
+  { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\
+      soap_open_logfile(soap, SOAP_INDEX_##DBGFILE);\
+    if (soap->fdebug[SOAP_INDEX_##DBGFILE])\
+    { FILE *fdebug = soap->fdebug[SOAP_INDEX_##DBGFILE];\
+      CMD;\
+      fflush(fdebug);\
+    }\
+  }\
+}
+# endif
+# ifndef DBGMSG
+#  define DBGMSG(DBGFILE, MSG, LEN) \
+{ if (soap)\
+  { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\
+      soap_open_logfile(soap, SOAP_INDEX_##DBGFILE);\
+    if (soap->fdebug[SOAP_INDEX_##DBGFILE])\
+    { fwrite((MSG), 1, (LEN), soap->fdebug[SOAP_INDEX_##DBGFILE]);\
+      fflush(soap->fdebug[SOAP_INDEX_##DBGFILE]);\
+    }\
+  }\
+}
+# endif
+# ifndef DGBFUN
+#  define DBGFUN(FNAME) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s()\n", __FILE__, __LINE__, FNAME))
+#  define DBGFUN1(FNAME, FMT, ARG) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT")\n", __FILE__, __LINE__, FNAME, (ARG)))
+#  define DBGFUN2(FNAME, FMT1, ARG1, FMT2, ARG2) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT1", "FMT2")\n", __FILE__, __LINE__, FNAME, (ARG1), (ARG2)))
+#  define DBGFUN3(FNAME, FMT1, ARG1, FMT2, ARG2, FMT3, ARG3) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "%s(%d): %s("FMT1", "FMT2", "FMT3")\n", __FILE__, __LINE__, FNAME, (ARG1), (ARG2), (ARG3)))
+# endif
+# ifndef DBGHEX
+#  define DBGHEX(DBGFILE, MSG, LEN) \
+{ if (soap)\
+  { if (!soap->fdebug[SOAP_INDEX_##DBGFILE])\
+      soap_open_logfile(soap, SOAP_INDEX_##DBGFILE);\
+    if (soap->fdebug[SOAP_INDEX_##DBGFILE])\
+    { int i; char *s;\
+      for (s = (char*)(MSG), i = (LEN); i; i--)\
+        fprintf(soap->fdebug[SOAP_INDEX_##DBGFILE], "%2.2hhX  ", *s++);\
+      fflush(soap->fdebug[SOAP_INDEX_##DBGFILE]);\
+    }\
+  }\
+}
+# endif
+#else
+# define DBGLOG(DBGFILE, CMD)
+# define DBGMSG(DBGFILE, MSG, LEN)
+# define DBGFUN(FNAME)
+# define DBGFUN1(FNAME, FMT, ARG)
+# define DBGFUN2(FNAME, FMT1, ARG1, FMT2, ARG2)
+# define DBGFUN3(FNAME, FMT1, ARG1, FMT2, ARG2, FMT3, ARG3)
+# define DBGHEX(DBGFILE, MSG, LEN)
+#endif
+
+/* UCS-4 requires 32 bits (0-7FFFFFFF, the sign bit is used by gSOAP to distinguish XML entities) */
+typedef soap_int32 soap_wchar;
+
+/* namespace table row */
+struct Namespace
+{ const char *id;
+  const char *ns;
+  const char *in;
+  char *out;
+};
+
+/* namespace stack */
+struct soap_nlist
+{ struct soap_nlist *next;
+  unsigned int level; /* nesting depth level */
+  short index; /* corresponding entry in ns mapping table */
+  char *ns; /* only set when parsed ns URI is not in the ns mapping table */
+  char id[1]; /* the actual string value flows into the allocated region below this struct */
+};
+
+/* block stack for nested block allocations */
+struct soap_blist
+{ struct soap_blist *next;
+  char *ptr;
+  size_t size;
+};
+
+/* array layout */
+struct soap_array
+{ void *__ptr;
+  int __size;
+};
+
+/* pointer serialization management */
+struct soap_plist
+{ struct soap_plist *next;
+  const void *ptr;
+  const struct soap_array *array;
+  int type;
+  int id;
+  char mark1;
+  char mark2;
+};
+
+/* block allocation for pointer serialization management */
+struct soap_pblk
+{ struct soap_pblk *next;
+  struct soap_plist plist[SOAP_PTRBLK];
+};
+
+#ifdef SOAP_DEBUG
+/* malloc/free tracking for debugging */
+struct soap_mlist
+{ struct soap_mlist *next;
+  const void *ptr;
+  const char *file;
+  int line;
+  short live;
+};
+#endif
+
+/* class allocation list */
+struct soap_clist
+{ struct soap_clist *next;
+  void *ptr;
+  int type;
+  int size;
+  void (*fdelete)(struct soap_clist*);
+};
+
+/* attributes */
+struct soap_attribute
+{ struct soap_attribute *next;
+  char *value;
+  size_t size;
+  char *ns;
+  short visible;
+  char name[1]; /* the actual name string flows into the allocated region below this struct */
+};
+
+struct soap_cookie
+{ struct soap_cookie *next;
+  char *name;
+  char *value;
+  char *domain;
+  char *path;
+  long expire;		/* client-side: local time to expire; server-side: seconds to expire */
+  unsigned int version;
+  short secure;
+  short session;	/* server-side */
+  short env;		/* server-side: got cookie from client and should not be (re)send */
+  short modified;	/* server-side: client cookie was modified and should be send */
+};
+
+#ifdef __cplusplus
+SOAP_FMAC1 struct soap_multipart* SOAP_FMAC2 soap_next_multipart(struct soap_multipart*);
+
+class soap_multipart_iterator
+{ public:
+  struct soap_multipart *content;
+  bool operator==(const soap_multipart_iterator& iter) const
+    { return content == iter.content; }
+  bool operator!=(const soap_multipart_iterator& iter) const
+    { return content != iter.content; }
+  struct soap_multipart &operator*() const
+    { return *content; }
+  soap_multipart_iterator &operator++()
+    { content = soap_next_multipart(content); return *this; }
+  soap_multipart_iterator() : content(NULL)
+    { }
+  soap_multipart_iterator(struct soap_multipart *p) : content(p)
+    { }
+};
+#endif
+
+#ifndef WITH_LEANER
+struct soap_dime
+{ size_t count;
+  size_t size;
+  size_t chunksize;
+  size_t buflen;
+  char flags;
+  char *ptr;
+  const char *id;
+  const char *type;
+  const char *options;
+  struct soap_multipart *list;		/* list of DIME attachments received */
+  struct soap_multipart *first, *last;	/* temporary in/out queue */
+#ifdef __cplusplus
+  soap_multipart_iterator begin()
+    { soap_multipart_iterator iter(list); return iter; };
+  soap_multipart_iterator end()
+    { soap_multipart_iterator iter(NULL); return iter; };
+#endif
+};
+#endif
+
+#ifndef WITH_LEANER
+struct soap_mime
+{ char *boundary;			/* MIME boundary */
+  const char *start;			/* MIME start ID */
+  struct soap_multipart *list;		/* list of MIME attachments received */
+  struct soap_multipart *first, *last;	/* temporary in/out queue */
+#ifdef __cplusplus
+  soap_multipart_iterator begin()
+    { soap_multipart_iterator iter(list); return iter; };
+  soap_multipart_iterator end()
+    { soap_multipart_iterator iter(NULL); return iter; };
+#endif
+};
+#endif
+
+#ifndef WITH_LEANER
+/* RFC2045 MIME content transfer encodings */
+enum soap_mime_encoding
+{ SOAP_MIME_NONE,
+  SOAP_MIME_7BIT,
+  SOAP_MIME_8BIT,
+  SOAP_MIME_BINARY,
+  SOAP_MIME_QUOTED_PRINTABLE,
+  SOAP_MIME_BASE64,
+  SOAP_MIME_IETF_TOKEN,
+  SOAP_MIME_X_TOKEN
+};
+#endif
+
+#ifndef WITH_LEANER
+/* DIME/MIME multipart list */
+struct soap_multipart
+{ struct soap_multipart *next;
+  char *ptr;				/* points to raw data content */
+  size_t size;				/* size of data content */
+  const char *id;			/* DIME/MIME content ID or form data name */
+  const char *type;			/* DIME/MIME type (MIME type format) */
+  const char *options;			/* DIME options */
+  enum soap_mime_encoding encoding;	/* MIME Content-Transfer-Encoding */
+  const char *location;			/* MIME Content-Location (optional) */
+  const char *description;		/* MIME Content-Description (optional) */
+#ifdef __cplusplus
+  typedef soap_multipart_iterator iterator;
+#endif
+};
+#endif
+
+#ifndef WITH_LEANER
+/* attachment DIME and MTOM XOP forwarding */
+struct soap_xlist
+{ struct soap_xlist *next;
+  unsigned char **ptr;
+  int *size;
+  char *id;
+  char **type;
+  char **options;
+};
+#endif
+
+/******************************************************************************/
+
+#ifndef WITH_LEANER
+#ifdef __cplusplus
+class soap_dom_attribute_iterator
+{ public:
+  struct soap_dom_attribute *att;
+  const char *nstr;
+  const char *name;
+  bool operator==(const soap_dom_attribute_iterator&) const;
+  bool operator!=(const soap_dom_attribute_iterator&) const;
+  struct soap_dom_attribute &operator*() const;
+  soap_dom_attribute_iterator &operator++();
+  soap_dom_attribute_iterator();
+  soap_dom_attribute_iterator(struct soap_dom_attribute*);
+  ~soap_dom_attribute_iterator();
+};
+#endif
+#endif
+
+#ifndef WITH_LEANER
+struct soap_dom_attribute
+{ struct soap_dom_attribute *next;
+  const char *nstr;
+  char *name;
+  char *data;
+  wchar_t *wide;
+  struct soap *soap;
+#ifdef __cplusplus
+  typedef soap_dom_attribute_iterator iterator;
+  struct soap_dom_attribute &set(const char *nstr, const char *name);	/* set namespace and name */
+  struct soap_dom_attribute &set(const char *data);		/* set data */
+  soap_dom_attribute_iterator begin();
+  soap_dom_attribute_iterator end();
+  soap_dom_attribute_iterator find(const char *nstr, const char *name);
+  void unlink();
+  soap_dom_attribute();
+  soap_dom_attribute(struct soap *soap);
+  soap_dom_attribute(struct soap *soap, const char *nstr, const char *name, const char *data);
+  ~soap_dom_attribute();
+#endif
+};
+#endif
+
+#ifndef WITH_LEANER
+#ifdef __cplusplus
+class soap_dom_element_iterator
+{ public:
+  struct soap_dom_element *elt;
+  const char *nstr;
+  const char *name;
+  int type;
+  bool operator==(const soap_dom_element_iterator&) const;
+  bool operator!=(const soap_dom_element_iterator&) const;
+  struct soap_dom_element &operator*() const;
+  soap_dom_element_iterator &operator++();
+  soap_dom_element_iterator();
+  soap_dom_element_iterator(struct soap_dom_element*);
+  ~soap_dom_element_iterator();
+};
+#endif
+#endif
+
+#ifndef WITH_LEANER
+struct soap_dom_element
+{ struct soap_dom_element *next;	/* next sibling */
+  struct soap_dom_element *prnt;	/* parent */
+  struct soap_dom_element *elts;	/* list of child elements */
+  struct soap_dom_attribute *atts;	/* list of attributes */
+  const char *nstr;			/* namespace string */
+  char *name;				/* element tag name */
+  char *data;				/* element content data (with SOAP_C_UTFSTRING flag set) */
+  wchar_t *wide;			/* element content data */
+  int type;				/* optional: serialized C/C++ data type */
+  void *node;				/* optional: pointer to serialized C/C++ data */
+  char *head;				/* leading whitespace to start tag */
+  char *tail;				/* leading whitespace to end tag */
+  struct soap *soap;			/* soap context that manages this node */
+#ifdef __cplusplus
+  typedef soap_dom_element_iterator iterator;
+  struct soap_dom_element &set(const char *nstr, const char *name);
+  struct soap_dom_element &set(const char *data);
+  struct soap_dom_element &set(void *node, int type);
+  struct soap_dom_element &add(struct soap_dom_element*);
+  struct soap_dom_element &add(struct soap_dom_element&);
+  struct soap_dom_element &add(struct soap_dom_attribute*);
+  struct soap_dom_element &add(struct soap_dom_attribute&);
+  soap_dom_element_iterator begin();
+  soap_dom_element_iterator end();
+  soap_dom_element_iterator find(const char *nstr, const char *name);
+  soap_dom_element_iterator find(int type);
+  void unlink();
+  soap_dom_element();
+  soap_dom_element(struct soap *soap);
+  soap_dom_element(struct soap *soap, const char *nstr, const char *name);
+  soap_dom_element(struct soap *soap, const char *nstr, const char *name, const char *data);
+  soap_dom_element(struct soap *soap, const char *nstr, const char *name, void *node, int type);
+  ~soap_dom_element();
+#endif
+};
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_dom_current_nstr(struct soap *soap, const char *tag);
+SOAP_FMAC1 struct soap_dom_element * SOAP_FMAC2 soap_dom_next_element(struct soap_dom_element *elt);
+SOAP_FMAC1 struct soap_dom_attribute * SOAP_FMAC2 soap_dom_next_attribute(struct soap_dom_attribute *att);
+#endif
+
+#if defined(__cplusplus) && !defined(WITH_LEAN)
+}
+extern std::ostream &operator<<(std::ostream&, const struct soap_dom_element&);
+extern std::istream &operator>>(std::istream&, struct soap_dom_element&);
+extern "C" {
+#endif
+
+/******************************************************************************/
+
+struct soap
+{ short version;		/* 1 = SOAP1.1 and 2 = SOAP1.2 (set automatically from namespace URI in nsmap table) */
+  short copy;			/* 1 = copy of another soap struct */
+  soap_mode mode;
+  soap_mode imode;
+  soap_mode omode;
+  const char *float_format;	/* user-definable format string for floats (<1024 chars) */
+  const char *double_format;	/* user-definable format string for doubles (<1024 chars) */
+  const char *dime_id_format;	/* user-definable format string for integer DIME id (<SOAP_TAGLEN chars) */
+  const char *http_version;	/* HTTP version used "1.0" or "1.1" */
+  const char *http_content;	/* optional custom response content type (with SOAP_FILE) */
+  const char *encodingStyle;	/* default = NULL which means that SOAP encoding is used */
+  const char *actor;		/* SOAP-ENV:actor or role attribute value */
+  int recv_timeout;		/* when > 0, gives socket recv timeout in seconds, < 0 in usec */
+  int send_timeout;		/* when > 0, gives socket send timeout in seconds, < 0 in usec */
+  int connect_timeout;		/* when > 0, gives socket connect() timeout in seconds, < 0 in usec */
+  int accept_timeout;		/* when > 0, gives socket accept() timeout in seconds, < 0 in usec */
+  int socket_flags;		/* socket recv() and send() flags, e.g. set to MSG_NOSIGNAL to disable sigpipe */
+  int connect_flags;		/* connect() SOL_SOCKET sockopt flags, e.g. set to SO_DEBUG to debug socket */
+  int bind_flags;		/* bind() SOL_SOCKET sockopt flags, e.g. set to SO_REUSEADDR to enable reuse */
+  int accept_flags;		/* accept() SOL_SOCKET sockopt flags */
+  const struct Namespace *namespaces;	/* Pointer to global namespace mapping table */
+  struct Namespace *local_namespaces;	/* Local namespace mapping table */
+  struct soap_nlist *nlist;	/* namespace stack */
+  struct soap_blist *blist;	/* block allocation stack */
+  struct soap_clist *clist;	/* class instance allocation list */
+  void *alist;			/* memory allocation (malloc) list */
+  struct soap_ilist *iht[SOAP_IDHASH];
+  struct soap_plist *pht[SOAP_PTRHASH];
+  struct soap_pblk *pblk;	/* plist block allocation */
+  short pidx;			/* plist block allocation */
+  struct SOAP_ENV__Header *header;
+  struct SOAP_ENV__Fault *fault;
+  int idnum;
+  void *user;			/* to pass user-defined data */
+  struct soap_plugin *plugins;	/* linked list of plug-in data */
+  char *userid;			/* HTTP Basic authorization userid */
+  char *passwd;			/* HTTP Basic authorization passwd */
+  int (*fpost)(struct soap*, const char*, const char*, int, const char*, const char*, size_t);
+  int (*fget)(struct soap*);
+  int (*fform)(struct soap*);
+  int (*fposthdr)(struct soap*, const char*, const char*);
+  int (*fresponse)(struct soap*, int, size_t);
+  int (*fparse)(struct soap*);
+  int (*fparsehdr)(struct soap*, const char*, const char*);
+  int (*fresolve)(struct soap*, const char*, struct in_addr* inaddr);
+  int (*fconnect)(struct soap*, const char*, const char*, int);
+  int (*fdisconnect)(struct soap*);
+  int (*fclosesocket)(struct soap*, SOAP_SOCKET);
+  int (*fshutdownsocket)(struct soap*, SOAP_SOCKET, int);
+  int (*fopen)(struct soap*, const char*, const char*, int);
+  int (*faccept)(struct soap*, int, struct sockaddr*, int *n);
+  int (*fclose)(struct soap*);
+  int (*fsend)(struct soap*, const char*, size_t);
+  size_t (*frecv)(struct soap*, char*, size_t);
+  int (*fpoll)(struct soap*);
+  void (*fseterror)(struct soap*, const char **c, const char **s);
+  int (*fignore)(struct soap*, const char*);
+  int (*fserveloop)(struct soap*);
+  void *(*fplugin)(struct soap*, const char*);
+#ifndef WITH_LEANER
+  int (*fprepareinit)(struct soap*);
+  int (*fpreparesend)(struct soap*, const char*, size_t);
+  int (*fpreparerecv)(struct soap*, const char*, size_t);
+  int (*fpreparefinal)(struct soap*);
+  void *(*fdimereadopen)(struct soap*, void*, const char*, const char*, const char*);
+  void *(*fdimewriteopen)(struct soap*, const char*, const char*, const char*);
+  void (*fdimereadclose)(struct soap*, void*);
+  void (*fdimewriteclose)(struct soap*, void*);
+  size_t (*fdimeread)(struct soap*, void*, char*, size_t);
+  int (*fdimewrite)(struct soap*, void*, const char*, size_t);
+#endif
+  int master;
+  int socket;
+#if defined(__cplusplus) && !defined(WITH_LEAN)
+  std::ostream *os;
+  std::istream *is;
+#else
+  void *os;	/* preserve alignment */
+  void *is;	/* preserve alignment */
+#endif
+#ifndef UNDER_CE
+  int sendfd;
+  int recvfd;
+#else
+  FILE *sendfd;
+  FILE *recvfd;
+#endif
+#ifdef WIN32
+  char errorstr[256];	/* buf for FormatMessage() */
+#endif
+  size_t bufidx;	/* index in soap.buf[] */
+  size_t buflen;	/* length of soap.buf[] content */
+  soap_wchar ahead;	/* parser lookahead */
+  short cdata;		/* CDATA parser state */
+  short body;		/* parsed XML element has a body or not */
+  unsigned int level;	/* XML nesting level */
+  size_t count;		/* message length counter */
+  size_t length;	/* message length as set by HTTP header */
+#ifdef WITH_FAST
+  char *labbuf;		/* look-aside buffer */
+  size_t lablen;	/* look-aside buffer allocated length */
+  size_t labidx;	/* look-aside buffer index to available part */
+#endif
+  char buf[SOAP_BUFLEN];/* send and receive buffer */
+  char tmpbuf[1024];	/* in/output buffer for HTTP headers, simpleType values, attribute names, and DIME >=1024 bytes */
+  char msgbuf[1024];	/* output buffer for (error) messages <=1024 bytes */
+  char tag[SOAP_TAGLEN];
+  char id[SOAP_TAGLEN];
+  char href[SOAP_TAGLEN];
+  char type[SOAP_TAGLEN];
+  char arrayType[SOAP_TAGLEN];
+  char arraySize[SOAP_TAGLEN];
+  char arrayOffset[SOAP_TAGLEN];
+  short other;
+  short position;
+  int positions[SOAP_MAXDIMS];
+  short root;
+  struct soap_attribute *attributes;	/* attribute list */
+  short encoding;	/* when set, output encodingStyle */
+  short mustUnderstand;	/* a mustUnderstand element was parsed or is output */
+  short keep_alive;	/* connection should be kept open */
+  short null;		/* parsed XML is xsi:nil */
+  short ns;		/* when not set, output full xmlns bindings */
+  short part;		/* parsing state */
+  short alloced;
+  short peeked;
+  size_t chunksize;
+  size_t chunkbuflen;
+  char endpoint[SOAP_TAGLEN];
+  char path[SOAP_TAGLEN];
+  char host[SOAP_TAGLEN];
+  char *action;
+  char *authrealm;		/* HTTP authentication realm */
+  char *prolog;			/* XML declaration prolog */
+  unsigned long ip;		/* IP number */
+  int port;			/* port number */
+  unsigned int max_keep_alive;
+  const char *proxy_host;	/* Proxy Server host name */
+  int proxy_port;		/* Proxy Server port (default = 8080) */
+  const char *proxy_userid;	/* Proxy Authorization user name */
+  const char *proxy_passwd;	/* Proxy Authorization password */
+  int status;			/* -1 when request, else error code to be returned by server */
+  int error;
+  int errmode;
+  int errnum;
+#ifndef WITH_LEANER
+  struct soap_dom_element *dom;
+  struct soap_dime dime;
+  struct soap_mime mime;
+  struct soap_xlist *xlist;
+#endif
+#if !defined(WITH_LEAN) || defined(SOAP_DEBUG)
+  const char *logfile[SOAP_MAXLOGS];
+  FILE *fdebug[SOAP_MAXLOGS];
+  struct soap_mlist *mht[SOAP_PTRHASH];
+#endif
+#ifndef WITH_LEAN
+  const char *c14ninclude;
+  const char *c14nexclude;
+  struct soap_cookie *cookies;
+  const char *cookie_domain;
+  const char *cookie_path;
+  int cookie_max;
+#endif
+#ifndef WITH_NOIO
+#ifdef WITH_IPV6
+  struct sockaddr_storage peer;	/* IPv6: set by soap_accept and by UDP recv */
+#else
+  struct sockaddr_in peer;	/* IPv4: set by soap_connect/soap_accept and by UDP recv */
+#endif
+  size_t peerlen;
+#endif
+#ifdef WITH_OPENSSL
+  int (*fsslauth)(struct soap*);
+  int (*fsslverify)(int, X509_STORE_CTX*);
+  BIO *bio;
+  SSL *ssl;
+  SSL_CTX *ctx;
+  short require_server_auth;
+  short require_client_auth;
+  short rsa;			/* when set, use RSA instead of DH */
+  const char *keyfile;
+  const char *password;
+  const char *dhfile;
+  const char *cafile;
+  const char *capath;
+  const char *crlfile;
+  const char *randfile;
+  SSL_SESSION *session;
+  char session_host[SOAP_TAGLEN];
+  int session_port;
+#endif
+#ifdef WITH_ZLIB
+  short zlib_state;		/* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_INFLATE */
+  short zlib_in;		/* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_GZIP */
+  short zlib_out;		/* SOAP_ZLIB_NONE, SOAP_ZLIB_DEFLATE, or SOAP_ZLIB_GZIP */
+  z_stream d_stream;		/* decompression stream */
+  char z_buf[SOAP_BUFLEN];	/* buffer */
+  size_t z_buflen;
+  unsigned short z_level;	/* compression level to be used (0=none, 1=fast to 9=best) */
+  uLong z_crc;			/* internal gzip crc */
+  float z_ratio_in;		/* detected compression ratio compressed_length/length of inbound message */
+  float z_ratio_out;		/* detected compression ratio compressed_length/length of outbound message */
+#endif
+/* WR[ */
+#ifdef WMW_RPM_IO
+  void *rpmreqid;
+#endif /* WMW_RPM_IO */
+/* ]WR */
+};
+
+struct soap_code_map
+{ long code;
+  const char *string;
+};
+
+/* forwarding list */
+struct soap_flist
+{ struct soap_flist *next;
+  int type;
+  void *ptr;
+  unsigned int level;
+  void (*fcopy)(struct soap*, int, int, void*, const void*, size_t);
+};
+
+/* id-ref forwarding list */
+struct soap_ilist
+{ struct soap_ilist *next;
+  int type;
+  size_t size;
+  void *link;
+  void *copy;
+  struct soap_flist *flist;
+  void *ptr;
+  unsigned int level;
+  char id[1]; /* the actual id string value flows into the allocated region below this struct */
+};
+
+struct soap_plugin
+{ struct soap_plugin *next;
+  const char *id;
+  void *data;
+  int (*fcopy)(struct soap *soap, struct soap_plugin *dst, struct soap_plugin *src);
+  void (*fdelete)(struct soap *soap, struct soap_plugin *p); /* should delete fields of plugin only and not free(p) */
+};
+
+#ifndef WITH_NONAMESPACES
+extern SOAP_NMAC struct Namespace namespaces[];
+#endif
+
+#ifndef WITH_LEAN
+# define soap_get0(soap) (((soap)->bufidx>=(soap)->buflen && soap_recv(soap)) ? EOF : (unsigned char)(soap)->buf[(soap)->bufidx])
+# define soap_get1(soap) (((soap)->bufidx>=(soap)->buflen && soap_recv(soap)) ? EOF : (unsigned char)(soap)->buf[(soap)->bufidx++])
+#else
+soap_wchar soap_get0(struct soap*);
+soap_wchar soap_get1(struct soap*);
+#endif
+
+#define soap_revget1(soap) ((soap)->bufidx--)
+#define soap_unget(soap, c) ((soap)->ahead = c)
+#define soap_register_plugin(soap, plugin) soap_register_plugin_arg(soap, plugin, NULL)
+#define soap_imode(soap, n) ((soap)->mode = (soap)->imode = (n))
+#define soap_set_imode(soap, n) ((soap)->imode |= (n))
+#define soap_clr_imode(soap, n) ((soap)->imode &= ~(n))
+#define soap_omode(soap, n) ((soap)->mode = (soap)->omode = (n))
+#define soap_set_omode(soap, n) ((soap)->omode |= (n))
+#define soap_clr_omode(soap, n) ((soap)->omode &= ~(n))
+#define soap_set_mode(soap, n) ((soap)->imode |= (n), (soap)->omode |= (n))
+#define soap_clr_mode(soap, n) ((soap)->imode &= ~(n), (soap)->omode &= ~(n))
+#define soap_destroy(soap) soap_delete((soap), NULL)
+
+#ifdef HAVE_STRRCHR
+# define soap_strrchr(s, t) strrchr(s, t)
+#else
+ SOAP_FMAC1 char* SOAP_FMAC2 soap_strrchr(const char *s, int t);
+#endif
+
+#ifdef HAVE_STRTOL
+# define soap_strtol(s, t, b) strtol(s, t, b)
+#else
+ SOAP_FMAC1 long SOAP_FMAC2 soap_strtol(const char *s, char **t, int b);
+#endif
+
+#ifdef HAVE_STRTOUL
+# define soap_strtoul(s, t, b) strtoul(s, t, b)
+#else
+ SOAP_FMAC1 unsigned long SOAP_FMAC2 soap_strtoul(const char *s, char **t, int b);
+#endif
+
+#if defined(WITH_OPENSSL)
+# define soap_random soap_rand()
+SOAP_FMAC1 int SOAP_FMAC2 soap_rand();
+#elif defined(HAVE_RANDOM)
+# define soap_random (int)random()
+#else
+# define soap_random rand()
+#endif
+
+#ifdef WITH_NOIDREF
+# define soap_embedded(s, p, t) (0)
+# define soap_id_lookup(s, i, p, t, n, k) (p)
+# define soap_id_forward(s, h, p, st, tt, n, k, fc) (p)
+# define soap_reference(s, a, t) (1)
+# define soap_array_reference(s, p, a, n, t) (1)
+# define soap_embed(s, p, a, n, t, pp) (0)
+# define soap_embedded_id(s, i, p, t) (i)
+# define soap_is_embedded(s, p) (0)
+# define soap_is_single(s, p) (1)
+# define soap_lookup_type(s, i) (0)
+# define soap_getindependent(s) (0)
+# define soap_putindependent(s) (0)
+# define soap_getelement(s, n) (n)
+# define soap_putelement(s, p, t, i, n) (0)
+# define soap_markelement(s, p, n) (0)
+#endif
+
+SOAP_FMAC1 void SOAP_FMAC2 soap_fault(struct soap*);
+SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultcode(struct soap*);
+SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultsubcode(struct soap*);
+SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultstring(struct soap*);
+SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultdetail(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_serializeheader(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_putheader(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getheader(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_serializefault(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_putfault(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getfault(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_poll(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_connect_command(struct soap*, int, const char*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_connect(struct soap*, const char*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_bind(struct soap*, const char*, int, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_accept(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_accept(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_server_context(struct soap*, unsigned short, const char*, const char*, const char*, const char*, const char*, const char*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_client_context(struct soap*, unsigned short, const char*, const char*, const char*, const char*, const char*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_puthttphdr(struct soap*, int status, size_t count);
+
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_get_header_attribute(struct soap*, const char*, const char*);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_decode_key(char*, size_t, const char*);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_decode_val(char*, size_t, const char*);
+
+SOAP_FMAC1 size_t SOAP_FMAC2 soap_hash(const char*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_endpoint(struct soap*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_flush_raw(struct soap*, const char*, size_t);
+SOAP_FMAC1 int SOAP_FMAC2 soap_flush(struct soap*);
+SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_get(struct soap*);
+SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_getchar(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_tag_cmp(const char*, const char*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_fault(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_sender_fault(struct soap*, const char*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_sender_fault_subcode(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_receiver_fault(struct soap*, const char*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_receiver_fault_subcode(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_set_sender_error(struct soap*, const char*, const char*, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_set_receiver_error(struct soap*, const char*, const char*, int);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_send_raw(struct soap*, const char*, size_t);
+SOAP_FMAC1 int SOAP_FMAC2 soap_recv_raw(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_recv(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_send(struct soap*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_send2(struct soap*, const char*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_send3(struct soap*, const char*, const char*, const char*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_pututf8(struct soap*, unsigned long);
+SOAP_FMAC1 soap_wchar SOAP_FMAC2 soap_getutf8(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_putbase64(struct soap*, const unsigned char*, int);
+SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_getbase64(struct soap*, int*, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_puthex(struct soap*, const unsigned char*, int);
+SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_gethex(struct soap*, int*);
+
+#ifndef WITH_LEANER
+SOAP_FMAC1 int SOAP_FMAC2 soap_xop_forward(struct soap*, unsigned char**, int*, char**, char**, char**);
+SOAP_FMAC1 int SOAP_FMAC2 soap_dime_forward(struct soap*, unsigned char**, int*, char**, char**, char**);
+#endif
+
+#ifndef WITH_NOIDREF
+SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_lookup_id(struct soap*, void *p, int t, struct soap_plist**);
+SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_lookup(struct soap*, const void *p, int t, struct soap_plist**);
+SOAP_FMAC1 int SOAP_FMAC2 soap_pointer_enter(struct soap*, const void *p, const struct soap_array *a, int n, int t, struct soap_plist**);
+SOAP_FMAC1 int SOAP_FMAC2 soap_array_pointer_lookup(struct soap*, const void *p, const struct soap_array *a, int n, int t, struct soap_plist**);
+SOAP_FMAC1 int SOAP_FMAC2 soap_embed(struct soap *soap, const void *p, const struct soap_array *a, int n, const char *tag, int type);
+SOAP_FMAC1 struct soap_ilist* SOAP_FMAC2 soap_lookup(struct soap*, const char*);
+SOAP_FMAC1 struct soap_ilist* SOAP_FMAC2 soap_enter(struct soap*, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_resolve(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_embedded(struct soap*, const void *p, int t);
+SOAP_FMAC1 int SOAP_FMAC2 soap_reference(struct soap*, const void *p, int t);
+SOAP_FMAC1 int SOAP_FMAC2 soap_array_reference(struct soap*, const void *p, const struct soap_array *a, int n, int t);
+SOAP_FMAC1 int SOAP_FMAC2 soap_embedded_id(struct soap*, int id, const void *p, int t);
+SOAP_FMAC1 int SOAP_FMAC2 soap_is_embedded(struct soap*, struct soap_plist*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_is_single(struct soap*, struct soap_plist*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_embedded(struct soap*, struct soap_plist*);
+#endif
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_begin_count(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_end_count(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_begin_send(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_end_send(struct soap*);
+
+SOAP_FMAC1 const struct soap_code_map* SOAP_FMAC2 soap_code(const struct soap_code_map*, const char *str);
+SOAP_FMAC1 long SOAP_FMAC2 soap_int_code(const struct soap_code_map*, const char *str, long other);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_str_code(const struct soap_code_map*, long code);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_getline(struct soap*, char*, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_begin_recv(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_end_recv(struct soap*);
+
+SOAP_FMAC1 void* SOAP_FMAC2 soap_malloc(struct soap*, size_t);
+SOAP_FMAC1 void SOAP_FMAC2 soap_dealloc(struct soap*, void*);
+SOAP_FMAC1 struct soap_clist * SOAP_FMAC2 soap_link(struct soap*, void*, int, int, void (*fdelete)(struct soap_clist*));
+SOAP_FMAC1 void SOAP_FMAC2 soap_unlink(struct soap*, const void*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_free(struct soap*);
+
+SOAP_FMAC1 void* SOAP_FMAC2 soap_track_malloc(struct soap*, const char*, int, size_t);
+SOAP_FMAC1 void SOAP_FMAC2 soap_track_free(struct soap*, const char*, int, void*);
+
+#ifndef WITH_NOIDREF
+SOAP_FMAC1 int SOAP_FMAC2 soap_lookup_type(struct soap*, const char *id);
+SOAP_FMAC1 void* SOAP_FMAC2 soap_id_lookup(struct soap*, const char *id, void **p, int t, size_t n, unsigned int k);
+SOAP_FMAC1 void* SOAP_FMAC2 soap_id_forward(struct soap*, const char *id, void *p, int st, int tt, size_t n, unsigned int k, void(*fcopy)(struct soap*, int, int, void*, const void*, size_t));
+#endif
+SOAP_FMAC1 void* SOAP_FMAC2 soap_id_enter(struct soap*, const char *id, void *p, int t, size_t n, unsigned int k, const char *type, const char *arrayType, void *(*finstantiate)(struct soap*, int, const char*, const char*, size_t*));
+SOAP_FMAC1 void SOAP_FMAC2 soap_fcopy(struct soap *soap, int st, int tt, void *p, const void *q, size_t n);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_size(const int *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getoffsets(const char *, const int *, int *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getsize(const char *, const char *, int *);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getsizes(const char *, int *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getposition(const char *, int *);
+
+SOAP_FMAC1 char* SOAP_FMAC2 soap_putsize(struct soap*, const char *, int);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_putsizesoffsets(struct soap*, const char *, const int *, const int *, int);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_putsizes(struct soap*, const char *, const int *, int);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_putoffset(struct soap*, int);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_putoffsets(struct soap*, const int *, int);
+ 
+SOAP_FMAC1 int SOAP_FMAC2 soap_closesock(struct soap*);
+
+SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new(void);
+SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new1(soap_mode);
+SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new2(soap_mode, soap_mode);
+SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_copy(struct soap*);
+SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_copy_context(struct soap*,struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_init(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_init1(struct soap*, soap_mode);
+SOAP_FMAC1 void SOAP_FMAC2 soap_init2(struct soap*, soap_mode, soap_mode);
+SOAP_FMAC1 void SOAP_FMAC2 soap_done(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_cleanup(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_begin(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_end(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_delete(struct soap*, void*);
+
+#ifdef SOAP_DEBUG
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_recv_logfile(struct soap*, const char*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_sent_logfile(struct soap*, const char*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_test_logfile(struct soap*, const char*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_close_logfiles(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_open_logfile(struct soap*, int);
+#endif
+
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_token(struct soap*);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_value(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_match_tag(struct soap*, const char*, const char *);
+SOAP_FMAC1 int SOAP_FMAC2 soap_match_array(struct soap*, const char*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_element(struct soap*, const char*, int, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_begin_out(struct soap*, const char *tag, int id, const char *type);
+SOAP_FMAC1 int SOAP_FMAC2 soap_array_begin_out(struct soap*, const char *tag, int id, const char *type, const char *offset);
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_ref(struct soap*, const char *tag, int id, int href);
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_href(struct soap*, const char *tag, int id, const char *ref, const char *val);
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_null(struct soap*, const char *tag, int id, const char *type);
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_id(struct soap*, const char *tag, int id, const void *p, const struct soap_array *a, int d, const char *type, int n);
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_result(struct soap*, const char *tag);
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_end_out(struct soap*, const char *tag);
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_start_end_out(struct soap*, const char *tag);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_attribute(struct soap*, const char*, const char*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_begin_in(struct soap*, const char *tag, int nillable);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_element_end_in(struct soap*, const char *tag);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_peek_element(struct soap*);
+
+SOAP_FMAC1 void SOAP_FMAC2 soap_retry(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_revert(struct soap*);
+
+SOAP_FMAC1 char* SOAP_FMAC2 soap_strdup(struct soap*, const char*);
+SOAP_FMAC1 const char * SOAP_FMAC2 soap_strsearch(const char *big, const char *little);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_string_out(struct soap*, const char *s, int flag);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_string_in(struct soap*, int, long, long);
+
+#ifndef WITH_LEANER
+SOAP_FMAC1 int SOAP_FMAC2 soap_wstring_out(struct soap*, const wchar_t *s, int flag);
+SOAP_FMAC1 wchar_t* SOAP_FMAC2 soap_wstring_in(struct soap*, int, long, long);
+#endif
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_match_namespace(struct soap*, const char *, const char*, int n1, int n2);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_set_namespaces(struct soap*, struct Namespace*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_local_namespaces(struct soap*);
+
+SOAP_FMAC1 void SOAP_FMAC2 soap_pop_namespace(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_push_namespace(struct soap*, const char *,const char *);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_store_lab(struct soap*, const char*, size_t);
+SOAP_FMAC1 int SOAP_FMAC2 soap_append_lab(struct soap*, const char*, size_t);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_new_block(struct soap*);
+SOAP_FMAC1 void* SOAP_FMAC2 soap_push_block(struct soap*, size_t);
+SOAP_FMAC1 void SOAP_FMAC2 soap_pop_block(struct soap*);
+SOAP_FMAC1 size_t SOAP_FMAC2 soap_size_block(struct soap*, size_t);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_first_block(struct soap*);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_next_block(struct soap*);
+SOAP_FMAC1 size_t SOAP_FMAC2 soap_block_size(struct soap*);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_save_block(struct soap*, char*, int);
+SOAP_FMAC1 void SOAP_FMAC2 soap_end_block(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_begin_out(struct soap*);
+SOAP_FMAC1 int soap_envelope_end_out(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_begin_in(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_end_in(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_body_begin_out(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_body_end_out(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_body_begin_in(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_body_end_in(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_recv_header(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_response(struct soap*, int);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_send_empty_response(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_recv_empty_response(struct soap*);
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_send_fault(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_recv_fault(struct soap*);
+
+#ifndef WITH_NOSTDLIB
+SOAP_FMAC1 void SOAP_FMAC2 soap_print_fault(struct soap*, FILE*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_print_fault_location(struct soap*, FILE*);
+#endif
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2byte(struct soap*, const char*, char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2short(struct soap*, const char*, short*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2int(struct soap*, const char*, int*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2long(struct soap*, const char*, long*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2LONG64(struct soap*, const char*, LONG64*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2float(struct soap*, const char*, float*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2double(struct soap*, const char*, double*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedByte(struct soap*, const char*, unsigned char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedShort(struct soap*, const char*, unsigned short*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedInt(struct soap*, const char*, unsigned int*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2unsignedLong(struct soap*, const char*, unsigned long*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2ULONG64(struct soap*, const char*, ULONG64*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2string(struct soap*, const char*, char**);
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2QName(struct soap*, const char*, char**);
+
+#ifndef WITH_LEAN
+SOAP_FMAC1 int SOAP_FMAC2 soap_s2dateTime(struct soap*, const char*, time_t*);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_s2base64(struct soap*, const unsigned char*, char*, int);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_s2hex(struct soap*, const unsigned char*, char*, int);
+#endif
+
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_byte2s(struct soap*, char);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_short2s(struct soap*, short);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_int2s(struct soap*, int);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_long2s(struct soap*, long);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_LONG642s(struct soap*, LONG64);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_float2s(struct soap*, float);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_double2s(struct soap*, double);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedByte2s(struct soap*, unsigned char);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedShort2s(struct soap*, unsigned short);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedInt2s(struct soap*, unsigned int);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_unsignedLong2s(struct soap*, unsigned long);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_ULONG642s(struct soap*, ULONG64);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_QName2s(struct soap*, const char*);
+
+#ifndef WITH_LEAN
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_dateTime2s(struct soap*, time_t);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_base642s(struct soap*, const char*, char*, size_t, int*);
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_hex2s(struct soap*, const char*, char*, size_t, int*);
+#endif
+
+
+SOAP_FMAC1 int* SOAP_FMAC2 soap_inint(struct soap*, const char *tag, int *p, const char *, int);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_inbyte(struct soap*, const char *tag, char *p, const char *, int);
+SOAP_FMAC1 long* SOAP_FMAC2 soap_inlong(struct soap*, const char *tag, long *p, const char *, int);
+SOAP_FMAC1 LONG64* SOAP_FMAC2 soap_inLONG64(struct soap*, const char *tag, LONG64 *p, const char *, int);
+SOAP_FMAC1 short* SOAP_FMAC2 soap_inshort(struct soap*, const char *tag, short *p, const char *, int);
+SOAP_FMAC1 float* SOAP_FMAC2 soap_infloat(struct soap*, const char *tag, float *p, const char *, int);
+SOAP_FMAC1 double* SOAP_FMAC2 soap_indouble(struct soap*, const char *tag, double *p, const char *, int);
+SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_inunsignedByte(struct soap*, const char *tag, unsigned char *p, const char *, int);
+SOAP_FMAC1 unsigned short* SOAP_FMAC2 soap_inunsignedShort(struct soap*, const char *tag, unsigned short *p, const char *, int);
+SOAP_FMAC1 unsigned int* SOAP_FMAC2 soap_inunsignedInt(struct soap*, const char *tag, unsigned int *p, const char *, int);
+SOAP_FMAC1 unsigned long* SOAP_FMAC2 soap_inunsignedLong(struct soap*, const char *tag, unsigned long *p, const char *, int);
+SOAP_FMAC1 ULONG64* SOAP_FMAC2 soap_inULONG64(struct soap*, const char *tag, ULONG64 *p, const char *, int);
+SOAP_FMAC1 char** SOAP_FMAC2 soap_instring(struct soap*, const char *tag, char **p, const char *, int, int, long, long);
+SOAP_FMAC1 char** SOAP_FMAC2 soap_inliteral(struct soap*, const char *tag, char **p);
+
+#ifndef WITH_LEAN
+SOAP_FMAC1 time_t* SOAP_FMAC2 soap_indateTime(struct soap*, const char *tag, time_t *p, const char *, int);
+#endif
+
+#ifndef WITH_LEANER
+SOAP_FMAC1 wchar_t** SOAP_FMAC2 soap_inwstring(struct soap*, const char *tag, wchar_t **p, const char *, int, long, long);
+SOAP_FMAC1 wchar_t** SOAP_FMAC2 soap_inwliteral(struct soap*, const char *tag, wchar_t **p);
+#endif
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_outbyte(struct soap*, const char *tag, int id, const char *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outshort(struct soap*, const char *tag, int id, const short *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outint(struct soap*, const char *tag, int id, const int *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outlong(struct soap*, const char *tag, int id, const long *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outLONG64(struct soap*, const char *tag, int id, const LONG64 *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outfloat(struct soap*, const char *tag, int id, const float *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outdouble(struct soap*, const char *tag, int id, const double *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedByte(struct soap*, const char *tag, int id, const unsigned char *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedShort(struct soap*, const char *tag, int id, const unsigned short *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedInt(struct soap*, const char *tag, int id, const unsigned int *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outunsignedLong(struct soap*, const char *tag, int id, const unsigned long *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outULONG64(struct soap*, const char *tag, int id, const ULONG64 *p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outstring(struct soap*, const char *tag, int id, char *const*p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outliteral(struct soap*, const char *tag, char *const*p);
+
+#ifndef WITH_LEAN
+SOAP_FMAC1 int SOAP_FMAC2 soap_outdateTime(struct soap*, const char *tag, int id, const time_t *p, const char *, int);
+#endif
+
+#ifndef WITH_LEANER
+SOAP_FMAC1 int SOAP_FMAC2 soap_outwstring(struct soap*, const char *tag, int id, wchar_t *const*p, const char *, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_outwliteral(struct soap*, const char *tag, wchar_t *const*p);
+#endif
+
+#ifndef WITH_LEANER
+SOAP_FMAC1 int SOAP_FMAC2 soap_attachment(struct soap *, const char*, int, const void*, const struct soap_array*, const char*, const char*, const char*, int, const char*, int);
+SOAP_FMAC1 int SOAP_FMAC2 soap_move(struct soap*, long);
+SOAP_FMAC1 size_t SOAP_FMAC2 soap_tell(struct soap*);
+SOAP_FMAC1 char* SOAP_FMAC2 soap_dime_option(struct soap*, unsigned short, const char*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getdimehdr(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getdime(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_putdimehdr(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_putdime(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getmimehdr(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_getmime(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_putmimehdr(struct soap*, struct soap_multipart*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_putmime(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_dime(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_set_mime(struct soap*, const char *boundary, const char *start);
+SOAP_FMAC1 void SOAP_FMAC2 soap_clr_dime(struct soap*);
+SOAP_FMAC1 void SOAP_FMAC2 soap_clr_mime(struct soap*);
+SOAP_FMAC1 int SOAP_FMAC2 soap_set_dime_attachment(struct soap*, char *ptr, size_t size, const char *type, const char *id, unsigned short optype, const char *option);
+SOAP_FMAC1 int SOAP_FMAC2 soap_set_mime_attachment(struct soap*, char *ptr, size_t size, enum soap_mime_encoding encoding, const char *type, const char *id, const char *location, const char *description);
+SOAP_FMAC1 struct soap_multipart* SOAP_FMAC2 soap_next_multipart(struct soap_multipart*);
+#endif
+
+SOAP_FMAC1 int SOAP_FMAC2 soap_register_plugin_arg(struct soap*, int (*fcreate)(struct soap*, struct soap_plugin*, void*), void*);
+SOAP_FMAC1 void* SOAP_FMAC2 soap_lookup_plugin(struct soap*, const char*);
+
+SOAP_FMAC1 const char* SOAP_FMAC2 soap_attr_value(struct soap *soap, const char *name, int flag);
+SOAP_FMAC1 int SOAP_FMAC2 soap_set_attr(struct soap *soap, const char *name, const char *value);
+SOAP_FMAC1 void SOAP_FMAC2 soap_clr_attr(struct soap *soap);
+
+#ifdef WITH_COOKIES
+SOAP_FMAC1 size_t SOAP_FMAC2 soap_encode_cookie(const char*, char*, size_t);
+SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_set_cookie(struct soap*, const char*, const char*, const char*, const char*);
+SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_cookie(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 extern char* SOAP_FMAC2 soap_cookie_value(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 extern char* SOAP_FMAC2 soap_env_cookie_value(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 extern long SOAP_FMAC2 soap_cookie_expire(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 extern int SOAP_FMAC2 soap_set_cookie_expire(struct soap*, const char*, long, const char*, const char*);
+SOAP_FMAC1 extern int SOAP_FMAC2 soap_set_cookie_session(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 extern int SOAP_FMAC2 soap_clr_cookie_session(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 extern void SOAP_FMAC2 soap_clr_cookie(struct soap*, const char*, const char*, const char*);
+SOAP_FMAC1 extern int SOAP_FMAC2 soap_getenv_cookies(struct soap*);
+SOAP_FMAC1 extern struct soap_cookie* SOAP_FMAC2 soap_copy_cookies(struct soap*);
+SOAP_FMAC1 extern void SOAP_FMAC2 soap_free_cookies(struct soap*);
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Build information file for building
+*               HTI OS layer components.
+*                
+*
+*/
+
+#include <platform_paths.hrh>
+
+// API header exports
+#include "../hti_plat/group/bld.inf"
+
+PRJ_EXPORTS
+../rom/htios.iby        CORE_IBY_EXPORT_PATH(tools,htios.iby)
+
+// HTI config file library
+#include "../HtiCfg/group/bld.inf"
+
+// Auto start recognizer
+#include "../HtiAutoStart/group/bld.inf"
+
+// HTI Framework
+#include "../HtiFramework/group/bld.inf"
+
+// Communication plugins
+#include "../HtiCommPlugins/HtiBtCommPlugin/group/bld.inf"
+#include "../HtiCommPlugins/HtiIPCommPlugin/group/bld.inf"
+#include "../HtiCommPlugins/HtiSerialCommPlugin/group/bld.inf"
+#include "../HtiCommPlugins/HtiUsbSerialCommPlugin/group/bld.inf"
+
+// Service plugins
+#include "../HtiServicePlugins/HtiAppServicePlugin/group/bld.inf"
+#include "../HtiServicePlugins/HtiEchoServicePlugin/group/bld.inf"
+#include "../HtiServicePlugins/HtiFtpServicePlugin/group/bld.inf"
+#include "../HtiServicePlugins/HtiIpProxyServicePlugin/group/bld.inf"
+#include "../HtiServicePlugins/HtiStifTfServicePlugin/group/bld.inf"
+
+// Helper for copying files to TCB folders
+#include "../HtiFileHlp/group/bld.inf"
+
+// Hti Watchdog
+#include "../HtiWatchDog/group/bld.inf"
+
+// Hti Restart
+#include "../HtiRestart/group/bld.inf"
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Includes HTI API bld.inf files.
+*
+*/
+
+
+#include "../hti_api/group/bld.inf"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: Build information for HTI API.
+*
+*/
+
+#include <platform_paths.hrh>
+
+
+PRJ_EXPORTS
+../inc/HtiServicePluginInterface.h          OS_LAYER_PLATFORM_EXPORT_PATH(HtiServicePluginInterface.h)
+../inc/HtiServicePluginInterface.inl        OS_LAYER_PLATFORM_EXPORT_PATH(HtiServicePluginInterface.inl)
+../inc/HtiDispatcherInterface.h             OS_LAYER_PLATFORM_EXPORT_PATH(HtiDispatcherInterface.h)
+../inc/HtiLogging.h                         OS_LAYER_PLATFORM_EXPORT_PATH(HtiLogging.h)
+../inc/HtiCommPluginInterface.h             OS_LAYER_PLATFORM_EXPORT_PATH(HtiCommPluginInterface.h)
+../inc/HtiCommPluginInterface.inl           OS_LAYER_PLATFORM_EXPORT_PATH(HtiCommPluginInterface.inl)
+../inc/HtiVersion.h                         OS_LAYER_PLATFORM_EXPORT_PATH(HtiVersion.h)
+../inc/HtiStartupWaitInterface.h            OS_LAYER_PLATFORM_EXPORT_PATH(HtiStartupWaitInterface.h)
+../inc/HtiCfg.h                             OS_LAYER_PLATFORM_EXPORT_PATH(HtiCfg.h)
+../inc/HtiFtpBackupFakeBase.h               OS_LAYER_PLATFORM_EXPORT_PATH(HtiFtpBackupFakeBase.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/hti_api.metaxml	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<api id="89b74b7c67a81ea9ced727bbaf0b3c18" dataversion="2.0">
+  <name>HTI API</name>
+  <description>Defines the API used by HTI and its communication plug-ins and service plug-ins.</description>
+  <type>c++</type>
+  <collection>htios</collection>
+  <libs>
+    <lib name="HtiCfg.lib"/>
+  </libs>
+  <release category="platform" sinceversion="5.1"/>
+  <attributes>
+    <htmldocprovided>no</htmldocprovided>
+    <adaptation>no</adaptation>
+  </attributes>
+</api>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiCfg.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Utility library for reading simple configuration
+*               property files containing Key=Value lines.
+*
+*/
+
+#ifndef __HTICFG_H__
+#define __HTICFG_H__
+
+// INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+
+// Parameter lengths
+const static TInt KMaxParameterNameLength = 64;
+const static TInt KMaxParameterValueLength = 64;
+const static TInt KMaxParameterLength = KMaxParameterNameLength + 1 + KMaxParameterValueLength;
+
+// Configuration file constants
+#define KCfgNewLine (TChar)'\n'
+#define KCfgSeparator (TChar)'='
+#define KCfgComment (TChar)'#'
+
+// FORWARD DECLARATIONS
+class CDesC8ArrayFlat;
+
+// CLASS DECLARATION
+class CHtiCfg: public CBase
+    {
+public:
+
+    /**
+    * Create instance of configuration class.
+    * @return Configuration class instance.
+    */
+    IMPORT_C static CHtiCfg* NewL();
+
+    /**
+    * Create instance of configuration class leaving it to cleanup stack.
+    * @return Configuration class instance.
+    */
+    IMPORT_C static CHtiCfg* NewLC();
+
+    /**
+    * Destructor.
+    */
+    IMPORT_C virtual ~CHtiCfg();
+
+    /**
+    * Loads the configuration file and reads the values to iCfgParameters.
+    * Drive letter is not specified. File will be searched from all drives.
+    * @param aCfgFilePath absolute path (without drive letter) to the directory
+    *                     from where to search the configuration file
+    * @param aCfgFileName configuration filename.
+    */
+    IMPORT_C void LoadCfgL( const TDesC& aCfgFilePath,
+                            const TDesC& aCfgFileName );
+
+    /**
+    * Reads the values from iCfgParameters and saves them to configuration file.
+    * Drive letter is not specified. File will be searched from all drives and
+    * if not found file will be crated to c-drive.
+    * @param aCfgFilePath directory from where to search the configuration file
+    * @param aCfgFileName configuration filename.
+    */
+    IMPORT_C void SaveCfgL( const TDesC& aCfgFilePath,
+                            const TDesC& aCfgFileName );
+
+    /**
+    * Gets a parameter value as descriptor.
+    * @param aName name of the parameter whose value to get
+    * @return Parameter value.
+    */
+    IMPORT_C TPtrC8 GetParameterL( const TDesC8& aName );
+
+    /**
+    * Gets a numerical parameter value as integer.
+    * @param aName name of the parameter whose value to get
+    * @return Parameter value.
+    */
+    IMPORT_C TInt GetParameterIntL( const TDesC8& aName );
+
+    /**
+    * Sets a parameter
+    * @param aName name of the parameter whose value to set
+    * @param aValue parameter value to set
+    * @return error code.
+    */
+    IMPORT_C TInt SetParameterL( const TDesC8& aName,  const TDesC8& aValue );
+
+    /**
+    * Removes a parameter
+    * @param aName name of the parameter to remove
+    * @return error code.
+    */
+    IMPORT_C TInt RemoveParameterL( const TDesC8& aName );
+
+private:
+
+    /**
+    * Constructor.
+    */
+    CHtiCfg();
+
+    /**
+    * Second phase construction.
+    */
+    void ConstructL();
+
+
+private: // data
+
+    // array of key=value lines
+    CDesC8ArrayFlat* iCfgParameters;
+
+    };
+
+#endif // __HTICFG_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiCommPluginInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,118 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface defenition for communication plugins.
+*        Implementation is constructed by matching string.
+*        The default implementation is FBus plugin.
+*
+*/
+
+
+#ifndef HTICOMMPLUGININTERFACE_H__
+#define HTICOMMPLUGININTERFACE_H__
+
+#include <ecom/ecom.h>
+
+#ifndef __WINS__
+_LIT8( KCommDefaultImplementation, "USBSERIAL" );
+#else
+_LIT8( KCommDefaultImplementation, "SERIAL" );
+#endif
+
+const TUid KHTICommInterfaceUid = { 0x1020DEB8 };
+
+/**
+*  Completion code for Receive() and Send(), when underlying communication
+*  module has reinitialized, i.e. cancelled any send and receive operations.
+*/
+const TInt KErrComModuleReset = 100;
+
+
+class CHTICommPluginInterface : public CBase
+    {
+public: //ECom specific methods (implemented as inline)
+
+    /**
+    * Wraps ECom object instantitation
+    * default resovler is used.
+    * Plug-in specified by KCommDefaultImplementation
+    * is loaded.
+    */
+    static CHTICommPluginInterface* NewL();
+
+    /**
+    * Wraps ECom object instantitation
+    * default resovler is used
+    *
+    * @param aMatchString plug-in name as specified in
+    *        in plug-in implementation resource file
+    */
+    static CHTICommPluginInterface* NewL(const TDesC8& aMatchString);
+
+    /**
+    * Wraps ECom object destruction
+    */
+    virtual ~CHTICommPluginInterface();
+
+
+public: //Service plugin interface methods
+
+    /**
+    * Receive a message to the provided descriptor.
+    * It is possible that the descriptor will not be full on request
+    *   complition.
+    *
+    * @param aMessage Buffer for receiving incoming message
+    * @param aStatus AO's status
+    */
+    virtual void Receive( TDes8& aMessage, TRequestStatus& aStatus ) = 0;
+
+    /**
+    * Send a message.
+    *
+    * @param aMessage Buffer with data for sending
+    * @param aStatus AO's status
+    */
+    virtual void Send(const TDesC8& aMessage, TRequestStatus& aStatus ) = 0;
+
+    /**
+    * Cancels receive operation
+    */
+    virtual void CancelReceive() = 0;
+    /**
+    * Cancels send operation
+    */
+    virtual void CancelSend() = 0;
+
+    /**
+    *   Retruns the size of a buffer used for
+    *   Send() function.
+    **/
+    virtual TInt GetSendBufferSize() = 0;
+
+    /**
+    *   Retruns the size of a buffer used for
+    *   Receive() function.
+    **/
+    virtual TInt GetReceiveBufferSize() = 0;
+
+private:
+    /**
+    * Instance identifier key
+    */
+    TUid iDtor_ID_Key;
+    };
+
+#include <HtiCommPluginInterface.inl>
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiCommPluginInterface.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Contins ECom related implementaion of CHTICommInterface
+*        definition
+*
+*/
+
+
+inline CHTICommPluginInterface* CHTICommPluginInterface::NewL()
+    {
+    return NewL(KCommDefaultImplementation);
+    }
+
+inline CHTICommPluginInterface* CHTICommPluginInterface::NewL(
+    const TDesC8& aMatchString)
+    {
+
+    TEComResolverParams resolverParams;
+    resolverParams.SetDataType(aMatchString);
+    TAny* ptr = REComSession::CreateImplementationL(
+        KHTICommInterfaceUid,
+        _FOFF(CHTICommPluginInterface,iDtor_ID_Key),
+        resolverParams);
+
+     return reinterpret_cast<CHTICommPluginInterface*>( ptr );
+    }
+
+inline CHTICommPluginInterface::~CHTICommPluginInterface()
+    {
+    REComSession::DestroyedImplementation(iDtor_ID_Key);
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiDispatcherInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,138 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of MDispatcher interface that used
+*        to dispatch incoming messages to servers
+*        and outcoming to host client.
+*        MDispatcher* should be used by services to send outcoming
+*        messages
+*
+*/
+
+
+#ifndef DISPATCHERINTERFACE_H__
+#define DISPATCHERINTERFACE_H__
+
+#include <e32std.h>
+
+class CHtiMessage;
+class CConsoleBase;
+
+enum THtiMessagePriority
+    {
+    EHtiPriorityDefault = 0,
+    EHtiPriorityData = 0,
+    EHtiPriorityControl = 2
+    };
+
+const TInt KErrorDescriptionMaxLength = 118;
+
+/**
+* Observer interface that should be implemented by plugin if it wants
+* to resend message failed due to KErrNoMemory.
+**/
+class MHtiMemoryObserver
+    {
+public:
+    /**
+    *
+    * This function called by the dispatcher after plug-in request
+    * (@see MHtiDispatcher::AddMemoryObserver()) every time
+    * when some message was removed from the outgoing queue.
+    *
+    * @param aAvailableMemory amount of memory currently available for
+    *           outgoing messages
+    **/
+    virtual void NotifyMemoryChange(TInt aAvailableMemory) = 0;
+    };
+
+/**
+* Interface to the HTI dispatcher used by service plug-ins for message
+* sending.
+**/
+class MHtiDispatcher
+    {
+public:
+
+    /**
+    *
+    * Send message from the service back to host client.
+    * Transfer ownership of aMessage.
+    * The function adds messages to the outgoing queue.
+    * Message will be actualy sent later.
+    * Function can return KErrNoMemory if there is not enough memory to
+    * add it to the queue.
+    * Plug-in use AddMemoryObserver to be notified later when memory
+    * will be available to continue data transfer.
+    *
+    * @param aMessage contain server-specific data
+    * @param aTargetServiceUid service UID
+    * @param aWrappedFlag shoud set to ETrue if message should be
+    *       wrapped by security manager
+    * @param aPriority message priority
+    *
+    * @return KErrNone if message was succesfully added to the outgoing queue
+    *         KErrNoMemory when there is not enough memory.
+    */
+    virtual TInt DispatchOutgoingMessage( TDesC8* aMessage,
+                    const TUid aTargetServiceUid,
+                    TBool aWrappedFlag,
+                    THtiMessagePriority aPriority ) = 0;
+
+    virtual TInt DispatchOutgoingMessage(TDesC8* aMessage,
+                    const TUid aTargetServiceUid) = 0;
+
+    virtual TInt DispatchOutgoingErrorMessage(TInt aErrorCode,
+                    const TDesC8& aErrorDescription,
+                    const TUid aTargetServiceUid) = 0;
+    /**
+    * Adds memory observer.
+    *
+    * @param anObserver memory observer
+    */
+    virtual void AddMemoryObserver(MHtiMemoryObserver* anObserver) = 0;
+
+    /**
+    * Removes memory observer.
+    *
+    * @param anObserver memory observer
+    */
+    virtual void RemoveMemoryObserver(MHtiMemoryObserver* anObserver) = 0;
+
+    /**
+    * Returns tha amount of currenly available memory for messages.
+    */
+    virtual TInt GetFreeMemory() = 0;
+
+    /**
+    * Notifis dispatcher that some async request is over.
+    * Should be used when plug-in uses async services
+    * and enters in a busy state (IsBusy() returns true)
+    * Should be called when plug-in is able to process new messages again
+    */
+    virtual void Notify( TInt anError ) = 0;
+
+    /*
+    * Getter for the HTI console
+    */
+    virtual CConsoleBase* GetConsole() = 0;
+
+    /*
+    * Shutdown HTI and reboot the device.
+    *
+    * Called from service plug-ins or from EHtiReboot HtiSystem command
+    */
+    virtual void ShutdownAndRebootDeviceL() = 0;
+    };
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiFtpBackupFakeBase.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of the CHtiFtpBackupFakeBase class.
+*
+*/
+
+
+#ifndef __HTIFTPBACKUPFAKEBASE_H
+#define __HTIFTPBACKUPFAKEBASE_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <f32file.h>
+
+// CONSTANTS
+const TUid KHtiFtpBackupFakeInterfaceUid = { 0x20022D5F };
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+/**
+* Definition of the CHtiFtpBackupFakeBase
+*/
+class CHtiFtpBackupFakeBase : public CBase
+    {
+    public:
+        virtual void ConstructL( RFs* aFs ) = 0;
+        virtual TInt ActivateBackup() = 0;
+        virtual TInt DeactivateBackup() = 0;
+    protected:
+        RFs*        iFs;        // referenced
+    };
+
+
+#endif // __HTIFTPBACKUPFAKEBASE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiLogging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,115 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logging macros
+*
+*/
+
+
+#ifndef LOG_DEF__
+#define LOG_DEF__
+
+#define LOG_HTI_FLOW
+
+#ifdef __ENABLE_LOGGING__
+
+#ifndef __HTI_LOG_RDEBUG__
+
+// LOGGING TO FILE
+
+#include <flogger.h>
+_LIT(KFreeMemFormat,      "Total free: %d bytes");
+_LIT(KFreeHeapMemFormat,  "Heap available: %d bytes, biggest %d bytes");
+_LIT(KAllocHeapMemFormat, "Heap alloc: %d bytes, %d cells");
+_LIT(KLogFolder, "hti");
+_LIT(KLogFile, "hti_log.txt");
+
+#define HTI_LOG_TEXT(a1) {_LIT(temp, a1); RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, temp);}
+#define HTI_LOG_DES(a1) {RFileLogger::Write(KLogFolder, KLogFile, EFileLoggingModeAppend, (a1));}
+#define HTI_LOG_FORMAT(a1,a2) {_LIT(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, temp, (a2));}
+#define HTI_LOG_HEX(p,l) {RFileLogger::HexDump(KLogFolder, KLogFile, EFileLoggingModeAppend, NULL, NULL, p, l);}
+
+#define HTI_LOG_FREE_MEM() {TMemoryInfoV1Buf info;UserHal::MemoryInfo(info);RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KFreeMemFormat, info().iFreeRamInBytes);}
+#define HTI_LOG_FREE_HEAP_MEM() {TInt b;TInt free=User::Available(b);RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KFreeHeapMemFormat, free, b);}
+#define HTI_LOG_ALLOC_HEAP_MEM() {TInt b;TInt c = User::AllocSize(b);RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KAllocHeapMemFormat, b, c);}
+
+// define separately macros to track function flow
+#ifdef LOG_HTI_FLOW
+_LIT8(KFuncIn, "-=> %S");
+_LIT8(KFuncOut, "<=- %S");
+
+#define HTI_LOG_FUNC_IN(a1)  {_LIT8(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KFuncIn, &temp);}
+#define HTI_LOG_FUNC_OUT(a1) {_LIT8(temp, a1); RFileLogger::WriteFormat(KLogFolder, KLogFile, EFileLoggingModeAppend, KFuncOut, &temp);}
+
+#else
+
+#define HTI_LOG_FUNC_IN(a1)
+#define HTI_LOG_FUNC_OUT(a1)
+
+#endif // LOG_HTI_FLOW
+
+#else
+
+// LOGGING TO RDEBUG
+
+#include <e32debug.h>
+_LIT(KFreeMemFormat,      "[HTI] Total free: %d bytes");
+_LIT(KFreeHeapMemFormat,  "[HTI] Heap available: %d bytes, biggest %d bytes");
+_LIT(KAllocHeapMemFormat, "[HTI] Heap alloc: %d bytes, %d cells");
+_LIT(KDes, "[HTI] %S");
+_LIT(KPrefix, "[HTI] ");
+#define HTI_LOG_TEXT(a1) {_LIT(temp, a1); RDebug::Print(KDes, &temp);}
+#define HTI_LOG_DES(a1) {TBuf<128> temp;temp.Copy(a1);RDebug::Print(KDes, &temp);}
+#define HTI_LOG_FORMAT(a1,a2) {_LIT(param1, a1);TBuf<128> temp;temp.Copy(KPrefix);temp.Append(param1);RDebug::Print(temp, (a2));}
+#define HTI_LOG_HEX(p,l)
+
+#define HTI_LOG_FREE_MEM() {TMemoryInfoV1Buf info;UserHal::MemoryInfo(info);RDebug::Print(KFreeMemFormat, info().iFreeRamInBytes);}
+#define HTI_LOG_FREE_HEAP_MEM() {TInt b;TInt free=User::Available(b);RDebug::Print(KFreeHeapMemFormat, free, b);}
+#define HTI_LOG_ALLOC_HEAP_MEM() {TInt b;TInt c = User::AllocSize(b);RDebug::Print(KAllocHeapMemFormat, b, c);}
+
+//define separately macros to track function flow
+#ifdef LOG_HTI_FLOW
+_LIT(KFuncIn,  "[HTI] -=> %S");
+_LIT(KFuncOut, "[HTI] <=- %S");
+
+#define HTI_LOG_FUNC_IN(a1)  {_LIT(temp, a1); RDebug::Print(KFuncIn, &temp);}
+#define HTI_LOG_FUNC_OUT(a1) {_LIT(temp, a1); RDebug::Print(KFuncOut, &temp);}
+
+#else
+
+#define HTI_LOG_FUNC_IN(a1)
+#define HTI_LOG_FUNC_OUT(a1)
+
+#endif // LOG_HTI_FLOW
+
+#endif // __HTI_LOG_RDEBUG__
+
+#else
+
+// NO LOGGING
+
+#define HTI_LOG_TEXT(a1)
+#define HTI_LOG_DES(a1)
+#define HTI_LOG_FORMAT(a1,a2)
+#define HTI_LOG_HEX(p,l)
+
+#define HTI_LOG_FREE_MEM()
+#define HTI_LOG_FREE_HEAP_MEM()
+#define HTI_LOG_ALLOC_HEAP_MEM()
+
+#define HTI_LOG_FUNC_IN(a1)
+#define HTI_LOG_FUNC_OUT(a1)
+
+#endif  // __ENABLE_LOGGING__
+
+#endif  // LOG_DEF__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiServicePluginInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,115 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Interface defenition for HTI services
+*
+*/
+
+
+#ifndef SERVICEPLUGININTERFACE_H__
+#define SERVICEPLUGININTERFACE_H__
+
+#include <ecom/ecom.h>
+
+#include <HtiDispatcherInterface.h>
+
+const TUid KHTIServiceInterfaceUid = {0x1020DEB7};
+
+
+class CHTIServicePluginInterface : public CBase, public MHtiMemoryObserver
+    {
+public: //ECom specific methods (implemented as inline)
+
+    /**
+    * Wraps ECom object instantitation
+    * plug-in loaded by its UID
+    *
+    * @param aUID service plugin implementation UDI
+    */
+    static CHTIServicePluginInterface* NewL(const TUid aUID);
+
+    /**
+    * Wraps ECom object instantitation
+    * default resovler is used
+    *
+    * @param aMatchString service plugin name
+    */
+    static CHTIServicePluginInterface* NewL(const TDesC8& aMatchString);
+
+    /**
+    * Wraps ECom object destruction
+    */
+    virtual ~CHTIServicePluginInterface();
+
+public: //Comm plugin interface methods
+
+    /**
+    * This method is called by framework after the plugin was loaded and
+    * iDispatcher set.
+    */
+    virtual void InitL(){};
+
+    /**
+    * Result indicates eiterh plug-in is able to process request
+    * (e.g. a plug-in doesn't have an outstanding request to async service).
+    * Framework calls this method before calling ProcessMessageL().
+    * If plug-in is busy, request will be dispatched later.
+    * Typically, AO's CActive::IsActive() can be used
+    * in a overriden implementation.
+    * Default implementation returns EFalse.
+    */
+    virtual TBool IsBusy();
+
+    /**
+    * Interface service
+    * implementation of service, should return ASAP.
+    * aMessage contan is service specific.
+    *
+    * @param aMessage message body destinated to a servive
+    * @param aPriority message priority
+    */
+    virtual void ProcessMessageL(const TDesC8& aMessage,
+                                THtiMessagePriority aPriority) = 0;
+
+    virtual void Error(TInt /*aErrorCode*/, const TDesC8& /*aErrorDescription*/){};
+
+    /**
+    * Set dispatcher that used by services to send messages.
+    *
+    */
+    virtual void SetDispatcher(MHtiDispatcher* aDispatcher);
+
+public: //from MHtiMemoryObserver
+    /**
+    * Empty implementation.
+    */
+    virtual void NotifyMemoryChange(TInt /*aAvailableMemory*/){};
+
+protected:
+    /**
+    * Pointer to a dispatcher. It is not availble during construction.
+    * If it should be used before starting process messages, InitL()
+    * must be overriden.
+    */
+    MHtiDispatcher* iDispatcher;
+
+private:
+    /**
+    * Instance identifier key
+    */
+    TUid iDtor_ID_Key;
+    };
+
+#include <HtiServicePluginInterface.inl>
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiServicePluginInterface.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Contins ECom related implementaion of
+*        CHTIServiceInterfaceinterface class
+*
+*/
+
+
+inline CHTIServicePluginInterface* CHTIServicePluginInterface::NewL(
+    const TUid aUID)
+    {
+    TAny* ptr = REComSession::CreateImplementationL(
+        aUID,
+        _FOFF(CHTIServicePluginInterface,iDtor_ID_Key) );
+
+     return reinterpret_cast<CHTIServicePluginInterface*>( ptr );
+    }
+
+inline CHTIServicePluginInterface* CHTIServicePluginInterface::NewL(
+    const TDesC8& aMatchString)
+    {
+
+    TEComResolverParams resolverParams;
+    resolverParams.SetDataType(aMatchString);
+    TAny* ptr = REComSession::CreateImplementationL(
+        KHTIServiceInterfaceUid,
+        _FOFF(CHTIServicePluginInterface,iDtor_ID_Key),
+        resolverParams);
+
+     return reinterpret_cast<CHTIServicePluginInterface*>( ptr );
+    }
+
+inline CHTIServicePluginInterface::~CHTIServicePluginInterface()
+    {
+    REComSession::DestroyedImplementation(iDtor_ID_Key);
+    }
+
+
+inline void CHTIServicePluginInterface::SetDispatcher(
+                MHtiDispatcher* aDispatcher)
+    {
+    iDispatcher = aDispatcher;
+    }
+
+inline TBool CHTIServicePluginInterface::IsBusy()
+    {
+    return EFalse;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiStartupWaitInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Definition of MHtiStartupWaitInterface that is used to make
+*                HtiFramework wait for OS startup before continuing own startup.
+*
+*/
+
+
+#ifndef HTISTARTUPWAITINTERFACE_H__
+#define HTISTARTUPWAITINTERFACE_H__
+
+#include <e32std.h>
+
+const TUid KHtiStartupWaitInterfaceUid = { 0x1020DEB9 };
+
+class MHtiStartupWaitInterface
+    {
+    public:
+        virtual TInt WaitForStartup( TInt aMaxWaitTime ) = 0;
+    };
+
+#endif
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/hti_plat/hti_api/inc/HtiVersion.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  HTI version information
+*
+*/
+
+
+#ifndef HTIVERSION_H__
+#define HTIVERSION_H__
+
+//  INCLUDES
+#include <e32std.h>
+
+// CONSTANTS
+
+const TUint8 KHtiVersionMajor = 2;
+const TUint8 KHtiVersionMinor = 25;
+const TUint8 KHtiVersionBuild = 0;
+
+const TUint16 KHtiVersionYear  = 2010;
+const TUint8  KHtiVersionMonth = 6;
+const TUint8  KHtiVersionWeek  = 23;
+const TUint8  KHtiVersionDay   = 11;
+
+//  MACROS
+
+//  DATA TYPES
+
+//  EXTERNAL DATA STRUCTURES
+
+//  FUNCTION PROTOTYPES
+
+//  FORWARD DECLARATIONS
+
+//  CLASS DEFINITIONS
+
+#endif  // HTIVERSION_H__
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hti/rom/htios.iby	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,66 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: Specifies HTI OS layer components for ROM image
+*
+*/
+
+#ifndef __HTIOS_IBY__
+#define __HTIOS_IBY__
+
+// HTI config file library
+file=ABI_DIR\BUILD_DIR\HtiCfg.dll                   SHARED_LIB_DIR\HtiCfg.dll               
+
+// HTI Framework
+file=ABI_DIR\BUILD_DIR\HtiFramework.exe             SHARED_LIB_DIR\HtiFramework.exe
+
+// Serial Interface
+ECOM_PLUGIN(HtiSerialCommEcomPlugin.dll, HtiSerialCommEcomPlugin.rsc)
+
+// USB Serial Interface
+ECOM_PLUGIN(HtiUsbSerialCommEcomPlugin.dll, HtiUsbSerialCommEcomPlugin.rsc)
+
+// Bluetooth Interface
+file=ABI_DIR\BUILD_DIR\HtiBtSerialComHelper.dll     SHARED_LIB_DIR\HtiBtSerialComHelper.dll
+file=ABI_DIR\BUILD_DIR\HtiBtCommServer.dll          SHARED_LIB_DIR\HtiBtCommServer.dll
+file=ABI_DIR\BUILD_DIR\HtiBtCommInterface.dll       SHARED_LIB_DIR\HtiBtCommInterface.dll
+ECOM_PLUGIN(HtiBtCommEcomPlugin.dll, HtiBtCommEcomPlugin.rsc)
+
+// TCP/IP interface
+file=ABI_DIR\BUILD_DIR\HtiIPCommServer.exe          SHARED_LIB_DIR\HtiIPCommServer.exe
+file=ABI_DIR\BUILD_DIR\HtiIPCommServerClient.dll    SHARED_LIB_DIR\HtiIPCommServerClient.dll
+ECOM_PLUGIN(HtiIPCommEcomPlugin.dll, HtiIPCommEcomPlugin.rsc)
+
+// HtiAutoStart plug-in
+ECOM_PLUGIN(HtiAutoStart.dll,HtiAutoStart.rsc)
+
+// Test service plug-ins
+ECOM_PLUGIN(HtiAppServicePlugin.dll,HtiAppServicePlugin.rsc)
+ECOM_PLUGIN(HtiEchoServicePlugin.dll,HtiEchoServicePlugin.rsc)
+ECOM_PLUGIN(HtiFtpServicePlugin.dll,HtiFtpServicePlugin.rsc)
+ECOM_PLUGIN(HtiIpProxyServicePlugin.dll,HtiIpProxyServicePlugin.rsc)
+ECOM_PLUGIN(HtiStifTfServicePlugin.dll,HtiStifTfServicePlugin.rsc)
+
+// File helper
+file=ABI_DIR\BUILD_DIR\HtiFileHlp.exe               SHARED_LIB_DIR\HtiFileHlp.exe
+
+ // HTI Watchdog
+file=ABI_DIR\BUILD_DIR\HtiWatchDog.exe              SHARED_LIB_DIR\HtiWatchDog.exe
+
+ // HTI Restart
+file=ABI_DIR\BUILD_DIR\HtiRestart.exe               SHARED_LIB_DIR\HtiRestart.exe
+
+
+#endif // __HTIOS_IBY__
+
+// End of file
--- a/memspy/CommandLine/Include/MemSpyCommandLine.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/CommandLine/Include/MemSpyCommandLine.h	Wed Oct 13 16:17:58 2010 +0300
@@ -22,9 +22,6 @@
 #include <e32base.h>
 #include <f32file.h>
 #include <badesca.h>
-#include <e32cons.h>
-
-#include "MemSpyCommands.h"
 
 #ifdef _DEBUG
 #   define TRACE( x ) x
@@ -39,28 +36,21 @@
 class RFs;
 class CCommandLineArguments;
 class RMemSpyEngineClientInterface;
-class CConsoleBase;
-class RMemSpySession;
 
-class CMemSpyCommandLine :  public CActive
+class CMemSpyCommandLine : public CBase
     {
 public:
-    //static CMemSpyCommandLine* NewLC();
-	static CMemSpyCommandLine* NewLC( CConsoleBase& aConsole );
+    static CMemSpyCommandLine* NewLC();
     ~CMemSpyCommandLine();
 
 private:
-    //CMemSpyCommandLine();
-    CMemSpyCommandLine( CConsoleBase& aConsole );
+    CMemSpyCommandLine();
     void ConstructL();
 
 public: // API
-    //void PerformBatchL( const TDesC& aFileName ); 	//support of the batch files removed 
+    void PerformBatchL( const TDesC& aFileName );
     void PerformOpL( const CCommandLineArguments& aCommandLine );
     void PerformSingleOpL( const TDesC& aCommand, const CDesCArray& aParameters );
-    //
-    //AO request method
-    void WaitForInput();
 
 private: // Internal methods
     void ConnectToMemSpyL();
@@ -70,26 +60,10 @@
     TInt FindBatchFile( TDes &aFileName );
     TInt FindFile( TDes &aFileName, const TDesC &aDirPath );
 
-private: // Console write methods
-    void RedrawInputPrompt();
-    void RedrawStatusMessage();
-    void RedrawStatusMessage( const TDesC& aMessage );
-    void ProcessCommandBufferL();
-    void RunL(); // from CActive
-    TInt RunError( TInt aError );
-    void DoCancel();
-    
 private: // Data members
     RFs iFsSession;
     RMemSpyEngineClientInterface* iMemSpy;
-    RMemSpySession* iMemSpySession;
     TBool iIsBatch; // For avoiding recursion
-    
-private: // Data members - console - write status messages
-    CConsoleBase& iConsole;
-    TPoint iCommandPromptPos;
-    TPoint iStatusMessagePos;
-    TBuf<KMemSpyMaxInputBufferLength> iCommandBuffer;
     };
 
 
--- a/memspy/CommandLine/Include/MemSpyCommands.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/CommandLine/Include/MemSpyCommands.h	Wed Oct 13 16:17:58 2010 +0300
@@ -18,77 +18,39 @@
 #ifndef MEMSPYCOMMANDS_H
 #define MEMSPYCOMMANDS_H
 
-// Literal constants
-_LIT( KMemSpyCLINewLine, "\r\n" );
-_LIT( KMemSpyCLIName, "MemSpy CommandLineInterpreter" );
-_LIT( KMemSpyCLIInputPrompt, " > %S" );
-_LIT( KMemSpyCLIWildcardCharacter, "*" );
-
-// Numerical constants
-const TInt KMemSpyMaxDisplayLengthThreadName = 48;
-const TInt KMemSpyMaxDisplayLengthSizeText = 14;
-const TInt KMemSpyMaxInputBufferLength = 200;
-
-// Key constants (S60)
-const TInt KMemSpyUiS60KeyCodeButtonOk = 2000;
-const TInt KMemSpyUiS60KeyCodeButtonCancel = 2001;
-const TInt KMemSpyUiS60KeyCodeRockerEnter = 63557;
 
-// Status messages
-_LIT( KOutputChangeMessage, "Change output mode opetarion in progress" );
-_LIT( KHeapDumpMessage, "Heap dump opetarion in progress" );
-_LIT( KSWMTMessage, "System Wide Memory Tracking opetarion in progress" );
+// Literal constants
+_LIT( KMemSpyCmdHeapDump, "CmdHeap_Dump" );
+_LIT( KMemSpyCmdHeapDumpKernel, "CmdHeap_Dump_Kernel" );
+_LIT( KMemSpyCmdHeapCompact, "CmdHeap_Compact" );
+_LIT( KMemSpyCmdSWMTForceUpdate, "CmdSWMT_ForceUpdate" );
+_LIT( KMemSpyCmdSWMTReset, "CmdSWMT_Reset" );
+_LIT( KMemSpyCmdOpenFile, "CmdOpenFile" );
+_LIT( KMemSpyCmdContainer, "CmdContainer" );
+_LIT( KMemSpyCmdBitmapsSave, "CmdBitmaps_Save" );
+_LIT( KMemSpyCmdRamDisableAknIconCache, "CmdRAM_DisableAknIconCache" );
+_LIT( KMemSpyCmdOutputToFile, "CmdOutput_ToFile" );
+_LIT( KMemSpyCmdOutputToTrace, "CmdOutput_ToTrace" );
 
-// Help text
-_LIT( KHelpMessage, "=== MemSpy CommandLineInterpreter Help ===\r\n" );
-_LIT( KHelpOutputCommand, "Change output mode to trace: 'memspy output trace'\r\n" );
-_LIT( KHelpOutputToFileCommand, "Change output mode to trace: 'memspy output file'\r\n" );
-_LIT( KHelpHeapDumpCommand, "Heap dump: 'memspy heapdup <all | kernel | user heap filter >'\r\n" );
-_LIT( KHelpSwmtCommand, "SWMT: 'memspy swmt <starttimer <value in seconds> | stop timer | dumpnow > <categories>'\r\n" );
-_LIT( KHelpKillServerCommand, "Kill server: 'memspy killserver'\r\n" );
-_LIT( KHelpCommand, "Press 'c' to continue" );
 
-//new commands
+_LIT( KMemSpyCmdUiSendToBackground, "CmdUI_Background" );
+_LIT( KMemSpyCmdUiBringToForeground, "CmdUI_Foreground" );
 
-//HELP
-_LIT( KMemSpyCmdHelp1, "-?" );
-_LIT( KMemSpyCmdHelp2, "-h" );
-_LIT( KMemSpyCmdHelp3, "-help" );
-_LIT( KMemSpyCmdHelp4, "--help" );
-
-//OUTPUT
-_LIT( KMemSpyCmdOutput, "output" );
-_LIT( KMemSpyCmdOutputParameterTrace, "trace" );
-_LIT( KMemSpyCmdOutputParameterFile, "file" );
-//<directory> //parameter to be parsed
-
-//HEAP DUMP
-_LIT( KMemSpyCmdHeapDump, "heapdump" );
-_LIT( KMemSpyCmdHeapDumpParameterAll, "all" ); //default
-_LIT( KMemSpyCmdHeapDumpParameterKernel, "kernel" ); //kernel heap dump
+_LIT( KMemSpyCmdUiExit, "CmdUI_Exit" );
 
-//SWMT
-_LIT( KMemSpyCmdSwmt, "swmt" );
-_LIT( KMemSpyCmdSwmtParameterStarttimer, "starttimer" ); //<value in seconds> optionaly
-_LIT( KMemSpyCmdSwmtParameterStoptimer, "stoptimer" );
-_LIT( KMemSpyCmdSwmtParameterDumpnow, "dumpnow" );
-
-//KILL SERVER
-_LIT( KMemSpyCmdKillServer, "killserver"); //kills the server in case of it is running
+_LIT( KMemSpyCmdSWMTTypeHeap,                    "HEAP" );
+_LIT( KMemSpyCmdSWMTTypeChunk,                   "CHNK" );
+_LIT( KMemSpyCmdSWMTTypeCode,                    "CODE" );
+_LIT( KMemSpyCmdSWMTTypeStack,                   "STAK" );
+_LIT( KMemSpyCmdSWMTTypeGlobalData,              "GLOD" );
+_LIT( KMemSpyCmdSWMTTypeRamDrive,                "RAMD" );
+_LIT( KMemSpyCmdSWMTTypeOpenFile,                "FILE" );
+_LIT( KMemSpyCmdSWMTTypeDiskSpace,               "DISK" );
+_LIT( KMemSpyCmdSWMTTypeHandleGeneric,           "HGEN" );
+_LIT( KMemSpyCmdSWMTTypeFbserv,                  "FABS" );
+_LIT( KMemSpyCmdSWMTTypeFileServerCache,         "F32C" );
+_LIT( KMemSpyCmdSWMTTypeSystemMemory,            "SYSM" );
+_LIT( KMemSpyCmdSWMTTypeWindowGroup,             "WNDG" );
+_LIT( KMemSpyCmdSWMTTypeHeapFilter,              "HEAPFilter:" );
 
-//SWMT CATEGORIES (TYPES)
-_LIT( KMemSpyCmdSWMTTypeHeap,                    "heap" );
-_LIT( KMemSpyCmdSWMTTypeChunk,                   "chnk" );
-_LIT( KMemSpyCmdSWMTTypeCode,                    "code" );
-_LIT( KMemSpyCmdSWMTTypeStack,                   "stak" );
-_LIT( KMemSpyCmdSWMTTypeGlobalData,              "glob" );
-_LIT( KMemSpyCmdSWMTTypeRamDrive,                "ramd" );
-_LIT( KMemSpyCmdSWMTTypeOpenFile,                "file" );
-_LIT( KMemSpyCmdSWMTTypeDiskSpace,               "disk" );
-_LIT( KMemSpyCmdSWMTTypeHandleGeneric,           "hgen" );
-_LIT( KMemSpyCmdSWMTTypeFbserv,                  "fabs" );
-_LIT( KMemSpyCmdSWMTTypeFileServerCache,         "f32c" );
-_LIT( KMemSpyCmdSWMTTypeSystemMemory,            "sysm" );
-_LIT( KMemSpyCmdSWMTTypeWindowGroup,             "wndg" );
-_LIT( KMemSpyCmdSWMTTypeAll,					 "all"	); //default value, dumps all categories expect heap dumps	
 #endif
--- a/memspy/CommandLine/Source/MemSpyCommandLine.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/CommandLine/Source/MemSpyCommandLine.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -21,52 +21,148 @@
 #include <bacline.h>
 #include <bautils.h>
 #include <memspyengineclientinterface.h>
-#include <memspysession.h>
 #include <memspy/engine/memspyenginehelpersysmemtrackerconfig.h>
 
 // User includes
 #include "MemSpyCommands.h"
 
-/*
-CMemSpyCommandLine::CMemSpyCommandLine()
-    {	
-    }
-*/
 
-CMemSpyCommandLine::CMemSpyCommandLine( CConsoleBase& aConsole )
-	: CActive( EPriorityHigh ), iConsole( aConsole )
-    {	
-	CActiveScheduler::Add( this );
+CMemSpyCommandLine::CMemSpyCommandLine()
+    {
     }
 
+
 CMemSpyCommandLine::~CMemSpyCommandLine()
     {
-	Cancel();
-	
-    if ( iMemSpySession )
+    if ( iMemSpy )
         {
-        iMemSpySession->Close();
+        iMemSpy->Close();
         }
-    delete iMemSpySession;
+    delete iMemSpy;
     iFsSession.Close();
     }
 
 
 void CMemSpyCommandLine::ConstructL()
     {
-    User::LeaveIfError( iFsSession.Connect() );   
-    iMemSpySession = new(ELeave) RMemSpySession();
-    ConnectToMemSpyL();                    
+    User::LeaveIfError( iFsSession.Connect() );
+    iMemSpy = new(ELeave) RMemSpyEngineClientInterface();
+    ConnectToMemSpyL();
     }
 
-CMemSpyCommandLine* CMemSpyCommandLine::NewLC( CConsoleBase& aConsole )
+
+CMemSpyCommandLine* CMemSpyCommandLine::NewLC()
     {
-    CMemSpyCommandLine* self = new(ELeave) CMemSpyCommandLine( aConsole );
+    CMemSpyCommandLine* self = new(ELeave) CMemSpyCommandLine();
     CleanupStack::PushL( self );
     self->ConstructL();
     return self;
     }
 
+
+void CMemSpyCommandLine::PerformBatchL( const TDesC& aFileName )
+    {
+    TInt err = KErrNone;
+    RFile file;
+    err = file.Open( iFsSession, aFileName, EFileRead );
+    TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformBatchL() - START - this: 0x%08x, openErr: %d, fileName: %S"), this, err, &aFileName ) );
+    User::LeaveIfError( err );
+
+    CleanupClosePushL( file );
+    CDesCArray* lines = ReadLinesL( file );
+    CleanupStack::PopAndDestroy( &file );
+    CleanupStack::PushL( lines );
+    
+    const TInt count = lines->Count();
+    TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformOpL() - got %d lines", count ) );
+    iIsBatch = ETrue;
+    for( TInt i=0; i<count; i++ )
+        {
+        const TPtrC pLine( (*lines)[ i ] );
+        TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformOpL() - processing line[%03d] \"%S\""), i, &pLine ) );
+    
+        // Must be at least 3 chars big, i.e. '[' and <command> and then ']'
+        if  ( pLine.Length() <= 2 || pLine[ 0 ] != '[' )
+            {
+            TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformOpL() - ignoring line: \"%S\""), &pLine ) );
+            }
+        else if  ( pLine[0] == '[' )
+            {
+            // Try to find end of command...
+            const TInt posOfClosingArgChar = pLine.Locate( ']' );
+            if  ( posOfClosingArgChar >= 2 )
+                {
+                // Get command
+                const TPtrC pCommand( pLine.Mid( 1, posOfClosingArgChar - 1 ) );
+                TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformOpL() - got command: %S"), &pCommand ) );
+
+                // Next, try to get any args
+                CDesCArrayFlat* args = new(ELeave) CDesCArrayFlat( 2 );
+                CleanupStack::PushL( args );
+
+                // There must be a mandatory space between closing ] and start of args...
+                // E.g.:
+                //
+                //  [CMD] ARG
+                //
+                const TInt remainderLength = pLine.Length() - posOfClosingArgChar;
+                if  ( remainderLength > 1 )
+                    {
+                    const TPtrC remainder( pLine.Mid( posOfClosingArgChar + 1 ) );
+                    TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformOpL() - got remainder: %S"), &pLine ) );
+
+                    // Extract arguments separated by tabs or space characters
+                    // and store in arguments array
+                    HBufC* argText = HBufC::NewLC( pLine.Length() + 1 );
+                    TPtr pArgText( argText->Des() );
+                    for( TInt j=0; j<remainder.Length(); j++ )
+                        {
+                        const TChar c( remainder[ j ] );
+                        //
+                        if  ( c == '\t' || c == ' ' )
+                            {
+                            pArgText.Trim();
+                            if  ( pArgText.Length() )
+                                {
+                                TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformOpL() - arg[%02d] %S"), args->Count(), &pArgText ) );
+                                args->AppendL( pArgText );
+                                pArgText.Zero();
+                                }
+                            }
+                        else
+                            {
+                            pArgText.Append( c );
+                            }
+                        }
+
+                    // Save leftovers...
+                    pArgText.Trim();
+                    if  ( pArgText.Length() )
+                        {
+                        TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformOpL() - arg[%02d] %S"), args->Count(), &pArgText ) );
+                        args->AppendL( pArgText );
+                        }
+
+                    CleanupStack::PopAndDestroy( argText );
+                    }
+
+                // Now we can perform the operation!
+                PerformSingleOpL( pCommand, *args );
+
+                CleanupStack::PopAndDestroy( args );
+                }
+            }
+
+        TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformOpL() - processing line: \"%S\""), &pLine ) );
+        }
+
+    iIsBatch = EFalse;
+    
+    CleanupStack::PopAndDestroy( lines );
+    TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformBatchL() - END - this: 0x%08x, fileName: %S"), this, &aFileName ) );
+    }
+
+
 void CMemSpyCommandLine::PerformOpL( const CCommandLineArguments& aCommandLine )
     {
     const TInt count = aCommandLine.Count();
@@ -122,187 +218,125 @@
     batchFile.Append( aCommand );
     
     TInt err = KErrNotSupported;
-    TInt error = KErrNotSupported;
-    
-    // --- HELP
-    if ( aCommand.CompareF( KMemSpyCmdHelp1) == 0 || 
-    	 aCommand.CompareF( KMemSpyCmdHelp2) == 0 ||
-    	 aCommand.CompareF( KMemSpyCmdHelp3) == 0 ||
-    	 aCommand.CompareF( KMemSpyCmdHelp4) == 0 )
-    	{
-		iConsole.Write( KHelpMessage );
-		iConsole.Write( KMemSpyCLINewLine );		
-		iConsole.Write( KHelpOutputCommand );
-		iConsole.Write( KHelpOutputToFileCommand );
-		iConsole.Write( KHelpHeapDumpCommand );
-		iConsole.Write( KHelpSwmtCommand );
-		iConsole.Write( KHelpKillServerCommand );
-		iConsole.Write( KMemSpyCLINewLine );
-		iConsole.Write( KHelpCommand );
+    if  ( aCommand.CompareF( KMemSpyCmdSWMTForceUpdate ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - SWMT_ForceUpdate", this ) );
+        if ( paramCount > 0 )
+            {
+            TInt categories( 0 );
+            TName threadNameFilter;
+            TRAP( err, ParseSWMTParametersL( aParameters, categories, threadNameFilter ) );            
+            if ( !err )
+                {
+                err = iMemSpy->SystemWideMemoryTrackerCategoriesSet( categories );
+                if ( !err && threadNameFilter.Length() > 0 )
+                    {
+                    err = iMemSpy->SystemWideMemoryTrackerThreadFilterSet( threadNameFilter );
+                    }
+                }
+            }
+        if ( !err )
+            {
+            err = iMemSpy->PerformOperation( EMemSpyClientServerOpSystemWideMemoryTrackingForceUpdate );
+            }
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdSWMTReset ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - SWMT_Reset", this ) );
+        err = iMemSpy->PerformOperation( EMemSpyClientServerOpSystemWideMemoryTrackingReset );
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdHeapDumpKernel ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Heap_DumpKernel", this ) );
+        err = iMemSpy->PerformOperation( EMemSpyClientServerOpHeapData, KMemSpyClientServerThreadIdKernel );
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdHeapCompact ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Heap_Compact", this ) );
+        err = iMemSpy->PerformOperation( EMemSpyClientServerOpHeapInfoCompact );
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdContainer ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Container", this ) );
+        err = iMemSpy->PerformOperation( EMemSpyClientServerOpEnumerateKernelContainerAll );
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdBitmapsSave ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Bitmaps_Save", this ) );
+        err = iMemSpy->SaveAllBitmaps();
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdRamDisableAknIconCache ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Ram_DisableAknIconCache", this ) );
+        err = iMemSpy->DisableAknIconCache();
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdOutputToFile ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Output_ToFile", this ) );
+        err = iMemSpy->SwitchOutputModeFile();
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdOutputToTrace ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Output_ToTrace", this ) );
+        err = iMemSpy->SwitchOutputModeTrace();
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdUiSendToBackground ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - UI_Background", this ) );
+        err = iMemSpy->SendToBackground();
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdUiBringToForeground ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - UI_Foreground", this ) );
+        err = iMemSpy->BringToForeground();
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdUiExit ) == 0 )
+        {
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - UI_Exit", this ) );
+        err = iMemSpy->Exit();
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdHeapDump ) == 0 )
+        {
+        if  ( paramCount == 0 )
+            {
+            // Dump heap data for all threads
+            TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Heap_Dump (all threads)", this ) );
+            err = iMemSpy->PerformOperation( EMemSpyClientServerOpHeapData );
+            }
+        else if ( paramCount >= 1 )
+            {
+            // Dump heap data for named thread
+            const TPtrC pThreadName( aParameters[ 0 ] );
+            TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Heap_Dump (%S)"), this, &pThreadName ) );
+            err = iMemSpy->PerformOperation( EMemSpyClientServerOpHeapData, pThreadName );
+            }
+        }
+    else if ( aCommand.CompareF( KMemSpyCmdOpenFile ) == 0 )
+        {
+        if  ( paramCount == 0 )
+            {
+            // Dump heap data for all threads
+            TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - OpenFile (all threads)", this ) );
+            err = iMemSpy->PerformOperation( EMemSpyClientServerOpOpenFiles );
+            }
+        else if ( paramCount >= 1 )
+            {
+            // Dump heap data for named thread
+            const TPtrC pThreadName( aParameters[ 0 ] );
+            TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - OpenFile (%S)"), this, &pThreadName ) );
+            err = iMemSpy->PerformOperation( EMemSpyClientServerOpOpenFiles, pThreadName );
+            }
+        }
+    else if ( !iIsBatch && FindBatchFile( batchFile ) == KErrNone )
+        {
+        TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Batch file: %S"), this, &batchFile ) );
+        PerformBatchL( batchFile );
+        }
+    else
+        {
+        TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Unsupported Command: %S"), this, &aCommand ) );
+        }
 
-	    // Show input prompt.
-	    iCommandPromptPos = iConsole.CursorPos();
-	    RedrawInputPrompt();
-	    WaitForInput();
-	    
-	    CActiveScheduler::Start();
-    	}
-    // --- OUTPUT
-    //TODO: directory option to be added
-    else if  ( aCommand.CompareF( KMemSpyCmdOutput ) == 0 )	//change output mode   
-    	{    						
-		if( paramCount >= 1 )
-			{
-			if( aParameters[0].CompareF( KMemSpyCmdOutputParameterFile ) == 0 )
-				{
-				if( paramCount == 2 )
-					{
-					TBuf<KMaxFileName> directory;
-					directory.Copy( aParameters[1] );
-					iMemSpySession->SwitchOutputToFileL( directory );
-					}
-				else
-					{
-					iMemSpySession->SwitchOutputToFileL( KNullDesC );
-					}
-				}
-			else if( aParameters[0].CompareF( KMemSpyCmdOutputParameterTrace ) == 0)
-				{
-				TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Output Trace", this ) );
-				iMemSpySession->SwitchOutputToTraceL();
-				}
-			}		           
-    	}    	
-    // --- HEAP DUMP    
-    else if ( aCommand.CompareF( KMemSpyCmdHeapDump) == 0 )    	
-		{		
-		RedrawStatusMessage( KHeapDumpMessage );
-		
-		if( paramCount == 0 ) // no parameter - dump all heap data + kernel heap at the end
-			{		
-		
-			TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Heap_Dump (all threads)", this ) );			
-			// Dump heap data for all threads - Thread agnostic operation					
-			iMemSpySession->OutputHeapData();
-			// Dump kernel heap data
-			iMemSpySession->OutputThreadHeapDataL( KMemSpyClientServerThreadIdKernel );					
-			}
-		else if( paramCount >= 1)
-			{
-			if( aParameters[0].CompareF( KMemSpyCmdHeapDumpParameterAll ) == 0 )
-				{
-				iMemSpySession->OutputHeapData();				
-				iMemSpySession->OutputThreadHeapDataL( KMemSpyClientServerThreadIdKernel );				
-				}
-			else if( aParameters[0].CompareF( KMemSpyCmdHeapDumpParameterKernel ) == 0 )
-				{
-				TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Heap_DumpKernel", this ) );
-				iMemSpySession->OutputThreadHeapDataL( KMemSpyClientServerThreadIdKernel );				
-				}
-			else
-				{				
-				// Dump heap data for named thread - filter
-				const TPtrC pThreadName( aParameters[0] );
-				TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - Heap_Dump (%S)"), this, &pThreadName ) );				
-				iMemSpySession->OutputThreadHeapDataL( pThreadName );
-				}
-  			}
-		}
-    
-    // --- SYSTEM WIDE MEMORY TRACKING    
-    else if( aCommand.CompareF( KMemSpyCmdSwmt ) == 0 )
-    	{    
-		RedrawStatusMessage( KSWMTMessage );
-    		
-		TInt categories( 0 );
-		TName threadNameFilter;
-		
-		if( paramCount == 0 ) //default state -> "dumpnow" command with "all" categories
-			{
-			TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - this: 0x%08x - dumpnow command", this ) );
-			TInt category = TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryAll;
-			iMemSpySession->SetSwmtCategoriesL( category );			
-			iMemSpySession->ForceSwmtUpdateL();			
-			}
-		else if( paramCount >= 1)
-			{
-			const TPtrC pParam( aParameters[0] );
-			if( pParam.CompareF( KMemSpyCmdSwmtParameterStarttimer) == 0 ) // "starttimer" - start tracking
-				{
-				TInt result(0);
-				categories = TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryAll;
-				iMemSpySession->SetSwmtTimerIntervalL( KMemSpySysMemTrackerConfigMinTimerPeriod );
-				
-				if( paramCount >= 2 ) // user gave some optional parameters - <categories> or <value in seconds>
-					{					
-					TLex lex( aParameters[1] );
-				    if ( lex.Val( result ) == KErrNone ) //if 2nd parameter is not number, then parse parameters
-				    	{
-						if( result >= KMemSpySysMemTrackerConfigMinTimerPeriod && result <= KMemSpySysMemTrackerConfigMaxTimerPeriod )
-							{
-							iMemSpySession->SetSwmtTimerIntervalL( result );							;
-							}											
-				    	}				   
-				    TRAP( err, ParseSWMTParametersL( aParameters, categories, threadNameFilter) );
-					}																				
-				
-				//if( !err )
-				//	{
-					/*
-					_LIT( KPressS, "Press 's' to stop the timer " );
-					iConsole.Write( KPressS );
-					
-					iCommandPromptPos = iConsole.CursorPos();					
-					RedrawInputPrompt();					
-					WaitForInput();
-					*/
-					    
-					iMemSpySession->StartSwmtTimerL();
-					
-					//CActiveScheduler::Start();									
-				//	}	
-				}
-			else if( pParam.CompareF( KMemSpyCmdSwmtParameterStoptimer) == 0 ) // "stoptime" - stop tracking
-				{
-				iMemSpySession->StopSwmtTimerL();
-				}
-			else if( pParam.CompareF( KMemSpyCmdSwmtParameterDumpnow ) == 0 ) // "dumpnow" - runs one tracking cycle (CmdSWMT_ForceUpdate before)
-				{
-				categories = TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryAll;
-				if( paramCount >= 2 ) // user gave some optional parameters - <categories>
-					{
-					TRAP( err, ParseSWMTParametersL( aParameters, categories, threadNameFilter) );
-					}				
-																
-				if( !err )
-					{
-					iMemSpySession->SetSwmtCategoriesL( categories );
-					iMemSpySession->ForceSwmtUpdateL();
-					}												
-				}							
-			else //no parameters ("starttimer / stoptimer / dumpnow"), just categories / thread filter
-				 //so dumpnow is used as default with category / thread specified
-				{
-				TRAP( err, ParseSWMTParametersL( aParameters, categories, threadNameFilter) );
-				if( !err )
-					{
-					iMemSpySession->SetSwmtCategoriesL( categories );
-					if( threadNameFilter.Length() > 0 )
-						{
-						iMemSpySession->SetSwmtFilter( threadNameFilter );
-						}
-					}								
-					iMemSpySession->ForceSwmtUpdateL();				
-				}
-			}
-    	}
-    // --- KILL SERVER
-    else if ( aCommand.CompareF( KMemSpyCmdKillServer ) == 0 )
-    	{    
-    	}
-    
-   // RedrawStatusMessage();   
-    
     TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::PerformSingleOpL() - END - err: %d, this: 0x%08x, cmd: %S" ), err, this, &aCommand ) );
 
     // Calculate duration
@@ -330,7 +364,7 @@
     {
     TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::ConnectToMemSpyL() - START - this: 0x%08x", this ) );
 
-    TInt err = iMemSpySession->Connect();
+    TInt err = iMemSpy->Connect();
     TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::ConnectToMemSpyL() - connect #1 err: %d, this: 0x%08x", err, this ) );
 
     if  ( err == KErrNotFound )
@@ -356,48 +390,47 @@
 
     TInt err = KErrGeneral;
     RProcess proc;
-    
-    // Try to run server first
-    err = proc.Create( KMemSpyProcessName0, KNullDesC );
-    if ( err == KErrNone )
-    	{
-		TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - Create server process successfully... - this: 0x%08x", this ) );
+
+    // First try with s60 UI
+    err = proc.Create( KMemSpyProcessName1, KNullDesC );
+    if  ( err == KErrNone )
+        {
+        TFullName fullName;
+        proc.FullName( fullName );
+        TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - Create S60 UI process successfully... - this: 0x%08x, name: %S"), this, &fullName ) );
 
-		TRequestStatus status;
-		proc.Rendezvous( status );
-		proc.Resume();
-
-		TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - MemSpy resumed, waiting for Rendezvous... - this: 0x%08x", this ) );
+        TRequestStatus status;
+        proc.Rendezvous( status );
+        proc.Resume();
 
-		User::WaitForRequest( status );
-		err = status.Int();
-		proc.Close();
-
-		TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - Rendezvous complete: %d, this: 0x%08x", err, this ) );
-    	}
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - MemSpy resumed, waiting for Rendezvous... - this: 0x%08x", this ) );
+        User::WaitForRequest( status );
+        err = status.Int();
+        proc.Close();
 
-    // If server is not available, try with s60 UI
-    if ( err != KErrNone )
-    	{
-		err = proc.Create( KMemSpyProcessName1, KNullDesC );
-		if  ( err == KErrNone )
-			{
-			TFullName fullName;
-			proc.FullName( fullName );
-			TRACE( RDebug::Print( _L("[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - Create S60 UI process successfully... - this: 0x%08x, name: %S"), this, &fullName ) );
-	
-			TRequestStatus status;
-			proc.Rendezvous( status );
-			proc.Resume();
-	
-			TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - MemSpy resumed, waiting for Rendezvous... - this: 0x%08x", this ) );
-			User::WaitForRequest( status );
-			err = status.Int();
-			proc.Close();
-	
-			TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - Rendezvous complete: %d, this: 0x%08x", err, this ) );
-			}
-    	}
+        TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - Rendezvous complete: %d, this: 0x%08x", err, this ) );
+        }
+    if  ( err != KErrNone )
+        {
+        // Try console UI
+        err = proc.Create( KMemSpyProcessName2, KNullDesC );
+        if  ( err == KErrNone )
+            {
+            TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - Create Console UI process successfully... - this: 0x%08x", this ) );
+
+            TRequestStatus status;
+            proc.Rendezvous( status );
+            proc.Resume();
+
+            TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - MemSpy resumed, waiting for Rendezvous... - this: 0x%08x", this ) );
+
+            User::WaitForRequest( status );
+            err = status.Int();
+            proc.Close();
+
+            TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - Rendezvous complete: %d, this: 0x%08x", err, this ) );
+            }
+        }
 
     TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine::LaunchMemSpyL() - final error: %d, this: 0x%08x", err, this ) );
     User::LeaveIfError( err );
@@ -501,12 +534,11 @@
     // In that case other parameters are ignored.
     TLex lex( aParameters[ 0 ] );
     if ( lex.Val( result ) != KErrNone )
-        {		
+        {
         // Parameters were given in text form:
         const TInt count( aParameters.Count() );
         for ( TInt i = 0; i < count ; i++ )
             {
-			lex = aParameters[ i ]; //check if num.
             if ( aParameters[i].CompareF( KMemSpyCmdSWMTTypeHeap ) == 0 )
                 result |= TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryUserHeap |
                           TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryKernelHeap;
@@ -533,31 +565,17 @@
                 result |= TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryFileServerCache;
             else if ( aParameters[i].CompareF( KMemSpyCmdSWMTTypeSystemMemory ) == 0 )
                 result |= TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategorySystemMemory;
-            else if ( aParameters[i].CompareF( KMemSpyCmdSWMTTypeWindowGroup ) == 0 )            	
-                result |= TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryWindowGroups;            
-            else if ( aParameters[i].CompareF( KMemSpyCmdSWMTTypeAll) == 0 ) //"all" category added
-            	result = TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryAll;
-            else if ( aParameters[i].CompareF( KMemSpyCmdSwmtParameterDumpnow) == 0 || 
-            		aParameters[i].CompareF( KMemSpyCmdSwmtParameterStarttimer) == 0 || 
-            		aParameters[i].CompareF( KMemSpyCmdSwmtParameterStoptimer) == 0 )
-            	{    
-				TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine:: command parameter") );
-            	}
-            else if ( lex.Val( result ) == KErrNone )
-            	{
-				TRACE( RDebug::Printf( "[MemSpyCmdLine] CMemSpyCommandLine:: number - timer period") );
-            	}
-            else// if ( aParameters[i].Find( KMemSpyCmdSWMTTypeHeapFilter ) == 0 )
-                {				
-                aFilter.Copy( aParameters[i].Right( aParameters[i].Length() -11 ) );              
+            else if ( aParameters[i].CompareF( KMemSpyCmdSWMTTypeWindowGroup ) == 0 )
+                result |= TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryWindowGroups;
+            else if ( aParameters[i].Find( KMemSpyCmdSWMTTypeHeapFilter ) == 0 )
+                {
+                aFilter.Copy( aParameters[i].Right( aParameters[i].Length() -11 ) );
                 }
-          /*  else
-            	{
-                //User::Leave( KErrNotSupported );            	            
-            	}*/
+            else
+                User::Leave( KErrNotSupported );
             }
         }
-    else if ( aParameters.Count() > 1 )//&& aParameters[1].Find( KMemSpyCmdSWMTTypeHeapFilter ) == 0 )
+    else if ( aParameters.Count() > 1 && aParameters[1].Find( KMemSpyCmdSWMTTypeHeapFilter ) == 0 )
         {
         aFilter.Copy( aParameters[1].Right( aParameters[1].Length() -11 ) );
         }
@@ -589,110 +607,3 @@
     return err;
     }
 
-
-//CLI status messages methods
-void CMemSpyCommandLine::RedrawInputPrompt()
-    {
-    iConsole.SetCursorPosAbs( iCommandPromptPos );
-    iConsole.ClearToEndOfLine();
-    iConsole.Printf( KMemSpyCLIInputPrompt, &iCommandBuffer );
-    }
-
-
-void CMemSpyCommandLine::RedrawStatusMessage()
-    {
-    RedrawStatusMessage( KNullDesC );
-    }
-
-
-void CMemSpyCommandLine::RedrawStatusMessage( const TDesC& aMessage )
-    {
-    iConsole.SetCursorPosAbs( iStatusMessagePos );
-    iConsole.ClearToEndOfLine();
-    iConsole.Write( aMessage );
-    iConsole.Write( KMemSpyCLINewLine );
-    }
-
-void CMemSpyCommandLine::WaitForInput()
-    {
-    ASSERT( !IsActive() );
-    iConsole.Read( iStatus );
-    SetActive();
-    }
-
-void CMemSpyCommandLine::DoCancel()
-    {
-    iConsole.ReadCancel();
-    }
-
-void CMemSpyCommandLine::RunL()
-    {
-    TKeyCode key = iConsole.KeyCode();
-    //
-    if  ( key == EKeyEnter || key == KMemSpyUiS60KeyCodeButtonOk || key == KMemSpyUiS60KeyCodeRockerEnter )
-        {
-        TRAP_IGNORE( ProcessCommandBufferL() );
-        }
-    else
-        {
-        TChar character( key );
-        if  ( character.IsPrint() )
-            {
-            if  ( iCommandBuffer.Length() < iCommandBuffer.MaxLength() )
-                {
-                iCommandBuffer.Append( TChar( key ) );
-                }
-
-            RedrawInputPrompt();
-            }
-        }
-
-    WaitForInput();
-    }
-
-TInt CMemSpyCommandLine::RunError( TInt aError )
-	{	
-	return KErrNone;
-	}
-
-void CMemSpyCommandLine::ProcessCommandBufferL()
-    {
-    iCommandBuffer.Trim();
-    //
-#ifdef _DEBUG
-    RDebug::Print( _L("[MCon] CMemSpyConsoleMenu::ProcessCommandBufferL() - cmd: [%S]"), &iCommandBuffer );
-#endif
-    //
-    TBool validCommand = EFalse;
-    if  ( iCommandBuffer.Length() == 1 )
-        {
-        // Reset if not recognised...
-        validCommand = ETrue;
-
-        const TChar cmd = iCommandBuffer[ 0 ]; 
-        switch( cmd )
-            {
-        	case 's':
-        	case 'S':
-        		{
-        		iMemSpy->PerformOperation( EMemSpyClientServerOpSystemWideMemoryTrackingTimerStop );
-        		
-        		CActiveScheduler::Stop();
-        		return;
-        		}
-        	case 'c':
-        	case 'C':
-        		CActiveScheduler::Stop();
-        		return;            
-        	default:
-        		validCommand = EFalse;
-        		break;
-            }
-        }    
-    if  ( !validCommand )
-        {
-        _LIT( KInvalidEntry, "*** ERROR - Invalid Command ***" );
-        RedrawStatusMessage( KInvalidEntry );
-        RedrawInputPrompt();
-        }
-    }
--- a/memspy/CommandLine/Source/MemSpyCommandLineMain.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/CommandLine/Source/MemSpyCommandLineMain.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -25,7 +25,7 @@
 
 // User includes
 #include "MemSpyCommandLine.h"
-#include "MemSpyCommands.h"
+
 
 // ---------------------------------------------------------------------------
 // DoMainL()
@@ -38,27 +38,21 @@
     CActiveScheduler* scheduler = new (ELeave) CActiveScheduler();
     CActiveScheduler::Install( scheduler );
     CleanupStack::PushL( scheduler );
-    
+
     // Get command line 
     CCommandLineArguments* args = CCommandLineArguments::NewLC();
-    
-    //--
-    CConsoleBase* console = Console::NewL( KMemSpyCLIName, TSize( KConsFullScreen, KConsFullScreen ) );
-    CleanupStack::PushL( console );
-    //--
-    
+
     // Command line manager
-    CMemSpyCommandLine* commandLineMgr = CMemSpyCommandLine::NewLC( *console );
+    CMemSpyCommandLine* commandLineMgr = CMemSpyCommandLine::NewLC();
 
     // Play nicely with external processes
     RProcess::Rendezvous( KErrNone );
 
     // Perform op
-    commandLineMgr->PerformOpL( *args );  
-        
+    commandLineMgr->PerformOpL( *args );
+
     // Tidy up
-    //CleanupStack::PopAndDestroy( 3, scheduler ); // scheduler, args, commandLineMgr
-    CleanupStack::PopAndDestroy( 4 ); // scheduler, args,  console, commandLineMgr
+    CleanupStack::PopAndDestroy( 3, scheduler ); // scheduler, args, commandLineMgr
     }
    
 
--- a/memspy/CommandLine/group/MemSpyCommandLine.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/CommandLine/group/MemSpyCommandLine.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -25,7 +25,7 @@
 VENDORID		VID_DEFAULT
 SMPSAFE
 
-CAPABILITY		WriteDeviceData
+CAPABILITY			none
 
 SOURCEPATH      ../Source
 SOURCE          MemSpyCommandLine.cpp
@@ -37,12 +37,6 @@
 
 OS_LAYER_SYSTEMINCLUDE
 
-APP_LAYER_SYSTEMINCLUDE
-
-LIBRARY         MemSpyClient.lib
-
-LIBRARY					euser.lib 
-LIBRARY 				efsrv.lib 
-LIBRARY 				bafl.lib 
+LIBRARY					euser.lib efsrv.lib bafl.lib 
 
 
--- a/memspy/Console/Include/ConsoleMenu.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Console/Include/ConsoleMenu.h	Wed Oct 13 16:17:58 2010 +0300
@@ -26,22 +26,22 @@
 // Engine includes
 #include <memspy/engine/memspyengine.h>
 #include <memspy/engine/memspyengineobserver.h>
-#include <memspysession.h>
+
 // User includes
 #include "ConsoleConstants.h"
 
 // Classes referenced
 class CConsoleBase;
-class RMemSpySession;
+
 
 class CMemSpyConsoleMenu : public CActive, public MMemSpyEngineObserver
     {
 public:
-    static CMemSpyConsoleMenu* NewLC( RMemSpySession& aSession, CConsoleBase& aConsole );
+    static CMemSpyConsoleMenu* NewLC( CMemSpyEngine& aEngine, CConsoleBase& aConsole );
     ~CMemSpyConsoleMenu();
 
 private:
-    CMemSpyConsoleMenu( RMemSpySession& aEngine, CConsoleBase& aConsole );
+    CMemSpyConsoleMenu( CMemSpyEngine& aEngine, CConsoleBase& aConsole );
     void ConstructL();
 
 public: // API
@@ -74,10 +74,8 @@
     void InitiateMemSpyClientServerOperationL( TInt aOpCode );
 
 private: // Data members
-    RMemSpySession& iSession;
+    CMemSpyEngine& iEngine;
     CConsoleBase& iConsole;
-    
-    TMemSpyOutputType iOutputType;
     //
     TBuf<KMemSpyMaxInputBufferLength> iCommandBuffer;
     TPoint iCommandPromptPos;
--- a/memspy/Console/Source/ConsoleDWOperation.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Console/Source/ConsoleDWOperation.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -56,7 +56,7 @@
 #endif
 
     iWaiter = new(ELeave) CActiveSchedulerWait();
-    //iOperation = CMemSpyDeviceWideOperations::NewL( iEngine, *this, aOperation );
+    iOperation = CMemSpyDeviceWideOperations::NewL( iEngine, *this, aOperation );
 
 #ifdef _DEBUG
     RDebug::Printf("[MCon] CMemSpyDeviceWideOperationWaiter::ExecuteL() - starting scheduler wait..." );
--- a/memspy/Console/Source/ConsoleMain.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Console/Source/ConsoleMain.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -26,7 +26,6 @@
 
 // Engine includes
 #include <memspy/engine/memspyengine.h>
-#include <memspysession.h>
 
 // User includes
 #include "ConsoleMenu.h"
@@ -55,12 +54,11 @@
 	CleanupStack::PushL( console );
 
     // Engine
-    RMemSpySession session;
-    User::LeaveIfError(session.Connect());
-    CleanupClosePushL(session);
+    CMemSpyEngine* engine = CMemSpyEngine::NewL( fsSession );
+    CleanupStack::PushL( engine );
 
     // Menu & event handler AO
-    CMemSpyConsoleMenu::NewLC( session, *console );
+    CMemSpyConsoleMenu::NewLC( *engine, *console );
 
     // Play nicely with external processes
     RProcess::Rendezvous( KErrNone );
--- a/memspy/Console/Source/ConsoleMenu.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Console/Source/ConsoleMenu.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -39,17 +39,18 @@
 #include "ConsoleDWOperation.h"
 
 
-CMemSpyConsoleMenu::CMemSpyConsoleMenu( RMemSpySession& aSession, CConsoleBase& aConsole )
-:   CActive( EPriorityHigh ), iSession( aSession ), iConsole( aConsole ), iOutputType(EOutputTypeDebug)
+CMemSpyConsoleMenu::CMemSpyConsoleMenu( CMemSpyEngine& aEngine, CConsoleBase& aConsole )
+:   CActive( EPriorityHigh ), iEngine( aEngine ), iConsole( aConsole )
     {
     CActiveScheduler::Add( this );
-    // TODO: iEngine.SetObserver( this );
+    iEngine.SetObserver( this );
     }
 
 
 CMemSpyConsoleMenu::~CMemSpyConsoleMenu()
     {
     Cancel();
+    iEngine.SetObserver( NULL );
     }
 
 
@@ -60,9 +61,9 @@
     }
 
 
-CMemSpyConsoleMenu* CMemSpyConsoleMenu::NewLC( RMemSpySession& aSession, CConsoleBase& aConsole )
+CMemSpyConsoleMenu* CMemSpyConsoleMenu::NewLC( CMemSpyEngine& aEngine, CConsoleBase& aConsole )
     {
-    CMemSpyConsoleMenu* self = new(ELeave) CMemSpyConsoleMenu( aSession, aConsole );
+    CMemSpyConsoleMenu* self = new(ELeave) CMemSpyConsoleMenu( aEngine, aConsole );
     CleanupStack::PushL( self );
     self->ConstructL();
     return self;
@@ -75,7 +76,7 @@
    
     // First line - sink type (defaults to file)
     _LIT( KLine1, "1 or T. Toggle output mode between file or trace [%S]" );
-    if  ( iOutputType == EOutputTypeDebug )
+    if  ( iEngine.SinkType() == ESinkTypeDebug )
         {
         _LIT( KLine1Trace, "Trace" );
         iConsole.Printf( KLine1, &KLine1Trace );
@@ -203,7 +204,14 @@
 
 void CMemSpyConsoleMenu::OnCmdSinkTypeToggleL()
     {
-	iOutputType = iOutputType == EOutputTypeFile ? EOutputTypeDebug : EOutputTypeFile;
+    if  ( iEngine.SinkType() == ESinkTypeDebug )
+        {
+        iEngine.InstallSinkL( ESinkTypeFile );
+        }
+    else
+        {
+        iEngine.InstallSinkL( ESinkTypeDebug );
+        }
     }
 
 
@@ -216,7 +224,7 @@
     _LIT( KMsg, "Ouputting Kernel data..." );
     RedrawStatusMessage( KMsg );
 
-    iSession.OutputKernelHeapDataL( iOutputType );
+    iEngine.HelperHeap().OutputHeapDataKernelL();
 
     RedrawStatusMessage( KNullDesC );
     }
@@ -231,7 +239,14 @@
     _LIT( KMsg, "Ouputting Kernel Object listing..." );
     RedrawStatusMessage( KMsg );
     //
-    iSession.OutputKernelObjectsL( iOutputType );
+    CMemSpyEngineHelperKernelContainers& kernelContainerManager = iEngine.HelperKernelContainers();
+    CMemSpyEngineGenericKernelObjectContainer* model = kernelContainerManager.ObjectsAllL();
+    CleanupStack::PushL( model );
+    //
+    CMemSpyEngineOutputSink& sink = iEngine.Sink();
+    model->OutputL( sink );
+    //
+    CleanupStack::PopAndDestroy( model );
 
     RedrawStatusMessage( KNullDesC );
     }
@@ -243,7 +258,7 @@
     RDebug::Printf( "[MCon] CMemSpyConsoleMenu::OnCmdCSVListingStackL() - START" );
 #endif
 
-    iSession.OutputCompactStackInfoL( iOutputType );
+    iEngine.HelperStack().OutputStackInfoForDeviceL();
     }
 
 
@@ -253,7 +268,7 @@
     RDebug::Printf( "[MCon] CMemSpyConsoleMenu::OnCmdCSVListingHeapL() - START" );
 #endif
 
-    iSession.OutputCompactHeapInfoL( iOutputType );
+    iEngine.HelperHeap().OutputHeapInfoForDeviceL();
     }
 
 
@@ -281,34 +296,44 @@
         TPtr pCmdBuf( cmdBuf->Des() );
         pCmdBuf.Copy( iCommandBuffer );
         pCmdBuf.Append( KMemSpyConsoleWildcardCharacter );
-        
-        TInt err;
-        TProcessId procId;
-        TRAP(err, procId = iSession.GetProcessIdByNameL(pCmdBuf));
+        //
+        CMemSpyEngineObjectContainer& container = iEngine.Container();
+        const TInt count = container.Count();
+        TFullName fullThreadName;
         //
-        if (err == KErrNone) 
-        	{
-        	RArray<CMemSpyApiThread*> threads;
-        	
-        	TRAP(err, iSession.GetThreadsL(procId, threads));
-        	if (err == KErrNone)
-        		{
-				_LIT( KProcessingRequest, "** Dumping Heap Data for thread: %S" );     	
-				TFullName fullThreadName;
-				
-                for( TInt i=0; i<threads.Count(); i++ )
+        TInt index = 0;
+#ifdef _DEBUG
+        RDebug::Printf( "[MCon] CMemSpyConsoleMenu::OnCmdHeapDataUserL() - procCount: %d", count );
+#endif
+
+        while( index < count )
+            {
+            CMemSpyProcess& process = container.At( index );
+            const TPtrC processName( process.Name() );
+#ifdef _DEBUG
+            RDebug::Print( _L("[MCon] CMemSpyConsoleMenu::OnCmdHeapDataUserL() - procName: 0x%08x %S"), &process, &processName );
+#endif
+
+            //
+            if  ( processName.MatchF( pCmdBuf ) >= 0 )
+                {
+                _LIT( KProcessingRequest, "** Dumping Heap Data for thread: %S" );
+                const TInt threadCount = process.Count();
+                for( TInt i=0; i<threadCount; i++ )
                     {
-                    CMemSpyApiThread* thread = threads[i];
+                    CMemSpyThread& thread = process.At( i );
                     //
-                    fullThreadName = thread->Name();
+                    fullThreadName = thread.FullName();
                     iConsole.Printf( KProcessingRequest, &fullThreadName );
                     iConsole.Write( KMemSpyConsoleNewLine );
                     //
-                    TRAP_IGNORE( iSession.OutputThreadHeapDataL(iOutputType, thread->Id()) );
-                    
-                    delete thread;
+                    TRAP_IGNORE( iEngine.HelperHeap().OutputHeapDataUserL( thread ) );
                     }
+
+                break;
                 }
+            
+            ++index;
             }
 
         CleanupStack::PopAndDestroy( cmdBuf );
@@ -344,36 +369,38 @@
         TPtr pCmdBuf( cmdBuf->Des() );
         pCmdBuf.Copy( iCommandBuffer );
         pCmdBuf.Append( KMemSpyConsoleWildcardCharacter );
-        
-        TInt err;
-		TProcessId procId;
-		TRAP(err, procId = iSession.GetProcessIdByNameL(pCmdBuf));
-		//
-		if (err == KErrNone) 
-			{
-			RArray<CMemSpyApiThread*> threads;
-			
-			TRAP(err, iSession.GetThreadsL(procId, threads));
-			if (err == KErrNone)
-				{
-				_LIT( KProcessingRequest, "** Dumping Heap Cell List for thread: %S" );     	
-				TFullName fullThreadName;
-				
-				for( TInt i=0; i<threads.Count(); i++ )
-					{
-					CMemSpyApiThread* thread = threads[i];
-					//
-					fullThreadName = thread->Name();
-					iConsole.Printf( KProcessingRequest, &fullThreadName );
-					iConsole.Write( KMemSpyConsoleNewLine );
-					//
-					TRAP_IGNORE( iSession.OutputThreadCellListL(iOutputType, thread->Id()) );
-					
-					delete thread;
-					}
-				}
-			}
-        
+        //
+        CMemSpyEngineObjectContainer& container = iEngine.Container();
+        const TInt count = container.Count();
+        TFullName fullThreadName;
+        //
+        TInt index = 0;
+        while( index < count )
+            {
+            CMemSpyProcess& process = container.At( index );
+            const TPtrC processName( process.Name() );
+            //
+            if  ( processName.MatchF( pCmdBuf ) >= 0 )
+                {
+                _LIT( KProcessingRequest, "** Dumping Heap Cell List for thread: %S" );
+                const TInt threadCount = process.Count();
+                for( TInt i=0; i<threadCount; i++ )
+                    {
+                    CMemSpyThread& thread = process.At( i );
+                    //
+                    fullThreadName = thread.FullName();
+                    iConsole.Printf( KProcessingRequest, &fullThreadName );
+                    iConsole.Write( KMemSpyConsoleNewLine );
+                    //
+                    TRAP_IGNORE( iEngine.HelperHeap().OutputCellListingUserL( thread ) );
+                    }
+
+                break;
+                }
+            
+            ++index;
+            }
+
         CleanupStack::PopAndDestroy( cmdBuf );
         DrawMenuL();
         }
@@ -577,72 +604,71 @@
 
 void CMemSpyConsoleMenu::InitiateMemSpyClientServerOperationL( TInt aOpCode )
     {
-	// TODO: ....
-//#ifdef _DEBUG
-//    RDebug::Printf( "[MCon] CMemSpyConsoleMenu::InitiateMemSpyClientServerOperationL() - START - aOpCode: %d, iRunningDeviceWideOperation: %d", aOpCode, iRunningDeviceWideOperation );
-//#endif
-//    //
-//    if ( aOpCode == EMemSpyClientServerOpExit )
-//        {
-//        // Exit console app UI
-//        CActiveScheduler::Stop();
-//        }
-//    else
-//        {
-//        CMemSpyDeviceWideOperations::TOperation op = CMemSpyDeviceWideOperations::EPerEntityGeneralSummary;
-//        switch( aOpCode )
-//            {
-//        case EMemSpyClientServerOpSummaryInfo:
-//            op = CMemSpyDeviceWideOperations::EPerEntityGeneralSummary;
-//            break;
-//        case EMemSpyClientServerOpSummaryInfoDetailed:
-//            op = CMemSpyDeviceWideOperations::EPerEntityGeneralDetailed;
-//            break;
-//        //
-//        case EMemSpyClientServerOpHeapInfo:
-//            op = CMemSpyDeviceWideOperations::EPerEntityHeapInfo;
-//            break;
-//        case EMemSpyClientServerOpHeapCellListing:
-//            op = CMemSpyDeviceWideOperations::EPerEntityHeapCellListing;
-//            break;
-//        case EMemSpyClientServerOpHeapData:
-//            op = CMemSpyDeviceWideOperations::EPerEntityHeapData;
-//            break;
-//        //
-//        case EMemSpyClientServerOpStackInfo:
-//            op = CMemSpyDeviceWideOperations::EPerEntityStackInfo;
-//            break;
-//        case EMemSpyClientServerOpStackDataUser:
-//            op = CMemSpyDeviceWideOperations::EPerEntityStackDataUser;
-//            break;
-//        case EMemSpyClientServerOpStackDataKernel:
-//            op = CMemSpyDeviceWideOperations::EPerEntityStackDataKernel;
-//            break;
-//        
-//        // These are not supported by the console UI
-//        default:
-//        case EMemSpyClientServerOpBitmapsSave:
-//        case EMemSpyClientServerOpSendToBackground:
-//        case EMemSpyClientServerOpBringToForeground:
-//            User::Leave( KErrNotSupported );
-//            break;
-//            }
-//
-//        if  ( iRunningDeviceWideOperation )
-//            {
-//            User::Leave( KErrInUse );
-//            }
-//        else
-//            {
-//            iRunningDeviceWideOperation = ETrue;
-//            TRAP_IGNORE( CMemSpyDeviceWideOperationWaiter::ExecuteLD( iEngine, op ) );
-//            iRunningDeviceWideOperation = EFalse;
-//            }
-//        }
-//
-//#ifdef _DEBUG
-//    RDebug::Printf( "[MCon] CMemSpyConsoleMenu::InitiateMemSpyClientServerOperationL() - END - aOpCode: %d", aOpCode );
-//#endif
+#ifdef _DEBUG
+    RDebug::Printf( "[MCon] CMemSpyConsoleMenu::InitiateMemSpyClientServerOperationL() - START - aOpCode: %d, iRunningDeviceWideOperation: %d", aOpCode, iRunningDeviceWideOperation );
+#endif
+    //
+    if ( aOpCode == EMemSpyClientServerOpExit )
+        {
+        // Exit console app UI
+        CActiveScheduler::Stop();
+        }
+    else
+        {
+        CMemSpyDeviceWideOperations::TOperation op = CMemSpyDeviceWideOperations::EPerEntityGeneralSummary;
+        switch( aOpCode )
+            {
+        case EMemSpyClientServerOpSummaryInfo:
+            op = CMemSpyDeviceWideOperations::EPerEntityGeneralSummary;
+            break;
+        case EMemSpyClientServerOpSummaryInfoDetailed:
+            op = CMemSpyDeviceWideOperations::EPerEntityGeneralDetailed;
+            break;
+        //
+        case EMemSpyClientServerOpHeapInfo:
+            op = CMemSpyDeviceWideOperations::EPerEntityHeapInfo;
+            break;
+        case EMemSpyClientServerOpHeapCellListing:
+            op = CMemSpyDeviceWideOperations::EPerEntityHeapCellListing;
+            break;
+        case EMemSpyClientServerOpHeapData:
+            op = CMemSpyDeviceWideOperations::EPerEntityHeapData;
+            break;
+        //
+        case EMemSpyClientServerOpStackInfo:
+            op = CMemSpyDeviceWideOperations::EPerEntityStackInfo;
+            break;
+        case EMemSpyClientServerOpStackDataUser:
+            op = CMemSpyDeviceWideOperations::EPerEntityStackDataUser;
+            break;
+        case EMemSpyClientServerOpStackDataKernel:
+            op = CMemSpyDeviceWideOperations::EPerEntityStackDataKernel;
+            break;
+        
+        // These are not supported by the console UI
+        default:
+        case EMemSpyClientServerOpBitmapsSave:
+        case EMemSpyClientServerOpSendToBackground:
+        case EMemSpyClientServerOpBringToForeground:
+            User::Leave( KErrNotSupported );
+            break;
+            }
+
+        if  ( iRunningDeviceWideOperation )
+            {
+            User::Leave( KErrInUse );
+            }
+        else
+            {
+            iRunningDeviceWideOperation = ETrue;
+            TRAP_IGNORE( CMemSpyDeviceWideOperationWaiter::ExecuteLD( iEngine, op ) );
+            iRunningDeviceWideOperation = EFalse;
+            }
+        }
+
+#ifdef _DEBUG
+    RDebug::Printf( "[MCon] CMemSpyConsoleMenu::InitiateMemSpyClientServerOperationL() - END - aOpCode: %d", aOpCode );
+#endif
     }
 
 
--- a/memspy/Console/group/MemSpyConsole.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Console/group/MemSpyConsole.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -25,8 +25,8 @@
 
 #include		"../../group/MemSpyCapabilities.mmh"
 
-//EPOCSTACKSIZE   0x4000
-//EPOCHEAPSIZE	0x100000 0x4000000
+EPOCSTACKSIZE   0x4000
+EPOCHEAPSIZE	0x100000 0x4000000
 
 
 SOURCEPATH      ../Source
@@ -41,5 +41,6 @@
 LIBRARY         euser.lib
 LIBRARY         efsrv.lib 
 
-LIBRARY		MemSpyClient.lib
-LIBRARY     MemSpyEngine.lib
\ No newline at end of file
+LIBRARY         memspydriverclient.lib
+LIBRARY         memspyengine.lib 
+
--- a/memspy/Console/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Console/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -23,4 +23,4 @@
 
 
 PRJ_MMPFILES
-//MemSpyConsole.mmp
+MemSpyConsole.mmp
--- a/memspy/Driver/BWINS/memspydriverclientu.def	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/BWINS/memspydriverclientu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -67,5 +67,4 @@
 	?WalkHeapReadCellData@RMemSpyDriverClient@@QAEHPAXAAVTDes8@@H@Z @ 66 NONAME ; int RMemSpyDriverClient::WalkHeapReadCellData(void *, class TDes8 &, int)
 	?GetCondVarSuspendedThreads@RMemSpyDriverClient@@QAEHPAXPAPAXAAH@Z @ 67 NONAME ; int RMemSpyDriverClient::GetCondVarSuspendedThreads(void *, void * *, int &)
 	?GetCondVarSuspendedThreadInfo@RMemSpyDriverClient@@QAEHPAXAAVTMemSpyDriverCondVarSuspendedThreadInfo@@@Z @ 68 NONAME ; int RMemSpyDriverClient::GetCondVarSuspendedThreadInfo(void *, class TMemSpyDriverCondVarSuspendedThreadInfo &)
-	?GetHeapInfoUser@RMemSpyDriverClient@@QAEHAAVTMemSpyHeapInfo@@IAAV?$RArray@VTMemSpyDriverFreeCell@@@@H@Z @ 69 NONAME ; int RMemSpyDriverClient::GetHeapInfoUser(class TMemSpyHeapInfo &, unsigned int, class RArray<class TMemSpyDriverFreeCell> &, int)
 
--- a/memspy/Driver/Kernel/Include/MemSpyDriverHeap.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/MemSpyDriverHeap.h	Wed Oct 13 16:17:58 2010 +0300
@@ -28,39 +28,104 @@
 #include "MemSpyDriverObjectsInternal.h"
 
 // Constants
-// We shouldn't be using any of these any more! -Tomsci
 const TUint KRHeapObjectSize = 0x74;
 const TUint KRAllocatorAndRHeapMemberDataOffset = 4; // 4 bytes past start of allocator address, i.e. skipping the vtable
 const TUint KRHeapMemberDataSize = KRHeapObjectSize - KRAllocatorAndRHeapMemberDataOffset;
 
 // Classes referenced
 class DMemSpyDriverOSAdaption;
-namespace LtkUtils
-	{
-	class RAllocatorHelper;
-	}
+
 
 /**
  * Essentially a mirror of RAllocator and RHeap's layout.
  */
 class RMemSpyDriverRHeapBase
 	{
+public:
+	struct SCell
+        {
+        TInt len; 
+        SCell* next;
+        };
+
+    struct SDebugCell
+        {
+        TInt len;
+        TInt nestingLevel;
+        TInt allocCount;
+        };
+
+    struct _s_align {char c; double d;};
+
+    struct SHeapCellInfo { RHeap* iHeap; TInt iTotalAlloc;	TInt iTotalAllocSize; TInt iTotalFree; TInt iLevelAlloc; SDebugCell* iStranded; };
+	
+    enum {ECellAlignment = sizeof(_s_align)-sizeof(double)};
+	enum {EFreeCellSize = sizeof(SCell)};
+	enum TDebugOp {EWalk=128};
+	enum TCellType
+		{EGoodAllocatedCell, EGoodFreeCell, EBadAllocatedCellSize, EBadAllocatedCellAddress,
+		EBadFreeCellAddress, EBadFreeCellSize};
+	
+    enum TDebugHeapId {EUser=0, EKernel=1};
+
 protected:
     RMemSpyDriverRHeapBase();
 
+public: // Inlines
+    inline TUint8* Base() const { return iBase; }
+    inline TInt Size() const { return iTop - iBase; }
+    inline TInt MaxLength() const { return iMaxLength; }
+
 public: // API
     void PrintInfo();
-	LtkUtils::RAllocatorHelper* Helper();
-	TMemSpyHeapInfo::THeapImplementationType GetTypeFromHelper() const;
+    void CopyObjectDataTo( TMemSpyHeapObjectDataRHeap& aData );
 
 public: // Virtual API
     virtual void Reset();
-	virtual void Close();
+    virtual void AssociateWithKernelChunk( DChunk* aChunk, TLinAddr aAddress, TUint32 aMappingAttributes ) = 0;
+    virtual void DisassociateWithKernelChunk() = 0;
     virtual DChunk& Chunk() = 0;
     virtual const DChunk& Chunk() const = 0;
+    virtual TLinAddr ChunkKernelAddress() const = 0;
+    virtual TBool ChunkIsInitialised() const = 0;
+    virtual TUint ClientToKernelDelta() const = 0;
+    virtual void GetHeapSpecificInfo( TMemSpyHeapInfo& /*aInfo*/ ) const { }
 
-protected:
-	LtkUtils::RAllocatorHelper* iHelper;
+public: // Utilities
+    TBool CheckCell( TAny* aCellAddress, TInt aLength ) const;
+    static TInt AllocatedCellHeaderSize( TBool aDebugLibrary );
+    static TInt FreeCellHeaderSize();
+    static TInt CellHeaderSize( const TMemSpyDriverInternalWalkHeapParamsCell& aCell, TBool aDebugEUser );
+
+public: // From RAllocator
+	TInt iAccessCount;
+	TInt iHandleCount;
+	TInt* iHandles;
+	TUint32 iFlags;
+	TInt iCellCount;
+	TInt iTotalAllocSize;
+
+public: // From RHeap
+	TInt iMinLength;
+	TInt iMaxLength;
+	TInt iOffset;
+	TInt iGrowBy;
+	TInt iChunkHandle;
+	RFastLock iLock;
+	TUint8* iBase;
+	TUint8* iTop;
+	TInt iAlign;
+	TInt iMinCell;
+	TInt iPageSize;
+	SCell iFree;
+	TInt iNestingLevel;
+	TInt iAllocCount;
+    RAllocator::TAllocFail iFailType;
+	TInt iFailRate;
+	TBool iFailed;
+	TInt iFailAllocCount;
+	TInt iRand;
+	TAny* iTestData;
     };
 
 
@@ -72,12 +137,17 @@
     RMemSpyDriverRHeapReadFromCopy( DMemSpyDriverOSAdaption& aOSAdaption );
 
 public: // New API
-    void AssociateWithKernelChunk( DChunk* aChunk, TLinAddr aAddress, TUint32 aMappingAttributes );
+    TInt ReadFromUserAllocator( DThread& aThread );
 
 public: // From RMemSpyDriverRHeapBase
     void Reset();
+    void AssociateWithKernelChunk( DChunk* aChunk, TLinAddr aAddress, TUint32 aMappingAttributes );
+    void DisassociateWithKernelChunk();
     DChunk& Chunk();
     const DChunk& Chunk() const;
+    TLinAddr ChunkKernelAddress() const;
+    TBool ChunkIsInitialised() const;
+    TUint ClientToKernelDelta() const;
 
 protected:
     inline DMemSpyDriverOSAdaption& OSAdaption() { return iOSAdaption; }
@@ -92,7 +162,7 @@
 
     // Calculated delta between client's address space values and actual kernel
     // address of the heap chunk.
-    //TUint iClientToKernelDelta;
+    TUint iClientToKernelDelta;
     };
 
 
@@ -101,21 +171,13 @@
 
 
 
-class RMemSpyDriverRHeapUser : public RMemSpyDriverRHeapBase
+class RMemSpyDriverRHeapUser : public RMemSpyDriverRHeapReadFromCopy
 	{
 public:
     RMemSpyDriverRHeapUser( DMemSpyDriverOSAdaption& aOSAdaption );
-	TInt OpenUserHeap(DThread& aThread, TBool aEuserUdeb);
 
-	DChunk& Chunk() { return *iChunk; }
-	const DChunk& Chunk() const { return *iChunk; }
-
-private:
-    inline DMemSpyDriverOSAdaption& OSAdaption() { return iOSAdaption; }
-
-private:
-    DMemSpyDriverOSAdaption& iOSAdaption;
-	DChunk* iChunk;
+public: // New API
+    TInt ReadFromUserAllocator( DThread& aThread );
     };
 
 
@@ -129,8 +191,8 @@
     void SetKernelHeap( RHeapK& aKernelHeap );
 
 public: // From RMemSpyDriverRHeapBase
-    //void DisassociateWithKernelChunk();
-	void Close();
+    void DisassociateWithKernelChunk();
+    void GetHeapSpecificInfo( TMemSpyHeapInfo& aInfo ) const;
 
 private:
     RHeapK* iKernelHeap;
@@ -142,19 +204,50 @@
     {
 public:
     RMemSpyDriverRHeapKernelInPlace();
-	TInt OpenKernelHeap();
     
+public: // API
+    void FailNext();
+    void SetKernelHeap( RHeapK& aKernelHeap );
 
 public: // From RMemSpyDriverRHeapBase
-    void Close();
-
+    void Reset();
+    void AssociateWithKernelChunk( DChunk* aChunk, TLinAddr aAddress, TUint32 aMappingAttributes );
+    void DisassociateWithKernelChunk();
     DChunk& Chunk();
     const DChunk& Chunk() const;
+    TLinAddr ChunkKernelAddress() const;
+    TBool ChunkIsInitialised() const;
+    TUint ClientToKernelDelta() const;
+    void GetHeapSpecificInfo( TMemSpyHeapInfo& aInfo ) const;
 
-	// Only important member data is the base class's RAllocatorHelper
-	// We do cache the chunk though
+private: // Internal methods
+    void CopyMembersFromKernelHeap();
+
+private: // Internal class
+
+    /**
+     * Used when opening the kernel heap
+     */
+#ifndef __SYMBIAN_KERNEL_HYBRID_HEAP__
+    class RHeapKExtended : public RHeapK
+        {
+    public:
+        inline void FailNext()
+            {
+            SetFailType( RAllocator::EFailNext );
+            SetFailRate( 1 );
+            ResetFailed();
+            ResetFailAllocCount();
+            }
+        inline void SetFailType( TAllocFail aType ) { iFailType = aType; }
+        inline void SetFailRate( TInt aRate ) { iFailRate = aRate; }
+        inline void ResetFailed() { iFailed = EFalse; }
+        inline void ResetFailAllocCount() { iFailAllocCount = 0; }
+        };
+#endif
 private:
-	DChunk* iChunk;
+    RHeapK* iKernelHeap;
+    DChunk* iChunk;
     };
 
 	
--- a/memspy/Driver/Kernel/Include/MemSpyDriverHeapStatistics.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/MemSpyDriverHeapStatistics.h	Wed Oct 13 16:17:58 2010 +0300
@@ -69,8 +69,7 @@
     TUint iLargestCellAddressFreePrevious;
 
     // The overhead associated with a free cell (header length)
-    //TUint iFreeCellOverheadHeaderLength;
-	TUint iReserved1;
+    TUint iFreeCellOverheadHeaderLength;
 
     // The slace space at the end of the heap
     TUint iSlackSpace;
@@ -94,8 +93,7 @@
     TLinAddr iLargestCellAddressAlloc;
    
     // The overhead associated with an allocated cell (header length)
-    //TUint iAllocCellOverheadHeaderLength;
-	TUint iReserved2;
+    TUint iAllocCellOverheadHeaderLength;
 
 public: // Common
 
--- a/memspy/Driver/Kernel/Include/MemSpyDriverHeapWalker.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/MemSpyDriverHeapWalker.h	Wed Oct 13 16:17:58 2010 +0300
@@ -29,23 +29,32 @@
 #include "MemSpyDriverHeap.h"
 #include "MemSpyDriverHeapStatistics.h"
 
-#include "heaputils.h"
-using namespace LtkUtils;
 
 // Heap walker observer interface - can be used to make a record of each cell
 class MMemSpyHeapWalkerObserver
     {
 public:
-    virtual TBool HandleHeapCell(TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber) = 0;
+    virtual TBool HandleHeapCell( TInt aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber ) = 0;
     virtual void HandleHeapWalkInit() = 0;
     };
 
 
+
+// A null observer that is used to collect basic statistics
+class TMemSpyHeapWalkerNullObserver : public MMemSpyHeapWalkerObserver
+    {
+public:
+    TBool HandleHeapCell( TInt /*aCellType*/, TAny* /*aCellAddress*/, TInt /*aLength*/, TInt /*aNestingLevel*/, TInt /*aAllocNumber*/ ) { return ETrue; }
+    void HandleHeapWalkInit() { }
+    };
+
+
 // Heap walker - allows in-place walking of any heap
 class RMemSpyDriverHeapWalker
     {
 public:
-	RMemSpyDriverHeapWalker(RMemSpyDriverRHeapBase& aHeap, MMemSpyHeapWalkerObserver* aObserver=NULL);
+    RMemSpyDriverHeapWalker( RMemSpyDriverRHeapBase& aHeap, TBool aDebugAllocator );
+    RMemSpyDriverHeapWalker( RMemSpyDriverRHeapBase& aHeap, TBool aDebugAllocator, MMemSpyHeapWalkerObserver& aObserver );
 		
 public: // API
     TInt Traverse();
@@ -54,9 +63,12 @@
     inline void SetPrintDebug() { iPrintDebug = ETrue; }
     inline const TMemSpyHeapWalkStatistics& Stats() const { return iStats; }
 
+public: // Utility functions
+    static TAny* KernelAddress( TAny* aUserAddress, TUint aDelta );
+    static TAny* UserAddress( TAny* aKernelAddress, TUint aDelta );
+    static RMemSpyDriverRHeapBase::SCell* CellByUserAddress( TAny* aAddress, TUint aDelta );
+
 private: // Internal methods
-	static TBool CellCallback(RAllocatorHelper& aHelper, TAny* aContext, RAllocatorHelper::TExtendedCellType aCellType, TLinAddr aCellAddress, TInt aLength);
-	TBool DoCellCallback(RAllocatorHelper& aHelper, RAllocatorHelper::TExtendedCellType aCellType, TLinAddr aCellAddress, TInt aLength);
     TBool NotifyCell( TMemSpyDriverCellType aType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel = -1, TInt aAllocNumber = -1 );
     //
     void UpdateStats( TMemSpyDriverCellType aType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber );
@@ -64,10 +76,14 @@
     void FinaliseStats();
     void PrintStats();
     //
+    TAny* KernelAddress( TAny* aUserAddress ) const;
+    TAny* UserAddress( TAny* aKernelAddress ) const;
+    //
     inline TBool PrintDebug() const { return iPrintDebug; }
 
 private:
     RMemSpyDriverRHeapBase& iHeap;
+    TBool iIsDebugAllocator;
     TBool iPrintDebug;
     MMemSpyHeapWalkerObserver* iObserver;
     TMemSpyHeapWalkStatistics iStats;
--- a/memspy/Driver/Kernel/Include/MemSpyDriverInspectedProcess.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/MemSpyDriverInspectedProcess.h	Wed Oct 13 16:17:58 2010 +0300
@@ -138,8 +138,6 @@
     void ResetPendingChanges();
     void PrintChunkInfo( DChunk& aChunk ) const;
     TBool IsChunkRelevantToOurProcess( DChunk& aChunk ) const;
-	void Lock() const;
-	void Unlock() const;
 
 public: // Queue link for process manager
 	SDblQueLink iPMLink;
--- a/memspy/Driver/Kernel/Include/MemSpyDriverLog.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/MemSpyDriverLog.h	Wed Oct 13 16:17:58 2010 +0300
@@ -119,6 +119,5 @@
 #   define TRACE_CHUNK( x )
 #endif
 
-#define LOG(args...) TRACE(Kern::Printf(args))
 
 #endif
--- a/memspy/Driver/Kernel/Include/MemSpyDriverOSAdaption.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/MemSpyDriverOSAdaption.h	Wed Oct 13 16:17:58 2010 +0300
@@ -106,7 +106,7 @@
     TUint GetId( DProcess& aObject ) const;
     MemSpyObjectIx* GetHandles( DProcess& aObject ) const;
     TExitType GetExitType( DProcess& aObject ) const;
-    DThread* OpenFirstThread( DProcess& aObject ) const;
+    DThread* GetFirstThread( DProcess& aObject ) const;
     TUint32 GetSID( DProcess& aObject ) const;
     TUint GetSecurityZone( DProcess& aObject ) const;
     SSecurityInfo& GetSecurityInfo( DProcess& aObject ) const;
@@ -122,7 +122,6 @@
     TUint8* GetAddressOfOwningProcess( DProcess& aObject ) const;
     TUint8* GetAddressOfDataBssStackChunk( DProcess& aObject ) const;
     TBool IsHandleIndexValid( DProcess& aObject ) const;
-	TBool IsKernProcess(DProcess& aProcess) const;
 
 private: // Data members
     };
--- a/memspy/Driver/Kernel/Include/MemSpyDriverObjectIx.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/MemSpyDriverObjectIx.h	Wed Oct 13 16:17:58 2010 +0300
@@ -126,8 +126,8 @@
 	// common operations
     RMemSpyObjectIx();
 
-    //static void Wait();
-	//static void Signal();
+    static void Wait();
+	static void Signal();
 
     inline TInt Count()
 		{ return iCount; }
@@ -137,7 +137,7 @@
 public:
 	// uncommon operations
 	DObject* operator[](TInt aIndex);
-	TBool Find(DObject* aObject);
+	TInt At(DObject* aObject);
 
 private:
 	TRWSpinLock		iRWL;
@@ -171,11 +171,11 @@
 public:
 	DObject* At(TInt aHandle,TInt aUniqueID);
 	DObject* At(TInt aHandle);
-	TBool Find(DObject* aObject);
+	TInt At(DObject* aObject);
 	TInt Count(DObject* aObject);
 	DObject* operator[](TInt aIndex);
-	//static void Wait( DMemSpyObjectIx* aObjectIndex );
-	//static void Signal( DMemSpyObjectIx* aObjectIndex );
+	static void Wait( DMemSpyObjectIx* aObjectIndex );
+	static void Signal( DMemSpyObjectIx* aObjectIndex );
 	inline TInt Count();
 	inline TInt ActiveCount();
 
@@ -206,24 +206,24 @@
 #if MCL_ROBJECTIX_DUPLICATION
 
     #define MemSpyObjectIx                                          RMemSpyObjectIx
-    //#define MemSpyObjectIx_Wait( IX )                               RMemSpyObjectIx::Wait()
-    //#define MemSpyObjectIx_Signal( IX )                             RMemSpyObjectIx::Signal()
+    #define MemSpyObjectIx_Wait( IX )                               RMemSpyObjectIx::Wait()
+    #define MemSpyObjectIx_Signal( IX )                             RMemSpyObjectIx::Signal()
     #define MemSpyObjectIx_GetHandlePointer_Thread( DTHREAD )       reinterpret_cast< MemSpyObjectIx* >( &DTHREAD.iHandles )
     #define MemSpyObjectIx_GetHandlePointer_Process( DPROCESS )     reinterpret_cast< MemSpyObjectIx* >( &DPROCESS.iHandles )
 
 #elif MCL_DOBJECTIX_DUPLICATION
 
     #define MemSpyObjectIx                                          DMemSpyObjectIx
-    //#define MemSpyObjectIx_Wait( IX )                               DMemSpyObjectIx::Wait( IX )
-    //#define MemSpyObjectIx_Signal( IX )                             DMemSpyObjectIx::Signal( IX )
+    #define MemSpyObjectIx_Wait( IX )                               DMemSpyObjectIx::Wait( IX )
+    #define MemSpyObjectIx_Signal( IX )                             DMemSpyObjectIx::Signal( IX )
     #define MemSpyObjectIx_GetHandlePointer_Thread( DTHREAD )       reinterpret_cast< MemSpyObjectIx* >( DTHREAD.iHandles )
     #define MemSpyObjectIx_GetHandlePointer_Process( DPROCESS )     reinterpret_cast< MemSpyObjectIx* >( DPROCESS.iHandles )
 
 #else
 
     #define MemSpyObjectIx                  DObjectIx
-    //#define MemSpyObjectIx_Wait( IX )       
-    //#define MemSpyObjectIx_Signal( IX )     
+    #define MemSpyObjectIx_Wait( IX )       
+    #define MemSpyObjectIx_Signal( IX )     
     #define MemSpyObjectIx_IsValid_Thread( DTHREAD )    ( DTHREAD.iHandles != NULL )
     #define MemSpyObjectIx_IsValid_Process( DPROCESS )  ( DPROCESS.iHandles != NULL )
     #define MemSpyObjectIx_GetHandlePointer_Thread( DTHREAD )       reinterpret_cast< MemSpyObjectIx* >( DTHREAD.iHandles )
@@ -231,7 +231,4 @@
 
 #endif
 
-#define MemSpyObjectIx_HandleLookupLock()							NKern::LockSystem()
-#define MemSpyObjectIx_HandleLookupUnlock()							NKern::UnlockSystem()
-
 #endif
--- a/memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanContainerBase.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanContainerBase.h	Wed Oct 13 16:17:58 2010 +0300
@@ -42,8 +42,8 @@
 protected: // Internal methods
     static TObjectType ObjectTypeFromMemSpyContainerType( TMemSpyDriverContainerType aType );
 
-	// Must be in critical section to call
-	DObject* CheckedOpen(TMemSpyDriverContainerType aContainerType, DObject* aObject, TBool aQuick=EFalse);
+    /** Returns with System Locked */
+    DObject* CheckIfObjectIsInContainer( TMemSpyDriverContainerType aContainerType, DObject* aSearchFor, TBool aQuick = EFalse );
 
 protected: // Internal methods
     void ResetTempHandles();
--- a/memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapBase.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapBase.h	Wed Oct 13 16:17:58 2010 +0300
@@ -61,20 +61,33 @@
 protected: // Capability checks for heap access
     TDrmMatchType IsDrmThread( DThread& aThread );
 
-protected: // From MHeapWalkerObserver
+private: // From MHeapWalkerObserver
     void HandleHeapWalkInit();
-    TBool HandleHeapCell( TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber );
+    TBool HandleHeapCell( TInt aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber );
 
 protected: // Heap utility functions
     TInt OpenKernelHeap( RHeapK*& aHeap, DChunk*& aChunk, TDes8* aClientHeapChunkName = NULL );
+    TInt OpenKernelHeap( RMemSpyDriverRHeapKernelInPlace& aHeap, TDes8* aClientHeapChunkName = NULL );
     TInt OpenKernelHeap( RMemSpyDriverRHeapKernelFromCopy& aHeap, TDes8* aClientHeapChunkName = NULL );
-    TInt GetHeapInfoKernel(RMemSpyDriverRHeapBase& aHeap, TMemSpyHeapInfo* aHeapInfo, TDes8* aTransferBuffer);
+    TInt OpenUserHeap( DThread& aClientThread, TUint aExpectedHeapVTable, RMemSpyDriverRHeapUser& aHeap, DChunk*& aUserHeapChunk, TDes8* aClientHeapChunkName = NULL );
+    TBool GetUserHeapHandle( DThread& aThread, RMemSpyDriverRHeapUser& aHeap, TUint aExpectedVTable );
+    TBool IsDebugKernel();
+    TBool IsDebugKernel( RMemSpyDriverRHeapKernelInPlace& aHeap );
+    TInt GetHeapInfoKernel( RMemSpyDriverRHeapBase& aHeap, TBool aIsDebugAllocator, const TDesC8& aChunkName, TMemSpyHeapInfo* aHeapInfo, TDes8* aTransferBuffer );
     void PrintHeapInfo( const TMemSpyHeapInfo& aInfo );
 
+protected: // Free cells
+    void ReleaseFreeCells();
+    TInt PrepareFreeCellTransferBuffer();
+	TInt FetchFreeCells( TDes8* aBufferSink );
+    TInt CalculateFreeCellBufferSize() const;
+
 private: // Data members
+	RArray< TMemSpyDriverFreeCell > iFreeCells;
 
     // Points to stack-based object whilst walking in progress
     RMemSpyMemStreamWriter* iStackStream;
+    RMemSpyMemStreamWriter* iHeapStream;
     TInt iFreeCellCount;
 	};
 
--- a/memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapInfo.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapInfo.h	Wed Oct 13 16:17:58 2010 +0300
@@ -53,22 +53,13 @@
 private: // Channel operation handlers
     TInt GetHeapInfoUser( TMemSpyDriverInternalHeapRequestParameters* aParams );
     TInt GetHeapInfoKernel( TMemSpyDriverInternalHeapRequestParameters* aParams, TDes8* aTransferBuffer );
-    TInt GetIsDebugKernel(TAny* aIsDebugKernel);
-
-private: // From MHeapWalkerObserver
-    void HandleHeapWalkInit();
-    TBool HandleHeapCell( TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber );
+    TInt GetIsDebugKernel( TBool* aIsDebugKernel );
 
 private: // Internal methods
-	void ReleaseCellList();
-    TInt PrepareCellListTransferBuffer();
-	TInt FetchCellList(TDes8* aBufferSink);
-    TInt CalculateCellListBufferSize() const;
+    TUint32 CalculateFreeCellBufferSize() const;
 
 private: // Data members
     TMemSpyDriverInternalHeapRequestParameters iHeapInfoParams;
-	RArray<TMemSpyDriverCell> iCellList;
-    RMemSpyMemStreamWriter* iHeapStream;
 	};
 
 
--- a/memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapWalk.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Include/SubChannels/MemSpyDriverLogChanHeapWalk.h	Wed Oct 13 16:17:58 2010 +0300
@@ -61,7 +61,7 @@
     const TMemSpyDriverInternalWalkHeapParamsCell* CellInfoForSpecificAddress( TAny* aAddress ) const;
 
 private: // Heap walker callback
-    TBool WalkerHandleHeapCell(TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber );
+    TBool WalkerHandleHeapCell( TInt aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber );
 
 private:
     TBool iHeapWalkInitialised;
@@ -85,7 +85,7 @@
 
 public: // From MHeapWalkerObserver
     void HandleHeapWalkInit() { }
-    TBool HandleHeapCell(TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber )
+    TBool HandleHeapCell( TInt aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber )
         {
         return iChannel.WalkerHandleHeapCell( aCellType, aCellAddress, aLength, aNestingLevel, aAllocNumber );
         }
--- a/memspy/Driver/Kernel/Source/MemSpyDriverEventMonitor.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverEventMonitor.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -170,7 +170,6 @@
 TUint DMemSpyEventMonitor::HandleEvent( TKernelEvent aType, TAny* a1, TAny* /*a2*/ )
 	{ 
 	// TRACE_EM( Kern::Printf("DMemSpyEventMonitor::HandleEvent() - PRE WAIT"));
-	NKern::ThreadEnterCS();
 	Kern::MutexWait(*iLock);
 	// TRACE_EM( Kern::Printf("DMemSpyEventMonitor::HandleEvent() - POST WAIT"));
 
@@ -251,7 +250,6 @@
 
 	// TRACE_EM( Kern::Printf("DMemSpyEventMonitor::HandleEvent() - PRE SIGNAL "));
 	Kern::MutexSignal( *iLock );
-	NKern::ThreadLeaveCS();
 	// TRACE_EM( Kern::Printf("DMemSpyEventMonitor::HandleEvent() - POST SIGNAL "));
 
 	// Allow other handlers to see this event
--- a/memspy/Driver/Kernel/Source/MemSpyDriverHeap.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverHeap.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -23,62 +23,129 @@
 // User includes
 #include "MemSpyDriverOSAdaption.h"
 #include "MemSpyDriverUtils.h"
-#include "heaputils.h"
 
+// Defines
+#define __NEXT_CELL(p)				((RMemSpyDriverRHeapBase::SCell*)(((TUint8*)p)+p->len))
+#define __NEXT_CELL2(p,l)			((RMemSpyDriverRHeapBase::SCell*)(((TUint8*)p)+l))
 
 
 RMemSpyDriverRHeapBase::RMemSpyDriverRHeapBase()
-	: iHelper(NULL)
     {
     Reset();
     }
 
-LtkUtils::RAllocatorHelper* RMemSpyDriverRHeapBase::Helper()
-	{
-	return iHelper;
-	}
-
-TMemSpyHeapInfo::THeapImplementationType RMemSpyDriverRHeapBase::GetTypeFromHelper() const
-	{
-	if (iHelper)
-		{
-		LtkUtils::RAllocatorHelper::TType type = iHelper->GetType();
-		switch (type)
-			{
-			case LtkUtils::RAllocatorHelper::ETypeRHeap:
-				return TMemSpyHeapInfo::ETypeRHeap;
-			case LtkUtils::RAllocatorHelper::ETypeRHybridHeap:
-				return TMemSpyHeapInfo::ETypeRHybridHeap;
-			case LtkUtils::RAllocatorHelper::ETypeUnknown:
-			default:
-				return TMemSpyHeapInfo::ETypeUnknown;
-			}
-		}
-	return TMemSpyHeapInfo::ETypeUnknown;
-	}
 
 void RMemSpyDriverRHeapBase::Reset()
     {
-	Close();
+	iAccessCount = 0;
+	iHandleCount = 0;
+	iHandles = NULL;
+	iFlags = 0;
+	iCellCount = 0;
+	iTotalAllocSize = 0;
+    
+    iMinLength = 0;
+	iMaxLength = 0;
+	iOffset = 0;
+	iGrowBy = 0;
+	iChunkHandle = 0;
+	// iLock needs no initialisation due to default ctor
+	iBase = NULL;
+	iTop = NULL;
+	iAlign = 0;
+	iMinCell = 0;
+	iPageSize = 0;
+	iFree.len = 0;
+	iFree.next = NULL;
+	iNestingLevel = 0;
+	iAllocCount = 0;
+    iFailType = RAllocator::EReset;
+	iFailRate = 0;
+	iFailed = EFalse;
+	iFailAllocCount = 0;
+	iRand = 0;
+	iTestData = NULL;
+    }
+
+
+TBool RMemSpyDriverRHeapBase::CheckCell( TAny* aCellAddress, TInt aLength ) const
+	{
+	const TLinAddr m = TLinAddr(iAlign - 1);
+    TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapBase::CheckCell() - cell: 0x%08x, len: %8d, iAlign: %d, m: %d", aCellAddress, aLength, iAlign, m) );
+
+    TBool isValid = ETrue;
+    //
+    if ( isValid && (aLength & m) )
+        {
+    	TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapBase::CheckCell() - ERROR - length is odd: %d, iAlign: %d, m: %d", aLength, iAlign, m) );
+        isValid = EFalse;
+        }
+    if ( isValid && aLength < iMinCell )
+        {
+    	TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapBase::CheckCell() - ERROR - length: %d, is less than min cell size (%d)", aLength, iMinCell) );
+        isValid = EFalse;
+        }
+    if ( isValid && (TUint8*)aCellAddress < iBase )
+        {
+    	TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapBase::CheckCell() - ERROR - cell address: 0x%08x, is before start address: 0x%08x", (TUint8*) aCellAddress, iBase) );
+        isValid = EFalse;
+        }
+
+    if  ( isValid )
+        {
+        const TUint8* nextCell = (TUint8*)__NEXT_CELL2(aCellAddress, aLength);
+        if  ( nextCell > iTop )
+            {
+        	TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapBase::CheckCell() - ERROR - nextCell: 0x%08x is after the top of the heap: 0x%08x", nextCell, iTop) );
+            isValid = EFalse;
+            }
+        }
+    //
+    return isValid;
 	}
 
-void RMemSpyDriverRHeapBase::Close()
-	{
-	if (iHelper)
-		{
-	    NKern::ThreadEnterCS();
-		iHelper->Close();
-		delete iHelper;
-		iHelper = NULL;
-		NKern::ThreadLeaveCS();
-		}
+
+TInt RMemSpyDriverRHeapBase::AllocatedCellHeaderSize( TBool aDebugLibrary )
+    {
+    // Allocated cells are only 4 bytes in UREL, but 12 bytes in UDEB.
+    TInt size = sizeof(SCell*);
+    //
+    if  ( aDebugLibrary )
+        {
+        size = sizeof(SDebugCell);
+        }
+    //
+    return size;
     }
 
+
+TInt RMemSpyDriverRHeapBase::FreeCellHeaderSize()
+    {
+    // Free cells remain the same size in UREL and UDEB builds.
+    const TInt size = sizeof(SCell);
+    return size; 
+    }
+
+
+TInt RMemSpyDriverRHeapBase::CellHeaderSize( const TMemSpyDriverInternalWalkHeapParamsCell& aCell, TBool aDebugLibrary )
+    {
+    TInt size = 0;
+    //
+    if  ( aCell.iCellType == EMemSpyDriverGoodAllocatedCell )
+        {
+        size = AllocatedCellHeaderSize( aDebugLibrary );
+        }
+    else if ( aCell.iCellType == EMemSpyDriverGoodFreeCell ) 
+        {
+        size = FreeCellHeaderSize();
+        }
+    //
+    return size;
+    }
+
+
 void RMemSpyDriverRHeapBase::PrintInfo()
     {
-	/* TOMSCI TODO replace with tracing based on latest struct info. See DMemSpyDriverLogChanHeapBase::PrintHeapInfo
-	 * Alternatively just call DMemSpyDriverLogChanHeapBase::PrintHeapInfo() somehow?
-	 
 #if defined(TRACE_TYPE_KERNELHEAP) || defined(TRACE_TYPE_USERHEAP)
     Kern::Printf(" " );
     Kern::Printf("RMemSpyDriverRHeapBase::PrintInfo - RAllocator - iAccessCount:    0x%08x", iAccessCount );
@@ -106,11 +173,70 @@
     Kern::Printf(" " );
     Kern::Printf(" " );
 #endif
-	*/
+    }
+
+
+void RMemSpyDriverRHeapBase::CopyObjectDataTo( TMemSpyHeapObjectDataRHeap& aData )
+    {
+    TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapBase::CopyObjectDataTo() - START" ) );
+
+    TUint8* sourceAddress = reinterpret_cast< TUint8* >( this );
+    sourceAddress += KRAllocatorAndRHeapMemberDataOffset;
+    memcpy( &aData, sourceAddress, KRHeapObjectSize );
+
+    TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapBase::CopyObjectDataTo() - END") );
     }
 
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 RMemSpyDriverRHeapReadFromCopy::RMemSpyDriverRHeapReadFromCopy( DMemSpyDriverOSAdaption& aOSAdaption )
-:   iOSAdaption( aOSAdaption ), iChunk( NULL ), iChunkAddress( 0 ), iChunkMappingAttributes( 0 ) /*, iClientToKernelDelta( 0 )*/
+:   iOSAdaption( aOSAdaption ), iChunk( NULL ), iChunkAddress( 0 ), iChunkMappingAttributes( 0 ), iClientToKernelDelta( 0 )
     {
     }
 
@@ -122,7 +248,7 @@
     iChunk = NULL;
     iChunkAddress = 0;
     iChunkMappingAttributes = 0;
-    //iClientToKernelDelta = 0;
+    iClientToKernelDelta = 0;
     }
 
 
@@ -137,13 +263,13 @@
     // Calculate start of real heap data (skipping over embedded RHeap object)
     // Since we must operate with kernel-side addressing into our cloned heap chunk,
     // we must use aAddress (the kernel address of the chunk) rather than aChunk->iBase
-    //TOMSCI iClientToKernelDelta = ( (TUint8*) aAddress ) - ( Base() - KRHeapObjectSize );
+    iClientToKernelDelta = ( (TUint8*) aAddress ) - ( Base() - KRHeapObjectSize );
 
     TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapReadFromCopy::AssociateWithKernelChunk() - END - delta between client's user-side base address (base: 0x%08x), kernel-side base address (base: 0x%08x), and kernel-side chunk (base: 0x%08x) is: 0x%08x", Base(), aChunk->iBase, aAddress, iClientToKernelDelta) );
     }
 
 
-/*void RMemSpyDriverRHeapReadFromCopy::DisassociateWithKernelChunk()
+void RMemSpyDriverRHeapReadFromCopy::DisassociateWithKernelChunk()
     {
     TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapReadFromCopy::DisassociateWithKernelChunk() - START - iChunk: 0x%08x", iChunk ) );
 
@@ -157,7 +283,7 @@
 
     TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapReadFromCopy::DisassociateWithKernelChunk() - END") );
     }
-*/
+
 
 DChunk& RMemSpyDriverRHeapReadFromCopy::Chunk()
     {
@@ -171,7 +297,7 @@
     }
 
 
-/*TLinAddr RMemSpyDriverRHeapReadFromCopy::ChunkKernelAddress() const
+TLinAddr RMemSpyDriverRHeapReadFromCopy::ChunkKernelAddress() const
     {
     return iChunkAddress;
     }
@@ -182,49 +308,118 @@
     return iChunk != NULL;
     }
 
+
 TUint RMemSpyDriverRHeapReadFromCopy::ClientToKernelDelta() const
     {
     return iClientToKernelDelta;
     }
-*/
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 
 
 
 
 
 RMemSpyDriverRHeapUser::RMemSpyDriverRHeapUser( DMemSpyDriverOSAdaption& aOSAdaption )
-	: RMemSpyDriverRHeapBase(), iOSAdaption(aOSAdaption)
+:   RMemSpyDriverRHeapReadFromCopy( aOSAdaption )
     {
     }
 
 
-TInt RMemSpyDriverRHeapUser::OpenUserHeap(DThread& aThread, TBool aEuserUdeb)
-	{
-	TLinAddr allocatorAddr = (TLinAddr)OSAdaption().DThread().GetAllocator(aThread);
-	NKern::ThreadEnterCS();
-	LtkUtils::RKernelSideAllocatorHelper* helper = new LtkUtils::RKernelSideAllocatorHelper;
-	if (!helper)
-		{
-		NKern::ThreadLeaveCS();
-		return KErrNoMemory;
-		}
-	TInt err = helper->OpenUserHeap(OSAdaption().DThread().GetId(aThread), allocatorAddr, aEuserUdeb);
-	if (!err)
-		{
-		iChunk = helper->OpenUnderlyingChunk();
-		if (!iChunk) err = KErrNotFound;
-		}
-	if (err)
-		{
-		delete helper;
-		}
-	else
-		{
-		iHelper = helper;
-		}
-	NKern::ThreadLeaveCS();
-	return err;
-	}
+TInt RMemSpyDriverRHeapUser::ReadFromUserAllocator( DThread& aThread )
+    {
+    TBuf8<KRHeapMemberDataSize> memberData;
+    memberData.SetMax();
+
+    NKern::ThreadEnterCS();
+    NKern::LockSystem();
+    RAllocator* allocator = OSAdaption().DThread().GetAllocator( aThread );
+    NKern::UnlockSystem();
+  	NKern::ThreadLeaveCS();
+
+    TUint8* memberDataAddress = (TUint8*) allocator + KRAllocatorAndRHeapMemberDataOffset;
+	TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapUser::ReadFromUserAllocator() - START - allocator addr: 0x%08x, therefore going to read %d bytes from address 0x%08x within client thread (0x%08x + %4d bytes)", allocator, KRHeapMemberDataSize, memberDataAddress, allocator, KRAllocatorAndRHeapMemberDataOffset ) );
+
+    const TInt error = Kern::ThreadRawRead( &aThread, memberDataAddress, (TAny*) memberData.Ptr(), KRHeapMemberDataSize );
+    TRACE_DATA( MemSpyDriverUtils::DataDump("%lS", memberData.Ptr(), KRHeapMemberDataSize, KRHeapMemberDataSize ) );
+
+    if  ( error == KErrNone )
+        {
+        TUint8* destinationAddress = reinterpret_cast< TUint8* >( this );
+
+        // Skip over our vTable too...
+        destinationAddress += KRAllocatorAndRHeapMemberDataOffset;
+
+        // Now copy data into this object
+        TPtr8 self( destinationAddress, KRHeapMemberDataSize, KRHeapMemberDataSize );
+        self.Copy( memberData );
+
+        PrintInfo();
+        }
+    else
+        {
+        }
+
+	TRACE_HEAP( Kern::Printf("RMemSpyDriverRHeapUser::ReadFromUserAllocator() - END - read error: %d", error ) );
+    return error;
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 
 RMemSpyDriverRHeapKernelFromCopy::RMemSpyDriverRHeapKernelFromCopy( DMemSpyDriverOSAdaption& aOSAdaption )
 :   RMemSpyDriverRHeapReadFromCopy( aOSAdaption )
@@ -253,7 +448,6 @@
     }
 
 
-/*
 void RMemSpyDriverRHeapKernelFromCopy::DisassociateWithKernelChunk()
     {
     TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelFromCopy::DisassociateWithKernelChunk() - START - iKernelHeap: 0x%08x", iKernelHeap ));
@@ -261,55 +455,93 @@
     RMemSpyDriverRHeapReadFromCopy::DisassociateWithKernelChunk();
     TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelFromCopy::DisassociateWithKernelChunk() - END") );
     }
-*/
+
 
-void RMemSpyDriverRHeapKernelFromCopy::Close()
-	{
-	//TOMSCI TODO close the chunk
-	}
+void RMemSpyDriverRHeapKernelFromCopy::GetHeapSpecificInfo( TMemSpyHeapInfo& aInfo ) const
+    {
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelFromCopy::GetHeapSpecificInfo() - START - iKernelHeap: 0x%08x", iKernelHeap ));
+    //
+    if  ( iKernelHeap )
+        {
+        const TUint32* pHeap = reinterpret_cast< TUint32* >( iKernelHeap );
+        //
+        TMemSpyHeapInfoRHeap& rHeapInfo = aInfo.AsRHeap();
+        TMemSpyHeapMetaDataRHeap& rHeapMetaData = rHeapInfo.MetaData();
+        rHeapMetaData.SetVTable( *pHeap );
+        rHeapMetaData.SetClassSize( KRHeapObjectSize );
+        //
+        TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelFromCopy::GetHeapSpecificInfo() - RHeapK vtable is: 0x%08x", *pHeap ));
+        }
+    //
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelFromCopy::GetHeapSpecificInfo() - END") );
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 
 RMemSpyDriverRHeapKernelInPlace::RMemSpyDriverRHeapKernelInPlace()
-	: iChunk(NULL)
+:   iKernelHeap( NULL ), iChunk( NULL )
     {
     }
 
-TInt RMemSpyDriverRHeapKernelInPlace::OpenKernelHeap()
-	{
-	NKern::ThreadEnterCS();
-	LtkUtils::RAllocatorHelper* helper = new LtkUtils::RAllocatorHelper;
-	if (!helper)
-		{
-		NKern::ThreadLeaveCS();
-		return KErrNoMemory;
-		}
-	TInt err = helper->OpenKernelHeap();
-	if (!err)
-		{
-		iChunk = helper->OpenUnderlyingChunk();
-		if (!iChunk) err = KErrNotFound;
-		}
+
+void RMemSpyDriverRHeapKernelInPlace::SetKernelHeap( RHeapK& aKernelHeap )
+    {
+    iKernelHeap = &aKernelHeap;
+    CopyMembersFromKernelHeap();
+    }
+
+
+void RMemSpyDriverRHeapKernelInPlace::FailNext()
+    {
+#ifndef __SYMBIAN_KERNEL_HYBRID_HEAP__
+    RMemSpyDriverRHeapKernelInPlace::RHeapKExtended* heap = reinterpret_cast< RMemSpyDriverRHeapKernelInPlace::RHeapKExtended* >( iKernelHeap );
+    heap->FailNext();
+#endif
+    }
+
 
-	if (err)
-		{
-		delete helper;
-		}
-	else
-		{
-		iHelper = helper;
-		}
-	NKern::ThreadLeaveCS();
-	return err;
-	}
+void RMemSpyDriverRHeapKernelInPlace::Reset()
+    {
+    RMemSpyDriverRHeapBase::Reset();
+	//
+    iChunk = NULL;
+    }
+
 
-void RMemSpyDriverRHeapKernelInPlace::Close()
+void RMemSpyDriverRHeapKernelInPlace::AssociateWithKernelChunk( DChunk* aChunk, TLinAddr /*aAddress*/, TUint32 /*aMappingAttributes*/ )
     {
-	NKern::ThreadEnterCS();
-	iChunk->Close(NULL);
-	iChunk = NULL;
-	RMemSpyDriverRHeapBase::Close();
-	NKern::ThreadLeaveCS();
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelInPlace::AssociateWithKernelChunk() - START - aChunk: %O, aChunk base: 0x%08x", aChunk, aChunk->iBase ) );
+    iChunk = aChunk;
     }
 
+
+void RMemSpyDriverRHeapKernelInPlace::DisassociateWithKernelChunk()
+    {
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelInPlace::DisassociateWithKernelChunk() - START - iChunk: 0x%08x", iChunk ));
+    iChunk = NULL;
+    iKernelHeap = NULL;
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelInPlace::DisassociateWithKernelChunk() - END") );
+    }
+
+
 DChunk& RMemSpyDriverRHeapKernelInPlace::Chunk()
     {
     return *iChunk;
@@ -321,3 +553,68 @@
     return *iChunk;
     }
 
+
+TLinAddr RMemSpyDriverRHeapKernelInPlace::ChunkKernelAddress() const
+    {
+    const TLinAddr ret = reinterpret_cast< TLinAddr >( iChunk->iBase );
+    return ret;
+    }
+
+
+TBool RMemSpyDriverRHeapKernelInPlace::ChunkIsInitialised() const
+    {
+    return iChunk != NULL;
+    }
+
+
+TUint RMemSpyDriverRHeapKernelInPlace::ClientToKernelDelta() const
+    {
+    // We're operating in kernel address space, there is no delta.
+    return 0;
+    }
+
+
+void RMemSpyDriverRHeapKernelInPlace::CopyMembersFromKernelHeap()
+    {
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelInPlace::CopyMembersFromKernelHeap() - START" ) );
+
+    // Perform a copy operation in order to populate base class with a duplicate of the kernel's heap info.
+    RHeapK* kernelHeap = iKernelHeap;
+
+    // Source address
+    TUint8* sourceAddress = (TUint8*) kernelHeap + KRAllocatorAndRHeapMemberDataOffset;
+    TUint8* destinationAddress = (TUint8*) this + KRAllocatorAndRHeapMemberDataOffset;
+
+    // Copy 
+    memcpy( destinationAddress, sourceAddress, KRHeapMemberDataSize );
+
+    // And print info in debug builds for verification...
+    PrintInfo();
+
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelInPlace::CopyMembersFromKernelHeap() - END" ) );
+    }
+
+
+void RMemSpyDriverRHeapKernelInPlace::GetHeapSpecificInfo( TMemSpyHeapInfo& aInfo ) const
+    {
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelInPlace::GetHeapSpecificInfo() - START - iKernelHeap: 0x%08x", iKernelHeap ));
+    //
+    if  ( iKernelHeap )
+        {
+        const TUint32* pHeap = reinterpret_cast< TUint32* >( iKernelHeap );
+        //
+        TMemSpyHeapInfoRHeap& rHeapInfo = aInfo.AsRHeap();
+        TMemSpyHeapMetaDataRHeap& rHeapMetaData = rHeapInfo.MetaData();
+        rHeapMetaData.SetVTable( *pHeap );
+        rHeapMetaData.SetClassSize( KRHeapObjectSize );
+        //
+        TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelInPlace::GetHeapSpecificInfo() - RHeapK vtable is: 0x%08x", *pHeap ));
+        }
+    //
+    TRACE_KH( Kern::Printf("RMemSpyDriverRHeapKernelInPlace::GetHeapSpecificInfo() - END") );
+    }
+
+
+
+
+
--- a/memspy/Driver/Kernel/Source/MemSpyDriverHeapWalker.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverHeapWalker.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -21,14 +21,22 @@
 #include "MemSpyDriverUtils.h"
 
 // Defines
+#define __NEXT_CELL(p)				((RMemSpyDriverRHeapBase::SCell*)(((TUint8*)p)+p->len))
 #define PRINTDEBUG( a ) { if ( PrintDebug() ) a; }
 
 
-RMemSpyDriverHeapWalker::RMemSpyDriverHeapWalker(RMemSpyDriverRHeapBase& aHeap, MMemSpyHeapWalkerObserver* aObserver)
-	: iHeap(aHeap), iPrintDebug(EFalse), iObserver(aObserver)
-	{
-	InitialiseStats();
-	}
+RMemSpyDriverHeapWalker::RMemSpyDriverHeapWalker( RMemSpyDriverRHeapBase& aHeap, TBool aDebugAllocator )
+:   iHeap( aHeap ), iIsDebugAllocator( aDebugAllocator ), iPrintDebug( EFalse ), iObserver( NULL )
+    {
+    InitialiseStats();
+    }
+
+
+RMemSpyDriverHeapWalker::RMemSpyDriverHeapWalker( RMemSpyDriverRHeapBase& aHeap, TBool aDebugAllocator, MMemSpyHeapWalkerObserver& aObserver )
+:   iHeap( aHeap ), iIsDebugAllocator( aDebugAllocator ), iPrintDebug( EFalse ), iObserver( &aObserver )
+    {
+    InitialiseStats();
+    }
 
 
 TInt RMemSpyDriverHeapWalker::Traverse()
@@ -36,7 +44,7 @@
 // Walk the heap calling the info function.
 //
 	{
-    PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - START"));
+    PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - START - delta: 0x%08x", iHeap.ClientToKernelDelta() ));
     InitialiseStats();
     if  ( iObserver )
         {
@@ -45,64 +53,135 @@
         }
 
     PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - heap walk init complete" ));
-
-	TInt err = iHeap.Helper()->Walk(&CellCallback, this);
-    FinaliseStats();
-    //PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - END - pF: 0x%08x, pC: 0x%08x, heapBase: 0x%08x, heapTop: 0x%08x", pF, pC, heapBase, heapTop));
-	return err;
-	}
+    TAny* heapBase = KernelAddress( iHeap.iBase );
+    TAny* heapTop = KernelAddress( iHeap.iTop );
+	PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - kernel-side chunk address: 0x%08x, chunkBase: 0x%08x, heapBase: 0x%08x, heapTop: 0x%08x", iHeap.ChunkKernelAddress(), iHeap.Chunk().iBase, heapBase, heapTop));
 
-TBool RMemSpyDriverHeapWalker::CellCallback(RAllocatorHelper& aHelper, TAny* aContext, RAllocatorHelper::TExtendedCellType aCellType, TLinAddr aCellAddress, TInt aLength)
-	{
-	return static_cast<RMemSpyDriverHeapWalker*>(aContext)->DoCellCallback(aHelper, aCellType, aCellAddress, aLength);
-	}
-
-TBool RMemSpyDriverHeapWalker::DoCellCallback(RAllocatorHelper& aHelper, RAllocatorHelper::TExtendedCellType aCellType, TLinAddr aCellAddress, TInt aLength)
-	{
-	TAny* cellAddress = (TAny*)aCellAddress;
-	TMemSpyDriverCellType memspyCellType = (TMemSpyDriverCellType)aCellType; // We make sure these use the same values
-	switch (aCellType)
+    TRACE_DATA( MemSpyDriverUtils::DataDump("%lS", (TUint8*) iHeap.ChunkKernelAddress(), iHeap.Chunk().iSize, iHeap.Chunk().iSize ) );
+   
+	TInt nestingLevel = 0;
+	TInt allocationNumber = 0;
+	//
+	RMemSpyDriverRHeapBase::SCell* pC = (RMemSpyDriverRHeapBase::SCell*) heapBase;		// allocated cells
+	RMemSpyDriverRHeapBase::SCell* pF = &iHeap.iFree;				            // free cells
+	PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - before while loop entry - pC: 0x%08x, pF: 0x%08x, heapBase: 0x%08x, heapTop: 0x%08x", pC, pF, heapBase, heapTop));
+    //
+    while( ( pF == &iHeap.iFree ) || ( pF >= heapBase && pF < heapTop ) )
 		{
-		case RAllocatorHelper::EHeapBadFreeCellAddress:
-			PRINTDEBUG(Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EBadFreeCellAddress: 0x%08x", cellAddress));
-			NotifyCell(memspyCellType, cellAddress, 0);
-			return EFalse;
-		case RAllocatorHelper::EHeapBadFreeCellSize:
-			PRINTDEBUG(Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EBadFreeCellSize: 0x%08x", cellAddress));
-			NotifyCell(memspyCellType, cellAddress, aLength);
-			return EFalse;
-		case RAllocatorHelper::EHeapBadAllocatedCellSize:
-			PRINTDEBUG(Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EBadAllocatedCellSize: 0x%08x", cellAddress));
-			NotifyCell(memspyCellType, cellAddress, aLength);
-			return EFalse;
-		case RAllocatorHelper::EHeapBadAllocatedCellAddress:
-			PRINTDEBUG(Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EBadAllocatedCellAddress: 0x%08x", cellAddress));
-			NotifyCell(memspyCellType, cellAddress, aLength);
-			return EFalse;
-		default:
-			break;
+        pF = (RMemSpyDriverRHeapBase::SCell*) KernelAddress( pF->next );				// next free cell
+	    PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - pC: 0x%08x, pF: 0x%08x, heapBase: 0x%08x, heapTop: 0x%08x", pC, pF, heapBase, heapTop));
+
+        if  ( pF )
+        	{
+            PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - freeCell:       0x%08x", pF ));
+
+            if  ( pF >= heapBase && pF < heapTop )
+                {
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - freeCell->next: 0x%08x", pF->next ));
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - freeCell->len:  0x%08x", pF->len ));
+                }
+            else
+                {
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - FATAL ERROR - freeCell:  0x%08x is outside heap bounds!", pF ));
+                }
+
+            PRINTDEBUG( Kern::Printf(" "));
+            }
+		
+        if  (!pF)
+            {
+            PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - next free cell address is NULL"));
+			pF = (RMemSpyDriverRHeapBase::SCell*) heapTop;		// to make size checking work
+            }
+		else if (  (TUint8*) pF < heapBase || (TUint8*) pF >= heapTop || (KernelAddress( pF->next ) && KernelAddress( pF->next ) <= pF ) )
+			{
+			// free cell pointer off the end or going backwards
+            PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EBadFreeCellAddress: 0x%08x", pF ));
+            NotifyCell( EMemSpyDriverBadFreeCellAddress, UserAddress(pF), 0 );
+			return KErrAbort;
+			}
+		else
+			{
+			TInt l = pF->len;
+			if ( l< iHeap.iMinCell || (l & (iHeap.iAlign-1)))
+				{
+				// free cell length invalid
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EBadFreeCellSize: 0x%08x", pF ));
+		        NotifyCell( EMemSpyDriverBadFreeCellSize, UserAddress(pF), l );
+			    return KErrAbort;
+				}
+			}
+
+        while ( pC != pF )				// walk allocated cells up to next free cell
+			{
+    	    if  ( pC )
+        	    {
+                // The 'next' cell field is only applicable if the cell is a 'free' cell, hence we only print the cell's
+                // address, its length, and its _calculated_ next cell (based upon address + length). Calc length is done
+                // a bit later on...
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - allocCell:       0x%08x", pC ));
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - allocCell->len:  0x%08x", pC->len ));
+                PRINTDEBUG( Kern::Printf(" "));
+                }
+            
+            TInt l = pC->len;
+			if (l<iHeap.iMinCell || (l & (iHeap.iAlign-1)))
+				{
+				// allocated cell length invalid
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EBadAllocatedCellSize: 0x%08x", pC ));
+		        NotifyCell( EMemSpyDriverBadAllocatedCellSize, UserAddress(pC), l );
+			    return KErrAbort;
+				}
+
+            // ALLOCATED CELL
+            if  ( iIsDebugAllocator )
+                {
+                RMemSpyDriverRHeapBase::SDebugCell* debugCell = (RMemSpyDriverRHeapBase::SDebugCell*) pC;
+                nestingLevel = debugCell->nestingLevel;
+                allocationNumber = debugCell->allocCount;
+                }
+
+            PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EGoodAllocatedCell: 0x%08x", pC ));
+	        if  ( NotifyCell( EMemSpyDriverGoodAllocatedCell, UserAddress(pC), l, nestingLevel, allocationNumber ) == EFalse )
+                {
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - END1 - KErrAbort on NotifyCell..."));
+			    return KErrAbort;
+                }
+
+			RMemSpyDriverRHeapBase::SCell* pN = (RMemSpyDriverRHeapBase::SCell*) __NEXT_CELL( pC );
+            PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - allocCell next:  0x%08x", pN ));
+			if (pN > pF)
+				{
+				// cell overlaps next free cell
+                PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EBadAllocatedCellAddress: 0x%08x", pC ));
+		        NotifyCell( EMemSpyDriverBadAllocatedCellAddress, UserAddress(pC), l );
+			    return KErrAbort;
+				}
+
+            pC = pN;
+			}
+
+        PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - freeCell before exit check is: 0x%08x", pF ));
+        if  ((TUint8*) pF >= heapTop )
+            {
+            PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - freeCell reached top of heap -> done"));
+			break;		// reached end of heap
+            }
+		
+        pC = (RMemSpyDriverRHeapBase::SCell*) __NEXT_CELL(pF);	// step to next allocated cell
+
+        // FREE CELL
+        PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EGoodFreeCell: 0x%08x", pF ));
+        if  ( NotifyCell( EMemSpyDriverGoodFreeCell, UserAddress(pF), pF->len ) == EFalse )
+            {
+            PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - END2 - KErrAbort on NotifyCell..."));
+			return KErrAbort;
+            }
 		}
 
-	if (aCellType & RAllocatorHelper::EAllocationMask)
-		{
-		PRINTDEBUG(Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EGoodAllocatedCell: 0x%08x", cellAddress));
-		TInt nestingLevel = -1;
-		aHelper.GetCellNestingLevel(cellAddress, nestingLevel);
-		TInt allocCount = aHelper.AllocCountForCell(cellAddress);
-		if (allocCount < 0) allocCount = -1; // This is what NotifyCell expects
-		return NotifyCell(memspyCellType, cellAddress, aLength, nestingLevel, allocCount);
-		}
-	else if (aCellType & RAllocatorHelper::EFreeMask)
-		{
-		PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - EGoodFreeCell: 0x%08x", cellAddress));
-		return NotifyCell(memspyCellType, cellAddress, aLength);
-		}
-	else if (aCellType & RAllocatorHelper::EBadnessMask)
-		{
-		NotifyCell(memspyCellType, cellAddress, aLength);
-		return EFalse;
-		}
-	return ETrue; // For any new types that get added
+    FinaliseStats();
+    PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::Traverse() - END - pF: 0x%08x, pC: 0x%08x, heapBase: 0x%08x, heapTop: 0x%08x", pF, pC, heapBase, heapTop));
+    return KErrNone;
 	}
 
 
@@ -140,7 +219,9 @@
     alloc.SetLargestCellAddress( (TAny*) iStats.iLargestCellAddressAlloc );
     alloc.SetLargestCellSize( iStats.iLargestCellSizeAlloc );
 
-	aStats.iCommittedFreeSpace = iHeap.Helper()->CommittedFreeSpace();
+    // Copy common info
+    TMemSpyHeapStatisticsRHeapCommon& common = aStats.StatsCommon();
+    common.SetTotalCellCount( iStats.iNumberOfWalkedCells );
 
 	PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::CopyStatsTo() - END"));
     }
@@ -152,6 +233,56 @@
     iObserver = aObserver;
     }
 
+
+TAny* RMemSpyDriverHeapWalker::KernelAddress( TAny* aUserAddress, TUint aDelta )
+    {
+    TAny* ret = NULL;
+    //
+    if  ( aUserAddress )
+        {
+	    TRACE_HEAP( Kern::Printf("RMemSpyDriverHeapWalker::KernelAddress() - aUserAddress: 0x%08x", aUserAddress));
+        ret = (TUint8*) aUserAddress + aDelta;
+        }
+    //
+	TRACE_HEAP( Kern::Printf("RMemSpyDriverHeapWalker::KernelAddress() - ret: 0x%08x", ret));
+    return ret;
+    }
+
+ 
+TAny* RMemSpyDriverHeapWalker::UserAddress( TAny* aKernelAddress, TUint aDelta )
+    {
+    TAny* ret = NULL;
+    //
+    if  ( aKernelAddress )
+        {
+	    TRACE_HEAP( Kern::Printf("RMemSpyDriverHeapWalker::UserAddress() - aKernelAddress: 0x%08x", aKernelAddress));
+        ret = (TUint8*) aKernelAddress - aDelta;
+        }
+    //
+	TRACE_HEAP( Kern::Printf("RMemSpyDriverHeapWalker::UserAddress() - ret: 0x%08x", ret));
+    return ret;
+    }
+
+
+TAny* RMemSpyDriverHeapWalker::KernelAddress( TAny* aUserAddress) const
+    {
+    return KernelAddress( aUserAddress, iHeap.ClientToKernelDelta() );
+    }
+
+
+TAny* RMemSpyDriverHeapWalker::UserAddress( TAny* aKernelAddress ) const
+    {
+    return UserAddress( aKernelAddress, iHeap.ClientToKernelDelta() );
+    }
+
+
+RMemSpyDriverRHeapBase::SCell* RMemSpyDriverHeapWalker::CellByUserAddress( TAny* aAddress, TUint aDelta )
+    {
+    RMemSpyDriverRHeapBase::SCell* ret = (RMemSpyDriverRHeapBase::SCell*) KernelAddress( aAddress, aDelta );
+    return ret;
+    }
+
+
 TBool RMemSpyDriverHeapWalker::NotifyCell( TMemSpyDriverCellType aType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber )
     {
     // Update stats first
@@ -170,9 +301,32 @@
 
 void RMemSpyDriverHeapWalker::UpdateStats( TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber )
     {
-    PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::UpdateStats - type: %d address: 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", aCellType, aCellAddress, aLength, aNestingLevel, aAllocNumber ));
+    switch( aCellType )
+        {
+    case EMemSpyDriverGoodAllocatedCell:
+        PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::UpdateStats - EGoodAllocatedCell       - 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", aCellAddress, aLength, aNestingLevel, aAllocNumber ));
+        break;
+    case EMemSpyDriverGoodFreeCell:
+        PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::UpdateStats - EGoodFreeCell            - 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", aCellAddress, aLength, aNestingLevel, aAllocNumber ));
+        break;
+    case EMemSpyDriverBadAllocatedCellSize:
+        Kern::Printf("RMemSpyDriverHeapWalker::UpdateStats - EBadAllocatedCellSize    - 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", aCellAddress, aLength, aNestingLevel, aAllocNumber );
+        break;
+    case EMemSpyDriverBadAllocatedCellAddress:
+        Kern::Printf("RMemSpyDriverHeapWalker::UpdateStats - EBadAllocatedCellAddress - 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", aCellAddress, aLength, aNestingLevel, aAllocNumber );
+        break;
+    case EMemSpyDriverBadFreeCellAddress:
+        Kern::Printf("RMemSpyDriverHeapWalker::UpdateStats - EBadFreeCellAddress      - 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", aCellAddress, aLength, aNestingLevel, aAllocNumber );
+        break;
+    case EMemSpyDriverBadFreeCellSize:
+        Kern::Printf("RMemSpyDriverHeapWalker::UpdateStats - EBadFreeCellSize         - 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", aCellAddress, aLength, aNestingLevel, aAllocNumber );
+        break;
+    default:
+        Kern::Printf("RMemSpyDriverHeapWalker::UpdateStats - UHANDLED TYPE!           - 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d, type: %d", aCellAddress, aLength, aNestingLevel, aAllocNumber, aCellType );
+        break;
+        }
 
-    if (aCellType & EMemSpyDriverFreeCellMask)
+    if  ( aCellType == EMemSpyDriverGoodFreeCell )
         {
         // Update checksum
         iStats.iFreeCellCRC = iStats.iFreeCellCRC ^ reinterpret_cast<TUint32>( aCellAddress );
@@ -201,7 +355,7 @@
             iStats.iFirstFreeCellAddress = (TLinAddr) aCellAddress;
             }
         }
-    else if (aCellType & EMemSpyDriverAllocatedCellMask)
+    else if ( aCellType == EMemSpyDriverGoodAllocatedCell )
         {
         // Track cell counts and length
         ++iStats.iAllocCellCount;
@@ -218,10 +372,14 @@
             iStats.iLargestCellAddressAlloc = (TLinAddr) aCellAddress;
             }
         }
+    else
+        {
+        iStats.iLastFreeCellLength = aLength;
+        }
 
     iStats.iLastCellType = aCellType;
     iStats.iLastCellAddress = (TLinAddr) aCellAddress;
-    iStats.iLastCellWasFreeCell = (aCellType & EMemSpyDriverFreeCellMask);
+    iStats.iLastCellWasFreeCell = ( aCellType == EMemSpyDriverGoodFreeCell );
     ++iStats.iNumberOfWalkedCells;
     }
 
@@ -232,7 +390,7 @@
     iStats.iNumberOfWalkedCells = 0;
     iStats.iFirstFreeCellAddress = 0;
     iStats.iFirstFreeCellLength = 0;
-    iStats.iLastCellType = EMemSpyDriverAllocatedCellMask;
+    iStats.iLastCellType = EMemSpyDriverGoodAllocatedCell;
     iStats.iLastCellWasFreeCell = EFalse;
     iStats.iLastFreeCellLength = 0;
     iStats.iTotalFreeSpace = 0;
@@ -248,6 +406,10 @@
     iStats.iLargestCellAddressFreePrevious = 0;
     iStats.iSpackSpaceCellAddress = 0;
     iStats.iLastCellAddress = 0;
+
+    // These two can be identified up front
+    iStats.iFreeCellOverheadHeaderLength = RMemSpyDriverRHeapBase::FreeCellHeaderSize();
+    iStats.iAllocCellOverheadHeaderLength = RMemSpyDriverRHeapBase::AllocatedCellHeaderSize( iIsDebugAllocator );
     }
 
 
@@ -285,3 +447,4 @@
     PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::PrintStats - iLargestCellAddressAlloc     : 0x%08x", iStats.iLargestCellAddressAlloc ) );
     PRINTDEBUG( Kern::Printf("RMemSpyDriverHeapWalker::PrintStats - iFreeCellCRC                 : 0x%08x", iStats.iFreeCellCRC ) );
     }
+
--- a/memspy/Driver/Kernel/Source/MemSpyDriverInspectedProcess.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverInspectedProcess.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -78,7 +78,6 @@
 
 TInt DMemSpyInspectedProcess::Open( DProcess* aProcess )
     {
-	__ASSERT_CRITICAL;
     TRACE( Kern::Printf("DMemSpyInspectedProcess::Open() - START - this: 0x%08x, aProcess: 0x%08x (%O)", this, aProcess, aProcess ));
 
     TInt error = KErrNone;
@@ -129,7 +128,7 @@
 
 TInt DMemSpyInspectedProcess::NotifyOnChange( DThread* aThread, TRequestStatus* aRequestStatus, TMemSpyDriverProcessInspectionInfo* aInfo )
     {
-	Lock();
+	Kern::MutexWait( *iLock );
 
     TInt err = KErrInUse;
     const TBool notificationQueued = NotifyOnChangeQueued();
@@ -159,7 +158,9 @@
 			CompleteClientsRequest( KErrNone, &cachedChange->iInfo );
 			
 			// Discard cached entry
+            NKern::ThreadEnterCS();
 			delete cachedChange;
+            NKern::ThreadLeaveCS();
 			}
         else if ( iAmDead )
             {
@@ -173,14 +174,14 @@
 	//
     TRACE( Kern::Printf("DMemSpyInspectedProcess::NotifyOnChange() - END - this: 0x%08x, err: %d", this, err ) );
 
-	Unlock();
+	Kern::MutexSignal( *iLock );
     return err;
     }
 
 
 TInt DMemSpyInspectedProcess::NotifyOnChangeCancel()
     {
-	Lock();
+	Kern::MutexWait( *iLock );
     TRACE( Kern::Printf("DMemSpyInspectedProcess::NotifyOnChangeCancel() - START - this: 0x%08x, queued: %d, iChangeObserverThread: 0x%08x, iChangeObserverRS: 0x%08x", this, NotifyOnChangeQueued(), iChangeObserverThread, iChangeObserverRS ) );
     //
     if  ( NotifyOnChangeQueued() )
@@ -193,7 +194,7 @@
         }
 	//
     TRACE( Kern::Printf("DMemSpyInspectedProcess::NotifyOnChangeCancel() - END - this: 0x%08x", this ) );
-	Unlock();
+	Kern::MutexSignal( *iLock );
 
     return KErrNone;
     }
@@ -203,9 +204,9 @@
     {
     TRACE( Kern::Printf("DMemSpyInspectedProcess::NotifyOnChangeQueued() - START - this: 0x%08x", this ) );
     //
-	Lock();
+	Kern::MutexWait( *iLock );
     const TBool queued = ( iChangeObserverRS != NULL );
-	Unlock();
+	Kern::MutexSignal( *iLock );
     //
     TRACE( Kern::Printf("DMemSpyInspectedProcess::NotifyOnChangeQueued() - END - this: 0x%08x, queued: %d", this, queued ) );
     return queued;
@@ -448,9 +449,10 @@
     const TUint procId = iDevice.OSAdaption().DProcess().GetId( aProcess );
     if  ( procId == iProcessId )
         {
-	    Lock();
+	    Kern::MutexWait( *iLock );
 
         TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleProcessUpdated() - START - this: 0x%08x, iProcess: 0x%08x (%O)", this, iProcess, iProcess ) );
+	    NKern::ThreadEnterCS();
 
         // Mark all tracked chunks as dirty whilst we work out
         // what is and isn't mapped into the process
@@ -474,9 +476,10 @@
             CompleteClientsRequest( KErrNone, &iInfoCurrent );
             }
 
+        NKern::ThreadLeaveCS();
         TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleProcessUpdated() - END - this: 0x%08x", this ) );
 
-        Unlock();
+        Kern::MutexSignal( *iLock );
         }
     }
 
@@ -488,9 +491,10 @@
 
     if  ( pid == iProcessId )
         {
-	    Lock();
+	    Kern::MutexWait( *iLock );
 
         TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleProcessRemoved() - START - this: 0x%08x", this ) );
+	    NKern::ThreadEnterCS();
 
         // We will implement a multi phased approach to the process being removed.
         //
@@ -525,9 +529,10 @@
         // Stop listening to events since we've drained everything now...
         iAmDead = ETrue;
 
+        NKern::ThreadLeaveCS();
         TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleProcessRemoved() - END - this: 0x%08x", this ) );
 
-        Unlock();
+        Kern::MutexSignal( *iLock );
         }
     }
 
@@ -595,7 +600,7 @@
 
 void DMemSpyInspectedProcess::EMHandleThreadChanged( DThread& /*aThread*/ )
     {
-	Lock();
+	Kern::MutexWait( *iLock );
 
     TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleThreadChanged() - START - this: 0x%08x", this ) );
 
@@ -603,6 +608,7 @@
     // We must be careful to only access the members of aThread that still
     // exist as if it is being destroyed, the object may be in an intermediate
     // state.
+	NKern::ThreadEnterCS();
 
     // All we are really interested in is recalculating the stack usage
     // for the process... 
@@ -611,17 +617,19 @@
     // Always inform observer about new results.
     CompleteClientsRequest( KErrNone, &iInfoCurrent );
 
+    NKern::ThreadLeaveCS();
     TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleThreadChanged() - END - this: 0x%08x", this ) );
 
-    Unlock();
+    Kern::MutexSignal( *iLock );
     }
 
 
 void DMemSpyInspectedProcess::EMHandleChunkAdd( DChunk& aChunk )
     {
-	Lock();
+	Kern::MutexWait( *iLock );
 
     TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleChunkAdd() - START - this: 0x%08x, aChunk: 0x%08x (%O)", this, &aChunk, &aChunk ) );
+	NKern::ThreadEnterCS();
 
     // Is this chunk related to our process somehow?
     if  ( IsChunkRelevantToOurProcess( aChunk ) )
@@ -648,17 +656,19 @@
             }
         }
 
+    NKern::ThreadLeaveCS();
     TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleChunkAdd() - END - this: 0x%08x", this ) );
 
-    Unlock();
+    Kern::MutexSignal( *iLock );
     }
 
 
 void DMemSpyInspectedProcess::EMHandleChunkUpdated( DChunk& aChunk )
     {
-	Lock();
+	Kern::MutexWait( *iLock );
 
     TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleChunkUpdated() - START - this: 0x%08x, aChunk: 0x%08x [S: %8d] (%O)", this, &aChunk, aChunk.Size(), &aChunk ) );
+	NKern::ThreadEnterCS();
 
     // Is this chunk mapped into our process?
     TMemSpyTrackedChunk* trackedEntry = TrackedChunkByHandle( &aChunk );
@@ -702,17 +712,19 @@
             }
         }
 
+    NKern::ThreadLeaveCS();
     TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleChunkUpdated() - END - this: 0x%08x", this ) );
 
-    Unlock();
+    Kern::MutexSignal( *iLock );
     }
 
 
 void DMemSpyInspectedProcess::EMHandleChunkDeleted( DChunk& aChunk )
     {
-	Lock();
+	Kern::MutexWait( *iLock );
 
     TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleChunkDeleted() - START - this: 0x%08x", this ) );
+	NKern::ThreadEnterCS();
 
     // Is this chunk mapped into our process?
     TMemSpyTrackedChunk* trackedEntry = TrackedChunkByHandle( &aChunk );
@@ -730,9 +742,10 @@
             }
         }
 
+    NKern::ThreadLeaveCS();
     TRACE( Kern::Printf("DMemSpyInspectedProcess::EMHandleChunkDeleted() - END - this: 0x%08x", this ) );
 
-    Unlock();
+    Kern::MutexSignal( *iLock );
     }
 
 
@@ -871,7 +884,6 @@
         TRACE( Kern::Printf("DMemSpyInspectedProcess::IsHeapChunk() - firstThread: 0x%08x (%O)", firstThread, firstThread ) );
         if  ( firstThread != NULL )
             {
-			NKern::ThreadEnterCS();
             TInt err = firstThread->Open();
             TRACE( Kern::Printf("DMemSpyInspectedProcess::IsHeapChunk() - firstThread open result: %d", err ) );
 
@@ -900,7 +912,6 @@
                 TRACE( Kern::Printf("DMemSpyInspectedProcess::IsHeapChunk() - closing first thread..." ) );
             	Kern::SafeClose( (DObject*&) firstThread, NULL );
                 }
-			NKern::ThreadLeaveCS();
             }
         }
     //
@@ -1105,7 +1116,6 @@
 
 void DMemSpyInspectedProcess::FindChunks( DProcess& aProcess )
     {
-	__ASSERT_CRITICAL;
     TRACE( Kern::Printf("DMemSpyInspectedProcess::FindChunks() - START - this: 0x%08x", this ) );
   
     DMemSpyDriverOSAdaptionDChunk& chunkAdaption = iDevice.OSAdaption().DChunk();
@@ -1115,11 +1125,9 @@
     if  ( processAdaption.IsHandleIndexValid( aProcess ) )
         {
 	    MemSpyObjectIx* processHandles = processAdaption.GetHandles( aProcess );
-		
-		MemSpyObjectIx_HandleLookupLock();
+        MemSpyObjectIx_Wait( processHandles );
+
         const TInt count = processHandles->Count();
-		MemSpyObjectIx_HandleLookupUnlock();
-
         TRACE( Kern::Printf("DMemSpyInspectedProcess::FindChunks() - got: %d handles...", count ) );
 
 	    for( TInt i=0; i<count; i++ )
@@ -1127,11 +1135,9 @@
             TRACE( Kern::Printf("DMemSpyInspectedProcess::FindChunks() - checking handle index: %2d", i ) );
 
     	    // Get a handle from the process container...
-            MemSpyObjectIx_HandleLookupLock();
-			if (i >= processHandles->Count()) break; // Count may have changed in the meantime
+            NKern::LockSystem();
     	    DObject* object = (*processHandles)[ i ];
-			if (object && object->Open() != KErrNone) object = NULL;
-			MemSpyObjectIx_HandleLookupUnlock();
+            NKern::UnlockSystem();
 
             const TObjectType objectType = ( object ? chunkAdaption.GetObjectType( *object ) : EObjectTypeAny );
             TRACE( Kern::Printf("DMemSpyInspectedProcess::FindChunks() - object: 0x%08x, type: %2d (%O)", object, objectType, object ) );
@@ -1173,8 +1179,9 @@
                         }
                     }
                 }
-			if (object) object->Close(NULL);
     	    }
+
+        MemSpyObjectIx_Signal( processHandles );
         }
 
     TRACE( Kern::Printf("DMemSpyInspectedProcess::FindChunks() - END - this: 0x%08x", this ) );
@@ -1228,17 +1235,6 @@
     }
 
 
-void DMemSpyInspectedProcess::Lock() const
-	{
-	NKern::ThreadEnterCS();
-	Kern::MutexWait(*iLock);
-	}
-
-void DMemSpyInspectedProcess::Unlock() const
-	{
-	Kern::MutexSignal(*iLock);
-	NKern::ThreadLeaveCS();
-	}
 
 
 
--- a/memspy/Driver/Kernel/Source/MemSpyDriverLogicalChannel.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverLogicalChannel.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -51,10 +51,10 @@
 
     NKern::ThreadEnterCS();
     SubChannelsDestroy();
+    NKern::ThreadLeaveCS();
 
     TRACE( Kern::Printf("DMemSpyDriverLogicalChannel::~DMemSpyDriverLogicalChannel() - closing client thread..."));
     Kern::SafeClose( (DObject*&) iClientThread, NULL );
-    NKern::ThreadLeaveCS();
 
     TRACE( Kern::Printf("DMemSpyDriverLogicalChannel::~DMemSpyDriverLogicalChannel() - calling device to cleanup..."));
     MemSpyDevice().Cleanup();
--- a/memspy/Driver/Kernel/Source/MemSpyDriverOSAdaption.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverOSAdaption.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -22,18 +22,28 @@
 #include <nk_plat.h>
 
 #ifdef __MARM__
+
 #include <arm.h>
+// Necessary when accessing data members by steam via offsets in order
+// to prevent potential unaligned data aborts
+
+#ifdef __CC_ARM
+#define UNALIGNED_DATA_MEMBER __packed
+#endif /* __CC_ARM */
+
+#endif /* __MARM__ */
+
+#ifndef UNALIGNED_DATA_MEMBER
+#define UNALIGNED_DATA_MEMBER
 #endif
 
-// I've removed UNALIGNED_DATA_MEMBER in preference for just using memcpy to get round the potential unaligned access. -TomS
-
 // User includes
 #include "MemSpyDriverLog.h"
 #include "MemSpyDriverPAndS.h"
 #include "MemSpyDriverDevice.h"
 
 // Internal constants
-const TInt KMemSpyLocalThreadDataSizeEstimate = 0x80; // The amount of user stack that MemSpy attempts to scan for the RHeap vTable
+const TInt KMemSpyLocalThreadDataSizeEstimate = 0x80; // The amount of user stack that MemSpy attempts to scan for the RHeaep vTable
 
 
 
@@ -154,9 +164,10 @@
     {
     DThread* dThread = &aObject;
     TUint32 pTarget = reinterpret_cast<TUint32>( dThread ) + iOffset_ExitType;
-	TUint8 exitType = *reinterpret_cast<TUint8*>(pTarget);
-    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetExitType() - aObject: 0x%08x, ret: %d", &aObject, (TInt)exitType ) );
-    return (TExitType)exitType;
+    UNALIGNED_DATA_MEMBER TExitType* pRet = reinterpret_cast< TExitType* >( pTarget );
+    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetExitType() - aObject: 0x%08x, ret: 0x%08x", &aObject, pRet ) );
+    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetExitType() - value: %d", *pRet ) );
+    return *pRet;
     }
 
 
@@ -164,11 +175,10 @@
     {
     DThread* dThread = &aObject;
     TUint32 pTarget = reinterpret_cast<TUint32>( dThread ) + iOffset_SupervisorStackBase;
-
-	TUint32 ret;
-	memcpy(&ret, (const TAny*)pTarget, sizeof(TUint32));
-    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetSupervisorStackBase() - aObject: 0x%08x, ret: 0x%08x", &aObject, ret ) );
-    return ret;
+    UNALIGNED_DATA_MEMBER TUint32* pRet = reinterpret_cast< TUint32* >( pTarget );
+    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetSupervisorStackBase() - aObject: 0x%08x, ret: 0x%08x", &aObject, pRet ) );
+    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetSupervisorStackBase() - 0x%08x: %d", *pRet ) );
+    return *pRet;
     }
 
 
@@ -176,11 +186,10 @@
     {
     DThread* dThread = &aObject;
     TUint32 pTarget = reinterpret_cast<TUint32>( dThread ) + iOffset_SupervisorStackSize;
-	
-	TInt ret;
-	memcpy(&ret, (const TAny*)pTarget, sizeof(TInt));
-    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetSupervisorStackSize() - aObject: 0x%08x, ret: %d", &aObject, ret ) );
-    return ret;
+    UNALIGNED_DATA_MEMBER TInt* pRet = reinterpret_cast< TInt* >( pTarget );
+    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetSupervisorStackSize() - aObject: 0x%08x, ret: 0x%08x", &aObject, pRet ) );
+    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetSupervisorStackSize() - value: %d", *pRet ) );
+    return *pRet;
     }
 
 
@@ -202,7 +211,6 @@
     }
 
 
-// TODO try to rework this without inspecting the stack!
 CActiveScheduler* DMemSpyDriverOSAdaptionDThread::GetActiveScheduler( DThread& aObject ) const
     {
     TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetActiveScheduler() - START" ) );
@@ -326,19 +334,18 @@
         }
     }
 
-// TODO re-work this without inspecting the stack.
-// In particular we can get the allocator from the DThread object's iAllocator object
-RAllocator* DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress( DThread& aThread, TUint32& aStackAddress ) const
+
+RAllocator* DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress( DThread& aObject, TUint32& aStackAddress ) const
     {
-    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress() - START for aThread 0x%08x with ID %d", &aThread, aThread.iId ) );
+    TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress() - START" ) );
     //
     aStackAddress = 0;
     RAllocator* ret = NULL;
 
     // We will assume the thread is running and that the user-side stack has been set up
     // accordingly.
-    const TUint32 base = GetUserStackBase( aThread );
-    const TInt size = GetUserStackSize( aThread );
+    const TUint32 base = GetUserStackBase( aObject );
+    const TInt size = GetUserStackSize( aObject );
     TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress() - base: 0x%08x, size: %d, KMemSpyLocalThreadDataSizeEstimate: %d", base, size, KMemSpyLocalThreadDataSizeEstimate ) );
     const TUint32 top = base + size;
 
@@ -356,20 +363,12 @@
         //
         TUint32* ptr = reinterpret_cast< TUint32* >( addr );
         //
-        r = Kern::ThreadRawRead( &aThread, ptr, &value, sizeof( value ) );
+        r = Kern::ThreadRawRead( &aObject, ptr, &value, sizeof( value ) );
         if  ( r == KErrNone )
             {
-            r = Kern::ThreadRawRead( &aThread, reinterpret_cast< const TAny* >( value ), &possibleVTable, sizeof( possibleVTable ) );
+            Kern::ThreadRawRead( &aObject, reinterpret_cast< const TAny* >( value ), &possibleVTable, sizeof( possibleVTable ) );
             }
-
-        if ( r == KErrNone )
-            {
-            TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress() - stack[0x%08x] 0x%08x, vTable: 0x%08x (offset: %04d)", addr, value, possibleVTable, top - addr ) );
-            }
-        else
-            {
-            TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress() - stack[0x%08x] 0x%08x, (offset: %04d) read failed: %d", addr, value, top - addr, r ) );
-            }
+        TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress() - stack[0x%08x] 0x%08x, vTable: 0x%08x (offset: %04d)", addr, value, possibleVTable, top - addr ) );
         }
 #endif
 
@@ -380,7 +379,7 @@
         //
         TUint32* ptr = reinterpret_cast< TUint32* >( addr );
         //
-        r = Kern::ThreadRawRead( &aThread, ptr, &value, sizeof( value ) );
+        r = Kern::ThreadRawRead( &aObject, ptr, &value, sizeof( value ) );
         TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress() - read from: 0x%08x, result: %d, value: 0x%08x", addr, r, value ) );
         //
         if  ( r == KErrNone )
@@ -389,7 +388,7 @@
             // the TLD class holds an RAllocator* and we need to ascertain the vTable of the RAllocator* matches the
             // only supported vTable that MemSpy understands (RHeap*).
             TUint32 possibleVTable = 0;
-            r = Kern::ThreadRawRead( &aThread, reinterpret_cast< const TAny* >( value ), &possibleVTable, sizeof( possibleVTable ) );
+            r = Kern::ThreadRawRead( &aObject, reinterpret_cast< const TAny* >( value ), &possibleVTable, sizeof( possibleVTable ) );
             TRACE( Kern::Printf( "DMemSpyDriverOSAdaptionDThread::GetAllocatorAndStackAddress() - possible vtable read from: 0x%08x, result: %d, possibleVTable: 0x%08x", value, r, possibleVTable ) );
             if  ( r == KErrNone && possibleVTable == rHeapVTable )
                 {
@@ -449,23 +448,9 @@
     }
 
 
-DThread* DMemSpyDriverOSAdaptionDProcess::OpenFirstThread( DProcess& aProcess ) const
+DThread* DMemSpyDriverOSAdaptionDProcess::GetFirstThread( DProcess& aObject ) const
     {
-	// It appears that the system lock needs to be held while manipulating the iThreadQ
-	DThread* result = NULL;
-	NKern::LockSystem();
-	// We don't use DProcess::FirstThread() as that doesn't appear to do any checking of whether the list is empty, ie if there are no threads at all
-	SDblQueLink* threadLink = aProcess.iThreadQ.First();
-	if (threadLink != NULL && threadLink != &aProcess.iThreadQ.iA)
-		{
-		result = _LOFF(threadLink,DThread,iProcessLink);
-		if (result->Open() != KErrNone)
-			{
-			result = NULL;
-			}
-		}
-	NKern::UnlockSystem();
-    return result;
+    return aObject.FirstThread();
     }
 
 
@@ -560,11 +545,6 @@
     return (TUint8*)aObject.iDataBssStackChunk;
     }
 
-TBool DMemSpyDriverOSAdaptionDProcess::IsKernProcess(DProcess& aProcess) const
-	{
-	// The kernel process always has pid 1
-	return GetId(aProcess) == 1;
-	}
 
 
 
@@ -586,32 +566,9 @@
     }
 
 
-TUint8* DMemSpyDriverOSAdaptionDChunk::GetBase( DChunk& aChunk ) const
+TUint8* DMemSpyDriverOSAdaptionDChunk::GetBase( DChunk& aObject ) const
     {
-    TUint8* base = aChunk.Base();
-	if (base == 0)
-		{
-		// Under flexible memory model, DChunk::Base() will return NULL (for non-fixed chunks anyway, and that means most of them)
-		// A more useful thing to return is the base address in the owning process
-		DProcess* proc = GetOwningProcess(aChunk);
-		NKern::ThreadEnterCS();
-		if (proc && proc->Open() == KErrNone)
-			{
-			// Probably shouldn't call ChunkUserBase for a non-user-owned chunk
-			if (!OSAdaption().DProcess().IsKernProcess(*proc))
-				{
-				DThread* firstThread = OSAdaption().DProcess().OpenFirstThread(*proc);
-				if (firstThread)
-					{
-					base = Kern::ChunkUserBase(&aChunk, firstThread);
-					firstThread->Close(NULL);
-					}
-				}
-			proc->Close(NULL);
-			}
-		NKern::ThreadLeaveCS();
-		}
-	return base; 
+    return aObject.Base();
     }
 
 
--- a/memspy/Driver/Kernel/Source/MemSpyDriverObjectIx.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverObjectIx.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -55,30 +55,6 @@
 	{ Kern::Fault("DOBJECT",aPanic); }
 	
 
-TBool MemSpyObjectIx::Find(DObject* aObj)
-	{
-	//Check preconditions(debug build only)
-	__ASSERT_CRITICAL;
-	__ASSERT_NO_FAST_MUTEX;
-
-	// I don't like the implementation of At() that was here before, it wasn't safe at all without HandleMutex. So I'm replacing it with a simpler
-	// version based on operator[] that only does what we need and does it safely.
-
-	TBool found = EFalse;
-	MemSpyObjectIx_HandleLookupLock();
-	const TInt count = Count();
-	for (TInt i = 0; i < count; i++)
-		{
-		if ((*this)[i] == aObj)
-			{
-			found = ETrue;
-			break;
-			}
-		}
-	MemSpyObjectIx_HandleLookupUnlock();
-	return found;
-	}
-
 #if MCL_ROBJECTIX_DUPLICATION
 
 #define asserta(x)	do { if (!(x)) { __crash(); } } while(0)
@@ -89,18 +65,17 @@
     }
 
 
-/*
 void RMemSpyObjectIx::Wait()
 	{
-	Kern::MutexWait(*HandleMutex);
+//	Kern::MutexWait(*HandleMutex);
 	} // RObjectIx::Wait
 
 
 void RMemSpyObjectIx::Signal()
 	{
-	Kern::MutexSignal(*HandleMutex);
+//	Kern::MutexSignal(*HandleMutex);
 	} // RObjectIx::Signal
-*/
+
 
 DObject* RMemSpyObjectIx::operator[](TInt aIndex)
 	{
@@ -114,19 +89,73 @@
 	} // RObjectIx::operator[]
 
 
+TInt RMemSpyObjectIx::At(DObject* aObj)
+	{
+	//Check preconditions(debug build only)
+	__ASSERT_CRITICAL;
+	__ASSERT_NO_FAST_MUTEX;
+	//__ASSERT_MUTEX(HandleMutex);
+
+	if (iState==ETerminated)
+		{
+		return KErrNotFound;
+		}
+
+	TInt h = KErrNotFound;
+	AcquireWriteLock();
+	iState = (TUint8)ESearching;		// enable monitoring of new handles
+	iModList.iMonitor.iObj = aObj;		// object to check for
+	iModList.iMonitor.iBoundary = 0;	// will change if aObj is added to a slot before this point
+	TInt pos = 0;
+	while (pos<iCount && iActiveCount)	// stop if index empty
+		{
+		TInt limit = pos + EMaxLockedIter;
+		if (limit>iCount)
+			{
+			limit = iCount;
+			}
+		while (pos<limit)
+			{
+			SSlot* slot = iSlots + pos;
+			if (Occupant(slot) == aObj)
+				{
+				// found it, finish
+				h = MakeHandle(pos, slot->iUsed.iAttr);
+				break;
+				}
+			pos++;
+			}
+		if (h>0)
+			{
+			break;	// found it, finish
+			}
+		iModList.iMonitor.iBoundary = pos;	// will change if aObj is added to a slot already checked
+		ReleaseWriteLock();	// let other threads in
+		AcquireWriteLock();
+		pos = iModList.iMonitor.iBoundary;	// next position to check
+		}
+	iState = (TUint8)ENormal;
+	ReleaseWriteLock();
+	return h;
+	} // RObjectIx::At
+
+
+
+
+
+
 #elif MCL_DOBJECTIX_DUPLICATION
 
-/*
-void DMemSpyObjectIx::Wait( DMemSpyObjectIx* aObjectIndex )
+void DMemSpyObjectIx::Wait( DMemSpyObjectIx* /*aObjectIndex*/ )
 	{
 //	Kern::MutexWait(*aObjectIndex->HandleMutex);
 	}
 
-void DMemSpyObjectIx::Signal( DMemSpyObjectIx* aObjectIndex )
+void DMemSpyObjectIx::Signal( DMemSpyObjectIx* /*aObjectIndex*/ )
 	{
 //	Kern::MutexSignal(*aObjectIndex->HandleMutex);
 	}
-*/
+
 
 /** Counts the number of times an object appears in this index.
 
@@ -208,6 +237,42 @@
 	return pS->obj;
 	}
 
+
+
+/**	Looks up an object in the index by object pointer.
+
+	Returns a handle to the object.
+
+	@param	aObj	Pointer to the object to look up.
+	
+	@return	Handle to object (always >0);
+	        KErrNotFound, if object not present in index.
+
+    @pre    Calling thread must be in a critical section.
+    @pre    No fast mutex can be held.
+	@pre	Call in a thread context.
+	@pre	DObject::HandleMutex held.
+ */
+TInt DMemSpyObjectIx::At(DObject* aObj)
+	{
+	//Check preconditions(debug build only)
+	__ASSERT_CRITICAL;
+	__ASSERT_NO_FAST_MUTEX;
+
+	if (iCount)
+		{
+		SDObjectIxRec* pS=iObjects;
+		SDObjectIxRec* pE=pS+iCount;
+		TInt i=0;
+		while(pS<pE && pS->obj!=aObj)
+			pS++, i++;
+		if (pS<pE)
+			return(makeHandle(i,pS->str.instance));
+		}
+	return KErrNotFound;
+	}
+
+
 /** Finds the object at a specific position in the index array.
 
 	@param	aIndex	Index into array.
--- a/memspy/Driver/Kernel/Source/MemSpyDriverStreamWriter.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverStreamWriter.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -69,7 +69,7 @@
         }
     else
         {
-        //TRACE( Kern::Printf( "RMemSpyMemStreamWriter::WriteInt32() - asked to write: 0x%08x from fn: 0x%08x BUT AM FULL", aValue, __return_address() ) );
+        TRACE( Kern::Printf( "RMemSpyMemStreamWriter::WriteInt32() - asked to write: 0x%08x from fn: 0x%08x BUT AM FULL", aValue, __return_address() ) );
         }
     //
     return ret;
@@ -89,7 +89,7 @@
         }
     else
         {
-        //TRACE( Kern::Printf( "RMemSpyMemStreamWriter::WriteUint32() - asked to write: 0x%08x from fn: 0x%08x BUT AM FULL", aValue, __return_address() ) );
+        TRACE( Kern::Printf( "RMemSpyMemStreamWriter::WriteUint32() - asked to write: 0x%08x from fn: 0x%08x BUT AM FULL", aValue, __return_address() ) );
         }
     //
     return ret;
--- a/memspy/Driver/Kernel/Source/MemSpyDriverSuspensionManager.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/MemSpyDriverSuspensionManager.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -427,8 +427,10 @@
     //
 	if ( iTempObj )
         {
+		NKern::LockSystem();
 		r = iTempObj->Open();
 	    TRACE( Kern::Printf("DMemSpySuspensionManager::OpenTempObject() - open returned: %d", r ));
+		NKern::UnlockSystem();
 		//
         if  ( r == KErrNone )
             {
@@ -497,9 +499,14 @@
 	__ASSERT_DEBUG( iTempObj, MemSpyDriverUtils::Fault( __LINE__ ) );
     if  ( iTempObj )
         {
-		NKern::ThreadEnterCS();
+	    NKern::ThreadEnterCS();
+        
+        TRACE( Kern::Printf("DMemSpySuspensionManager::CloseTempObject() - in CS..." ));
 	    Kern::SafeClose( iTempObj, NULL );
-		NKern::ThreadLeaveCS();
+        TRACE( Kern::Printf("DMemSpySuspensionManager::CloseTempObject() - done safe close..." ));
+	    NKern::ThreadLeaveCS();
+
+        TRACE( Kern::Printf("DMemSpySuspensionManager::CloseTempObject() - left CS" ));
         }
 
     TRACE( Kern::Printf("DMemSpySuspensionManager::CloseTempObject() - END" ));
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanBase.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanBase.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -143,8 +143,10 @@
     //
 	if ( iTempObj )
         {
+		NKern::LockSystem();
 		r = iTempObj->Open();
 	    TRACE( Kern::Printf("DMemSpyDriverLogChanBase::OpenTempObject() - open returned: %d", r ));
+		NKern::UnlockSystem();
 		//
         if  ( r == KErrNone )
             {
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanChunks.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanChunks.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -164,18 +164,15 @@
 
 	    // Iterate through each handle in the process
 	    MemSpyObjectIx* processHandles = processAdaption.GetHandles( *process );
-		MemSpyObjectIx_HandleLookupLock();
+        MemSpyObjectIx_Wait( processHandles );
+
         const TInt processHandleCount = processHandles->Count();
-		MemSpyObjectIx_HandleLookupUnlock();
-
 	    for( TInt processHandleIndex = 0; processHandleIndex<processHandleCount && r == KErrNone && currentWriteIndex < maxCount; processHandleIndex++ )
     	    {
     	    // Get a handle from the process container...
-            MemSpyObjectIx_HandleLookupLock();
-			if (processHandleIndex >= processHandles->Count()) break; // Count may have changed in the meantime
+            NKern::LockSystem();
     	    DObject* object = (*processHandles)[ processHandleIndex ];
-			if (object && object->Open() != KErrNone) object = NULL;
-			MemSpyObjectIx_HandleLookupUnlock();
+            NKern::UnlockSystem();
             
             if  ( object )
                 {
@@ -190,10 +187,11 @@
                         ++currentWriteIndex;
                         }
                     }
-				object->Close(NULL);
                 }
     	    }
 
+        MemSpyObjectIx_Signal( processHandles );
+
         // If we were asked for process-related chunks, also check the chunk container
         // for entries which we don't have handles to, but do refer to our process
         // Need a listing of all chunks in the system. Let client filter duplicates.
@@ -278,36 +276,34 @@
 	NKern::ThreadEnterCS();
 
     container->Wait();
+    NKern::LockSystem();
     const TInt count = container->Count();
+    NKern::UnlockSystem();
 
     DChunk* foundChunk = NULL;
     
     for(TInt i=0; i<count; i++)
         {
+        NKern::LockSystem();
         DChunk* chunk = (DChunk*) (*container)[i];
+        NKern::UnlockSystem();
+        //
         if  ( chunk == params.iHandle )
             {
             foundChunk = chunk;
             TRACE( PrintChunkInfo( *chunk ) );
-			r = foundChunk->Open();
             break;
             }
         }
 
     container->Signal();
+	NKern::ThreadLeaveCS();
 
     if  ( foundChunk == NULL )
         {
     	Kern::Printf("DMemSpyDriverLogChanChunks::GetChunkInfo() - END - KErrNotFound - couldnt find chunk");
-		NKern::ThreadLeaveCS();
         return KErrNotFound;
         }
-	if (r)
-		{
-		Kern::Printf("DMemSpyDriverLogChanChunks::GetChunkInfo() - END - %d - Failed to open chunk", r);
-		NKern::ThreadLeaveCS();
-		return r;
-		}
 
     // Prepare return data
     DMemSpyDriverOSAdaptionDChunk& chunkAdaption = OSAdaption().DChunk();
@@ -339,10 +335,6 @@
     // Get type & attribs
     params.iType = IdentifyChunkType( *foundChunk );
     params.iAttributes = chunkAdaption.GetAttributes( *foundChunk );
-
-	// Finished with foundChunk
-	foundChunk->Close(NULL);
-	NKern::ThreadLeaveCS();
     
     // Write back to client
     r = Kern::ThreadRawWrite( &ClientThread(), aParams, &params, sizeof(TMemSpyDriverInternalChunkInfoParams) );
@@ -478,36 +470,40 @@
 
     if  ( process && size >= 4 )
         {
-		NKern::ThreadEnterCS();
         // Chunks are mapped into entire process so any thread within the process is enough...
-        DThread* firstThread = processAdaption.OpenFirstThread( *process );
+        DThread* firstThread = processAdaption.GetFirstThread( *process );
         TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - firstThread: 0x%08x (%O)", firstThread, firstThread ) );
         if  ( firstThread != NULL )
             {
-            TBuf8<4> allocatorVTableBuffer;
-            TInt err = Kern::ThreadRawRead( firstThread, base, (TUint8*) allocatorVTableBuffer.Ptr(), allocatorVTableBuffer.MaxLength() );
-            TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk - read result of vtable data from requested thread is: %d", err ));
-            //
+            TInt err = firstThread->Open();
+            TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - firstThread open result: %d", err ) );
+
             if  ( err == KErrNone )
                 {
-                TRACE( MemSpyDriverUtils::DataDump("possible chunk vtable data - %lS", allocatorVTableBuffer.Ptr(), allocatorVTableBuffer.MaxLength(), allocatorVTableBuffer.MaxLength() ) );
-                allocatorVTableBuffer.SetLength( allocatorVTableBuffer.MaxLength() );
-                
-                const TUint32 vtable =   allocatorVTableBuffer[0] +
-                                        (allocatorVTableBuffer[1] << 8) + 
-                                        (allocatorVTableBuffer[2] << 16) + 
-                                        (allocatorVTableBuffer[3] << 24);
-                TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk - [possible] vTable within chunk is: 0x%08x", vtable) );
+                TBuf8<4> allocatorVTableBuffer;
+                err = Kern::ThreadRawRead( firstThread, base, (TUint8*) allocatorVTableBuffer.Ptr(), allocatorVTableBuffer.MaxLength() );
+                TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk - read result of vtable data from requested thread is: %d", err ));
+                //
+                if  ( err == KErrNone )
+                    {
+                    TRACE( MemSpyDriverUtils::DataDump("possible chunk vtable data - %lS", allocatorVTableBuffer.Ptr(), allocatorVTableBuffer.MaxLength(), allocatorVTableBuffer.MaxLength() ) );
+                    allocatorVTableBuffer.SetLength( allocatorVTableBuffer.MaxLength() );
+                    
+                    const TUint32 vtable =   allocatorVTableBuffer[0] +
+                                            (allocatorVTableBuffer[1] << 8) + 
+                                            (allocatorVTableBuffer[2] << 16) + 
+                                            (allocatorVTableBuffer[3] << 24);
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk - [possible] vTable within chunk is: 0x%08x", vtable) );
 
-                // Check the v-table to work out if it really is an RHeap
-                isHeap = ( vtable == rHeapVTable );
-                TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - isHeap: %d", isHeap ) );
-                }
+                    // Check the v-table to work out if it really is an RHeap
+                    isHeap = ( vtable == rHeapVTable );
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - isHeap: %d", isHeap ) );
+                    }
 
-            TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - closing first thread..." ) );
-            Kern::SafeClose( (DObject*&) firstThread, NULL );
+                TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - closing first thread..." ) );
+            	Kern::SafeClose( (DObject*&) firstThread, NULL );
+                }
             }
-		NKern::ThreadLeaveCS();
         }
 
     /* We only want RHeap's at the moment
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanClientServer.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanClientServer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -96,8 +96,8 @@
     NKern::ThreadEnterCS();
 
     DObject* serverHandle = (DObject*) params.iServerHandle;
-    DServer* server = static_cast<DServer*>(CheckedOpen(EMemSpyDriverContainerTypeServer, serverHandle));
-    if (server == NULL)
+    serverHandle = CheckIfObjectIsInContainer( EMemSpyDriverContainerTypeServer, serverHandle );
+    if  ( serverHandle == NULL )
         {
     	Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionHandles() - END - server not found");
         NKern::ThreadLeaveCS();
@@ -106,29 +106,47 @@
 
 	ResetTempHandles();
 
-    NKern::LockSystem(); // Iterating session queue requires system lock
-    // Iterate through this server's sessions, writing back session pointer (handle)
-    // to client
-    SDblQue& serverQueue = serverAdaption.GetSessionQueue( *server );
-    SDblQueLink* anchor = &serverQueue.iA;
-    SDblQueLink* link = serverQueue.First();
-    while( link != anchor )
+    DServer* server = (DServer*) serverHandle;
+    NKern::LockSystem();
+
+    r = server->Open();
+    if  ( r == KErrNone )
         {
-		DSession* session = serverAdaption.GetSession( link );
+        // Iterate through this server's sessions, writing back session pointer (handle)
+        // to client
+        SDblQue& serverQueue = serverAdaption.GetSessionQueue( *server );
+        SDblQueLink* anchor = &serverQueue.iA;
+        SDblQueLink* link = serverQueue.First();
+        while( link != anchor )
+        	{
+			DSession* session = serverAdaption.GetSession( link );
 
-        // Found a match in the specified container. Write the object's handle (aka the object address)
-        // back to the client address space
-        if  ( session )
-            {
-            AddTempHandle( session );
+            // Found a match in the specified container. Write the object's handle (aka the object address)
+            // back to the client address space
+            if  ( session )
+                {
+                AddTempHandle( session );
+                }
+
+            // Get next item
+            link = link->iNext;
             }
 
-        // Get next item
-        link = link->iNext;
+        NKern::ThreadEnterCS();
+        TRACE( Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionHandles() - in CS..." ));
+        //
+	    Kern::SafeClose( (DObject*&) server, NULL );
+        TRACE( Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionHandles() - done safe close..." ));
+        //
+	    NKern::ThreadLeaveCS();
+        TRACE( Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionHandles() - left CS" ));
         }
+    else
+        {
+    	Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionHandles - error: %d opening server", r);
+        }
+
     NKern::UnlockSystem();
-	server->Close(NULL);
-	NKern::ThreadLeaveCS();
 
     // This variable holds the number of handles that we have already
 	// written to the client-side.
@@ -158,6 +176,7 @@
             }
         }
 
+	NKern::ThreadLeaveCS();
 
 	TRACE( Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionHandles() - END - r: %d", r));
 	return r;
@@ -180,48 +199,74 @@
 
 	NKern::ThreadEnterCS();
 
-    DSession* session = (DSession*)CheckedOpen(EMemSpyDriverContainerTypeSession, (DObject*)aSessionHandle);
-    if (session == NULL )
+    DObject* sessionHandle = (DObject*) aSessionHandle;
+    sessionHandle = CheckIfObjectIsInContainer( EMemSpyDriverContainerTypeSession, sessionHandle );
+    if  ( sessionHandle == NULL )
         {
     	Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionInfo() - END - session not found");
         NKern::ThreadLeaveCS();
         return KErrNotFound;
         }
 
+    DSession* session = (DSession*) sessionHandle;
     session->FullName( params.iName );
 
-    // Get owner type and id
-    DObject* sessionOwner = sessionAdaption.GetOwner( *session );
-    if  ( sessionOwner )
+    NKern::LockSystem();
+    r = session->Open();
+    if  ( r == KErrNone )
         {
-        const TObjectType objectType = sessionAdaption.GetObjectType( *sessionOwner );
-        if  ( objectType == EProcess )
+        // Get owner type and id
+        DObject* sessionOwner = sessionAdaption.GetOwner( *session );
+        if  ( sessionOwner )
             {
-            DProcess* sessionProcess = (DProcess*) sessionOwner;
-            //
-            params.iOwnerId = processAdaption.GetId( *sessionProcess );
-            params.iOwnerType = TMemSpyDriverServerSessionInfo::EOwnerProcess;
+            const TObjectType objectType = sessionAdaption.GetObjectType( *sessionOwner );
+            if  ( objectType == EProcess )
+                {
+                DProcess* sessionProcess = (DProcess*) sessionOwner;
+                //
+                params.iOwnerId = processAdaption.GetId( *sessionProcess );
+                params.iOwnerType = TMemSpyDriverServerSessionInfo::EOwnerProcess;
+                }
+            else if ( objectType == EThread )
+                {
+                DThread* sessionThread = (DThread*) sessionOwner;
+                //
+                params.iOwnerId = threadAdaption.GetId( *sessionThread );
+                params.iOwnerType = TMemSpyDriverServerSessionInfo::EOwnerThread;
+                }
             }
-        else if ( objectType == EThread )
+        else
             {
-            DThread* sessionThread = (DThread*) sessionOwner;
-            //
-            params.iOwnerId = threadAdaption.GetId( *sessionThread );
-            params.iOwnerType = TMemSpyDriverServerSessionInfo::EOwnerThread;
+            params.iOwnerId = -1;
+            params.iOwnerType = TMemSpyDriverServerSessionInfo::EOwnerNone;
             }
+
+        // Other attributes
+        params.iSessionType = sessionAdaption.GetSessionType( *session );
+        params.iAddress = (TUint8*)session;
+
+        NKern::ThreadEnterCS();
+        TRACE( Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionInfo() - in CS..." ));
+        //
+	    Kern::SafeClose( (DObject*&) session, NULL );
+        TRACE( Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionInfo() - done safe close..." ));
+        //
+	    NKern::ThreadLeaveCS();
+        TRACE( Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionInfo() - left CS" ));
         }
     else
         {
-        params.iOwnerId = -1;
-        params.iOwnerType = TMemSpyDriverServerSessionInfo::EOwnerNone;
+    	Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionInfo - error: %d opening server", r);
         }
 
-    // Other attributes
-    params.iSessionType = sessionAdaption.GetSessionType( *session );
-    params.iAddress = (TUint8*)session;
-	session->Close(NULL);
+    NKern::UnlockSystem();
+
+    if  ( r == KErrNone )
+        {
+        r = Kern::ThreadRawWrite( &ClientThread(), aParams, &params, sizeof(TMemSpyDriverServerSessionInfo) );
+        }
+
 	NKern::ThreadLeaveCS();
-    r = Kern::ThreadRawWrite( &ClientThread(), aParams, &params, sizeof(TMemSpyDriverServerSessionInfo) );
 
 	TRACE( Kern::Printf("DMemSpyDriverLogChanClientServer::GetServerSessionInfo() - END - r: %d", r));
 	return r;
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanContainerBase.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanContainerBase.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -49,44 +49,58 @@
 
 
 
-DObject* DMemSpyDriverLogChanContainerBase::CheckedOpen(TMemSpyDriverContainerType aContainerType, DObject* aObject, TBool aQuick)
-	{
-	__ASSERT_CRITICAL;
-	__ASSERT_DEBUG(aObject != NULL, MemSpyDriverUtils::Fault( __LINE__ ));
-    const TObjectType expectedType = ObjectTypeFromMemSpyContainerType(aContainerType);
+
+
+
+DObject* DMemSpyDriverLogChanContainerBase::CheckIfObjectIsInContainer( TMemSpyDriverContainerType aContainerType, DObject* aSearchFor, TBool aQuick )
+    {
+	__ASSERT_DEBUG( aSearchFor != NULL, MemSpyDriverUtils::Fault( __LINE__ ) );
+    const TObjectType expectedType = ObjectTypeFromMemSpyContainerType( aContainerType );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanContainerBase::CheckIfObjectIsInContainer - START - aSearchFor: 0x%08x, expectedType: %d", aSearchFor, expectedType ));
 
-    // Quick mode means we just check container ids and we trust that the object will exist.
-	// [TomS: not entirely convinced we can ever be certain of that]
-    TInt err = KErrNotFound;
-    if (aQuick)
+    DObject* ret = NULL;
+    
+    // Quick mode means we just check container ids and we trust that the object
+    // will exist.
+    if ( aQuick )
         {
-		LOG("quick CheckedOpen of %08x", aObject);
-        const TObjectType objectType = OSAdaption().DThread().GetObjectType(*aObject);
-        if (objectType == expectedType)
+        const TObjectType objectType = OSAdaption().DThread().GetObjectType( *aSearchFor );
+        TRACE( Kern::Printf("DMemSpyDriverLogChanContainerBase::CheckIfObjectIsInContainer - aSearchFor.iContainerID: %d", objectType ) );
+        if  ( objectType == expectedType )
             {
-            err = aObject->Open();
+            ret = aSearchFor;
             }
         }
-	else
-		{
-        DObjectCon* container = Kern::Containers()[expectedType];
+    else
+        {
+        // Full check to see if the specified object is part of the container
+        DObjectCon* container = Kern::Containers()[ expectedType ];
         container->Wait();
+        NKern::LockSystem();
+
         const TInt count = container->Count();
-        for (TInt i = 0; i < count; i++)
+        for(TInt i=0; i<count; i++)
             {
-            DObject* object = (*container)[i];
-            if (object == aObject)
+            DObject* object = (*container)[ i ];
+
+            // Do the two match?
+            if  ( object == aSearchFor )
                 {
-                err = aObject->Open();
-				break;
-				}
-			}
-		container->Signal();
-		}
+                TRACE( Kern::Printf("    found match: %O", object));
+
+                ret = object;
+                break;
+                }
+            }
 
-	LOG("CheckedOpen(%d, 0x%08x, quick=%d) returned error %d", aContainerType, aObject, aQuick, err);
-	return (err == KErrNone) ? aObject : NULL;
-	}
+        NKern::UnlockSystem();
+        container->Signal();
+        }
+
+    TRACE( Kern::Printf("DMemSpyDriverLogChanContainerBase::CheckIfObjectIsInContainer - END - ret: 0x%08x", ret ));
+    TRACE( Kern::Printf(" ") );
+    return ret;
+    }
 
 
 
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanContainers.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanContainers.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -146,6 +146,7 @@
 
         DObjectCon* container = Kern::Containers()[type];
         container->Wait();
+        NKern::LockSystem();
 
         const TInt count = container->Count();
         for(TInt i=0; i<count; i++)
@@ -157,7 +158,9 @@
                 }
             }
 
+        NKern::UnlockSystem();
         container->Signal();
+
     	NKern::ThreadLeaveCS();
         }
     else
@@ -211,30 +214,34 @@
 
                 // Iterate through each handle in the thread/process and add it to the temp handles container if
                 // the handle is of the correct type.
+                MemSpyObjectIx_Wait( handles );
 
-				MemSpyObjectIx_HandleLookupLock();
-				const TInt handleCount = handles->Count();
-				MemSpyObjectIx_HandleLookupUnlock();
+	            TInt handleCount = handles->Count();
                 TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetContainerHandles - %d handles in index...", handleCount ));
 
                 for( TInt handleIndex=0; handleIndex<handleCount; handleIndex++ )
     	            {
     	            // Get a handle from the container...
-					MemSpyObjectIx_HandleLookupLock();
-					if (handleIndex >= handles->Count()) break; // Count may have changed in the meantime
-    				DObject* objectToSearchFor = (*handles)[ handleIndex ];
-					if (objectToSearchFor && objectToSearchFor->Open() != KErrNone) objectToSearchFor = NULL;
-					MemSpyObjectIx_HandleLookupUnlock();
+                    NKern::LockSystem();
+    	            DObject* objectToSearchFor = (*handles)[ handleIndex ];
+                    NKern::UnlockSystem();
         
-                    if (objectToSearchFor && OSAdaption().DThread().GetObjectType(*objectToSearchFor) == ObjectTypeFromMemSpyContainerType(params.iContainer))
+                    if  ( objectToSearchFor != NULL )
                         {
-                        // Found a match in the specified container. Write the object's handle (aka the object address)
-                        // back to the client address space
-                        AddTempHandle( objectToSearchFor );
+                        // Check to see if this object is of the specified type. We can use quick mode
+                        // because we know the object is valid since it's registered as a handle of the
+                        // thread/process.
+                        DObject* matchResult = CheckIfObjectIsInContainer( params.iContainer, objectToSearchFor, ETrue );
+                        if  ( matchResult )
+                            {
+                            // Found a match in the specified container. Write the object's handle (aka the object address)
+                            // back to the client address space
+                            AddTempHandle( matchResult );
+                            }
                         }
-					if (objectToSearchFor) objectToSearchFor->Close(NULL);
     	            }
 
+                MemSpyObjectIx_Signal( handles );
                 NKern::ThreadLeaveCS();
                 }
 
@@ -300,21 +307,30 @@
 
     // First, locate the specific DObject in question. Cast the handle, but don't use the object...
     DObject* handleAsObject = (DObject*) params.iHandle;
-    handleAsObject = CheckedOpen(params.iType, handleAsObject);
+    handleAsObject = CheckIfObjectIsInContainer( params.iType, handleAsObject );
     if  ( handleAsObject != NULL )
         {
         // We found the right object. First get generic info.
         handleAsObject->FullName( params.iName );
         handleAsObject->Name( params.iNameDetail );
         
-        // Using threadAddaption to fetch generic info.
-        // Implementations of following get functions are actually in DMemSpyDriverOSAdaptionDObject
-        // so it does not matter what adaption to use for generic info.
-        DMemSpyDriverOSAdaptionDThread& threadAddaption = OSAdaption().DThread();
-        params.iAccessCount = threadAddaption.GetAccessCount( *handleAsObject );
-        params.iUniqueID = threadAddaption.GetUniqueID( *handleAsObject );
-        params.iProtection = threadAddaption.GetProtection( *handleAsObject );
-        params.iAddressOfKernelOwner = threadAddaption.GetAddressOfKernelOwner( *handleAsObject );
+        NKern::LockSystem();
+        r = handleAsObject->Open();
+        NKern::UnlockSystem();
+        //
+        if  ( r == KErrNone )
+            {
+            // Using threadAddaption to fetch generic info.
+            // Implementations of following get functions are actually in DMemSpyDriverOSAdaptionDObject
+            // so it does not matter what adaption to use for generic info.
+            DMemSpyDriverOSAdaptionDThread& threadAddaption = OSAdaption().DThread();
+            params.iAccessCount = threadAddaption.GetAccessCount( *handleAsObject );
+            params.iUniqueID = threadAddaption.GetUniqueID( *handleAsObject );
+            params.iProtection = threadAddaption.GetProtection( *handleAsObject );
+            params.iAddressOfKernelOwner = threadAddaption.GetAddressOfKernelOwner( *handleAsObject );
+            //
+            handleAsObject->Close( NULL );
+            }
         
         // Get type-specific info.
         if  ( params.iType == EMemSpyDriverContainerTypeThread )
@@ -322,49 +338,76 @@
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeThread" ));
 
             DThread* object = (DThread*) handleAsObject;
-            DMemSpyDriverOSAdaptionDThread& threadAdaption = OSAdaption().DThread();
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
             //
-            params.iId = threadAdaption.GetId( *object );
-            params.iPriority = threadAdaption.GetPriority( *object );
-            params.iAddressOfOwningProcess = threadAdaption.GetAddressOfOwningProcess( *object );
-            threadAdaption.GetNameOfOwningProcess( *object, params.iNameOfOwner );
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDThread& threadAdaption = OSAdaption().DThread();
+                //
+                params.iId = threadAdaption.GetId( *object );
+                params.iPriority = threadAdaption.GetPriority( *object );
+                params.iAddressOfOwningProcess = threadAdaption.GetAddressOfOwningProcess( *object );
+                threadAdaption.GetNameOfOwningProcess( *object, params.iNameOfOwner );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeProcess )
             {
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeProcess" ));
 
             DProcess* object = (DProcess*) handleAsObject;
-            DMemSpyDriverOSAdaptionDProcess& processAdaption = OSAdaption().DProcess();
-            //
-            params.iId = processAdaption.GetId( *object );
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
             //
-            params.iPriority = processAdaption.GetPriority( *object );
-            params.iAddressOfOwningProcess = processAdaption.GetAddressOfOwningProcess( *object );
-            params.iCreatorId = processAdaption.GetCreatorId( *object );
-            params.iSecurityZone = processAdaption.GetSecurityZone( *object );
-            params.iAttributes = processAdaption.GetAttributes( *object );
-            params.iAddressOfDataBssStackChunk = processAdaption.GetAddressOfDataBssStackChunk( *object );
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDProcess& processAdaption = OSAdaption().DProcess();
+                //
+                params.iId = processAdaption.GetId( *object );
+                //
+                params.iPriority = processAdaption.GetPriority( *object );
+                params.iAddressOfOwningProcess = processAdaption.GetAddressOfOwningProcess( *object );
+                params.iCreatorId = processAdaption.GetCreatorId( *object );
+                params.iSecurityZone = processAdaption.GetSecurityZone( *object );
+                params.iAttributes = processAdaption.GetAttributes( *object );
+                params.iAddressOfDataBssStackChunk = processAdaption.GetAddressOfDataBssStackChunk( *object );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeChunk )
             {
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeChunk" ));
 
             DChunk* object = (DChunk*) handleAsObject;
-            DMemSpyDriverOSAdaptionDChunk& ca = OSAdaption().DChunk();
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
             //
-            params.iSize = ca.GetSize( *object );
-            params.iId = ca.GetOwningProcessId( *object );
-            params.iAddressOfOwningProcess = ca.GetAddressOfOwningProcess( *object );
-            params.iMaxSize = ca.GetMaxSize( *object );
-            params.iBottom = ca.GetBottom( *object );
-            params.iTop = ca.GetTop( *object );
-            params.iAttributes = ca.GetAttributes( *object );
-            params.iStartPos = ca.GetStartPos( *object );
-            params.iControllingOwner = ca.GetControllingOwnerId( *object );
-            params.iRestrictions = ca.GetRestrictions( *object );
-            params.iMapAttr = ca.GetMapAttr( *object );
-            params.iChunkType = ca.GetType( *object );
-            ca.GetNameOfOwningProcess( *object, params.iNameOfOwner );
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDChunk& ca = OSAdaption().DChunk();
+                //
+                params.iSize = ca.GetSize( *object );
+                params.iId = ca.GetOwningProcessId( *object );
+                params.iAddressOfOwningProcess = ca.GetAddressOfOwningProcess( *object );
+                params.iMaxSize = ca.GetMaxSize( *object );
+                params.iBottom = ca.GetBottom( *object );
+                params.iTop = ca.GetTop( *object );
+                params.iAttributes = ca.GetAttributes( *object );
+                params.iStartPos = ca.GetStartPos( *object );
+                params.iControllingOwner = ca.GetControllingOwnerId( *object );
+                params.iRestrictions = ca.GetRestrictions( *object );
+                params.iMapAttr = ca.GetMapAttr( *object );
+                params.iChunkType = ca.GetType( *object );
+                ca.GetNameOfOwningProcess( *object, params.iNameOfOwner );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeLibrary )
             {
@@ -373,19 +416,28 @@
 	        Kern::AccessCode();
             //
             DLibrary* object = (DLibrary*) handleAsObject;
-            DMemSpyDriverOSAdaptionDCodeSeg& csa = OSAdaption().DCodeSeg();
-            DCodeSeg* codeSeg = csa.GetCodeSeg( *object );
-            params.iAddressOfCodeSeg = (TUint8*)codeSeg;
-            params.iMapCount = csa.GetMapCount( *object );
-            params.iState = csa.GetState( *object );
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
             //
-            if  ( codeSeg )
+            if  ( r == KErrNone )
                 {
-                params.iSize = csa.GetSize( *codeSeg );
-                }
-            else
-                {
-                r = KErrNotFound;
+                DMemSpyDriverOSAdaptionDCodeSeg& csa = OSAdaption().DCodeSeg();
+                DCodeSeg* codeSeg = csa.GetCodeSeg( *object );
+                params.iAddressOfCodeSeg = (TUint8*)codeSeg;
+                params.iMapCount = csa.GetMapCount( *object );
+                params.iState = csa.GetState( *object );
+                //
+                if  ( codeSeg )
+                    {
+                    params.iSize = csa.GetSize( *codeSeg );
+                    }
+                else
+                    {
+                    r = KErrNotFound;
+                    }
+                //
+                object->Close( NULL );
                 }
             //
 	        Kern::EndAccessCode();
@@ -395,21 +447,39 @@
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeSemaphore" ));
 
             DSemaphore* object = (DSemaphore*) handleAsObject;
-            DMemSpyDriverOSAdaptionDSemaphore& sa = OSAdaption().DSemaphore();
-            params.iCount = sa.GetCount( *object );
-            params.iResetting = sa.GetResetting( *object );
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
+            //
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDSemaphore& sa = OSAdaption().DSemaphore();
+                params.iCount = sa.GetCount( *object );
+                params.iResetting = sa.GetResetting( *object );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeMutex )
             {
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeMutex" ));
 
             DMutex* object = (DMutex*) handleAsObject;
-            DMemSpyDriverOSAdaptionDMutex& ma = OSAdaption().DMutex();
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
             //
-            params.iCount = ma.GetHoldCount( *object );
-            params.iWaitCount = ma.GetWaitCount( *object );
-            params.iResetting = ma.GetResetting( *object );
-            params.iOrder = ma.GetOrder( *object );
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDMutex& ma = OSAdaption().DMutex();
+                //
+                params.iCount = ma.GetHoldCount( *object );
+                params.iWaitCount = ma.GetWaitCount( *object );
+                params.iResetting = ma.GetResetting( *object );
+                params.iOrder = ma.GetOrder( *object );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeTimer )
             {
@@ -417,62 +487,98 @@
 
             // Get timer properties
             DTimer* object = (DTimer*) handleAsObject;
-            DMemSpyDriverOSAdaptionDTimer& ta = OSAdaption().DTimer();
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
             //
-            params.iTimerType = MapToMemSpyTimerType( ta.GetType( *object ) );
-            params.iTimerState = MapToMemSpyTimerState( ta.GetState( *object ) );
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDTimer& ta = OSAdaption().DTimer();
+                //
+                params.iTimerType = MapToMemSpyTimerType( ta.GetType( *object ) );
+                params.iTimerState = MapToMemSpyTimerState( ta.GetState( *object ) );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeServer )
             {
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeServer" ));
 
             DServer* object = (DServer*) handleAsObject;
-            DMemSpyDriverOSAdaptionDServer& sa = OSAdaption().DServer();
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
             //
-            params.iCount = sa.GetSessionCount( *object );
-            params.iId = sa.GetOwningThreadId( *object );
-            params.iSessionType = sa.GetSessionType( *object );
-            params.iAddressOfOwningThread = sa.GetAddressOfOwningThread( *object );
-            sa.GetNameOfOwningThread( *object, params.iNameOfOwner );
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDServer& sa = OSAdaption().DServer();
+                //
+                params.iCount = sa.GetSessionCount( *object );
+                params.iId = sa.GetOwningThreadId( *object );
+                params.iSessionType = sa.GetSessionType( *object );
+                params.iAddressOfOwningThread = sa.GetAddressOfOwningThread( *object );
+                sa.GetNameOfOwningThread( *object, params.iNameOfOwner );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeSession )
             {
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeSession" ));
 
             DSession* object = (DSession*) handleAsObject;
-            DMemSpyDriverOSAdaptionDServer& serverAdaption = OSAdaption().DServer();
-            DMemSpyDriverOSAdaptionDSession& sessionAdaption = OSAdaption().DSession();
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
+            //
+	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - open error: %d", r ));
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDServer& serverAdaption = OSAdaption().DServer();
+                DMemSpyDriverOSAdaptionDSession& sessionAdaption = OSAdaption().DSession();
 
-            params.iName.Zero();
+                params.iName.Zero();
 
-            TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - getting session type..." ));
-            params.iSessionType = sessionAdaption.GetSessionType( *object );
-            params.iAddressOfServer = sessionAdaption.GetAddressOfServer( *object );
-            params.iTotalAccessCount = sessionAdaption.GetTotalAccessCount( *object );
-            params.iSvrSessionType = sessionAdaption.GetSessionType( *object );
-            params.iMsgCount = sessionAdaption.GetMsgCount( *object );
-            params.iMsgLimit = sessionAdaption.GetMsgLimit( *object );
-            
-            // Its more useful in this instance, if the name object
-            // points to the server which the session is connected to
-            // (rather than displaying a process-local name).
-            DServer* server = (DServer*)CheckedOpen(EMemSpyDriverContainerTypeServer, sessionAdaption.GetServer( *object ));
-	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - getting full name, server: 0x%08x", server ));
-            //
-            if  ( server )
-                {
-                server->FullName( params.iName );
+                TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - getting session type..." ));
+                params.iSessionType = sessionAdaption.GetSessionType( *object );
+                params.iAddressOfServer = sessionAdaption.GetAddressOfServer( *object );
+                params.iTotalAccessCount = sessionAdaption.GetTotalAccessCount( *object );
+                params.iSvrSessionType = sessionAdaption.GetSessionType( *object );
+                params.iMsgCount = sessionAdaption.GetMsgCount( *object );
+                params.iMsgLimit = sessionAdaption.GetMsgLimit( *object );
+                
+                // Its more useful in this instance, if the name object
+                // points to the server which the session is connected to
+                // (rather than displaying a process-local name).
+                DServer* server = sessionAdaption.GetServer( *object );
+	            TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - getting full name, server: 0x%08x", server ));
+                //
+                if  ( server )
+                    {
+	                NKern::LockSystem();
+                    r = server->Open();
+     	            NKern::UnlockSystem();
 
-                // Continue as normal for other items
-	            TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - server: 0x%08x, server->iOwningThread: 0x%08x", server, server->iOwningThread ));
-                DThread* owningThread = serverAdaption.GetOwningThread( *server );
-                if  ( owningThread )
-                    {
-	                TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - getting server thread id..." ));
-                    params.iId = serverAdaption.GetOwningThreadId( *server );
+                    if  ( r == KErrNone )
+                        {
+                        server->FullName( params.iName );
+ 
+                        // Continue as normal for other items
+	                    TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - server: 0x%08x, server->iOwningThread: 0x%08x", server, server->iOwningThread ));
+                        DThread* owningThread = serverAdaption.GetOwningThread( *server );
+                        if  ( owningThread )
+                            {
+	                        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - getting server thread id..." ));
+                            params.iId = serverAdaption.GetOwningThreadId( *server );
+                            }
+
+                        server->Close( NULL );
+                        }
                     }
 
-                server->Close(NULL);
+                TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - closing session object..." ));
+                object->Close( NULL );
                 }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeLogicalDevice )
@@ -480,21 +586,39 @@
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeLogicalDevice" ));
 
             DLogicalDevice* object = (DLogicalDevice*) handleAsObject;
-            DMemSpyDriverOSAdaptionDLogicalDevice& lda = OSAdaption().DLogicalDevice();
-            params.iOpenChannels = lda.GetOpenChannels( *object );
-            params.iVersion = lda.GetVersion( *object );
-            params.iParseMask = lda.GetParseMask( *object );
-            params.iUnitsMask = lda.GetUnitsMask( *object );
+	        NKern::LockSystem();
+            r = object->Open();
+    	    NKern::UnlockSystem();
+            //
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDLogicalDevice& lda = OSAdaption().DLogicalDevice();
+                params.iOpenChannels = lda.GetOpenChannels( *object );
+                params.iVersion = lda.GetVersion( *object );
+                params.iParseMask = lda.GetParseMask( *object );
+                params.iUnitsMask = lda.GetUnitsMask( *object );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypePhysicalDevice )
             {
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypePhysicalDevice" ));
 	        
 	        DPhysicalDevice* object = (DPhysicalDevice*) handleAsObject;
-            DMemSpyDriverOSAdaptionDPhysicalDevice& pda = OSAdaption().DPhysicalDevice();
-            params.iVersion = pda.GetVersion( *object );
-            params.iUnitsMask = pda.GetUnitsMask( *object );
-            params.iAddressOfCodeSeg = pda.GetAddressOfCodeSeg( *object );
+            NKern::LockSystem();
+            r = object->Open();
+            NKern::UnlockSystem();
+            //
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDPhysicalDevice& pda = OSAdaption().DPhysicalDevice();
+                params.iVersion = pda.GetVersion( *object );
+                params.iUnitsMask = pda.GetUnitsMask( *object );
+                params.iAddressOfCodeSeg = pda.GetAddressOfCodeSeg( *object );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeLogicalChannel )
             {
@@ -505,19 +629,37 @@
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeChangeNotifier" ));
 
 	        DChangeNotifier* object = (DChangeNotifier*) handleAsObject;
-            DMemSpyDriverOSAdaptionDChangeNotifier& cna = OSAdaption().DChangeNotifier();
-            params.iChanges = cna.GetChanges( *object );
-            params.iAddressOfOwningThread = cna.GetAddressOfOwningThread( *object );
-            cna.GetNameOfOwningThread( *object, params.iNameOfOwner );
+            NKern::LockSystem();
+            r = object->Open();
+            NKern::UnlockSystem();
+            //
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDChangeNotifier& cna = OSAdaption().DChangeNotifier();
+                params.iChanges = cna.GetChanges( *object );
+                params.iAddressOfOwningThread = cna.GetAddressOfOwningThread( *object );
+                cna.GetNameOfOwningThread( *object, params.iNameOfOwner );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeUndertaker )
             {
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeUndertaker" ));
 	        
             DUndertaker* object = (DUndertaker*) handleAsObject;
-            DMemSpyDriverOSAdaptionDUndertaker& uta = OSAdaption().DUndertaker();
-            params.iAddressOfOwningThread = uta.GetAddressOfOwningThread( *object );
-            uta.GetNameOfOwningThread( *object, params.iNameOfOwner );
+            NKern::LockSystem();
+            r = object->Open();
+            NKern::UnlockSystem();
+            //
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDUndertaker& uta = OSAdaption().DUndertaker();
+                params.iAddressOfOwningThread = uta.GetAddressOfOwningThread( *object );
+                uta.GetNameOfOwningThread( *object, params.iNameOfOwner );
+                //
+                object->Close( NULL );
+                }
             }
         else if ( params.iType == EMemSpyDriverContainerTypeMsgQueue )
             {
@@ -532,18 +674,26 @@
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - EMemSpyDriverContainerTypeCondVar" ));
 	        
             DCondVar* object = (DCondVar*) handleAsObject;
-            DMemSpyDriverOSAdaptionDCondVar& cva = OSAdaption().DCondVar();
-            params.iResetting = cva.GetResetting( *object );
-            params.iAddressOfOwningThread = cva.GetAddressOfMutex( *object );
-            cva.GetNameOfMutex( *object, params.iNameOfOwner );
-            params.iWaitCount = cva.GetWaitCount( *object );
+            NKern::LockSystem();
+            r = object->Open();
+            NKern::UnlockSystem();
+            //
+            if  ( r == KErrNone )
+                {
+                DMemSpyDriverOSAdaptionDCondVar& cva = OSAdaption().DCondVar();
+                params.iResetting = cva.GetResetting( *object );
+                params.iAddressOfOwningThread = cva.GetAddressOfMutex( *object );
+                cva.GetNameOfMutex( *object, params.iNameOfOwner );
+                params.iWaitCount = cva.GetWaitCount( *object );
+                //
+                object->Close( NULL );
+                }
             }
         else
             {
 	        TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetGenericHandleInfo() - KErrNotSupported" ));
             r = KErrNotSupported;
             }
-		handleAsObject->Close(NULL);
         }
     else
         {
@@ -731,12 +881,13 @@
 	NKern::ThreadEnterCS();
 
     // First, locate the specific DObject in question. Cast the handle, but don't use the object...
-    DObject* object = CheckedOpen(EMemSpyDriverContainerTypePropertyRef, aHandle);
+    // NB: This claims the system lock
+    DObject* object = CheckIfObjectIsInContainer( EMemSpyDriverContainerTypePropertyRef, aHandle );
     TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::GetPAndSInfo() - handle search returned: 0x%08x", object ));
 
     if  ( object != NULL )
         {
-        NKern::LockSystem(); // Keep this, the DPropertyRef APIs use it -TomS
+        NKern::LockSystem();
 
         DMemSpyDriverOSAdaptionDPropertyRef& pra = OSAdaption().DPropertyRef();
         const TBool isReady = pra.GetIsReady( *object );
@@ -762,7 +913,6 @@
             }
 
         NKern::UnlockSystem();
-		object->Close(NULL);
         }
 
     NKern::ThreadLeaveCS();
@@ -789,7 +939,7 @@
     NKern::ThreadEnterCS();
     
     DObject* condVarHandle = (DObject*) params.iCondVarHandle;
-    condVarHandle = CheckedOpen(EMemSpyDriverContainerTypeCondVar, condVarHandle);
+    condVarHandle = CheckIfObjectIsInContainer( EMemSpyDriverContainerTypeCondVar, condVarHandle );
     if  ( condVarHandle == NULL )
         {
         Kern::Printf("DMemSpyDriverLogChanMisc::GetCondVarSuspThrs() - END - condVar not found");
@@ -799,9 +949,9 @@
     
     ResetTempHandles();
         
-    DCondVar* condVar = (DCondVar*) condVarHandle;
+    DCondVar* condVar = (DCondVar*) params.iCondVarHandle;;
     
-    NKern::LockSystem(); // Keep this, needed for iterating suspended queue -TomS
+    NKern::LockSystem();
 
     // Iterate through suspended threads, writing back thread pointer (handle)
     // to client
@@ -853,7 +1003,6 @@
             }
         }
 
-	condVarHandle->Close(NULL);
     NKern::ThreadLeaveCS();
 
     TRACE( Kern::Printf("DMemSpyDriverLogChanMisc::GetCondVarSuspThrs() - END - r: %d", r));
@@ -877,7 +1026,7 @@
     NKern::ThreadEnterCS();
 
     DObject* threadHandle = (DObject*) aThreadHandle;
-    threadHandle = CheckedOpen(EMemSpyDriverContainerTypeThread, threadHandle);
+    threadHandle = CheckIfObjectIsInContainer( EMemSpyDriverContainerTypeThread, threadHandle );
     if  ( threadHandle == NULL )
         {
         Kern::Printf("DMemSpyDriverLogChanMisc::GetCondVarSuspThrInfo() - END - thread not found");
@@ -894,7 +1043,6 @@
         r = Kern::ThreadRawWrite( &ClientThread(), aParams, &params, sizeof(TMemSpyDriverCondVarSuspendedThreadInfo) );
         }
     
-	threadHandle->Close(NULL);
     NKern::ThreadLeaveCS();
     
     TRACE( Kern::Printf("DMemSpyDriverLogChanMisc::GetCondVarSuspThrInfo() - END - r: %d", r));
@@ -958,13 +1106,17 @@
 
         if  ( handles != NULL )
             {
-            TBool found = handles->Find( aHandleToLookFor );
-	        if (found)
+            MemSpyObjectIx_Wait( handles );
+            //
+            TInt searchResult = handles->At( aHandleToLookFor );
+	        if  ( searchResult != KErrNotFound )
 		        {
                 TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::SearchThreadsFor - found handle match in [%O]", thread ));
                 aStream.WriteUint32( (TUint32) thread );
                 ++matches;
 		        }
+            //
+            MemSpyObjectIx_Signal( handles );
             }
         }
 
@@ -999,13 +1151,17 @@
 
         if  ( handles != NULL )
             {
-            TBool found = handles->Find( aHandleToLookFor );
-	        if  ( found )
+            MemSpyObjectIx_Wait( handles );
+            //
+            TInt searchResult = handles->At( aHandleToLookFor );
+	        if  ( searchResult != KErrNotFound )
 		        {
                 TRACE( Kern::Printf("DMemSpyDriverLogChanContainers::SearchProcessFor - found handle match in [%O]", process ));
                 aStream.WriteUint32( (TUint32) process );
                 ++matches;
 		        }
+            //
+            MemSpyObjectIx_Signal( handles );
             }
         }
 
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapBase.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapBase.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -47,6 +47,11 @@
 
 DMemSpyDriverLogChanHeapBase::~DMemSpyDriverLogChanHeapBase()
 	{
+	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::~DMemSpyDriverLogChanHeapBase() - START - this: 0x%08x", this ));
+
+    ReleaseFreeCells();
+
+	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::~DMemSpyDriverLogChanHeapBase() - END - this: 0x%08x", this ));
 	}
 
 
@@ -168,14 +173,243 @@
 
 
 
+TInt DMemSpyDriverLogChanHeapBase::OpenUserHeap( DThread& aClientThread, TUint aExpectedHeapVTable, RMemSpyDriverRHeapUser& aHeap, DChunk*& aUserHeapChunk, TDes8* aClientHeapChunkName )
+    {
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap() - START - aHeap.ChunkIsInitialised: %d, aExpectedHeapVTable: 0x%08x, aClientThread: %O", aHeap.ChunkIsInitialised(), aExpectedHeapVTable, &aClientThread ));
+    __ASSERT_ALWAYS( aHeap.ChunkIsInitialised() == EFalse, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapChunkAlreadyCloned ) );
+
+    TInt r = KErrNotFound;
+    aUserHeapChunk = NULL;
+    
+    NKern::ThreadEnterCS();
+
+    const TBool allocatorIsReallyRHeap = GetUserHeapHandle( aClientThread, aHeap, aExpectedHeapVTable );
+	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - allocatorIsReallyRHeap: %d", allocatorIsReallyRHeap));
+
+    if  ( allocatorIsReallyRHeap )
+        {
+        RAllocator* allocator = OSAdaption().DThread().GetAllocator( aClientThread );
+
+        // Open client's heap chunk in order to read it's dimensions
+        const TInt clientsHeapChunkHandle = aHeap.iChunkHandle;
+	    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - clientsHeapChunkHandle: 0x%08x, allocatorAddress: 0x%08x", clientsHeapChunkHandle, allocator));
+
+ 	    NKern::LockSystem();
+        DChunk* clientsHeapChunk = (DChunk*) Kern::ObjectFromHandle( &aClientThread, clientsHeapChunkHandle, EChunk );
+        NKern::UnlockSystem();
+	    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - clientsHeapChunk: 0x%08x", clientsHeapChunk ));
+       
+        if  ( clientsHeapChunk != NULL )
+            {
+            // Get the chunk name (if the caller asked for it)
+            if  ( aClientHeapChunkName )
+                {
+                clientsHeapChunk->FullName( *aClientHeapChunkName );
+                }
+                
+            // Update the heap chunk pointer. We do this now because this
+            // should point to the _real_ user-side heap chunk, rather than
+            // the copy of the chunk that we are about to make.
+            aUserHeapChunk = clientsHeapChunk;
+
+            // Set up ourselves to duplicate their heap chunk
+            const TInt clientsHeapChunkSize = OSAdaption().DChunk().GetSize( *clientsHeapChunk );
+	        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - chunkBase: 0x%08x, size: %8d, maxLen: %8d, chunk: %O", clientsHeapChunk->iBase, clientsHeapChunkSize, clientsHeapChunk->iMaxSize, clientsHeapChunk ));
+
+            // Make a new chunk that is the same size, owned by this thread.
+            TChunkCreateInfo info;
+            info.iType         = TChunkCreateInfo::ESharedKernelSingle;
+            info.iMaxSize      = clientsHeapChunkSize;
+            info.iOwnsMemory   = ETrue; // Use memory from system's free pool
+            info.iDestroyedDfc = NULL;
+        #ifdef __EPOC32__
+            info.iMapAttr      = (TInt)EMapAttrFullyBlocking; // Full caching
+        #endif
+
+            // Holds a copy of the client's heap chunk
+            DChunk* heapCopyChunk;
+            TLinAddr heapCopyChunkAddress;
+            TUint32 heapCopyChunkMappingAttributes;
+            r = Kern::ChunkCreate( info, heapCopyChunk, heapCopyChunkAddress, heapCopyChunkMappingAttributes );
+	        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - creating chunk returned: %d", r));
+            //
+            if  ( r == KErrNone )
+                {
+	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - copy chunk base: 0x%08x, heapCopyChunkAddress: 0x%08x", heapCopyChunk->iBase, heapCopyChunkAddress));
+                
+                // Commit memory for entire buffer
+                TUint32 physicalAddress = 0;
+                r = Kern::ChunkCommitContiguous( heapCopyChunk, 0, clientsHeapChunkSize, physicalAddress );
+	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - commiting chunk returned: %d", r));
+
+                if  ( r != KErrNone)
+                    {
+                    // On error, thow away the chunk we have created
+                    Kern::ChunkClose( heapCopyChunk );
+                    heapCopyChunk = NULL;
+                    }
+                else
+                    {
+    	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - heapCopyChunk->iSize: 0x%08x, heapCopyChunk->iBase: 0x%08x, heapCopyChunkAddress: 0x%08x, physicalAddress: 0x%08x", heapCopyChunk->iSize, heapCopyChunk->iBase, heapCopyChunkAddress, physicalAddress));
+    
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - trying to copy %d bytes from clients allocator address of 0x%08x", clientsHeapChunkSize, allocator ));
+                    r = Kern::ThreadRawRead( &aClientThread, allocator, (TAny*) heapCopyChunkAddress, clientsHeapChunkSize );
+
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - read result of clients heap data is: %d", r));
+                    if  ( r == KErrNone )
+                        {
+                        // Transfer ownership of the copy heap chunk to the heap object. This also calculates the delta
+                        // beween the heap addresses in the client's address space and the kernel address space.
+                        aHeap.AssociateWithKernelChunk( heapCopyChunk, heapCopyChunkAddress, heapCopyChunkMappingAttributes );
+                        }
+                    }
+                }
+            }
+        else
+            {
+	        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - could not open clients heap chunk by its handle" ) );
+            r = KErrNotFound;
+            }
+        }
+    else
+        {
+	    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - clients heap is not an RHeap (allocated vTable mismatch)" ) );
+        r = KErrNotSupported;
+        }
+
+    NKern::ThreadLeaveCS();
+
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenUserHeap - r: %d", r ));
+    return r;
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+TBool DMemSpyDriverLogChanHeapBase::GetUserHeapHandle( DThread& aThread, RMemSpyDriverRHeapUser& aHeap, TUint aExpectedVTable )
+    {
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetUserHeapHandle() - START - aExpectedVTable: 0x%08x", aExpectedVTable) );
+
+    RAllocator* allocator = OSAdaption().DThread().GetAllocator( aThread );
+	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetUserHeapHandle - allocator addr: 0x%08x", allocator) );
+    TUint* pAllocator = (TUint*) allocator;
+    // 
+    TBool vTableOkay = EFalse;
+    TUint vtable = 0;
+
+    // Read a bit more data than is available for debugging purposes
+    TBuf8<32> vtableBuf;
+    TInt r = Kern::ThreadRawRead( &aThread, pAllocator, (TUint8*) vtableBuf.Ptr(), vtableBuf.MaxLength() );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetUserHeapHandle - read result of vtable data from requested thread is: %d", r));
+    if  ( r == KErrNone )
+        {
+        TRACE( MemSpyDriverUtils::DataDump("allocator vtable data - %lS", vtableBuf.Ptr(), vtableBuf.MaxLength(), vtableBuf.MaxLength() ) );
+        vtableBuf.SetLength( vtableBuf.MaxLength() );
+        
+        vtable = vtableBuf[0] +
+                (vtableBuf[1] << 8) + 
+                (vtableBuf[2] << 16) + 
+                (vtableBuf[3] << 24);
+        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetUserHeapHandle - client VTable is: 0x%08x", vtable) );
+
+        // Check the v-table to work out if it really is an RHeap
+        vTableOkay = ( vtable == aExpectedVTable );
+        if  ( vTableOkay )
+            {
+            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetUserHeapHandle - vtables okay") );
+            r = aHeap.ReadFromUserAllocator( aThread );
+            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetUserHeapHandle - after userget, error: %d", r));
+        
+            }
+        else
+            {
+            TRACE( Kern::Printf( "DMemSpyDriverLogChanHeapBase::GetUserHeapHandle - vtables dont match! - aExpectedVTable: 0x%08x, allocator addr: 0x%08x, client VTable is: 0x%08x, aThread: %O", aExpectedVTable, allocator, vtable, &aThread ) );
+            }
+        }
+    else
+        {
+        TRACE( Kern::Printf( "DMemSpyDriverLogChanHeapBase::GetUserHeapHandle - error during client vTable reading: %d, aThread: %O", r, &aThread ) );
+        }
+    //
+    return (vTableOkay && (r == KErrNone));
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 void DMemSpyDriverLogChanHeapBase::PrintHeapInfo( const TMemSpyHeapInfo& aInfo )
     {
     const TMemSpyHeapInfoRHeap& rHeapInfo = aInfo.AsRHeap();
-    //const TMemSpyHeapObjectDataRHeap& rHeapObjectData = rHeapInfo.ObjectData();
+    const TMemSpyHeapObjectDataRHeap& rHeapObjectData = rHeapInfo.ObjectData();
     const TMemSpyHeapStatisticsRHeap& rHeapStats = rHeapInfo.Statistics();
     const TMemSpyHeapMetaDataRHeap& rHeapMetaData = rHeapInfo.MetaData();
 
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RAllocator                                      -" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RAllocator::iAccessCount:       %d", rHeapObjectData.iAccessCount ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RAllocator::iHandleCount:       %d", rHeapObjectData.iHandleCount ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RAllocator::iHandles:           0x%08x", rHeapObjectData.iHandles ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RAllocator::iFlags:             0x%08x", rHeapObjectData.iFlags ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RAllocator::iCellCount:         %d", rHeapObjectData.iCellCount ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RAllocator::iTotalAllocSize:    %d", rHeapObjectData.iTotalAllocSize ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - " ) );
+
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap                                           -" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iMinLength:              %d", rHeapObjectData.iMinLength ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iMaxLength:              %d", rHeapObjectData.iMaxLength ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iOffset:                 %d", rHeapObjectData.iOffset ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iGrowBy:                 %d", rHeapObjectData.iGrowBy ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iChunkHandle:            0x%08x", rHeapObjectData.iChunkHandle ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iBase:                   0x%08x", rHeapObjectData.iBase ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iTop:                    0x%08x", rHeapObjectData.iTop ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iAlign:                  %d", rHeapObjectData.iAlign ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iMinCell:                %d", rHeapObjectData.iAlign ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iPageSize:               %d", rHeapObjectData.iAlign ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iFree.next:              0x%08x", rHeapObjectData.iFree.next ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iFree.len:               %d", rHeapObjectData.iFree.len ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iNestingLevel:           %d", rHeapObjectData.iNestingLevel ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iAllocCount:             %d", rHeapObjectData.iAllocCount ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iFailType:               %d", rHeapObjectData.iFailType ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iFailRate:               %d", rHeapObjectData.iFailRate ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iFailed:                 %d", rHeapObjectData.iFailed ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iFailAllocCount:         %d", rHeapObjectData.iFailAllocCount ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iRand:                   %d", rHeapObjectData.iRand ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - RHeap::iTestData:               0x%08x", rHeapObjectData.iTestData ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - " ) );
+
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - Stats (Free)                                    -" ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - cell count:                     %d", rHeapStats.StatsFree().TypeCount() ) );
@@ -197,6 +431,12 @@
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - " ) );
 
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - Stats (Common)                                  -" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - total cell count:               %d", rHeapStats.StatsCommon().TotalCellCount() ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - " ) );
+
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - Misc. Info                                      -" ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() ---------------------------------------------------" ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - chunk size:                     %d", rHeapMetaData.ChunkSize() ) );
@@ -205,17 +445,73 @@
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - debug allocator:                %d", rHeapMetaData.IsDebugAllocator() ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - shared heap:                    %d", rHeapMetaData.IsSharedHeap() ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - user thread:                    %d", rHeapMetaData.IsUserThread() ) );
-    //TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - cell header size (free):        %d", rHeapMetaData.HeaderSizeFree() ) );
-    //TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - cell header size (alloc):       %d", rHeapMetaData.HeaderSizeAllocated() ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - cell header size (free):        %d", rHeapMetaData.HeaderSizeFree() ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - cell header size (alloc):       %d", rHeapMetaData.HeaderSizeAllocated() ) );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - heap vTable:                    0x%08x", rHeapMetaData.VTable() ) );
-    //TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - heap object size:               %d", rHeapMetaData.ClassSize() ) );
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - heap size:                      %d", rHeapMetaData.iHeapSize ) );
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - allocator address:              0x%08x", rHeapMetaData.iAllocatorAddress ) );
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - min heap size:                  %d", rHeapMetaData.iMinHeapSize ) );
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - max heap size:                  %d", rHeapMetaData.iMaxHeapSize ) );
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrintHeapInfo() - heap object size:               %d", rHeapMetaData.ClassSize() ) );
     }
 
-TInt DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel(RMemSpyDriverRHeapBase& aHeap, TMemSpyHeapInfo* aHeapInfo, TDes8* aTransferBuffer )
+
+
+
+
+
+
+
+
+
+TBool DMemSpyDriverLogChanHeapBase::IsDebugKernel()
+    {
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::IsDebugKernel() - START") );
+    
+    TInt r = KErrNone;
+    TBool debugKernel = EFalse;
+
+    NKern::ThreadEnterCS();
+    RMemSpyDriverRHeapKernelInPlace rHeap;
+    r = OpenKernelHeap( rHeap );
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::IsDebugKernel() - open kernel heap returned: %d", r) );
+
+    if  ( r == KErrNone )
+        {
+        debugKernel = IsDebugKernel( rHeap );
+
+        // Tidy up
+        rHeap.DisassociateWithKernelChunk();
+        }
+
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::IsDebugKernel() - debugKernel: %d", debugKernel) );
+    NKern::ThreadLeaveCS();
+
+ 	TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::IsDebugKernel() - END - ret: %d", r) );
+    return debugKernel;
+    }
+
+
+TBool DMemSpyDriverLogChanHeapBase::IsDebugKernel( RMemSpyDriverRHeapKernelInPlace& aHeap )
+    {
+    TBool debugKernel = EFalse;
+    //
+ 	TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::IsDebugKernel() - START") );
+    NKern::ThreadEnterCS();
+
+    // Request that the kernel fail the next heap allocation
+    aHeap.FailNext();
+
+    // Allocate a new cell, and in debug builds of the kernel, this should be NULL
+    TInt* cell = new TInt();
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::IsDebugKernel() - cell: 0x%08x", cell) );
+    debugKernel = ( cell == NULL );
+    delete cell;
+
+    NKern::ThreadLeaveCS();
+ 	TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::IsDebugKernel() - END - debugKernel: %d", debugKernel) );
+    //
+    return debugKernel;
+    }
+
+
+TInt DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel( RMemSpyDriverRHeapBase& aHeap, TBool aIsDebugAllocator, const TDesC8& aChunkName, TMemSpyHeapInfo* aHeapInfo, TDes8* aTransferBuffer )
     {
     TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel() - START - aTransferBuffer: 0x%08x", aTransferBuffer ) );
 
@@ -224,13 +520,16 @@
 
     // This object holds all of the info we will accumulate for the client.
     TMemSpyHeapInfo masterHeapInfo;
-    masterHeapInfo.SetType(aHeap.GetTypeFromHelper());
+    masterHeapInfo.SetType( TMemSpyHeapInfo::ETypeRHeap );
     masterHeapInfo.SetTid( 2 );
     masterHeapInfo.SetPid( 1 );
 
     // This is the RHeap-specific object that contains all RHeap info
     TMemSpyHeapInfoRHeap& rHeapInfo = masterHeapInfo.AsRHeap();
 
+    // This is the object data for the RHeap instance
+    TMemSpyHeapObjectDataRHeap& rHeapObjectData = rHeapInfo.ObjectData();
+    aHeap.CopyObjectDataTo( rHeapObjectData );
 
     // When walking the kernel heap we must keep track of the free cells
     // without allocating any more memory (on the kernel heap...)
@@ -245,7 +544,7 @@
 
     // We must walk the client's heap in order to build statistics
     TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - calling heap walker constructor..."));
-    RMemSpyDriverHeapWalker heapWalker(aHeap);
+    RMemSpyDriverHeapWalker heapWalker( aHeap, aIsDebugAllocator );
     if  ( aTransferBuffer )
         {
         // This will allow us to identify that we're writing directly to the stream
@@ -265,6 +564,10 @@
         TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - not collecting free cells"));
         }
 
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - locking system..." ));
+    NKern::LockSystem();
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - disabling interrupts..." ));
+    const TInt irq = NKern::DisableAllInterrupts();
     TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - starting traversal..." ));
 
 #if defined( TRACE_TYPE_KERNELHEAP )
@@ -272,8 +575,11 @@
 #endif
     r = heapWalker.Traverse();
 
-    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - finished traversal - err: %d, iStackStream: 0x%08x, pCount: 0x%08x, isOpen: %d", 
-                            r, iStackStream, pCount, ( iStackStream == NULL ? 0 : iStackStream->IsOpen() ) ));
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - restoring interrupts..." ));
+    NKern::RestoreInterrupts( irq );
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - finished traversal - err: %d, iStackStream: 0x%08x, pCount: 0x%08x, isOpen: %d", r, iStackStream, pCount, ( iStackStream == NULL ? 0 : iStackStream->IsOpen() ) ));
+    NKern::UnlockSystem();
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel - unlocked system" ));
 
     // Write free cells if requested
     if  ( r == KErrNone && iStackStream && iStackStream->IsOpen() && pCount )
@@ -290,19 +596,18 @@
 
     // Get remaining meta data that isn't stored elsewhere
     TMemSpyHeapMetaDataRHeap& rHeapMetaData = rHeapInfo.MetaData();
-	TFullName chunkName;
-	aHeap.Chunk().FullName(chunkName);
-    rHeapMetaData.SetChunkName(chunkName);
+    rHeapMetaData.SetChunkName( aChunkName );
     rHeapMetaData.SetChunkSize( (TUint) aHeap.Chunk().Size() );
     rHeapMetaData.SetChunkHandle( &aHeap.Chunk() );
-    rHeapMetaData.SetChunkBaseAddress( OSAdaption().DChunk().GetBase(aHeap.Chunk()) );
-    rHeapMetaData.SetDebugAllocator(aHeap.Helper()->AllocatorIsUdeb());
+    rHeapMetaData.SetChunkBaseAddress( aHeap.Chunk().Base() );
+    rHeapMetaData.SetDebugAllocator( aIsDebugAllocator );
+    rHeapMetaData.SetHeaderSizeFree( RMemSpyDriverRHeapBase::FreeCellHeaderSize() );
+    rHeapMetaData.SetHeaderSizeAllocated( RMemSpyDriverRHeapBase::AllocatedCellHeaderSize( aIsDebugAllocator ) );
     rHeapMetaData.SetUserThread( EFalse );
     rHeapMetaData.SetSharedHeap( ETrue );
-	rHeapMetaData.iHeapSize = aHeap.Helper()->CommittedSize();
-	rHeapMetaData.iAllocatorAddress = (TAny*)aHeap.Helper()->AllocatorAddress();
-	rHeapMetaData.iMinHeapSize = aHeap.Helper()->MinCommittedSize();
-	rHeapMetaData.iMaxHeapSize = aHeap.Helper()->MaxCommittedSize();
+
+    // Get any heap-specific info
+    aHeap.GetHeapSpecificInfo( masterHeapInfo );
 
     PrintHeapInfo( masterHeapInfo );
 
@@ -336,12 +641,17 @@
 
 
 
-TBool DMemSpyDriverLogChanHeapBase::HandleHeapCell(TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt /*aNestingLevel*/, TInt /*aAllocNumber*/)
+TBool DMemSpyDriverLogChanHeapBase::HandleHeapCell( TInt aCellType, TAny* aCellAddress, TInt aLength, TInt /*aNestingLevel*/, TInt /*aAllocNumber*/ )
     {
     TInt error = KErrNone;
     //
-    if  (aCellType & EMemSpyDriverFreeCellMask)
+    if  ( aCellType == EMemSpyDriverGoodFreeCell || aCellType == EMemSpyDriverBadFreeCellAddress || aCellType == EMemSpyDriverBadFreeCellSize )
         {
+        TMemSpyDriverFreeCell cell;
+        cell.iType = aCellType;
+        cell.iAddress = aCellAddress;
+        cell.iLength = aLength;
+        //
         if  ( iStackStream )
             {
             if  ( !iStackStream->IsFull() )
@@ -359,16 +669,163 @@
                 error = KErrAbort;
                 }
             }
-       }
+        else
+            {
+            NKern::ThreadEnterCS();
+            error = iFreeCells.Append( cell );
+            NKern::ThreadLeaveCS();
+            //
+            if ( error == KErrNone )
+                {
+                ++iFreeCellCount;
+                }
+            }
+        }
     //
     return ( error == KErrNone );
     }
 
 
 void DMemSpyDriverLogChanHeapBase::HandleHeapWalkInit()
-	{
-	iFreeCellCount = 0;
-	}
+    {
+    // Can't delete the free cell list here as we might be walking the kernel heap
+    iFreeCellCount = 0;
+    }
+
+
+
+
+
+
+TInt DMemSpyDriverLogChanHeapBase::PrepareFreeCellTransferBuffer()
+    {
+    // Transfer free cells immediately from xfer stream
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrepareFreeCellTransferBuffer() - START - iHeapStream: 0x%08x", iHeapStream ));
+    __ASSERT_ALWAYS( !iHeapStream, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapFreeCellStreamNotClosed ) );
+    //
+    TInt r = KErrNoMemory;
+    //
+    NKern::ThreadEnterCS();
+    //
+    iHeapStream = new RMemSpyMemStreamWriter();
+    if  ( iHeapStream )
+        {
+        const TInt requiredMemory = CalculateFreeCellBufferSize();
+        r = OpenXferStream( *iHeapStream, requiredMemory );
+        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrepareFreeCellTransferBuffer() - requested %d bytes for free cell list, r: %d", requiredMemory, r ));
+
+        if  ( r == KErrNone )
+            {
+            const TInt count = iFreeCells.Count();
+            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrepareFreeCellTransferBuffer() - free cell count: %d", count ));
+            //
+            iHeapStream->WriteInt32( count );
+            for( TInt i=0; i<count; i++ )
+                {
+                const TMemSpyDriverFreeCell& cell = iFreeCells[ i ];
+                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrepareFreeCellTransferBuffer() - storing entry: %d", i ));
+                //
+                iHeapStream->WriteInt32( cell.iType );
+                iHeapStream->WriteUint32( reinterpret_cast<TUint32>( cell.iAddress ) );
+                iHeapStream->WriteInt32( cell.iLength );
+                }
+
+            // Finished with the array now
+            iFreeCells.Reset();
+
+            // We return the amount of client-side memory that needs to be allocated to hold the buffer
+            r = requiredMemory;
+            }
+        }
+    //
+    NKern::ThreadLeaveCS();
+               
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::PrepareFreeCellTransferBuffer() - END - r: %d", r));
+	return r;
+    }
+
+
+TInt DMemSpyDriverLogChanHeapBase::FetchFreeCells( TDes8* aBufferSink )
+    {
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::FetchFreeCells() - START - iHeapStream: 0x%08x", iHeapStream ));
+    __ASSERT_ALWAYS( iHeapStream, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapFreeCellStreamNotOpen ) );
+
+    TInt r = KErrNone;
+
+    // Write buffer to client
+    NKern::ThreadEnterCS();
+    r = iHeapStream->WriteAndClose( aBufferSink );
+
+    // Tidy up
+    ReleaseFreeCells();
+
+    NKern::ThreadLeaveCS();
+    //
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::FetchFreeCells() - END - r: %d", r));
+	return r;
+    }
+
+
+
+TInt DMemSpyDriverLogChanHeapBase::CalculateFreeCellBufferSize() const
+    {
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::CalculateFreeCellBufferSize() - START" ));
+
+    const TInt count = iFreeCells.Count();
+    const TInt entrySize = sizeof( TInt32 ) + sizeof( TInt32 ) + sizeof( TUint32 );
+    const TInt r = ( count * entrySize ) + sizeof( TInt ); // Extra TInt to hold count
+                
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::CalculateFreeCellBufferSize() - END - r: %d, count: %d, entrySize: %d", r, count, entrySize ));
+	return r;
+    }
+
+
+
+void DMemSpyDriverLogChanHeapBase::ReleaseFreeCells()
+    {
+	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::ReleaseFreeCells() - START - this: 0x%08x", this ));
+
+    // Housekeeping
+    NKern::ThreadEnterCS();
+    iFreeCells.Reset();
+    //
+    iStackStream = NULL;
+    //
+    delete iHeapStream;
+    iHeapStream = NULL;
+    NKern::ThreadLeaveCS();
+
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapBase::ReleaseFreeCells() - END - this: 0x%08x", this ));
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 
 TInt DMemSpyDriverLogChanHeapBase::OpenKernelHeap( RHeapK*& aHeap, DChunk*& aChunk, TDes8* aClientHeapChunkName )
     {
@@ -448,7 +905,7 @@
         // Finalise construction of heap 
         if  ( kernelHeap != NULL )
             {
-            TRACE_KH( Kern::Printf( "DMemSpyDriverLogChanHeapBase::OpenKernelHeap - kernelHeapChunk->Base(): 0x%08x", kernelHeapChunk->Base() ) );
+            TRACE_KH( Kern::Printf( "DMemSpyDriverLogChanHeapBase::OpenKernelHeap - kernelHeap->Base(): 0x%08x, kernelHeapChunk->Base(): 0x%08x", kernelHeap->Base(), kernelHeapChunk->Base() ) );
             aHeap = kernelHeap;
             aChunk = kernelHeapChunk;
 
@@ -478,6 +935,27 @@
     return r;
     }
 
+
+TInt DMemSpyDriverLogChanHeapBase::OpenKernelHeap( RMemSpyDriverRHeapKernelInPlace& aHeap, TDes8* aClientHeapChunkName )
+    {
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenKernelHeap(IP) - START") );
+
+    RHeapK* heap = NULL;
+    DChunk* chunk = NULL;
+    TInt r = OpenKernelHeap( heap, chunk, aClientHeapChunkName );
+	
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenKernelHeap(IP) - open err: %d", r ) );
+    if  ( r == KErrNone )
+        {
+        aHeap.SetKernelHeap( *heap );
+        aHeap.AssociateWithKernelChunk( chunk, TLinAddr( chunk->iBase ), 0 );
+        }
+
+	TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenKernelHeap(IP) - END - ret: %d", r ) );
+    return r;
+    }
+
+
 TInt DMemSpyDriverLogChanHeapBase::OpenKernelHeap( RMemSpyDriverRHeapKernelFromCopy& aHeap, TDes8* aClientHeapChunkName )
     {
     TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenKernelHeap(CP) - START") );
@@ -539,7 +1017,7 @@
                 NKern::LockSystem();
                 const TUint32 copyLength = heapSize; // TODO Min( heap->Size(), heapSize );
 
-                TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenKernelHeap(CP) - trying to copy %d (vs orig estimate of %d) bytes from kernel allocator address: 0x%08x", copyLength, heapSize, heap));
+                TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapBase::OpenKernelHeap(CP) - trying to copy %d (vs orig estimate of %d) bytes from kernel allocator address: 0x%08x", copyLength, heapSize, heap->Base() ));
                 memcpy( (TUint8*) heapCopyChunkAddress, heap, copyLength );
 
                 NKern::UnlockSystem();
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapData.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapData.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -162,21 +162,25 @@
     //
     // The driver leaves kernel context with the copy of the kernel heap still associated with MemSpy's process.
     // The second driver call will copy the chunk data to user side and release the kernel side chunk.
-    //const TBool isInit = iKernelHeap.ChunkIsInitialised();
-    //TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataKernelInit() - START - isInit: %d", isInit ));
-    //__ASSERT_ALWAYS( !isInit, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicKernelHeapDataInitError ) );
+    const TBool isInit = iKernelHeap.ChunkIsInitialised();
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataKernelInit() - START - isInit: %d", isInit ));
+    __ASSERT_ALWAYS( !isInit, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicKernelHeapDataInitError ) );
 
     iKernelHeap.Reset();
     NKern::ThreadEnterCS();
 
+    // We must identify if we have a debug kernel allocator
+    const TBool debugAllocator = IsDebugKernel();
+    TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataKernelInit() - debugAllocator: %d", debugAllocator ) );
+
     TFullName heapChunkName;
     TInt r = OpenKernelHeap( iKernelHeap, &heapChunkName );
     TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataKernelInit() - open err: %d", r));
 
     if  ( r == KErrNone )
         {
-        r = GetHeapInfoKernel( iKernelHeap, aInfo, aFreeCells );
-        TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapDataKernelInit() - base class get heap info: %d", r) );
+        r = GetHeapInfoKernel( iKernelHeap, debugAllocator, heapChunkName, aInfo, aFreeCells );
+        TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - base class get heap info: %d", r) );
 
         // If everything was okay, we can now return back to user-side, indicating the amount of heap data
         // that they must prepare to read (in the next operation).
@@ -184,12 +188,12 @@
             {
             // Indicate how big a buffer the user-side must prepare.
             r = OSAdaption().DChunk().GetSize( iKernelHeap.Chunk() );
-            TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapDataKernelInit() - user side buffer needs to be: %d", r) );
+            TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - user side buffer needs to be: %d", r) );
             }
-        else
+        else if ( iKernelHeap.ChunkIsInitialised() )
             {
             // Error scenario - must close heap
-            iKernelHeap.Close();
+            iKernelHeap.DisassociateWithKernelChunk();
             }
         }
 
@@ -202,15 +206,12 @@
 
 TInt DMemSpyDriverLogChanHeapData::GetHeapDataKernelFetch( TDes8* aSink )
     {
-	//TOMSCI TODO this function is fundamentally flawed
-	return KErrNotSupported;
-	/*
     TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataKernelFetch() - START"));
 
     NKern::ThreadEnterCS();
 
     // We should already have an initialised copy of the kernel heap
-    const TBool isInit = iKernelHeap.Helper() != NULL;
+    const TBool isInit = iKernelHeap.ChunkIsInitialised();
     TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataKernelFetch() - isInit: %d", isInit ));
     __ASSERT_ALWAYS( isInit, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicKernelHeapDataFetchError ) );
 
@@ -260,7 +261,6 @@
 
 	TRACE_KH( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataKernelFetch() - END - ret: %d", r));
     return r;
-	*/
     }
 
 
@@ -279,7 +279,7 @@
 
 
 
-const TInt KPageSize = 4096;
+
 
 TInt DMemSpyDriverLogChanHeapData::GetHeapDataUser( TMemSpyDriverInternalHeapDataParams& aParams )
     {
@@ -304,110 +304,135 @@
 		    return KErrAccessDenied;
             }
         }
-
+    
     // Check that the process' thread's are suspended
     DThread* thread = (DThread*) TempObject();
     if  ( SuspensionManager().IsSuspended( *thread ) )
         {
-        // Open the heap
+        // Find the chunk with the correct handle
 	    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - thread: %O", thread) );
         RMemSpyDriverRHeapUser heap( OSAdaption() );
-		r = heap.OpenUserHeap(*thread, aParams.iDebugAllocator);
-		TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - opening heap returned: %d", r) );
-        if  (r == KErrNone)
+        const TBool allocatorIsReallyRHeap = GetUserHeapHandle( *thread, heap, aParams.iRHeapVTable );
+        if  ( allocatorIsReallyRHeap )
             {
-            if  ( aParams.iChecksum != 0 )
+            const TInt chunkHandle = heap.iChunkHandle;
+	        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - chunkHandle: 0x%08x, thread: %O", chunkHandle, thread) );
+
+  	        NKern::ThreadEnterCS();
+ 	        NKern::LockSystem();
+            DChunk* chunk = (DChunk*) Kern::ObjectFromHandle( thread, chunkHandle, EChunk );
+            NKern::UnlockSystem();
+	        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - chunk: 0x%08x", chunk ) );
+  	        NKern::ThreadLeaveCS();
+
+            if  ( chunk != NULL )
                 {
-                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - checksum validation requested - expecting: 0x%08x", aParams.iChecksum ) );
-                RMemSpyDriverHeapWalker heapWalker(heap);
-                
-                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - starting traversal..." ));
-#if ( defined( TRACE_TYPE_USERHEAP ) && defined( TRACE_TYPE_HEAPWALK ) )
-                heapWalker.SetPrintDebug();
-#endif
-                r = heapWalker.Traverse();
-                const TUint32 calculatedChecksum = heapWalker.Stats().iFreeCellCRC;
-                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - finished traversal - err: %d, checksum: 0x%08x", r, calculatedChecksum ));
+                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - chunkBase: 0x%08x, size: %8d, maxLen: %8d, chunk: %O", chunk->iBase, chunk->iSize, chunk->iMaxSize, chunk) );
+
+                // If the client specified a checksum value, then we must walk the heap just to make sure
+                // it hasn't changed. Expensive operation, but good for paranoia purposes...
+                if  ( aParams.iChecksum != 0 )
+                    {
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - checksum validation requested - expecting: 0x%08x", aParams.iChecksum ) );
 
-                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - comparing CALCULATED: 0x%08x vs EXPECTED: 0x%08x", calculatedChecksum, aParams.iChecksum ));
-                if  ( calculatedChecksum != aParams.iChecksum )
-                    {
-                    Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - comparing CALCULATED: 0x%08x vs EXPECTED: 0x%08x for thread %O", calculatedChecksum, aParams.iChecksum, thread );
-                    r = KErrCorrupt;
-                    }
-                }
+                    RMemSpyDriverRHeapUser rHeap( OSAdaption() );
+                    DChunk* userHeapChunk = NULL;
+                    r = OpenUserHeap( *thread, aParams.iRHeapVTable, rHeap, userHeapChunk );
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - opening client heap returned: %d", r) );
+                    if  ( r == KErrNone )
+                        {
+                        TMemSpyHeapWalkerNullObserver observer; 
+                        RMemSpyDriverHeapWalker heapWalker( rHeap, aParams.iDebugAllocator );
+                        heapWalker.SetObserver( &observer );
+                        
+                        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - starting traversal..." ));
+#if ( defined( TRACE_TYPE_USERHEAP ) && defined( TRACE_TYPE_HEAPWALK ) )
+                        heapWalker.SetPrintDebug();
+#endif
+                        r = heapWalker.Traverse();
+                        const TUint32 calculatedChecksum = heapWalker.Stats().iFreeCellCRC;
+                        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - finished traversal - err: %d, checksum: 0x%08x", r, calculatedChecksum ));
 
-            // Get user side (MemSpy) descriptor length info
-            if  ( r == KErrNone )
-                {
-                TInt destLen = 0;
-                TInt destMax = 0;
-                TUint8* destPtr = NULL;
-                r = Kern::ThreadGetDesInfo( &ClientThread(), aParams.iDes, destLen, destMax, destPtr, ETrue );
-                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - user side descriptor: 0x%08x (0x%08x), len: %8d, maxLen: %8d, r: %d", aParams.iDes, destPtr, destLen, destMax, r ));
-				destMax = destMax & ~(KPageSize-1); // Round down dest max to page size
-				if (destMax <= 0 || (aParams.iReadAddress & (KPageSize-1))) r = KErrArgument; // If destMax is less than a page or the read address isn't a multiple of page size then we don't want to know
+                        // Release resources
+                        rHeap.DisassociateWithKernelChunk();
 
+                        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - comparing CALCULATED: 0x%08x vs EXPECTED: 0x%08x", calculatedChecksum, aParams.iChecksum ));
+                        if  ( calculatedChecksum != aParams.iChecksum )
+                            {
+                            Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - comparing CALCULATED: 0x%08x vs EXPECTED: 0x%08x for thread %O", calculatedChecksum, aParams.iChecksum, thread );
+                            r = KErrCorrupt;
+                            }
+                        }
+                    else
+                        {
+                        // Couldn't verify checksum in this situation...
+                        }
+                    }
+
+                // Get user side (MemSpy) descriptor length info
                 if  ( r == KErrNone )
                     {
-					const TLinAddr chunkBase = (TLinAddr)OSAdaption().DChunk().GetBase(heap.Chunk());
-					const TLinAddr chunkMaxAddr = chunkBase + OSAdaption().DChunk().GetMaxSize(heap.Chunk());
-        	        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - chunkBase:    0x%08x", chunkBase) );
-        
-					TLinAddr readAddress = aParams.iReadAddress;
-                    if (aParams.iRemaining < 0 )
-                        {
-                        // Initial case, start from the bottom
-                        readAddress = chunkBase;
-						aParams.iRemaining = heap.Helper()->CommittedSize();
-                        }
+                    TInt destLen;
+                    TInt destMax;
+                    TUint8* destPtr = NULL;
+                    r = Kern::ThreadGetDesInfo( &ClientThread(), aParams.iDes, destLen, destMax, destPtr, ETrue );
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - user side descriptor: 0x%08x (0x%08x), len: %8d, maxLen: %8d, r: %d", aParams.iDes, destPtr, destLen, destMax, r ));
 
-                    // The remaining number of bytes should allow us to calculate the position
-                    // to read from.
-                    TInt amountToRead = Min( aParams.iRemaining, destMax );
-        	        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - amountToRead:           %8d", amountToRead) );
-        
-                    // Do the read from the heap we are spying on into MemSpy's address space
-					// TomS: I didn't know you could do this - you live and learn
-					do
-						{
-						r = Kern::ThreadRawRead( thread, (const void*)readAddress, destPtr, amountToRead );
-        				TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - read result: %d", r) );
+                    if  ( r == KErrNone )
+                        {
+                        // Calculate start of real heap data (skipping over embedded RHeap object)
+                        const TUint8* startOfHeapOffset = heap.iBase;
+        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - startOfHeapOffset:    0x%08x", startOfHeapOffset) );
+            
+                        // Deal with initial case
+                        const TUint heapSize = heap.Size();
+        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - heapSize:               %8d", heapSize) );
+                        if  ( aParams.iRemaining < 0 )
+                            {
+                            // Initial case, remaining initialised to -1
+                            aParams.iRemaining = heapSize;
+                            }
 
-						if (r == KErrBadDescriptor)
-							{
-							// This is not necessarily an error - it could be we've hit an unmapped page
-							if (amountToRead > KPageSize)
-								{
-								// retry reading a single page instead
-								amountToRead = KPageSize;
-								}
-							else
-								{
-								// Try the next page
-								readAddress += KPageSize;
-								}
-							}
-						} while (r == KErrBadDescriptor && readAddress < chunkMaxAddr);
-                    //
-                    if  (r == KErrNone)
-                        {
-                        // Client takes care of updating descriptor length.
-                        r = amountToRead;
+                        // The remaining number of bytes should allow us to calculate the position
+                        // to read from.
+                        const TInt amountToRead = Min( aParams.iRemaining, destMax );
+        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - amountToRead:           %8d", amountToRead) );
+                        const TInt readOffset = ( heapSize - aParams.iRemaining );
+        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - readOffset:             %8d", readOffset) );
+                        const TAny* readAddress = startOfHeapOffset + readOffset;
+        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - readAddress:          0x%08x", readAddress) );
+            
+                        // Do the read from the heap we are spying on into MemSpy's address space
+                        r = Kern::ThreadRawRead( thread, readAddress, destPtr, amountToRead );
+        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - read result: %d", r) );
+                        //
+                        if  (r == KErrNone)
+                            {
+                            // Client takes care of updating descriptor length.
+                            r = amountToRead;
+                            }
+                        else if ( r == KErrBadDescriptor )
+                            {
+                            MemSpyDriverUtils::PanicThread( ClientThread(), EPanicBadDescriptor );
+                            }
+            
+                        // Update remaining bytes
+                        aParams.iRemaining -= amountToRead;
+                        aParams.iReadAddress = (TUint) readAddress;
                         }
-        
-                    // Update remaining bytes
-                    aParams.iRemaining -= amountToRead;
-                    aParams.iReadAddress = readAddress;
                     }
                 }
-			}
+            else
+                {
+    	        Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - chunk not found! thread: %O", thread );
+                r = KErrNotFound;
+                }
+            }
         else
             {
-    	    Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - couldnt open heap for thread %O, err=%d", thread, r);
+    	    Kern::Printf("DMemSpyDriverLogChanHeapData::GetHeapDataUser - couldnt find heap - vtable mis-match? thread: %O", thread );
             r = KErrNotSupported;
             }
-		heap.Close();
         }
     else
         {
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapInfo.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapInfo.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -46,18 +46,24 @@
 DMemSpyDriverLogChanHeapInfo::~DMemSpyDriverLogChanHeapInfo()
 	{
 	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::~DMemSpyDriverLogChanHeapInfo() - START - this: 0x%08x", this ));
-	ReleaseCellList();
 	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::~DMemSpyDriverLogChanHeapInfo() - END - this: 0x%08x", this ));
 	}
 
+
+
+
+
+
+
+
 TInt DMemSpyDriverLogChanHeapInfo::Request( TInt aFunction, TAny* a1, TAny* a2 )
 	{
 	TInt r = DMemSpyDriverLogChanHeapBase::Request( aFunction, a1, a2 );
     if  ( r == KErrNone )
         {
-        if  ( aFunction != EMemSpyDriverOpCodeHeapInfoFetchCellList )
+        if  ( aFunction != EMemSpyDriverOpCodeHeapInfoFetchFreeCells )
             {
-            ReleaseCellList();
+            ReleaseFreeCells();
             }
         //
         switch( aFunction )
@@ -69,10 +75,10 @@
             r = GetHeapInfoKernel( (TMemSpyDriverInternalHeapRequestParameters*) a1, (TDes8*) a2 );
             break;
         case EMemSpyDriverOpCodeHeapInfoGetIsDebugKernel:
-            r = GetIsDebugKernel(a1);
+            r = GetIsDebugKernel( (TBool*) a1 );
             break;
-        case EMemSpyDriverOpCodeHeapInfoFetchCellList:
-            r = FetchCellList( (TDes8*) a1 );
+        case EMemSpyDriverOpCodeHeapInfoFetchFreeCells:
+            r = FetchFreeCells( (TDes8*) a1 );
             break;
 
         default:
@@ -126,42 +132,50 @@
             DThread* thread = (DThread*) TempObject();
             if  ( SuspensionManager().IsSuspended( *thread ) )
                 {
+                TFullName chunkName;
+
                 // Open client's heap
                 RMemSpyDriverRHeapUser rHeap( OSAdaption() );
-				r = rHeap.OpenUserHeap(*thread, iHeapInfoParams.iDebugAllocator);
+                DChunk* userHeapChunk = NULL;
+                r = OpenUserHeap( *thread, iHeapInfoParams.iRHeapVTable, rHeap, userHeapChunk, &chunkName );
                 TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - opening client heap returned: %d", r) );
 
                 if  ( r == KErrNone )
                     {
                     // This object holds all of the info we will accumulate for the client.
                     TMemSpyHeapInfo masterHeapInfo;
-                    masterHeapInfo.SetType(rHeap.GetTypeFromHelper());
+                    masterHeapInfo.SetType( TMemSpyHeapInfo::ETypeRHeap );
                     masterHeapInfo.SetTid( iHeapInfoParams.iTid );
                     masterHeapInfo.SetPid( OSAdaption().DThread().GetOwningProcessId( *thread ) );
 
                     // This is the RHeap-specific object that contains all RHeap info
                     TMemSpyHeapInfoRHeap& rHeapInfo = masterHeapInfo.AsRHeap();
 
+                    // This is the object data for the RHeap instance
+                    TMemSpyHeapObjectDataRHeap& rHeapObjectData = rHeapInfo.ObjectData();
+                    rHeap.CopyObjectDataTo( rHeapObjectData );
 
                     // We must walk the client's heap in order to build statistics
                     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - calling heap walker constructor..."));
-					RMemSpyDriverHeapWalker heapWalker(rHeap);
-                    if  (iHeapInfoParams.iBuildFreeCellList || iHeapInfoParams.iBuildAllocCellList)
+                    TMemSpyHeapWalkerNullObserver observer; 
+                    RMemSpyDriverHeapWalker heapWalker( rHeap, iHeapInfoParams.iDebugAllocator );
+                    if  ( iHeapInfoParams.iBuildFreeCellList )
                         {
                         heapWalker.SetObserver( this );
-                        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - collecting cells"));
+                        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - collecting free cells"));
                         }
                     else
                         {
-                        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - not collecting cells"));
+                        heapWalker.SetObserver( &observer );
+                        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - not collecting free cells"));
                         }
 
-                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - starting traversal openerr: %d...", r));
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - starting traversal..." ));
 
 #if ( defined( TRACE_TYPE_USERHEAP ) && defined( TRACE_TYPE_HEAPWALK ) )
                     heapWalker.SetPrintDebug();
 #endif
-                    if (r == KErrNone) r = heapWalker.Traverse();
+                    r = heapWalker.Traverse();
                     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoUser - finished traversal - err: %d", r ));
 
                     TMemSpyHeapStatisticsRHeap& rHeapStats = rHeapInfo.Statistics();
@@ -169,26 +183,24 @@
 
                     // Get remaining meta data that isn't stored elsewhere
                     TMemSpyHeapMetaDataRHeap& rHeapMetaData = rHeapInfo.MetaData();
-					DChunk& userHeapChunk = rHeap.Chunk();
-					TFullName chunkName;
-					userHeapChunk.FullName(chunkName);
-					rHeapMetaData.SetChunkName( chunkName );
-		            rHeapMetaData.SetChunkSize( (TUint) OSAdaption().DChunk().GetSize( userHeapChunk ) );
-					rHeapMetaData.SetChunkHandle( &userHeapChunk );
-					rHeapMetaData.SetChunkBaseAddress( OSAdaption().DChunk().GetBase( userHeapChunk ) );
-                    rHeapMetaData.SetDebugAllocator(rHeap.Helper()->AllocatorIsUdeb());
+                    rHeapMetaData.SetChunkName( chunkName );
+                    rHeapMetaData.SetChunkSize( (TUint) OSAdaption().DChunk().GetSize( *userHeapChunk ) );
+                    rHeapMetaData.SetChunkHandle( userHeapChunk );
+                    rHeapMetaData.SetChunkBaseAddress( OSAdaption().DChunk().GetBase( *userHeapChunk ) );
+                    rHeapMetaData.SetDebugAllocator( iHeapInfoParams.iDebugAllocator );
+                    rHeapMetaData.SetHeaderSizeFree( RMemSpyDriverRHeapBase::FreeCellHeaderSize() );
+                    rHeapMetaData.SetHeaderSizeAllocated( RMemSpyDriverRHeapBase::AllocatedCellHeaderSize( iHeapInfoParams.iDebugAllocator ) );
                     rHeapMetaData.SetUserThread( ETrue );
-					rHeapMetaData.iHeapSize = rHeap.Helper()->CommittedSize();
-					rHeapMetaData.iAllocatorAddress = (TAny*)rHeap.Helper()->AllocatorAddress();
-					rHeapMetaData.iMinHeapSize = rHeap.Helper()->MinCommittedSize();
-					rHeapMetaData.iMaxHeapSize = rHeap.Helper()->MaxCommittedSize();
+
+                    // Get any heap-specific info
+                    rHeap.GetHeapSpecificInfo( masterHeapInfo );
 
                     PrintHeapInfo( masterHeapInfo );
 
                     // Write free cells if requested
-                    if  ( r == KErrNone && (iHeapInfoParams.iBuildFreeCellList || iHeapInfoParams.iBuildAllocCellList))
+                    if  ( r == KErrNone && iHeapInfoParams.iBuildFreeCellList )
                         {
-                        r = PrepareCellListTransferBuffer();
+                        r = PrepareFreeCellTransferBuffer();
                         }
 
                     // Update info ready for writing back to the user-side
@@ -205,7 +217,7 @@
                         }
 
                     // Release resources
-					rHeap.Close();
+                    rHeap.DisassociateWithKernelChunk();
                     }
                 }
             else
@@ -237,23 +249,24 @@
     if  ( r == KErrNone )
         {
         // Open kernel heap
+        TFullName heapChunkName;
         RMemSpyDriverRHeapKernelInPlace rHeap;
-        r = rHeap.OpenKernelHeap();
+        r = OpenKernelHeap( rHeap, &heapChunkName );
         TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - open err: %d", r ) );
 
         if  ( r == KErrNone )
             {
-            r = DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel(rHeap, params.iMasterInfo, aTransferBuffer);
+            // We must identify if we have a debug kernel allocator
+            const TBool debugAllocator = IsDebugKernel( rHeap );
+            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - debugAllocator: %d", debugAllocator ) );
+
+            r = DMemSpyDriverLogChanHeapBase::GetHeapInfoKernel( rHeap, debugAllocator, heapChunkName, params.iMasterInfo, aTransferBuffer );
             TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - base class get heap info: %d", r) );
             }
-        else 
-            {
-            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - open err: %d", r ) );
-            }
         }
     else
         {
-        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - params read error: %d", r) );
+    	Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - params read error: %d", r);
         }
 
 	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetHeapInfoKernel() - END - ret: %d", r) );
@@ -265,7 +278,7 @@
 
 
 
-TInt DMemSpyDriverLogChanHeapInfo::GetIsDebugKernel(TAny* aResult)
+TInt DMemSpyDriverLogChanHeapInfo::GetIsDebugKernel( TBool* aIsDebugKernel )
     {
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetIsDebugKernel() - START") );
     
@@ -275,22 +288,22 @@
     NKern::ThreadEnterCS();
     
     RMemSpyDriverRHeapKernelInPlace rHeap;
-    r = rHeap.OpenKernelHeap();
+    r = OpenKernelHeap( rHeap );
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetIsDebugKernel() - open kernel heap returned: %d", r) );
 
     if  ( r == KErrNone )
         {
-        debugKernel = rHeap.Helper()->AllocatorIsUdeb();
+        debugKernel = IsDebugKernel( rHeap );
 
         // Tidy up
-        rHeap.Close();
+        rHeap.DisassociateWithKernelChunk();
         }
 
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetIsDebugKernel() - debugKernel: %d", debugKernel) );
 
     // Write back to user-land
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::GetIsDebugKernel() - writing to user-side...") );
-    r = Kern::ThreadRawWrite( &ClientThread(), aResult, &debugKernel, sizeof(TBool) );
+    r = Kern::ThreadRawWrite( &ClientThread(), aIsDebugKernel, &debugKernel, sizeof(TBool) );
 
     NKern::ThreadLeaveCS();
 
@@ -298,121 +311,39 @@
     return r;
     }
 
-TInt DMemSpyDriverLogChanHeapInfo::PrepareCellListTransferBuffer()
-    {
-    // Transfer free cells immediately from xfer stream
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::PrepareCellListTransferBuffer() - START - iHeapStream: 0x%08x", iHeapStream ));
-    __ASSERT_ALWAYS( !iHeapStream, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapFreeCellStreamNotClosed ) );
-    //
-    TInt r = KErrNoMemory;
-    //
-    NKern::ThreadEnterCS();
-    //
-    iHeapStream = new RMemSpyMemStreamWriter();
-    if  ( iHeapStream )
-        {
-        const TInt requiredMemory = CalculateCellListBufferSize();
-        r = OpenXferStream( *iHeapStream, requiredMemory );
-        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::PrepareCellListTransferBuffer() - requested %d bytes for free cell list, r: %d", requiredMemory, r ));
+
+
 
-        if  ( r == KErrNone )
-            {
-            const TInt count = iCellList.Count();
-            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::PrepareCellListTransferBuffer() - cell count: %d", count ));
-            //
-            iHeapStream->WriteInt32( count );
-            for( TInt i=0; i<count; i++ )
-                {
-                const TMemSpyDriverCell& cell = iCellList[ i ];
-                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::PrepareCellListTransferBuffer() - storing entry: %d", i ));
-                //
-                iHeapStream->WriteInt32( cell.iType );
-                iHeapStream->WriteUint32( reinterpret_cast<TUint32>( cell.iAddress ) );
-                iHeapStream->WriteInt32( cell.iLength );
-                }
+
 
-            // Finished with the array now
-            iCellList.Reset();
 
-            // We return the amount of client-side memory that needs to be allocated to hold the buffer
-            r = requiredMemory;
-            }
-        }
-    //
-    NKern::ThreadLeaveCS();
-               
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::PrepareCellListTransferBuffer() - END - r: %d", r));
-	return r;
-    }
 
 
-TInt DMemSpyDriverLogChanHeapInfo::FetchCellList( TDes8* aBufferSink )
-    {
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::FetchCellList() - START - iHeapStream: 0x%08x", iHeapStream ));
-    __ASSERT_ALWAYS( iHeapStream, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapFreeCellStreamNotOpen ) );
+
 
-    TInt r = KErrNone;
+
 
-    // Write buffer to client
-    NKern::ThreadEnterCS();
-    r = iHeapStream->WriteAndClose( aBufferSink );
+
 
-    // Tidy up
-    ReleaseCellList();
 
-    NKern::ThreadLeaveCS();
-    //
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::FetchCellList() - END - r: %d", r));
-	return r;
-    }
 
 
 
-TInt DMemSpyDriverLogChanHeapInfo::CalculateCellListBufferSize() const
-    {
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::CalculateCellListBufferSize() - START" ));
+
+
 
-    const TInt count = iCellList.Count();
-    const TInt entrySize = sizeof( TInt32 ) + sizeof( TInt32 ) + sizeof( TUint32 );
-    const TInt r = ( count * entrySize ) + sizeof( TInt ); // Extra TInt to hold count
-                
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::CalculateCellListBufferSize() - END - r: %d, count: %d, entrySize: %d", r, count, entrySize ));
-	return r;
-    }
+
+
+
 
 
 
-void DMemSpyDriverLogChanHeapInfo::ReleaseCellList()
-    {
-	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::ReleaseCellList() - START - this: 0x%08x", this ));
+
 
-    NKern::ThreadEnterCS();
-    iCellList.Reset();
-    delete iHeapStream;
-    iHeapStream = NULL;
-    NKern::ThreadLeaveCS();
 
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapInfo::ReleaseCellList() - END - this: 0x%08x", this ));
-    }
+
 
-TBool DMemSpyDriverLogChanHeapInfo::HandleHeapCell(TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt /*aNestingLevel*/, TInt /*aAllocNumber*/)
-    {
-	TInt err = KErrNone;
-    if (((aCellType & EMemSpyDriverFreeCellMask) && iHeapInfoParams.iBuildFreeCellList) || 
-        ((aCellType & EMemSpyDriverAllocatedCellMask) && iHeapInfoParams.iBuildAllocCellList))
-		{
-		TMemSpyDriverCell cell;
-		cell.iType = aCellType;
-		cell.iAddress = aCellAddress;
-		cell.iLength = aLength;
+
 
-		NKern::ThreadEnterCS();
-		err = iCellList.Append(cell);
-		NKern::ThreadLeaveCS();
-		}
-	return err == KErrNone;
-	}
 
-void DMemSpyDriverLogChanHeapInfo::HandleHeapWalkInit()
-	{
-	}
+
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapWalk.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanHeapWalk.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -124,7 +124,7 @@
 TInt DMemSpyDriverLogChanHeapWalk::WalkHeapInit( TMemSpyDriverInternalWalkHeapParamsInit* aParams )
     {
 	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapInit() - START"));
-    __ASSERT_ALWAYS( !iHeapWalkInitialised && iWalkHeap.Helper() == NULL, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapWalkPending ) );
+    __ASSERT_ALWAYS( !iHeapWalkInitialised && iWalkHeap.ChunkIsInitialised() == EFalse, MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapWalkPending ) );
 
     TInt r = Kern::ThreadRawRead( &ClientThread(), aParams, &iHeapWalkInitialParameters, sizeof(TMemSpyDriverInternalWalkHeapParamsInit) );
     if  ( r == KErrNone )
@@ -141,8 +141,8 @@
                 TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapInit - thread: %O", thread));
 
                 // Open client's heap
-                r = iWalkHeap.OpenUserHeap(*thread, iHeapWalkInitialParameters.iDebugAllocator);
-
+                DChunk* userHeapChunk = NULL;
+                r = OpenUserHeap( *thread, iHeapWalkInitialParameters.iRHeapVTable, iWalkHeap, userHeapChunk );
                 TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapInit - opening client heap returned: %d", r) );
 
                 if  ( r == KErrNone )
@@ -154,7 +154,7 @@
 
                     // Walk the client's heap
                     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapInit - calling heap walker constructor..."));
-                    RMemSpyDriverHeapWalker heapWalker(iWalkHeap);
+                    RMemSpyDriverHeapWalker heapWalker( iWalkHeap, iHeapWalkInitialParameters.iDebugAllocator );
                     
                     TMemSpyDriverLogChanHeapWalkObserver observer( *this );
                     heapWalker.SetObserver( &observer );
@@ -169,7 +169,7 @@
                 if  ( r < KErrNone )
                     {
                     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapInit - error scenario - releasing kernel heap chunk copy" ));
-                    iWalkHeap.Close();
+                    iWalkHeap.DisassociateWithKernelChunk();
                     }
                 }
             else
@@ -199,7 +199,7 @@
     {
     const TInt walkedHeapCellCount = iWalkHeapCells.Count();
 	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapNextCell() - START - current cell count: %d", walkedHeapCellCount));
-    __ASSERT_ALWAYS( iHeapWalkInitialised && iWalkHeap.Helper(), MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapWalkNotInitialised ) );
+    __ASSERT_ALWAYS( iHeapWalkInitialised && iWalkHeap.ChunkIsInitialised(), MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapWalkNotInitialised ) );
 
     // Open the original thread
 	TInt r = OpenTempObject( aTid, EThread );
@@ -257,7 +257,12 @@
         TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapClose - heap walk was still open..."));
       	NKern::ThreadEnterCS();
 
-		iWalkHeap.Close();
+        if  ( iWalkHeap.ChunkIsInitialised() )
+            {
+            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapClose - removing chunk (%O) from process", &iWalkHeap.Chunk() ) );
+            iWalkHeap.DisassociateWithKernelChunk();
+            iWalkHeap.Reset();
+            }
 
         // Discard handled cells
         iWalkHeapCells.Reset();
@@ -274,9 +279,10 @@
 
 TInt DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData(TMemSpyDriverInternalWalkHeapCellDataReadParams* aParams)
     {
-    __ASSERT_ALWAYS( iHeapWalkInitialised && iWalkHeap.Helper(), MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapWalkNotInitialised ) );
+    __ASSERT_ALWAYS( iHeapWalkInitialised && iWalkHeap.ChunkIsInitialised(), MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapWalkNotInitialised ) );
     //
-	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData() - START - thread id: %d, vtable: 0x%08x", iHeapWalkInitialParameters.iTid, iHeapWalkInitialParameters.iRHeapVTable));
+    const TBool debugEUser = iHeapWalkInitialParameters.iDebugAllocator;
+	TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData() - START - thread id: %d, vtable: 0x%08x, debugAllocator: %d", iHeapWalkInitialParameters.iTid, iHeapWalkInitialParameters.iRHeapVTable, debugEUser));
     //
 	TMemSpyDriverInternalWalkHeapCellDataReadParams params;
     TInt r = Kern::ThreadRawRead( &ClientThread(), aParams, &params, sizeof(TMemSpyDriverInternalWalkHeapCellDataReadParams) );
@@ -300,58 +306,92 @@
             {
             // Check we can find the cell in the cell list...
             const TMemSpyDriverInternalWalkHeapParamsCell* cell = CellInfoForSpecificAddress( params.iCellAddress );
+            if  ( cell == NULL )
+                {
+                // Maybe the client tried the base address of the cell data.
+                // try to take the header into account and retry.
+                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - didnt find matching cell for address: 0x%08x... trying address minus allocatedCellHeaderSize", params.iCellAddress ));
+
+                const TUint32 cellHeaderSize = (TUint32) RMemSpyDriverRHeapBase::AllocatedCellHeaderSize( debugEUser );
+        
+                TUint32 addr = (TUint32) params.iCellAddress;
+                addr -= cellHeaderSize;
+                params.iCellAddress = (TAny*) addr;
+                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - new address: 0x%08x", params.iCellAddress ));
+        
+                // Last try
+                cell = CellInfoForSpecificAddress( params.iCellAddress );
+                }
 
             TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - cell: 0x%08x for address: 0x%08x", cell, params.iCellAddress ));
 
             if  ( cell )
                 {
-                const TInt cellLen = cell->iLength;
-                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - cellLen: %d", cellLen ));
-
-                if  ( params.iReadLen <= cellLen )
+                const TBool isValidCell = iWalkHeap.CheckCell( cell->iCellAddress, cell->iLength );
+                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - isValidCell: %d", isValidCell ));
+        
+                if  ( isValidCell )
                     {
+                    // Check the length request is valid
+                    const TInt cellLen = cell->iLength;
+                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - cellLen: %d", cellLen ));
 
-                    // Get user side descriptor length info
-         	        TInt destLen = 0;
-        	        TInt destMax = 0;
-                    TUint8* destPtr = NULL;
+                    if  ( params.iReadLen <= cellLen )
+                        {
+                        const TInt cellHeaderSize = RMemSpyDriverRHeapBase::CellHeaderSize( *cell, debugEUser );
+        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - cellHeaderSize: %8d", cellHeaderSize ));
 
-                    r = Kern::ThreadGetDesInfo( &ClientThread(), params.iDes, destLen, destMax, destPtr, ETrue );
-        	        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - user side descriptor: 0x%08x (0x%08x), len: %8d, maxLen: %8d, r: %d", params.iDes, destPtr, destLen, destMax, r ));
+                        // Get user side descriptor length info
+         	            TInt destLen = 0;
+        	            TInt destMax = 0;
+                        TUint8* destPtr = NULL;
+
+                        r = Kern::ThreadGetDesInfo( &ClientThread(), params.iDes, destLen, destMax, destPtr, ETrue );
+        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - user side descriptor: 0x%08x (0x%08x), len: %8d, maxLen: %8d, r: %d", params.iDes, destPtr, destLen, destMax, r ));
 
-                    // Work out the start offset for the data...
-                    if  ( r == KErrNone && destMax >= params.iReadLen )
-                        {
-                        const TAny* srcPos = ((TUint8*) cell->iCellAddress);
-        	            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - srcPos: 0x%08x", srcPos ));
+                        // Work out the start offset for the data...
+                        if  ( r == KErrNone && destMax >= params.iReadLen )
+                            {
+                            const TAny* srcPos = ((TUint8*) cell->iCellAddress) + cellHeaderSize;
+        	                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - srcPos: 0x%08x", srcPos ));
+
+                            // Read some data 
+                            r = Kern::ThreadRawRead( thread, srcPos, destPtr, params.iReadLen );
+    	                    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - read from thread returned: %d", r));
 
-                        // Read some data 
-                        r = Kern::ThreadRawRead( thread, srcPos, destPtr, params.iReadLen );
-    	                TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - read from thread returned: %d", r));
-
-                        if  ( r == KErrNone )
+                            if  ( r == KErrNone )
+                                {
+                                // Client will update descriptor length in this situation.
+                                r = params.iReadLen;
+                                }
+                            else if ( r == KErrBadDescriptor )
+                                {
+                                MemSpyDriverUtils::PanicThread( ClientThread(), EPanicBadDescriptor );
+                                }
+                            }
+                        else
                             {
-                            // Client will update descriptor length in this situation.
-                            r = params.iReadLen;
+                            if  ( r != KErrBadDescriptor )
+                                {
+                                r = KErrArgument;                
+            	                Kern::Printf( "DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - error - user-descriptor isnt big enough for requested data" );
+                                }
+                            else
+                                {
+            	                Kern::Printf( "DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - error - bad or non-writable user-side descriptor" );
+                                }
                             }
                         }
                     else
                         {
-                        if  ( r != KErrBadDescriptor )
-                            {
-                            r = KErrArgument;                
-            	            Kern::Printf( "DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - error - user-descriptor isnt big enough for requested data" );
-                            }
-                        else
-                            {
-            	            Kern::Printf( "DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - error - bad or non-writable user-side descriptor" );
-                            }
+                        r = KErrArgument;
+        	            Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - error - read length is bigger than cell length");
                         }
                     }
                 else
                     {
                     r = KErrArgument;
-        	        Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - error - read length is bigger than cell length");
+                    Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - invalid cell address: 0x%08x", cell);
                     }
                 }
             else
@@ -373,16 +413,17 @@
     	Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData - thread not found");
 		}
     //
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData() - END result=%d", r));
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapReadCellData() - END"));
     return r;
     }
 
 
 TInt DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo( TAny* aCellAddress, TMemSpyDriverInternalWalkHeapParamsCell* aParams )
     {
-    __ASSERT_ALWAYS( iHeapWalkInitialised && iWalkHeap.Helper(), MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapWalkNotInitialised ) );
+    __ASSERT_ALWAYS( iHeapWalkInitialised && iWalkHeap.ChunkIsInitialised(), MemSpyDriverUtils::PanicThread( ClientThread(), EPanicHeapWalkNotInitialised ) );
     //
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo() - START - thread id: %d, vtable: 0x%08x", iHeapWalkInitialParameters.iTid, iHeapWalkInitialParameters.iRHeapVTable));
+    const TBool debugEUser = iHeapWalkInitialParameters.iDebugAllocator;
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo() - START - thread id: %d, vtable: 0x%08x, debugAllocator: %d", iHeapWalkInitialParameters.iTid, iHeapWalkInitialParameters.iRHeapVTable, debugEUser));
     TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo - cell: 0x%08x", aCellAddress));
 
     // Open the original thread
@@ -409,6 +450,16 @@
     if  ( cell == NULL )
         {
         TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo - no exact match for address: 0x%08x...", aCellAddress));
+
+        // Maybe the client tried the base address of the cell data.
+        // try to take the header into account and retry.
+        const TUint32 cellHeaderSize = (TUint32) RMemSpyDriverRHeapBase::AllocatedCellHeaderSize( debugEUser );
+        TUint32 addr = (TUint32) aCellAddress;
+        addr -= cellHeaderSize;
+        
+        TAny* cellByRawStartingAddress = (TAny*) addr;
+        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo - trying to search by start of cell address: 0x%08x (cellHeaderSize: %d)", cellByRawStartingAddress, cellHeaderSize));
+        cell = CellInfoForSpecificAddress( cellByRawStartingAddress );
         
         // If the cell still wasn't found, then let's look for any heap cell that contains
         // the client-specified address (i.e. find the heap cell that contains the specified
@@ -422,9 +473,18 @@
 
     if  ( cell )
         {
-        // Have enough info to write back to client now
-        TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo - returning... cellType: %1d, addr: 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", cell->iCellType, cell->iCellAddress, cell->iLength, cell->iNestingLevel, cell->iAllocNumber ));
-        r = Kern::ThreadRawWrite( &ClientThread(), aParams, cell, sizeof(TMemSpyDriverInternalWalkHeapParamsCell) );
+        const TBool isValidCell = iWalkHeap.CheckCell( cell->iCellAddress, cell->iLength );
+        if  ( isValidCell )
+            {
+            // Have enough info to write back to client now
+            TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo - returning... cellType: %1d, addr: 0x%08x, len: %8d, nestingLev: %8d, allocNum: %8d", cell->iCellType, cell->iCellAddress, cell->iLength, cell->iNestingLevel, cell->iAllocNumber ));
+            r = Kern::ThreadRawWrite( &ClientThread(), aParams, cell, sizeof(TMemSpyDriverInternalWalkHeapParamsCell) );
+            }
+        else
+            {
+            r = KErrArgument;
+            Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo - invalid cell address: 0x%08x", cell);
+            }
         }
     else
         {
@@ -434,7 +494,7 @@
     
     CloseTempObject();
     //
-    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo() - END result=%d", r));
+    TRACE( Kern::Printf("DMemSpyDriverLogChanHeapWalk::WalkHeapGetCellInfo() - END"));
     return r;
     }
 
@@ -516,7 +576,7 @@
 
 
 
-TBool DMemSpyDriverLogChanHeapWalk::WalkerHandleHeapCell(TMemSpyDriverCellType aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber )
+TBool DMemSpyDriverLogChanHeapWalk::WalkerHandleHeapCell( TInt aCellType, TAny* aCellAddress, TInt aLength, TInt aNestingLevel, TInt aAllocNumber )
     {
     TInt error = KErrNone;
     //
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanMisc.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanMisc.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -171,6 +171,7 @@
 
         DObjectCon* container = Kern::Containers()[ EProcess ];
         container->Wait();
+        NKern::LockSystem();
 
         const TInt count = container->Count();
         for(TInt i=0; i<count; i++)
@@ -192,7 +193,9 @@
                 }
             }
 
+        NKern::UnlockSystem();
         container->Signal();
+
     	NKern::ThreadLeaveCS();
         }
 
--- a/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanStack.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Kernel/Source/SubChannels/MemSpyDriverLogChanStack.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -186,6 +186,10 @@
                 stackSize = threadAdaption.GetSupervisorStackSize( *thread );
                 stackBase = threadAdaption.GetSupervisorStackBase( *thread );
                 }
+            //We have a stack so setting it as available
+            if(stackSize!=0 &&  stackBase!=0)
+                stackAvailable=ETrue;
+            
             TRACE( Kern::Printf("DMemSpyDriverLogChanStack::GetStackData() - stackAvailable: %d", stackAvailable ));
             //           
             if  ( stackAvailable )
--- a/memspy/Driver/Shared/MemSpyDriverObjectsInternal.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Shared/MemSpyDriverObjectsInternal.h	Wed Oct 13 16:17:58 2010 +0300
@@ -33,7 +33,8 @@
     {
 public:
     inline TMemSpyDriverInternalHeapRequestParameters()
-        : iTid(0), iRHeapVTable(0), iBuildFreeCellList(EFalse), iBuildAllocCellList(EFalse), iDebugAllocator(EFalse), iMasterInfo(NULL)
+        : iTid( 0 ), iRHeapVTable( 0 ), iBuildFreeCellList( EFalse ), iDebugAllocator( EFalse ), 
+          iMasterInfo( NULL )
         {
         }
 
@@ -41,7 +42,6 @@
     TUint iTid;
     TUint32 iRHeapVTable;
     TBool iBuildFreeCellList;
-	TBool iBuildAllocCellList;
 
 public: // Params IN or OUT (IN in User heap requests, OUT in Kernel heap requests)
     TBool iDebugAllocator;
--- a/memspy/Driver/Shared/MemSpyDriverOpCodes.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/Shared/MemSpyDriverOpCodes.h	Wed Oct 13 16:17:58 2010 +0300
@@ -56,7 +56,7 @@
 	EMemSpyDriverOpCodeHeapInfoGetUser,
 	EMemSpyDriverOpCodeHeapInfoGetKernel,
     EMemSpyDriverOpCodeHeapInfoGetIsDebugKernel,
-    EMemSpyDriverOpCodeHeapInfoFetchCellList,
+    EMemSpyDriverOpCodeHeapInfoFetchFreeCells,
     EMemSpyDriverOpCodeHeapInfoEnd,
 
     // HEAP DATA
--- a/memspy/Driver/Shared/heaputils.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1684 +0,0 @@
-// heaputils.cpp
-// 
-// Copyright (c) 2010 Accenture. All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the "Eclipse Public License v1.0"
-// which accompanies this distribution, and is available
-// at the URL "http://www.eclipse.org/legal/epl-v10.html".
-// 
-// Initial Contributors:
-// Accenture - Initial contribution
-//
-#ifdef TEST_HYBRIDHEAP_ASSERTS
-#define private public
-#include <e32def.h>
-#include "slab.h"
-#include "page_alloc.h"
-#include "heap_hybrid.h"
-#endif
-
-#include "heaputils.h"
-
-#ifdef __KERNEL_MODE__
-
-#include <kern_priv.h>
-#define MEM Kern
-__ASSERT_COMPILE(sizeof(LtkUtils::RKernelSideAllocatorHelper) == 10*4);
-#define KERN_ENTER_CS() NKern::ThreadEnterCS()
-#define KERN_LEAVE_CS() NKern::ThreadLeaveCS()
-#define LOG(args...)
-#define HUEXPORT_C
-#else
-
-#include <e32std.h>
-#define MEM User
-#define KERN_ENTER_CS()
-#define KERN_LEAVE_CS()
-//#include <e32debug.h>
-//#define LOG(args...) RDebug::Printf(args)
-#define LOG(args...)
-
-#ifdef STANDALONE_ALLOCHELPER
-#define HUEXPORT_C
-#else
-#define HUEXPORT_C EXPORT_C
-#endif
-
-#endif // __KERNEL_MODE__
-
-using LtkUtils::RAllocatorHelper;
-const TUint KPageSize = 4096;
-__ASSERT_COMPILE(sizeof(RAllocatorHelper) == 9*4);
-
-// RAllocatorHelper
-
-HUEXPORT_C RAllocatorHelper::RAllocatorHelper()
-	: iAllocatorAddress(0), iAllocatorType(EUnknown), iInfo(NULL), iValidInfo(0), iTempSlabBitmap(NULL), iPageCache(NULL), iPageCacheAddr(0)
-#ifdef __KERNEL_MODE__
-	, iChunk(NULL)
-#endif
-	{
-	}
-
-namespace LtkUtils
-	{
-	class THeapInfo
-		{
-	public:
-		THeapInfo()
-			{
-			ClearStats();
-			}
-
-		void ClearStats()
-			{
-			memclr(this, sizeof(THeapInfo));
-			}
-
-		TInt iAllocatedSize; // number of bytes in allocated cells (excludes free cells, cell header overhead)
-		TInt iCommittedSize; // amount of memory actually committed (includes cell header overhead, gaps smaller than an MMU page)
-		TInt iAllocationCount; // number of allocations currently
-		TInt iMaxCommittedSize; // or thereabouts
-		TInt iMinCommittedSize;
-		TInt iUnusedPages;
-		TInt iCommittedFreeSpace;
-		// Heap-only stats
-		TInt iHeapFreeCellCount;
-		// Hybrid-only stats
-		TInt iDlaAllocsSize;
-		TInt iDlaAllocsCount;
-		TInt iDlaFreeSize;
-		TInt iDlaFreeCount;
-		TInt iSlabAllocsSize;
-		TInt iSlabAllocsCount;
-		TInt iPageAllocsSize;
-		TInt iPageAllocsCount;
-		TInt iSlabFreeCellSize;
-		TInt iSlabFreeCellCount;
-		TInt iSlabFreeSlabSize;
-		TInt iSlabFreeSlabCount;
-		};
-	}
-
-const TInt KTempBitmapSize = 256; // KMaxSlabPayload / mincellsize, technically. Close enough.
-
-#ifdef __KERNEL_MODE__
-
-TInt RAllocatorHelper::OpenKernelHeap()
-	{
-	_LIT(KName, "SvHeap");
-	NKern::ThreadEnterCS();
-	DObjectCon* chunkContainer = Kern::Containers()[EChunk];
-	chunkContainer->Wait();
-	const TInt chunkCount = chunkContainer->Count();
-	DChunk* foundChunk = NULL;
-	for(TInt i=0; i<chunkCount; i++)
-		{
-		DChunk* chunk = (DChunk*)(*chunkContainer)[i];
-		if (chunk->NameBuf() && chunk->NameBuf()->Find(KName) != KErrNotFound)
-			{
-			// Found it. No need to open it, we can be fairly confident the kernel heap isn't going to disappear from under us
-			foundChunk = chunk;
-			break;
-			}
-		}
-	iChunk = foundChunk;
-    chunkContainer->Signal();
-#ifdef __WINS__
-	TInt err = OpenChunkHeap((TLinAddr)foundChunk->Base(), 0); // It looks like DChunk::iBase/DChunk::iFixedBase should both be ok for the kernel chunk
-#else
-	// Copied from P::KernelInfo
-	const TRomHeader& romHdr=Epoc::RomHeader();
-	const TRomEntry* primaryEntry=(const TRomEntry*)Kern::SuperPage().iPrimaryEntry;
-	const TRomImageHeader* primaryImageHeader=(const TRomImageHeader*)primaryEntry->iAddressLin;
-	TLinAddr stack = romHdr.iKernDataAddress + Kern::RoundToPageSize(romHdr.iTotalSvDataSize);
-	TLinAddr heap = stack + Kern::RoundToPageSize(primaryImageHeader->iStackSize);
-	TInt err = OpenChunkHeap(heap, 0); // aChunkMaxSize is only used for trying the middle of the chunk for hybrid allocatorness, and the kernel heap doesn't use that (thankfully). So we can safely pass in zero.
-
-#endif
-	if (!err) err = FinishConstruction();
-	NKern::ThreadLeaveCS();
-	return err;
-	}
-
-#else
-
-HUEXPORT_C TInt RAllocatorHelper::Open(RAllocator* aAllocator)
-	{
-	iAllocatorAddress = (TLinAddr)aAllocator;
-	TInt udeb = EuserIsUdeb();
-	if (udeb < 0) return udeb; // error
-
-	TInt err = IdentifyAllocatorType(udeb);
-	if (!err)
-		{
-		err = FinishConstruction(); // Allocate everything up front
-		}
-	if (!err)
-		{
-		// We always stealth our own allocations, again to avoid tripping up allocator checks
-		SetCellNestingLevel(iInfo, -1);
-		SetCellNestingLevel(iTempSlabBitmap, -1);
-		SetCellNestingLevel(iPageCache, -1);
-		}
-	return err;
-	}
-
-#endif
-
-TInt RAllocatorHelper::FinishConstruction()
-	{
-	TInt err = KErrNone;
-	KERN_ENTER_CS();
-	if (!iInfo)
-		{
-		iInfo = new THeapInfo;
-		if (!iInfo) err = KErrNoMemory;
-		}
-	if (!err && !iTempSlabBitmap)
-		{
-		iTempSlabBitmap = (TUint8*)MEM::Alloc(KTempBitmapSize);
-		if (!iTempSlabBitmap) err = KErrNoMemory;
-		}
-	if (!err && !iPageCache)
-		{
-		iPageCache = MEM::Alloc(KPageSize);
-		if (!iPageCache) err = KErrNoMemory;
-		}
-
-	if (err)
-		{
-		delete iInfo;
-		iInfo = NULL;
-		MEM::Free(iTempSlabBitmap);
-		iTempSlabBitmap = NULL;
-		MEM::Free(iPageCache);
-		iPageCache = NULL;
-		}
-	KERN_LEAVE_CS();
-	return err;
-	}
-
-TInt RAllocatorHelper::ReadWord(TLinAddr aLocation, TUint32& aResult) const
-	{
-	// Check if we can satisfy the read from the cache
-	if (aLocation >= iPageCacheAddr)
-		{
-		TUint offset = aLocation - iPageCacheAddr;
-		if (offset < KPageSize)
-			{
-			aResult = ((TUint32*)iPageCache)[offset >> 2];
-			return KErrNone;
-			}
-		}
-
-	// If we reach here, not in page cache. Try and read in the new page
-	if (iPageCache)
-		{
-		TLinAddr pageAddr = aLocation & ~(KPageSize-1);
-		TInt err = ReadData(pageAddr, iPageCache, KPageSize);
-		if (!err)
-			{
-			iPageCacheAddr = pageAddr;
-			aResult = ((TUint32*)iPageCache)[(aLocation - iPageCacheAddr) >> 2];
-			return KErrNone;
-			}
-		}
-
-	// All else fails, try just reading it uncached
-	return ReadData(aLocation, &aResult, sizeof(TUint32));
-	}
-
-TInt RAllocatorHelper::ReadByte(TLinAddr aLocation, TUint8& aResult) const
-	{
-	// Like ReadWord but 8-bit
-
-	// Check if we can satisfy the read from the cache
-	if (aLocation >= iPageCacheAddr)
-		{
-		TUint offset = aLocation - iPageCacheAddr;
-		if (offset < KPageSize)
-			{
-			aResult = ((TUint8*)iPageCache)[offset];
-			return KErrNone;
-			}
-		}
-
-	// If we reach here, not in page cache. Try and read in the new page
-	if (iPageCache)
-		{
-		TLinAddr pageAddr = aLocation & ~(KPageSize-1);
-		TInt err = ReadData(pageAddr, iPageCache, KPageSize);
-		if (!err)
-			{
-			iPageCacheAddr = pageAddr;
-			aResult = ((TUint8*)iPageCache)[(aLocation - iPageCacheAddr)];
-			return KErrNone;
-			}
-		}
-
-	// All else fails, try just reading it uncached
-	return ReadData(aLocation, &aResult, sizeof(TUint8));
-	}
-
-
-TInt RAllocatorHelper::WriteWord(TLinAddr aLocation, TUint32 aWord)
-	{
-	// Invalidate the page cache if necessary
-	if (aLocation >= iPageCacheAddr && aLocation - iPageCacheAddr < KPageSize)
-		{
-		iPageCacheAddr = 0;
-		}
-
-	return WriteData(aLocation, &aWord, sizeof(TUint32));
-	}
-
-TInt RAllocatorHelper::ReadData(TLinAddr aLocation, TAny* aResult, TInt aSize) const
-	{
-	// RAllocatorHelper base class impl is for allocators in same address space, so just copy it
-	memcpy(aResult, (const TAny*)aLocation, aSize);
-	return KErrNone;
-	}
-
-TInt RAllocatorHelper::WriteData(TLinAddr aLocation, const TAny* aData, TInt aSize)
-	{
-	memcpy((TAny*)aLocation, aData, aSize);
-	return KErrNone;
-	}
-
-#ifdef __KERNEL_MODE__
-
-LtkUtils::RKernelSideAllocatorHelper::RKernelSideAllocatorHelper()
-	: iThread(NULL)
-	{}
-
-void LtkUtils::RKernelSideAllocatorHelper::Close()
-	{
-	NKern::ThreadEnterCS();
-	if (iThread)
-		{
-		iThread->Close(NULL);
-		}
-	iThread = NULL;
-	RAllocatorHelper::Close();
-	NKern::ThreadLeaveCS();
-	}
-
-TInt LtkUtils::RKernelSideAllocatorHelper::ReadData(TLinAddr aLocation, TAny* aResult, TInt aSize) const
-	{
-	return Kern::ThreadRawRead(iThread, (const TAny*)aLocation, aResult, aSize);
-	}
-
-TInt LtkUtils::RKernelSideAllocatorHelper::WriteData(TLinAddr aLocation, const TAny* aData, TInt aSize)
-	{
-	return Kern::ThreadRawWrite(iThread, (TAny*)aLocation, aData, aSize);
-	}
-
-TInt LtkUtils::RKernelSideAllocatorHelper::TryLock()
-	{
-	return KErrNotSupported;
-	}
-
-void LtkUtils::RKernelSideAllocatorHelper::TryUnlock()
-	{
-	// Not supported
-	}
-
-TInt LtkUtils::RKernelSideAllocatorHelper::OpenUserHeap(TUint aThreadId, TLinAddr aAllocatorAddress, TBool aEuserIsUdeb)
-	{
-	NKern::ThreadEnterCS();
-	DObjectCon* threads = Kern::Containers()[EThread];
-	threads->Wait();
-	iThread = Kern::ThreadFromId(aThreadId);
-	if (iThread && iThread->Open() != KErrNone)
-		{
-		// Failed to open
-		iThread = NULL;
-		}
-	threads->Signal();
-	NKern::ThreadLeaveCS();
-	if (!iThread) return KErrNotFound;
-	iAllocatorAddress = aAllocatorAddress;
-	TInt err = IdentifyAllocatorType(aEuserIsUdeb);
-	if (err) Close();
-	return err;
-	}
-
-#endif // __KERNEL_MODE__
-
-TInt RAllocatorHelper::OpenChunkHeap(TLinAddr aChunkBase, TInt aChunkMaxSize)
-	{
-	iAllocatorAddress = aChunkBase;
-#ifdef __KERNEL_MODE__
-	// Must be in CS
-	// Assumes that this only ever gets called for the kernel heap. Otherwise goes through RKernelSideAllocatorHelper::OpenUserHeap.
-	TInt udeb = EFalse; // We can't figure this out until after we've got the heap
-	TBool isTheKernelHeap = ETrue;
-#else
-	// Assumes the chunk isn't the kernel heap. It's not a good idea to try messing with the kernel heap from user side...
-	TInt udeb = EuserIsUdeb();
-	if (udeb < 0) return udeb; // error
-    TBool isTheKernelHeap = EFalse;
-#endif
-
-	TInt err = IdentifyAllocatorType(udeb, isTheKernelHeap);
-	if (err == KErrNone && iAllocatorType == EAllocator)
-		{
-		// We've no reason to assume it's an allocator because we don't know the iAllocatorAddress actually is an RAllocator*
-		err = KErrNotFound;
-		}
-	if (err && aChunkMaxSize > 0)
-		{
-		TInt oldErr = err;
-		TAllocatorType oldType = iAllocatorType;
-		// Try middle of chunk, in case it's an RHybridHeap
-		iAllocatorAddress += aChunkMaxSize / 2;
-		err = IdentifyAllocatorType(udeb, isTheKernelHeap);
-		if (err || iAllocatorType == EAllocator)
-			{
-			// No better than before
-			iAllocatorAddress = aChunkBase;
-			iAllocatorType = oldType;
-			err = oldErr;
-			}
-		}
-#ifdef __KERNEL_MODE__
-	if (err == KErrNone)
-		{
-		// Now we know the allocator, we can figure out the udeb-ness
-		RAllocator* kernelAllocator = reinterpret_cast<RAllocator*>(iAllocatorAddress);
-		kernelAllocator->DebugFunction(RAllocator::ESetFail, (TAny*)9999, (TAny*)0); // Use an invalid fail reason - this should have no effect on the operation of the heap
-		TInt err = kernelAllocator->DebugFunction(7, NULL, NULL); // 7 is RAllocator::TAllocDebugOp::EGetFail
-		if (err == 9999)
-			{
-			// udeb new hybrid heap
-			udeb = ETrue;
-			}
-		else if (err == KErrNotSupported)
-			{
-			// Old heap - fall back to slightly nasty non-thread-safe method
-			kernelAllocator->DebugFunction(RAllocator::ESetFail, (TAny*)RAllocator::EFailNext, (TAny*)1);
-			TAny* res = Kern::Alloc(4);
-			if (!res) udeb = ETrue;
-			Kern::Free(res);
-			}
-		else
-			{
-			// it's new urel
-			}
-
-		// Put everything back
-		kernelAllocator->DebugFunction(RAllocator::ESetFail, (TAny*)RAllocator::ENone, (TAny*)0);
-		// And update the type now we know the udeb-ness for certain
-		err = IdentifyAllocatorType(udeb, isTheKernelHeap);
-		}
-#endif
-	return err;
-	}
-
-
-// The guts of RAllocatorHelper
-
-enum TWhatToGet
-	{
-	ECommitted = 1,
-	EAllocated = 2,
-	ECount = 4,
-	EMaxSize = 8,
-	EUnusedPages = 16,
-	ECommittedFreeSpace = 32,
-	EMinSize = 64,
-	EHybridStats = 128,
-	};
-
-class RHackAllocator : public RAllocator
-	{
-public:
-	using RAllocator::iHandles;
-	using RAllocator::iTotalAllocSize;
-	using RAllocator::iCellCount;
-	};
-
-class RHackHeap : public RHeap
-	{
-public:
-	// Careful, only allowed to use things that are still in the new RHeap, and are still in the same place
-	using RHeap::iMaxLength;
-	using RHeap::iChunkHandle;
-	using RHeap::iLock;
-	using RHeap::iBase;
-	using RHeap::iAlign;
-	using RHeap::iTop;
-	};
-
-const TInt KChunkSizeOffset = 30*4;
-const TInt KPageMapOffset = 141*4;
-//const TInt KDlOnlyOffset = 33*4;
-const TInt KMallocStateOffset = 34*4;
-const TInt KMallocStateTopSizeOffset = 3*4;
-const TInt KMallocStateTopOffset = 5*4;
-const TInt KMallocStateSegOffset = 105*4;
-const TInt KUserHybridHeapSize = 186*4;
-const TInt KSparePageOffset = 167*4;
-const TInt KPartialPageOffset = 165*4;
-const TInt KFullSlabOffset = 166*4;
-const TInt KSlabAllocOffset = 172*4;
-const TInt KSlabParentOffset = 1*4;
-const TInt KSlabChild1Offset = 2*4;
-const TInt KSlabChild2Offset = 3*4;
-const TInt KSlabPayloadOffset = 4*4;
-const TInt KSlabsetSize = 4;
-
-#ifdef TEST_HYBRIDHEAP_ASSERTS
-__ASSERT_COMPILE(_FOFF(RHybridHeap, iChunkSize) == KChunkSizeOffset);
-__ASSERT_COMPILE(_FOFF(RHybridHeap, iPageMap) == KPageMapOffset);
-__ASSERT_COMPILE(_FOFF(RHybridHeap, iGlobalMallocState) == KMallocStateOffset);
-__ASSERT_COMPILE(sizeof(malloc_state) == 107*4);
-__ASSERT_COMPILE(_FOFF(malloc_state, iTopSize) == KMallocStateTopSizeOffset);
-__ASSERT_COMPILE(_FOFF(malloc_state, iTop) == KMallocStateTopOffset);
-__ASSERT_COMPILE(_FOFF(malloc_state, iSeg) == KMallocStateSegOffset);
-__ASSERT_COMPILE(sizeof(RHybridHeap) == KUserHybridHeapSize);
-__ASSERT_COMPILE(_FOFF(RHybridHeap, iSparePage) == KSparePageOffset);
-__ASSERT_COMPILE(_FOFF(RHybridHeap, iPartialPage) == KPartialPageOffset);
-__ASSERT_COMPILE(_FOFF(RHybridHeap, iSlabAlloc) == KSlabAllocOffset);
-__ASSERT_COMPILE(_FOFF(slab, iParent) == KSlabParentOffset);
-__ASSERT_COMPILE(_FOFF(slab, iChild1) == KSlabChild1Offset);
-__ASSERT_COMPILE(_FOFF(slab, iChild2) == KSlabChild2Offset);
-__ASSERT_COMPILE(_FOFF(slab, iPayload) == KSlabPayloadOffset);
-__ASSERT_COMPILE(sizeof(slabset) == KSlabsetSize);
-#endif
-
-TInt RAllocatorHelper::TryLock()
-	{
-#ifdef __KERNEL_MODE__
-	NKern::ThreadEnterCS();
-	DMutex* m = *(DMutex**)(iAllocatorAddress + _FOFF(RHackHeap, iLock));
-	if (m) Kern::MutexWait(*m);
-	return KErrNone;
-#else
-	if (iAllocatorType != EUnknown && iAllocatorType != EAllocator)
-		{
-		RFastLock& lock = *reinterpret_cast<RFastLock*>(iAllocatorAddress + _FOFF(RHackHeap, iLock));
-		lock.Wait();
-		return KErrNone;
-		}
-	return KErrNotSupported;
-#endif
-	}
-
-void RAllocatorHelper::TryUnlock()
-	{
-#ifdef __KERNEL_MODE__
-	DMutex* m = *(DMutex**)(iAllocatorAddress + _FOFF(RHackHeap, iLock));
-	if (m) Kern::MutexSignal(*m);
-	NKern::ThreadLeaveCS();
-#else
-	if (iAllocatorType != EUnknown && iAllocatorType != EAllocator)
-		{
-		RFastLock& lock = *reinterpret_cast<RFastLock*>(iAllocatorAddress + _FOFF(RHackHeap, iLock));
-		lock.Signal();
-		}
-#endif
-	}
-
-HUEXPORT_C void RAllocatorHelper::Close()
-	{
-	KERN_ENTER_CS();
-	iAllocatorType = EUnknown;
-	iAllocatorAddress = 0;
-	delete iInfo;
-	iInfo = NULL;
-	iValidInfo = 0;
-	MEM::Free(iTempSlabBitmap);
-	iTempSlabBitmap = NULL;
-	MEM::Free(iPageCache);
-	iPageCache = NULL;
-	iPageCacheAddr = 0;
-	KERN_LEAVE_CS();
-	}
-
-TInt RAllocatorHelper::IdentifyAllocatorType(TBool aAllocatorIsUdeb, TBool aIsTheKernelHeap)
-	{
-	iAllocatorType = EUnknown;
-
-	TUint32 handlesPtr = 0;
-	TInt err = ReadWord(iAllocatorAddress + _FOFF(RHackAllocator, iHandles), handlesPtr);
-
-	if (err) return err;
-	if (aIsTheKernelHeap || 
-	    handlesPtr == iAllocatorAddress + _FOFF(RHackHeap, iChunkHandle) || 
-	    handlesPtr == iAllocatorAddress + _FOFF(RHackHeap, iLock))
-		{
-		// It's an RHeap of some kind - I doubt any other RAllocator subclass will use iHandles in this way
-		TUint32 base = 0;
-		err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iBase), base);
-		if (err) return err;
-		TInt objsize = (TInt)base - (TInt)iAllocatorAddress;
-		if (objsize <= 32*4)
-			{
-			// Old RHeap
-			iAllocatorType = aAllocatorIsUdeb ? EUdebOldRHeap : EUrelOldRHeap;
-			}
-		else
-			{
-			// new hybrid heap - bigger than the old one. Likewise figure out if udeb or urel.
-			iAllocatorType = aAllocatorIsUdeb ? EUdebHybridHeap : EUrelHybridHeap;
-			}
-		}
-	else
-		{
-		iAllocatorType = EAllocator;
-		}
-	return KErrNone;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::SetCellNestingLevel(TAny* aCell, TInt aNestingLevel)
-	{
-	TInt err = KErrNone;
-
-	switch (iAllocatorType)
-		{
-		case EUdebOldRHeap:
-		case EUdebHybridHeap:
-			// By this reckoning, they're in the same place amazingly
-			{
-			TLinAddr nestingAddr = (TLinAddr)aCell - 8;
-			err = WriteWord(nestingAddr, aNestingLevel);
-			break;
-			}
-		default:
-			break;
-		}
-	return err;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::GetCellNestingLevel(TAny* aCell, TInt& aNestingLevel)
-	{
-	switch (iAllocatorType)
-		{
-		case EUdebOldRHeap:
-		case EUdebHybridHeap:
-			// By this reckoning, they're in the same place amazingly
-			{
-			TLinAddr nestingAddr = (TLinAddr)aCell - 8;
-			return ReadWord(nestingAddr, (TUint32&)aNestingLevel);
-			}
-		default:
-			return KErrNotSupported;
-		}
-	}
-
-TInt RAllocatorHelper::RefreshDetails(TUint aMask)
-	{
-	TInt err = FinishConstruction();
-	if (err) return err;
-
-	// Invalidate the page cache
-	iPageCacheAddr = 0;
-
-	TryLock();
-	err = DoRefreshDetails(aMask);
-	TryUnlock();
-	return err;
-	}
-
-const TInt KHeapWalkStatsForOldHeap = (EUnusedPages|ECommittedFreeSpace);
-const TInt KHeapWalkStatsForNewHeap = (EAllocated|ECount|EUnusedPages|ECommittedFreeSpace|EHybridStats);
-
-TInt RAllocatorHelper::DoRefreshDetails(TUint aMask)
-	{
-	TInt err = KErrNotSupported;
-	switch (iAllocatorType)
-		{
-		case EUrelOldRHeap:
-		case EUdebOldRHeap:
-			{
-			if (aMask & ECommitted)
-				{
-				// The old RHeap::Size() used to use iTop - iBase, which was effectively chunkSize - sizeof(RHeap)
-				// I think that for CommittedSize we should include the size of the heap object, just as it includes
-				// the size of heap cell metadata and overhead. Plus it makes sure the committedsize is a multiple of the page size
-				TUint32 top = 0;
-				//TUint32 base = 0;
-				//err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iBase), base);
-				//if (err) return err;
-				err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iTop), top);
-				if (err) return err;
-
-				//iInfo->iCommittedSize = top - base;
-				iInfo->iCommittedSize = top - iAllocatorAddress;
-				iValidInfo |= ECommitted;
-				}
-			if (aMask & EAllocated)
-				{
-				TUint32 allocSize = 0;
-				err = ReadWord(iAllocatorAddress + _FOFF(RHackAllocator, iTotalAllocSize), allocSize);
-				if (err) return err;
-				iInfo->iAllocatedSize = allocSize;
-				iValidInfo |= EAllocated;
-				}
-			if (aMask & ECount)
-				{
-				TUint32 count = 0;
-				err = ReadWord(iAllocatorAddress + _FOFF(RHackAllocator, iCellCount), count);
-				if (err) return err;
-				iInfo->iAllocationCount = count;
-				iValidInfo |= ECount;
-				}
-			if (aMask & EMaxSize)
-				{
-				TUint32 maxlen = 0;
-				err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iMaxLength), maxlen);
-				if (err) return err;
-				iInfo->iMaxCommittedSize = maxlen;
-				iValidInfo |= EMaxSize;
-				}
-			if (aMask & EMinSize)
-				{
-				TUint32 minlen = 0;
-				err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iMaxLength) - 4, minlen); // This isn't a typo! iMinLength is 4 bytes before iMaxLength, on old heap ONLY
-				if (err) return err;
-				iInfo->iMinCommittedSize = minlen;
-				iValidInfo |= EMinSize;
-				}
-			if (aMask & KHeapWalkStatsForOldHeap)
-				{
-				// Need a heap walk
-				iInfo->ClearStats();
-				iValidInfo = 0;
-				err = DoWalk(&WalkForStats, NULL);
-				if (err == KErrNone) iValidInfo |= KHeapWalkStatsForOldHeap;
-				}
-			return err;
-			}
-		case EUrelHybridHeap:
-		case EUdebHybridHeap:
-			{
-			TBool needWalk = EFalse;
-			if (aMask & ECommitted)
-				{
-				// RAllocator::Size uses iChunkSize - sizeof(RHybridHeap);
-				// We can't do exactly the same, because we can't calculate sizeof(RHybridHeap), only ROUND_UP(sizeof(RHybridHeap), iAlign)
-				// And if fact we don't bother and just use iChunkSize
-				TUint32 chunkSize = 0;
-				err = ReadWord(iAllocatorAddress + KChunkSizeOffset, chunkSize);
-				if (err) return err;
-				//TUint32 baseAddr = 0;
-				//err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iBase), baseAddr);
-				//if (err) return err;
-				iInfo->iCommittedSize = chunkSize; // - (baseAddr - iAllocatorAddress);
-				iValidInfo |= ECommitted;
-				}
-			if (aMask & (EAllocated|ECount))
-				{
-				if (iAllocatorType == EUdebHybridHeap)
-					{
-					// Easy, just get them from the counter
-					TUint32 totalAlloc = 0;
-					err = ReadWord(iAllocatorAddress + _FOFF(RHackAllocator, iTotalAllocSize), totalAlloc);
-					if (err) return err;
-					iInfo->iAllocatedSize = totalAlloc;
-					iValidInfo |= EAllocated;
-
-					TUint32 cellCount = 0;
-					err = ReadWord(iAllocatorAddress + _FOFF(RHackAllocator, iCellCount), cellCount);
-					if (err) return err;
-					iInfo->iAllocationCount = cellCount;
-					iValidInfo |= ECount;
-					}
-				else
-					{
-					// A heap walk is needed
-					needWalk = ETrue;
-					}
-				}
-			if (aMask & EMaxSize)
-				{
-				TUint32 maxlen = 0;
-				err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iMaxLength), maxlen);
-				if (err) return err;
-				iInfo->iMaxCommittedSize = maxlen;
-				iValidInfo |= EMaxSize;
-				}
-			if (aMask & EMinSize)
-				{
-				TUint32 minlen = 0;
-				err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iAlign) + 4*4, minlen); // iMinLength is in different place to old RHeap
-				if (err) return err;
-				iInfo->iMinCommittedSize = minlen;
-				iValidInfo |= EMinSize;
-				}
-			if (aMask & (EUnusedPages|ECommittedFreeSpace|EHybridStats))
-				{
-				// EAllocated and ECount have already been taken care of above
-				needWalk = ETrue;
-				}
-
-			if (needWalk)
-				{
-				iInfo->ClearStats();
-				iValidInfo = 0;
-				err = DoWalk(&WalkForStats, NULL);
-				if (err == KErrNone) iValidInfo |= KHeapWalkStatsForNewHeap;
-				}
-			return err;
-			}
-		default:
-			return KErrNotSupported;
-		}
-	}
-
-TInt RAllocatorHelper::CheckValid(TUint aMask)
-	{
-	if ((iValidInfo & aMask) == aMask)
-		{
-		return KErrNone;
-		}
-	else
-		{
-		return RefreshDetails(aMask);
-		}
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::CommittedSize()
-	{
-	TInt err = CheckValid(ECommitted);
-	if (err) return err;
-	return iInfo->iCommittedSize;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::AllocatedSize()
-	{
-	TInt err = CheckValid(EAllocated);
-	if (err) return err;
-	return iInfo->iAllocatedSize;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::AllocationCount()
-	{
-	TInt err = CheckValid(ECount);
-	if (err) return err;
-	return iInfo->iAllocationCount;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::RefreshDetails()
-	{
-	return RefreshDetails(iValidInfo);
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::MaxCommittedSize()
-	{
-	TInt err = CheckValid(EMaxSize);
-	if (err) return err;
-	return iInfo->iMaxCommittedSize;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::MinCommittedSize()
-	{
-	TInt err = CheckValid(EMinSize);
-	if (err) return err;
-	return iInfo->iMinCommittedSize;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::AllocCountForCell(TAny* aCell) const
-	{
-	TUint32 allocCount = 0;
-	switch (iAllocatorType)
-		{
-		case EUdebOldRHeap:
-		case EUdebHybridHeap: // Both are in the same place, amazingly
-			{
-			TLinAddr allocCountAddr = (TLinAddr)aCell - 4;
-			TInt err = ReadWord(allocCountAddr, allocCount);
-			if (err) return err;
-			return (TInt)allocCount;
-			}
-		default:
-			return KErrNotSupported;
-		}
-	}
-
-struct SContext3
-	{
-	RAllocatorHelper::TWalkFunc3 iOrigWalkFn;
-	TAny* iOrigContext;
-	};
-
-TBool RAllocatorHelper::DispatchClientWalkCallback(RAllocatorHelper& aHelper, TAny* aContext, RAllocatorHelper::TExtendedCellType aCellType, TLinAddr aCellPtr, TInt aCellLength)
-	{
-	WalkForStats(aHelper, NULL, aCellType, aCellPtr, aCellLength);
-	SContext3* context = static_cast<SContext3*>(aContext);
-	return (*context->iOrigWalkFn)(aHelper, context->iOrigContext, aCellType, aCellPtr, aCellLength);
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::Walk(TWalkFunc3 aCallbackFn, TAny* aContext)
-	{
-	// Might as well take the opportunity of updating our stats at the same time as walking the heap for the client
-	SContext3 context = { aCallbackFn, aContext };
-
-	TInt err = FinishConstruction(); // In case this hasn't been done yet
-	if (err) return err;
-
-	TryLock();
-	err = DoWalk(&DispatchClientWalkCallback, &context);
-	TryUnlock();
-	return err;
-	}
-
-TInt RAllocatorHelper::DoWalk(TWalkFunc3 aCallbackFn, TAny* aContext)
-	{
-	TInt err = KErrNotSupported;
-	switch (iAllocatorType)
-		{
-		case EUdebOldRHeap:
-		case EUrelOldRHeap:
-			err = OldSkoolWalk(aCallbackFn, aContext);
-			break;
-		case EUrelHybridHeap:
-		case EUdebHybridHeap:
-			err = NewHotnessWalk(aCallbackFn, aContext);
-			break;
-		default:
-			err = KErrNotSupported;
-			break;
-		}
-	return err;
-	}
-
-struct SContext
-	{
-	RAllocatorHelper::TWalkFunc iOrigWalkFn;
-	TAny* iOrigContext;
-	};
-
-struct SContext2
-	{
-	RAllocatorHelper::TWalkFunc2 iOrigWalkFn;
-	TAny* iOrigContext;
-	};
-
-#define New2Old(aNew) (((aNew)&RAllocatorHelper::EAllocationMask) ? RAllocatorHelper::EAllocation : ((aNew)&RAllocatorHelper::EFreeMask) ? RAllocatorHelper::EFreeSpace : RAllocatorHelper::EBadness)
-
-TBool DispatchOldTWalkFuncCallback(RAllocatorHelper& /*aHelper*/, TAny* aContext, RAllocatorHelper::TExtendedCellType aCellType, TLinAddr aCellPtr, TInt aCellLength)
-	{
-	SContext* context = static_cast<SContext*>(aContext);
-	return (*context->iOrigWalkFn)(context->iOrigContext, New2Old(aCellType), aCellPtr, aCellLength);
-	}
-
-TBool DispatchOldTWalk2FuncCallback(RAllocatorHelper& aHelper, TAny* aContext, RAllocatorHelper::TExtendedCellType aCellType, TLinAddr aCellPtr, TInt aCellLength)
-	{
-	SContext2* context = static_cast<SContext2*>(aContext);
-	return (*context->iOrigWalkFn)(aHelper, context->iOrigContext, New2Old(aCellType), aCellPtr, aCellLength);
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::Walk(TWalkFunc aCallbackFn, TAny* aContext)
-	{
-	// For backwards compatability insert a compatability callback to map between the different types of callback that clients requested
-	SContext context = { aCallbackFn, aContext };
-	return Walk(&DispatchOldTWalkFuncCallback, &context);
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::Walk(TWalkFunc2 aCallbackFn, TAny* aContext)
-	{
-	SContext2 context = { aCallbackFn, aContext };
-	return Walk(&DispatchOldTWalk2FuncCallback, &context);
-	}
-
-
-TInt RAllocatorHelper::OldSkoolWalk(TWalkFunc3 aCallbackFn, TAny* aContext)
-	{
-	TLinAddr pC = 0;
-	TInt err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iBase), pC); // pC = iBase; // allocated cells
-	if (err) return err;
-	TLinAddr pF = iAllocatorAddress + _FOFF(RHackHeap, iAlign) + 3*4; // pF = &iFree; // free cells
-
-	TLinAddr top = 0;
-	err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iTop), top);
-	if (err) return err;
-	const TInt KAllocatedCellHeaderSize = iAllocatorType == EUdebOldRHeap ? 12 : 4;
-	TInt minCell = 0;
-	err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iAlign) + 4, (TUint32&)minCell);
-	if (err) return err;
-	TInt align = 0;
-	err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iAlign), (TUint32&)align);
-	if (err) return err;
-
-	FOREVER
-		{
-		err = ReadWord(pF+4, pF); // pF = pF->next; // next free cell
-		if (err) return err;
-		TLinAddr pFnext = 0;
-		if (pF) err = ReadWord(pF + 4, pFnext);
-		if (err) return err;
-
-		if (!pF)
-			{
-			pF = top; // to make size checking work
-			}
-		else if (pF>=top || (pFnext && pFnext<=pF) )
-			{
-			// free cell pointer off the end or going backwards
-			//Unlock();
-			(*aCallbackFn)(*this, aContext, EHeapBadFreeCellAddress, pF, 0);
-			return KErrCorrupt;
-			}
-		else
-			{
-			TInt l; // = pF->len
-			err = ReadWord(pF, (TUint32&)l);
-			if (err) return err;
-			if (l<minCell || (l & (align-1)))
-				{
-				// free cell length invalid
-				//Unlock();
-				(*aCallbackFn)(*this, aContext, EHeapBadFreeCellSize, pF, l);
-				return KErrCorrupt;
-				}
-			}
-		
-		while (pC!=pF)				// walk allocated cells up to next free cell
-			{
-			TInt l; // pC->len;
-			err = ReadWord(pC, (TUint32&)l);
-			if (err) return err;
-			if (l<minCell || (l & (align-1)))
-				{
-				// allocated cell length invalid
-				//Unlock();
-				(*aCallbackFn)(*this, aContext, EHeapBadAllocatedCellSize, pC, l);
-				return KErrCorrupt;
-				}
-			TBool shouldContinue = (*aCallbackFn)(*this, aContext, EHeapAllocation, pC + KAllocatedCellHeaderSize, l - KAllocatedCellHeaderSize);
-			if (!shouldContinue) return KErrNone;
-			
-			//SCell* pN = __NEXT_CELL(pC);
-			TLinAddr pN = pC + l;
-			if (pN > pF)
-				{
-				// cell overlaps next free cell
-				//Unlock();
-				(*aCallbackFn)(*this, aContext, EHeapBadAllocatedCellAddress, pC, l);
-				return KErrCorrupt;
-				}
-			pC = pN;
-			}
-		if (pF == top)
-			break;		// reached end of heap
-		TInt pFlen = 0;
-		err = ReadWord(pF, (TUint32&)pFlen);
-		if (err) return err;
-		pC = pF + pFlen; // pC = __NEXT_CELL(pF);	// step to next allocated cell
-		TBool shouldContinue = (*aCallbackFn)(*this, aContext, EHeapFreeCell, pF, pFlen);
-		if (!shouldContinue) return KErrNone;
-		}
-	return KErrNone;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::CountUnusedPages()
-	{
-	TInt err = CheckValid(EUnusedPages);
-	if (err) return err;
-	return iInfo->iUnusedPages;
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::CommittedFreeSpace()
-	{
-	TInt err = CheckValid(ECommittedFreeSpace);
-	if (err) return err;
-	return iInfo->iCommittedFreeSpace;
-	}
-
-#define ROUND_DOWN(val, pow2) ((val) & ~((pow2)-1))
-#define ROUND_UP(val, pow2) ROUND_DOWN((val) + (pow2) - 1, (pow2))
-
-HUEXPORT_C TLinAddr RAllocatorHelper::AllocatorAddress() const
-	{
-	return iAllocatorAddress;
-	}
-
-TBool RAllocatorHelper::WalkForStats(RAllocatorHelper& aSelf, TAny* /*aContext*/, TExtendedCellType aType, TLinAddr aCellPtr, TInt aCellLength)
-	{
-	//ASSERT(aCellLength >= 0);
-	THeapInfo& info = *aSelf.iInfo;
-
-	TInt pagesSpanned = 0; // The number of pages that fit entirely inside the payload of this cell
-	if ((TUint)aCellLength > KPageSize)
-		{
-		TLinAddr nextPageAlignedAddr = ROUND_UP(aCellPtr, KPageSize);
-		pagesSpanned = ROUND_DOWN(aCellPtr + aCellLength - nextPageAlignedAddr, KPageSize) / KPageSize;
-		}
-
-	if (aSelf.iAllocatorType == EUrelOldRHeap || aSelf.iAllocatorType == EUdebOldRHeap)
-		{
-		if (aType & EFreeMask)
-			{
-			info.iUnusedPages += pagesSpanned;
-			info.iCommittedFreeSpace += aCellLength;
-			info.iHeapFreeCellCount++;
-			}
-		}
-	else
-		{
-		if (aType & EAllocationMask)
-			{
-			info.iAllocatedSize += aCellLength;
-			info.iAllocationCount++;
-			}
-		else if (aType & EFreeMask)
-			{
-			// I *think* that DLA will decommit pages from inside free cells...
-			TInt committedLen = aCellLength - (pagesSpanned * KPageSize);
-			info.iCommittedFreeSpace += committedLen;
-			}
-
-		switch (aType)
-			{
-			case EDlaAllocation:
-				info.iDlaAllocsSize += aCellLength;
-				info.iDlaAllocsCount++;
-				break;
-			case EPageAllocation:
-				info.iPageAllocsSize += aCellLength;
-				info.iPageAllocsCount++;
-				break;
-			case ESlabAllocation:
-				info.iSlabAllocsSize += aCellLength;
-				info.iSlabAllocsCount++;
-				break;
-			case EDlaFreeCell:
-				info.iDlaFreeSize += aCellLength;
-				info.iDlaFreeCount++;
-				break;
-			case ESlabFreeCell:
-				info.iSlabFreeCellSize += aCellLength;
-				info.iSlabFreeCellCount++;
-				break;
-			case ESlabFreeSlab:
-				info.iSlabFreeSlabSize += aCellLength;
-				info.iSlabFreeSlabCount++;
-				break;
-			default:
-				break;
-			}
-		}
-
-	return ETrue;
-	}
-
-#define PAGESHIFT 12
-
-TUint RAllocatorHelper::PageMapOperatorBrackets(unsigned ix, TInt& err) const
-	{
-	//return 1U&(iBase[ix>>3] >> (ix&7));
-	TUint32 basePtr = 0;
-	err = ReadWord(iAllocatorAddress + KPageMapOffset, basePtr);
-	if (err) return 0;
-
-	TUint8 res = 0;
-	err = ReadByte(basePtr + (ix >> 3), res);
-	if (err) return 0;
-
-	return 1U&(res >> (ix&7));
-	}
-
-
-TInt RAllocatorHelper::PageMapFind(TUint start, TUint bit, TInt& err)
-	{
-	TUint32 iNbits = 0;
-	err = ReadWord(iAllocatorAddress + KPageMapOffset + 4, iNbits);
-	if (err) return 0;
-
-	if (start<iNbits) do
-		{
-		//if ((*this)[start]==bit)
-		if (PageMapOperatorBrackets(start, err) == bit || err)
-			return start;
-		} while (++start<iNbits);
-	return -1;
-	}
-
-TUint RAllocatorHelper::PagedDecode(TUint pos, TInt& err)
-	{
-	unsigned bits = PageMapBits(pos,2,err);
-	if (err) return 0;
-	bits >>= 1;
-	if (bits == 0)
-		return 1;
-	bits = PageMapBits(pos+2,2,err);
-	if (err) return 0;
-	if ((bits & 1) == 0)
-		return 2 + (bits>>1);
-	else if ((bits>>1) == 0)
-		{
-		return PageMapBits(pos+4, 4,err);
-		}
-	else
-		{
-		return PageMapBits(pos+4, 18,err);
-		}
-	}
-
-TUint RAllocatorHelper::PageMapBits(unsigned ix, unsigned len, TInt& err)
-	{
-	int l=len;
-	unsigned val=0;
-	unsigned bit=0;
-	while (--l>=0)
-		{
-		//val |= (*this)[ix++]<<bit++;
-		val |= PageMapOperatorBrackets(ix++, err) << bit++;
-		if (err) return 0;
-		}
-	return val;
-	}
-
-enum TSlabType { ESlabFullInfo, ESlabPartialInfo, ESlabEmptyInfo };
-
-#ifndef TEST_HYBRIDHEAP_ASSERTS
-#define MAXSLABSIZE		56
-#define	SLABSHIFT		10
-#define	SLABSIZE		(1 << SLABSHIFT)
-const TInt KMaxSlabPayload = SLABSIZE - KSlabPayloadOffset;
-#endif
-
-TInt RAllocatorHelper::NewHotnessWalk(TWalkFunc3 aCallbackFn, TAny* aContext)
-	{
-	// RHybridHeap does paged, slab then DLA, so that's what we do too
-	// Remember Kernel RHybridHeaps don't even have the page and slab members
-
-	TUint32 basePtr;
-	TInt err = ReadWord(iAllocatorAddress + _FOFF(RHackHeap, iBase), basePtr);
-	if (err) return err;
-	if (basePtr < iAllocatorAddress + KUserHybridHeapSize)
-		{
-		// Must be a kernel one - don't do page and slab
-		}
-	else
-		{
-		// Paged
-		TUint32 membase = 0;
-		err = ReadWord(iAllocatorAddress + KPageMapOffset + 8, membase);
-		if (err) return err;
-
-		TBool shouldContinue = ETrue;
-		for (int ix = 0;(ix = PageMapFind(ix,1,err)) >= 0 && err == KErrNone;)
-			{
-			int npage = PagedDecode(ix, err);
-			if (err) return err;
-			// Introduce paged buffer to the walk function 
-			TLinAddr bfr = membase + (1 << (PAGESHIFT-1))*ix;
-			int len = npage << PAGESHIFT;
-			if ( (TUint)len > KPageSize )
-				{ // If buffer is not larger than one page it must be a slab page mapped into bitmap
-				if (iAllocatorType == EUdebHybridHeap)
-					{
-					bfr += 8;
-					len -= 8;
-					}
-				shouldContinue = (*aCallbackFn)(*this, aContext, EPageAllocation, bfr, len);
-				if (!shouldContinue) return KErrNone;
-				}
-			ix += (npage<<1);
-			}
-		if (err) return err;
-
-		// Slab
-		TUint32 sparePage = 0;
-		err = ReadWord(iAllocatorAddress + KSparePageOffset, sparePage);
-		if (err) return err;
-		if (sparePage)
-			{
-			//Walk(wi, iSparePage, iPageSize, EGoodFreeCell, ESlabSpare); // Introduce Slab spare page to the walk function 
-			// This counts as 4 spare slabs
-			for (TInt i = 0; i < 4; i++)
-				{
-				shouldContinue = (*aCallbackFn)(*this, aContext, ESlabFreeSlab, sparePage + SLABSIZE*i, SLABSIZE);
-				if (!shouldContinue) return KErrNone;
-				}
-			}
-
-		//TreeWalk(&iFullSlab, &SlabFullInfo, i, wi);
-		TInt err = TreeWalk(iAllocatorAddress + KFullSlabOffset, ESlabFullInfo, aCallbackFn, aContext, shouldContinue);
-		if (err || !shouldContinue) return err;
-		for (int ix = 0; ix < (MAXSLABSIZE>>2); ++ix)
-			{
-			TUint32 partialAddr = iAllocatorAddress + KSlabAllocOffset + ix*KSlabsetSize;
-			//TreeWalk(&iSlabAlloc[ix].iPartial, &SlabPartialInfo, i, wi);
-			err = TreeWalk(partialAddr, ESlabPartialInfo, aCallbackFn, aContext, shouldContinue);
-			if (err || !shouldContinue) return err;
-			}
-		//TreeWalk(&iPartialPage, &SlabEmptyInfo, i, wi);
-		TreeWalk(iAllocatorAddress + KPartialPageOffset, ESlabEmptyInfo, aCallbackFn, aContext, shouldContinue);
-		}
-
-	// DLA
-#define CHUNK_OVERHEAD (sizeof(TUint))
-#define CHUNK_ALIGN_MASK (7) 
-#define CHUNK2MEM(p)        ((TLinAddr)(p) + 8)
-#define MEM2CHUNK(mem)      ((TLinAddr)(p) - 8)
-/* chunk associated with aligned address A */
-#define ALIGN_OFFSET(A)\
-	((((TLinAddr)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
-	((8 - ((TLinAddr)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
-#define ALIGN_AS_CHUNK(A)   ((A) + ALIGN_OFFSET(CHUNK2MEM(A)))
-#define CINUSE_BIT 2
-#define INUSE_BITS 3
-
-	TUint32 topSize = 0;
-	err = ReadWord(iAllocatorAddress + KMallocStateOffset + KMallocStateTopSizeOffset, topSize);
-	if (err) return err;
-
-	TUint32 top = 0;
-	err = ReadWord(iAllocatorAddress + KMallocStateOffset + KMallocStateTopOffset, top);
-	if (err) return err;
-
-	TInt max = ((topSize-1) & ~CHUNK_ALIGN_MASK) - CHUNK_OVERHEAD;
-	if ( max < 0 )
-		max = 0;
-	
-	TBool shouldContinue = (*aCallbackFn)(*this, aContext, EDlaFreeCell, top, max);
-	if (!shouldContinue) return KErrNone;
-	
-	TUint32 mallocStateSegBase = 0;
-	err = ReadWord(iAllocatorAddress + KMallocStateOffset + KMallocStateSegOffset, mallocStateSegBase);
-	if (err) return err;
-
-	for (TLinAddr q = ALIGN_AS_CHUNK(mallocStateSegBase); q != top; /*q = NEXT_CHUNK(q)*/)
-		{
-		TUint32 qhead = 0;
-		err = ReadWord(q + 4, qhead);
-		if (err) return err;
-		//TInt sz = CHUNKSIZE(q);
-		TInt sz = qhead & ~(INUSE_BITS);
-		if (!(qhead & CINUSE_BIT))
-			{
-			//Walk(wi, CHUNK2MEM(q), sz, EGoodFreeCell, EDougLeaAllocator); // Introduce DL free buffer to the walk function 
-			shouldContinue = (*aCallbackFn)(*this, aContext, EDlaFreeCell, CHUNK2MEM(q), sz);
-			if (!shouldContinue) return KErrNone;
-			}
-		else
-			{
-			//Walk(wi, CHUNK2MEM(q), (sz- CHUNK_OVERHEAD), EGoodAllocatedCell, EDougLeaAllocator); // Introduce DL allocated buffer to the walk function 
-			TLinAddr addr = CHUNK2MEM(q);
-			TInt size = sz - CHUNK_OVERHEAD;
-			if (iAllocatorType == EUdebHybridHeap)
-				{
-				size -= 8;
-				addr += 8;
-				}
-			shouldContinue = (*aCallbackFn)(*this, aContext, EDlaAllocation, addr, size);
-			if (!shouldContinue) return KErrNone;
-			}
-		// This is q = NEXT_CHUNK(q) expanded
-		q = q + sz;
-		}
-	return KErrNone;
-	}
-
-TInt RAllocatorHelper::TreeWalk(TUint32 aSlabRoot, TInt aSlabType, TWalkFunc3 aCallbackFn, TAny* aContext, TBool& shouldContinue)
-	{
-	const TSlabType type = (TSlabType)aSlabType;
-
-	TUint32 s = 0;
-	TInt err = ReadWord(aSlabRoot, s);
-	if (err) return err;
-	//slab* s = *root;
-	if (!s)
-		return KErrNone;
-	
-	for (;;)
-		{
-		//slab* c;
-		//while ((c = s->iChild1) != 0)
-		//	s = c;		// walk down left side to end
-		TUint32 c;
-		for(;;)
-			{
-			err = ReadWord(s + KSlabChild1Offset, c);
-			if (err) return err;
-			if (c == 0) break;
-			else s = c;
-			}
-		for (;;)
-			{
-			//TODOf(s, i, wi);
-			//TODO __HEAP_CORRUPTED_TEST_STATIC
-			TUint32 h;
-			err = ReadWord(s, h); // = aSlab->iHeader;
-			if (err) return err;
-			TUint32 size = (h&0x0003f000)>>12; //SlabHeaderSize(h);
-			TUint debugheadersize = 0;
-			if (iAllocatorType == EUdebHybridHeap) debugheadersize = 8;
-			TUint32 usedCount = (((h&0x0ffc0000)>>18) + 4) / size; // (SlabHeaderUsedm4(h) + 4) / size;
-			switch (type)
-				{
-				case ESlabFullInfo:
-					{
-					TUint32 count = usedCount;
-					TUint32 i = 0;
-					while ( i < count )
-						{
-						TUint32 addr = s + KSlabPayloadOffset + i*size; //&aSlab->iPayload[i*size];
-						shouldContinue = (*aCallbackFn)(*this, aContext, ESlabAllocation, addr + debugheadersize, size - debugheadersize);
-						if (!shouldContinue) return KErrNone;
-						i++;
-						}
-					break;
-					}
-				case ESlabPartialInfo:
-					{
-					//TODO __HEAP_CORRUPTED_TEST_STATIC
-					TUint32 count = KMaxSlabPayload / size;
-					TUint32 freeOffset = (h & 0xff) << 2;
-					if (freeOffset == 0)
-						{
-						// TODO Shouldn't happen for a slab on the partial list
-						}
-					memset(iTempSlabBitmap, 1, KTempBitmapSize); // Everything defaults to in use
-					TUint wildernessCount = count - usedCount;
-					while (freeOffset)
-						{
-						wildernessCount--;
-						TInt idx = (freeOffset-KSlabPayloadOffset)/size;
-						LOG("iTempSlabBitmap freeOffset %d index %d", freeOffset, idx);
-						iTempSlabBitmap[idx] = 0; // Mark it as free
-
-						TUint32 addr = s + freeOffset;
-						TUint8 nextCell = 0;
-						err = ReadByte(addr, nextCell);
-						if (err) return err;
-						freeOffset = ((TUint32)nextCell) << 2;
-						}
-					memset(iTempSlabBitmap + count - wildernessCount, 0, wildernessCount); // Mark the wilderness as free
-					for (TInt i = 0; i < count; i++)
-						{
-						TLinAddr addr = s + KSlabPayloadOffset + i*size;
-						if (iTempSlabBitmap[i])
-							{
-							// In use
-							shouldContinue = (*aCallbackFn)(*this, aContext, ESlabAllocation, addr + debugheadersize, size - debugheadersize);
-							}
-						else
-							{
-							// Free
-							shouldContinue = (*aCallbackFn)(*this, aContext, ESlabFreeCell, addr, size);
-							}
-						if (!shouldContinue) return KErrNone;
-						}
-					break;
-					}
-				case ESlabEmptyInfo:
-					{
-					// Check which slabs of this page are empty
-					TUint32 pageAddr = ROUND_DOWN(s, KPageSize);
-					TUint32 headerForPage = 0;
-					err = ReadWord(pageAddr, headerForPage);
-					if (err) return err;
-					TUint32 slabHeaderPageMap = (headerForPage & 0x00000f00)>>8; // SlabHeaderPagemap(unsigned h)
-					for (TInt slabIdx = 0; slabIdx < 4; slabIdx++)
-						{
-						if (slabHeaderPageMap & (1<<slabIdx))
-							{
-							TUint32 addr = pageAddr + SLABSIZE*slabIdx + KSlabPayloadOffset; //&aSlab->iPayload[i*size];
-							shouldContinue = (*aCallbackFn)(*this, aContext, ESlabFreeSlab, addr, KMaxSlabPayload);
-							if (!shouldContinue) return KErrNone;
-							}
-						}
-					break;
-					}
-				}
-
-			//c = s->iChild2;
-			err = ReadWord(s + KSlabChild2Offset, c);
-			if (err) return err;
-
-			if (c)
-				{	// one step down right side, now try and walk down left
-				s = c;
-				break;
-				}
-			for (;;)
-				{	// loop to walk up right side
-				TUint32 pp = 0;
-				err = ReadWord(s + KSlabParentOffset, pp);
-				if (err) return err;
-				//slab** pp = s->iParent;
-				if (pp == aSlabRoot)
-					return KErrNone;
-#define SlabFor(x) ROUND_DOWN(x, SLABSIZE)
-				s = SlabFor(pp);
-				//if (pp == &s->iChild1)
-				if (pp == s + KSlabChild1Offset)
-					break;
-				}
-			}
-		}
-	}
-
-// Really should be called TotalSizeForCellType(...)
-HUEXPORT_C TInt RAllocatorHelper::SizeForCellType(TExtendedCellType aType)
-	{
-	if (aType & EBadnessMask) return KErrArgument;
-	if (aType == EAllocationMask) return AllocatedSize();
-
-	if (iAllocatorType == EUdebOldRHeap || iAllocatorType == EUrelOldRHeap)
-		{
-		switch (aType)
-			{
-			case EHeapAllocation:
-				return AllocatedSize();
-			case EHeapFreeCell:
-			case EFreeMask:
-				return CommittedFreeSpace();
-			default:
-				return KErrNotSupported;
-			}
-		}
-	else if (iAllocatorType == EUrelHybridHeap || iAllocatorType == EUdebHybridHeap)
-		{
-		TInt err = CheckValid(EHybridStats);
-		if (err) return err;
-
-		switch (aType)
-			{
-			case EHeapAllocation:
-			case EHeapFreeCell:
-				return KErrNotSupported;
-			case EDlaAllocation:
-				return iInfo->iDlaAllocsSize;
-			case EPageAllocation:
-				return iInfo->iPageAllocsSize;
-			case ESlabAllocation:
-				return iInfo->iSlabAllocsSize;
-			case EDlaFreeCell:
-				return iInfo->iDlaFreeSize;
-			case ESlabFreeCell:
-				return iInfo->iSlabFreeCellSize;
-			case ESlabFreeSlab:
-				return iInfo->iSlabFreeSlabSize;
-			case EFreeMask:
-				// Note this isn't the same as asking for CommittedFreeSpace(). SizeForCellType(EFreeMask) may include decommitted pages that lie inside a free cell
-				return iInfo->iDlaFreeSize + iInfo->iSlabFreeCellSize + iInfo->iSlabFreeSlabSize;
-			default:
-				return KErrNotSupported;
-			}
-		}
-	else
-		{
-		return KErrNotSupported;
-		}
-	}
-
-HUEXPORT_C TInt RAllocatorHelper::CountForCellType(TExtendedCellType aType)
-	{
-	if (aType & EBadnessMask) return KErrArgument;
-	if (aType == EAllocationMask) return AllocationCount();
-
-	if (iAllocatorType == EUdebOldRHeap || iAllocatorType == EUrelOldRHeap)
-		{
-		switch (aType)
-			{
-			case EHeapAllocation:
-				return AllocationCount();
-			case EHeapFreeCell:
-			case EFreeMask:
-				{
-				TInt err = CheckValid(ECommittedFreeSpace);
-				if (err) return err;
-				return iInfo->iHeapFreeCellCount;
-				}
-			default:
-				return KErrNotSupported;
-			}
-		}
-	else if (iAllocatorType == EUrelHybridHeap || iAllocatorType == EUdebHybridHeap)
-		{
-		TInt err = CheckValid(EHybridStats);
-		if (err) return err;
-
-		switch (aType)
-			{
-			case EHeapAllocation:
-			case EHeapFreeCell:
-				return KErrNotSupported;
-			case EDlaAllocation:
-				return iInfo->iDlaAllocsCount;
-			case EPageAllocation:
-				return iInfo->iPageAllocsCount;
-			case ESlabAllocation:
-				return iInfo->iSlabAllocsCount;
-			case EDlaFreeCell:
-				return iInfo->iDlaFreeCount;
-			case ESlabFreeCell:
-				return iInfo->iSlabFreeCellCount;
-			case ESlabFreeSlab:
-				return iInfo->iSlabFreeSlabCount;
-			case EFreeMask:
-				// This isn't a hugely meaningful value, but if that's what they asked for...
-				return iInfo->iDlaFreeCount + iInfo->iSlabFreeCellCount + iInfo->iSlabFreeSlabCount;
-			default:
-				return KErrNotSupported;
-			}
-		}
-	else
-		{
-		return KErrNotSupported;
-		}
-	}
-
-HUEXPORT_C TBool LtkUtils::RAllocatorHelper::AllocatorIsUdeb() const
-	{
-	return iAllocatorType == EUdebOldRHeap || iAllocatorType == EUdebHybridHeap;
-	}
-
-
-HUEXPORT_C const TDesC& LtkUtils::RAllocatorHelper::Description() const
-	{
-	_LIT(KRHeap, "RHeap");
-	_LIT(KRHybridHeap, "RHybridHeap");
-	_LIT(KUnknown, "Unknown");
-	switch (iAllocatorType)
-		{
-		case EUrelOldRHeap:
-		case EUdebOldRHeap:
-			return KRHeap;
-		case EUrelHybridHeap:
-		case EUdebHybridHeap:
-			return KRHybridHeap;
-		case EAllocator:
-		case EUnknown:
-		default:
-			return KUnknown;
-		}
-	}
-
-#ifdef __KERNEL_MODE__
-
-DChunk* LtkUtils::RAllocatorHelper::OpenUnderlyingChunk()
-	{
-	// Enter and leave in CS and with no locks held. On exit the returned DChunk has been Open()ed.
-	TInt err = iChunk->Open();
-	if (err) return NULL;
-	return iChunk;
-	}
-
-DChunk* LtkUtils::RKernelSideAllocatorHelper::OpenUnderlyingChunk()
-	{
-	if (iAllocatorType != EUrelOldRHeap && iAllocatorType != EUdebOldRHeap && iAllocatorType != EUrelHybridHeap && iAllocatorType != EUdebHybridHeap) return NULL;
-	// Note RKernelSideAllocatorHelper doesn't use or access RAllocatorHelper::iChunk, because we figure out the chunk handle in a different way.
-	// It is for this reason that iChunk is private, to remove temptation
-	
-	// Enter and leave in CS and with no locks held. On exit the returned DChunk has been Open()ed.
-	TUint32 chunkHandle = 0;
-	TInt err = ReadData(iAllocatorAddress + _FOFF(RHackHeap, iChunkHandle), &chunkHandle, sizeof(TUint32));
-	if (err) return NULL;
-
-	NKern::LockSystem();
-	DChunk* result = (DChunk*)Kern::ObjectFromHandle(iThread, chunkHandle, EChunk);
-	if (result && result->Open() != KErrNone)
-		{
-		result = NULL;
-		}
-	NKern::UnlockSystem();
-	return result;
-	}
-
-LtkUtils::RAllocatorHelper::TType LtkUtils::RAllocatorHelper::GetType() const
-	{
-	switch (iAllocatorType)
-		{
-		case EUrelOldRHeap:
-		case EUdebOldRHeap:
-			return ETypeRHeap;
-		case EUrelHybridHeap:
-		case EUdebHybridHeap:
-			return ETypeRHybridHeap;
-		case EAllocator:
-		case EUnknown:
-		default:
-			return ETypeUnknown;
-		}
-	}
-
-#else
-
-TInt LtkUtils::RAllocatorHelper::EuserIsUdeb()
-	{
-	TAny* buf = User::Alloc(4096);
-	if (!buf) return KErrNoMemory;
-	RAllocator* dummyHeap = UserHeap::FixedHeap(buf, 4096, 4, ETrue);
-	if (!dummyHeap) return KErrNoMemory; // Don't think this can happen
-
-	dummyHeap->__DbgSetAllocFail(RAllocator::EFailNext, 1);
-	TAny* ptr = dummyHeap->Alloc(4);
-	// Because we specified singleThreaded=ETrue we can allow dummyHeap to just go out of scope here
-	User::Free(buf);
-
-	if (ptr)
-		{
-		// Clearly the __DbgSetAllocFail had no effect so we must be urel
-		// We don't need to free ptr because it came from the dummy heap
-		return EFalse;
-		}
-	else
-		{
-		return ETrue;
-		}
-	}
-
-#ifndef STANDALONE_ALLOCHELPER
-
-#include <fshell/ltkutils.h>
-HUEXPORT_C void LtkUtils::MakeHeapCellInvisible(TAny* aCell)
-	{
-	RAllocatorHelper helper;
-	TInt err = helper.Open(&User::Allocator());
-	if (err == KErrNone)
-		{
-		helper.SetCellNestingLevel(aCell, -1);
-		helper.Close();
-		}
-	}
-#endif // STANDALONE_ALLOCHELPER
-
-#endif
--- a/memspy/Driver/Shared/heaputils.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,216 +0,0 @@
-// heaputils.h
-// 
-// Copyright (c) 2010 Accenture. All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the "Eclipse Public License v1.0"
-// which accompanies this distribution, and is available
-// at the URL "http://www.eclipse.org/legal/epl-v10.html".
-// 
-// Initial Contributors:
-// Accenture - Initial contribution
-//
-
-
-#ifndef FSHELL_HEAP_UTILS_H
-#define FSHELL_HEAP_UTILS_H
-
-#include <e32cmn.h>
-
-#ifdef __KERNEL_MODE__
-class DThread;
-class DChunk;
-#else
-class RMemoryAccess;
-#endif // __KERNEL_MODE__
-
-#if defined(STANDALONE_ALLOCHELPER) || defined(__KERNEL_MODE__)
-#define HUIMPORT_C
-#define HUCLASS(x) NONSHARABLE_CLASS(x)
-#else
-#define HUIMPORT_C IMPORT_C
-#define HUCLASS(x) class x
-#endif
-
-namespace LtkUtils
-	{
-
-class THeapInfo;
-	
-HUCLASS(RAllocatorHelper) // class RAllocatorHelper
-	{
-public:
-	HUIMPORT_C RAllocatorHelper();
-#ifdef __KERNEL_MODE__
-	TInt OpenKernelHeap();
-#else
-	HUIMPORT_C TInt Open(RAllocator* aAllocator);
-#endif
-	HUIMPORT_C TInt SetCellNestingLevel(TAny* aCell, TInt aNestingLevel);
-	HUIMPORT_C TInt GetCellNestingLevel(TAny* aCell, TInt& aNestingLevel);
-	HUIMPORT_C TInt AllocCountForCell(TAny* aCell) const;
-	HUIMPORT_C TLinAddr AllocatorAddress() const;
-	HUIMPORT_C TInt RefreshDetails();
-	
-	HUIMPORT_C TInt CommittedSize();
-	HUIMPORT_C TInt AllocatedSize();
-	HUIMPORT_C TInt AllocationCount();
-	HUIMPORT_C TInt MaxCommittedSize();
-	HUIMPORT_C TInt MinCommittedSize();
-	HUIMPORT_C TInt CountUnusedPages();
-	HUIMPORT_C TInt CommittedFreeSpace();
-
-	enum TCellType
-		{
-		EAllocation, EFreeSpace, EBadness
-		};
-
-	enum TExtendedCellType
-		{
-		EAllocationMask = 0xFF,
-		EFreeMask = 0xFF00,
-		EBadnessMask = 0xFF000000,
-
-		EHeapAllocation = 1,
-		EDlaAllocation = 2,
-		EPageAllocation = 3,
-		ESlabAllocation = 4,
-		
-		EHeapFreeCell = 0x0100,
-		EDlaFreeCell = 0x0200,
-		// There is nothing 'free' in the page allocator
-		ESlabFreeCell = 0x0300, // Used to track free cells in partially-filled slabs
-		ESlabFreeSlab = 0x0400, // Used to track entirely empty slabs (that don't have a specific cell size)
-
-		EHeapBadFreeCellAddress = 0x01000000,
-		EHeapBadFreeCellSize = 0x02000000,
-		EHeapBadAllocatedCellSize = 0x03000000,
-		EHeapBadAllocatedCellAddress = 0x04000000,
-		};
-			
-	// TBool WalkFunc(TAny* aContext, TCellType aCellType, TLinAddr aCellPtr, TInt aCellLength)
-	// aCellPtr points to the start of the cell payload for allocated cells (unlike RHeap's walker, which points to the cell header)
-	// aCellLength is the payload length, ie what AllocLen(aCellPtr) would return
-	// return ETrue to continue walking, EFalse to stop the walk
-	typedef TBool (*TWalkFunc)(TAny*, TCellType, TLinAddr, TInt);
-	typedef TBool (*TWalkFunc2)(RAllocatorHelper&, TAny*, TCellType, TLinAddr, TInt);
-	typedef TBool (*TWalkFunc3)(RAllocatorHelper&, TAny*, TExtendedCellType, TLinAddr, TInt);
-	HUIMPORT_C TInt Walk(TWalkFunc aCallbackFn, TAny* aContext);
-	HUIMPORT_C TInt Walk(TWalkFunc2 aCallbackFn, TAny* aContext); // Like the other but the walk func gives you the RAllocatorHelper pointer too
-	HUIMPORT_C TInt Walk(TWalkFunc3 aCallbackFn, TAny* aContext); // Like the other but the walk func gives you more details about the allocation type
-	HUIMPORT_C TInt SizeForCellType(TExtendedCellType aType);
-	HUIMPORT_C TInt CountForCellType(TExtendedCellType aType);
-	HUIMPORT_C TBool AllocatorIsUdeb() const;
-	HUIMPORT_C const TDesC& Description() const;
-	HUIMPORT_C virtual void Close();
-
-#ifdef __KERNEL_MODE__
-	virtual DChunk* OpenUnderlyingChunk(); // Must be in CS
-	enum TType
-		{
-		ETypeUnknown,
-		ETypeRHeap,
-		ETypeRHybridHeap,
-		};
-	TType GetType() const; // This is for information only, nothing should care about the return value
-#endif
-
-protected:
-	TInt FinishConstruction();
-	TInt IdentifyAllocatorType(TBool aAllocatorIsUdeb, TBool aIsTheKernelHeap=EFalse);
-	TInt OpenChunkHeap(TLinAddr aChunkBase, TInt aChunkMaxSize);
-#ifndef __KERNEL_MODE__
-	static TInt EuserIsUdeb();
-#endif
-	virtual TInt ReadData(TLinAddr aLocation, TAny* aResult, TInt aSize) const;
-	virtual TInt WriteData(TLinAddr aLocation, const TAny* aData, TInt aSize);
-	virtual TInt TryLock();
-	virtual void TryUnlock();
-
-private:
-	TInt ReadWord(TLinAddr aLocation, TUint32& aResult) const;
-	TInt ReadByte(TLinAddr aLocation, TUint8& aResult) const;
-	TInt WriteWord(TLinAddr aLocation, TUint32 aWord);
-	TInt RefreshDetails(TUint aMask);
-	TInt DoRefreshDetails(TUint aMask);
-	TInt CheckValid(TUint aMask);
-	TInt DoWalk(TWalkFunc3 aCallbackFn, TAny* aContext);
-	TInt OldSkoolWalk(TWalkFunc3 aCallbackFn, TAny* aContext);
-	TInt NewHotnessWalk(TWalkFunc3 aCallbackFn, TAny* aContext);
-	static TBool DispatchClientWalkCallback(RAllocatorHelper& aHelper, TAny* aContext, TExtendedCellType aCellType, TLinAddr aCellPtr, TInt aCellLength);
-	static TBool WalkForStats(RAllocatorHelper& aSelf, TAny* aContext, TExtendedCellType aType, TLinAddr aCellPtr, TInt aCellLength);
-	TUint PageMapOperatorBrackets(unsigned ix, TInt& err) const;
-	TInt PageMapFind(TUint start, TUint bit, TInt& err);
-	TUint PageMapBits(unsigned ix, unsigned len, TInt& err);
-	TUint PagedDecode(TUint pos, TInt& err);
-	TInt TreeWalk(TUint32 aSlabRoot, TInt aSlabType, TWalkFunc3 aCallbackFn, TAny* aContext, TBool& shouldContinue);
-protected:
-	TLinAddr iAllocatorAddress;
-	enum TAllocatorType
-		{
-		EUnknown,
-		EAllocator,
-		EUrelOldRHeap,
-		EUdebOldRHeap,
-		EUrelHybridHeap,
-		EUdebHybridHeap,
-		};
-	TAllocatorType iAllocatorType;
-private:
-	THeapInfo* iInfo;
-	TUint iValidInfo;
-	TUint8* iTempSlabBitmap;
-	mutable TAny* iPageCache;
-	mutable TLinAddr iPageCacheAddr;
-#ifdef __KERNEL_MODE__
-	DChunk* iChunk;
-	//TUint iSpare[0];
-#else
-	TUint iSpare[1];
-#endif
-	};
-
-#ifdef __KERNEL_MODE__
-
-class RKernelSideAllocatorHelper : public RAllocatorHelper
-	{
-public:
-	RKernelSideAllocatorHelper();
-	TInt OpenUserHeap(TUint aThreadId, TLinAddr aAllocatorAddress, TBool aEuserIsUdeb);
-	virtual DChunk* OpenUnderlyingChunk(); // Must be in CS
-	virtual void Close();
-
-protected:
-	virtual TInt ReadData(TLinAddr aLocation, TAny* aResult, TInt aSize) const;
-	virtual TInt WriteData(TLinAddr aLocation, const TAny* aData, TInt aSize);
-	virtual TInt TryLock();
-	virtual void TryUnlock();
-private:
-	DThread* iThread;
-	};
-
-#else
-
-class RProxyAllocatorHelper : public RAllocatorHelper
-	{
-public:
-	HUIMPORT_C RProxyAllocatorHelper();
-	HUIMPORT_C TInt Open(RMemoryAccess& aMem, TUint aThreadId);
-	HUIMPORT_C TInt OpenChunkHeap(RMemoryAccess& aMem, TAny* aDChunkPtr);
-	HUIMPORT_C virtual void Close();
-
-protected:
-	virtual TInt ReadData(TLinAddr aLocation, TAny* aResult, TInt aSize) const;
-	virtual TInt WriteData(TLinAddr aLocation, const TAny* aData, TInt aSize);
-	virtual TInt TryLock();
-	virtual void TryUnlock();
-
-private:
-	RMemoryAccess* iMemoryAccess;
-	TUint iThreadId;
-	};
-
-#endif // __KERNEL_MODE__
-
-	} // namespace LtkUtils
-
-#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/memspy/Driver/User/Include/RBuildQueryableHeap.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#ifndef RBUILDQUERYABLEHEAP_H
+#define RBUILDQUERYABLEHEAP_H
+
+// System includes
+#include <e32cmn.h>
+
+// User includes
+#include <memspy/driver/memspydriverenumerationsshared.h>
+
+
+class RBuildQueryableHeap : public RHeap
+    {
+public: // API
+    TBool IsDebugEUser() const;
+    TInt CellHeaderSize( TMemSpyDriverCellType aType ) const;
+    };
+
+
+
+#endif
--- a/memspy/Driver/User/Source/MemSpyDriverClient.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/User/Source/MemSpyDriverClient.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -22,11 +22,11 @@
 
 // User includes
 #include "MemSpyDriverOpCodes.h"
+#include "RBuildQueryableHeap.h"
 #include <memspy/driver/memspydriverconstants.h>
 #include <memspy/driver/memspydriverobjectsshared.h>
 #include "MemSpyDriverStreamReaderImp.h"
 #include "MemSpyDriverObjectsInternal.h"
-#include "heaputils.h"
 
 // Constants
 const TInt KMemSpyClientBufferGrowSize = 0x1000 * 8; // 32kb
@@ -511,7 +511,7 @@
             TMemSpyHeapInfoRHeap& rHeapInfo = aInfo.AsRHeap();
             TMemSpyHeapMetaDataRHeap& metaData = rHeapInfo.MetaData();
             metaData.SetVTable( RHeapVTable() );
-            //metaData.SetClassSize( sizeof( RHeap ) );
+            metaData.SetClassSize( sizeof( RHeap ) );
             }
         }
     else if ( r == KErrNotSupported )
@@ -523,14 +523,9 @@
 	return r;
     }
 
+
 EXPORT_C TInt RMemSpyDriverClient::GetHeapInfoUser( TMemSpyHeapInfo& aInfo, TUint aTid, RArray< TMemSpyDriverFreeCell >& aFreeCells )
-	{
-	return GetHeapInfoUser(aInfo, aTid, aFreeCells, EFalse);
-	}
-
-// For the record I don't think this function should be exported, but since the one above was I'm going with the flow. -TomS
-EXPORT_C TInt RMemSpyDriverClient::GetHeapInfoUser(TMemSpyHeapInfo& aInfo, TUint aTid, RArray<TMemSpyDriverCell>& aCells, TBool aCollectAllocatedCellsAsWellAsFree)
-	{
+    {
     TMemSpyDriverInternalHeapRequestParameters params;
     //
     params.iTid = aTid;
@@ -538,10 +533,8 @@
     params.iDebugAllocator = DebugEUser();
     params.iMasterInfo = &aInfo;
     params.iBuildFreeCellList = ETrue;
-	params.iBuildAllocCellList = aCollectAllocatedCellsAsWellAsFree;
-
     //
-    aCells.Reset();
+    aFreeCells.Reset();
     ResetStreamBuffer();
 	TInt r = DoControl( EMemSpyDriverOpCodeHeapInfoGetUser, &params );
 	//
@@ -555,7 +548,7 @@
             TMemSpyHeapInfoRHeap& rHeapInfo = aInfo.AsRHeap();
             TMemSpyHeapMetaDataRHeap& metaData = rHeapInfo.MetaData();
             metaData.SetVTable( RHeapVTable() );
-            //metaData.SetClassSize( sizeof( RHeap ) );
+            metaData.SetClassSize( sizeof( RHeap ) );
             }
 
         // Resize transfer buffer to make room for free cells. We only make the buffer
@@ -568,10 +561,10 @@
         // Now fetch the heap data
         if  ( r == KErrNone )
             {
-            r = DoControl( EMemSpyDriverOpCodeHeapInfoFetchCellList, &iBuffer );
+            r = DoControl( EMemSpyDriverOpCodeHeapInfoFetchFreeCells, &iBuffer );
             if  ( r == KErrNone )
                 {
-                TRAP( r, ReadHeapInfoFreeCellsFromXferBufferL( aCells ) );
+                TRAP( r, ReadHeapInfoFreeCellsFromXferBufferL( aFreeCells ) );
                 }
             }
         }
@@ -670,7 +663,6 @@
     params.iDes = &aDest;
     params.iChecksum = aFreeCellChecksum;
     params.iRemaining = -1;
-	params.iReadAddress = 0;
     aDest.Zero();
     //
 	TInt r = DoControl( EMemSpyDriverOpCodeHeapDataGetUser, &params, NULL );
@@ -696,7 +688,6 @@
     params.iDes = &aDest;
     params.iChecksum = 0;
     params.iRemaining = aAmountRemaining;
-	params.iReadAddress = aReadAddress;
     aDest.Zero();
     //
 	TInt r = DoControl( EMemSpyDriverOpCodeHeapDataGetUser, &params, NULL );
@@ -799,7 +790,7 @@
 
 EXPORT_C TInt RMemSpyDriverClient::WalkHeapNextCell( TUint aTid, TMemSpyDriverCellType& aCellType, TAny*& aCellAddress, TInt& aLength, TInt& aNestingLevel, TInt& aAllocNumber, TInt& aCellHeaderSize, TAny*& aCellPayloadAddress )
     {
-    aCellType = EMemSpyDriverBadCellMask;
+    aCellType = EMemSpyDriverGoodAllocatedCell;
     aCellAddress = NULL;
     aLength = 0;
     aNestingLevel = 0;
@@ -812,11 +803,14 @@
     //
 	if  ( r == KErrNone )
 	    {
+        RBuildQueryableHeap* heap = static_cast< RBuildQueryableHeap* >( &User::Allocator() );
+        //
         aCellType = (TMemSpyDriverCellType) params.iCellType;
         aCellAddress = params.iCellAddress;
         aLength = params.iLength;
         aNestingLevel = params.iNestingLevel;
         aAllocNumber = params.iAllocNumber;
+        aCellHeaderSize = heap->CellHeaderSize( aCellType );
         aCellPayloadAddress = ((TUint8*) aCellAddress) + aCellHeaderSize;
         }
     //
@@ -845,7 +839,7 @@
 
 EXPORT_C TInt RMemSpyDriverClient::WalkHeapGetCellInfo( TAny*& aCellAddress, TMemSpyDriverCellType& aCellType, TInt& aLength, TInt& aNestingLevel, TInt& aAllocNumber, TInt& aCellHeaderSize, TAny*& aCellPayloadAddress )
     {
-    aCellType = EMemSpyDriverBadCellMask;
+    aCellType = EMemSpyDriverGoodAllocatedCell;
     aLength = 0;
     aNestingLevel = 0;
     aAllocNumber = 0;
@@ -857,11 +851,14 @@
     //
 	if  ( r == KErrNone )
 	    {
+        RBuildQueryableHeap* heap = static_cast< RBuildQueryableHeap* >( &User::Allocator() );
+        //
         aCellAddress = params.iCellAddress;
         aCellType = (TMemSpyDriverCellType) params.iCellType;
         aLength = params.iLength;
         aNestingLevel = params.iNestingLevel;
         aAllocNumber = params.iAllocNumber;
+        aCellHeaderSize = heap->CellHeaderSize( aCellType );
         aCellPayloadAddress = ((TUint8*) aCellAddress) + aCellHeaderSize;
         }
     //
@@ -1404,15 +1401,10 @@
 
 TBool RMemSpyDriverClient::DebugEUser()
     {
-	LtkUtils::RAllocatorHelper allocHelper;
-	TBool result = EFalse;
-	TInt err = allocHelper.Open(&User::Allocator());
-	if (!err)
-		{
-		result = allocHelper.AllocatorIsUdeb();
-		allocHelper.Close();
-		}
-	return result;
+    RHeap* heap = static_cast< RHeap* >( &User::Allocator() );
+    RBuildQueryableHeap* queryHeap = static_cast< RBuildQueryableHeap* >( heap );
+    const TBool isDebugEUser = queryHeap->IsDebugEUser();
+    return isDebugEUser;
     }
 
 
@@ -1443,7 +1435,7 @@
         for( TInt i=0; i<count; i++ )
             {
             TMemSpyDriverFreeCell entry;
-            entry.iType = (TMemSpyDriverCellType)stream.ReadInt32L();
+            entry.iType = stream.ReadInt32L();
             entry.iAddress = reinterpret_cast< TAny* >( stream.ReadUint32L() );
             entry.iLength = stream.ReadInt32L();
             aFreeCells.AppendL( entry );
@@ -1470,13 +1462,10 @@
     {
 #if defined( _DEBUG ) && !defined( __WINS__ )
     const TMemSpyHeapInfoRHeap& rHeapInfo = aInfo.AsRHeap();
-    //const TMemSpyHeapObjectDataRHeap& rHeapObjectData = rHeapInfo.ObjectData();
+    const TMemSpyHeapObjectDataRHeap& rHeapObjectData = rHeapInfo.ObjectData();
     const TMemSpyHeapStatisticsRHeap& rHeapStats = rHeapInfo.Statistics();
     const TMemSpyHeapMetaDataRHeap& rHeapMetaData = rHeapInfo.MetaData();
 
-	/*
-	 * TODO update to reflect new memory allocator structs etc
-	 * 
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() ---------------------------------------------------");
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - RAllocator                                      -");
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() ---------------------------------------------------");
@@ -1512,7 +1501,6 @@
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - RHeap::iRand:                   %d", rHeapObjectData.iRand);
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - RHeap::iTestData:               0x%08x", rHeapObjectData.iTestData);
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - ");
-	*/
 
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() ---------------------------------------------------");
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - Stats (Free)                                    -");
@@ -1536,6 +1524,12 @@
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - ");
 
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() ---------------------------------------------------");
+    RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - Stats (Common)                                  -");
+    RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() ---------------------------------------------------");
+    RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - total cell count:               %d", rHeapStats.StatsCommon().TotalCellCount());
+    RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - ");
+
+    RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() ---------------------------------------------------");
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - Misc. Info                                      -");
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() ---------------------------------------------------");
     const TPtrC chunkName( rHeapMetaData.ChunkName() );
@@ -1548,8 +1542,8 @@
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - user thread:                    %d", rHeapMetaData.IsUserThread() );
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - thread id:                      %d", aInfo.Tid() );
     RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - process id:                     %d", aInfo.Pid() );
-    //RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - cell header size (free):        %d", rHeapMetaData.HeaderSizeFree());
-    //RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - cell header size (alloc):       %d", rHeapMetaData.HeaderSizeAllocated());
+    RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - cell header size (free):        %d", rHeapMetaData.HeaderSizeFree());
+    RDebug::Printf("RMemSpyDriverClient::PrintHeapInfo() - cell header size (alloc):       %d", rHeapMetaData.HeaderSizeAllocated());
 #else
     (void) aInfo;
 #endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/memspy/Driver/User/Source/RBuildQueryableHeap.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+*
+*/
+
+#include "RBuildQueryableHeap.h"
+
+// System includes
+#include <e32std.h>
+#include <e32debug.h>
+
+
+TBool RBuildQueryableHeap::IsDebugEUser() const
+    {
+    User::__DbgSetAllocFail( FALSE, RAllocator::EFailNext, 1);
+
+    TInt* cell = new TInt();
+#if defined(_DEBUG) && !defined( __WINS__ )
+    RDebug::Printf("RBuildQueryableHeap::IsDebugEUser() - cell: 0x%08x", cell);
+#endif
+
+    const TBool debugEUser = ( cell == NULL );
+#if defined(_DEBUG) && !defined( __WINS__ )
+    RDebug::Printf("RBuildQueryableHeap::IsDebugEUser() - debugEUser: %d", debugEUser);
+#endif
+
+    delete cell;
+    //
+    return debugEUser;
+    }
+
+
+TInt RBuildQueryableHeap::CellHeaderSize( TMemSpyDriverCellType aType ) const
+    {
+	TInt size = 0;
+	//
+	switch( aType )
+	{
+	case EMemSpyDriverGoodAllocatedCell:
+	case EMemSpyDriverBadAllocatedCellSize:
+	case EMemSpyDriverBadAllocatedCellAddress:
+		{
+		size = sizeof( TInt ); // Allocated UREL cells contain just a length
+		if  ( IsDebugEUser() )
+			{
+			size = sizeof( RHeap::SDebugCell );
+			}
+		break;
+		}
+	case EMemSpyDriverGoodFreeCell:
+	case EMemSpyDriverBadFreeCellAddress:
+	case EMemSpyDriverBadFreeCellSize:
+		size = EFreeCellSize;
+		break;
+	default:
+		break;
+	}
+    //
+    return size;
+    }
+
--- a/memspy/Driver/eabi/memspydriverclientu.def	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/eabi/memspydriverclientu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -67,5 +67,4 @@
 	_ZN22RMemSpyMemStreamReader5ReadLER6TDes16 @ 66 NONAME
 	_ZN19RMemSpyDriverClient26GetCondVarSuspendedThreadsEPvPS0_Ri @ 67 NONAME
 	_ZN19RMemSpyDriverClient29GetCondVarSuspendedThreadInfoEPvR39TMemSpyDriverCondVarSuspendedThreadInfo @ 68 NONAME
-	_ZN19RMemSpyDriverClient15GetHeapInfoUserER15TMemSpyHeapInfojR6RArrayI21TMemSpyDriverFreeCellEi @ 69 NONAME
 
--- a/memspy/Driver/group/MemSpyDriver.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/group/MemSpyDriver.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -69,11 +69,6 @@
 USERINCLUDE     ../Kernel/Include
 USERINCLUDE     ../Kernel/Include/SubChannels
 
-// New Allocator support
-MACRO			STANDALONE_ALLOCHELPER
-SOURCEPATH      ../Shared
-SOURCE          heaputils.cpp
-
 OS_LAYER_KERNEL_SYSTEMINCLUDE
 
 START WINS
--- a/memspy/Driver/group/MemSpyDriverClient.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Driver/group/MemSpyDriverClient.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -29,6 +29,7 @@
 
 SOURCEPATH				../User/Source
 SOURCE					MemSpyDriverClient.cpp
+SOURCE					RBuildQueryableHeap.cpp
 SOURCE					MemSpyDriverStreamReader.cpp
 SOURCE					MemSpyDriverStreamReaderImp.cpp
 
@@ -39,10 +40,6 @@
 
 LIBRARY					euser.lib efsrv.lib
 
-// New Allocator support
-MACRO			STANDALONE_ALLOCHELPER
-SOURCEPATH      ../Shared
-SOURCE          heaputils.cpp
 
 
 
--- a/memspy/Engine/BWINS/MemSpyEngineu.def	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/BWINS/MemSpyEngineu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -384,44 +384,24 @@
 	?Type@CMemSpyThreadInfoItemBase@@QBE?AW4TMemSpyThreadInfoItemType@@XZ @ 383 NONAME ; enum TMemSpyThreadInfoItemType CMemSpyThreadInfoItemBase::Type(void) const
 	?TypeAsString@CMemSpyEngineGenericKernelObjectList@@SA?AVTPtrC16@@W4TMemSpyDriverContainerType@@@Z @ 384 NONAME ; class TPtrC16 CMemSpyEngineGenericKernelObjectList::TypeAsString(enum TMemSpyDriverContainerType)
 	?VID@CMemSpyProcess@@QBEKXZ @ 385 NONAME ; unsigned long CMemSpyProcess::VID(void) const
-	__E32Dll @ 386 NONAME ABSENT ; int CMemSpyEngineWindowGroupList::MdcaCount(void) const
-	__E32Dll @ 387 NONAME ABSENT ; void CMemSpyEngineHelperWindowServer::GetWindowGroupListL(class RArray<class TMemSpyEngineWindowGroupInfo> &)
-	__E32Dll @ 388 NONAME ABSENT ; CMemSpyEngineWindowGroupList::~CMemSpyEngineWindowGroupList(void)
-	__E32Dll @ 389 NONAME ABSENT ; int CMemSpyEngineWindowGroupList::Count(void) const
-	__E32Dll @ 390 NONAME ABSENT ; int CMemSpyEngineWindowGroupList::ItemIndex(class TMemSpyEngineWindowGroupInfo const &) const
-	__E32Dll @ 391 NONAME ABSENT ; class CMemSpyEngineWindowGroupList * CMemSpyEngineHelperWindowServer::WindowGroupListL(void)
-	__E32Dll @ 392 NONAME ABSENT ; class CMemSpyEngineHelperWindowServer & CMemSpyEngine::HelperWindowServer(void)
-	__E32Dll @ 393 NONAME ABSENT ; class TPtrC16 CMemSpyEngineWindowGroupList::MdcaPoint(int) const
-	__E32Dll @ 394 NONAME ABSENT ; class TMemSpyEngineWindowGroupInfo const & CMemSpyEngineWindowGroupList::At(int) const
-	__E32Dll @ 395 NONAME ABSENT ; int CMemSpyEngineWindowGroupList::ItemIndex(class TMemSpyEngineWindowGroupBasicInfo const &) const
-	__E32Dll @ 396 NONAME ABSENT ; class TMemSpyEngineWindowGroupBasicInfo const & CMemSpyEngineWindowGroupList::At(int) const
-	__E32Dll @ 397 NONAME ABSENT ; void CMemSpyEngineHelperWindowServer::GetWindowGroupListL(class RArray<class TMemSpyEngineWindowGroupBasicInfo> &)
-	__E32Dll @ 398 NONAME ABSENT ; void CMemSpyEngineHelperWindowServer::GetWindowGroupDetailsL(int, class TMemSpyEngineWindowGroupDetails &)
-	__E32Dll @ 399 NONAME ABSENT ; void CMemSpyEngineHelperWindowServer::SwitchToL(int)
+	?MdcaCount@CMemSpyEngineWindowGroupList@@UBEHXZ @ 386 NONAME ABSENT ; int CMemSpyEngineWindowGroupList::MdcaCount(void) const
+	?GetWindowGroupListL@CMemSpyEngineHelperWindowServer@@QAEXAAV?$RArray@VTMemSpyEngineWindowGroupInfo@@@@@Z @ 387 NONAME ABSENT ; void CMemSpyEngineHelperWindowServer::GetWindowGroupListL(class RArray<class TMemSpyEngineWindowGroupInfo> &)
+	??1CMemSpyEngineWindowGroupList@@UAE@XZ @ 388 NONAME ABSENT ; CMemSpyEngineWindowGroupList::~CMemSpyEngineWindowGroupList(void)
+	?Count@CMemSpyEngineWindowGroupList@@QBEHXZ @ 389 NONAME ABSENT ; int CMemSpyEngineWindowGroupList::Count(void) const
+	?ItemIndex@CMemSpyEngineWindowGroupList@@QBEHABVTMemSpyEngineWindowGroupInfo@@@Z @ 390 NONAME ABSENT ; int CMemSpyEngineWindowGroupList::ItemIndex(class TMemSpyEngineWindowGroupInfo const &) const
+	?WindowGroupListL@CMemSpyEngineHelperWindowServer@@QAEPAVCMemSpyEngineWindowGroupList@@XZ @ 391 NONAME ABSENT ; class CMemSpyEngineWindowGroupList * CMemSpyEngineHelperWindowServer::WindowGroupListL(void)
+	?HelperWindowServer@CMemSpyEngine@@QAEAAVCMemSpyEngineHelperWindowServer@@XZ @ 392 NONAME ABSENT ; class CMemSpyEngineHelperWindowServer & CMemSpyEngine::HelperWindowServer(void)
+	?MdcaPoint@CMemSpyEngineWindowGroupList@@UBE?AVTPtrC16@@H@Z @ 393 NONAME ABSENT ; class TPtrC16 CMemSpyEngineWindowGroupList::MdcaPoint(int) const
+	?At@CMemSpyEngineWindowGroupList@@QBEABVTMemSpyEngineWindowGroupInfo@@H@Z @ 394 NONAME ABSENT ; class TMemSpyEngineWindowGroupInfo const & CMemSpyEngineWindowGroupList::At(int) const
+	?ItemIndex@CMemSpyEngineWindowGroupList@@QBEHABVTMemSpyEngineWindowGroupBasicInfo@@@Z @ 395 NONAME ABSENT ; int CMemSpyEngineWindowGroupList::ItemIndex(class TMemSpyEngineWindowGroupBasicInfo const &) const
+	?At@CMemSpyEngineWindowGroupList@@QBEABVTMemSpyEngineWindowGroupBasicInfo@@H@Z @ 396 NONAME ABSENT ; class TMemSpyEngineWindowGroupBasicInfo const & CMemSpyEngineWindowGroupList::At(int) const
+	?GetWindowGroupListL@CMemSpyEngineHelperWindowServer@@QAEXAAV?$RArray@VTMemSpyEngineWindowGroupBasicInfo@@@@@Z @ 397 NONAME ABSENT ; void CMemSpyEngineHelperWindowServer::GetWindowGroupListL(class RArray<class TMemSpyEngineWindowGroupBasicInfo> &)
+	?GetWindowGroupDetailsL@CMemSpyEngineHelperWindowServer@@QAEXHAAVTMemSpyEngineWindowGroupDetails@@@Z @ 398 NONAME ABSENT ; void CMemSpyEngineHelperWindowServer::GetWindowGroupDetailsL(int, class TMemSpyEngineWindowGroupDetails &)
+	?SwitchToL@CMemSpyEngineHelperWindowServer@@QAEXH@Z @ 399 NONAME ABSENT ; void CMemSpyEngineHelperWindowServer::SwitchToL(int)
 	?Capabilities@CMemSpyProcess@@QBE?AUSCapabilitySet@@XZ @ 400 NONAME ; struct SCapabilitySet CMemSpyProcess::Capabilities(void) const
 	?UIDs@CMemSpyProcess@@QBE?AVTUidType@@XZ @ 401 NONAME ; class TUidType CMemSpyProcess::UIDs(void) const
 	?HelperCondVar@CMemSpyEngine@@QAEAAVCMemSpyEngineHelperCondVar@@XZ @ 402 NONAME ; class CMemSpyEngineHelperCondVar & CMemSpyEngine::HelperCondVar(void)
 	?GetCondVarSuspendedThreadsL@CMemSpyEngineHelperCondVar@@QAEXABVTMemSpyDriverHandleInfoGeneric@@AAV?$RArray@VTMemSpyDriverCondVarSuspendedThreadInfo@@@@@Z @ 403 NONAME ; void CMemSpyEngineHelperCondVar::GetCondVarSuspendedThreadsL(class TMemSpyDriverHandleInfoGeneric const &, class RArray<class TMemSpyDriverCondVarSuspendedThreadInfo> &)
 	?HelperWindowServer@CMemSpyEngine@@QAEAAVMMemSpyEngineHelperWindowServer@@XZ @ 404 NONAME ; class MMemSpyEngineHelperWindowServer & CMemSpyEngine::HelperWindowServer(void)
 	?IsHelperWindowServerSupported@CMemSpyEngine@@QAEHXZ @ 405 NONAME ; int CMemSpyEngine::IsHelperWindowServerSupported(void)
-	__E32Dll @ 406 NONAME ABSENT ; int CMemSpyEngineGenericKernelObjectList::Size(void) const
-	__E32Dll @ 407 NONAME ABSENT ; int CMemSpyEngineGenericKernelObjectList::Size(void)
-	?Size@CMemSpyEngineGenericKernelObjectList@@QBEHXZ @ 408 NONAME ; int CMemSpyEngineGenericKernelObjectList::Size(void) const
-	?NewHeapRawInfo@CMemSpyEngineHelperHeap@@QAEAAVTMemSpyHeapData@@ABVTMemSpyHeapInfo@@@Z @ 409 NONAME ABSENT ; class TMemSpyHeapData & CMemSpyEngineHelperHeap::NewHeapRawInfo(class TMemSpyHeapInfo const &)
-	?NewHeapRawInfo@CMemSpyEngineHelperHeap@@QAE?AVTMemSpyHeapData@@ABVTMemSpyHeapInfo@@@Z @ 410 NONAME ; class TMemSpyHeapData CMemSpyEngineHelperHeap::NewHeapRawInfo(class TMemSpyHeapInfo const &)
-	?ItemsCount@CMemSpyEngineGenericKernelObjectList@@QBEHXZ @ 411 NONAME ; int CMemSpyEngineGenericKernelObjectList::ItemsCount(void) const
-	?Priority@CMemSpyThread@@QBE?AW4TThreadPriority@@XZ @ 412 NONAME ; enum TThreadPriority CMemSpyThread::Priority(void) const
-	?NewL@CMemSpyEngine@@SAPAV1@AAVRFs@@H@Z @ 413 NONAME ; class CMemSpyEngine * CMemSpyEngine::NewL(class RFs &, int)
-	?Value@CMemSpyThreadInfoItemBase@@QBE?AVTPtrC16@@H@Z @ 414 NONAME ; class TPtrC16 CMemSpyThreadInfoItemBase::Value(int) const
-	?ExitType@CMemSpyProcess@@QBE?AW4TExitType@@XZ @ 415 NONAME ; enum TExitType CMemSpyProcess::ExitType(void) const
-	?ExitCategory@CMemSpyProcess@@QBE?AV?$TBuf@$0BA@@@XZ @ 416 NONAME ; class TBuf<16> CMemSpyProcess::ExitCategory(void) const
-	?Priority@CMemSpyProcess@@QBE?AW4TProcessPriority@@XZ @ 417 NONAME ; enum TProcessPriority CMemSpyProcess::Priority(void) const
-	?Caption@CMemSpyThreadInfoItemBase@@QBE?AVTPtrC16@@H@Z @ 418 NONAME ; class TPtrC16 CMemSpyThreadInfoItemBase::Caption(int) const
-	?ExitReason@CMemSpyProcess@@QBEHXZ @ 419 NONAME ; int CMemSpyProcess::ExitReason(void) const
-	?NewL@CMemSpyEngineSinkMetaData@@SAPAV1@ABVTDesC16@@000HHABVTTime@@@Z @ 420 NONAME ; class CMemSpyEngineSinkMetaData * CMemSpyEngineSinkMetaData::NewL(class TDesC16 const &, class TDesC16 const &, class TDesC16 const &, class TDesC16 const &, int, int, class TTime const &)
-	?InstallDebugSinkL@CMemSpyEngine@@QAEXXZ @ 421 NONAME ; void CMemSpyEngine::InstallDebugSinkL(void)
-	?NewL@CMemSpyEngineSinkMetaData@@SAPAV1@ABVTDesC16@@000HH@Z @ 422 NONAME ; class CMemSpyEngineSinkMetaData * CMemSpyEngineSinkMetaData::NewL(class TDesC16 const &, class TDesC16 const &, class TDesC16 const &, class TDesC16 const &, int, int)
-	?InstallFileSinkL@CMemSpyEngine@@QAEXABVTDesC16@@@Z @ 423 NONAME ; void CMemSpyEngine::InstallFileSinkL(class TDesC16 const &)
-	?CheckForChangesNowL@CMemSpyEngineHelperSysMemTracker@@QAEXXZ @ 424 NONAME ; void CMemSpyEngineHelperSysMemTracker::CheckForChangesNowL(void)
-	?GetHeapInfoUserL@CMemSpyEngineHelperHeap@@QAEXABVTProcessId@@ABVTThreadId@@AAVTMemSpyHeapInfo@@PAV?$RArray@VTMemSpyDriverFreeCell@@@@H@Z @ 425 NONAME ; void CMemSpyEngineHelperHeap::GetHeapInfoUserL(class TProcessId const &, class TThreadId const &, class TMemSpyHeapInfo &, class RArray<class TMemSpyDriverFreeCell> *, int)
 
--- a/memspy/Engine/Include/ClientServer/MemSpyEngineServer.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Include/ClientServer/MemSpyEngineServer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -23,36 +23,17 @@
 
 // User includes
 #include <memspyengineclientinterface.h>
-#include <memspy/engine/memspydevicewideoperations.h>
 
 // Classes referenced
 class CMemSpyEngine;
-class CMemSpyDwOperationTracker;
 
-NONSHARABLE_CLASS( CShutdown ) : public CTimer
-    {
-    enum {KMyShutdownDelay=10 * 1000000};       // 10s
-public:
-    inline CShutdown();
-    inline void ConstructL();
-    inline void Start();
-private:
-    void RunL();
-    };
+
 
 NONSHARABLE_CLASS( CMemSpyEngineServer ) : public CServer2
     {
 public:
     static CMemSpyEngineServer* NewL( CMemSpyEngine& aEngine );
     ~CMemSpyEngineServer();
-    
-    CMemSpyDwOperationTracker* CurrentOperationTracker() const { return iCurrentOperationTracker; }
-    void SetCurrentOperationTracker(CMemSpyDwOperationTracker* aTracker) { iCurrentOperationTracker = aTracker; }
-    
-    CMemSpyEngine& Engine() { return iEngine; } 
-    
-    void AddSession(TBool aCliRequest);
-    void DropSession(TBool aCliRequest);
 
 private:
     CMemSpyEngineServer( CMemSpyEngine& aEngine );
@@ -63,12 +44,6 @@
 
 private:
     CMemSpyEngine& iEngine;
-    CMemSpyDwOperationTracker* iCurrentOperationTracker;
-    
-    TInt iSessionCount;
-    TBool iCliConnected;
-    
-    CShutdown iShutdown;
     };
 
 
@@ -78,9 +53,7 @@
 public:
 	static CMemSpyEngineSession* NewL( CMemSpyEngine& aEngine, const RMessage2& aMessage );
 	~CMemSpyEngineSession();
-	
-	void CreateL();
-	
+
 private:
 	CMemSpyEngineSession( CMemSpyEngine& aEngine );
 	void ConstructL( const RMessage2& aMessage );
@@ -90,54 +63,17 @@
 
 private: // Internal methods
     void DoServiceL( const RMessage2& aMessage );
-    void DoAsyncServiceL( const RMessage2& aMessage );
-    void DoUiServiceL( const RMessage2& aMessage );
-    void DoCmdServiceL( const RMessage2& aMessage );
     static TInt ValidateFunction( TInt aFunction, TBool aIncludesThreadId, TBool aIncludesThreadName );
     void HandleThreadSpecificOpL( TInt aFunction, const TThreadId& aThreadId );
     void HandleThreadSpecificOpL( TInt aFunction, const TDesC& aThreadName );
     void HandleThreadAgnosticOpL( TInt aFunction, const RMessage2& aMessage );
-    void StartDeviceWideOperationL(CMemSpyDeviceWideOperations::TOperation aOperation, const RMessage2& aMessage);
-    
-    inline CMemSpyEngineServer& Server() const { return *static_cast<CMemSpyEngineServer*>(const_cast<CServer2*>(CSession2::Server())); }
 
 private:
     CMemSpyEngine& iEngine;
     HBufC* iClientThreadName;
     TUint32 iClientThreadId;
-    TBool iIsCliRequest;
     };
 
-/**
- * CMemSpyDwOperationTracker
- * Tracks device wide operation progress and calls iOperationMessage.Complete upon completion. 
- */
-NONSHARABLE_CLASS( CMemSpyDwOperationTracker ) : public MMemSpyDeviceWideOperationsObserver
-	{
-public:
-	static CMemSpyDwOperationTracker* NewL(CMemSpyDeviceWideOperations::TOperation aOperation, 
-			const RMessage2& aOperationMessage,
-			CMemSpyEngineServer& aServer);
-	~CMemSpyDwOperationTracker();
-	
-	void AddNotificationL(const RMessage2& aMessage);
-	
-	void Cancel();
-
-public: // From MMemSpyDeviceWideOperationsObserver
-	void HandleDeviceWideOperationEvent(TEvent aEvent, TInt aParam1, const TDesC& aParam2);
-	
-private:
-	CMemSpyDwOperationTracker(const RMessage2& aOperationMessage, CMemSpyEngineServer& aServer);
-	void ConstructL(CMemSpyDeviceWideOperations::TOperation aOperation);
-	
-private:
-	RMessage2 iOperationMessage;
-	CMemSpyEngineServer& iServer;
-	CArrayFixFlat<RMessage2>* iPendingNotifications;
-	CMemSpyDeviceWideOperations* iOperation;
-	TInt iProgress;
-	};
 
 
 #endif
--- a/memspy/Engine/Include/Sink/MemSpyEngineOutputSinkFile.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Include/Sink/MemSpyEngineOutputSinkFile.h	Wed Oct 13 16:17:58 2010 +0300
@@ -32,12 +32,12 @@
 NONSHARABLE_CLASS( CMemSpyEngineOutputSinkFile ) : public CMemSpyEngineOutputSink
     {
 public:
-    static CMemSpyEngineOutputSinkFile* NewL( CMemSpyEngine& aEngine, const TDesC& aRootFolder );
+    static CMemSpyEngineOutputSinkFile* NewL( CMemSpyEngine& aEngine );
     ~CMemSpyEngineOutputSinkFile();
 
 public:
     CMemSpyEngineOutputSinkFile( CMemSpyEngine& aEngine );
-    void ConstructL( const TDesC& aRootFolder );
+    void ConstructL();
     
 private: // From CMemSpyEngineOutputSink
     void ProcessSuspendedL( TProcessId aId );
@@ -64,8 +64,6 @@
 
     TUint iFileServerProcessId;
     TBool iFileServerSuspended;
-    
-    HBufC* iRoot;
 
 private:
     friend class CMemSpyEngineFileHolder;
@@ -119,4 +117,4 @@
 
 
 
-#endif
+#endif
\ No newline at end of file
--- a/memspy/Engine/Source/ClientServer/MemSpyEngineServer.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/ClientServer/MemSpyEngineServer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -19,9 +19,6 @@
 
 // System includes
 #include <e32svr.h>
-#include <w32std.h>
-#include <APGTASK.H>
-#include <APGWGNAM.H>  
 
 // User includes
 #include <memspy/engine/memspyengine.h>
@@ -41,45 +38,7 @@
 #include <memspy/engine/memspyenginehelpersysmemtracker.h>
 #include <memspy/engine/memspyenginehelpersysmemtrackerconfig.h>
 #include <memspy/engine/memspyenginehelperkernelcontainers.h>
-#include <memspy/engine/memspyengineobjectthreadinfocontainer.h>
-#include <memspy/engine/memspyengineobjectthreadinfoobjects.h>
-#include <memspy/engine/memspyenginehelpersysmemtrackercycle.h>
-#include <memspy/engine/memspyenginehelperserver.h>
-#include <memspy/engine/memspyenginehelperecom.h>
 
-#include <memspy/engine/memspyprocessdata.h>
-#include <memspy/engine/memspythreaddata.h>
-#include <memspy/engine/memspykernelobjectdata.h>
-#include <memspy/engine/memspythreadinfoitemdata.h>
-#include <memspy/engine/memspymemorytrackingcycledata.h>
-#include <memspy/engine/memspyengineoutputsink.h>
-#include <memspy/engine/memspyenginehelperactiveobject.h>
-#include <memspy/engine/memspyserverdata.h>
-#include <memspysession.h>
-#include <memspy/engine/memspyecomdata.h>
-
-inline CShutdown::CShutdown() :CTimer(-1)
-    {
-    CActiveScheduler::Add(this);
-    }
-
-inline void CShutdown::ConstructL()
-    {
-    CTimer::ConstructL();
-    }
-
-inline void CShutdown::Start()
-    {
-    After(KMyShutdownDelay);
-    }
-
-void CShutdown::RunL()
-    //
-    // Initiate server exit when the timer expires
-    //
-    {
-    CActiveScheduler::Stop();
-    }
 
 CMemSpyEngineServer::CMemSpyEngineServer( CMemSpyEngine& aEngine )
 :   CServer2( EPriorityNormal ), iEngine( aEngine )
@@ -95,10 +54,6 @@
 void CMemSpyEngineServer::ConstructL()
     {
     StartL( KMemSpyServerName );
-        
-    iShutdown.ConstructL();
-    // ensure that the server still exits even if the 1st client fails to connect
-    iShutdown.Start();
     }
 
 
@@ -124,33 +79,6 @@
 	return session;
     }
 
-void CMemSpyEngineServer::AddSession(TBool aCliRequest)
-    {
-    if (aCliRequest)
-        {
-        iCliConnected = ETrue;
-        }
-    else
-        {
-        ++iSessionCount;
-        }
-    iShutdown.Cancel();
-    }
-
-void CMemSpyEngineServer::DropSession(TBool aCliRequest)
-    {
-    if (!aCliRequest)
-        {
-        --iSessionCount;
-        }
-    
-    if (iSessionCount == 0 && !iCliConnected)
-        {
-        iShutdown.Start();
-        }
-    }
-
-
 
 
 
@@ -192,8 +120,6 @@
 #endif
 
     delete iClientThreadName;
-        
-    Server().DropSession(iIsCliRequest);
     }
 
 
@@ -212,17 +138,10 @@
     iClientThreadId = thread.Id();
 
     CleanupStack::PopAndDestroy( &thread );
-    
-    const TUid KCliUid3 = { 0x2002129D };
-    iIsCliRequest = aMessage.SecureId() == TSecureId(KCliUid3);
-    
+
     TRACE( RDebug::Print( _L("[MemSpy] CMemSpyEngineSession::ConstructL() - NEW SESSION - this: 0x%08x, id: %4d, client: %S"), this, iClientThreadId, iClientThreadName ) );
     }
 
-void CMemSpyEngineSession::CreateL()
-    {   
-    Server().AddSession(iIsCliRequest);
-    }
 
 CMemSpyEngineSession* CMemSpyEngineSession::NewL( CMemSpyEngine& aEngine, const RMessage2& aMessage )
     {
@@ -243,998 +162,13 @@
         {
         RDebug::Print( _L("[MemSpy] CMemSpyEngineSession::ServiceL() - SERVICE ERROR - this: 0x%08x, fn: %d, err: %d, client: %S"), this, aMessage.Function(), error, iClientThreadName );
         }
-    
-    if ((aMessage.Function() & KMemSpyOpFlagsAsyncOperation) == 0 || error != KErrNone)
-    	{
-		aMessage.Complete( error );
-    	}
+    aMessage.Complete( error );
 
     TRACE( RDebug::Print( _L("[MemSpy] CMemSpyEngineSession::ServiceL() - END - this: 0x%08x, fn: 0x%08x, id: %4d, client: %S"), this, aMessage.Function(), iClientThreadId, iClientThreadName ) );
 	}
 
-// ---------------------------------------------------------
-// DoServiceL( const RMessage2& aMessage )
-// ---------------------------------------------------------
-//
+
 void CMemSpyEngineSession::DoServiceL( const RMessage2& aMessage )
-	{
-	TInt function = aMessage.Function() & KMemSpyOpFlagsTypeMask;
-	if (function >= EMemSpyClientServerOpMarkerUiFirst && 
-		function < EMemSpyClientServerOpMarkerUiLast)
-		
-		DoUiServiceL(aMessage);
-	else
-		DoCmdServiceL(aMessage);
-	}
-// ---------------------------------------------------------
-// DoUiServiceL( const RMessage2& aMessage )
-// ---------------------------------------------------------
-//
-void CMemSpyEngineSession::DoUiServiceL( const RMessage2& aMessage )
-    {
-	switch (aMessage.Function() & KMemSpyOpFlagsTypeMask)
-		{
-	    case EMemSpyClientServerOpGetOutputSink:
-	        {
-	        TMemSpySinkType sink = iEngine.SinkType();
-	        TPckgBuf<TMemSpySinkType> type( sink );
-	        
-	        aMessage.WriteL( 0, type );
-	        break;
-	        }
-		case EMemSpyClientServerOpGetProcessCount:
-			{
-			aMessage.WriteL(0, TPckgBuf<TInt>(iEngine.Container().Count()));
-			break;
-			}
-		case EMemSpyClientServerOpGetProcesses:
-			{
-			CMemSpyEngineObjectContainer& list = iEngine.Container();
-			
-			TPckgBuf<TInt> a0;
-			aMessage.ReadL(0, a0);
-			TInt realCount = Min(a0(), list.Count());
-			
-			for(TInt i=0, offset = 0; i<realCount; i++, offset += sizeof(TMemSpyProcessData))
-				{
-				CMemSpyProcess& process = iEngine.Container().At(i);
-				TMemSpyProcessData data;
-				data.iIsDead = process.IsDead();
-				data.iId = process.Id();
-				data.iName.Copy(process.Name().Left(KMaxFullName));
-				data.iThreadCount = process.Count();
-				data.iPriority = process.Priority();
-				data.iExitType = process.ExitType();
-				data.iExitReason = process.ExitReason();
-				data.iExitCategory = process.ExitCategory();
-				data.iSID = process.SID();
-				
-				TPckgBuf<TMemSpyProcessData> buffer(data);
-				aMessage.WriteL(1, buffer, offset);
-				}
-			
-			a0 = list.Count();
-			aMessage.WriteL(0, a0);
-
-			break;
-			}
-		case EMemSpyClienServerOpGetProcessIdByName:
-			{
-			TFullName processName;
-			aMessage.ReadL(0, processName);
-			
-			TBool found(EFalse);
-			
-			for (TInt i=0; i<iEngine.Container().Count(); i++)
-				{
-				CMemSpyProcess& process = iEngine.Container().At(i);
-				if (process.Name().FindF(processName) >= 0)
-					{
-					found = ETrue;
-					TPckgBuf<TProcessId> procId(process.Id());
-					aMessage.WriteL(1, procId);
-					}
-				}
-			
-			if (!found)
-				{
-				User::Leave(KErrNotFound);
-				}
-			
-			break;
-			}
-		case EMemSpyClientServerOpProcessSystemPermanentOrCritical:
-			{
-			TBool ret = EFalse;
-			TPckgBuf<TProcessId> id;
-			aMessage.ReadL( 0, id );
-			
-			CMemSpyEngineObjectContainer& container = iEngine.Container();
-			CMemSpyProcess& process = container.ProcessByIdL( id() );
-			
-			if  ( process.IsSystemPermanent() || process.IsSystemCritical() )
-				{
-				ret = ETrue;
-				}
-			TPckgBuf<TBool> retBuf( ret );
-			aMessage.WriteL( 1, retBuf );
-			
-			break;
-			}
-		case EMemSpyClientServerOpEndProcess:
-			{
-			TPckgBuf<TProcessId> id;
-			aMessage.ReadL( 0, id );
-			TPckgBuf<TMemSpyEndType> type;
-			aMessage.ReadL( 1, type );
-					
-			CMemSpyEngineObjectContainer& container = iEngine.Container();			
-			CMemSpyProcess& process = container.ProcessByIdL( id() );
-									
-			switch ( type() )
-				{
-				case ETerminate:
-					{
-					process.TerminateL();
-					break;
-					}
-				case EPanic:
-					{
-					process.PanicL();
-					break;
-					}
-				case EKill:
-					{
-					process.KillL();
-					break;
-					}
-				}																
-			break;
-			}
-		case EMemSpyClientServerOpSwitchToProcess:
-			{/*
-			TInt wgCount;
-			RWsSession wsSession;
-			User::LeaveIfError( wsSession.Connect() );
-			CleanupClosePushL( wsSession );
-			User::LeaveIfError( wgCount = wsSession.NumWindowGroups() );
-			RArray<RWsSession::TWindowGroupChainInfo> wgArray;
-			CleanupClosePushL( wgArray );
-			User::LeaveIfError( wsSession.WindowGroupList( &wgArray ) );
-			TApaTask task( wsSession );
-			TBool brought( EFalse );
-			TInt wgId( KErrNotFound );
-			TThreadId threadId;
-			
-			TPckgBuf<TProcessId> id;
-			aMessage.ReadL( 0, id );
-			CMemSpyEngineObjectContainer& container = iEngine.Container();
-			CMemSpyProcess& process = container.ProcessByIdL( id() );
-			
-			// loop trough threads in a process
-			for ( TInt i = 0; i < process.MdcaCount(); i++ )
-				{
-				TInt wgCountLocal = wgCount;
-							
-				// loop trough all window groups and see if a thread id matches
-				while( !brought && wgCountLocal-- )
-					{
-					wgId = wgArray[wgCountLocal].iId;
-					User::LeaveIfError( wsSession.GetWindowGroupClientThreadId( wgId, threadId ) );
-					if ( threadId == process.At( i ).Id() )
-						{
-						CApaWindowGroupName* wgName = CApaWindowGroupName::NewLC( wsSession, wgId );
-						task.SetWgId( wgId );
-						if ( !wgName->Hidden() && task.Exists() )
-							{
-							task.BringToForeground();
-							brought = ETrue;                        
-							}
-						CleanupStack::PopAndDestroy( wgName );
-						}
-					}
-				}
-			
-			TPckgBuf<TBool> ret( brought );
-			aMessage.WriteL( 1, ret );
-			
-			break;*/
-			}
-		case EMemSpyClientServerOpGetThreadCount:
-			{
-			TPckgBuf<TProcessId> pid;
-			aMessage.ReadL(1, pid);
-			CMemSpyProcess& process = iEngine.Container().ProcessByIdL(pid());
-			aMessage.WriteL(0, TPckgBuf<TInt>(process.Count()));
-			break;
-			}
-		case EMemSpyClientServerOpGetThreads:
-			{
-			TPckgBuf<TProcessId> pid;
-			aMessage.ReadL(2, pid);
-			
-			CMemSpyProcess& list = iEngine.Container().ProcessByIdL(pid());
-			
-			TPckgBuf<TInt> a0;
-			aMessage.ReadL(0, a0);
-			TInt realCount = Min(a0(), list.Count());
-						
-			for(TInt i=0, offset = 0; i<realCount; i++, offset += sizeof(TMemSpyThreadData))
-				{
-				CMemSpyThread& thread = list.At(i);
-				
-				TMemSpyThreadData data;
-				data.iId = thread.Id();
-				data.iName.Copy(thread.Name().Left(KMaxFullName));
-				data.iThreadPriority = thread.Priority();
-				
-				TPckgBuf<TMemSpyThreadData> buffer(data);
-				aMessage.WriteL(1, buffer, offset);
-				}
-			
-			a0 = list.Count();
-			aMessage.WriteL(0, a0);
-
-			break;
-			}
-		case EMemSpyClientServerOpSetThreadPriority:
-			{
-			TPckgBuf<TThreadId> tid;
-			TPckgBuf<TInt> priority;
-			aMessage.ReadL(0, tid);
-			aMessage.ReadL(1, priority);
-			
-			CMemSpyProcess* process = NULL;
-			CMemSpyThread* thread = NULL; 
-			User::LeaveIfError(iEngine.Container().ProcessAndThreadByThreadId(tid(), process, thread));
-			
-			if (thread)
-				{				
-				thread->SetPriorityL(static_cast<TThreadPriority>(priority()));
-				}					
-			break;
-			}
-		case EMemSpyClientServerOpThreadSystemPermanentOrCritical:
-			{
-			TPckgBuf<TThreadId> id;
-			aMessage.ReadL( 0, id );
-			
-			CMemSpyEngineObjectContainer& container = iEngine.Container();            
-			CMemSpyProcess* process = NULL;
-			CMemSpyThread* thread = NULL; 
-			User::LeaveIfError( container.ProcessAndThreadByThreadId( id(), process, thread ) );
-			
-			TBool ret = thread && ( thread->IsSystemPermanent() || thread->IsSystemCritical() );
-			
-			TPckgBuf<TBool> retBuf( ret );
-			aMessage.WriteL( 1, retBuf );
-							
-			break;
-			}
-		case EMemSpyClientServerOpEndThread:
-			{
-			TPckgBuf<TThreadId> id;
-			aMessage.ReadL( 0, id );
-			TPckgBuf<TMemSpyEndType> type;
-			aMessage.ReadL( 1, type );
-			
-			CMemSpyEngineObjectContainer& container = iEngine.Container();
-			CMemSpyProcess* process = NULL;
-			CMemSpyThread* thread = NULL; 
-			User::LeaveIfError( container.ProcessAndThreadByThreadId( id(), process, thread ) );
-			
-			if( thread )
-				{
-				switch ( type() )
-					{
-					case ETerminate:
-						{
-						thread->TerminateL();
-						break;
-						}
-					case EPanic:
-						{
-						thread->PanicL();
-						break;
-						}
-					case EKill:
-						{
-						thread->KillL();
-						break;
-						}
-					}				
-				}			
-			break;
-			}
-		case EMemSpyClientServerOpSwitchToThread:
-			{
-			TInt wgCount;
-			RWsSession wsSession;
-			User::LeaveIfError( wsSession.Connect() );
-			CleanupClosePushL( wsSession );
-			User::LeaveIfError( wgCount = wsSession.NumWindowGroups() );
-			RArray<RWsSession::TWindowGroupChainInfo> wgArray;
-			CleanupClosePushL( wgArray );
-			User::LeaveIfError( wsSession.WindowGroupList( &wgArray ) );
-			TApaTask task( wsSession );
-			TBool brought( EFalse );
-			TInt wgId( KErrNotFound );
-			TThreadId threadId;
-					
-			TPckgBuf<TThreadId> id;
-			aMessage.ReadL( 0, id );
-					
-			// loop trough all window groups and see if a thread id matches
-			while( !brought && wgCount-- )
-				{
-				wgId = wgArray[wgCount].iId;
-				User::LeaveIfError( wsSession.GetWindowGroupClientThreadId( wgId, threadId ) );
-				if ( threadId == id() )
-					{
-					CApaWindowGroupName* wgName = CApaWindowGroupName::NewLC( wsSession, wgId );
-					task.SetWgId( wgId );
-					if ( !wgName->Hidden() && task.Exists() )
-						{
-						task.BringToForeground();
-						brought = ETrue;                        
-						}
-					CleanupStack::PopAndDestroy( wgName );
-					}
-				}			
-			TPckgBuf<TBool> ret( brought );
-			aMessage.WriteL( 1, ret );															
-					
-			break;
-			}		
-		case EMemSpyClientServerOpGetInfoItemType:
-			{
-			
-			TPckgBuf<TInt> index;
-			aMessage.ReadL( 0, index );			
-			TPckgBuf<TThreadId> id;
-			aMessage.ReadL( 1, id);
-								
-			CMemSpyEngineObjectContainer& container = iEngine.Container();            
-			CMemSpyProcess* process = NULL; //not needed
-			CMemSpyThread* thread = NULL; 
-			User::LeaveIfError( container.ProcessAndThreadByThreadId( id(), process, thread ) );
-		            
-			CMemSpyThreadInfoContainer& threadInfoContainer = thread->InfoContainerForceSyncronousConstructionL();                        
-			TMemSpyThreadInfoItemType retType = threadInfoContainer.Item( index() ).Type();
-			
-			TPckgBuf<TMemSpyThreadInfoItemType> ret( retType );
-			aMessage.WriteL( 2, ret );			
-			
-			break;
-			}
-		case EMemSpyClientServerOpGetThreadInfoItemsCount:
-			{
-			TPckgBuf<TThreadId> id;
-			aMessage.ReadL( 0, id );
-			TPckgBuf<TMemSpyThreadInfoItemType> type;
-			aMessage.ReadL( 1, type );					 
-			
-			CMemSpyEngineObjectContainer& container = iEngine.Container();            
-			CMemSpyProcess* process = NULL;
-			CMemSpyThread* thread = NULL; 
-			
-			container.ProcessAndThreadByThreadId( id(), process, thread );
-			
-			CMemSpyThreadInfoContainer& threadInfoContainer = thread->InfoContainerForceSyncronousConstructionL();                 
-								
-			CMemSpyThreadInfoItemBase& threadInfoItemBase = threadInfoContainer.Item( type() );
-				    
-			TInt count = threadInfoItemBase.MdcaCount();		    
-			TPckgBuf<TInt> tempret( count );
-			aMessage.WriteL( 2, tempret );
-		
-			break;
-			}		
-		case EMemSpyClientServerOpGetThreadInfoItems:
-			{
-			TPckgBuf<TInt> count;
-			aMessage.ReadL( 0, count );						
-			TPckgBuf<TThreadId> id;
-			aMessage.ReadL( 1, id );
-			TPckgBuf<TMemSpyThreadInfoItemType> type;
-			aMessage.ReadL( 2, type );			
-			
-			CMemSpyEngineObjectContainer& container = iEngine.Container();            
-			CMemSpyProcess* process = NULL;
-			CMemSpyThread* thread = NULL; 
-			User::LeaveIfError( container.ProcessAndThreadByThreadId( id() , process, thread ) );
-							  
-			CMemSpyThreadInfoContainer& threadInfoContainer = thread->InfoContainerForceSyncronousConstructionL();      
-
-			CMemSpyThreadInfoItemBase& threadInfoItemBase = threadInfoContainer.Item( type() ); //get ThreadInfoItemBaseByType
-			
-			TInt itemCount = Min(count(), threadInfoItemBase.MdcaCount());
-								
-			for( TInt i=0, offset = 0; i<itemCount; i++, offset += sizeof( TMemSpyThreadInfoItemData ) )
-				{
-				TMemSpyThreadInfoItemData data;
-				
-				TPtrC caption(threadInfoItemBase.MdcaPoint(i).Mid(1));
-				TInt tabPos = caption.Locate('\t');
-				if (tabPos != KErrNotFound)
-					caption.Set(caption.Left(tabPos));
-				
-				TPtrC value(threadInfoItemBase.MdcaPoint(i));
-				tabPos = value.LocateReverse('\t');
-				if (tabPos != KErrNotFound)
-					value.Set(value.Mid(tabPos + 1));
-												
-				data.iCaption.Copy( caption.Left(64) );
-				data.iValue.Copy( value.Left(32) );
-							
-				TPckgBuf<TMemSpyThreadInfoItemData> buffer(data);
-				aMessage.WriteL(3, buffer, offset);				
-				}			
-			aMessage.WriteL(0, count);
-					
-			break;
-			}
-			
-		case EMemSpyClientServerOpGetProcessIdByThreadId:
-			{
-			TPckgBuf<TThreadId> tid;
-			aMessage.ReadL( 1, tid );					
-			
-			CMemSpyProcess* process = NULL;
-			CMemSpyThread* thread = NULL;
-			//
-			const TInt error = iEngine.Container().ProcessAndThreadByThreadId( tid(), process, thread );
-			
-			TProcessId pid = process->Id();
-			
-			TPckgBuf<TProcessId> ret(pid);
-			aMessage.WriteL( 0, ret );
-									
-			break;
-			}
-			
-		// --- KernelObjects related functions ---
-		case EMemSpyClientServerOpGetKernelObjectCount:
-			{
-			TInt iCount = EMemSpyDriverContainerTypeLast - EMemSpyDriverContainerTypeFirst + 1;
-			TPckgBuf<TInt> ret( iCount );
-			aMessage.WriteL(0, ret);			
-			break;
-			}
-		case EMemSpyClientServerOpGetKernelObjects:
-			{
-			TPckgBuf<TInt> count;
-			aMessage.ReadL(0, count);
-			
-			CMemSpyEngineGenericKernelObjectContainer* model = iEngine.HelperKernelContainers().ObjectsAllL(); //contains all the objects
-			CleanupStack::PushL( model );
-			
-			for( TInt i=0, offset = 0; i<count(); i++, offset += sizeof( TMemSpyKernelObjectData ) )
-				{
-				TMemSpyKernelObjectData data;
-				
-				TPtrC name(model->At(i).Name().Mid(1));
-				TInt tabPos = name.Locate('\t');
-				if (tabPos != KErrNotFound)
-					name.Set(name.Left(tabPos));
-												
-				data.iName.Copy(name);
-				data.iType = model->At(i).Type();
-				data.iCount = model->At(i).Count();											
-				data.iSize = model->At(i).Count() * model->At(i).Count();
-
-				TPckgBuf<TMemSpyKernelObjectData> buffer(data);
-				aMessage.WriteL(1, buffer, offset);
-				}			
-			aMessage.WriteL(0, count);
-			CleanupStack::PopAndDestroy( model );
-			break;
-			}
-		case EMemSpyClientServerOpGetKernelObjectItemCount:
-			{
-			TPckgBuf<TMemSpyDriverContainerType> tempType;
-			aMessage.ReadL(1, tempType); //get type of kernel object
-			TMemSpyDriverContainerType type = tempType();
-			
-			CMemSpyEngineHelperKernelContainers& kernelContainerManager = iEngine.HelperKernelContainers();
-			CMemSpyEngineGenericKernelObjectList* iObjectList = kernelContainerManager.ObjectsForSpecificContainerL( type );			
-			
-			TInt count = iObjectList->Count();
-			TPckgBuf<TInt> ret( count );
-			aMessage.WriteL( 0, ret );
-						
-			break;
-			}
-		case EMemSpyClientServerOpGetKernelObjectItems:
-			{
-			TPckgBuf<TInt> count;
-			TPckgBuf<TMemSpyDriverContainerType> tempType;
-			aMessage.ReadL( 0, count ); //get count of items
-			aMessage.ReadL(1, tempType); //get type of kernel object
-			TInt c = count();
-						
-			CMemSpyEngineHelperKernelContainers& kernelContainerManager = iEngine.HelperKernelContainers();
-			CMemSpyEngineGenericKernelObjectList* iObjectList = kernelContainerManager.ObjectsForSpecificContainerL( tempType() );			
-			
-			for( TInt i=0, offset = 0; i<c; i++, offset += sizeof( TMemSpyDriverHandleInfoGeneric ) )
-				{
-				TMemSpyDriverHandleInfoGeneric data;								
-															
-				data = iObjectList->At( i );
-				
-				TPckgBuf<TMemSpyDriverHandleInfoGeneric> buffer(data);
-				aMessage.WriteL(2, buffer, offset);
-				}			
-					
-			break;
-			}
-			
-		case EMemSpyClientServerOpOutputAllContainerContents:
-			{
-			CMemSpyEngineHelperKernelContainers& kernelContainerManager = iEngine.HelperKernelContainers();
-			CMemSpyEngineGenericKernelObjectContainer* model = kernelContainerManager.ObjectsAllL();
-			
-			model->OutputL( iEngine.Sink() );
-
-			break;
-			}
-			
-		case EMemSpyClientServerOpDumpKernelHeap:
-			{
-		    iEngine.HelperHeap().OutputHeapDataKernelL();
-			
-			break;
-			}
-			
-		case EMemSpyClientServerOpOutputInfoHandles:
-			{
-			TPckgBuf<TThreadId> id;
-			aMessage.ReadL(0, id);
-			CMemSpyEngineObjectContainer& container = iEngine.Container();            
-			CMemSpyProcess* process = NULL;
-			CMemSpyThread* thread = NULL; 
-			User::LeaveIfError( container.ProcessAndThreadByThreadId( id() , process, thread ) );
-										  
-			CMemSpyThreadInfoContainer& threadInfoContainer = thread->InfoContainerForceSyncronousConstructionL();
-			
-			threadInfoContainer.PrintL();
-			
-			break;
-			}
-			
-		case EMemSpyClientServerOpOutputAOList:
-			{
-			TPckgBuf<TThreadId> id;
-			TPckgBuf<TMemSpyThreadInfoItemType> type;
-			aMessage.ReadL(0, id);
-			aMessage.ReadL(1, type);
-			
-			CMemSpyEngineObjectContainer& container = iEngine.Container();            
-			CMemSpyProcess* process = NULL;
-			CMemSpyThread* thread = NULL; 
-			User::LeaveIfError( container.ProcessAndThreadByThreadId( id() , process, thread ) );
-										  
-			CMemSpyThreadInfoContainer& threadInfoContainer = thread->InfoContainerForceSyncronousConstructionL();      
-
-			CMemSpyThreadInfoItemBase* threadInfoItem = &threadInfoContainer.Item( type() );
-						
-			CMemSpyThreadInfoActiveObjects* activeObjectArray = static_cast< CMemSpyThreadInfoActiveObjects* >( threadInfoItem );			
-						
-		    // Begin a new data stream
-		    _LIT( KMemSpyContext, "Active Object List - " );
-		    _LIT( KMemSpyFolder, "Active Objects" );
-		    iEngine.Sink().DataStreamBeginL( KMemSpyContext, KMemSpyFolder );
-		    		    
-		    // Set prefix for overall listing
-		    iEngine.Sink().OutputPrefixSetLC( KMemSpyContext );
-
-		    // Create header
-		    CMemSpyEngineActiveObjectArray::OutputDataColumnsL( iEngine );
-		    
-		    // List items
-		    const TInt count = activeObjectArray->Array().Count();
-		    for(TInt i=0; i<count; i++)
-		        {
-		        const CMemSpyEngineActiveObject& object = activeObjectArray->Array().At( i );
-		        //
-		        object.OutputDataL( iEngine );
-		        }
-
-		    // Tidy up
-		    CleanupStack::PopAndDestroy(); // prefix
-
-		    // End data stream		    		    
-		    iEngine.Sink().DataStreamEndL();		    
-			
-			break;
-			}
-			
-		// --- Kernel Heap related functions ---
-		case EMemSpyClientServerOpGetHeap:
-			{
-			TMemSpyHeapInfo heapInfo;			
-			iEngine.HelperHeap().GetHeapInfoKernelL( heapInfo );
-			TMemSpyHeapData data = iEngine.HelperHeap().NewHeapRawInfo( heapInfo );
-			
-			TPckgBuf<TMemSpyHeapData> buffer(data);
-			aMessage.WriteL(0, buffer);
-			
-			break;
-			}
-			
-		case EMemSpyClientServerOpGetServerCount:
-            {
-            CMemSpyEngineServerList* list = iEngine.HelperServer().ServerListL();
-            CleanupStack::PushL(list);
-            // TODO: cache it between calls
-            aMessage.WriteL(0, TPckgBuf<TInt>(list->MdcaCount()));
-            
-            CleanupStack::PopAndDestroy(list);
-            break;
-            }
-        // --- Servers related functions
-        case EMemSpyClientServerOpGetServers:
-            {
-            CMemSpyEngineServerList* list = iEngine.HelperServer().ServerListL();
-            CleanupStack::PushL(list);
-            
-            TPckgBuf<TInt> a0;
-            aMessage.ReadL(0, a0);
-            TInt realCount = Min(a0(), list->MdcaCount());
-            
-            for(TInt i=0, offset = 0; i<realCount; i++, offset += sizeof(TMemSpyServerData))
-                {
-                const CMemSpyEngineServerEntry& server = list->At(i);
-                TMemSpyServerData data;
-                
-                CMemSpyProcess* process = NULL;
-                CMemSpyThread* thread = NULL;
-                TInt error = iEngine.Container().ProcessAndThreadByThreadId( server.Id(), process, thread );
-                if (error == KErrNone && thread)
-                    {
-                    data.iId = thread->Process().Id();
-                    }
-                data.iName.Copy(server.Name().Left(KMaxFullName));
-                data.iSessionCount = server.SessionCount();
-                
-                TPckgBuf<TMemSpyServerData> buffer(data);
-                aMessage.WriteL(1, buffer, offset);
-                }
-            
-            a0 = list->Count();
-            aMessage.WriteL(0, a0);
-            
-            CleanupStack::PopAndDestroy(list);
-
-            break;
-            }
-            
-        case EMemSpyClientServerOpGetSortedServers:
-        	{
-        	CMemSpyEngineServerList* list = iEngine.HelperServer().ServerListL();
-        	CleanupStack::PushL(list);
-        	
-        	TPckgBuf<TSortType> a2;
-        	aMessage.ReadL( 2, a2 );
-        	
-        	//sort the list of the servers
-        	if( a2() == ESortServByName )
-        		list->SortByNameL();
-        	else
-        		list->SortBySessionCountL();
-        	
-        	TPckgBuf<TInt> a0;        	
-        	aMessage.ReadL(0, a0);        	        	        
-        	
-        	TInt realCount = Min(a0(), list->MdcaCount());
-        	            
-        	for(TInt i=0, offset = 0; i<realCount; i++, offset += sizeof(TMemSpyServerData))
-        		{
-				const CMemSpyEngineServerEntry& server = list->At(i);
-				TMemSpyServerData data;
-        	                
-				data.iId = server.Id();
-				data.iName.Copy(server.Name().Left(KMaxFullName));
-				data.iSessionCount = server.SessionCount();
-        	                
-				TPckgBuf<TMemSpyServerData> buffer(data);
-				aMessage.WriteL(1, buffer, offset);
-        		}        	           
-			a0 = list->Count();
-			aMessage.WriteL(0, a0);
-        	            
-			CleanupStack::PopAndDestroy(list);
-			break;
-        	}
-          
-        case EMemSpyClientServerOpServerListOutputGeneric:
-        	{
-            TPckgBuf<TBool> a0;
-            aMessage.ReadL(0, a0);
-        	
-            CMemSpyEngineServerList* list;            
-            list = iEngine.HelperServer().ServerListL();
-            CleanupStack::PushL(list);
-            
-            _LIT( KMemSpyContext, "Server List - " );
-            _LIT( KMemSpyFolder, "Servers" );
-            iEngine.Sink().DataStreamBeginL( KMemSpyContext, KMemSpyFolder );
-
-            // Set prefix for overall listing
-            iEngine.Sink().OutputPrefixSetLC( KMemSpyContext );
-
-            // Create header
-            CMemSpyEngineServerList::OutputDataColumnsL( iEngine, a0() );
-               
-            // List items
-            const TInt count = list->Count();
-            for(TInt i=0; i<count; i++)
-            	{
-				const CMemSpyEngineServerEntry& server = list->At( i );
-				//
-				server.OutputDataL( iEngine.HelperServer(), a0() );
-            	}
-
-            // Tidy up
-            CleanupStack::PopAndDestroy(); // prefix
-            
-            // End data stream
-            iEngine.Sink().DataStreamEndL();
-            
-            CleanupStack::PopAndDestroy(list);        	
-        	break;
-        	}        	
-        	
-		case EMemSpyClientServerOpGetMemoryTrackingCycleCount:
-			{
-			TInt count = iEngine.HelperSysMemTracker().CompletedCycles().Count();
-			TPckgBuf<TInt> ret( count );
-			aMessage.WriteL( 0, ret );			
-			break;
-			}		
-			
-		case EMemSpyClientServerOpGetMemoryTrackingCycles:
-			{
-			const RPointerArray<CMemSpyEngineHelperSysMemTrackerCycle>& list = iEngine.HelperSysMemTracker().CompletedCycles();
-
-			TPckgBuf<TInt> a0;
-			aMessage.ReadL(0, a0);
-			TInt realCount = Min(a0(), list.Count());
-			
-			for (TInt i=0, offset = 0; i<realCount; i++, offset += sizeof(TMemSpyMemoryTrackingCycleData))
-				{
-				CMemSpyProcess& process = iEngine.Container().At(i);
-				TMemSpyMemoryTrackingCycleData data;
-				data.iCycleNumber = list[i]->CycleNumber();
-				data.iCaption.Copy(list[i]->Caption().Left(KMaxFullName));
-				data.iTime = list[i]->Time();
-				data.iFreeMemory = list[i]->MemoryFree();
-				data.iMemoryDelta = list[i]->MemoryDelta();
-				data.iPreviousCycleDiff = list[i]->MemoryFreePreviousCycle();
-				data.iChangeCount = list[i]->ChangeCount();
-				
-				TPckgBuf<TMemSpyMemoryTrackingCycleData> buffer(data);
-				aMessage.WriteL(1, buffer, offset);
-				}
-			
-			a0 = list.Count();
-			aMessage.WriteL(0, a0);
-
-		break;
-		}
-
-	case EMemSpyClientServerOpIsSwmtRunning:
-		{
-		TPckgBuf<TBool> running(iEngine.HelperSysMemTracker().IsActive());
-		aMessage.WriteL(0, running);
-		break;
-		}
-		
-	case EMemSpyClientServerOpSystemWideMemoryTrackingTimerPeriodGet:
-	    {	    			   
-	    // Get current config
-	    TMemSpyEngineHelperSysMemTrackerConfig config;
-	    iEngine.HelperSysMemTracker().GetConfig( config );
-	    TInt time = config.iTimerPeriod.Int();
-	    TPckgBuf<TInt> tim(time);			            
-	    aMessage.WriteL( 0, tim );
-	    break;
-	    }
-	    
-	case EMemSpyClientServerOpSystemWideMemoryTrackingCategoriesGet:
-		{
-		// Get current config
-		TMemSpyEngineHelperSysMemTrackerConfig config;
-		iEngine.HelperSysMemTracker().GetConfig( config );		
-		TInt categories = config.iEnabledCategories;		
-		TPckgBuf<TInt> ret( categories );
-		aMessage.WriteL( 0, ret );						
-		break;
-		}
-		
-	case EMemSpyClientServerOpSystemWideMemoryTrackingThreadNameFilterGet:
-		{
-		TMemSpyEngineHelperSysMemTrackerConfig config;
-		iEngine.HelperSysMemTracker().GetConfig( config );                 
-		TName threadNameFilter = config.iThreadNameFilter;
-		TPckgBuf<TName> name(threadNameFilter);
-		aMessage.WriteL( 0, name );
-		
-		break;
-		}
-		
-	case EMemSpyClientServerOpSystemWideMemoryTrackingHeapDumpGet:
-		{
-		TMemSpyEngineHelperSysMemTrackerConfig config;
-		iEngine.HelperSysMemTracker().GetConfig( config );		           
-		TBool heapDump = config.iDumpData;
-		TPckgBuf<TBool> heap(heapDump);			            
-		aMessage.WriteL( 0, heap );
-		break;
-		}
-						
-	case EMemSpyClientServerOpSystemWideMemoryTrackingModeGet:
-		{
-		TMemSpyEngineHelperSysMemTrackerConfig config;
-		iEngine.HelperSysMemTracker().GetConfig( config );	 		 
-		TPckgBuf<TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode> mod(config.iMode);			             		            
-		aMessage.WriteL(0, mod);	 			 		    
-		break;
-		}			
-		
-	case EMemSpyClientServerOpNotifyDeviceWideOperationProgress:
-		{
-		if (!Server().CurrentOperationTracker())
-			{
-			User::Leave(KErrNotReady);
-			}
-		
-		Server().CurrentOperationTracker()->AddNotificationL(aMessage);
-		break;
-		}
-		
-	case EMemSpyClientServerOpCancelDeviceWideOperation:
-		if (!Server().CurrentOperationTracker())
-			{
-			User::Leave(KErrNotReady);
-			}
-		
-		Server().CurrentOperationTracker()->Cancel();
-		break;
-	
-		
-	case EMemSpyClientServerOpGetEComCategoryCount:
-	    aMessage.WriteL(0, TPckgBuf<TInt>(iEngine.HelperECom().MdcaCount()));
-	    break;
-	    
-
-	case EMemSpyClientServerOpGetEComCategories:
-	    {
-	    TPckgBuf<TInt> a0;
-        aMessage.ReadL(0, a0);
-        TInt realCount = Min(a0(), iEngine.HelperECom().MdcaCount());
-        
-        for (TInt i=0, offset = 0; i<realCount; i++, offset += sizeof(TMemSpyEComCategoryData))
-            {
-            TMemSpyEComCategoryData data;
-            data.iId.iUid = i;
-            data.iName.Copy(iEngine.HelperECom().At(i).Name());
-            data.iInterfaceCount = iEngine.HelperECom().At(i).MdcaCount();
-            
-            TPckgBuf<TMemSpyEComCategoryData> buffer(data);
-            aMessage.WriteL(1, buffer, offset);
-		}
-        
-        a0 = iEngine.HelperECom().MdcaCount();
-        aMessage.WriteL(0, a0);
-	    break;
-    }
-	    
-	case EMemSpyClientServerOpGetEComInterfaceCount:
-	    {
-	    TPckgBuf<TUid> a1;
-        aMessage.ReadL(1, a1);
-        TInt index = a1().iUid;
-        
-        if (index < 0 || index >= iEngine.HelperECom().MdcaCount())
-            {
-            User::Leave(KErrArgument);
-            }
-        
-        aMessage.WriteL(0, TPckgBuf<TInt>(iEngine.HelperECom().At(index).MdcaCount()));
-	    break;
-	    }
-	            
-	case EMemSpyClientServerOpGetEComInterfaces:
-	    {
-	    TPckgBuf<TInt> a0;
-        aMessage.ReadL(0, a0);
-        TInt realCount = Min(a0(), iEngine.HelperECom().MdcaCount());
-        
-        TPckgBuf<TUid> a1;
-        aMessage.ReadL(1, a1);
-        TInt categoryIndex = a1().iUid;
-        
-        if (categoryIndex < 0 || categoryIndex >= iEngine.HelperECom().MdcaCount())
-            {
-            User::Leave(KErrArgument);
-            }
-        
-        CMemSpyEngineEComCategory &category = iEngine.HelperECom().At(categoryIndex);
-        
-        for (TInt i=0, offset = 0; i<realCount; i++, offset += sizeof(TMemSpyEComInterfaceData))
-            {
-            TMemSpyEComInterfaceData data;
-            data.iId.iUid = (TInt32) &category.At(i);
-            data.iCategoryId.iUid = categoryIndex;
-            data.iName.Copy(category.At(i).Name());
-            data.iImplementationCount = category.At(i).MdcaCount();
-            
-            TPckgBuf<TMemSpyEComInterfaceData> buffer(data);
-            aMessage.WriteL(2, buffer, offset);
-            }
-        
-        a0 = realCount;
-        aMessage.WriteL(0, a0);
-        
-        break;
-	    }
-	    
-	case EMemSpyClientServerOpGetEComImplementationCount:
-	    {
-	    TPckgBuf<TUid> a1;
-        aMessage.ReadL(1, a1);
-        CMemSpyEngineEComInterface* interface = reinterpret_cast<CMemSpyEngineEComInterface*>(a1().iUid);
-        
-        // TODO: check if it really is valid interface 
-        
-        aMessage.WriteL(0, TPckgBuf<TInt>(interface->MdcaCount()));
-	    break;
-	    }
-	                
-	case EMemSpyClientServerOpGetEComImplementations:
-	    {
-        TPckgBuf<TUid> a1;
-        aMessage.ReadL(1, a1);
-        CMemSpyEngineEComInterface* interface = reinterpret_cast<CMemSpyEngineEComInterface*>(a1().iUid);
-        
-        TPckgBuf<TInt> a0;
-        aMessage.ReadL(0, a0);
-        TInt realCount = Min(a0(), interface->MdcaCount());
-        
-        
-        for (TInt i=0, offset = 0; i<realCount; i++, offset += sizeof(TMemSpyEComImplementationData))
-            {
-            TMemSpyEComImplementationData data;
-            data.iName.Copy(interface->At(i).Info().DisplayName());
-            data.iImplementationUid = interface->At(i).Info().ImplementationUid();
-            data.iVersion = interface->At(i).Info().Version();
-            data.iDataType.Copy(interface->At(i).Info().DataType());
-            data.iOpaqueData.Copy(interface->At(i).Info().OpaqueData());
-            data.iDrive = interface->At(i).Info().Drive();
-            data.iRomOnly = interface->At(i).Info().RomOnly();
-            data.iRomBased = interface->At(i).Info().RomBased();
-            data.iVendorId = interface->At(i).Info().VendorId();
-            data.iDisabled = interface->At(i).Info().Disabled();
-            
-            TPckgBuf<TMemSpyEComImplementationData> buffer(data);
-            aMessage.WriteL(2, buffer, offset);
-            }
-        
-        a0 = realCount;
-        aMessage.WriteL(0, a0);
-        
-        break;
-	    }
-	    
-		}
-    }
-
-// ---------------------------------------------------------
-// DoCmdServiceL( const RMessage2& aMessage )
-// ---------------------------------------------------------
-//
-void CMemSpyEngineSession::DoCmdServiceL( const RMessage2& aMessage )
     {
     TInt error = KErrNone;
 
@@ -1448,31 +382,16 @@
 void CMemSpyEngineSession::HandleThreadAgnosticOpL( TInt aFunction, const RMessage2& aMessage )
     {
     TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - START" ) );
-    
     //
     if  ( aFunction ==  EMemSpyClientServerOpHeapInfoCompact )
         {
         TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpHeapInfoCompact") );
-        if (aMessage.Function() & KMemSpyOpFlagsAsyncOperation)
-        	{
-			StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EEntireDeviceHeapInfoCompact, aMessage);
-        	}
-        else
-        	{
-			iEngine.HelperHeap().OutputHeapInfoForDeviceL();
-        	}
+        iEngine.HelperHeap().OutputHeapInfoForDeviceL();
         }
     else if ( aFunction ==  EMemSpyClientServerOpStackInfoCompact )
         {
         TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpStackInfoCompact") );
-        if (aMessage.Function() & KMemSpyOpFlagsAsyncOperation)
-			{
-			StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EEntireDeviceStackInfoCompact, aMessage);
-			}
-		else
-			{
-			iEngine.HelperStack().OutputStackInfoForDeviceL();
-			}
+        iEngine.HelperStack().OutputStackInfoForDeviceL();
         }
     else if ( aFunction == EMemSpyClientServerOpSystemWideMemoryTrackingTimerStart )
         {
@@ -1521,7 +440,6 @@
         // And update config... which will leave if the config is invalid
         iEngine.HelperSysMemTracker().SetConfigL( config );
         }
-    
     else if ( aFunction == EMemSpyClientServerOpSystemWideMemoryTrackingThreadNameFilterSet )
         {
         TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpSystemWideMemoryTrackingThreadNameFilterSet") );
@@ -1560,48 +478,15 @@
         // And update config... which will leave if the config is invalid
         iEngine.HelperSysMemTracker().SetConfigL( config );
         }
-    else if( aFunction == EMemSpyClientServerOpSystemWideMemoryTrackingModeSet)
-    	{
-		TMemSpyEngineHelperSysMemTrackerConfig config;
-		iEngine.HelperSysMemTracker().GetConfig( config );
-		
-		TPckgBuf<TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode> mode;
-		aMessage.ReadL( 0, mode );
-		
-		config.iMode = mode();
-			
-		// And update config... which will leave if the config is invalid
-		iEngine.HelperSysMemTracker().SetConfigL( config );
-    	}
-    
     else if ( aFunction == EMemSpyClientServerOpSwitchOutputSinkTrace )
         {
         TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpSwitchOutputSinkTrace") );
-        iEngine.InstallDebugSinkL();
+        iEngine.InstallSinkL( ESinkTypeDebug );
         }
     else if ( aFunction == EMemSpyClientServerOpSwitchOutputSinkFile )
         {
         TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpSwitchOutputSinkFile") );
-        // Read file name from message.
-        TFileName fileName;
-        RBuf buf;
-		buf.CleanupClosePushL();
-		
-		TInt len = aMessage.GetDesLength( 0 );
-		if ( len > 0 )
-			{
-			buf.CreateL( len );
-			aMessage.ReadL( 0, buf, 0 );
-			
-			iEngine.InstallFileSinkL( buf );           
-			}
-		else
-			{
-			iEngine.InstallFileSinkL( KNullDesC );
-			}
-		
-		CleanupStack::PopAndDestroy( &buf );
-        
+        iEngine.InstallSinkL( ESinkTypeFile );
         }
     else if ( aFunction == EMemSpyClientServerOpEnumerateKernelContainer )
         {
@@ -1632,46 +517,6 @@
         TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpDisableAknIconCache") );
         iEngine.HelperRAM().SetAknIconCacheStatusL( EFalse );
         }
-    else if ( aFunction == EMemSpyClientServerOpSummaryInfo )
-    	{
-		TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpSummaryInfo") );
-		StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EPerEntityGeneralSummary, aMessage);
-    	}
-    else if ( aFunction == EMemSpyClientServerOpSummaryInfoDetailed )
-		{
-		TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpSummaryInfoDetailed") );
-		StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EPerEntityGeneralDetailed, aMessage);
-		}
-    else if ( aFunction == EMemSpyClientServerOpHeapInfo )
-		{
-		TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpHeapInfo") );
-		StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EPerEntityHeapInfo, aMessage);
-		}
-    else if ( aFunction == EMemSpyClientServerOpHeapCellListing )
-		{
-		TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpHeapCellListing") );
-		StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EPerEntityHeapCellListing, aMessage);
-		}
-    else if ( aFunction == EMemSpyClientServerOpHeapData )
-		{
-		TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpHeapData") );
-		StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EPerEntityHeapData, aMessage);
-		}
-    else if ( aFunction == EMemSpyClientServerOpStackInfo )
-		{
-		TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpStackInfo") );
-		StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EPerEntityStackInfo, aMessage);
-		}
-    else if ( aFunction == EMemSpyClientServerOpStackDataUser )
-		{
-		TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpStackDataUser") );
-		StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EPerEntityStackDataUser, aMessage);
-		}
-    else if ( aFunction == EMemSpyClientServerOpStackDataKernel )
-		{
-		TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - EMemSpyClientServerOpStackDataKernel") );
-		StartDeviceWideOperationL(CMemSpyDeviceWideOperations::EPerEntityStackDataKernel, aMessage);
-		}
     else
         {
         TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - [device-wide operation] => invoking UI") );
@@ -1681,108 +526,7 @@
     TRACE( RDebug::Printf("[MemSpy] CMemSpyEngineSession::HandleThreadAgnosticOpL() - END" ) );
     }
 
-void CMemSpyEngineSession::StartDeviceWideOperationL(CMemSpyDeviceWideOperations::TOperation aOperation, const RMessage2& aMessage)
-	{
-	if (Server().CurrentOperationTracker())
-		{
-		User::Leave(KErrInUse);
-		}
-	
-	Server().SetCurrentOperationTracker(CMemSpyDwOperationTracker::NewL(aOperation, aMessage, Server()));
-	}
-
-
-
-
-
 
 
 
 
-CMemSpyDwOperationTracker* CMemSpyDwOperationTracker::NewL(CMemSpyDeviceWideOperations::TOperation aOperation, 
-		const RMessage2& aOperationMessage, CMemSpyEngineServer& aServer)
-	{
-	CMemSpyDwOperationTracker* self = new (ELeave) CMemSpyDwOperationTracker(aOperationMessage, aServer);
-	CleanupStack::PushL( self );
-	self->ConstructL(aOperation);
-	CleanupStack::Pop( self );
-	return self;
-	}
-	
-CMemSpyDwOperationTracker::~CMemSpyDwOperationTracker()
-	{
-	delete iOperation;
-	delete iPendingNotifications;
-	}
-
-CMemSpyDwOperationTracker::CMemSpyDwOperationTracker(const RMessage2& aOperationMessage, CMemSpyEngineServer& aServer) : 
-		iOperationMessage(aOperationMessage),
-		iServer(aServer),
-		iPendingNotifications(0),
-		iOperation(0),
-		iProgress(0)
-	{
-	}
-
-
-void CMemSpyDwOperationTracker::ConstructL(CMemSpyDeviceWideOperations::TOperation aOperation)
-	{
-	iPendingNotifications = new (ELeave) CArrayFixFlat<RMessage2>(3);
-	iOperation = CMemSpyDeviceWideOperations::NewL(iServer.Engine(), *this, aOperation);
-	}
-
-void CMemSpyDwOperationTracker::AddNotificationL(const RMessage2& aMessage)
-	{
-	iPendingNotifications->AppendL(aMessage);
-	}
-
-void CMemSpyDwOperationTracker::Cancel()
-	{
-	iOperation->Cancel();
-	}
-
-void CMemSpyDwOperationTracker::HandleDeviceWideOperationEvent(TEvent aEvent, TInt aParam1, const TDesC& aParam2)
-	{
-	switch( aEvent )
-		{
-	case MMemSpyDeviceWideOperationsObserver::EOperationCompleted:
-	case MMemSpyDeviceWideOperationsObserver::EOperationCancelled:
-		iServer.SetCurrentOperationTracker(0);
-		
-		for (TInt i=0; i<iPendingNotifications->Count(); i++)
-			{
-			iPendingNotifications->At(i).Complete(KErrCancel);
-			}
-		
-		if (iOperationMessage.Function() & KMemSpyOpFlagsAsyncOperation)
-			{
-			iOperationMessage.Complete(
-				aEvent == MMemSpyDeviceWideOperationsObserver::EOperationCompleted ? KErrNone : KErrCancel);
-			}
-		
-		iPendingNotifications->Reset();
-		
-		delete this;
-		break;
-		
-	case MMemSpyDeviceWideOperationsObserver::EOperationProgressEnd:
-		{
-		iProgress += aParam1;
-		for (TInt i=0; i<iPendingNotifications->Count(); i++)
-			{
-			TInt err;
-			TRAP(err, iPendingNotifications->At(i).WriteL(0, TPckgBuf<TInt>( iProgress * 100 / iOperation->TotalOperationSize() )));
-			TRAP(err, iPendingNotifications->At(i).WriteL(1, aParam2));
-			if (err != KErrNone)
-				{
-				// TODO: iPendingProgressNotifications->At(i).Panic()
-				}
-			iPendingNotifications->At(i).Complete(KErrNone);
-			}
-		iPendingNotifications->Reset();
-		break;
-		}
-		
-		}
-	
-	}
--- a/memspy/Engine/Source/DeviceWideOps/MemSpyDeviceWideOperations.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/DeviceWideOps/MemSpyDeviceWideOperations.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -286,10 +286,9 @@
         break;
     case EPerEntityHeapData:
         // Complete op by outputting kernel heap data
-        // TODO: Uncomment after kernel heap dump is fixed
-//        pType.Set( KMemSpyUiThreadNameKernel );
-//        iObserver.HandleDeviceWideOperationEvent( MMemSpyDeviceWideOperationsObserver::EOperationProgressStart, 0, pType );
-//        iEngine.HelperHeap().OutputHeapDataKernelL();
+        pType.Set( KMemSpyUiThreadNameKernel );
+        iObserver.HandleDeviceWideOperationEvent( MMemSpyDeviceWideOperationsObserver::EOperationProgressStart, 0, pType );
+        iEngine.HelperHeap().OutputHeapDataKernelL();
         break;
     default:
         break;
--- a/memspy/Engine/Source/Helpers/MemSpyEngineHelperActiveObject.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/Helpers/MemSpyEngineHelperActiveObject.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -68,7 +68,7 @@
 
 EXPORT_C CMemSpyEngineActiveObjectArray* CMemSpyEngineHelperActiveObject::ActiveObjectListL( const CMemSpyThread& aThread )
     {
-    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListL() - START");
+    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListLC() - START");
     CMemSpyEngineActiveObjectArray* array = CMemSpyEngineActiveObjectArray::NewLC();
 
     // Is the thread's process already suspended? If not, we need to do it now.
@@ -76,7 +76,7 @@
     const TBool isSuspended = ( iEngine.SuspendedProcessId() == parentProcessId );
     if  ( !isSuspended )
         {
-        //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListL() - suspending process");
+        //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListLC() - suspending process");
         iEngine.ProcessSuspendLC( parentProcessId );
         }
 
@@ -84,7 +84,7 @@
     CleanupStack::PushL( TCleanupItem( CleanupHeapWalk, this ) );
 
     // Get the thread info
-    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListL() - getting thread info...");
+    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListLC() - getting thread info...");
     TMemSpyDriverThreadInfo threadInfo;
     TInt err = iEngine.Driver().GetThreadInfo( aThread.Id(), threadInfo );
     User::LeaveIfError( err );
@@ -95,15 +95,15 @@
 #endif
 
     // Get the heap info - we need this for verification purposes
-    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListL() - getting heap info...");
+    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListLC() - getting heap info...");
     err = iEngine.Driver().GetHeapInfoUser( iHeapInfo, aThread.Id() );
     User::LeaveIfError( err );
-    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListL() - allocated cell header length is: %d", iHeapInfo.iHeapCellHeaderLengthAllocated);
+    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListLC() - allocated cell header length is: %d", iHeapInfo.iHeapCellHeaderLengthAllocated);
 
     // Do we have a ROM-based scheduler pointer?
-    if  ( scheduler != NULL && iHeapInfo.Type() != TMemSpyHeapInfo::ETypeUnknown )
+    if  ( scheduler != NULL && iHeapInfo.Type() == TMemSpyHeapInfo::ETypeRHeap )
         {
-        //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListL() - scheduler: 0x%08x", scheduler);
+        //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListLC() - scheduler: 0x%08x", scheduler);
 
         // Let's try to get the scheduler's heap cell...
         HBufC8* data = SchedulerHeapCellDataLC( scheduler, aThread.Id() );
@@ -114,14 +114,14 @@
         }
 
     // Tidy up
-    CleanupStack::PopAndDestroy(this); // heap walk cleanup item
+    CleanupStack::PopAndDestroy(); // heap walk cleanup item
     if  ( !isSuspended )
         {
-        CleanupStack::PopAndDestroy(); // will resume the process we suspended earlier
+        iEngine.ProcessResume();
         }
     //
     CleanupStack::Pop( array );
-    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListL() - END");
+    //RDebug::Printf("CMemSpyEngineHelperActiveObject::ActiveObjectListLC() - END");
     return array;
     }
 
@@ -149,9 +149,9 @@
     //RDebug::Printf("CMemSpyEngineHelperActiveObject::SchedulerHeapCellDataLC() - err: %d, cellLength: %d, cellAllocationNumber: %d, cellType: %d", err, cellLength, cellAllocationNumber, cellType);
     User::LeaveIfError( err );
     
-	if (cellType & EMemSpyDriverAllocatedCellMask)
+    if  ( cellType == EMemSpyDriverGoodAllocatedCell )
         {
-        const TInt payloadLength = cellLength;
+        const TInt payloadLength = cellLength - iHeapInfo.AsRHeap().MetaData().HeaderSizeAllocated();
         HBufC8* data = HBufC8::NewLC( payloadLength );
         TPtr8 pData( data->Des() );
         //
@@ -281,9 +281,9 @@
     //RDebug::Printf("CMemSpyEngineHelperActiveObject::ReadActiveObjectDataL() - err: %d, cellLength: %d, cellAllocationNumber: %d, cellType: %d", err, cellLength, cellAllocationNumber, cellType);
     User::LeaveIfError( err );
     
-    if (cellType & EMemSpyDriverAllocatedCellMask)
+    if  ( cellType == EMemSpyDriverGoodAllocatedCell )
         {
-        const TInt payloadLength = cellLength;
+        const TInt payloadLength = cellLength - iHeapInfo.AsRHeap().MetaData().HeaderSizeAllocated();
         //RDebug::Printf("CMemSpyEngineHelperActiveObject::ReadActiveObjectDataL() - payloadLength: %d", payloadLength);
 
         // const TInt payloadLength = Max( 512, cellLength - iHeapInfo.iHeapCellHeaderLengthAllocated ); // Prevent negative payload lengths?
--- a/memspy/Engine/Source/Helpers/MemSpyEngineHelperFbServ.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/Helpers/MemSpyEngineHelperFbServ.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -300,11 +300,12 @@
     // Get the heap info - we need this for verification purposes
     TMemSpyHeapInfo info;
     TInt err = iEngine.Driver().GetHeapInfoUser( info, aFbServThread.Id() );
-    if ( err == KErrNone && info.Type() == TMemSpyHeapInfo::ETypeUnknown )
+    if ( err == KErrNone && info.Type() != TMemSpyHeapInfo::ETypeRHeap )
         {
         err = KErrNotSupported;
         }
     User::LeaveIfError( err );
+    TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::LocateCFbTopHeapCellDataLC() - allocated cell header length is: %d", info.AsRHeap().MetaData().HeaderSizeAllocated() ));
 
     // Now walk the heap!
     err = iEngine.Driver().WalkHeapInit( aFbServThread.Id() );
@@ -323,12 +324,13 @@
             err = iEngine.Driver().WalkHeapNextCell( aFbServThread.Id(), cellType, cellAddress, cellLength, cellNestingLevel, cellAllocationNumber, cellHeaderSize, cellPayloadAddress );
             TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::LocateCFbTopHeapCellDataLC() - cellIndex[%d] err: %d, cellLength: %d, cellAllocationNumber: %d, cellType: %d", cellIndex, err, cellLength, cellAllocationNumber, cellType));
 
-            if  ( err == KErrNone && (cellType & EMemSpyDriverAllocatedCellMask))
+            if  ( err == KErrNone && cellType == EMemSpyDriverGoodAllocatedCell )
                 {
                 // We know we are looking for a relatively large *allocated* cell.
-                if  ( cellLength >= KFbServExpectedMinimumCellSize && cellLength <= KFbServExpectedMaximumCellSize )
+                if  ( cellLength >= KFbServExpectedMinimumCellSize && cellLength <= KFbServExpectedMaximumCellSize && cellType == EMemSpyDriverGoodAllocatedCell )
                     {
-                    const TInt payloadLength = cellLength;
+                    const TInt payloadLength = cellLength - info.AsRHeap().MetaData().HeaderSizeAllocated();
+                    TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::LocateCFbTopHeapCellDataLC() - cell was long enough. Full cell len: %d, header: %d, therefore dataLen: %d", cellLength, info.AsRHeap().MetaData().HeaderSizeAllocated(), payloadLength));
 
                     // This is *probably* the right cell. Let's get the data and check.
                     HBufC8* data = HBufC8::NewLC( payloadLength );
@@ -343,9 +345,9 @@
                         //iEngine.Sink().OutputBinaryDataL( KHeapDumpDataFormat, pData.Ptr(), (const TUint8*) cellAddress, pData.Length() );
                     
                         // Check the data
-                        const TUint heapMaxSize = info.AsRHeap().MetaData().iMaxHeapSize;
-                        const TUint heapBaseAddress = (TUint) info.AsRHeap().MetaData().ChunkBaseAddress();
-                        const TBool correctHeapCellLocated = VerifyCorrectHeapCellL( *data, cellAddress, cellPayloadAddress, heapBaseAddress, heapMaxSize );
+                        const TUint heapSize = info.AsRHeap().ObjectData().Size();
+                        const TUint heapBaseAddress = (TUint) info.AsRHeap().ObjectData().Base();
+                        const TBool correctHeapCellLocated = VerifyCorrectHeapCellL( *data, cellAddress, cellPayloadAddress, heapBaseAddress, heapSize );
                         TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::LocateCFbTopHeapCellDataLC() - verified: %d", correctHeapCellLocated));
 
                         if  ( correctHeapCellLocated )
@@ -402,7 +404,7 @@
     TInt err = iEngine.Driver().WalkHeapGetCellInfo( aCellAddress, cellType, cellLength, cellNestingLevel, cellAllocationNumber, cellHeaderSize, cellPayloadAddress );
     TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::ReadCObjectConInfoL() - err: %d, cellAddress: 0x%08x, cellLength: %d, cellAllocationNumber: %d, cellType: %d", err, aCellAddress, cellLength, cellAllocationNumber, cellType));
 
-	if (err == KErrNone && (cellType & EMemSpyDriverAllocatedCellMask))
+    if  ( err == KErrNone && cellType == EMemSpyDriverGoodAllocatedCell )
         {
         // Check that the cell size meets our expectations - it should be a CObjectCon cell.
         const TInt expectedCellSize = sizeof(CObjectCon*) + cellHeaderSize;
@@ -518,7 +520,7 @@
     TInt err = iEngine.Driver().WalkHeapGetCellInfo( aArrayCellAddress, cellType, cellLength, cellNestingLevel, cellAllocationNumber, cellHeaderSize, cellPayloadAddress );
     TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::LocateCFbTopHeapCellDataLC() - err: %d, cellAddress: 0x%08x, cellLength: %d, cellAllocationNumber: %d, cellType: %d", err, aArrayCellAddress, cellLength, cellAllocationNumber, cellType));
 
-    if (err == KErrNone && (cellType & EMemSpyDriverAllocatedCellMask))
+    if  ( err == KErrNone && cellType == EMemSpyDriverGoodAllocatedCell )
         {
         // Check that the cell size meets our expectations. 
         // The cell should be a very specific length
@@ -575,13 +577,13 @@
     }
 
 
-TBool CMemSpyEngineHelperFbServ::VerifyCorrectHeapCellL( const TDesC8& aData, TAny* aCellAddress, TAny* aPayloadAddress, TUint aHeapStartingAddress, TUint aHeapMaxSize )
+TBool CMemSpyEngineHelperFbServ::VerifyCorrectHeapCellL( const TDesC8& aData, TAny* aCellAddress, TAny* aPayloadAddress, TUint aHeapStartingAddress, TUint aHeapSize )
     {
     (void) aPayloadAddress;
     (void) aCellAddress;
-    TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::VerifyCorrectHeapCellL() - START - aDataLen: %d, aCellAddress: 0x%08x, aPayloadAddress: 0x%08x, aHeapStartingAddress: 0x%08x, aHeapSize: %d", aData.Length(), aCellAddress, aPayloadAddress, aHeapStartingAddress, aHeapMaxSize ));
+    TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::VerifyCorrectHeapCellL() - START - aDataLen: %d, aCellAddress: 0x%08x, aPayloadAddress: 0x%08x, aHeapStartingAddress: 0x%08x, aHeapSize: %d", aData.Length(), aCellAddress, aPayloadAddress, aHeapStartingAddress, aHeapSize ));
 
-    const TUint KFbServHeapCeilingAddress = aHeapStartingAddress + aHeapMaxSize;
+    const TUint KFbServHeapCeilingAddress = aHeapStartingAddress + aHeapSize;
 
     // Whether we can use this cell's data...
     TBool correctCell = EFalse;
@@ -744,7 +746,7 @@
     TInt err = iEngine.Driver().WalkHeapGetCellInfo( aCellAddress, cellType, cellLength, cellNestingLevel, cellAllocationNumber, cellHeaderSize, cellPayloadAddress );
     TRACE( RDebug::Printf("CMemSpyEngineHelperFbServ::GetBitmapObjectLC() - err: %d, cellAddress: 0x%08x, cellLength: %d, cellAllocationNumber: %d, cellType: %d", err, aCellAddress, cellLength, cellAllocationNumber, cellType));
 
-    if (err == KErrNone && (cellType & EMemSpyDriverAllocatedCellMask))
+    if  ( err == KErrNone && cellType == EMemSpyDriverGoodAllocatedCell )
         {
         // Check that the cell size meets our expectations - it should be a CBitmapObject, but without the additional "this" pointer
         // which we have tacked onto the object.
--- a/memspy/Engine/Source/Helpers/MemSpyEngineHelperHeap.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/Helpers/MemSpyEngineHelperHeap.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -45,7 +45,6 @@
 _LIT( KCellTypeBadAllocatedCellAddress,  "[Bad Allocated Cell Address]");
 _LIT( KCellTypeBadFreeCellAddress,       "[Bad Free Cell Address]     ");
 _LIT( KCellTypeBadFreeCellSize,          "[Bad Free Cell Size]        ");
-_LIT( KCellTypeBad,                      "[Bad Cell]                  ");
 _LIT( KCellTypeUnknown,                  "[Unknown!]                  ");
 _LIT( KCellListLineFormat, "%S cell: 0x%08x, cellLen: %8d, allocNum: %8d, nestingLev: %8d, cellData: 0x%08x, cellDataAddr: 0x%08x, headerSize: %02d");
 _LIT( KMemSpyMarkerHeapData, "<%SMEMSPY_HEAP_DATA_%03d>" );
@@ -105,7 +104,7 @@
         {
         UpdateSharedHeapInfoL( aThread.Process().Id(), aThread.Id(), heapInfo );
         }
-    if  ( error == KErrNone && heapInfo.Type() != TMemSpyHeapInfo::ETypeUnknown )
+    if  ( error == KErrNone && heapInfo.Type() == TMemSpyHeapInfo::ETypeRHeap )
         {
         // Get thread name for context
         const TFullName pName( aThread.FullName() );
@@ -160,43 +159,36 @@
                 TUint fourByteCellData = 0;
                 TPtrC pType(KNullDesC);
                 //
-				if (cellType & EMemSpyDriverAllocatedCellMask)
-					{
+                switch(cellType)
+                    {
+                case EMemSpyDriverGoodAllocatedCell:
+                    {
                     r = iEngine.Driver().WalkHeapReadCellData( cellAddress, cellData, 4 );
                     if  ( r == KErrNone )
                         {
                         fourByteCellData = DescriptorAsDWORD( cellData );
                         }
                     pType.Set(KCellTypeGoodAllocatedCell);
+                    break;
                     }
-				else if (cellType & EMemSpyDriverFreeCellMask)
-					{
+                case EMemSpyDriverGoodFreeCell:
                     pType.Set(KCellTypeGoodFreeCell);
-					}
-				else if (cellType & EMemSpyDriverBadCellMask)
-					{
-					switch (cellType)
-						{
-					case EMemSpyDriverHeapBadAllocatedCellSize:
-						pType.Set(KCellTypeBadAllocatedCellSize);
-						break;
-					case EMemSpyDriverHeapBadAllocatedCellAddress:
-						pType.Set(KCellTypeBadAllocatedCellAddress);
-						break;
-					case EMemSpyDriverHeapBadFreeCellAddress:
-						pType.Set(KCellTypeBadFreeCellAddress);
-						break;
-					case EMemSpyDriverHeapBadFreeCellSize:
-						pType.Set(KCellTypeBadFreeCellSize);
-						break;
-					default:
-						pType.Set(KCellTypeBad);
-						break;
-						}
-					}
-				else
-					{
+                    break;
+                case EMemSpyDriverBadAllocatedCellSize:
+                    pType.Set(KCellTypeBadAllocatedCellSize);
+                    break;
+                case EMemSpyDriverBadAllocatedCellAddress:
+                    pType.Set(KCellTypeBadAllocatedCellAddress);
+                    break;
+                case EMemSpyDriverBadFreeCellAddress:
+                    pType.Set(KCellTypeBadFreeCellAddress);
+                    break;
+                case EMemSpyDriverBadFreeCellSize:
+                    pType.Set(KCellTypeBadFreeCellSize);
+                    break;
+                default:
                     pType.Set(KCellTypeUnknown);
+                    break;
                     }
 
                 if  ( r == KErrNone )
@@ -249,30 +241,31 @@
     // Make sure the process is suspended for the entire time we are manipulating it's heap
     iEngine.ProcessSuspendLC( aThread.Process().Id() );
 
-    // Get the heap info, including cell information
-    RArray<TMemSpyDriverCell> cells;
-    CleanupClosePushL( cells );
+    // Get the heap info, including free cell information
+    RArray<TMemSpyDriverFreeCell> freeCells;
+    CleanupClosePushL( freeCells );
     TMemSpyHeapInfo heapInfo;
     TRACE( RDebug::Printf( "CMemSpyEngineHelperHeap::OutputHeapDataUserL() - checksum1: 0x%08x", heapInfo.AsRHeap().Statistics().StatsFree().Checksum() ) );
-    GetHeapInfoUserL(aThread.Process().Id(), aThread.Id(), heapInfo, &cells, ETrue);
+    GetHeapInfoUserL( aThread.Process().Id(), aThread.Id(), heapInfo, &freeCells );
     TRACE( RDebug::Printf( "CMemSpyEngineHelperHeap::OutputHeapDataUserL() - checksum2: 0x%08x", heapInfo.AsRHeap().Statistics().StatsFree().Checksum() ) );
 
     // Get the heap data
     const TFullName pName( aThread.FullName() );
-    OutputHeapDataUserL( aThread.Process().Id(), aThread.Id(), pName, heapInfo, aCreateDataStream, &cells );
-    CleanupStack::PopAndDestroy( &cells );
+    OutputHeapDataUserL( aThread.Process().Id(), aThread.Id(), pName, heapInfo, aCreateDataStream, &freeCells );
+    CleanupStack::PopAndDestroy( &freeCells );
 
     // Resume process
     CleanupStack::PopAndDestroy();
     }
 
 
-EXPORT_C void CMemSpyEngineHelperHeap::OutputHeapDataUserL(const TProcessId& aPid, const TThreadId& aTid, const TDesC& aThreadName, const TMemSpyHeapInfo& aInfo, const RArray<TMemSpyDriverCell>* aCells)
+EXPORT_C void CMemSpyEngineHelperHeap::OutputHeapDataUserL( const TProcessId& aPid, const TThreadId& aTid, const TDesC& aThreadName, const TMemSpyHeapInfo& aInfo, const RArray<TMemSpyDriverFreeCell>* aFreeCells )
     {
-    OutputHeapDataUserL(aPid, aTid, aThreadName, aInfo, ETrue, aCells);
+    OutputHeapDataUserL( aPid, aTid, aThreadName, aInfo, ETrue, aFreeCells );
     }
 
-void CMemSpyEngineHelperHeap::OutputHeapDataUserL( const TProcessId& aPid, const TThreadId& aTid, const TDesC& aThreadName, const TMemSpyHeapInfo& aInfo, TBool aCreateDataStream, const RArray<TMemSpyDriverCell>* aCells )
+
+void CMemSpyEngineHelperHeap::OutputHeapDataUserL( const TProcessId& aPid, const TThreadId& aTid, const TDesC& aThreadName, const TMemSpyHeapInfo& aInfo, TBool aCreateDataStream, const RArray<TMemSpyDriverFreeCell>* aFreeCells )
     {
     TBuf<KMaxFullName + 100> printFormat;
 
@@ -298,7 +291,7 @@
     iEngine.Sink().OutputPrefixSetFormattedLC( KMemSpyPrefixHeapData, &aThreadName );
 
     // Info section
-    OutputHeapInfoL( aInfo, aThreadName, aCells );
+    OutputHeapInfoL( aInfo, aThreadName, aFreeCells );
 
     // Code segments (needed for map file reading...)
     _LIT(KCellListCodeSegInfoFormat, "CodeSegs - ");
@@ -322,25 +315,14 @@
     TRACE( RDebug::Printf( "CMemSpyEngineHelperHeap::OutputHeapDataUserL() - checksum: 0x%08x", checksum ) );
 
     TInt r = iEngine.Driver().GetHeapData( aTid, checksum, pData, readAddress, remaining );
-	TUint prevEndAddress = readAddress + pData.Length();
-    if (r == KErrNone)
+    if  ( r == KErrNone )
         {
-        while (r == KErrNone)
+        while ( r == KErrNone )
             {
-			if (readAddress > prevEndAddress)
-				{
-				// We've hit a discontinuity, ie one or more unmapped pages
-				_LIT(KBreak, "........");
-				iEngine.Sink().OutputLineL(KBreak);
-				}
             _LIT(KHeapDumpDataFormat, "%S");
-            iEngine.Sink().OutputBinaryDataL(KHeapDumpDataFormat, pData.Ptr(), (const TUint8*) readAddress, pData.Length());
-			readAddress += pData.Length();
-            if (remaining > 0)
-				{
-				prevEndAddress = readAddress;
-                r = iEngine.Driver().GetHeapDataNext(aTid, pData, readAddress, remaining);
-				}
+            iEngine.Sink().OutputBinaryDataL( KHeapDumpDataFormat, pData.Ptr(), (const TUint8*) readAddress, pData.Length() );
+            if  ( remaining > 0 )
+                r = iEngine.Driver().GetHeapDataNext( aTid, pData, readAddress, remaining );
             else
                 break;
             }
@@ -383,9 +365,11 @@
 
 
 
-EXPORT_C void CMemSpyEngineHelperHeap::OutputHeapInfoL( const TMemSpyHeapInfo& aInfo, const TDesC& aThreadName, const RArray<TMemSpyDriverCell>* aCells )
-	{
-    CMemSpyEngineOutputList* list = NewHeapSummaryExtendedLC(aInfo, aCells);
+
+
+EXPORT_C void CMemSpyEngineHelperHeap::OutputHeapInfoL( const TMemSpyHeapInfo& aInfo, const TDesC& aThreadName, const RArray<TMemSpyDriverFreeCell>* aFreeCells )
+    {
+    CMemSpyEngineOutputList* list = NewHeapSummaryExtendedLC( aInfo, aFreeCells );
 
     // Format the thread name according to upper/lower case request parameters
     _LIT( KOverallCaption1, "HEAP INFO FOR THREAD '%S'");
@@ -432,6 +416,7 @@
     {
     const TMemSpyHeapInfoRHeap& rHeapInfo = aInfo.AsRHeap();
     const TMemSpyHeapMetaDataRHeap& rHeapMetaData = rHeapInfo.MetaData();
+    const TMemSpyHeapObjectDataRHeap& rHeapObjectData = rHeapInfo.ObjectData();
     const TMemSpyHeapStatisticsRHeap& rHeapStats = rHeapInfo.Statistics();
 
     // Example:
@@ -471,20 +456,20 @@
                                          aIndex,
                                          aInfo.Tid(),
                                          rHeapMetaData.ChunkHandle(),
-                                         rHeapMetaData.iAllocatorAddress,
-                                         rHeapMetaData.iHeapSize,
-                                         rHeapMetaData.iMinHeapSize,
-                                         rHeapMetaData.iMaxHeapSize,
-                                         NULL, // there's no longer a free list so we can't return the next ptr
-                                         0, // there's no longer a free list so we can't return it's length
+                                         rHeapObjectData.Base(),
+                                         rHeapObjectData.Size(),
+                                         rHeapObjectData.iMinLength,
+                                         rHeapObjectData.iMaxLength,
+                                         rHeapObjectData.iFree.next,
+                                         rHeapObjectData.iFree.len,
                                          rHeapStats.StatsFree().TypeCount(),
                                          rHeapStats.StatsFree().TypeSize(),
                                          rHeapStats.StatsFree().SlackSpaceCellSize(),
                                          rHeapStats.StatsFree().LargestCellSize(),
                                          rHeapStats.StatsAllocated().LargestCellSize(),
-                                         rHeapStats.StatsAllocated().TypeCount(),
-                                         0, // min cell no longer makes sense
-                                         rHeapStats.StatsAllocated().TypeSize(),
+                                         rHeapObjectData.iCellCount,
+                                         rHeapObjectData.iMinCell,
+                                         rHeapObjectData.iTotalAllocSize,
                                          rHeapMetaData.IsSharedHeap(),
                                          &KFmtFields,
                                          aIndex
@@ -534,7 +519,7 @@
         // Get kernel heap info
         GetHeapInfoKernelL( info );
 
-        if ( info.Type() != TMemSpyHeapInfo::ETypeUnknown )
+        if ( info.Type() == TMemSpyHeapInfo::ETypeRHeap )
             {
             TName threadName;
             MemSpyEngineUtils::GetKernelHeapThreadAndProcessNames( threadName, processName );
@@ -561,7 +546,7 @@
                     {
                     UpdateSharedHeapInfoL( process.Id(), thread.Id(), info );
                     }
-                if  ( error == KErrNone && info.Type() != TMemSpyHeapInfo::ETypeUnknown )
+                if  ( error == KErrNone && info.Type() == TMemSpyHeapInfo::ETypeRHeap )
                     {
                     OutputCSVEntryL( index++, info, threadName, processName );
                     }
@@ -592,21 +577,16 @@
 
 
 
-EXPORT_C void CMemSpyEngineHelperHeap::GetHeapInfoUserL(const TProcessId& aProcess, const TThreadId& aThread, TMemSpyHeapInfo& aInfo, RArray<TMemSpyDriverFreeCell>* aFreeCells)
-    {
-	GetHeapInfoUserL(aProcess, aThread, aInfo, aFreeCells, EFalse);
-	}
-
-EXPORT_C void CMemSpyEngineHelperHeap::GetHeapInfoUserL(const TProcessId& aProcess, const TThreadId& aThread, TMemSpyHeapInfo& aInfo, RArray<TMemSpyDriverCell>* aCells, TBool aCollectAllocatedCellsAsWellAsFree)
+EXPORT_C void CMemSpyEngineHelperHeap::GetHeapInfoUserL( const TProcessId& aProcess, const TThreadId& aThread, TMemSpyHeapInfo& aInfo, RArray<TMemSpyDriverFreeCell>* aFreeCells )
     {
     iEngine.ProcessSuspendLC( aProcess );
     TRACE( RDebug::Printf( "CMemSpyEngineHelperHeap::GetHeapInfoUserL() - checksum1: 0x%08x", aInfo.AsRHeap().Statistics().StatsFree().Checksum() ) );
     
     TInt r = KErrNone;
     //
-    if  (aCells)
+    if  ( aFreeCells )
         {
-        r = iEngine.Driver().GetHeapInfoUser( aInfo, aThread, *aCells, aCollectAllocatedCellsAsWellAsFree);
+        r = iEngine.Driver().GetHeapInfoUser( aInfo, aThread, *aFreeCells );
         }
     else
         {
@@ -756,11 +736,9 @@
     _LIT(KHeaderDump, "Heap Data");
     iEngine.Sink().OutputSectionHeadingL( KHeaderDump, '-' );
 
-    /*TOMSCI TODO this stuff needs fixing
-	_LIT(KHeapDumpDataFormat, "%S");
+    _LIT(KHeapDumpDataFormat, "%S");
     const TUint8* heapBaseAddress = info.AsRHeap().ObjectData().Base();
     iEngine.Sink().OutputBinaryDataL( KHeapDumpDataFormat, data->Ptr(), heapBaseAddress, data->Length() );
-	*/
 
     CleanupStack::PopAndDestroy(); // clear prefix
     CleanupStack::PopAndDestroy( data );
@@ -817,29 +795,22 @@
         _LIT( KItem0_Type_Unknown, "Unknown" );
         list->AddItemL( KItem0, KItem0_Type_Unknown );
         }
-    else
+    else if ( aInfo.Type() == TMemSpyHeapInfo::ETypeRHeap )
         {
         const TMemSpyHeapInfoRHeap& rHeap = aInfo.AsRHeap();
         const TMemSpyHeapMetaDataRHeap& metaData = rHeap.MetaData();
+        const TMemSpyHeapObjectDataRHeap& objectData = rHeap.ObjectData();
         const TMemSpyHeapStatisticsRHeap& statistics = rHeap.Statistics();
 
         _LIT( KItem0_Type_RHeap, "RHeap" );
-        _LIT( KItem0_Type_RHybridHeap, "RHybridHeap" );
-		if (aInfo.Type() == TMemSpyHeapInfo::ETypeRHeap)
-			{
-	        list->AddItemL( KItem0, KItem0_Type_RHeap );
-			}
-		else
-			{
-	        list->AddItemL( KItem0, KItem0_Type_RHybridHeap );
-			}
+        list->AddItemL( KItem0, KItem0_Type_RHeap );
 
         // Heap size is the size of the heap minus the size of the embedded (in-place) RHeap. 
         _LIT( KItem1, "Heap size" );
-        list->AddItemL(KItem1, metaData.iHeapSize);
+        list->AddItemL( KItem1, objectData.Size() );
 
-        _LIT( KItem8b, "Allocator address" );
-        list->AddItemHexL( KItem8b, (TUint)metaData.iAllocatorAddress );
+        _LIT( KItem8b, "Heap base address" );
+        list->AddItemHexL( KItem8b, (TUint) objectData.Base() );
         
         _LIT( KItem1b, "Shared" );
         list->AddItemYesNoL( KItem1b, metaData.IsSharedHeap() );
@@ -874,21 +845,34 @@
         // Fragmentation is a measurement of free space scattered throughout the heap, but ignoring
         // any slack space at the end (which can often be recovered, to the granularity of one page of ram)
         _LIT( KItem8a, "Fragmentation" );
-        list->AddItemPercentageL( KItem8a, metaData.iHeapSize, ( statistics.StatsFree().TypeSize()  - statistics.StatsFree().SlackSpaceCellSize() ) );
+        list->AddItemPercentageL( KItem8a, objectData.Size(), ( statistics.StatsFree().TypeSize()  - statistics.StatsFree().SlackSpaceCellSize() ) );
+
+        _LIT( KItem13, "Header size (A)" );
+        list->AddItemL( KItem13, metaData.HeaderSizeAllocated() );
+
+        _LIT( KItem14, "Header size (F)" );
+        list->AddItemL( KItem14, metaData.HeaderSizeFree() );
 
+        _LIT( KItem9a, "Overhead (alloc)" );
+        const TInt allocOverhead = metaData.HeaderSizeAllocated() * statistics.StatsAllocated().TypeCount();
+        list->AddItemL( KItem9a, allocOverhead );
+
+        _LIT( KItem9b, "Overhead (free)" );
+        const TInt freeOverhead = metaData.HeaderSizeFree() * statistics.StatsFree().TypeCount();
+        list->AddItemL( KItem9b, freeOverhead );
 
         _LIT( KItem9c, "Overhead (total)" );
-		const TInt totalOverhead = metaData.iHeapSize - statistics.StatsAllocated().TypeSize();
+        const TInt totalOverhead = freeOverhead + allocOverhead;
         list->AddItemL( KItem9c, totalOverhead );
 
         _LIT( KItem9d, "Overhead" );
-        list->AddItemPercentageL( KItem9d, metaData.iHeapSize, totalOverhead  );
+        list->AddItemPercentageL( KItem9d, objectData.Size(), totalOverhead  );
 
         _LIT( KItem10, "Min. length" );
-        list->AddItemL( KItem10, metaData.iMinHeapSize );
+        list->AddItemL( KItem10, objectData.iMinLength );
 
         _LIT( KItem11, "Max. length" );
-        list->AddItemL( KItem11, metaData.iMaxHeapSize );
+        list->AddItemL( KItem11, objectData.iMaxLength );
 
         _LIT( KItem12, "Debug Allocator Library" );
         list->AddItemYesNoL( KItem12, metaData.IsDebugAllocator() );
@@ -898,78 +882,23 @@
     }
 
 
-EXPORT_C CMemSpyEngineOutputList* CMemSpyEngineHelperHeap::NewHeapSummaryExtendedLC( const TMemSpyHeapInfo& aInfo, const RArray<TMemSpyDriverCell>* aCells )
-	{
+EXPORT_C CMemSpyEngineOutputList* CMemSpyEngineHelperHeap::NewHeapSummaryExtendedLC( const TMemSpyHeapInfo& aInfo, const RArray<TMemSpyDriverFreeCell>* aFreeCells )
+    {
     CMemSpyEngineOutputList* list = CMemSpyEngineOutputList::NewLC( iEngine.Sink() );
     //
     AppendMetaDataL( aInfo, *list );
+    AppendObjectDataL( aInfo, *list );
     AppendStatisticsL( aInfo, *list );
     //
-    if  ( aCells )
+    if  ( aFreeCells )
         {
-        AppendCellsL( *aCells, *list );
+        AppendFreeCellsL( *aFreeCells, *list );
         }
     //
     return list;
     }
 
 
-//cigasto: not formatted - raw heap info 
-EXPORT_C TMemSpyHeapData CMemSpyEngineHelperHeap::NewHeapRawInfo( const TMemSpyHeapInfo& aInfo )
-	{
-	_LIT(KUnknown, "Unknown");
-	TMemSpyHeapData list;
-	list.iType.Copy(KUnknown);
-
-	// Heap type	
-	if (aInfo.Type() != TMemSpyHeapInfo::ETypeUnknown)
-		{
-		const TMemSpyHeapInfoRHeap& rHeap = aInfo.AsRHeap();
-		const TMemSpyHeapMetaDataRHeap& metaData = rHeap.MetaData();
-		const TMemSpyHeapStatisticsRHeap& statistics = rHeap.Statistics();
-
-		_LIT(KRHeap, "RHeap");
-		_LIT(KRHybridHeap, "RHybridHeap");
-		switch (aInfo.Type())
-			{
-			case TMemSpyHeapInfo::ETypeRHeap:
-				list.iType.Copy(KRHeap);
-				break;
-			case TMemSpyHeapInfo::ETypeRHybridHeap:
-				list.iType.Copy(KRHybridHeap);
-				break;
-			default:
-				break;
-			}
-
-	    // Heap size is the total amount of memory committed to the heap, which includes the size of the embedded (in-place) RHeap/RHybridHeap.
-	    list.iSize = metaData.iHeapSize;
-	    list.iBaseAddress = (TUint)metaData.iAllocatorAddress; // TODO we can't do the base address any more, allocator address is the closest thing
-	    list.iShared = metaData.IsSharedHeap();
-	    list.iChunkSize = metaData.ChunkSize();
-	    list.iAllocationsCount = statistics.StatsAllocated().TypeCount();
-	    list.iFreeCount = statistics.StatsFree().TypeCount();
-	    list.iBiggestAllocation = statistics.StatsAllocated().LargestCellSize();
-	    list.iBiggestFree = statistics.StatsFree().LargestCellSize();
-	    list.iTotalAllocations =  statistics.StatsAllocated().TypeSize();	        
-	    list.iTotalFree =  statistics.StatsFree().TypeSize();
-	    list.iSlackFreeSpace = statistics.StatsFree().SlackSpaceCellSize();
-	    list.iFragmentation = statistics.StatsFree().TypeSize() - statistics.StatsFree().SlackSpaceCellSize(); //to calculate percentage value use iSize as 100% value
-	    list.iHeaderSizeA = 0; //metaData.HeaderSizeAllocated();
-	    list.iHeaderSizeF = 0; //metaData.HeaderSizeFree();
-	    TInt allocOverhead = rHeap.Overhead(); //metaData.HeaderSizeAllocated() * statistics.StatsAllocated().TypeCount();
-	    list.iAllocationOverhead = allocOverhead;
-	    //TInt freeOverhead = metaData.HeaderSizeFree() * statistics.StatsFree().TypeCount();
-	    list.iFreeOverhead = 0; // TODO there is no way of calculating this
-	    list.iTotalOverhead = allocOverhead; // freeOverhead + allocOverhead
-	    list.iOverhead = allocOverhead; //freeOverhead + allocOverhead; //to calculate percentage value use iSize as 100% value    
-	    list.iMinLength = metaData.iMinHeapSize;
-	    list.iMaxLength = metaData.iMaxHeapSize;
-	    list.iDebugAllocatorLibrary = metaData.IsDebugAllocator();
-		}
-
-	return list;
-	}
 
 
 
@@ -1023,7 +952,7 @@
 
     // Type
     _LIT( KMetaData_Type,  "Type:" );
-    if ( aInfo.Type() == TMemSpyHeapInfo::ETypeUnknown )
+    if ( aInfo.Type() != TMemSpyHeapInfo::ETypeRHeap )
         {
         _LIT( KMetaData_Type_Unknown,  "Unknown" );
         aList.AddItemL( KMetaData_Type, KMetaData_Type_Unknown );
@@ -1034,23 +963,15 @@
     
         // Type
         _LIT( KMetaData_Type_RHeap,  "Symbian OS RHeap" );
-        _LIT( KMetaData_Type_RHybridHeap,  "Symbian OS RHybridHeap" );
-		if (aInfo.Type() == TMemSpyHeapInfo::ETypeRHeap)
-			{
-	        aList.AddItemL( KMetaData_Type, KMetaData_Type_RHeap );
-			}
-		else
-			{
-			aList.AddItemL( KMetaData_Type, KMetaData_Type_RHybridHeap );
-			}
+        aList.AddItemL( KMetaData_Type, KMetaData_Type_RHeap );
 
         // VTable
-        //_LIT( KMetaData_VTable,  "VTable:" );
-        //aList.AddItemHexL( KMetaData_VTable, metaData.VTable() );
+        _LIT( KMetaData_VTable,  "VTable:" );
+        aList.AddItemHexL( KMetaData_VTable, metaData.VTable() );
 
         // Object size
-        //_LIT( KMetaData_ObjectSize,  "Object Size:" );
-        //aList.AddItemL( KMetaData_ObjectSize, metaData.ClassSize() );
+        _LIT( KMetaData_ObjectSize,  "Object Size:" );
+        aList.AddItemL( KMetaData_ObjectSize, metaData.ClassSize() );
 
         // Chunk name
         _LIT( KMetaData_ChunkName,  "Chunk Name:" );
@@ -1069,6 +990,14 @@
         _LIT( KMetaData_DebugAllocator,  "Debug Allocator:" );
         aList.AddItemYesNoL( KMetaData_DebugAllocator, metaData.IsDebugAllocator() );
 
+        // Cell header overhead (free cells)
+        _LIT( KMetaData_CellHeaderOverheadFree,  "Overhead (Free):" );
+        aList.AddItemL( KMetaData_CellHeaderOverheadFree, metaData.HeaderSizeFree() );
+
+        // Cell header overhead (allocated cells)
+        _LIT( KMetaData_CellHeaderOverheadAlloc,  "Overhead (Alloc):" );
+        aList.AddItemL( KMetaData_CellHeaderOverheadAlloc, metaData.HeaderSizeAllocated() );
+
         // Shared Heap
         _LIT( KMetaData_Shared,  "Shared:" );
         aList.AddItemYesNoL( KMetaData_Shared, metaData.IsSharedHeap() );
@@ -1080,9 +1009,90 @@
     aList.AddBlankItemL( 1 );
     }
 
+
+void CMemSpyEngineHelperHeap::AppendObjectDataL( const TMemSpyHeapInfo& aInfo, CMemSpyEngineOutputList& aList )
+    {
+    if ( aInfo.Type() == TMemSpyHeapInfo::ETypeRHeap )
+        {
+        const TMemSpyHeapInfoRHeap& rHeap = aInfo.AsRHeap();
+        const TMemSpyHeapObjectDataRHeap& objectData = rHeap.ObjectData();
+
+        // Make caption
+        _LIT( KOverallCaption1, "RAllocator" );
+        aList.AddItemL( KOverallCaption1 );
+        aList.AddUnderlineForPreviousItemL( '=', 0 );
+
+        // RAllocator
+        _LIT( KObjectData_RAllocator_iAccessCount,  "RAllocator::iAccessCount" );
+        aList.AddItemL( KObjectData_RAllocator_iAccessCount, objectData.iAccessCount );
+        _LIT( KObjectData_RAllocator_iHandleCount,  "RAllocator::iHandleCount" );
+        aList.AddItemL( KObjectData_RAllocator_iHandleCount, objectData.iHandleCount );
+        _LIT( KObjectData_RAllocator_iHandles,  "RAllocator::iHandles" );
+        aList.AddItemL( KObjectData_RAllocator_iHandles, objectData.iHandles );
+        _LIT( KObjectData_RAllocator_iFlags,  "RAllocator::iFlags" );
+        aList.AddItemHexL( KObjectData_RAllocator_iFlags, objectData.iFlags );
+        _LIT( KObjectData_RAllocator_iCellCount,  "RAllocator::iCellCount" );
+        aList.AddItemL( KObjectData_RAllocator_iCellCount, objectData.iCellCount );
+        _LIT( KObjectData_RAllocator_iTotalAllocSize,  "RAllocator::iTotalAllocSize" );
+        aList.AddItemL( KObjectData_RAllocator_iTotalAllocSize, objectData.iTotalAllocSize );
+
+        aList.AddBlankItemL( 1 );
+
+        // Make caption
+        _LIT( KOverallCaption2, "RHeap" );
+        aList.AddItemL( KOverallCaption2 );
+        aList.AddUnderlineForPreviousItemL( '=', 0 );
+
+        // RHeap
+        _LIT( KObjectData_RHeap_iMinLength,  "RHeap::iMinLength" );
+        aList.AddItemL( KObjectData_RHeap_iMinLength, objectData.iMinLength );
+        _LIT( KObjectData_RHeap_iMaxLength,  "RHeap::iMaxLength" );
+        aList.AddItemL( KObjectData_RHeap_iMaxLength, objectData.iMaxLength );
+        _LIT( KObjectData_RHeap_iOffset,  "RHeap::iOffset" );
+        aList.AddItemL( KObjectData_RHeap_iOffset, objectData.iOffset );
+        _LIT( KObjectData_RHeap_iGrowBy,  "RHeap::iGrowBy" );
+        aList.AddItemL( KObjectData_RHeap_iGrowBy, objectData.iGrowBy );
+        _LIT( KObjectData_RHeap_iChunkHandle,  "RHeap::iChunkHandle" );
+        aList.AddItemHexL( KObjectData_RHeap_iChunkHandle, objectData.iChunkHandle );
+        _LIT( KObjectData_RHeap_iBase,  "RHeap::iBase" );
+        aList.AddItemL( KObjectData_RHeap_iBase, objectData.iBase );
+        _LIT( KObjectData_RHeap_iTop,  "RHeap::iTop" );
+        aList.AddItemL( KObjectData_RHeap_iTop, objectData.iTop );
+        _LIT( KObjectData_RHeap_iAlign,  "RHeap::iAlign" );
+        aList.AddItemL( KObjectData_RHeap_iAlign, objectData.iAlign );
+        _LIT( KObjectData_RHeap_iMinCell,  "RHeap::iMinCell" );
+        aList.AddItemL( KObjectData_RHeap_iMinCell, objectData.iMinCell );
+        _LIT( KObjectData_RHeap_iPageSize,  "RHeap::iPageSize" );
+        aList.AddItemL( KObjectData_RHeap_iPageSize, objectData.iPageSize );
+        _LIT( KObjectData_RHeap_iFree_next,  "RHeap::iFree.next" );
+        aList.AddItemL( KObjectData_RHeap_iFree_next, objectData.iFree.next );
+        _LIT( KObjectData_RHeap_iFree_len,  "RHeap::iFree.len" );
+        aList.AddItemL( KObjectData_RHeap_iFree_len, objectData.iFree.len );
+        _LIT( KObjectData_RHeap_iNestingLevel,  "RHeap::iNestingLevel" );
+        aList.AddItemL( KObjectData_RHeap_iNestingLevel, objectData.iNestingLevel );
+        _LIT( KObjectData_RHeap_iAllocCount,  "RHeap::iAllocCount" );
+        aList.AddItemL( KObjectData_RHeap_iAllocCount, objectData.iAllocCount );
+        _LIT( KObjectData_RHeap_iFailType,  "RHeap::iFailType" );
+        aList.AddItemL( KObjectData_RHeap_iFailType, (TInt) objectData.iFailType );
+        _LIT( KObjectData_RHeap_iFailRate,  "RHeap::iFailRate" );
+        aList.AddItemL( KObjectData_RHeap_iFailRate, objectData.iFailRate );
+        _LIT( KObjectData_RHeap_iFailed,  "RHeap::iFailed" );
+        aList.AddItemTrueFalseL( KObjectData_RHeap_iFailed, objectData.iFailed );
+        _LIT( KObjectData_RHeap_iFailAllocCount,  "RHeap::iFailAllocCount" );
+        aList.AddItemL( KObjectData_RHeap_iFailAllocCount, objectData.iFailAllocCount );
+        _LIT( KObjectData_RHeap_iRand,  "RHeap::iRand" );
+        aList.AddItemL( KObjectData_RHeap_iRand, objectData.iRand );
+        _LIT( KObjectData_RHeap_iTestData,  "RHeap::iTestData" );
+        aList.AddItemL( KObjectData_RHeap_iTestData, objectData.iTestData );
+
+        aList.AddBlankItemL( 1 );
+        }
+    }
+
+
 void CMemSpyEngineHelperHeap::AppendStatisticsL( const TMemSpyHeapInfo& aInfo, CMemSpyEngineOutputList& aList )
     {
-    if (aInfo.Type() != TMemSpyHeapInfo::ETypeUnknown)
+    if ( aInfo.Type() == TMemSpyHeapInfo::ETypeRHeap )
         {
         const TMemSpyHeapInfoRHeap& rHeap = aInfo.AsRHeap();
         const TMemSpyHeapStatisticsRHeap& rHeapStats = rHeap.Statistics();
@@ -1102,13 +1112,10 @@
         aList.AddItemL( KStatsData_CellSize, rHeapStats.StatsFree().TypeSize() );
         aList.AddItemL( KStatsData_LargestCellAddress, rHeapStats.StatsFree().LargestCellAddress() );
         aList.AddItemL( KStatsData_LargestCellSize, rHeapStats.StatsFree().LargestCellSize() );
-		if (aInfo.Type() == TMemSpyHeapInfo::ETypeRHeap)
-			{
-			_LIT( KStatsData_Free_SlackCellAddress,  "Slack:" );
-			aList.AddItemL( KStatsData_Free_SlackCellAddress, rHeapStats.StatsFree().SlackSpaceCellAddress() );
-			_LIT( KStatsData_Free_SlackCellSize,  "Slack size:" );
-			aList.AddItemL( KStatsData_Free_SlackCellSize, rHeapStats.StatsFree().SlackSpaceCellSize() );
-			}
+        _LIT( KStatsData_Free_SlackCellAddress,  "Slack:" );
+        aList.AddItemL( KStatsData_Free_SlackCellAddress, rHeapStats.StatsFree().SlackSpaceCellAddress() );
+        _LIT( KStatsData_Free_SlackCellSize,  "Slack size:" );
+        aList.AddItemL( KStatsData_Free_SlackCellSize, rHeapStats.StatsFree().SlackSpaceCellSize() );
         _LIT( KStatsData_Free_Checksum,  "Checksum:" );
         aList.AddItemHexL( KStatsData_Free_Checksum, rHeapStats.StatsFree().Checksum() );
 
@@ -1125,60 +1132,43 @@
         aList.AddItemL( KStatsData_LargestCellSize, rHeapStats.StatsAllocated().LargestCellSize() );
 
         aList.AddBlankItemL( 1 );
-         }
+
+        // Common
+        _LIT( KOverallCaption3, "Common Statistics" );
+        aList.AddItemL( KOverallCaption3 );
+        aList.AddUnderlineForPreviousItemL( '=', 0 );
+
+        _LIT( KStatsData_Common_TotalCellCount,  "Total cell count:" );
+        aList.AddItemL( KStatsData_Common_TotalCellCount, rHeapStats.StatsCommon().TotalCellCount() );
+
+        _LIT( KStatsData_Common_TotalSize,  "Total cell size:" );
+        aList.AddItemL( KStatsData_Common_TotalSize, rHeapStats.StatsAllocated().TypeSize() + rHeapStats.StatsFree().TypeSize() );
+
+        aList.AddBlankItemL( 1 );
+        }
     }
 
 
-void CMemSpyEngineHelperHeap::AppendCellsL(const RArray<TMemSpyDriverCell>& aCells, CMemSpyEngineOutputList& aList)
+void CMemSpyEngineHelperHeap::AppendFreeCellsL( const RArray<TMemSpyDriverFreeCell>& aFreeCells, CMemSpyEngineOutputList& aList )
     {
-    // For reasons that may or may not turn out to be sensible, we separate free and allocated cells in the output data
-
+    // Free space
     _LIT( KOverallCaption1, "Free Cell List" );
     aList.AddItemL( KOverallCaption1 );
     aList.AddUnderlineForPreviousItemL( '=', 0 );
 
     TBuf<128> caption;
     _LIT( KCaptionFormat, "FC %04d" );
-    _LIT( KValueFormat, "0x%08x %8d %d" );
+    _LIT( KValueFormat, "0x%08x %8d %1d" );
 
-	TBool foundAllocatedCells = EFalse;
-    const TInt count = aCells.Count();
+    const TInt count = aFreeCells.Count();
     for( TInt i=0; i<count; i++ )
         {
-        const TMemSpyDriverCell& cell = aCells[ i ];
-		if (cell.iType & EMemSpyDriverAllocatedCellMask)
-			{
-			foundAllocatedCells = ETrue;
-			}
-		else if (cell.iType & EMemSpyDriverFreeCellMask)
-			{
-	        caption.Format( KCaptionFormat, i + 1 );
-		    aList.AddItemFormatL( caption, KValueFormat, cell.iAddress, cell.iLength, cell.iType );
-			}
+        const TMemSpyDriverFreeCell& cell = aFreeCells[ i ];
+        caption.Format( KCaptionFormat, i + 1 );
+        aList.AddItemFormatL( caption, KValueFormat, cell.iAddress, cell.iLength, cell.iType );
         }
+    }
 
-	if (foundAllocatedCells)
-		{
-        aList.AddBlankItemL( 1 );
-		_LIT( KOverallCaption1, "Allocated Cell List" );
-		aList.AddItemL( KOverallCaption1 );
-		aList.AddUnderlineForPreviousItemL( '=', 0 );
-
-		TBuf<128> caption;
-		_LIT( KCaptionFormat, "AC %04d" );
-		_LIT( KValueFormat, "0x%08x %8d %d" );
-
-		for (TInt i = 0; i < count; i++)
-			{
-			const TMemSpyDriverCell& cell = aCells[ i ];
-			if (cell.iType & EMemSpyDriverAllocatedCellMask)
-				{
-				caption.Format( KCaptionFormat, i + 1 );
-				aList.AddItemFormatL( caption, KValueFormat, cell.iAddress, cell.iLength, cell.iType );
-				}
-			}
-		}
-    }
 
 void CMemSpyEngineHelperHeap::UpdateSharedHeapInfoL( const TProcessId& aProcess, const TThreadId& aThread, TMemSpyHeapInfo& aInfo )
     {
--- a/memspy/Engine/Source/Helpers/MemSpyEngineHelperKernelContainers.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/Helpers/MemSpyEngineHelperKernelContainers.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -247,16 +247,6 @@
     {
     return iType;
     }
-
-EXPORT_C TInt CMemSpyEngineGenericKernelObjectList::Size() const
-    {
-    return iSize;
-    }
-
-EXPORT_C TInt CMemSpyEngineGenericKernelObjectList::ItemsCount() const
-	{
-	return iItems.Count();
-	}
     
 
 EXPORT_C TPtrC CMemSpyEngineGenericKernelObjectList::TypeAsString( TMemSpyDriverContainerType aType )
@@ -402,7 +392,7 @@
     AddItemL( aItem.iHandle );
     iItems.AppendL( aItem );
     //
-    //UpdateNameL();
+    UpdateNameL();
     }
 
 
--- a/memspy/Engine/Source/Helpers/MemSpyEngineHelperStack.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/Helpers/MemSpyEngineHelperStack.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -250,22 +250,36 @@
 
         if  ( r == KErrNone )
             {
-            while ( r == KErrNone )
-                {
-                iEngine.Sink().OutputBinaryDataL( KStackDataPrefix, pData.Ptr(), (const TUint8*) info.iUserStackBase, pData.Length() );
-                //
-                if  ( remaining > 0 )
+            if ( aType == EMemSpyDriverDomainUser ) {
+                while ( r == KErrNone )
                     {
-                    info.iUserStackBase += pData.Length();
-                    r = iEngine.Driver().GetStackDataNext( aThread.Id(), pData, remaining, aType, aEntireStack );
+                    iEngine.Sink().OutputBinaryDataL( KStackDataPrefix, pData.Ptr(), (const TUint8*) info.iUserStackBase, pData.Length() );
+                    //
+                    if  ( remaining > 0 )
+                        {
+                        info.iUserStackBase += pData.Length();
+                        r = iEngine.Driver().GetStackDataNext( aThread.Id(), pData, remaining, aType, aEntireStack );
+                        }
+                    else
+                        {
+                        break;
+                        }
                     }
-                else
-                    {
-                    break;
+            }
+            else if ( aType == EMemSpyDriverDomainKernel ) {
+                while ( r == KErrNone ) {
+                
+                    iEngine.Sink().OutputBinaryDataL( KStackDataPrefix, pData.Ptr(), (const TUint8*) info.iSupervisorStackBase, pData.Length() );
+                    //
+                    if  ( remaining > 0 ) {
+                        info.iSupervisorStackBase += pData.Length();
+                        r = iEngine.Driver().GetStackDataNext( aThread.Id(), pData, remaining, aType, aEntireStack );
                     }
-                }
+                    else {
+                         break;
+                    }
+               }
             }
-
         }
     CleanupStack::PopAndDestroy( data );
 
@@ -276,6 +290,7 @@
     iEngine.Sink().OutputLineFormattedL( KMemSpyMarkerStackData, &KMemSpySinkTagClose, (TUint) aThread.Id() );
     iEngine.Sink().DataStreamEndL();
     }
+}    
 
 
 EXPORT_C void CMemSpyEngineHelperStack::OutputStackInfoForDeviceL()
--- a/memspy/Engine/Source/MemSpyEngine.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/MemSpyEngine.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -67,10 +67,6 @@
     return self;
     }
 
-EXPORT_C CMemSpyEngine* CMemSpyEngine::NewL( RFs& aFsSession, TBool aStartServer )
-    {
-    return NewL(aFsSession);
-    }
 
 EXPORT_C RFs& CMemSpyEngine::FsSession()
     {
@@ -122,18 +118,9 @@
 
 EXPORT_C void CMemSpyEngine::InstallSinkL( TMemSpySinkType aType )
     {
-    iImp->InstallSinkL( aType, KNullDesC );
+    iImp->InstallSinkL( aType );
     }
 
-EXPORT_C void CMemSpyEngine::InstallDebugSinkL()
-    {
-    iImp->InstallSinkL( ESinkTypeDebug, KNullDesC );
-    }
-
-EXPORT_C void CMemSpyEngine::InstallFileSinkL( const TDesC& aRootFolder )
-    {
-    iImp->InstallSinkL( ESinkTypeFile, aRootFolder );
-    }
 
 EXPORT_C void CMemSpyEngine::ListOpenFilesL()
     {
--- a/memspy/Engine/Source/MemSpyEngineImp.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/MemSpyEngineImp.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -52,11 +52,6 @@
 #include <memspy/engine/memspyenginehelperwindowserver.h>
 #include <memspy/engine/memspyenginehelpercondvar.h>
 
-#ifdef _DEBUG
-#define LOG(args...) RDebug::Printf(args)
-#else
-#define LOG(args...)
-#endif
 
 CMemSpyEngineImp::CMemSpyEngineImp( RFs& aFsSession, CMemSpyEngine& aEngine )
 :   iFsSession( aFsSession ), iEngine( aEngine )
@@ -66,14 +61,18 @@
 
 CMemSpyEngineImp::~CMemSpyEngineImp()
     {
-    LOG( "CMemSpyEngineImp::~CMemSpyEngineImp() - START" );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::~CMemSpyEngineImp() - START" );
+#endif
 
     if  ( iMidwife )
         {
         iMidwife->RemoveObserver( *this );
         }
 
-    LOG( "CMemSpyEngineImp::~CMemSpyEngineImp() - deleting helpers..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::~CMemSpyEngineImp() - deleting helpers..." );
+#endif
     delete iHelperSysMemTracker;
     delete iServer;
     delete iHelperKernelContainers;
@@ -95,37 +94,52 @@
     
     iHelperWindowServerLoader.Close();
 
-    LOG( "CMemSpyEngineImp::~CMemSpyEngineImp() - deleting utilities..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::~CMemSpyEngineImp() - deleting utilities..." );
+#endif
     delete iChunkWatcher;
     delete iUndertaker;
     delete iMidwife;
 
-    LOG( "CMemSpyEngineImp::~CMemSpyEngineImp() - destroying containers..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::~CMemSpyEngineImp() - destroying containers..." );
+#endif
     iContainers.ResetAndDestroy();
     iContainers.Close();
 
-    LOG( "CMemSpyEngineImp::~CMemSpyEngineImp() - destroying driver..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::~CMemSpyEngineImp() - destroying driver..." );
+#endif
     if  ( iMemSpyDriver )
         {
         iMemSpyDriver->Close();
         delete iMemSpyDriver;
         }
 
-    LOG( "CMemSpyEngineImp::~CMemSpyEngineImp() - destroying sink..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::~CMemSpyEngineImp() - destroying sink..." );
+#endif
     delete iSink;
 
-    LOG( "CMemSpyEngineImp::~CMemSpyEngineImp() - END" );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::~CMemSpyEngineImp() - END" );
+#endif
     }
 
 
 void CMemSpyEngineImp::ConstructL()
     {
-    LOG( "CMemSpyEngineImp::ConstructL() - START" );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructL() - START" );
+#endif
     //
     iFsSession.SetSessionPath( _L("\\") );
     
+    // Starting the server before the driver connection is made
+    // ensures that only one instance of MemSpy can run (either the S60
+    // UI or the console UI ).
     iServer = CMemSpyEngineServer::NewL( iEngine );
-    
+    //
     iMemSpyDriver = new(ELeave) RMemSpyDriverClient();
     const TInt error = Driver().Open();
     User::LeaveIfError( error );
@@ -149,60 +163,96 @@
     iHelperSysMemTracker = CMemSpyEngineHelperSysMemTracker::NewL( iEngine );
     iMidwife->AddObserverL( *this );
 
-    LOG( "CMemSpyEngineImp::ConstructL() - END" );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructL() - END" );
+#endif
     }
 
 
 void CMemSpyEngineImp::ConstructHelpersL()
     {
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - START" );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - START" );
+#endif
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - Heap..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - Heap..." );
+#endif
     iHelperHeap = CMemSpyEngineHelperHeap::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - Stack..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - Stack..." );
+#endif
     iHelperStack = CMemSpyEngineHelperStack::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - Code Segments..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - Code Segments..." );
+#endif
     iHelperCodeSegment = CMemSpyEngineHelperCodeSegment::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - Chunk..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - Chunk..." );
+#endif
     iHelperChunk = CMemSpyEngineHelperChunk::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - Thread..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - Thread..." );
+#endif
     iHelperThread = CMemSpyEngineHelperThread::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - Process..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - Process..." );
+#endif
     iHelperProcess = CMemSpyEngineHelperProcess::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - Server..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - Server..." );
+#endif
     iHelperServer = CMemSpyEngineHelperServer::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - AO..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - AO..." );
+#endif
     iHelperActiveObject = CMemSpyEngineHelperActiveObject::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - Kernel Containers..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - Kernel Containers..." );
+#endif
     iHelperKernelContainers = CMemSpyEngineHelperKernelContainers::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - File System..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - File System..." );
+#endif
     iHelperFileSystem = CMemSpyEngineHelperFileSystem::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - ECOM..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - ECOM..." );
+#endif
     iHelperECom = CMemSpyEngineHelperECom::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - FBSERV..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - FBSERV..." );
+#endif
     iHelperFbServ = CMemSpyEngineHelperFbServ::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - ROM..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - ROM..." );
+#endif
     iHelperROM = CMemSpyEngineHelperROM::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - RAM..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - RAM..." );
+#endif
     iHelperRAM = CMemSpyEngineHelperRAM::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - WindowServer..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - WindowServer..." );
+#endif
     
     TInt err = iHelperWindowServerLoader.Load( _L("memspywindowserverhelper.dll") );
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - WindowServer load err: %d", err );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - WindowServer load err: %d", err );
+#endif
     if ( !err )
         {
 #ifdef __WINS__ // ordinal is different 
@@ -212,19 +262,18 @@
 #endif
         if ( entry != NULL )
             {
-			typedef MMemSpyEngineHelperWindowServer* (*TEntryFn)(void);
-			TRAP(err, iHelperWindowServer = ((TEntryFn)entry)());
-			if (err)
-				{
-				LOG("err from memspywindowserverhelper.dll - %d", err);
-				}
+            iHelperWindowServer = (MMemSpyEngineHelperWindowServer*) entry();
             }
         }
     
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - CondVar..." );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - CondVar..." );
+#endif
     iHelperCondVar = CMemSpyEngineHelperCondVar::NewL( iEngine );
 
-    LOG( "CMemSpyEngineImp::ConstructHelpersL() - END" );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::ConstructHelpersL() - END" );
+#endif
     }
 
 
@@ -285,14 +334,12 @@
     return iSink->Type();
     }
 
+
 void CMemSpyEngineImp::InstallSinkL( TMemSpySinkType aType )
-	{
-	InstallSinkL( aType, KNullDesC );
-	}
-
-void CMemSpyEngineImp::InstallSinkL( TMemSpySinkType aType, const TDesC& aRootFolder )
     {
-    LOG( "CMemSpyEngineImp::InstallSinkL() - START - switching sink from %d to %d...", (iSink != NULL ? iSink->Type() : -1), aType );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::InstallSinkL() - START - switching sink from %d to %d...", (iSink != NULL ? iSink->Type() : -1), aType );
+#endif
     //
     CMemSpyEngineOutputSink* sink = NULL;
     //
@@ -302,14 +349,16 @@
         sink = CMemSpyEngineOutputSinkDebug::NewL( iEngine );
         break;
     case ESinkTypeFile:
-        sink = CMemSpyEngineOutputSinkFile::NewL( iEngine, aRootFolder );
+        sink = CMemSpyEngineOutputSinkFile::NewL( iEngine );
         break;
         }
     //
     delete iSink;
     iSink = sink;
     //
-    LOG( "CMemSpyEngineImp::InstallSinkL() - END - sink type: %d", iSink->Type() );
+#ifdef _DEBUG
+    RDebug::Printf( "CMemSpyEngineImp::InstallSinkL() - END - sink type: %d", iSink->Type() );
+#endif
     }
 
 
--- a/memspy/Engine/Source/MemSpyEngineUtils.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/MemSpyEngineUtils.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -274,7 +274,7 @@
 
 EXPORT_C TMemSpyPercentText MemSpyEngineUtils::FormatPercentage( TReal aOneHundredPercentValue, TReal aValue )
     {
-    const TReal value = (( aValue / aOneHundredPercentValue) * 100.0);
+    const TReal value = (TInt) (( aValue / aOneHundredPercentValue) * 100.0);
     
     _LIT(KPercentFormat, "%3.2f %%");
 
@@ -365,7 +365,6 @@
 EXPORT_C void MemSpyEngineUtils::GetFolderL( RFs& aFsSession, TDes& aFolder, const CMemSpyEngineSinkMetaData& aMetaData, const TDriveNumber* aForceDrive )
     {
     const TChar KMemSpyDirectorySeparator = '\\';
-    const TChar KMemSpyDriveSeparator = ':';
 
     TDriveList drives;
     User::LeaveIfError( aFsSession.DriveList( drives ) );
@@ -380,26 +379,7 @@
         }
     else
         {
-		// check if drive is specified in root path
-		if ( aMetaData.Root().Length() > 2 && aMetaData.Root()[1] == KMemSpyDriveSeparator )
-			{
-			TChar drive = aMetaData.Root()[0];
-			
-			// check if drive is valid
-			if (drives.Locate(drive) != KErrNone)
-				{
-				TDriveUnit driveUnit( aMetaData.Root().Left(1) );
-				logDrive = static_cast<TDriveNumber>(static_cast<TInt>(driveUnit));
-				}
-			else
-				{
-				logDrive = MemSpyEngineUtils::LocateSuitableDrive( aFsSession );
-				}
-			}
-		else
-			{
-			logDrive = MemSpyEngineUtils::LocateSuitableDrive( aFsSession );
-			}
+        logDrive = MemSpyEngineUtils::LocateSuitableDrive( aFsSession );
         }
 
     // Prepare the drive buffer
@@ -409,35 +389,7 @@
     // Prepare the drive name
     TDriveUnit driveUnit( logDrive );
     pFileName.Append( driveUnit.Name() );
-    
-    if ( aMetaData.Root().Length() == 0 )
-    	{
-		pFileName.Append( KMemSpyLogRootPath );
-    	}
-    else
-    	{
-		TPtrC root( aMetaData.Root() );
-		// check if root path contains drive (e.g. c:) and remove it
-		if ( root.Length() > 2 && root[1] == KMemSpyDriveSeparator )
-			{
-			root.Set( root.Mid( 2 ) );
-			}
-		// check if root starts with \ and remove it
-		if ( root.Length() > 1 && root[0] == KMemSpyDirectorySeparator )
-			{
-			root.Set( root.Mid( 1 ) );
-			}
-		
-		// append root path
-		pFileName.Append( KMemSpyDirectorySeparator );
-		pFileName.Append( root );
-		
-		// add trailing slash if necessary
-		if ( root[root.Length() - 1] != KMemSpyDirectorySeparator )
-			{
-			pFileName.Append( KMemSpyDirectorySeparator );
-			}
-    	}
+    pFileName.Append( KMemSpyLogRootPath );
 
     // Add any custom folder information
     if  ( aMetaData.Folder().Length() > 0 )
--- a/memspy/Engine/Source/Sink/MemSpyEngineOutputList.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/Sink/MemSpyEngineOutputList.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -102,18 +102,8 @@
         for( TInt j=0; j<count; j++ )
             {
             const CMemSpyEngineOutputListItem* item = iItems[ j ];
-			if (item->Value().Length())
-				{
-	            maxLengthCaption = Max( maxLengthCaption, item->Caption().Length() );
-	            maxLengthValue = Max( maxLengthValue, item->Value().Length() );
-				}
-			else
-				{
-				// If something doesn't have a value (ie it's a section header, represented as just a caption) then the caption
-				// shouldn't be factored into the maxcaptionlength. But consider it in maxlengthValue to make sure we actually
-				// make the overall buffers big enough
-				maxLengthValue = Max( maxLengthValue, item->Caption().Length() );
-				}
+            maxLengthCaption = Max( maxLengthCaption, item->Caption().Length() );
+            maxLengthValue = Max( maxLengthValue, item->Value().Length() );
             }
 
         // Second pass - real this time - to print the values
@@ -131,15 +121,7 @@
             HBufC* value = MemSpyEngineUtils::CleanupTextLC( item->Value() );
 
             // Now format the final line, with padding.
-			if (value->Length()) 
-				{
-	            pLine.Justify( *caption, maxLengthCaption + 3, ELeft, TChar(' ') );
-				}
-			else
-				{
-				// items without value (ie just captions, ie section headers) aren't constrained by the maxLengthCaption restriction
-				pLine.Copy(*caption);
-				}
+            pLine.Justify( *caption, maxLengthCaption + 3, ELeft, TChar(' ') );
             pLine.Append( *value );
             CleanupStack::PopAndDestroy( 2, caption );
 
--- a/memspy/Engine/Source/Sink/MemSpyEngineOutputSink.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/Sink/MemSpyEngineOutputSink.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -380,7 +380,6 @@
 
 EXPORT_C CMemSpyEngineSinkMetaData::~CMemSpyEngineSinkMetaData()
     {
-	delete iRoot;
     delete iContext;
     delete iFolder;
     delete iExtension;
@@ -388,9 +387,8 @@
     }
 
 
-void CMemSpyEngineSinkMetaData::ConstructL( const TDesC& aRoot, const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, const TTime& aFolderTime )
+void CMemSpyEngineSinkMetaData::ConstructL( const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, const TTime& aFolderTime )
     {
-	iRoot = aRoot.AllocL();
     iContext = aContext.AllocL();
     iFolder = aFolder.AllocL();
     iExtension = aExtension.AllocL();
@@ -409,24 +407,15 @@
     return CMemSpyEngineSinkMetaData::NewL( KNullDesC, KNullDesC, KNullDesC, ETrue, ETrue );
     }
 
-EXPORT_C CMemSpyEngineSinkMetaData* CMemSpyEngineSinkMetaData::NewL(  const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp )
-	{
-	return NewL( KNullDesC, aContext, aFolder, aExtension, aOverwrite, aUseFileTimeStamp );
-	}
 
-EXPORT_C CMemSpyEngineSinkMetaData* CMemSpyEngineSinkMetaData::NewL( const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp, const TTime& aFolderTimeStamp )
-    {
-    return NewL( KNullDesC, aContext, aFolder, aExtension, aOverwrite, aUseFileTimeStamp, aFolderTimeStamp );
-    }
-
-EXPORT_C CMemSpyEngineSinkMetaData* CMemSpyEngineSinkMetaData::NewL( const TDesC& aRoot, const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp )
+EXPORT_C CMemSpyEngineSinkMetaData* CMemSpyEngineSinkMetaData::NewL( const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp )
     {
     // Create a dummy time, we'll clear it after ConstructL() returns...
     TTime now; now.HomeTime();
 
     CMemSpyEngineSinkMetaData* self = new(ELeave) CMemSpyEngineSinkMetaData( aOverwrite, aUseFileTimeStamp );
     CleanupStack::PushL( self );
-    self->ConstructL( aRoot, aContext, aFolder, aExtension, now );
+    self->ConstructL( aContext, aFolder, aExtension, now );
     CleanupStack::Pop( self );
 
     // Clear folder time stamp
@@ -434,11 +423,14 @@
     return self;
     }
 
-EXPORT_C CMemSpyEngineSinkMetaData* CMemSpyEngineSinkMetaData::NewL( const TDesC& aRoot, const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp, const TTime& aFolderTimeStamp )
+
+EXPORT_C CMemSpyEngineSinkMetaData* CMemSpyEngineSinkMetaData::NewL( const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp, const TTime& aFolderTimeStamp )
     {
     CMemSpyEngineSinkMetaData* self = new(ELeave) CMemSpyEngineSinkMetaData( aOverwrite, aUseFileTimeStamp );
     CleanupStack::PushL( self );
-    self->ConstructL( aRoot, aContext, aFolder, aExtension, aFolderTimeStamp );
+    self->ConstructL( aContext, aFolder, aExtension, aFolderTimeStamp );
     CleanupStack::Pop( self );
     return self;
     }
+
+
--- a/memspy/Engine/Source/Sink/MemSpyEngineOutputSinkFile.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/Sink/MemSpyEngineOutputSinkFile.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -41,8 +41,6 @@
 CMemSpyEngineOutputSinkFile::~CMemSpyEngineOutputSinkFile()
     {
     TRACE( RDebug::Printf( "CMemSpyEngineOutputSinkFile::~CMemSpyEngineOutputSinkFile() - START" ) );
-    
-    delete iRoot;
 
     TRACE( RDebug::Printf( "CMemSpyEngineOutputSinkFile::~CMemSpyEngineOutputSinkFile() - destroying normal logs..." ) );
     iLogs.ResetAndDestroy();
@@ -58,11 +56,9 @@
     }
 
 
-void CMemSpyEngineOutputSinkFile::ConstructL( const TDesC& aRootFolder )
+void CMemSpyEngineOutputSinkFile::ConstructL()
     {
     TRACE( RDebug::Printf( "CMemSpyEngineOutputSinkFile::ConstructL() - START" ) );
-    
-    iRoot = aRootFolder.AllocL();
 
     BaseConstructL();
 
@@ -82,11 +78,11 @@
     }
 
 
-CMemSpyEngineOutputSinkFile* CMemSpyEngineOutputSinkFile::NewL( CMemSpyEngine& aEngine, const TDesC& aRootFolder )
+CMemSpyEngineOutputSinkFile* CMemSpyEngineOutputSinkFile::NewL( CMemSpyEngine& aEngine )
     {
     CMemSpyEngineOutputSinkFile* self = new(ELeave) CMemSpyEngineOutputSinkFile( aEngine );
     CleanupStack::PushL( self );
-    self->ConstructL( aRootFolder );
+    self->ConstructL();
     CleanupStack::Pop( self );
     return self;
     }
@@ -158,7 +154,7 @@
 
 void CMemSpyEngineOutputSinkFile::DataStreamBeginL( const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseTimeStamp )
     {
-    CMemSpyEngineSinkMetaData* meta = CMemSpyEngineSinkMetaData::NewL( iRoot->Des(), aContext, aFolder, aExtension, aOverwrite, aUseTimeStamp );
+    CMemSpyEngineSinkMetaData* meta = CMemSpyEngineSinkMetaData::NewL( aContext, aFolder, aExtension, aOverwrite, aUseTimeStamp );
     CleanupStack::PushL( meta );
 
     TRACE( RDebug::Printf( "CMemSpyEngineOutputSinkFile::DataStreamBeginL() - START - log count: %d, iFileServerSuspended: %d", iLogs.Count(), iFileServerSuspended ) );
@@ -413,7 +409,7 @@
 
     // Make emtpy meta data
     ASSERT( !iMetaData );
-    iMetaData = CMemSpyEngineSinkMetaData::NewL( iParent.iRoot->Des(), KNullDesC, KNullDesC, KNullDesC, ETrue, ETrue );
+    iMetaData = CMemSpyEngineSinkMetaData::NewL( KNullDesC, KNullDesC, KNullDesC, ETrue, ETrue );
 
     // Prepare common details
     CommonConstructL();
--- a/memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTracker.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTracker.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -129,7 +129,7 @@
     }
 
 
-EXPORT_C void CMemSpyEngineHelperSysMemTracker::CheckForChangesNowL()
+void CMemSpyEngineHelperSysMemTracker::CheckForChangesNowL()
     {
     iImp->CheckForChangesNowL();
     }
--- a/memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTrackerEntryHeap.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTrackerEntryHeap.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -216,8 +216,15 @@
 
 TBool CMemSpyEngineHelperSysMemTrackerEntryHeap::HaveFreeCellsChanged() const
     {
-    TBool changed = ( iCurrent.AsRHeap().Statistics().StatsFree().TypeCount() != iLast.AsRHeap().Statistics().StatsFree().TypeCount() ) ||
-		( iCurrent.AsRHeap().Statistics().StatsFree().TypeSize() != iLast.AsRHeap().Statistics().StatsFree().TypeSize() );
+    TBool changed = 
+        ( iCurrent.AsRHeap().ObjectData().iFree.next != iLast.AsRHeap().ObjectData().iFree.next ) ||
+        ( iCurrent.AsRHeap().ObjectData().iFree.len != iLast.AsRHeap().ObjectData().iFree.len );
+    //
+    if ( !changed )
+        {
+        changed |= ( iCurrent.AsRHeap().Statistics().StatsFree().TypeCount() != iLast.AsRHeap().Statistics().StatsFree().TypeCount() );
+        changed |= ( iCurrent.AsRHeap().Statistics().StatsFree().SlackSpaceCellSize() != iLast.AsRHeap().Statistics().StatsFree().SlackSpaceCellSize() );
+        }
     //
     return changed;
     }
@@ -289,7 +296,7 @@
 
 void CMemSpyEngineHelperSysMemTrackerCycleChangeHeap::OutputHeaderL( CMemSpyEngineOutputSink& aSink, CMemSpyEngineHelperSysMemTrackerCycle& /*aCycle*/ )
     {
-    _LIT( KHeaderHeap, "Type, Thread, Chunk, Handle, Heap Addr, Size, Min, Max, 1st Free Addr, 1st Free Len, Alloc Count, Alloc Space, Free Count, Free Space, Free Slack, F.Largest, A.Largest, Attribs");
+    _LIT( KHeaderHeap, "Type, Thread, Chunk, Handle, Base Addr, Size, Min, Max, 1st Free Addr, 1st Free Len, Alloc Count, Alloc Space, Free Count, Free Space, Free Slack, F.Largest, A.Largest, Attribs");
     aSink.OutputLineL( KHeaderHeap );
     }
 
@@ -308,6 +315,7 @@
     TPtr pBuf(buf->Des());
 
     const TMemSpyHeapMetaDataRHeap& metaData = iCurrent.AsRHeap().MetaData();
+    const TMemSpyHeapObjectDataRHeap& objectData = iCurrent.AsRHeap().ObjectData();
     const TMemSpyHeapStatisticsRHeap& stats = iCurrent.AsRHeap().Statistics();
 
     // Strip any process & thread
@@ -318,12 +326,12 @@
                  iThreadName, 
                  &pChunkName,
                  metaData.ChunkHandle(),
-                 /*objectData.Base(),*/ metaData.iAllocatorAddress,
+                 objectData.Base(),
                  metaData.ChunkSize(),
-                 /*objectData.iMinLength,*/ metaData.iMinHeapSize,
-                 /*objectData.iMaxLength,*/ metaData.iMaxHeapSize,
-                 /*objectData.iFree.next,*/ NULL, //TODO
-                 /*objectData.iFree.len,*/ 0,
+                 objectData.iMinLength,
+                 objectData.iMaxLength,
+                 objectData.iFree.next,
+                 objectData.iFree.len,
                  stats.StatsAllocated().TypeCount(),
                  stats.StatsAllocated().TypeSize(),
                  stats.StatsFree().TypeCount(),
@@ -363,22 +371,18 @@
         {
         // Starts a data Stream
         aCycle.DataStreamBeginL( aSink, *iThreadName );
-        
-        TInt err = KErrNone;
 
         if  ( IsKernel() )
             {
-            TRAP(err, engine.HelperHeap().OutputHeapDataKernelL( KMemSpyEngineSinkDoNotCreateOwnDataStream ));
+            engine.HelperHeap().OutputHeapDataKernelL( KMemSpyEngineSinkDoNotCreateOwnDataStream );
             }
         else if ( thread )
             {
-            TRAP(err, engine.HelperHeap().OutputHeapDataUserL( *thread, KMemSpyEngineSinkDoNotCreateOwnDataStream )); 
+            engine.HelperHeap().OutputHeapDataUserL( *thread, KMemSpyEngineSinkDoNotCreateOwnDataStream ); 
             }
 
         // End the stream (commit the file)
         aCycle.DataStreamEndL( aSink );
-        
-        User::LeaveIfError(err);
         }
     }
 
--- a/memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTrackerEntryManager.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/SysMemTracker/MemSpyEngineHelperSysMemTrackerEntryManager.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -443,13 +443,12 @@
     }
 #endif
 
-// TODO: Uncomment when  bitmap handels are fixed
-//    if ( config.iEnabledCategories & TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryBitmapHandles )
-//        {
-//        RDebug::Print( KMemSpyKeepaliveMessage );
-//        // Bitmap
-//        CreateSeedItemsBitmapL( *chunks );        
-//        }
+    if ( config.iEnabledCategories & TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryBitmapHandles )
+        {
+        RDebug::Print( KMemSpyKeepaliveMessage );
+        // Bitmap
+        CreateSeedItemsBitmapL( *chunks );        
+        }
 
 #ifdef SYSMEMTRACKERLOGGING
     {
@@ -480,13 +479,12 @@
     }
 #endif
 
-//  TODO: Uncomment after fix
-//    if ( config.iEnabledCategories & TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryKernelHeap )
-//        {
-//        RDebug::Print( KMemSpyKeepaliveMessage );
-//        // Look for kernel heaps
-//        CreateSeedItemsHeapKernelL( *chunks );
-//        }
+    if ( config.iEnabledCategories & TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryKernelHeap )
+        {
+        RDebug::Print( KMemSpyKeepaliveMessage );
+        // Look for kernel heaps
+        CreateSeedItemsHeapKernelL( *chunks );
+        }
 
 #ifdef SYSMEMTRACKERLOGGING
     {
@@ -553,13 +551,12 @@
     }
 #endif
 
-//    TODO: Uncomment after fix
-//    if ( config.iEnabledCategories & TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryUserStacks )
-//        {
-//        RDebug::Print( KMemSpyKeepaliveMessage );
-//        // Stacks ($DAT)
-//        CreateSeedItemsStacksL( *chunks );        
-//        }
+    if ( config.iEnabledCategories & TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryUserStacks )
+        {
+        RDebug::Print( KMemSpyKeepaliveMessage );
+        // Stacks ($DAT)
+        CreateSeedItemsStacksL( *chunks );        
+        }
 
 #ifdef SYSMEMTRACKERLOGGING
      {
@@ -572,13 +569,12 @@
     }
 #endif
 
-//  TODO: Uncomment after fix
-//    if ( config.iEnabledCategories & TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryGlobalData )
-//        {
-//        RDebug::Print( KMemSpyKeepaliveMessage );
-//        // Global data (DLL$DATA)
-//        CreateSeedItemsGlobalDataL( *chunks );        
-//        }
+    if ( config.iEnabledCategories & TMemSpyEngineHelperSysMemTrackerConfig::EMemSpyEngineSysMemTrackerCategoryGlobalData )
+        {
+        RDebug::Print( KMemSpyKeepaliveMessage );
+        // Global data (DLL$DATA)
+        CreateSeedItemsGlobalDataL( *chunks );        
+        }
 
  #ifdef SYSMEMTRACKERLOGGING
     {
--- a/memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectContainer.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectContainer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -773,9 +773,9 @@
         for( TInt i=0; i<leftCount; i++ )
             {
             const TMemSpyHeapInfo& info = leftInfos[ i ];
-            if ( info.Type() != TMemSpyHeapInfo::ETypeUnknown )
+            if ( info.Type() == TMemSpyHeapInfo::ETypeRHeap )
                 {
-                leftSize += (TInt) info.AsRHeap().MetaData().iHeapSize;
+                leftSize += (TInt) info.AsRHeap().ObjectData().Size();
                 }
             }
         CleanupStack::PopAndDestroy( &leftInfos );
@@ -789,9 +789,9 @@
         for( TInt i=0; i<rightCount; i++ )
             {
             const TMemSpyHeapInfo& info = rightInfos[ i ];
-            if ( info.Type() == TMemSpyHeapInfo::ETypeUnknown )
+            if ( info.Type() == TMemSpyHeapInfo::ETypeRHeap )
                 {
-                rightSize += (TInt) info.AsRHeap().MetaData().iHeapSize;
+                rightSize += (TInt) info.AsRHeap().ObjectData().Size();
                 }
             }
         CleanupStack::PopAndDestroy( &rightInfos );
--- a/memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectProcess.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectProcess.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -515,25 +515,6 @@
     return iInfo->VID();
     }
 
-EXPORT_C TProcessPriority CMemSpyProcess::Priority() const
-	{
-	return iPriority;
-	}
-
-EXPORT_C TExitCategoryName CMemSpyProcess::ExitCategory() const
-	{
-	return iExitCategory;
-	}
-
-EXPORT_C TInt CMemSpyProcess::ExitReason() const
-	{
-	return iExitReason;
-	}
-
-EXPORT_C TExitType CMemSpyProcess::ExitType() const
-	{
-	return iExitType;
-	}
 
 EXPORT_C TUidType CMemSpyProcess::UIDs() const
     {
--- a/memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectThread.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectThread.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -387,11 +387,6 @@
     return  isDead;
     }
 
-EXPORT_C TThreadPriority CMemSpyThread::Priority() const
-	{
-	return iPriority;
-	}
-
 
 void CMemSpyThread::RefreshL()
     {
--- a/memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectThreadInfoObjects.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/Source/ThreadAndProcess/MemSpyEngineObjectThreadInfoObjects.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -123,17 +123,6 @@
     return TPtrC( item->Combined() );
     }
 
-EXPORT_C TPtrC CMemSpyThreadInfoItemBase::Caption(TInt aIndex ) const
-	{
-	CItem* item = iItems[ aIndex ];
-	return TPtrC( item->Caption() );
-	}
-
-EXPORT_C TPtrC CMemSpyThreadInfoItemBase::Value(TInt aIndex ) const
-	{
-	CItem* item = iItems[ aIndex ];
-	return TPtrC( item->Value() );
-	}
 
 EXPORT_C CMemSpyEngine& CMemSpyThreadInfoItemBase::Engine() const
     {
@@ -1702,18 +1691,20 @@
 #endif
 
     // See if we have an entry with that name...
-    TInt foundIndex = 0;
-    TRAP(ret, foundIndex = FindServerL(aName));
+    TIdentityRelation<CSessionInfoEntry> comparer( CompareEntries );
+    HBufC* name = aName.AllocLC();
+    CSessionInfoEntry* entry = new(ELeave) CSessionInfoEntry( name );
+    CleanupStack::Pop( name );
+    CleanupStack::PushL( entry );
+    const TInt foundIndex = iServerNames.Find( entry, comparer );
+    CleanupStack::PopAndDestroy( entry );
     
-    if (ret == KErrNone)
+    // If we did, get the count
+    if  ( foundIndex >=0 && foundIndex < iServerNames.Count() )
         {
-        // If we did, get the count
-        if  ( foundIndex >=0 && foundIndex < iServerNames.Count() )
-            {
-            ret = iServerNames[ foundIndex ]->iCount;
-            }
+        ret = iServerNames[ foundIndex ]->iCount;
         }
-
+    //
 #ifdef _DEBUG
     RDebug::Printf( "CMemSpyThreadInfoSession::ConnectionCount() - END - ret: %d", ret );
 #endif
@@ -1721,22 +1712,10 @@
     return ret;
     }
 
-TInt CMemSpyThreadInfoSession::FindServerL( const TDesC& aName ) const
-    {
-    TIdentityRelation<CSessionInfoEntry> comparer( CompareEntries );
-    HBufC* name = aName.AllocLC();
-    CSessionInfoEntry* entry = new(ELeave) CSessionInfoEntry( name );
-    CleanupStack::Pop( name ); // don't destroy it as name is now owned by entry 
-    CleanupStack::PushL( entry );
-    const TInt foundIndex = iServerNames.Find( entry, comparer );
-    User::LeaveIfError(foundIndex); // so we only return a real index
-    CleanupStack::PopAndDestroy( entry );
-    return foundIndex;
-    }
 
 void CMemSpyThreadInfoSession::HandleContainerItemL( TMemSpyDriverHandleInfoGeneric& aItem, TInt /*aRefCount*/, TDes& aFullName )
     {
-    // Check whether we have the item already
+    // Check whether we have the item already?
     TIdentityRelation<CSessionInfoEntry> comparer( CompareEntries );
 
     // Prepare object, just in case we don't find it...
--- a/memspy/Engine/eabi/MemSpyEngineu.def	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/eabi/MemSpyEngineu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -536,21 +536,4 @@
 	_ZTI49CMemSpyEngineHelperSysMemTrackerEntryWindowServer @ 535 NONAME ; #<TI>#
 	_ZTV49CMemSpyEngineHelperSysMemTrackerEntryWindowServer @ 536 NONAME ; #<VT>#
 	_ZN13CMemSpyEngine29IsHelperWindowServerSupportedEv @ 537 NONAME
-	_ZN23CMemSpyEngineHelperHeap14NewHeapRawInfoERK15TMemSpyHeapInfo @ 538 NONAME
-	_ZNK36CMemSpyEngineGenericKernelObjectList10ItemsCountEv @ 539 NONAME
-	_ZNK36CMemSpyEngineGenericKernelObjectList4SizeEv @ 540 NONAME
-	_ZNK13CMemSpyThread8PriorityEv @ 541 NONAME
-	_ZN13CMemSpyEngine4NewLER3RFsi @ 542 NONAME
-	_ZNK14CMemSpyProcess10ExitReasonEv @ 543 NONAME
-	_ZNK14CMemSpyProcess12ExitCategoryEv @ 544 NONAME
-	_ZNK14CMemSpyProcess8ExitTypeEv @ 545 NONAME
-	_ZNK14CMemSpyProcess8PriorityEv @ 546 NONAME
-	_ZNK25CMemSpyThreadInfoItemBase5ValueEi @ 547 NONAME
-	_ZNK25CMemSpyThreadInfoItemBase7CaptionEi @ 548 NONAME
-	_ZN13CMemSpyEngine16InstallFileSinkLERK7TDesC16 @ 549 NONAME
-	_ZN13CMemSpyEngine17InstallDebugSinkLEv @ 550 NONAME
-	_ZN25CMemSpyEngineSinkMetaData4NewLERK7TDesC16S2_S2_S2_ii @ 551 NONAME
-	_ZN25CMemSpyEngineSinkMetaData4NewLERK7TDesC16S2_S2_S2_iiRK5TTime @ 552 NONAME
-	_ZN32CMemSpyEngineHelperSysMemTracker19CheckForChangesNowLEv @ 553 NONAME
-	_ZN23CMemSpyEngineHelperHeap16GetHeapInfoUserLERK10TProcessIdRK9TThreadIdR15TMemSpyHeapInfoP6RArrayI21TMemSpyDriverFreeCellEi @ 554 NONAME
 
--- a/memspy/Engine/group/MemSpyEngine.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/Engine/group/MemSpyEngine.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -113,18 +113,15 @@
 
 OS_LAYER_SYSTEMINCLUDE
 
-APP_LAYER_SYSTEMINCLUDE
-
 LIBRARY			euser.lib 
 LIBRARY			MemSpyDriverClient.lib hal.lib estor.lib
 LIBRARY			efsrv.lib bafl.lib fbscli.lib
 LIBRARY			ecom.lib xmlframework.lib charconv.lib
-LIBRARY			apgrfx.lib
-LIBRARY	 		ws32.lib
+
 
 
 #include "MemSpyEngine.config"
 
-//EXPORTUNFROZEN
 
 
+
--- a/memspy/MemSpyClient/bwins/MemSpyClientu.def	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,221 +0,0 @@
-EXPORTS
-	?CpuUse@CMemSpyApiThread@@QBEHXZ @ 1 NONAME ; int CMemSpyApiThread::CpuUse(void) const
-	?Name@CMemSpyApiKernelObjectItem@@QBEABVTDesC8@@XZ @ 2 NONAME ; class TDesC8 const & CMemSpyApiKernelObjectItem::Name(void) const
-	?GetThreadInfoItemsL@RMemSpySession@@QAEXAAV?$RArray@PAVCMemSpyApiThreadInfoItem@@@@VTThreadId@@W4TMemSpyThreadInfoItemType@@@Z @ 3 NONAME ; void RMemSpySession::GetThreadInfoItemsL(class RArray<class CMemSpyApiThreadInfoItem *> &, class TThreadId, enum TMemSpyThreadInfoItemType)
-	?Description@TMemSpyDeviceWideOperationProgress@@QBEABVTDesC16@@XZ @ 4 NONAME ; class TDesC16 const & TMemSpyDeviceWideOperationProgress::Description(void) const
-	?TotalOverhead@CMemSpyApiHeap@@QAEHXZ @ 5 NONAME ; int CMemSpyApiHeap::TotalOverhead(void)
-	?OutputDetailedPhoneInfo@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 6 NONAME ; void RMemSpySession::OutputDetailedPhoneInfo(class TRequestStatus &)
-	?UniqueID@CMemSpyApiKernelObjectItem@@QBEHXZ @ 7 NONAME ; int CMemSpyApiKernelObjectItem::UniqueID(void) const
-	?OutputHeapData@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 8 NONAME ; void RMemSpySession::OutputHeapData(class TRequestStatus &)
-	?GetSwmtCategoriesL@RMemSpySession@@QAEXAAH@Z @ 9 NONAME ; void RMemSpySession::GetSwmtCategoriesL(int &)
-	?SessionType@CMemSpyApiKernelObjectItem@@QBE?AW4TIpcSessionType@@XZ @ 10 NONAME ; enum TIpcSessionType CMemSpyApiKernelObjectItem::SessionType(void) const
-	?VID@CMemSpyApiThread@@QBEHXZ @ 11 NONAME ; int CMemSpyApiThread::VID(void) const
-	?OutputStackInfoL@RMemSpySession@@QAEXVTThreadId@@@Z @ 12 NONAME ; void RMemSpySession::OutputStackInfoL(class TThreadId)
-	?FreeMemory@CMemSpyApiMemoryTrackingCycle@@QBEAB_JXZ @ 13 NONAME ; long long const & CMemSpyApiMemoryTrackingCycle::FreeMemory(void) const
-	?ProcessNumberUsing@CMemSpyApiThread@@QBEHXZ @ 14 NONAME ; int CMemSpyApiThread::ProcessNumberUsing(void) const
-	?PreviousCycleDiff@CMemSpyApiMemoryTrackingCycle@@QBE_JXZ @ 15 NONAME ; long long CMemSpyApiMemoryTrackingCycle::PreviousCycleDiff(void) const
-	?OutputStackDataL@RMemSpySession@@QAEXVTThreadId@@W4TMemSpyDriverDomainType@@@Z @ 16 NONAME ; void RMemSpySession::OutputStackDataL(class TThreadId, enum TMemSpyDriverDomainType)
-	?OutputThreadHeapDataL@RMemSpySession@@QAEXVTThreadId@@@Z @ 17 NONAME ; void RMemSpySession::OutputThreadHeapDataL(class TThreadId)
-	?ExitType@CMemSpyApiProcess@@QBE?AW4TExitType@@XZ @ 18 NONAME ; enum TExitType CMemSpyApiProcess::ExitType(void) const
-	?SwitchOutputToFileL@RMemSpySession@@QAEXABVTDesC16@@@Z @ 19 NONAME ; void RMemSpySession::SwitchOutputToFileL(class TDesC16 const &)
-	?OutputHeapCellListing@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 20 NONAME ; void RMemSpySession::OutputHeapCellListing(class TRequestStatus &)
-	?SetThreadPriorityL@RMemSpySession@@QAEXVTThreadId@@H@Z @ 21 NONAME ; void RMemSpySession::SetThreadPriorityL(class TThreadId, int)
-	?Restrictions@CMemSpyApiKernelObjectItem@@QBEIXZ @ 22 NONAME ; unsigned int CMemSpyApiKernelObjectItem::Restrictions(void) const
-	?Id@CMemSpyApiKernelObjectItem@@QBEHXZ @ 23 NONAME ; int CMemSpyApiKernelObjectItem::Id(void) const
-	?Count@CMemSpyApiKernelObjectItem@@QBEHXZ @ 24 NONAME ; int CMemSpyApiKernelObjectItem::Count(void) const
-	?ControllingOwner@CMemSpyApiKernelObjectItem@@QBEIXZ @ 25 NONAME ; unsigned int CMemSpyApiKernelObjectItem::ControllingOwner(void) const
-	?SwmtResetTracking@RMemSpySession@@QAEXXZ @ 26 NONAME ; void RMemSpySession::SwmtResetTracking(void)
-	?Version@CMemSpyApiKernelObjectItem@@QBE?AVTVersion@@XZ @ 27 NONAME ; class TVersion CMemSpyApiKernelObjectItem::Version(void) const
-	?SwitchToProcess@RMemSpySession@@QAEHVTProcessId@@H@Z @ 28 NONAME ; int RMemSpySession::SwitchToProcess(class TProcessId, int)
-	?MaxSize@CMemSpyApiKernelObjectItem@@QBEHXZ @ 29 NONAME ; int CMemSpyApiKernelObjectItem::MaxSize(void) const
-	?IsSwmtRunningL@RMemSpySession@@QAEHXZ @ 30 NONAME ; int RMemSpySession::IsSwmtRunningL(void)
-	?AddressOfOwningProcess@CMemSpyApiKernelObjectItem@@QAEPAEXZ @ 31 NONAME ; unsigned char * CMemSpyApiKernelObjectItem::AddressOfOwningProcess(void)
-	?ExitReason@CMemSpyApiProcess@@QBEHXZ @ 32 NONAME ; int CMemSpyApiProcess::ExitReason(void) const
-	?MsgCount@CMemSpyApiKernelObjectItem@@QBEHXZ @ 33 NONAME ; int CMemSpyApiKernelObjectItem::MsgCount(void) const
-	?AllocationsCount@CMemSpyApiHeap@@QAEHXZ @ 34 NONAME ; int CMemSpyApiHeap::AllocationsCount(void)
-	?WaitCount@CMemSpyApiKernelObjectItem@@QBEHXZ @ 35 NONAME ; int CMemSpyApiKernelObjectItem::WaitCount(void) const
-	?SID@CMemSpyApiProcess@@QBEKXZ @ 36 NONAME ; unsigned long CMemSpyApiProcess::SID(void) const
-	?GetKernelObjectsL@RMemSpySession@@QAEXAAV?$RArray@PAVCMemSpyApiKernelObject@@@@@Z @ 37 NONAME ; void RMemSpySession::GetKernelObjectsL(class RArray<class CMemSpyApiKernelObject *> &)
-	?CycleNumber@CMemSpyApiMemoryTrackingCycle@@QBEHXZ @ 38 NONAME ; int CMemSpyApiMemoryTrackingCycle::CycleNumber(void) const
-	?Size@CMemSpyApiKernelObject@@QBE_JXZ @ 39 NONAME ; long long CMemSpyApiKernelObject::Size(void) const
-	?SetSwmtCategoriesL@RMemSpySession@@QAEXH@Z @ 40 NONAME ; void RMemSpySession::SetSwmtCategoriesL(int)
-	?CancelDeviceWideOperationL@RMemSpySession@@QAEXXZ @ 41 NONAME ; void RMemSpySession::CancelDeviceWideOperationL(void)
-	?TotalAllocations@CMemSpyApiHeap@@QAEHXZ @ 42 NONAME ; int CMemSpyApiHeap::TotalAllocations(void)
-	?Name@CMemSpyApiProcess@@QBEABVTDesC16@@XZ @ 43 NONAME ; class TDesC16 const & CMemSpyApiProcess::Name(void) const
-	?DumpKernelHeap@RMemSpySession@@QAEXXZ @ 44 NONAME ; void RMemSpySession::DumpKernelHeap(void)
-	?GetKernelObjects@RMemSpySession@@QAEHAAV?$RArray@PAVCMemSpyApiKernelObject@@@@@Z @ 45 NONAME ; int RMemSpySession::GetKernelObjects(class RArray<class CMemSpyApiKernelObject *> &)
-	?Priority@CMemSpyApiProcess@@QBE?AW4TProcessPriority@@XZ @ 46 NONAME ; enum TProcessPriority CMemSpyApiProcess::Priority(void) const
-	?HeaderSizeF@CMemSpyApiHeap@@QAEHXZ @ 47 NONAME ; int CMemSpyApiHeap::HeaderSizeF(void)
-	?OutputCompactStackInfoL@RMemSpySession@@QAEXXZ @ 48 NONAME ; void RMemSpySession::OutputCompactStackInfoL(void)
-	?MsgLimit@CMemSpyApiKernelObjectItem@@QBEHXZ @ 49 NONAME ; int CMemSpyApiKernelObjectItem::MsgLimit(void) const
-	?AddressOfDataBssStackChunk@CMemSpyApiKernelObjectItem@@QAEPAEXZ @ 50 NONAME ; unsigned char * CMemSpyApiKernelObjectItem::AddressOfDataBssStackChunk(void)
-	?Top@CMemSpyApiKernelObjectItem@@QBEHXZ @ 51 NONAME ; int CMemSpyApiKernelObjectItem::Top(void) const
-	?Resetting@CMemSpyApiKernelObjectItem@@QBEEXZ @ 52 NONAME ; unsigned char CMemSpyApiKernelObjectItem::Resetting(void) const
-	?GetProcessIdByThreadId@RMemSpySession@@QAEXAAVTProcessId@@VTThreadId@@@Z @ 53 NONAME ; void RMemSpySession::GetProcessIdByThreadId(class TProcessId &, class TThreadId)
-	?HeaderSizeA@CMemSpyApiHeap@@QAEHXZ @ 54 NONAME ; int CMemSpyApiHeap::HeaderSizeA(void)
-	?OutputHeapData@RMemSpySession@@QAEXXZ @ 55 NONAME ; void RMemSpySession::OutputHeapData(void)
-	?TotalAccessCount@CMemSpyApiKernelObjectItem@@QBEGXZ @ 56 NONAME ; unsigned short CMemSpyApiKernelObjectItem::TotalAccessCount(void) const
-	?Changes@CMemSpyApiKernelObjectItem@@QBEIXZ @ 57 NONAME ; unsigned int CMemSpyApiKernelObjectItem::Changes(void) const
-	??0RMemSpySession@@QAE@XZ @ 58 NONAME ; RMemSpySession::RMemSpySession(void)
-	?OutputUserStackData@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 59 NONAME ; void RMemSpySession::OutputUserStackData(class TRequestStatus &)
-	?AddressOfServer@CMemSpyApiKernelObjectItem@@QAEPAEXZ @ 60 NONAME ; unsigned char * CMemSpyApiKernelObjectItem::AddressOfServer(void)
-	?Size@CMemSpyApiHeap@@QAEHXZ @ 61 NONAME ; int CMemSpyApiHeap::Size(void)
-	?GetServersL@RMemSpySession@@QAEXAAV?$RArray@PAVCMemSpyApiServer@@@@@Z @ 62 NONAME ; void RMemSpySession::GetServersL(class RArray<class CMemSpyApiServer *> &)
-	??1CMemSpyApiKernelObject@@QAE@XZ @ 63 NONAME ; CMemSpyApiKernelObject::~CMemSpyApiKernelObject(void)
-	?GetInfoItemType@RMemSpySession@@QAEHHVTThreadId@@AAW4TMemSpyThreadInfoItemType@@@Z @ 64 NONAME ; int RMemSpySession::GetInfoItemType(int, class TThreadId, enum TMemSpyThreadInfoItemType &)
-	??1CMemSpyApiHeap@@QAE@XZ @ 65 NONAME ; CMemSpyApiHeap::~CMemSpyApiHeap(void)
-	?SetSwmtHeapDumpsEnabledL@RMemSpySession@@QAEXH@Z @ 66 NONAME ; void RMemSpySession::SetSwmtHeapDumpsEnabledL(int)
-	?SetSwmtFilter@RMemSpySession@@QAEXABVTDesC16@@@Z @ 67 NONAME ; void RMemSpySession::SetSwmtFilter(class TDesC16 const &)
-	?Size@CMemSpyApiKernelObjectItem@@QBEKXZ @ 68 NONAME ; unsigned long CMemSpyApiKernelObjectItem::Size(void) const
-	?OutputThreadInfoHandlesL@RMemSpySession@@QAEXVTThreadId@@@Z @ 69 NONAME ; void RMemSpySession::OutputThreadInfoHandlesL(class TThreadId)
-	?OutputThreadHeapDataL@RMemSpySession@@QAEXABVTDesC16@@@Z @ 70 NONAME ; void RMemSpySession::OutputThreadHeapDataL(class TDesC16 const &)
-	?Type@CMemSpyApiKernelObject@@QBE?AW4TMemSpyDriverContainerType@@XZ @ 71 NONAME ; enum TMemSpyDriverContainerType CMemSpyApiKernelObject::Type(void) const
-	?Name@CMemSpyApiKernelObject@@QBEABVTDesC16@@XZ @ 72 NONAME ; class TDesC16 const & CMemSpyApiKernelObject::Name(void) const
-	?Fragmentation@CMemSpyApiHeap@@QAEHXZ @ 73 NONAME ; int CMemSpyApiHeap::Fragmentation(void)
-	?TimerType@CMemSpyApiKernelObjectItem@@QBE?AW4TMemSpyDriverTimerType@@XZ @ 74 NONAME ; enum TMemSpyDriverTimerType CMemSpyApiKernelObjectItem::TimerType(void) const
-	?Value@CMemSpyApiThreadInfoItem@@QBEABVTDesC16@@XZ @ 75 NONAME ; class TDesC16 const & CMemSpyApiThreadInfoItem::Value(void) const
-	?SecurityZone@CMemSpyApiKernelObjectItem@@QBEIXZ @ 76 NONAME ; unsigned int CMemSpyApiKernelObjectItem::SecurityZone(void) const
-	?CreatorId@CMemSpyApiKernelObjectItem@@QBEIXZ @ 77 NONAME ; unsigned int CMemSpyApiKernelObjectItem::CreatorId(void) const
-	?Order@CMemSpyApiKernelObjectItem@@QBEEXZ @ 78 NONAME ; unsigned char CMemSpyApiKernelObjectItem::Order(void) const
-	?NameDetail@CMemSpyApiKernelObjectItem@@QBEABVTDesC8@@XZ @ 79 NONAME ; class TDesC8 const & CMemSpyApiKernelObjectItem::NameDetail(void) const
-	?OutputStackInfo@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 80 NONAME ; void RMemSpySession::OutputStackInfo(class TRequestStatus &)
-	?Handle@CMemSpyApiKernelObjectItem@@QBEPAXXZ @ 81 NONAME ; void * CMemSpyApiKernelObjectItem::Handle(void) const
-	?GetProcessesL@RMemSpySession@@QAEXAAV?$RArray@PAVCMemSpyApiProcess@@@@W4TSortType@@@Z @ 82 NONAME ; void RMemSpySession::GetProcessesL(class RArray<class CMemSpyApiProcess *> &, enum TSortType)
-	?ParseMask@CMemSpyApiKernelObjectItem@@QBEIXZ @ 83 NONAME ; unsigned int CMemSpyApiKernelObjectItem::ParseMask(void) const
-	?Attributes@CMemSpyApiKernelObjectItem@@QBEHXZ @ 84 NONAME ; int CMemSpyApiKernelObjectItem::Attributes(void) const
-	?MemoryDelta@CMemSpyApiMemoryTrackingCycle@@QBE_JXZ @ 85 NONAME ; long long CMemSpyApiMemoryTrackingCycle::MemoryDelta(void) const
-	?GetSwmtFilter@RMemSpySession@@QAEXAAV?$TBuf@$0IA@@@@Z @ 86 NONAME ; void RMemSpySession::GetSwmtFilter(class TBuf<128> &)
-	?Caption@CMemSpyApiThreadInfoItem@@QBEABVTDesC16@@XZ @ 87 NONAME ; class TDesC16 const & CMemSpyApiThreadInfoItem::Caption(void) const
-	?DebugAllocatorLibrary@CMemSpyApiHeap@@QAEHXZ @ 88 NONAME ; int CMemSpyApiHeap::DebugAllocatorLibrary(void)
-	?Overhead@CMemSpyApiHeap@@QAEHXZ @ 89 NONAME ; int CMemSpyApiHeap::Overhead(void)
-	?ForceSwmtUpdate@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 90 NONAME ; void RMemSpySession::ForceSwmtUpdate(class TRequestStatus &)
-	?GetHeapL@RMemSpySession@@QAEPAVCMemSpyApiHeap@@XZ @ 91 NONAME ; class CMemSpyApiHeap * RMemSpySession::GetHeapL(void)
-	?ServerListOutputGenericL@RMemSpySession@@QAEXH@Z @ 92 NONAME ; void RMemSpySession::ServerListOutputGenericL(int)
-	?OutputKernelStackData@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 93 NONAME ; void RMemSpySession::OutputKernelStackData(class TRequestStatus &)
-	?GetSwmtTimerIntervalL@RMemSpySession@@QAEXAAH@Z @ 94 NONAME ; void RMemSpySession::GetSwmtTimerIntervalL(int &)
-	?GetSwmtHeapDumpsEnabledL@RMemSpySession@@QAEXAAH@Z @ 95 NONAME ; void RMemSpySession::GetSwmtHeapDumpsEnabledL(int &)
-	?AddressOfOwningThread@CMemSpyApiKernelObjectItem@@QAEPAEXZ @ 96 NONAME ; unsigned char * CMemSpyApiKernelObjectItem::AddressOfOwningThread(void)
-	?ThreadPriority@CMemSpyApiThread@@QBE?AW4TThreadPriority@@XZ @ 97 NONAME ; enum TThreadPriority CMemSpyApiThread::ThreadPriority(void) const
-	?GetHeap@RMemSpySession@@QAEPAVCMemSpyApiHeap@@XZ @ 98 NONAME ; class CMemSpyApiHeap * RMemSpySession::GetHeap(void)
-	??1CMemSpyApiMemoryTrackingCycle@@QAE@XZ @ 99 NONAME ; CMemSpyApiMemoryTrackingCycle::~CMemSpyApiMemoryTrackingCycle(void)
-	?AccessCount@CMemSpyApiKernelObjectItem@@QBEHXZ @ 100 NONAME ; int CMemSpyApiKernelObjectItem::AccessCount(void) const
-	?ChangeCount@CMemSpyApiMemoryTrackingCycle@@QBEHXZ @ 101 NONAME ; int CMemSpyApiMemoryTrackingCycle::ChangeCount(void) const
-	?OutputHeapInfo@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 102 NONAME ; void RMemSpySession::OutputHeapInfo(class TRequestStatus &)
-	?Time@CMemSpyApiMemoryTrackingCycle@@QBEABVTTime@@XZ @ 103 NONAME ; class TTime const & CMemSpyApiMemoryTrackingCycle::Time(void) const
-	?SetSwmtTimerIntervalL@RMemSpySession@@QAEXH@Z @ 104 NONAME ; void RMemSpySession::SetSwmtTimerIntervalL(int)
-	?MaxLength@CMemSpyApiHeap@@QAEHXZ @ 105 NONAME ; int CMemSpyApiHeap::MaxLength(void)
-	?OutputKernelHeapData@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 106 NONAME ; void RMemSpySession::OutputKernelHeapData(class TRequestStatus &)
-	?AddressOfKernelOwner@CMemSpyApiKernelObjectItem@@QAEPAEXZ @ 107 NONAME ; unsigned char * CMemSpyApiKernelObjectItem::AddressOfKernelOwner(void)
-	??1CMemSpyApiThreadInfoItem@@QAE@XZ @ 108 NONAME ; CMemSpyApiThreadInfoItem::~CMemSpyApiThreadInfoItem(void)
-	?FreeCount@CMemSpyApiHeap@@QAEHXZ @ 109 NONAME ; int CMemSpyApiHeap::FreeCount(void)
-	?TotalFree@CMemSpyApiHeap@@QAEHXZ @ 110 NONAME ; int CMemSpyApiHeap::TotalFree(void)
-	?SwitchToThread@RMemSpySession@@QAEHVTThreadId@@H@Z @ 111 NONAME ; int RMemSpySession::SwitchToThread(class TThreadId, int)
-	?GetServersL@RMemSpySession@@QAEXAAV?$RArray@PAVCMemSpyApiServer@@@@W4TSortType@@@Z @ 112 NONAME ; void RMemSpySession::GetServersL(class RArray<class CMemSpyApiServer *> &, enum TSortType)
-	?FreeOverhead@CMemSpyApiHeap@@QAEHXZ @ 113 NONAME ; int CMemSpyApiHeap::FreeOverhead(void)
-	?SwitchOutputToTraceL@RMemSpySession@@QAEXXZ @ 114 NONAME ; void RMemSpySession::SwitchOutputToTraceL(void)
-	?SlackFreeSpace@CMemSpyApiHeap@@QAEHXZ @ 115 NONAME ; int CMemSpyApiHeap::SlackFreeSpace(void)
-	?Priority@CMemSpyApiKernelObjectItem@@QBEHXZ @ 116 NONAME ; int CMemSpyApiKernelObjectItem::Priority(void) const
-	?ForceSwmtUpdateL@RMemSpySession@@QAEXXZ @ 117 NONAME ; void RMemSpySession::ForceSwmtUpdateL(void)
-	?ThreadCount@CMemSpyApiProcess@@QBEHXZ @ 118 NONAME ; int CMemSpyApiProcess::ThreadCount(void) const
-	?RequestCount@CMemSpyApiThread@@QBEHXZ @ 119 NONAME ; int CMemSpyApiThread::RequestCount(void) const
-	?Caption@CMemSpyApiMemoryTrackingCycle@@QBEABVTDesC16@@XZ @ 120 NONAME ; class TDesC16 const & CMemSpyApiMemoryTrackingCycle::Caption(void) const
-	?StopSwmtTimerL@RMemSpySession@@QAEXXZ @ 121 NONAME ; void RMemSpySession::StopSwmtTimerL(void)
-	??1CMemSpyApiProcess@@QAE@XZ @ 122 NONAME ; CMemSpyApiProcess::~CMemSpyApiProcess(void)
-	?MinLength@CMemSpyApiHeap@@QAEHXZ @ 123 NONAME ; int CMemSpyApiHeap::MinLength(void)
-	?ExitCategory@CMemSpyApiProcess@@QBE?AV?$TBuf@$0BA@@@XZ @ 124 NONAME ; class TBuf<16> CMemSpyApiProcess::ExitCategory(void) const
-	?Progress@TMemSpyDeviceWideOperationProgress@@QBEHXZ @ 125 NONAME ; int TMemSpyDeviceWideOperationProgress::Progress(void) const
-	?Count@CMemSpyApiKernelObject@@QBEHXZ @ 126 NONAME ; int CMemSpyApiKernelObject::Count(void) const
-	?IsDead@CMemSpyApiProcess@@QBEHXZ @ 127 NONAME ; int CMemSpyApiProcess::IsDead(void) const
-	?EndThreadL@RMemSpySession@@QAEHVTThreadId@@W4TMemSpyEndType@@@Z @ 128 NONAME ; int RMemSpySession::EndThreadL(class TThreadId, enum TMemSpyEndType)
-	?StartPos@CMemSpyApiKernelObjectItem@@QBEHXZ @ 129 NONAME ; int CMemSpyApiKernelObjectItem::StartPos(void) const
-	?TimerState@CMemSpyApiKernelObjectItem@@QBE?AW4TMemSpyDriverTimerState@@XZ @ 130 NONAME ; enum TMemSpyDriverTimerState CMemSpyApiKernelObjectItem::TimerState(void) const
-	?BaseAddress@CMemSpyApiHeap@@QAEHXZ @ 131 NONAME ; int CMemSpyApiHeap::BaseAddress(void)
-	?ExitType@CMemSpyApiThread@@QBE?AW4TExitType@@XZ @ 132 NONAME ; enum TExitType CMemSpyApiThread::ExitType(void) const
-	?StartSwmtTimerL@RMemSpySession@@QAEXH@Z @ 133 NONAME ; void RMemSpySession::StartSwmtTimerL(int)
-	?Type@CMemSpyApiHeap@@QAEAAVTDesC16@@XZ @ 134 NONAME ; class TDesC16 & CMemSpyApiHeap::Type(void)
-	?GetOutputSink@RMemSpySession@@QAEXAAW4TMemSpySinkType@@@Z @ 135 NONAME ; void RMemSpySession::GetOutputSink(enum TMemSpySinkType &)
-	?Id@CMemSpyApiProcess@@QBE?AVTProcessId@@XZ @ 136 NONAME ; class TProcessId CMemSpyApiProcess::Id(void) const
-	?BiggestAllocation@CMemSpyApiHeap@@QAEHXZ @ 137 NONAME ; int CMemSpyApiHeap::BiggestAllocation(void)
-	??1CMemSpyApiKernelObjectItem@@QAE@XZ @ 138 NONAME ; CMemSpyApiKernelObjectItem::~CMemSpyApiKernelObjectItem(void)
-	?AllocationOverhead@CMemSpyApiHeap@@QAEHXZ @ 139 NONAME ; int CMemSpyApiHeap::AllocationOverhead(void)
-	?NameOfOwner@CMemSpyApiKernelObjectItem@@QBEABVTDesC8@@XZ @ 140 NONAME ; class TDesC8 const & CMemSpyApiKernelObjectItem::NameOfOwner(void) const
-	?OutputAllContainerContents@RMemSpySession@@QAEXXZ @ 141 NONAME ; void RMemSpySession::OutputAllContainerContents(void)
-	?OutputKernelObjectsL@RMemSpySession@@QAEXXZ @ 142 NONAME ; void RMemSpySession::OutputKernelObjectsL(void)
-	?ThreadSystemPermanentOrCritical@RMemSpySession@@QAEHVTThreadId@@H@Z @ 143 NONAME ; int RMemSpySession::ThreadSystemPermanentOrCritical(class TThreadId, int)
-	?Protection@CMemSpyApiKernelObjectItem@@QBEIXZ @ 144 NONAME ; unsigned int CMemSpyApiKernelObjectItem::Protection(void) const
-	?BiggestFree@CMemSpyApiHeap@@QAEHXZ @ 145 NONAME ; int CMemSpyApiHeap::BiggestFree(void)
-	?Attributes@CMemSpyApiThread@@QBEHXZ @ 146 NONAME ; int CMemSpyApiThread::Attributes(void) const
-	?GetSwmtCyclesCount@RMemSpySession@@QAEHXZ @ 147 NONAME ; int RMemSpySession::GetSwmtCyclesCount(void)
-	?Bottom@CMemSpyApiKernelObjectItem@@QBEHXZ @ 148 NONAME ; int CMemSpyApiKernelObjectItem::Bottom(void) const
-	?StartSwmtTimerL@RMemSpySession@@QAEXXZ @ 149 NONAME ; void RMemSpySession::StartSwmtTimerL(void)
-	?EndProcessL@RMemSpySession@@QAEHVTProcessId@@W4TMemSpyEndType@@@Z @ 150 NONAME ; int RMemSpySession::EndProcessL(class TProcessId, enum TMemSpyEndType)
-	?GetKernelObjectItemsL@RMemSpySession@@QAEXAAV?$RArray@PAVCMemSpyApiKernelObjectItem@@@@W4TMemSpyDriverContainerType@@@Z @ 151 NONAME ; void RMemSpySession::GetKernelObjectItemsL(class RArray<class CMemSpyApiKernelObjectItem *> &, enum TMemSpyDriverContainerType)
-	?NotifyDeviceWideOperationProgress@RMemSpySession@@QAEXAAVTMemSpyDeviceWideOperationProgress@@AAVTRequestStatus@@@Z @ 152 NONAME ; void RMemSpySession::NotifyDeviceWideOperationProgress(class TMemSpyDeviceWideOperationProgress &, class TRequestStatus &)
-	?OutputCompactHeapInfo@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 153 NONAME ; void RMemSpySession::OutputCompactHeapInfo(class TRequestStatus &)
-	?OutputPhoneInfo@RMemSpySession@@QAEXXZ @ 154 NONAME ; void RMemSpySession::OutputPhoneInfo(void)
-	?ThreadHandles@CMemSpyApiThread@@QBEHXZ @ 155 NONAME ; int CMemSpyApiThread::ThreadHandles(void) const
-	?SvrSessionType@CMemSpyApiKernelObjectItem@@QBEEXZ @ 156 NONAME ; unsigned char CMemSpyApiKernelObjectItem::SvrSessionType(void) const
-	?SwitchOutputSinkL@RMemSpySession@@QAEXW4TMemSpySinkType@@@Z @ 157 NONAME ; void RMemSpySession::SwitchOutputSinkL(enum TMemSpySinkType)
-	?ChunkType@CMemSpyApiKernelObjectItem@@QBEIXZ @ 158 NONAME ; unsigned int CMemSpyApiKernelObjectItem::ChunkType(void) const
-	?GetSwmtMode@RMemSpySession@@QAEXAAW4TMemSpyEngineSysMemTrackerMode@TMemSpyEngineHelperSysMemTrackerConfig@@@Z @ 159 NONAME ; void RMemSpySession::GetSwmtMode(enum TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode &)
-	?Id@CMemSpyApiThread@@QBE?AVTThreadId@@XZ @ 160 NONAME ; class TThreadId CMemSpyApiThread::Id(void) const
-	?OutputPhoneInfo@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 161 NONAME ; void RMemSpySession::OutputPhoneInfo(class TRequestStatus &)
-	?GetProcessIdByNameL@RMemSpySession@@QAE?AVTProcessId@@ABVTDesC16@@@Z @ 162 NONAME ; class TProcessId RMemSpySession::GetProcessIdByNameL(class TDesC16 const &)
-	?GetMemoryTrackingCyclesL@RMemSpySession@@QAEXAAV?$RArray@PAVCMemSpyApiMemoryTrackingCycle@@@@@Z @ 163 NONAME ; void RMemSpySession::GetMemoryTrackingCyclesL(class RArray<class CMemSpyApiMemoryTrackingCycle *> &)
-	?MapAttr@CMemSpyApiKernelObjectItem@@QBEIXZ @ 164 NONAME ; unsigned int CMemSpyApiKernelObjectItem::MapAttr(void) const
-	?OutputCompactStackInfo@RMemSpySession@@QAEXAAVTRequestStatus@@@Z @ 165 NONAME ; void RMemSpySession::OutputCompactStackInfo(class TRequestStatus &)
-	?VID@CMemSpyApiProcess@@QBEKXZ @ 166 NONAME ; unsigned long CMemSpyApiProcess::VID(void) const
-	?AddressOfCodeSeg@CMemSpyApiKernelObjectItem@@QAEPAEXZ @ 167 NONAME ; unsigned char * CMemSpyApiKernelObjectItem::AddressOfCodeSeg(void)
-	?GetThreadsL@RMemSpySession@@QAEXVTProcessId@@AAV?$RArray@PAVCMemSpyApiThread@@@@W4TSortType@@@Z @ 168 NONAME ; void RMemSpySession::GetThreadsL(class TProcessId, class RArray<class CMemSpyApiThread *> &, enum TSortType)
-	?ProcessId@CMemSpyApiThread@@QBE?AVTProcessId@@XZ @ 169 NONAME ; class TProcessId CMemSpyApiThread::ProcessId(void) const
-	?Type@CMemSpyApiKernelObjectItem@@QBE?AW4TMemSpyDriverContainerType@@XZ @ 170 NONAME ; enum TMemSpyDriverContainerType CMemSpyApiKernelObjectItem::Type(void) const
-	?ChunkSize@CMemSpyApiHeap@@QAEHXZ @ 171 NONAME ; int CMemSpyApiHeap::ChunkSize(void)
-	?UnitsMask@CMemSpyApiKernelObjectItem@@QBEIXZ @ 172 NONAME ; unsigned int CMemSpyApiKernelObjectItem::UnitsMask(void) const
-	?Name@CMemSpyApiServer@@QBEABVTDesC16@@XZ @ 173 NONAME ; class TDesC16 const & CMemSpyApiServer::Name(void) const
-	?State@CMemSpyApiKernelObjectItem@@QBEEXZ @ 174 NONAME ; unsigned char CMemSpyApiKernelObjectItem::State(void) const
-	?Shared@CMemSpyApiHeap@@QAEHXZ @ 175 NONAME ; int CMemSpyApiHeap::Shared(void)
-	?SetSwmtAutoStartProcessList@RMemSpySession@@QAEXPAV?$CArrayFixFlat@VTUid@@@@@Z @ 176 NONAME ; void RMemSpySession::SetSwmtAutoStartProcessList(class CArrayFixFlat<class TUid> *)
-	?OutputCompactHeapInfoL@RMemSpySession@@QAEXXZ @ 177 NONAME ; void RMemSpySession::OutputCompactHeapInfoL(void)
-	?ProcessSystemPermanentOrCritical@RMemSpySession@@QAEHVTProcessId@@H@Z @ 178 NONAME ; int RMemSpySession::ProcessSystemPermanentOrCritical(class TProcessId, int)
-	??1CMemSpyApiServer@@QAE@XZ @ 179 NONAME ; CMemSpyApiServer::~CMemSpyApiServer(void)
-	?SetSwmtMode@RMemSpySession@@QAEXW4TMemSpyEngineSysMemTrackerMode@TMemSpyEngineHelperSysMemTrackerConfig@@@Z @ 180 NONAME ; void RMemSpySession::SetSwmtMode(enum TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode)
-	?OutputKernelHeapDataL@RMemSpySession@@QAEXXZ @ 181 NONAME ; void RMemSpySession::OutputKernelHeapDataL(void)
-	?Id@CMemSpyApiServer@@QBE?AVTProcessId@@XZ @ 182 NONAME ; class TProcessId CMemSpyApiServer::Id(void) const
-	?MapCount@CMemSpyApiKernelObjectItem@@QBEHXZ @ 183 NONAME ; int CMemSpyApiKernelObjectItem::MapCount(void) const
-	?OpenChannels@CMemSpyApiKernelObjectItem@@QAEHXZ @ 184 NONAME ; int CMemSpyApiKernelObjectItem::OpenChannels(void)
-	?ProcessPriority@CMemSpyApiThread@@QBE?AW4TProcessPriority@@XZ @ 185 NONAME ; enum TProcessPriority CMemSpyApiThread::ProcessPriority(void) const
-	?OutputAOListL@RMemSpySession@@QAEXVTThreadId@@W4TMemSpyThreadInfoItemType@@@Z @ 186 NONAME ; void RMemSpySession::OutputAOListL(class TThreadId, enum TMemSpyThreadInfoItemType)
-	?ThreadNumberUsing@CMemSpyApiThread@@QBEHXZ @ 187 NONAME ; int CMemSpyApiThread::ThreadNumberUsing(void) const
-	?OutputHeapInfoUserL@RMemSpySession@@QAEXVTThreadId@@@Z @ 188 NONAME ; void RMemSpySession::OutputHeapInfoUserL(class TThreadId)
-	?OutputThreadCellListL@RMemSpySession@@QAEXVTThreadId@@@Z @ 189 NONAME ; void RMemSpySession::OutputThreadCellListL(class TThreadId)
-	?SessionCount@CMemSpyApiServer@@QBEHXZ @ 190 NONAME ; int CMemSpyApiServer::SessionCount(void) const
-	??1CMemSpyApiThread@@QAE@XZ @ 191 NONAME ; CMemSpyApiThread::~CMemSpyApiThread(void)
-	?Connect@RMemSpySession@@QAEHXZ @ 192 NONAME ; int RMemSpySession::Connect(void)
-	?GetThreadInfoItems@RMemSpySession@@QAEHAAV?$RArray@PAVCMemSpyApiThreadInfoItem@@@@VTThreadId@@W4TMemSpyThreadInfoItemType@@@Z @ 193 NONAME ; int RMemSpySession::GetThreadInfoItems(class RArray<class CMemSpyApiThreadInfoItem *> &, class TThreadId, enum TMemSpyThreadInfoItemType)
-	?SID@CMemSpyApiThread@@QBEHXZ @ 194 NONAME ; int CMemSpyApiThread::SID(void) const
-	?GetKernelObjectItems@RMemSpySession@@QAEHAAV?$RArray@PAVCMemSpyApiKernelObjectItem@@@@W4TMemSpyDriverContainerType@@@Z @ 195 NONAME ; int RMemSpySession::GetKernelObjectItems(class RArray<class CMemSpyApiKernelObjectItem *> &, enum TMemSpyDriverContainerType)
-	?ProcessHandles@CMemSpyApiThread@@QBEHXZ @ 196 NONAME ; int CMemSpyApiThread::ProcessHandles(void) const
-	?Name@CMemSpyApiThread@@QBEABVTDesC16@@XZ @ 197 NONAME ; class TDesC16 const & CMemSpyApiThread::Name(void) const
-	?Id@CMemSpyApiEComCategory@@QBE?AVTUid@@XZ @ 198 NONAME ; class TUid CMemSpyApiEComCategory::Id(void) const
-	??1CMemSpyApiEComCategory@@UAE@XZ @ 199 NONAME ; CMemSpyApiEComCategory::~CMemSpyApiEComCategory(void)
-	?ImplementationUid@CMemSpyApiEComImplementation@@QBE?AVTUid@@XZ @ 200 NONAME ; class TUid CMemSpyApiEComImplementation::ImplementationUid(void) const
-	?DataType@CMemSpyApiEComImplementation@@QBEABVTDesC16@@XZ @ 201 NONAME ; class TDesC16 const & CMemSpyApiEComImplementation::DataType(void) const
-	?OpaqueData@CMemSpyApiEComImplementation@@QBEABVTDesC16@@XZ @ 202 NONAME ; class TDesC16 const & CMemSpyApiEComImplementation::OpaqueData(void) const
-	?GetEComCategoriesL@RMemSpySession@@QAEXAAV?$RArray@PAVCMemSpyApiEComCategory@@@@@Z @ 203 NONAME ; void RMemSpySession::GetEComCategoriesL(class RArray<class CMemSpyApiEComCategory *> &)
-	?Name@CMemSpyApiEComImplementation@@QBEABVTDesC16@@XZ @ 204 NONAME ; class TDesC16 const & CMemSpyApiEComImplementation::Name(void) const
-	?Drive@CMemSpyApiEComImplementation@@QBE?AVTDriveUnit@@XZ @ 205 NONAME ; class TDriveUnit CMemSpyApiEComImplementation::Drive(void) const
-	?VendorId@CMemSpyApiEComImplementation@@QBE?AVTVendorId@@XZ @ 206 NONAME ; class TVendorId CMemSpyApiEComImplementation::VendorId(void) const
-	?Version@CMemSpyApiEComImplementation@@QBEHXZ @ 207 NONAME ; int CMemSpyApiEComImplementation::Version(void) const
-	?Name@CMemSpyApiEComCategory@@QBEABVTDesC16@@XZ @ 208 NONAME ; class TDesC16 const & CMemSpyApiEComCategory::Name(void) const
-	?GetEComImplementationsL@RMemSpySession@@QAEXVTUid@@AAV?$RArray@PAVCMemSpyApiEComImplementation@@@@@Z @ 209 NONAME ; void RMemSpySession::GetEComImplementationsL(class TUid, class RArray<class CMemSpyApiEComImplementation *> &)
-	??1CMemSpyApiEComImplementation@@UAE@XZ @ 210 NONAME ; CMemSpyApiEComImplementation::~CMemSpyApiEComImplementation(void)
-	?InterfaceCount@CMemSpyApiEComCategory@@QBEHXZ @ 211 NONAME ; int CMemSpyApiEComCategory::InterfaceCount(void) const
-	?Id@CMemSpyApiEComInterface@@QBE?AVTUid@@XZ @ 212 NONAME ; class TUid CMemSpyApiEComInterface::Id(void) const
-	?RomBased@CMemSpyApiEComImplementation@@QBEHXZ @ 213 NONAME ; int CMemSpyApiEComImplementation::RomBased(void) const
-	?RomOnly@CMemSpyApiEComImplementation@@QBEHXZ @ 214 NONAME ; int CMemSpyApiEComImplementation::RomOnly(void) const
-	?GetEComInterfacesL@RMemSpySession@@QAEXVTUid@@AAV?$RArray@PAVCMemSpyApiEComInterface@@@@@Z @ 215 NONAME ; void RMemSpySession::GetEComInterfacesL(class TUid, class RArray<class CMemSpyApiEComInterface *> &)
-	?ImplementationCount@CMemSpyApiEComInterface@@QBEHXZ @ 216 NONAME ; int CMemSpyApiEComInterface::ImplementationCount(void) const
-	??1CMemSpyApiEComInterface@@UAE@XZ @ 217 NONAME ; CMemSpyApiEComInterface::~CMemSpyApiEComInterface(void)
-	?Name@CMemSpyApiEComInterface@@QBEABVTDesC16@@XZ @ 218 NONAME ; class TDesC16 const & CMemSpyApiEComInterface::Name(void) const
-	?Disabled@CMemSpyApiEComImplementation@@QBEHXZ @ 219 NONAME ; int CMemSpyApiEComImplementation::Disabled(void) const
-
--- a/memspy/MemSpyClient/eabi/MemSpyClientu.def	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,236 +0,0 @@
-EXPORTS
-	_ZN14CMemSpyApiHeap11BaseAddressEv @ 1 NONAME
-	_ZN14CMemSpyApiHeap11BiggestFreeEv @ 2 NONAME
-	_ZN14CMemSpyApiHeap11HeaderSizeAEv @ 3 NONAME
-	_ZN14CMemSpyApiHeap11HeaderSizeFEv @ 4 NONAME
-	_ZN14CMemSpyApiHeap12FreeOverheadEv @ 5 NONAME
-	_ZN14CMemSpyApiHeap13FragmentationEv @ 6 NONAME
-	_ZN14CMemSpyApiHeap13TotalOverheadEv @ 7 NONAME
-	_ZN14CMemSpyApiHeap14SlackFreeSpaceEv @ 8 NONAME
-	_ZN14CMemSpyApiHeap16AllocationsCountEv @ 9 NONAME
-	_ZN14CMemSpyApiHeap16TotalAllocationsEv @ 10 NONAME
-	_ZN14CMemSpyApiHeap17BiggestAllocationEv @ 11 NONAME
-	_ZN14CMemSpyApiHeap18AllocationOverheadEv @ 12 NONAME
-	_ZN14CMemSpyApiHeap21DebugAllocatorLibraryEv @ 13 NONAME
-	_ZN14CMemSpyApiHeap4SizeEv @ 14 NONAME
-	_ZN14CMemSpyApiHeap4TypeEv @ 15 NONAME
-	_ZN14CMemSpyApiHeap6SharedEv @ 16 NONAME
-	_ZN14CMemSpyApiHeap8OverheadEv @ 17 NONAME
-	_ZN14CMemSpyApiHeap9ChunkSizeEv @ 18 NONAME
-	_ZN14CMemSpyApiHeap9FreeCountEv @ 19 NONAME
-	_ZN14CMemSpyApiHeap9MaxLengthEv @ 20 NONAME
-	_ZN14CMemSpyApiHeap9MinLengthEv @ 21 NONAME
-	_ZN14CMemSpyApiHeap9TotalFreeEv @ 22 NONAME
-	_ZN14CMemSpyApiHeapD1Ev @ 23 NONAME
-	_ZN14CMemSpyApiHeapD2Ev @ 24 NONAME
-	_ZN14RMemSpySession10EndThreadLE9TThreadId14TMemSpyEndType @ 25 NONAME
-	_ZN14RMemSpySession11EndProcessLE10TProcessId14TMemSpyEndType @ 26 NONAME
-	_ZN14RMemSpySession11GetServersLER6RArrayIP16CMemSpyApiServerE @ 27 NONAME
-	_ZN14RMemSpySession11GetServersLER6RArrayIP16CMemSpyApiServerE9TSortType @ 28 NONAME
-	_ZN14RMemSpySession11GetSwmtModeERN38TMemSpyEngineHelperSysMemTrackerConfig30TMemSpyEngineSysMemTrackerModeE @ 29 NONAME
-	_ZN14RMemSpySession11GetThreadsLE10TProcessIdR6RArrayIP16CMemSpyApiThreadE9TSortType @ 30 NONAME
-	_ZN14RMemSpySession11SetSwmtModeEN38TMemSpyEngineHelperSysMemTrackerConfig30TMemSpyEngineSysMemTrackerModeE @ 31 NONAME
-	_ZN14RMemSpySession13GetOutputSinkER15TMemSpySinkType @ 32 NONAME
-	_ZN14RMemSpySession13GetProcessesLER6RArrayIP17CMemSpyApiProcessE9TSortType @ 33 NONAME
-	_ZN14RMemSpySession13GetSwmtFilterER4TBufILi128EE @ 34 NONAME
-	_ZN14RMemSpySession13OutputAOListLE9TThreadId25TMemSpyThreadInfoItemType @ 35 NONAME
-	_ZN14RMemSpySession13SetSwmtFilterERK7TDesC16 @ 36 NONAME
-	_ZN14RMemSpySession14DumpKernelHeapEv @ 37 NONAME
-	_ZN14RMemSpySession14IsSwmtRunningLEv @ 38 NONAME
-	_ZN14RMemSpySession14OutputHeapDataER14TRequestStatus @ 39 NONAME
-	_ZN14RMemSpySession14OutputHeapDataEv @ 40 NONAME
-	_ZN14RMemSpySession14OutputHeapInfoER14TRequestStatus @ 41 NONAME
-	_ZN14RMemSpySession14StopSwmtTimerLEv @ 42 NONAME
-	_ZN14RMemSpySession14SwitchToThreadE9TThreadIdi @ 43 NONAME
-	_ZN14RMemSpySession15ForceSwmtUpdateER14TRequestStatus @ 44 NONAME
-	_ZN14RMemSpySession15GetInfoItemTypeEi9TThreadIdR25TMemSpyThreadInfoItemType @ 45 NONAME
-	_ZN14RMemSpySession15OutputPhoneInfoER14TRequestStatus @ 46 NONAME
-	_ZN14RMemSpySession15OutputPhoneInfoEv @ 47 NONAME
-	_ZN14RMemSpySession15OutputStackInfoER14TRequestStatus @ 48 NONAME
-	_ZN14RMemSpySession15StartSwmtTimerLEi @ 49 NONAME
-	_ZN14RMemSpySession15StartSwmtTimerLEv @ 50 NONAME
-	_ZN14RMemSpySession15SwitchToProcessE10TProcessIdi @ 51 NONAME
-	_ZN14RMemSpySession16ForceSwmtUpdateLEv @ 52 NONAME
-	_ZN14RMemSpySession16GetKernelObjectsER6RArrayIP22CMemSpyApiKernelObjectE @ 53 NONAME
-	_ZN14RMemSpySession16OutputStackDataLE9TThreadId23TMemSpyDriverDomainType @ 54 NONAME
-	_ZN14RMemSpySession16OutputStackInfoLE9TThreadId @ 55 NONAME
-	_ZN14RMemSpySession17GetKernelObjectsLER6RArrayIP22CMemSpyApiKernelObjectE @ 56 NONAME
-	_ZN14RMemSpySession17SwitchOutputSinkLE15TMemSpySinkType @ 57 NONAME
-	_ZN14RMemSpySession17SwmtResetTrackingEv @ 58 NONAME
-	_ZN14RMemSpySession18GetEComCategoriesLER6RArrayIP22CMemSpyApiEComCategoryE @ 59 NONAME
-	_ZN14RMemSpySession18GetEComInterfacesLE4TUidR6RArrayIP23CMemSpyApiEComInterfaceE @ 60 NONAME
-	_ZN14RMemSpySession18GetSwmtCategoriesLERi @ 61 NONAME
-	_ZN14RMemSpySession18GetSwmtCyclesCountEv @ 62 NONAME
-	_ZN14RMemSpySession18GetThreadInfoItemsER6RArrayIP24CMemSpyApiThreadInfoItemE9TThreadId25TMemSpyThreadInfoItemType @ 63 NONAME
-	_ZN14RMemSpySession18SetSwmtCategoriesLEi @ 64 NONAME
-	_ZN14RMemSpySession18SetThreadPriorityLE9TThreadIdi @ 65 NONAME
-	_ZN14RMemSpySession19GetProcessIdByNameLERK7TDesC16 @ 66 NONAME
-	_ZN14RMemSpySession19GetThreadInfoItemsLER6RArrayIP24CMemSpyApiThreadInfoItemE9TThreadId25TMemSpyThreadInfoItemType @ 67 NONAME
-	_ZN14RMemSpySession19OutputHeapInfoUserLE9TThreadId @ 68 NONAME
-	_ZN14RMemSpySession19OutputUserStackDataER14TRequestStatus @ 69 NONAME
-	_ZN14RMemSpySession19SwitchOutputToFileLERK7TDesC16 @ 70 NONAME
-	_ZN14RMemSpySession20GetKernelObjectItemsER6RArrayIP26CMemSpyApiKernelObjectItemE26TMemSpyDriverContainerType @ 71 NONAME
-	_ZN14RMemSpySession20OutputKernelHeapDataER14TRequestStatus @ 72 NONAME
-	_ZN14RMemSpySession20OutputKernelObjectsLEv @ 73 NONAME
-	_ZN14RMemSpySession20SwitchOutputToTraceLEv @ 74 NONAME
-	_ZN14RMemSpySession21GetKernelObjectItemsLER6RArrayIP26CMemSpyApiKernelObjectItemE26TMemSpyDriverContainerType @ 75 NONAME
-	_ZN14RMemSpySession21GetSwmtTimerIntervalLERi @ 76 NONAME
-	_ZN14RMemSpySession21OutputCompactHeapInfoER14TRequestStatus @ 77 NONAME
-	_ZN14RMemSpySession21OutputHeapCellListingER14TRequestStatus @ 78 NONAME
-	_ZN14RMemSpySession21OutputKernelHeapDataLEv @ 79 NONAME
-	_ZN14RMemSpySession21OutputKernelStackDataER14TRequestStatus @ 80 NONAME
-	_ZN14RMemSpySession21OutputThreadCellListLE9TThreadId @ 81 NONAME
-	_ZN14RMemSpySession21OutputThreadHeapDataLE9TThreadId @ 82 NONAME
-	_ZN14RMemSpySession21OutputThreadHeapDataLERK7TDesC16 @ 83 NONAME
-	_ZN14RMemSpySession21SetSwmtTimerIntervalLEi @ 84 NONAME
-	_ZN14RMemSpySession22GetProcessIdByThreadIdER10TProcessId9TThreadId @ 85 NONAME
-	_ZN14RMemSpySession22OutputCompactHeapInfoLEv @ 86 NONAME
-	_ZN14RMemSpySession22OutputCompactStackInfoER14TRequestStatus @ 87 NONAME
-	_ZN14RMemSpySession23GetEComImplementationsLE4TUidR6RArrayIP28CMemSpyApiEComImplementationE @ 88 NONAME
-	_ZN14RMemSpySession23OutputCompactStackInfoLEv @ 89 NONAME
-	_ZN14RMemSpySession23OutputDetailedPhoneInfoER14TRequestStatus @ 90 NONAME
-	_ZN14RMemSpySession24GetMemoryTrackingCyclesLER6RArrayIP29CMemSpyApiMemoryTrackingCycleE @ 91 NONAME
-	_ZN14RMemSpySession24GetSwmtHeapDumpsEnabledLERi @ 92 NONAME
-	_ZN14RMemSpySession24OutputThreadInfoHandlesLE9TThreadId @ 93 NONAME
-	_ZN14RMemSpySession24ServerListOutputGenericLEi @ 94 NONAME
-	_ZN14RMemSpySession24SetSwmtHeapDumpsEnabledLEi @ 95 NONAME
-	_ZN14RMemSpySession26CancelDeviceWideOperationLEv @ 96 NONAME
-	_ZN14RMemSpySession26OutputAllContainerContentsEv @ 97 NONAME
-	_ZN14RMemSpySession27SetSwmtAutoStartProcessListEP13CArrayFixFlatI4TUidE @ 98 NONAME
-	_ZN14RMemSpySession31ThreadSystemPermanentOrCriticalE9TThreadIdi @ 99 NONAME
-	_ZN14RMemSpySession32ProcessSystemPermanentOrCriticalE10TProcessIdi @ 100 NONAME
-	_ZN14RMemSpySession33NotifyDeviceWideOperationProgressER34TMemSpyDeviceWideOperationProgressR14TRequestStatus @ 101 NONAME
-	_ZN14RMemSpySession7ConnectEv @ 102 NONAME
-	_ZN14RMemSpySession7GetHeapEv @ 103 NONAME
-	_ZN14RMemSpySession8GetHeapLEv @ 104 NONAME
-	_ZN14RMemSpySessionC1Ev @ 105 NONAME
-	_ZN14RMemSpySessionC2Ev @ 106 NONAME
-	_ZN16CMemSpyApiServerD1Ev @ 107 NONAME
-	_ZN16CMemSpyApiServerD2Ev @ 108 NONAME
-	_ZN16CMemSpyApiThreadD1Ev @ 109 NONAME
-	_ZN16CMemSpyApiThreadD2Ev @ 110 NONAME
-	_ZN17CMemSpyApiProcessD1Ev @ 111 NONAME
-	_ZN17CMemSpyApiProcessD2Ev @ 112 NONAME
-	_ZN22CMemSpyApiEComCategoryD0Ev @ 113 NONAME
-	_ZN22CMemSpyApiEComCategoryD1Ev @ 114 NONAME
-	_ZN22CMemSpyApiEComCategoryD2Ev @ 115 NONAME
-	_ZN22CMemSpyApiKernelObjectD1Ev @ 116 NONAME
-	_ZN22CMemSpyApiKernelObjectD2Ev @ 117 NONAME
-	_ZN23CMemSpyApiEComInterfaceD0Ev @ 118 NONAME
-	_ZN23CMemSpyApiEComInterfaceD1Ev @ 119 NONAME
-	_ZN23CMemSpyApiEComInterfaceD2Ev @ 120 NONAME
-	_ZN24CMemSpyApiThreadInfoItemD1Ev @ 121 NONAME
-	_ZN24CMemSpyApiThreadInfoItemD2Ev @ 122 NONAME
-	_ZN26CMemSpyApiKernelObjectItem12OpenChannelsEv @ 123 NONAME
-	_ZN26CMemSpyApiKernelObjectItem15AddressOfServerEv @ 124 NONAME
-	_ZN26CMemSpyApiKernelObjectItem16AddressOfCodeSegEv @ 125 NONAME
-	_ZN26CMemSpyApiKernelObjectItem20AddressOfKernelOwnerEv @ 126 NONAME
-	_ZN26CMemSpyApiKernelObjectItem21AddressOfOwningThreadEv @ 127 NONAME
-	_ZN26CMemSpyApiKernelObjectItem22AddressOfOwningProcessEv @ 128 NONAME
-	_ZN26CMemSpyApiKernelObjectItem26AddressOfDataBssStackChunkEv @ 129 NONAME
-	_ZN26CMemSpyApiKernelObjectItemD1Ev @ 130 NONAME
-	_ZN26CMemSpyApiKernelObjectItemD2Ev @ 131 NONAME
-	_ZN28CMemSpyApiEComImplementationD0Ev @ 132 NONAME
-	_ZN28CMemSpyApiEComImplementationD1Ev @ 133 NONAME
-	_ZN28CMemSpyApiEComImplementationD2Ev @ 134 NONAME
-	_ZN29CMemSpyApiMemoryTrackingCycleD1Ev @ 135 NONAME
-	_ZN29CMemSpyApiMemoryTrackingCycleD2Ev @ 136 NONAME
-	_ZNK16CMemSpyApiServer12SessionCountEv @ 137 NONAME
-	_ZNK16CMemSpyApiServer2IdEv @ 138 NONAME
-	_ZNK16CMemSpyApiServer4NameEv @ 139 NONAME
-	_ZNK16CMemSpyApiThread10AttributesEv @ 140 NONAME
-	_ZNK16CMemSpyApiThread12RequestCountEv @ 141 NONAME
-	_ZNK16CMemSpyApiThread13ThreadHandlesEv @ 142 NONAME
-	_ZNK16CMemSpyApiThread14ProcessHandlesEv @ 143 NONAME
-	_ZNK16CMemSpyApiThread14ThreadPriorityEv @ 144 NONAME
-	_ZNK16CMemSpyApiThread15ProcessPriorityEv @ 145 NONAME
-	_ZNK16CMemSpyApiThread17ThreadNumberUsingEv @ 146 NONAME
-	_ZNK16CMemSpyApiThread18ProcessNumberUsingEv @ 147 NONAME
-	_ZNK16CMemSpyApiThread2IdEv @ 148 NONAME
-	_ZNK16CMemSpyApiThread3SIDEv @ 149 NONAME
-	_ZNK16CMemSpyApiThread3VIDEv @ 150 NONAME
-	_ZNK16CMemSpyApiThread4NameEv @ 151 NONAME
-	_ZNK16CMemSpyApiThread6CpuUseEv @ 152 NONAME
-	_ZNK16CMemSpyApiThread8ExitTypeEv @ 153 NONAME
-	_ZNK16CMemSpyApiThread9ProcessIdEv @ 154 NONAME
-	_ZNK17CMemSpyApiProcess10ExitReasonEv @ 155 NONAME
-	_ZNK17CMemSpyApiProcess11ThreadCountEv @ 156 NONAME
-	_ZNK17CMemSpyApiProcess12ExitCategoryEv @ 157 NONAME
-	_ZNK17CMemSpyApiProcess2IdEv @ 158 NONAME
-	_ZNK17CMemSpyApiProcess3SIDEv @ 159 NONAME
-	_ZNK17CMemSpyApiProcess3VIDEv @ 160 NONAME
-	_ZNK17CMemSpyApiProcess4NameEv @ 161 NONAME
-	_ZNK17CMemSpyApiProcess6IsDeadEv @ 162 NONAME
-	_ZNK17CMemSpyApiProcess8ExitTypeEv @ 163 NONAME
-	_ZNK17CMemSpyApiProcess8PriorityEv @ 164 NONAME
-	_ZNK22CMemSpyApiEComCategory14InterfaceCountEv @ 165 NONAME
-	_ZNK22CMemSpyApiEComCategory2IdEv @ 166 NONAME
-	_ZNK22CMemSpyApiEComCategory4NameEv @ 167 NONAME
-	_ZNK22CMemSpyApiKernelObject4NameEv @ 168 NONAME
-	_ZNK22CMemSpyApiKernelObject4SizeEv @ 169 NONAME
-	_ZNK22CMemSpyApiKernelObject4TypeEv @ 170 NONAME
-	_ZNK22CMemSpyApiKernelObject5CountEv @ 171 NONAME
-	_ZNK23CMemSpyApiEComInterface19ImplementationCountEv @ 172 NONAME
-	_ZNK23CMemSpyApiEComInterface2IdEv @ 173 NONAME
-	_ZNK23CMemSpyApiEComInterface4NameEv @ 174 NONAME
-	_ZNK24CMemSpyApiThreadInfoItem5ValueEv @ 175 NONAME
-	_ZNK24CMemSpyApiThreadInfoItem7CaptionEv @ 176 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem10AttributesEv @ 177 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem10NameDetailEv @ 178 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem10ProtectionEv @ 179 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem10TimerStateEv @ 180 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem11AccessCountEv @ 181 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem11NameOfOwnerEv @ 182 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem11SessionTypeEv @ 183 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem12RestrictionsEv @ 184 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem12SecurityZoneEv @ 185 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem14SvrSessionTypeEv @ 186 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem16ControllingOwnerEv @ 187 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem16TotalAccessCountEv @ 188 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem2IdEv @ 189 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem3TopEv @ 190 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem4NameEv @ 191 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem4SizeEv @ 192 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem4TypeEv @ 193 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem5CountEv @ 194 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem5OrderEv @ 195 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem5StateEv @ 196 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem6BottomEv @ 197 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem6HandleEv @ 198 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem7ChangesEv @ 199 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem7MapAttrEv @ 200 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem7MaxSizeEv @ 201 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem7VersionEv @ 202 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem8MapCountEv @ 203 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem8MsgCountEv @ 204 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem8MsgLimitEv @ 205 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem8PriorityEv @ 206 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem8StartPosEv @ 207 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem8UniqueIDEv @ 208 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem9ChunkTypeEv @ 209 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem9CreatorIdEv @ 210 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem9ParseMaskEv @ 211 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem9ResettingEv @ 212 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem9TimerTypeEv @ 213 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem9UnitsMaskEv @ 214 NONAME
-	_ZNK26CMemSpyApiKernelObjectItem9WaitCountEv @ 215 NONAME
-	_ZNK28CMemSpyApiEComImplementation10OpaqueDataEv @ 216 NONAME
-	_ZNK28CMemSpyApiEComImplementation17ImplementationUidEv @ 217 NONAME
-	_ZNK28CMemSpyApiEComImplementation4NameEv @ 218 NONAME
-	_ZNK28CMemSpyApiEComImplementation5DriveEv @ 219 NONAME
-	_ZNK28CMemSpyApiEComImplementation7RomOnlyEv @ 220 NONAME
-	_ZNK28CMemSpyApiEComImplementation7VersionEv @ 221 NONAME
-	_ZNK28CMemSpyApiEComImplementation8DataTypeEv @ 222 NONAME
-	_ZNK28CMemSpyApiEComImplementation8DisabledEv @ 223 NONAME
-	_ZNK28CMemSpyApiEComImplementation8RomBasedEv @ 224 NONAME
-	_ZNK28CMemSpyApiEComImplementation8VendorIdEv @ 225 NONAME
-	_ZNK29CMemSpyApiMemoryTrackingCycle10FreeMemoryEv @ 226 NONAME
-	_ZNK29CMemSpyApiMemoryTrackingCycle11ChangeCountEv @ 227 NONAME
-	_ZNK29CMemSpyApiMemoryTrackingCycle11CycleNumberEv @ 228 NONAME
-	_ZNK29CMemSpyApiMemoryTrackingCycle11MemoryDeltaEv @ 229 NONAME
-	_ZNK29CMemSpyApiMemoryTrackingCycle17PreviousCycleDiffEv @ 230 NONAME
-	_ZNK29CMemSpyApiMemoryTrackingCycle4TimeEv @ 231 NONAME
-	_ZNK29CMemSpyApiMemoryTrackingCycle7CaptionEv @ 232 NONAME
-	_ZNK34TMemSpyDeviceWideOperationProgress11DescriptionEv @ 233 NONAME
-	_ZNK34TMemSpyDeviceWideOperationProgress8ProgressEv @ 234 NONAME
-
--- a/memspy/MemSpyClient/group/MemSpyClient.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <data_caging_paths.hrh>
-#include <platform_paths.hrh>
-
-TARGETTYPE dll
-TARGET MemSpyClient.dll
-UID 0 0x2002EA8E
-VENDORID	VID_DEFAULT
-SMPSAFE
-
-CAPABILITY PowerMgmt SwEvent ReadUserData WriteUserData ReadDeviceData WriteDeviceData CommDD MultimediaDD DRM TrustedUI ProtServ DiskAdmin NetworkControl AllFiles NetworkServices LocalServices Location SurroundingsDD UserEnvironment
-
-SOURCEPATH ../src
-SOURCE 		memspysession.cpp 
-SOURCE 		memspyapiprocess.cpp 
-SOURCE 		memspyapikernelobject.cpp 
-SOURCE		memspyapiheap.cpp 
-SOURCE 		memspyapikernelobjectitem.cpp 
-SOURCE		memspyapithread.cpp 
-SOURCE		memspyapithreadinfoitem.cpp
-SOURCE		memspyapimemorytrackingcycle.cpp
-SOURCE 		memspyapiserver.cpp
-SOURCE 		memspyapiecom.cpp  
-
-USERINCLUDE ../inc
-
-OS_LAYER_SYSTEMINCLUDE
-
-LIBRARY 		euser.lib
-LIBRARY			ecom.lib
-LIBRARY			efsrv.lib
-LIBRARY			estor.lib
-LIBRARY			bafl.lib
-LIBRARY			ws32.lib
-LIBRARY			cone.lib
-LIBRARY			eikcore.lib
-LIBRARY			fbscli.lib 
-LIBRARY 		PlatformEnv.lib
-LIBRARY         MemSpyEngine.lib
-
-//EXPORTUNFROZEN
--- a/memspy/MemSpyClient/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <platform_paths.hrh>
-
-PRJ_EXPORTS
-// Public API
-../inc/memspysession.h OS_LAYER_PLATFORM_EXPORT_PATH(memspysession.h)
-../inc/memspyprocessdata.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/engine/memspyprocessdata.h)
-../inc/memspykernelobjectdata.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/engine/memspykernelobjectdata.h)
-../inc/memspyheapdata.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/engine/memspyheapdata.h)
-../inc/memspythreaddata.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/engine/memspythreaddata.h)
-../inc/memspythreadinfoitemdata.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/engine/memspythreadinfoitemdata.h)
-../inc/memspymemorytrackingcycledata.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/engine/memspymemorytrackingcycledata.h)
-../inc/memspyserverdata.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/engine/memspyserverdata.h)
-../inc/memspyecomdata.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/engine/memspyecomdata.h)
-
-../inc/memspyapiprocess.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapiprocess.h)
-../inc/memspyapikernelobject.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapikernelobject.h)
-../inc/memspyapikernelobjectitem.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapikernelobjectitem.h)
-../inc/memspyapiheap.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapiheap.h)
-../inc/memspyapithread.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapithread.h)
-../inc/memspyapithreadinfoitem.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapithreadinfoitem.h)
-../inc/memspyapimemorytrackingcycle.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapimemorytrackingcycle.h)
-../inc/memspyapiserver.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapiserver.h)
-../inc/memspyapiecom.h OS_LAYER_PLATFORM_EXPORT_PATH(memspy/api/memspyapiecom.h)
-
-PRJ_MMPFILES
-MemSpyClient.mmp
\ No newline at end of file
--- a/memspy/MemSpyClient/inc/memspyapiecom.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,116 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  CMemSpyProcess class 
-*/
-
-#ifndef MEMSPYAPIECOM_H
-#define MEMSPYAPIECOM_H
-
-// System includes
-#include <e32base.h>
-#include <f32file.h>
-
-class TMemSpyEComCategoryData;
-class TMemSpyEComInterfaceData;
-class TMemSpyEComImplementationData;
-
-NONSHARABLE_CLASS( CMemSpyApiEComCategory ) : public CBase
-	{
-public:
-	IMPORT_C ~CMemSpyApiEComCategory();
-	
-	static CMemSpyApiEComCategory* NewL(const TMemSpyEComCategoryData& aData);
-
-	static CMemSpyApiEComCategory* NewLC(const TMemSpyEComCategoryData& aData);
-	
-public:
-	IMPORT_C TUid Id() const;
-	
-	IMPORT_C const TDesC& Name() const;
-	
-	IMPORT_C TInt InterfaceCount() const;
-	
-private:
-	void ConstructL(const TMemSpyEComCategoryData& aData);
-		
-private:
-	TMemSpyEComCategoryData *iData;
-};
-
-NONSHARABLE_CLASS( CMemSpyApiEComInterface ) : public CBase
-    {
-public:
-    IMPORT_C ~CMemSpyApiEComInterface();
-    
-    static CMemSpyApiEComInterface* NewL(const TMemSpyEComInterfaceData& aData);
-
-    static CMemSpyApiEComInterface* NewLC(const TMemSpyEComInterfaceData& aData);
-    
-public:
-    IMPORT_C TUid Id() const;
-    
-    IMPORT_C TUid CategoryId() const;
-    
-    IMPORT_C const TDesC& Name() const;
-    
-    IMPORT_C TInt ImplementationCount() const;
-    
-private:
-    void ConstructL(const TMemSpyEComInterfaceData& aData);
-        
-private:
-    TMemSpyEComInterfaceData *iData;
-};
-
-NONSHARABLE_CLASS( CMemSpyApiEComImplementation ) : public CBase 
-    {
-public:
-    IMPORT_C ~CMemSpyApiEComImplementation();
-    
-    static CMemSpyApiEComImplementation* NewL(const TMemSpyEComImplementationData& aData);
-
-    static CMemSpyApiEComImplementation* NewLC(const TMemSpyEComImplementationData& aData);
-    
-public:
-    IMPORT_C TUid ImplementationUid() const;
-        
-    IMPORT_C const TDesC& Name() const;
-    
-    IMPORT_C TInt Version() const;
-    
-    IMPORT_C const TDesC& DataType() const;
-        
-    IMPORT_C const TDesC& OpaqueData() const;
-    
-    IMPORT_C TDriveUnit Drive() const;
-        
-    IMPORT_C TBool RomOnly() const;
-        
-    IMPORT_C TBool RomBased() const;
-        
-    IMPORT_C TVendorId VendorId() const;
-        
-    IMPORT_C TBool Disabled() const;
-    
-private:
-    
-    void ConstructL(const TMemSpyEComImplementationData& aData);
-        
-private:
-    TMemSpyEComImplementationData *iData;
-};
-
-
-#endif // MEMSPYAPIECOM_H
--- a/memspy/MemSpyClient/inc/memspyapiheap.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,69 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  CMemSpyApiHeap class 
-*/
-
-#ifndef MEMSPYAPIHEAP_H
-#define MEMSPYAPIHEAP_H
-
-// System includes
-#include <e32base.h>
-
-class TMemSpyHeapData;
-
-NONSHARABLE_CLASS( CMemSpyApiHeap ) 
-	{
-public:
-	IMPORT_C ~CMemSpyApiHeap();
-	
-	static CMemSpyApiHeap* NewL(const TMemSpyHeapData& aData);
-
-	static CMemSpyApiHeap* NewLC(const TMemSpyHeapData& aData);
-	
-public: //API
-	IMPORT_C TDesC& Type();
-	IMPORT_C TInt Size();
-	IMPORT_C TInt BaseAddress();
-	IMPORT_C TBool Shared();
-	IMPORT_C TInt ChunkSize();
-	IMPORT_C TInt AllocationsCount();
-	IMPORT_C TInt FreeCount();
-	IMPORT_C TInt BiggestAllocation();
-	IMPORT_C TInt BiggestFree();
-	IMPORT_C TInt TotalAllocations();
-	IMPORT_C TInt TotalFree();
-	IMPORT_C TInt SlackFreeSpace();
-	IMPORT_C TInt Fragmentation(); // Percentage value, iSize is 100% - value for calculation
-	IMPORT_C TInt HeaderSizeA();
-	IMPORT_C TInt HeaderSizeF();
-	IMPORT_C TInt AllocationOverhead();
-	IMPORT_C TInt FreeOverhead();
-	IMPORT_C TInt TotalOverhead();
-	IMPORT_C TInt Overhead(); //Percentage value, iSize is 100% - value for calculation
-	IMPORT_C TInt MinLength();
-	IMPORT_C TInt MaxLength();
-	IMPORT_C TBool DebugAllocatorLibrary();
-	
-private:
-	CMemSpyApiHeap();
-	
-	void ConstructL(const TMemSpyHeapData& aData);
-		
-private:
-	TMemSpyHeapData *iHeapData;
-};
-
-	
-#endif // MEMSPYAPIHEAP_H
--- a/memspy/MemSpyClient/inc/memspyapikernelobject.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,56 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*  
-*/
-
-#ifndef MEMSPYAPIPKERNELOBJECT_H
-#define MEMSPYAPIPKERNELOBJECT_H
-
-// System includes
-#include <e32base.h>
-
-#include <memspy/driver/memspydriverenumerationsshared.h>
-
-class TMemSpyKernelObjectData;
-
-NONSHARABLE_CLASS( CMemSpyApiKernelObject ) 
-	{
-public:
-	IMPORT_C ~CMemSpyApiKernelObject();
-	
-	static CMemSpyApiKernelObject* NewL(const TMemSpyKernelObjectData& aData);
-
-	static CMemSpyApiKernelObject* NewLC(const TMemSpyKernelObjectData& aData);
-	
-public:
-	IMPORT_C TMemSpyDriverContainerType Type() const;
-	
-	IMPORT_C const TDesC& Name() const;	
-						
-	IMPORT_C TInt Count() const;
-		
-	IMPORT_C TInt64 Size() const;
-	
-private:
-	CMemSpyApiKernelObject();
-	
-	void ConstructL(const TMemSpyKernelObjectData& aData);
-		
-private:
-	TMemSpyKernelObjectData *iKernelObjectData;
-};
-
-	
-#endif // MEMSPYAPIPKERNELOBJECT_H
--- a/memspy/MemSpyClient/inc/memspyapikernelobjectitem.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,128 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  CMemSpyProcess class 
-*/
-
-#ifndef MEMSPYAPIKERNELOBJECTITEM_H
-#define MEMSPYAPIKERNELOBJECTITEM_H
-
-// System includes
-#include <e32base.h>
-#include <memspy/driver/memspydriverenumerationsshared.h>
-
-class TMemSpyDriverHandleInfoGeneric;
-//class TMemSpyDriverContainerType;	
-//class TMemSpyDriverTimerType;
-//class TMemSpyDriverTimerState;
-
-NONSHARABLE_CLASS( CMemSpyApiKernelObjectItem ) 
-	{
-public:
-	IMPORT_C ~CMemSpyApiKernelObjectItem();
-	
-	static CMemSpyApiKernelObjectItem* NewL(const TMemSpyDriverHandleInfoGeneric& aData);
-
-	static CMemSpyApiKernelObjectItem* NewLC(const TMemSpyDriverHandleInfoGeneric& aData);
-	
-public:	
-	
-	IMPORT_C const TDesC8& Name() const;	
-	
-	IMPORT_C TAny* Handle() const;
-	
-	IMPORT_C TMemSpyDriverContainerType Type() const;
-	
-    // For Process, thread, chunk (owning process id), server (owning thread id)
-    IMPORT_C TInt Id() const;
-
-    // For Chunk, Library
-    IMPORT_C TUint32 Size() const;
-   
-    // For Semaphore, Mutex, Server
-    IMPORT_C TInt Count() const;
-
-    // For Mutex
-    IMPORT_C TInt WaitCount() const;
-
-    // For Server, Session
-    IMPORT_C TIpcSessionType SessionType() const;
-
-    // For Timer
-    IMPORT_C TMemSpyDriverTimerType TimerType() const;
-    IMPORT_C TMemSpyDriverTimerState TimerState() const;
-
-    // For Logical channel
-    IMPORT_C TInt OpenChannels();
-    
-    // For most of the object types
-    IMPORT_C const TDesC8& NameDetail() const; // Name
-    IMPORT_C TInt AccessCount() const;
-    IMPORT_C TInt UniqueID() const;
-    IMPORT_C TUint Protection() const;
-    IMPORT_C TUint8* AddressOfKernelOwner();
-    IMPORT_C TInt Priority() const;
-    IMPORT_C TUint8* AddressOfOwningProcess();
-    IMPORT_C TUint CreatorId() const;
-    IMPORT_C TUint SecurityZone() const;
-    IMPORT_C TInt Attributes() const;
-    IMPORT_C TUint8* AddressOfDataBssStackChunk();
-
-    // For Server, Session
-    IMPORT_C TUint8* AddressOfOwningThread();
-    IMPORT_C TUint8* AddressOfServer();
-    IMPORT_C TUint16 TotalAccessCount() const;
-    IMPORT_C TUint8 SvrSessionType() const;
-    IMPORT_C TInt MsgCount() const;
-    IMPORT_C TInt MsgLimit() const;
-    
-    // For chunk
-    IMPORT_C TInt MaxSize() const;
-    IMPORT_C TInt Bottom() const;
-    IMPORT_C TInt Top() const;
-    IMPORT_C TInt StartPos() const;
-    IMPORT_C TUint ControllingOwner() const;
-    IMPORT_C TUint Restrictions() const;
-    IMPORT_C TUint MapAttr() const;
-    IMPORT_C TUint ChunkType() const;
-    IMPORT_C const TDesC8& NameOfOwner() const; // chunk, server
-    
-    // For library
-    IMPORT_C TInt MapCount() const;
-    IMPORT_C TUint8 State() const;
-    IMPORT_C TUint8* AddressOfCodeSeg();
-    
-    // Semaphore, mutex, condvar
-    IMPORT_C TUint8 Resetting() const;
-    IMPORT_C TUint8 Order() const;
-    
-    // For Logical/Physical device
-    IMPORT_C TVersion Version() const;
-    IMPORT_C TUint ParseMask() const;
-    IMPORT_C TUint UnitsMask() const;
-    
-    // For change notifier
-    IMPORT_C TUint Changes() const;
-	
-private:
-	CMemSpyApiKernelObjectItem();
-	
-	void ConstructL(const TMemSpyDriverHandleInfoGeneric& aData);
-		
-private:
-	TMemSpyDriverHandleInfoGeneric *iItem;
-};
-
-	
-#endif // MEMSPYAPIKERNELOBJECTITEM_H
--- a/memspy/MemSpyClient/inc/memspyapimemorytrackingcycle.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,53 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* 
-*/
-
-#ifndef MEMSPYAPIMEMORYTRACKINGCYCLE_H_
-#define MEMSPYAPIMEMORYTRACKINGCYCLE_H_
-
-#include <e32base.h>
-
-class TMemSpyMemoryTrackingCycleData;
-
-class CMemSpyApiMemoryTrackingCycle
-	{
-public: // API
-	IMPORT_C TInt CycleNumber() const;
-	IMPORT_C const TTime& Time() const;
-	IMPORT_C const TDesC& Caption() const;
-	IMPORT_C const TInt64& FreeMemory() const;
-	IMPORT_C TInt64 MemoryDelta() const;
-	IMPORT_C TInt64 PreviousCycleDiff() const;
-	IMPORT_C TInt ChangeCount() const;
-	
-public:
-	IMPORT_C ~CMemSpyApiMemoryTrackingCycle();
-	
-	static CMemSpyApiMemoryTrackingCycle* NewL(const TMemSpyMemoryTrackingCycleData& aData);
-
-	static CMemSpyApiMemoryTrackingCycle* NewLC(const TMemSpyMemoryTrackingCycleData& aData);
-	
-private:
-	CMemSpyApiMemoryTrackingCycle();
-	
-	void ConstructL(const TMemSpyMemoryTrackingCycleData& aData);
-	
-private:
-	TMemSpyMemoryTrackingCycleData* iData;
-	
-	};
-
-#endif /* MEMSPYAPIMEMORYTRACKINGCYCLE_H_ */
--- a/memspy/MemSpyClient/inc/memspyapiprocess.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,67 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  CMemSpyProcess class 
-*/
-
-#ifndef MEMSPYAPIPROCESS_H
-#define MEMSPYAPIPROCESS_H
-
-// System includes
-#include <e32base.h>
-
-class TMemSpyProcessData;
-
-NONSHARABLE_CLASS( CMemSpyApiProcess ) 
-	{
-public:
-	IMPORT_C ~CMemSpyApiProcess();
-	
-	static CMemSpyApiProcess* NewL(const TMemSpyProcessData& aData);
-
-	static CMemSpyApiProcess* NewLC(const TMemSpyProcessData& aData);
-	
-public:
-	IMPORT_C TProcessId Id() const;
-	
-	IMPORT_C const TDesC& Name() const;	
-	
-	IMPORT_C TExitCategoryName ExitCategory() const;
-	
-	IMPORT_C TInt ExitReason() const;
-	
-	IMPORT_C TExitType ExitType() const;
-	
-	IMPORT_C TInt ThreadCount() const;
-	
-	IMPORT_C TUint32 SID() const;
-	
-	IMPORT_C TUint32 VID() const;
-	
-	IMPORT_C TProcessPriority Priority() const;
-	
-	IMPORT_C TBool IsDead() const;
-	
-	
-private:
-	CMemSpyApiProcess();
-	
-	void ConstructL(const TMemSpyProcessData& aData);
-		
-private:
-	TMemSpyProcessData *iProcessData;
-};
-
-	
-#endif // MEMSPYAPIPROCESS_H
--- a/memspy/MemSpyClient/inc/memspyapiserver.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,52 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  CMemSpyProcess class 
-*/
-
-#ifndef MEMSPYAPISERVER_H
-#define MEMSPYAPISERVER_H
-
-// System includes
-#include <e32base.h>
-
-class TMemSpyServerData;
-
-NONSHARABLE_CLASS( CMemSpyApiServer ) 
-	{
-public:
-	IMPORT_C ~CMemSpyApiServer();
-	
-	static CMemSpyApiServer* NewL(const TMemSpyServerData& aData);
-
-	static CMemSpyApiServer* NewLC(const TMemSpyServerData& aData);
-	
-public:
-	IMPORT_C TProcessId Id() const;
-	
-	IMPORT_C const TDesC& Name() const;	
-	
-	IMPORT_C TInt SessionCount() const;
-	
-private:
-	CMemSpyApiServer();
-	
-	void ConstructL(const TMemSpyServerData& aData);
-		
-private:
-	TMemSpyServerData *iData;
-};
-
-	
-#endif // MEMSPYAPISERVER_H
--- a/memspy/MemSpyClient/inc/memspyapithread.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  CMemSpyProcessWrapper class and TMemSpyProcess data class
-*/
-
-#ifndef MEMSPYAPITHREAD_H
-#define MEMSPYAPITHREAD_H
-
-// System includes
-#include <e32base.h>
-
-class TMemSpyThreadData;
-
-NONSHARABLE_CLASS( CMemSpyApiThread ) {
-
-public:
-	IMPORT_C ~CMemSpyApiThread();
-	
-	static CMemSpyApiThread* NewL(const TMemSpyThreadData& aData);
-
-	static CMemSpyApiThread* NewLC(const TMemSpyThreadData& aData);
-
-public:
-	IMPORT_C TThreadId Id() const;
-	IMPORT_C TProcessId ProcessId() const;
-	
-	IMPORT_C const TDesC& Name() const;
-		
-	IMPORT_C TInt SID() const;
-	
-	IMPORT_C TInt VID() const;
-	
-	IMPORT_C TThreadPriority ThreadPriority() const;
-	
-	IMPORT_C TProcessPriority ProcessPriority() const;
-	
-	IMPORT_C TInt RequestCount() const;
-	
-	IMPORT_C TInt ThreadHandles() const;
-	
-	IMPORT_C TInt ProcessHandles() const;
-	
-	IMPORT_C TInt ThreadNumberUsing() const;
-	
-	IMPORT_C TInt ProcessNumberUsing() const;
-	
-	IMPORT_C TInt Attributes() const;
-	
-	IMPORT_C TInt CpuUse() const;
-	
-	IMPORT_C TExitType ExitType() const;
-	
-private:
-	CMemSpyApiThread();	
-	
-	void ConstructL(const TMemSpyThreadData& aData);
-private:
-	TMemSpyThreadData* iThreadData;
-};
-
-#endif
--- a/memspy/MemSpyClient/inc/memspyapithreadinfoitem.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  CMemSpyProcess class 
-*/
-
-#ifndef MEMSPYAPITHREADINFOITEM_H
-#define MEMSPYAPITHREADINFOITEM_H
-
-// System includes
-#include <e32base.h>
-
-class TMemSpyThreadInfoItemData;
-
-NONSHARABLE_CLASS( CMemSpyApiThreadInfoItem ) 
-	{
-public:
-	IMPORT_C ~CMemSpyApiThreadInfoItem();
-	
-	static CMemSpyApiThreadInfoItem* NewL(const TMemSpyThreadInfoItemData& aData);
-
-	static CMemSpyApiThreadInfoItem* NewLC(const TMemSpyThreadInfoItemData& aData);
-	
-public:		
-	IMPORT_C const TDesC& Caption() const;	
-	
-	IMPORT_C const TDesC& Value() const;	
-	
-private:
-	CMemSpyApiThreadInfoItem();
-	
-	void ConstructL(const TMemSpyThreadInfoItemData& aData);
-		
-private:
-	TMemSpyThreadInfoItemData *iInfoItem;
-};
-
-	
-#endif // MEMSPYAPITHREADINFOITEM_H
--- a/memspy/MemSpyClient/inc/memspyecomdata.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,68 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  TMemSpyProcessData class
-*/
-
-#ifndef MEMSPYECOMDATA_H
-#define MEMSPYECOMDATA_H
-
-// TMemSpyProcess data class holds data to be sent to the UI
-class TMemSpyEComCategoryData 
-	{	
-public:
-	//constructor & destructor
-	inline TMemSpyEComCategoryData ()
-		: iInterfaceCount(0)
-		{
-		}
-	
-public:
-    TUid iId;        
-    TFullName iName;
-    TInt iInterfaceCount;
-	};
-
-class TMemSpyEComInterfaceData 
-    {   
-public:
-    //constructor & destructor
-    inline TMemSpyEComInterfaceData ()
-        : iImplementationCount(0)
-        {
-        }
-    
-public:
-    TUid iId;
-    TUid iCategoryId;
-    TFullName iName;
-    TInt iImplementationCount;
-    };
-
-class TMemSpyEComImplementationData 
-    {   
-public:
-    TUid iImplementationUid;
-    TFullName iName;
-    TInt iVersion;
-    TFullName iDataType;
-    TFullName iOpaqueData;
-    TDriveUnit iDrive;
-    TBool iRomOnly;
-    TBool iRomBased;
-    TVendorId iVendorId;    
-    TBool iDisabled;
-    };
-
-#endif // MEMSPYECOMDATA_H
--- a/memspy/MemSpyClient/inc/memspyheapdata.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,64 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  TMemSpyProcessData class
-*/
-
-#ifndef MEMSPYHEAPDATA_H
-#define MEMSPYHEAPDATA_H
-
-#include <memspy/driver/memspydriverobjectsshared.h>
-
-// Constants
-const TInt KBuf = 16;
-
-// TMemSpyProcess data class holds data to be sent to the UI
-class TMemSpyHeapData 
-	{	
-public:
-	//constructor & destructor
-	inline TMemSpyHeapData()		
-	: iSize(0), iBaseAddress(0), iShared(EFalse), iChunkSize(0),
-	iAllocationsCount(0), iFreeCount(0), iBiggestAllocation(0), iBiggestFree(0), iTotalAllocations(0),
-    iTotalFree(0), iSlackFreeSpace(0), iFragmentation(0), iHeaderSizeA(0), iHeaderSizeF(0), iAllocationOverhead(0),
-    iFreeOverhead(0), iTotalOverhead(0), iOverhead(0), iMinLength(0), iMaxLength(0), iDebugAllocatorLibrary(EFalse)
-		{
-		}
-	
-public:
-	TBuf<KBuf> iType;
-	TUint iSize;
-	TLinAddr iBaseAddress;
-	TBool iShared;
-	TUint iChunkSize;
-	TUint iAllocationsCount;
-	TUint iFreeCount;
-	TUint iBiggestAllocation;
-	TUint iBiggestFree;
-    TUint iTotalAllocations;
-    TUint iTotalFree;
-    TUint iSlackFreeSpace;
-    TReal iFragmentation;
-    TUint iHeaderSizeA;
-    TUint iHeaderSizeF;
-    TUint iAllocationOverhead;
-    TUint iFreeOverhead;
-    TUint iTotalOverhead;
-    TReal iOverhead;
-    TInt iMinLength;
-    TInt iMaxLength;
-    TBool iDebugAllocatorLibrary;
-	};
-
-#endif // MEMSPYHEAPDATA_H
--- a/memspy/MemSpyClient/inc/memspykernelobjectdata.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  TMemSpyProcessData class
-*/
-
-#ifndef MEMSPYKERNELOBJECTDATA_H
-#define MEMSPYKERNELOBJECTDATA_H
-
-#include <memspy/driver/memspydriverenumerationsshared.h>
-
-// Constants
-const TInt KBufSize = 128;
-
-// TMemSpyProcess data class holds data to be sent to the UI
-class TMemSpyKernelObjectData 
-	{	
-public:
-	//constructor & destructor
-	inline TMemSpyKernelObjectData()
-		: iCount(0), iSize(0)
-		{
-		}
-	
-public:    
-    TMemSpyDriverContainerType iType;
-    TFullName iName;
-    TInt iCount;
-    TInt64 iSize;
-	};
-
-#endif // MEMSPYKERNELOBJECTDATA_H
--- a/memspy/MemSpyClient/inc/memspymemorytrackingcycledata.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,33 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* 
-*/
-
-
-#ifndef MEMSPYMEMORYTRACKINGCYCLEDATA_H_
-#define MEMSPYMEMORYTRACKINGCYCLEDATA_H_
-
-struct TMemSpyMemoryTrackingCycleData
-	{
-	TInt iCycleNumber;
-	TTime iTime;
-	TFullName iCaption;
-	TInt64 iFreeMemory;
-	TInt64 iMemoryDelta;
-	TInt64 iPreviousCycleDiff;
-	TInt iChangeCount;
-	};
-
-#endif /* MEMSPYMEMORYTRACKINGCYCLEDATA_H_ */
--- a/memspy/MemSpyClient/inc/memspyprocessdata.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  TMemSpyProcessData class
-*/
-
-#ifndef MEMSPYPROCESSDATA_H
-#define MEMSPYPROCESSDATA_H
-
-#include <memspy/driver/memspydriverobjectsshared.h>
-
-// TMemSpyProcess data class holds data to be sent to the UI
-class TMemSpyProcessData 
-	{	
-public:
-	//constructor & destructor
-	inline TMemSpyProcessData()
-		: iId(0), iThreadCount(0), iExitCategory(0), iExitReason(0)
-		{
-		}
-	
-public:
-    TProcessId iId;        
-    TFullName iName;
-    TProcessPriority iPriority;
-    TExitCategoryName iExitCategory;
-    TInt iExitReason;
-    TExitType iExitType;
-    TInt iThreadCount;
-    TUint32 iSID;
-    TUint32 iVID;
-    TBool iIsDead;
-	};
-
-#endif // MEMSPYPROCESSDATA_H
--- a/memspy/MemSpyClient/inc/memspyserverdata.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,37 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  TMemSpyProcessData class
-*/
-
-#ifndef MEMSPYSERVERDATA_H
-#define MEMSPYSERVERDATA_H
-
-// TMemSpyProcess data class holds data to be sent to the UI
-class TMemSpyServerData 
-	{	
-public:
-	//constructor & destructor
-	inline TMemSpyServerData()
-		: iId(0), iSessionCount(0)
-		{
-		}
-	
-public:
-    TProcessId iId;        
-    TFullName iName;
-    TInt iSessionCount;
-	};
-
-#endif // MEMSPYSERVERDATA_H
--- a/memspy/MemSpyClient/inc/memspysession.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,282 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-
-#ifndef MEMSPYSESSION_H
-#define MEMSPYSESSION_H
-
-
-// System includes
-#include <e32base.h>
-#include <u32std.h>
-
-//user includes
-#include <memspy/api/memspyapiprocess.h>
-
-#include <memspy/api/memspyapithread.h>
-#include <memspy/api/memspyapithreadinfoitem.h>
-#include <memspy/engine/memspythreadinfoitemdata.h>
-#include <memspy/engine/memspyengineobjectthreadinfoobjects.h>
-#include <memspy/engine/memspydevicewideoperations.h>
-
-#include <memspy/api/memspyapikernelobject.h>
-
-#include <memspy/api/memspyapikernelobjectitem.h> //for KernelObjectItems
-
-#include <memspy/api/memspyapiheap.h>
-
-#include <memspy/api/memspyapimemorytrackingcycle.h>
-
-#include <memspyengineclientinterface.h>
-#include <memspy/engine/memspyengineoutputsinktype.h>
-
-#include <memspy/engine/memspyenginehelpersysmemtrackerconfig.h>
-
-#include <memspy/api/memspyapiserver.h>
-
-#include <memspy/api/memspyapiecom.h>
-
-// Constants
-const TInt KMemSpyVersion           = 2;
-
-enum TSortType
-	{
-	ESortProcById,
-	ESortProcByName,
-	ESortProcByThreadCount,
-	ESortProcByCodeSegs,
-	ESortProcByHeapUsage,
-	ESortProcByStackUsage,
-	ESortServByName,
-	ESortServBySessionCount
-	};
-
-enum TMemSpyOutputType
-    {
-    EOutputTypeDebug = 0,
-    EOutputTypeFile
-    };
-
-class TMemSpyDeviceWideOperationProgress 
-	{
-public:
-	IMPORT_C TInt Progress() const;
-	IMPORT_C const TDesC& Description() const;
-	
-private:
-	TPckgBuf<TInt> iProgress;
-	TFullName iDescription;
-	
-friend class RMemSpySession;
-	};
-
-
-NONSHARABLE_CLASS( RMemSpySession ) : public RSessionBase
-    {
-public:
-    IMPORT_C RMemSpySession();
-    IMPORT_C TInt Connect();
-    
-public:	//API
-    //Thread speciifc operations
-    IMPORT_C void OutputKernelHeapDataL(); //EMemSpyClientServerOpHeapData
-    
-    IMPORT_C void OutputKernelHeapData(TRequestStatus& aStatus); //EMemSpyClientServerOpHeapData
-    
-    IMPORT_C void OutputThreadHeapDataL(TThreadId aThreadId); //EMemSpyClientServerOpHeapData
-    
-    IMPORT_C void OutputThreadHeapDataL(const TDesC& aThreadName); //EMemSpyClientServerOpHeapData
-    
-    IMPORT_C void OutputThreadCellListL(TThreadId aThreadId);//EMemSpyClientServerOpHeapCellListing    
-    
-    IMPORT_C void OutputHeapInfoUserL(TThreadId aThreadId);	//EMemSpyClientServerOpHeapInfo
-    
-    IMPORT_C void SwitchOutputSinkL( TMemSpySinkType aType); //EMemSpyClientServerOpSwitchOutputSinkFile / EMemSpyClientServerOpSwitchOutputSinkTrace
-    
-    IMPORT_C void SwitchOutputToTraceL(); // EMemSpyClientServerOpSwitchOutputSinkTrace
-    
-    IMPORT_C void SwitchOutputToFileL(const TDesC& aRootFolder); // EMemSpyClientServerOpSwitchOutputSinkFile
-    
-    IMPORT_C void OutputStackInfoL(TThreadId aThreadId); //EMemSpyClientServerOpStackInfo
-    
-    IMPORT_C void OutputStackDataL(TThreadId aThreadId, TMemSpyDriverDomainType aType ); //EMemSpyClientServerOpStackDataUser / EMemSpyClientServerOpStackDataKernel    
-    
-    IMPORT_C void OutputThreadInfoHandlesL(TThreadId aThreadId); //EMemSpyClientServerOpOutputInfoHandles
-    
-    IMPORT_C void OutputAOListL(TThreadId aId, TMemSpyThreadInfoItemType aType);	//EMemSpyClientServerOpOutputAOList    
-    
-    IMPORT_C void OutputKernelObjectsL();// EMemSpyClientServerOpEnumerateKernelContainerAll
-    
-    IMPORT_C void OutputCompactStackInfoL();// EMemSpyClientServerOpStackInfoCompact
-    
-    IMPORT_C void OutputCompactHeapInfoL();// EMemSpyClientServerOpHeapInfoCompact
-    
-    // Device Wide Operations
-    // Synchronous operations - for CLI
-    IMPORT_C void OutputHeapData();
-    
-    // Asynchronous operations
-    IMPORT_C void OutputPhoneInfo(TRequestStatus& aStatus);
-    
-    IMPORT_C void OutputDetailedPhoneInfo(TRequestStatus& aStatus);
-    
-    IMPORT_C void OutputHeapInfo(TRequestStatus& aStatus);
-    
-    IMPORT_C void OutputCompactHeapInfo(TRequestStatus &aStatus);
-    
-    IMPORT_C void OutputHeapCellListing(TRequestStatus& aStatus);
-    
-    IMPORT_C void OutputHeapData(TRequestStatus& aStatus);
-    
-    IMPORT_C void OutputStackInfo(TRequestStatus& aStatus);
-    
-    IMPORT_C void OutputCompactStackInfo(TRequestStatus &aStatus);
-    
-    IMPORT_C void OutputUserStackData(TRequestStatus& aStatus);
-    
-    IMPORT_C void OutputKernelStackData(TRequestStatus& aStatus);
-    
-    IMPORT_C void NotifyDeviceWideOperationProgress(TMemSpyDeviceWideOperationProgress &aProgress, TRequestStatus &aStatus);
-    
-    IMPORT_C void CancelDeviceWideOperationL();
-    
-    // Synchronous operations for MemSpyLauncher
-    IMPORT_C void OutputPhoneInfo();
-    
-    // "Ui" operations
-    
-    IMPORT_C void GetProcessesL(RArray<CMemSpyApiProcess*> &aProcesses, TSortType aSortType = ESortProcById);
-    
-    IMPORT_C TProcessId GetProcessIdByNameL(const TDesC& aProcessName);
-    
-    IMPORT_C void GetThreadsL(TProcessId aProcessId, RArray<CMemSpyApiThread*> &aThreads, TSortType aSortType = ESortProcById);
-    
-    IMPORT_C TInt ProcessSystemPermanentOrCritical( TProcessId aId, TBool aValue ); //aValue -> return value
-    
-    IMPORT_C void SetThreadPriorityL(TThreadId aId, TInt aPriority);
-    
-    IMPORT_C TInt EndProcessL( TProcessId aId, TMemSpyEndType aType );
-    
-    IMPORT_C TInt SwitchToProcess( TProcessId aId, TBool aBrought  );
-    
-    IMPORT_C void GetProcessIdByThreadId( TProcessId& aPID, TThreadId aTID );
-    
-    //SWMT operations
-    
-    IMPORT_C void GetMemoryTrackingCyclesL(RArray<CMemSpyApiMemoryTrackingCycle*>& aCycles);
-    
-    IMPORT_C TInt GetSwmtCyclesCount();
-    
-    IMPORT_C void SetSwmtAutoStartProcessList( CArrayFixFlat<TUid>* aList );
-    
-    IMPORT_C void SetSwmtFilter( const TDesC& aFilter );            
-    
-    IMPORT_C void SetSwmtCategoriesL(TInt aCategories);
-
-    IMPORT_C void SetSwmtHeapDumpsEnabledL(TBool aEnabled);
-    
-    IMPORT_C void SetSwmtMode(TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode aMode);      
-    
-    IMPORT_C void SwmtResetTracking();
-    
-    IMPORT_C void GetOutputSink( TMemSpySinkType& aType );
-           
-    IMPORT_C TBool IsSwmtRunningL();
-    
-    IMPORT_C void StartSwmtTimerL(TInt aPeriod);
-    
-    IMPORT_C void StartSwmtTimerL(); // for CLI
-    
-    IMPORT_C void SetSwmtTimerIntervalL(TInt aPeriod); //for CLI
-    
-    IMPORT_C void StopSwmtTimerL();
-    
-    IMPORT_C void ForceSwmtUpdateL();
-    
-    IMPORT_C void ForceSwmtUpdate(TRequestStatus& aStatus);
-    
-    IMPORT_C void GetSwmtFilter( TName& aFilter );            
-        
-    IMPORT_C void GetSwmtCategoriesL(TInt& aCategories);
-
-    IMPORT_C void GetSwmtHeapDumpsEnabledL(TBool& aEnabled);
-        
-    IMPORT_C void GetSwmtMode(TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode& aMode);
-    
-    IMPORT_C void GetSwmtTimerIntervalL(TInt& aPeriod);
-    
-    //Threads operations
-    /**
-     * 
-     */
-    IMPORT_C void GetThreadsL(TProcessId aProcessId, RArray<CMemSpyApiProcess*> &aThreads, TSortType aSortType = ESortProcById);
-    
-    IMPORT_C TInt ThreadSystemPermanentOrCritical( TThreadId aId, TBool aValue );
-        
-    IMPORT_C TInt EndThreadL( TThreadId aId, TMemSpyEndType aType );
-    
-    IMPORT_C TInt SwitchToThread( TThreadId aId, TBool aBrought );
-    
-    IMPORT_C TInt GetInfoItemType( TInt aIndex, TThreadId aId, TMemSpyThreadInfoItemType &aType );
-    
-    IMPORT_C TInt GetThreadInfoItems( RArray<CMemSpyApiThreadInfoItem*> &aInfoItems, TThreadId aId, TMemSpyThreadInfoItemType aType );
-    
-    IMPORT_C void GetThreadInfoItemsL( RArray<CMemSpyApiThreadInfoItem*> &aInfoItems, TThreadId aId, TMemSpyThreadInfoItemType aType );            
-    
-    //KernelObjects operations
-    
-    IMPORT_C void GetKernelObjectsL( RArray<CMemSpyApiKernelObject*> &aKernelObjects );
-    
-    IMPORT_C TInt GetKernelObjects( RArray<CMemSpyApiKernelObject*> &aKernelObjects );
-    
-    IMPORT_C void GetKernelObjectItemsL( RArray<CMemSpyApiKernelObjectItem*> &aKernelObjectItems, TMemSpyDriverContainerType aForContainer );
-    
-    IMPORT_C TInt GetKernelObjectItems( RArray<CMemSpyApiKernelObjectItem*> &aKernelObjectItems, TMemSpyDriverContainerType aForContainer );
-    
-    IMPORT_C void OutputAllContainerContents();
-    
-    // Heap 
-    
-    IMPORT_C CMemSpyApiHeap* GetHeapL();
-    
-	IMPORT_C CMemSpyApiHeap* GetHeap();
-	
-	IMPORT_C void DumpKernelHeap();
-	
-	// Servers
-	IMPORT_C void GetServersL(RArray<CMemSpyApiServer*> &aServers);
-	
-	IMPORT_C void GetServersL(RArray<CMemSpyApiServer*> &aServers, TSortType aSortType); 
-	
-	IMPORT_C void ServerListOutputGenericL( TBool aDetailed );
-		
-	// ECom
-
-	IMPORT_C void GetEComCategoriesL(RArray<CMemSpyApiEComCategory*> &aCategories);
-	
-	IMPORT_C void GetEComInterfacesL(TUid aCategory, RArray<CMemSpyApiEComInterface*> &aInterfaces);
-	
-	IMPORT_C void GetEComImplementationsL(TUid aInterface, RArray<CMemSpyApiEComImplementation*> &aImplementations);
-	
-private:
-    TInt StartServer();       
-    
-    void SetOutputTypeL(TMemSpyOutputType aOutputType);
-    
-    };
-
-#endif // MEMSPYSESSION_H
--- a/memspy/MemSpyClient/inc/memspythreaddata.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#ifndef MEMSPYTHREADDATA_H
-#define MEMSPYTHREADDATA_H
-
-//#include <kernel/arm/arm_types.h>
-
-class TMemSpyThreadData {
-public:
-	TMemSpyThreadData()
-	: iId(0), iPid(0), iSID(0), iVID(0), iRequestCount(0), iThreadHandles(0), iProcessHandles(0), iThreadNumberUsing(0), 
-	  iProcessNumberUsing(0), iAttributes(0), iCpuUse(0)
-		{
-		}
-	
-public:
-    TThreadId iId;
-    TProcessId iPid;    
-    TFullName iName;    //name without formatting. Formatting to be moved to the Avkon UI part
-    TInt iSID;
-    TInt iVID;
-    TThreadPriority iThreadPriority;
-    TProcessPriority iProcessPriority;
-    TInt iRequestCount;
-    TInt iThreadHandles;
-    TInt iProcessHandles;
-    TInt iThreadNumberUsing;
-    TInt iProcessNumberUsing;
-    TInt iAttributes;
-    TInt iCpuUse;        
-    TExitType iExitType;
-    RArray<TUint> iRegisters; //containts register contents of the thread (R00-R12, SP, LR, PC, Flags & DACR) - TUint for formating to HEX    
-};
-
-#endif
--- a/memspy/MemSpyClient/inc/memspythreadinfoitemdata.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,37 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* Contains the declaration of  TMemSpyProcessData class
-*/
-
-#ifndef MEMSPYTHREADINFOITEMDATA_H
-#define MEMSPYTHREADINFOITEMDATA_H
-
-#include <memspy/driver/memspydriverobjectsshared.h>
-
-// TMemSpyProcess data class holds data to be sent to the UI
-class TMemSpyThreadInfoItemData 
-	{	
-public:
-	//constructor & destructor
-	inline TMemSpyThreadInfoItemData()		
-		{
-		}
-	
-public:
-    TBuf<64> iCaption;
-    TBuf<32> iValue;
-	};
-
-#endif // MEMSPYTHREADINFOITEMDATA_H
--- a/memspy/MemSpyClient/src/memspyapiecom.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,190 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <f32file.h>
-#include <memspy/api/memspyapiecom.h>
-#include <memspy/engine/memspyengine.h>
-#include <memspy/engine/memspyecomdata.h>
-
-
-EXPORT_C CMemSpyApiEComCategory::~CMemSpyApiEComCategory()
-	{
-	delete iData;
-	}
-
-EXPORT_C TUid CMemSpyApiEComCategory::Id() const
-	{
-	return iData->iId;
-	}
-
-EXPORT_C const TDesC& CMemSpyApiEComCategory::Name() const
-	{
-	return iData->iName;
-	}
-
-EXPORT_C TInt CMemSpyApiEComCategory::InterfaceCount() const
-    {
-    return iData->iInterfaceCount;
-    }
-
-void CMemSpyApiEComCategory::ConstructL(const TMemSpyEComCategoryData& aData)
-	{
-	iData = new (ELeave) TMemSpyEComCategoryData( aData );
-	}
-
-CMemSpyApiEComCategory* CMemSpyApiEComCategory::NewL(const TMemSpyEComCategoryData& aData)
-	{
-    CMemSpyApiEComCategory* self = CMemSpyApiEComCategory::NewLC( aData );
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiEComCategory* CMemSpyApiEComCategory::NewLC(const TMemSpyEComCategoryData& aData)
-	{
-    CMemSpyApiEComCategory* self = new (ELeave) CMemSpyApiEComCategory;
-	CleanupStack::PushL( self );
-	self->ConstructL( aData );
-	return ( self );
-	}
-
-
-
-
-
-
-
-
-EXPORT_C CMemSpyApiEComInterface::~CMemSpyApiEComInterface()
-    {
-    delete iData;
-    }
-
-EXPORT_C TUid CMemSpyApiEComInterface::Id() const
-    {
-    return iData->iId;
-    }
-
-EXPORT_C const TDesC& CMemSpyApiEComInterface::Name() const
-    {
-    return iData->iName;
-    }
-
-EXPORT_C TInt CMemSpyApiEComInterface::ImplementationCount() const
-    {
-    return iData->iImplementationCount;
-    }
-
-void CMemSpyApiEComInterface::ConstructL(const TMemSpyEComInterfaceData& aData)
-    {
-    iData = new (ELeave) TMemSpyEComInterfaceData( aData );
-    }
-
-CMemSpyApiEComInterface* CMemSpyApiEComInterface::NewL(const TMemSpyEComInterfaceData& aData)
-    {
-    CMemSpyApiEComInterface* self = CMemSpyApiEComInterface::NewLC( aData );
-    CleanupStack::Pop(self);
-    return (self);
-    }
-
-CMemSpyApiEComInterface* CMemSpyApiEComInterface::NewLC(const TMemSpyEComInterfaceData& aData)
-    {
-    CMemSpyApiEComInterface* self = new (ELeave) CMemSpyApiEComInterface;
-    CleanupStack::PushL( self );
-    self->ConstructL( aData );
-    return ( self );
-    }
-
-
-
-
-
-
-
-EXPORT_C CMemSpyApiEComImplementation::~CMemSpyApiEComImplementation()
-    {
-    delete iData;
-    }
-
-EXPORT_C TUid CMemSpyApiEComImplementation::ImplementationUid() const
-    {
-    return iData->iImplementationUid;
-    }
-    
-EXPORT_C const TDesC& CMemSpyApiEComImplementation::Name() const
-    {
-    return iData->iName;
-    }
-    
-EXPORT_C TInt CMemSpyApiEComImplementation::Version() const
-    {
-    return iData->iVersion;
-    }
-    
-EXPORT_C const TDesC& CMemSpyApiEComImplementation::DataType() const
-    {
-    return iData->iDataType;
-    }
-        
-EXPORT_C const TDesC& CMemSpyApiEComImplementation::OpaqueData() const
-    {
-    return iData->iOpaqueData;
-    }
-    
-EXPORT_C TDriveUnit CMemSpyApiEComImplementation::Drive() const
-    {
-    return iData->iDrive;
-    }
-        
-EXPORT_C TBool CMemSpyApiEComImplementation::RomOnly() const
-    {
-    return iData->iRomOnly;
-    }
-        
-EXPORT_C TBool CMemSpyApiEComImplementation::RomBased() const
-    {
-    return iData->iRomBased;
-    }
-        
-EXPORT_C TVendorId CMemSpyApiEComImplementation::VendorId() const
-    {
-    return iData->iVendorId;
-    }
-        
-EXPORT_C TBool CMemSpyApiEComImplementation::Disabled() const
-    {
-    return iData->iDisabled;
-    }
-
-void CMemSpyApiEComImplementation::ConstructL(const TMemSpyEComImplementationData& aData)
-    {
-    iData = new (ELeave) TMemSpyEComImplementationData( aData );
-    }
-
-CMemSpyApiEComImplementation* CMemSpyApiEComImplementation::NewL(const TMemSpyEComImplementationData& aData)
-    {
-    CMemSpyApiEComImplementation* self = CMemSpyApiEComImplementation::NewLC( aData );
-    CleanupStack::Pop(self);
-    return (self);
-    }
-
-CMemSpyApiEComImplementation* CMemSpyApiEComImplementation::NewLC(const TMemSpyEComImplementationData& aData)
-    {
-    CMemSpyApiEComImplementation* self = new (ELeave) CMemSpyApiEComImplementation;
-    CleanupStack::PushL( self );
-    self->ConstructL( aData );
-    return ( self );
-    }
--- a/memspy/MemSpyClient/src/memspyapiheap.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,162 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <memspy/api/memspyapiheap.h>
-#include <memspy/engine/memspyengine.h>
-#include <memspy/engine/memspyheapdata.h>
-
-
-CMemSpyApiHeap::CMemSpyApiHeap() 
-	: iHeapData(0)
-	{
-	}
-
-EXPORT_C CMemSpyApiHeap::~CMemSpyApiHeap()
-	{
-	delete iHeapData;
-	}
-
-void CMemSpyApiHeap::ConstructL(const TMemSpyHeapData& aData)
-	{
-	iHeapData = new (ELeave) TMemSpyHeapData(aData);
-	}
-
-CMemSpyApiHeap* CMemSpyApiHeap::NewL(const TMemSpyHeapData& aData)
-	{
-	CMemSpyApiHeap* self = CMemSpyApiHeap::NewLC(aData);
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiHeap* CMemSpyApiHeap::NewLC(const TMemSpyHeapData& aData)
-	{
-	CMemSpyApiHeap* self = new (ELeave) CMemSpyApiHeap;
-	CleanupStack::PushL(self);
-	self->ConstructL(aData);
-	return (self);
-	}
-
-//api methods
-EXPORT_C TDesC& CMemSpyApiHeap::Type()
-	{
-	return iHeapData->iType;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::Size()
-	{
-	return iHeapData->iSize;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::BaseAddress()
-	{
-	return iHeapData->iBaseAddress;
-	}
-
-EXPORT_C TBool CMemSpyApiHeap::Shared()
-	{
-	return iHeapData->iShared;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::ChunkSize()
-	{
-	return iHeapData->iChunkSize;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::AllocationsCount()
-	{
-	return iHeapData->iAllocationsCount;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::FreeCount()
-	{
-	return iHeapData->iFreeCount;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::BiggestAllocation()
-	{
-	return iHeapData->iBiggestAllocation;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::BiggestFree()
-	{
-	return iHeapData->iBiggestFree;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::TotalAllocations()
-	{
-	return iHeapData->iTotalAllocations;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::TotalFree()
-	{
-	return iHeapData->iTotalFree;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::SlackFreeSpace()
-	{
-	return iHeapData->iSlackFreeSpace;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::Fragmentation()
-	{
-	return iHeapData->iFragmentation;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::HeaderSizeA()
-	{
-	return iHeapData->iHeaderSizeA;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::HeaderSizeF()
-	{
-	return iHeapData->iHeaderSizeF;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::AllocationOverhead()
-	{
-	return iHeapData->iAllocationOverhead;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::FreeOverhead()
-	{
-	return iHeapData->iFreeOverhead;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::TotalOverhead()
-	{
-	return iHeapData->iTotalOverhead;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::Overhead()
-	{
-	return iHeapData->iOverhead;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::MinLength()
-	{
-	return iHeapData->iMinLength;
-	}
-
-EXPORT_C TInt CMemSpyApiHeap::MaxLength()
-	{
-	return iHeapData->iMaxLength;
-	}
-
-EXPORT_C TBool CMemSpyApiHeap::DebugAllocatorLibrary()
-	{
-	return iHeapData->iDebugAllocatorLibrary;
-	}
--- a/memspy/MemSpyClient/src/memspyapikernelobject.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,72 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <memspy/api/memspyapikernelobject.h>
-#include <memspy/engine/memspykernelobjectdata.h>
-//#include <memspy/engine/memspyengineobjectprocess.h>
-//#include <memspy/engine/memspyengineobjectcontainer.h>
-
-
-EXPORT_C CMemSpyApiKernelObject::~CMemSpyApiKernelObject()
-	{
-	delete iKernelObjectData;
-	}
-
-
-CMemSpyApiKernelObject::CMemSpyApiKernelObject() : iKernelObjectData(0)
-	{
-	}
-
-CMemSpyApiKernelObject* CMemSpyApiKernelObject::NewL(const TMemSpyKernelObjectData& aData)
-	{
-	CMemSpyApiKernelObject* self = CMemSpyApiKernelObject::NewLC(aData);
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiKernelObject* CMemSpyApiKernelObject::NewLC(const TMemSpyKernelObjectData& aData)
-	{
-	CMemSpyApiKernelObject* self = new (ELeave) CMemSpyApiKernelObject;
-	CleanupStack::PushL(self);
-	self->ConstructL(aData);
-	return (self);
-	}
-
-void CMemSpyApiKernelObject::ConstructL(const TMemSpyKernelObjectData& aData)
-	{
-	iKernelObjectData = new (ELeave) TMemSpyKernelObjectData(aData);
-	}
-
-EXPORT_C TMemSpyDriverContainerType CMemSpyApiKernelObject::Type() const
-	{
-	return iKernelObjectData->iType;
-	}
-
-EXPORT_C const TDesC& CMemSpyApiKernelObject::Name() const
-	{
-	return iKernelObjectData->iName;
-	}
-					
-EXPORT_C TInt CMemSpyApiKernelObject::Count() const
-	{
-	return iKernelObjectData->iCount;
-	}
-	
-EXPORT_C TInt64 CMemSpyApiKernelObject::Size() const
-	{
-	return iKernelObjectData->iSize;
-	}
--- a/memspy/MemSpyClient/src/memspyapikernelobjectitem.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,309 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <memspy/api/memspyapikernelobjectitem.h>
-#include <memspy/driver/memspydriverobjectsshared.h>
-
-EXPORT_C CMemSpyApiKernelObjectItem::~CMemSpyApiKernelObjectItem()
-	{
-	delete iItem;
-	}
-
-
-CMemSpyApiKernelObjectItem::CMemSpyApiKernelObjectItem() : iItem(0)
-	{
-	}
-
-CMemSpyApiKernelObjectItem* CMemSpyApiKernelObjectItem::NewL(const TMemSpyDriverHandleInfoGeneric& aData)
-	{
-	CMemSpyApiKernelObjectItem* self = CMemSpyApiKernelObjectItem::NewLC(aData);
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiKernelObjectItem* CMemSpyApiKernelObjectItem::NewLC(const TMemSpyDriverHandleInfoGeneric& aData)
-	{
-	CMemSpyApiKernelObjectItem* self = new (ELeave) CMemSpyApiKernelObjectItem;
-	CleanupStack::PushL(self);
-	self->ConstructL(aData);
-	return (self);
-	}
-
-void CMemSpyApiKernelObjectItem::ConstructL(const TMemSpyDriverHandleInfoGeneric& aData)
-	{
-	iItem = new (ELeave) TMemSpyDriverHandleInfoGeneric(aData);
-	}
-
-EXPORT_C const TDesC8& CMemSpyApiKernelObjectItem::Name() const
-	{
-	/*
-	TBuf<KMaxName> ret;	
-	ret.Copy( iItem->iName );
-	return ret;
-	*/
-	return iItem->iName;
-	}
-
-EXPORT_C TAny* CMemSpyApiKernelObjectItem::Handle() const
-	{	
-	return iItem->iHandle;
-	}
-
-EXPORT_C TMemSpyDriverContainerType CMemSpyApiKernelObjectItem::Type() const
-	{
-	return iItem->iType;
-	}
-
-// For Process, thread, chunk (owning process id), server (owning thread id)
-EXPORT_C TInt CMemSpyApiKernelObjectItem::Id() const
-	{
-	return iItem->iId;
-	}
-
-// For Chunk, Library
-EXPORT_C TUint32 CMemSpyApiKernelObjectItem::Size() const
-	{
-	return iItem->iSize;
-	}
-
-// For Semaphore, Mutex, Server
-EXPORT_C TInt CMemSpyApiKernelObjectItem::Count() const
-	{
-	return iItem->iCount;
-	}
-
-// For Mutex
-EXPORT_C TInt CMemSpyApiKernelObjectItem::WaitCount() const
-	{
-	return iItem->iWaitCount;
-	}
-
-// For Server, Session
-EXPORT_C TIpcSessionType CMemSpyApiKernelObjectItem::SessionType() const
-	{
-	return iItem->iSessionType;
-	}
-
-// For Timer
-EXPORT_C TMemSpyDriverTimerType CMemSpyApiKernelObjectItem::TimerType() const
-	{
-	return iItem->iTimerType;
-	}
-
-EXPORT_C TMemSpyDriverTimerState CMemSpyApiKernelObjectItem::TimerState() const
-	{
-	return iItem->iTimerState;
-	}
-
-// For Logical channel
-EXPORT_C TInt CMemSpyApiKernelObjectItem::OpenChannels()
-	{
-	return iItem->iOpenChannels;
-	}
-
-// For most of the object types
-EXPORT_C const TDesC8& CMemSpyApiKernelObjectItem::NameDetail() const
-	{
-	/*
-	TBuf<KMaxName> ret;
-	ret.Copy( iItem->iNameDetail );
-	return ret;
-	*/
-	return iItem->iNameDetail;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::AccessCount() const
-	{
-	return iItem->iAccessCount;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::UniqueID() const
-	{
-	return iItem->iUniqueID;
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::Protection() const
-	{
-	return iItem->iProtection;
-	}
-		
-EXPORT_C TUint8* CMemSpyApiKernelObjectItem::AddressOfKernelOwner()
-	{
-	return iItem->iAddressOfKernelOwner;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::Priority() const
-	{
-	return iItem->iPriority;
-	}
-
-EXPORT_C TUint8* CMemSpyApiKernelObjectItem::AddressOfOwningProcess()
-	{
-	return iItem->iAddressOfOwningProcess;
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::CreatorId() const
-	{
-	return iItem->iCreatorId;
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::SecurityZone() const
-	{
-	return iItem->iSecurityZone;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::Attributes() const
-	{
-	return iItem->iAttributes;
-	}
-
-EXPORT_C TUint8* CMemSpyApiKernelObjectItem::AddressOfDataBssStackChunk()
-	{
-	return iItem->iAddressOfDataBssStackChunk;
-	}
-
-// For Server, Session
-EXPORT_C TUint8* CMemSpyApiKernelObjectItem::AddressOfOwningThread()
-	{
-	return iItem->iAddressOfOwningThread;
-	}
-
-EXPORT_C TUint8* CMemSpyApiKernelObjectItem::AddressOfServer()
-	{
-	return iItem->iAddressOfServer;
-	}
-
-EXPORT_C TUint16 CMemSpyApiKernelObjectItem::TotalAccessCount() const
-	{
-	return iItem->iTotalAccessCount;
-	}
-
-EXPORT_C TUint8 CMemSpyApiKernelObjectItem::SvrSessionType() const
-	{
-	return iItem->iSvrSessionType;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::MsgCount() const
-	{
-	return iItem->iMsgCount;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::MsgLimit() const
-	{
-	return iItem->iMsgLimit;
-	}
-
-// For chunk
-EXPORT_C TInt CMemSpyApiKernelObjectItem::MaxSize() const
-	{
-	return iItem->iMaxSize;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::Bottom() const
-	{
-	return iItem->iBottom;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::Top() const
-	{
-	return iItem->iTop;
-	}
-
-EXPORT_C TInt CMemSpyApiKernelObjectItem::StartPos() const
-	{
-	return iItem->iStartPos;
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::ControllingOwner() const
-	{
-	return iItem->iControllingOwner;
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::Restrictions() const
-	{
-	return iItem->iRestrictions;
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::MapAttr() const
-	{
-	return iItem->iMapAttr;
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::ChunkType() const
-	{
-	return iItem->iChunkType;
-	}
-
-EXPORT_C const TDesC8& CMemSpyApiKernelObjectItem::NameOfOwner() const
-	{
-	/*
-	TBuf<KMaxName> ret;
-	ret.Copy( iItem->iNameOfOwner );
-	return ret;
-	*/
-	return iItem->iNameOfOwner;
-	}
-
-// For library
-EXPORT_C TInt CMemSpyApiKernelObjectItem::MapCount() const
-	{
-	return iItem->iMapCount;
-	}
-
-EXPORT_C TUint8 CMemSpyApiKernelObjectItem::State() const
-	{
-	return iItem->iState;
-	}
-
-EXPORT_C TUint8* CMemSpyApiKernelObjectItem::AddressOfCodeSeg()
-	{
-	return iItem->iAddressOfCodeSeg;
-	}
-
-// Semaphore, mutex, condvar
-EXPORT_C TUint8 CMemSpyApiKernelObjectItem::Resetting() const
-	{
-	return iItem->iResetting;
-	}
-
-EXPORT_C TUint8 CMemSpyApiKernelObjectItem::Order() const
-	{
-	return iItem->iOrder;
-	}
-
-// For Logical/Physical device
-EXPORT_C TVersion CMemSpyApiKernelObjectItem::Version() const
-	{
-	return iItem->iVersion;
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::ParseMask() const
-	{
-	return iItem->iParseMask;	
-	}
-
-EXPORT_C TUint CMemSpyApiKernelObjectItem::UnitsMask() const
-	{
-	return iItem->iUnitsMask;
-	}
-
-// For change notifier
-EXPORT_C TUint CMemSpyApiKernelObjectItem::Changes() const
-	{
-	return iItem->iChanges;
-	}
-
--- a/memspy/MemSpyClient/src/memspyapimemorytrackingcycle.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,83 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* 
-*/
-
-#include <memspy/api/memspyapimemorytrackingcycle.h>
-#include <memspy/engine/memspymemorytrackingcycledata.h>
-
-EXPORT_C TInt CMemSpyApiMemoryTrackingCycle::CycleNumber() const
-	{
-	return iData->iCycleNumber;	
-	}
-
-EXPORT_C const TTime& CMemSpyApiMemoryTrackingCycle::Time() const
-	{
-	return iData->iTime;	
-	}
-
-EXPORT_C const TDesC& CMemSpyApiMemoryTrackingCycle::Caption() const
-	{
-	return iData->iCaption;	
-	}
-
-EXPORT_C const TInt64& CMemSpyApiMemoryTrackingCycle::FreeMemory() const
-	{
-	return iData->iFreeMemory;
-	}
-
-EXPORT_C TInt64 CMemSpyApiMemoryTrackingCycle::MemoryDelta() const
-	{
-	return iData->iMemoryDelta;
-	}
-
-EXPORT_C TInt64 CMemSpyApiMemoryTrackingCycle::PreviousCycleDiff() const
-	{
-	return iData->iPreviousCycleDiff;
-	}
-
-EXPORT_C TInt CMemSpyApiMemoryTrackingCycle::ChangeCount() const
-	{
-	return iData->iChangeCount;
-	}
-
-EXPORT_C CMemSpyApiMemoryTrackingCycle::~CMemSpyApiMemoryTrackingCycle()
-	{
-	delete iData;
-	}
-
-CMemSpyApiMemoryTrackingCycle* CMemSpyApiMemoryTrackingCycle::NewL(const TMemSpyMemoryTrackingCycleData& aData)
-	{
-	CMemSpyApiMemoryTrackingCycle* self = CMemSpyApiMemoryTrackingCycle::NewLC(aData);
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiMemoryTrackingCycle* CMemSpyApiMemoryTrackingCycle::NewLC(const TMemSpyMemoryTrackingCycleData& aData)
-	{
-	CMemSpyApiMemoryTrackingCycle* self = new (ELeave) CMemSpyApiMemoryTrackingCycle;
-	CleanupStack::PushL(self);
-	self->ConstructL(aData);
-	return self;
-	}
-
-CMemSpyApiMemoryTrackingCycle::CMemSpyApiMemoryTrackingCycle()
-	{
-	}
-
-void CMemSpyApiMemoryTrackingCycle::ConstructL(const TMemSpyMemoryTrackingCycleData& aData)
-	{
-	iData = new (ELeave) TMemSpyMemoryTrackingCycleData(aData);
-	}
--- a/memspy/MemSpyClient/src/memspyapiprocess.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,103 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <memspy/api/memspyapiprocess.h>
-#include <memspy/engine/memspyengine.h>
-#include <memspy/engine/memspyprocessdata.h>
-#include <memspy/engine/memspyengineobjectprocess.h>
-#include <memspy/engine/memspyengineobjectcontainer.h>
-
-
-EXPORT_C CMemSpyApiProcess::~CMemSpyApiProcess()
-	{
-	delete iProcessData;
-	}
-
-EXPORT_C TProcessId CMemSpyApiProcess::Id() const
-	{
-	return iProcessData->iId;
-	}
-
-EXPORT_C const TDesC& CMemSpyApiProcess::Name() const
-	{
-	return iProcessData->iName;
-	}
-
-EXPORT_C TExitCategoryName CMemSpyApiProcess::ExitCategory() const
-	{
-	return iProcessData->iExitCategory;
-	}
-	
-EXPORT_C TInt CMemSpyApiProcess::ExitReason() const
-	{
-	return iProcessData->iExitReason;
-	}
-	
-EXPORT_C TExitType CMemSpyApiProcess::ExitType() const
-	{
-	return iProcessData->iExitType;
-	}
-	
-EXPORT_C TInt CMemSpyApiProcess::ThreadCount() const
-	{
-	return iProcessData->iThreadCount;
-	}
-
-EXPORT_C TUint32 CMemSpyApiProcess::SID() const
-	{
-	return iProcessData->iSID;
-	}
-
-EXPORT_C TUint32 CMemSpyApiProcess::VID() const
-	{
-	return iProcessData->iSID;
-	}
-
-EXPORT_C TProcessPriority CMemSpyApiProcess::Priority() const
-	{
-	return iProcessData->iPriority;
-	}
-
-EXPORT_C TBool CMemSpyApiProcess::IsDead() const
-    {
-    return iProcessData->iIsDead;
-    }
-
-CMemSpyApiProcess::CMemSpyApiProcess() : iProcessData(0)
-	{
-	}
-
-void CMemSpyApiProcess::ConstructL(const TMemSpyProcessData& aData)
-	{
-	iProcessData = new (ELeave) TMemSpyProcessData(aData);
-	}
-
-CMemSpyApiProcess* CMemSpyApiProcess::NewL(const TMemSpyProcessData& aData)
-	{
-	CMemSpyApiProcess* self = CMemSpyApiProcess::NewLC(aData);
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiProcess* CMemSpyApiProcess::NewLC(const TMemSpyProcessData& aData)
-	{
-	CMemSpyApiProcess* self = new (ELeave) CMemSpyApiProcess;
-	CleanupStack::PushL(self);
-	self->ConstructL(aData);
-	return (self);
-	}
-
--- a/memspy/MemSpyClient/src/memspyapiserver.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <memspy/api/memspyapiserver.h>
-#include <memspy/engine/memspyengine.h>
-#include <memspy/engine/memspyserverdata.h>
-
-EXPORT_C CMemSpyApiServer::~CMemSpyApiServer()
-	{
-	delete iData;
-	}
-
-EXPORT_C TProcessId CMemSpyApiServer::Id() const
-	{
-	return iData->iId;
-	}
-
-EXPORT_C const TDesC& CMemSpyApiServer::Name() const
-	{
-	return iData->iName;
-	}
-	
-EXPORT_C TInt CMemSpyApiServer::SessionCount() const
-	{
-	return iData->iSessionCount;
-	}
-
-CMemSpyApiServer::CMemSpyApiServer() : iData(0)
-	{
-	}
-
-void CMemSpyApiServer::ConstructL(const TMemSpyServerData& aData)
-	{
-	iData = new (ELeave) TMemSpyServerData(aData);
-	}
-
-CMemSpyApiServer* CMemSpyApiServer::NewL(const TMemSpyServerData& aData)
-	{
-    CMemSpyApiServer* self = CMemSpyApiServer::NewLC(aData);
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiServer* CMemSpyApiServer::NewLC(const TMemSpyServerData& aData)
-	{
-    CMemSpyApiServer* self = new (ELeave) CMemSpyApiServer;
-	CleanupStack::PushL(self);
-	self->ConstructL(aData);
-	return (self);
-	}
-
--- a/memspy/MemSpyClient/src/memspyapithread.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,125 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <memspy/api/memspyapithread.h>
-#include <memspy/engine/memspythreaddata.h>
-
-
-EXPORT_C CMemSpyApiThread::~CMemSpyApiThread()
-	{
-	delete iThreadData;
-	}
-
-EXPORT_C TThreadId CMemSpyApiThread::Id() const
-	{
-	return iThreadData->iId;
-	}
-
-EXPORT_C TProcessId CMemSpyApiThread::ProcessId() const
-	{
-	return iThreadData->iPid;
-	}
-
-EXPORT_C const TDesC& CMemSpyApiThread::Name() const
-	{
-	return iThreadData->iName;
-	}
-
-EXPORT_C TInt CMemSpyApiThread::SID() const
-	{
-	return iThreadData->iSID;
-	}
-
-
-EXPORT_C TInt CMemSpyApiThread::VID() const
-	{
-	return iThreadData->iVID;
-	}
-
-EXPORT_C TThreadPriority CMemSpyApiThread::ThreadPriority() const
-	{
-	return iThreadData->iThreadPriority;
-	}
-
-EXPORT_C TProcessPriority CMemSpyApiThread::ProcessPriority() const
-	{
-	return iThreadData->iProcessPriority;
-	}
-
-EXPORT_C TInt CMemSpyApiThread::RequestCount() const
-	{
-	return iThreadData->iRequestCount;
-	}
-
-EXPORT_C TInt CMemSpyApiThread::ThreadHandles() const
-	{
-	return iThreadData->iThreadHandles;
-	}
-
-EXPORT_C TInt CMemSpyApiThread::ProcessHandles() const
-	{
-	return iThreadData->iProcessHandles;
-	}
-
-EXPORT_C TInt CMemSpyApiThread::ThreadNumberUsing() const
-	{
-	return iThreadData->iThreadNumberUsing;
-	}
-
-EXPORT_C TInt CMemSpyApiThread::ProcessNumberUsing() const
-	{
-	return iThreadData->iProcessNumberUsing;
-	}
-
-EXPORT_C TInt CMemSpyApiThread::Attributes() const
-	{
-	return iThreadData->iAttributes;
-	}
-
-EXPORT_C TInt CMemSpyApiThread::CpuUse() const
-	{
-	return iThreadData->iCpuUse;
-	}
-
-EXPORT_C TExitType CMemSpyApiThread::ExitType() const
-	{
-	return iThreadData->iExitType;
-	}
-
-CMemSpyApiThread::CMemSpyApiThread() : iThreadData(0)
-	{
-	}
-
-void CMemSpyApiThread::ConstructL(const TMemSpyThreadData& aData)
-	{
-	iThreadData = new (ELeave) TMemSpyThreadData(aData);
-	}
-
-CMemSpyApiThread* CMemSpyApiThread::NewL(const TMemSpyThreadData& aData)
-	{
-	CMemSpyApiThread* self = CMemSpyApiThread::NewLC(aData);
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiThread* CMemSpyApiThread::NewLC(const TMemSpyThreadData& aData)
-	{
-	CMemSpyApiThread* self = new (ELeave) CMemSpyApiThread;
-	CleanupStack::PushL(self);
-	self->ConstructL(aData);
-	return (self);
-	}
--- a/memspy/MemSpyClient/src/memspyapithreadinfoitem.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,60 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <memspy/api/memspyapithreadinfoitem.h>
-#include <memspy/engine/memspyengine.h>
-#include <memspy/engine/memspythreadinfoitemdata.h>
-
-EXPORT_C CMemSpyApiThreadInfoItem::~CMemSpyApiThreadInfoItem()
-	{
-	delete iInfoItem;
-	}
-
-EXPORT_C const TDesC& CMemSpyApiThreadInfoItem::Caption() const
-	{
-	return iInfoItem->iCaption;
-	}
-
-EXPORT_C const TDesC& CMemSpyApiThreadInfoItem::Value() const
-	{
-	return iInfoItem->iValue;
-	}
-
-CMemSpyApiThreadInfoItem::CMemSpyApiThreadInfoItem() : iInfoItem(0)
-	{
-	}
-
-void CMemSpyApiThreadInfoItem::ConstructL(const TMemSpyThreadInfoItemData& aData)
-	{
-	iInfoItem = new (ELeave) TMemSpyThreadInfoItemData(aData);
-	}
-
-CMemSpyApiThreadInfoItem* CMemSpyApiThreadInfoItem::NewL(const TMemSpyThreadInfoItemData& aData)
-	{
-	CMemSpyApiThreadInfoItem* self = CMemSpyApiThreadInfoItem::NewLC(aData);
-	CleanupStack::Pop(self);
-	return (self);
-	}
-
-CMemSpyApiThreadInfoItem* CMemSpyApiThreadInfoItem::NewLC(const TMemSpyThreadInfoItemData& aData)
-	{
-	CMemSpyApiThreadInfoItem* self = new (ELeave) CMemSpyApiThreadInfoItem;
-	CleanupStack::PushL(self);
-	self->ConstructL(aData);
-	return (self);
-	}
-
--- a/memspy/MemSpyClient/src/memspysession.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,908 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-
-#include "memspysession.h"
-
-#include <memspyengineclientinterface.h>
-// API
-#include <memspy/engine/memspyprocessdata.h>
-#include <memspy/engine/memspythreaddata.h> 
-#include <memspy/engine/memspykernelobjectdata.h>
-#include <memspy/engine/memspyheapdata.h>
-#include <memspy/engine/memspymemorytrackingcycledata.h>
-//KernelObjects
-#include <memspy/driver/memspydriverenumerationsshared.h>
-// Servers
-#include <memspy/engine/memspyserverdata.h>
-// ECom
-#include <memspy/engine/memspyecomdata.h>
-
-// IMPLEMENTATION
-
-EXPORT_C RMemSpySession::RMemSpySession()
-    {
-    }
-
-
-EXPORT_C TInt RMemSpySession::Connect()
-    {
-	TInt error(KErrNone);
-	
-	for (TInt i=0; i<2; i++) // Two retries max
-		{
-		TInt error = CreateSession(KMemSpyServerName, TVersion(KMemSpyVersion, 0, 0));
-		
-		if (error != KErrNotFound && error != KErrServerTerminated)
-			return error;
-		
-		error = StartServer();
-		
-		if (error != KErrNone && error != KErrAlreadyExists)
-			return error;
-		}
-	
-	return error;	
-    }
-
-TInt RMemSpySession::StartServer()
-	{
-	RProcess server;
-	_LIT(KCommand, "start");
-	const TUid KServerUid3 = {0xE5883BC2};
-	TInt error = server.Create(KMemSpyServerName, KCommand);//, KServerUid3);
-	
-	if (error != KErrNone)
-		return error;
-	
-	TRequestStatus startStatus, stopStatus;
-	server.Logon(stopStatus);
-	if (stopStatus != KRequestPending)
-		{
-		User::WaitForRequest(stopStatus);
-		server.Kill(0);
-		server.Close();
-		return stopStatus.Int();
-		}
-	
-	server.Rendezvous(startStatus);
-	server.Resume();
-	User::WaitForRequest(startStatus, stopStatus);
-	if (startStatus == KRequestPending)
-		{
-		// not started yet, i.e. stopStatus was signaled
-		server.Close();
-		return stopStatus.Int();
-		}
-	
-	// Rendezvous was called - the server is ready
-	
-	// We first need to cancel Logon
-	server.LogonCancel(stopStatus);
-	// We don't need this anymore
-	server.Close();
-	// Wait for LogonCancel to complete
-	User::WaitForRequest(stopStatus);
-
-	// Everything went OK
-	return KErrNone;
-	}
-
-EXPORT_C void RMemSpySession::GetProcessesL(RArray<CMemSpyApiProcess*> &aProcesses, TSortType aSortType)
-	{
-	TPckgBuf<TInt> count;
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetProcessCount, TIpcArgs(&count)));
-	
-	TInt requestedCount = count();
-	HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyProcessData));
-	TPtr8 bufferPtr(buffer->Des());
-	
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetProcesses, TIpcArgs(&count, &bufferPtr)));
-	aProcesses.Reset();
-	
-	TInt receivedCount = Min(count(), requestedCount);
-	for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyProcessData))
-		{
-		TPckgBuf<TMemSpyProcessData> data;
-		data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyProcessData));
-		aProcesses.AppendL(CMemSpyApiProcess::NewLC(data()));
-		}
-	CleanupStack::Pop(aProcesses.Count());
-	CleanupStack::PopAndDestroy(buffer);
-	}
-
-EXPORT_C TProcessId RMemSpySession::GetProcessIdByNameL(const TDesC& aProcessName)
-	{
-	TPckgBuf<TProcessId> procId;
-	User::LeaveIfError(SendReceive(EMemSpyClienServerOpGetProcessIdByName, 
-			TIpcArgs(&aProcessName, &procId)));
-	
-	return procId();
-	}
-
-EXPORT_C TInt RMemSpySession::ProcessSystemPermanentOrCritical( TProcessId aId, TBool aValue )
-	{
-	TPckgBuf<TProcessId> arg1( aId );
-	TPckgBuf<TBool> arg2( aValue );
-	TIpcArgs args( &arg1, &arg2 );
-		
-	TInt error = SendReceive( EMemSpyClientServerOpProcessSystemPermanentOrCritical, args );
-	
-	aValue = arg2();
-	
-	return error;
-	}
-
-EXPORT_C TInt RMemSpySession::EndProcessL( TProcessId aId, TMemSpyEndType aType )
-	{
-	TPckgBuf<TProcessId> arg1( aId );
-	TPckgBuf<TMemSpyEndType> arg2( aType );
-	TIpcArgs args( &arg1, &arg2 );
-	
-	TInt error = SendReceive( EMemSpyClientServerOpEndProcess, args );
-	
-	return error;
-	}
-
-EXPORT_C TInt RMemSpySession::SwitchToProcess( TProcessId aId, TBool aBrought )
-	{
-	TPckgBuf<TProcessId> arg1( aId );
-	TPckgBuf<TBool> arg2( aBrought );
-	TIpcArgs args( &arg1, &arg2 );
-	
-	TInt error = SendReceive( EMemSpyClientServerOpSwitchToProcess, args );
-	
-	return error;	
-	}
-
-// Threads related methods
-EXPORT_C void RMemSpySession::GetThreadsL(TProcessId aProcessId, RArray<CMemSpyApiThread*> &aThreads, TSortType aSortType)
-	{
-	TPckgBuf<TInt> count;
-	TPckgBuf<TProcessId> pid(aProcessId);
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetThreadCount, TIpcArgs(&count, &pid)));
-	
-	TInt requestedCount = count();
-	HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyThreadData));
-	TPtr8 bufferPtr(buffer->Des());
-	
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetThreads, TIpcArgs(&count, &bufferPtr, &pid)));
-	aThreads.Reset();
-	
-	TInt receivedCount = Min(count(), requestedCount);
-	for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyThreadData))
-		{
-		TPckgBuf<TMemSpyThreadData> data;
-		data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyThreadData));
-		aThreads.AppendL(CMemSpyApiThread::NewLC(data()));
-		}
-	CleanupStack::Pop(aThreads.Count());
-	CleanupStack::PopAndDestroy(buffer);
-	}
-
-EXPORT_C void RMemSpySession::SetThreadPriorityL(TThreadId aId, TInt aPriority)
-	{
-	TPckgBuf<TThreadId> arg1( aId );
-	TPckgBuf<TInt> arg2( aPriority );
-	
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpSetThreadPriority, TIpcArgs(&arg1, &arg2)));
-	}
-
-EXPORT_C TInt RMemSpySession::ThreadSystemPermanentOrCritical( TThreadId aId, TBool aValue )
-	{
-	TPckgBuf<TThreadId> arg1( aId );
-	TPckgBuf<TBool> arg2( aValue );
-	TIpcArgs args( &arg1, &arg2 );
-	
-	TInt error = SendReceive( EMemSpyClientServerOpThreadSystemPermanentOrCritical, args );
-	
-	aValue = arg2();
-	
-	return error;
-	}
-
-EXPORT_C TInt RMemSpySession::EndThreadL( TThreadId aId, TMemSpyEndType aType )
-	{
-	TPckgBuf<TThreadId> arg1( aId );
-	TPckgBuf<TMemSpyEndType> arg2( aType );
-	TIpcArgs args( &arg1, &arg2 );
-	
-	TInt error = SendReceive( EMemSpyClientServerOpEndThread, args );
-	
-	return error;
-	}
-
-EXPORT_C TInt RMemSpySession::SwitchToThread( TThreadId aId, TBool aBrought )
-	{
-	TPckgBuf<TThreadId> arg1( aId );
-	TPckgBuf<TBool> arg2( aBrought );
-	TIpcArgs args( &arg1, &arg2 );
-	
-	TInt error = SendReceive( EMemSpyClientServerOpSwitchToThread, args );
-	
-	return error;	
-	}
-
-EXPORT_C TInt RMemSpySession::GetInfoItemType( TInt aIndex, TThreadId aId, TMemSpyThreadInfoItemType &aType )
-	{
-	TPckgBuf<TInt> arg1( aIndex );
-	TPckgBuf<TThreadId> arg2( aId );
-	TPckgBuf<TMemSpyThreadInfoItemType> arg3;
-	TIpcArgs args( &arg1, &arg2, &arg3 );
-		
-	TInt error = SendReceive( EMemSpyClientServerOpGetInfoItemType, args );
-	
-	aType = arg3();
-	
-	return error;
-	}
-
-EXPORT_C void RMemSpySession::GetThreadInfoItemsL( RArray<CMemSpyApiThreadInfoItem*> &aInfoItems, TThreadId aId, TMemSpyThreadInfoItemType aType )
-	{
-	TPckgBuf<TThreadId> id( aId );	
-	TPckgBuf<TMemSpyThreadInfoItemType> type( aType );
-	TPckgBuf<TInt> count;	
-	
-	TInt error = SendReceive( EMemSpyClientServerOpGetThreadInfoItemsCount, TIpcArgs( &id, &type, &count ) );
-	TInt itemCount = count();
-	
-	if( error == KErrNone )
-		{		
-		if( itemCount == 0 )
-			{
-			aInfoItems.Reset();
-			}
-		else
-			{
-			HBufC8* buffer = HBufC8::NewLC( itemCount * sizeof(TMemSpyThreadInfoItemData) );
-			TPtr8 bufferPtr(buffer->Des());
-			
-			TPckgBuf<TInt> requestedCount( itemCount );
-			
-			TIpcArgs args( &requestedCount, &id, &type, &bufferPtr );
-			TInt error = SendReceive( EMemSpyClientServerOpGetThreadInfoItems, args ); // TODO check error
-			
-			aInfoItems.Reset();
-		
-			for(TInt i=0, offset = 0; i < itemCount; i++, offset+=sizeof(TMemSpyThreadInfoItemData))
-				{
-				TPckgBuf<TMemSpyThreadInfoItemData> data;
-				data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyThreadInfoItemData));
-				aInfoItems.AppendL(CMemSpyApiThreadInfoItem::NewLC(data()));
-				}
-			
-			CleanupStack::Pop(aInfoItems.Count());
-			CleanupStack::PopAndDestroy(buffer);
-			}
-		}
-	
-	User::LeaveIfError(error);
-	}
-
-EXPORT_C TInt RMemSpySession::GetThreadInfoItems( RArray<CMemSpyApiThreadInfoItem*> &aInfoItems, TThreadId aId, TMemSpyThreadInfoItemType aType )
-	{
-	TRAPD(error, GetThreadInfoItemsL(aInfoItems, aId, aType));
-	return error;
-	}
-
-EXPORT_C void RMemSpySession::GetProcessIdByThreadId( TProcessId& aPID, TThreadId aTID )
-	{	
-	TPckgBuf<TProcessId> pid(aPID);
-	TPckgBuf<TThreadId> tid(aTID);
-	
-	TIpcArgs args( &pid, &tid );
-	User::LeaveIfError( SendReceive( EMemSpyClientServerOpGetProcessIdByThreadId, args ) );
-	aPID = pid();
-	}
-
-//Kernel Objects specific operations
-EXPORT_C void RMemSpySession::GetKernelObjectsL( RArray<CMemSpyApiKernelObject*> &aKernelObjects )
-	{		
-	TPckgBuf<TInt> count;
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpGetKernelObjectCount, TIpcArgs(&count) ));
-	
-	TInt requestedCount = count();
-	HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyKernelObjectData));
-	TPtr8 bufferPtr(buffer->Des());
-		
-	TIpcArgs args( &count, &bufferPtr );
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpGetKernelObjects, args ));
-	
-	aKernelObjects.Reset();
-	
-	for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyKernelObjectData))
-		{
-		TPckgBuf<TMemSpyKernelObjectData> data;
-		data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyKernelObjectData));
-		aKernelObjects.AppendL(CMemSpyApiKernelObject::NewLC(data()));
-		}
-	
-	CleanupStack::Pop(aKernelObjects.Count());
-	CleanupStack::PopAndDestroy(buffer);
-	}
-
-EXPORT_C TInt RMemSpySession::GetKernelObjects( RArray<CMemSpyApiKernelObject*> &aKernelObjects )
-	{
-	TRAPD(error, GetKernelObjectsL(aKernelObjects));
-	return error;
-	}
-
-EXPORT_C void RMemSpySession::GetKernelObjectItemsL( RArray<CMemSpyApiKernelObjectItem*> &aKernelObjectItems, TMemSpyDriverContainerType aForContainer )
-	{
-	TPckgBuf<TInt> count;
-	TPckgBuf<TMemSpyDriverContainerType> type(aForContainer);
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpGetKernelObjectItemCount, TIpcArgs(&count, &type) ));
-
-	TInt requestedCount = count();
-	HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyDriverHandleInfoGeneric));
-	TPtr8 bufferPtr(buffer->Des());
-	
-	TIpcArgs args( &count, &type, &bufferPtr );
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpGetKernelObjectItems, args ));
-	
-	aKernelObjectItems.Reset();
-	
-	for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyDriverHandleInfoGeneric))
-		{
-		TPckgBuf<TMemSpyDriverHandleInfoGeneric> data;
-		data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyDriverHandleInfoGeneric));
-		aKernelObjectItems.AppendL( CMemSpyApiKernelObjectItem::NewLC( data() ) );
-		}
-	CleanupStack::Pop(aKernelObjectItems.Count());
-	CleanupStack::PopAndDestroy(buffer);
-	}
-
-EXPORT_C TInt RMemSpySession::GetKernelObjectItems( RArray<CMemSpyApiKernelObjectItem*> &aKernelObjectItems, TMemSpyDriverContainerType aForContainer )
-	{
-	TRAPD(error, GetKernelObjectItemsL(aKernelObjectItems, aForContainer));
-	return error;
-	}
-
-EXPORT_C void RMemSpySession::GetMemoryTrackingCyclesL(RArray<CMemSpyApiMemoryTrackingCycle*>& aCycles)
-	{
-	TPckgBuf<TInt> count;
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpGetMemoryTrackingCycleCount, TIpcArgs(&count) ));
-	
-	TInt requestedCount = count();
-	HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyMemoryTrackingCycleData));
-	TPtr8 bufferPtr(buffer->Des());
-		
-	TIpcArgs args( &count, &bufferPtr );
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpGetMemoryTrackingCycles, args ));
-	
-	aCycles.Reset();
-	
-	for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyMemoryTrackingCycleData))
-		{
-		TPckgBuf<TMemSpyMemoryTrackingCycleData> data;
-		data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyMemoryTrackingCycleData));
-		aCycles.AppendL(CMemSpyApiMemoryTrackingCycle::NewLC(data()));
-		}
-	
-	CleanupStack::Pop(aCycles.Count());
-	CleanupStack::PopAndDestroy(buffer);
-	}
-
-EXPORT_C void RMemSpySession::OutputAllContainerContents()
-	{
-	SendReceive( EMemSpyClientServerOpOutputAllContainerContents );
-	}
-
-
-//Heap specific operations
-
-EXPORT_C CMemSpyApiHeap* RMemSpySession::GetHeapL()
-	{
-	CMemSpyApiHeap* aHeap;
-	
-	HBufC8* buffer = HBufC8::NewLC( sizeof(TMemSpyHeapData) );
-	TPtr8 bufferPtr(buffer->Des());
-	TIpcArgs args( &bufferPtr );
-	
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpGetHeap, args ));
-	
-	TPckgBuf<TMemSpyHeapData> data;
-	data.Copy(bufferPtr.Ptr(), sizeof(TMemSpyHeapData));		
-	aHeap = CMemSpyApiHeap::NewL( data() );
-	
-	CleanupStack::PopAndDestroy(buffer);
-		
-	return aHeap;
-	}
-
-EXPORT_C CMemSpyApiHeap* RMemSpySession::GetHeap()
-	{
-	CMemSpyApiHeap *result = NULL;
-	TRAPD(error, result = GetHeapL());
-	return error == KErrNone ? result : NULL;
-	}
-
-
-
-EXPORT_C void RMemSpySession::GetEComCategoriesL(RArray<CMemSpyApiEComCategory*> &aCategories)
-    {
-    TPckgBuf<TInt> count;
-    User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetEComCategoryCount, TIpcArgs(&count)));
-    
-    TInt requestedCount = count();
-    HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyEComCategoryData));
-    TPtr8 bufferPtr(buffer->Des());
-    
-    User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetEComCategories, TIpcArgs(&count, &bufferPtr)));
-    aCategories.Reset();
-    
-    TInt receivedCount = Min(count(), requestedCount);
-    for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyEComCategoryData))
-        {
-        TPckgBuf<TMemSpyEComCategoryData> data;
-        data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyEComCategoryData));
-        aCategories.AppendL(CMemSpyApiEComCategory::NewLC(data()));
-        }
-    CleanupStack::Pop(aCategories.Count());
-    CleanupStack::PopAndDestroy(buffer);
-    }
-    
-EXPORT_C void RMemSpySession::GetEComInterfacesL(TUid aCategory, RArray<CMemSpyApiEComInterface*> &aInterfaces)
-    {
-    TPckgBuf<TInt> count;
-    TPckgBuf<TUid> category(aCategory);
-    User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetEComInterfaceCount, TIpcArgs(&count, &category)));
-    
-    TInt requestedCount = count();
-    HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyEComInterfaceData));
-    TPtr8 bufferPtr(buffer->Des());
-    
-    User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetEComInterfaces, TIpcArgs(&count, &category, &bufferPtr)));
-    aInterfaces.Reset();
-    
-    TInt receivedCount = Min(count(), requestedCount);
-    for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyEComInterfaceData))
-        {
-        TPckgBuf<TMemSpyEComInterfaceData> data;
-        data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyEComInterfaceData));
-        aInterfaces.AppendL(CMemSpyApiEComInterface::NewLC(data()));
-        }
-    CleanupStack::Pop(aInterfaces.Count());
-    CleanupStack::PopAndDestroy(buffer);
-    }
-
-EXPORT_C void RMemSpySession::GetEComImplementationsL(TUid aInterface, RArray<CMemSpyApiEComImplementation*> &aImplementations)
-    {
-    TPckgBuf<TInt> count;
-    TPckgBuf<TUid> interface(aInterface);
-    User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetEComImplementationCount, TIpcArgs(&count, &interface)));
-    
-    TInt requestedCount = count();
-    HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyEComImplementationData));
-    TPtr8 bufferPtr(buffer->Des());
-    
-    User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetEComImplementations, TIpcArgs(&count, &interface, &bufferPtr)));
-    aImplementations.Reset();
-    
-    TInt receivedCount = Min(count(), requestedCount);
-    for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyEComImplementationData))
-        {
-        TPckgBuf<TMemSpyEComImplementationData> data;
-        data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyEComImplementationData));
-        aImplementations.AppendL(CMemSpyApiEComImplementation::NewLC(data()));
-        }
-    CleanupStack::Pop(aImplementations.Count());
-    CleanupStack::PopAndDestroy(buffer);
-    }
-
-EXPORT_C void RMemSpySession::DumpKernelHeap()
-	{
-	SendReceive( EMemSpyClientServerOpDumpKernelHeap );
-	}
-
-EXPORT_C void RMemSpySession::OutputKernelHeapDataL()
-	{		
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpHeapData | KMemSpyOpFlagsIncludesThreadId,
-			TIpcArgs(KMemSpyClientServerThreadIdKernel)));
-	
-	}
-
-EXPORT_C void RMemSpySession::OutputKernelHeapData(TRequestStatus& aStatus)
-	{
-	SendReceive(EMemSpyClientServerOpHeapData,
-		TIpcArgs(KMemSpyClientServerThreadIdKernel),
-		aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputThreadHeapDataL( TThreadId aThreadId)
-	{			
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpHeapData | KMemSpyOpFlagsIncludesThreadId,
-			TIpcArgs(aThreadId)));
-	}
-
-EXPORT_C void RMemSpySession::OutputThreadHeapDataL(const TDesC& aThreadName)
-	{	
-	const TIpcArgs args( &aThreadName );
-	        
-	User::LeaveIfError( SendReceive( EMemSpyClientServerOpHeapData | KMemSpyOpFlagsIncludesThreadName, args ));	
-	}
-
-EXPORT_C void RMemSpySession::OutputThreadCellListL(TThreadId aThreadId)
-	{	
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpHeapCellListing | KMemSpyOpFlagsIncludesThreadId,
-			TIpcArgs(aThreadId)));
-	}
-
-EXPORT_C void RMemSpySession::OutputHeapInfoUserL(TThreadId aThreadId)
-	{
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpHeapInfo | KMemSpyOpFlagsIncludesThreadId,
-			TIpcArgs(aThreadId)));
-	}
-
-EXPORT_C void RMemSpySession::SwitchOutputSinkL( TMemSpySinkType aType )
-	{
-	TInt op;
-	if( aType == ESinkTypeFile )
-		op = EMemSpyClientServerOpSwitchOutputSinkFile;
-	else
-		op = EMemSpyClientServerOpSwitchOutputSinkTrace;
-			
-	User::LeaveIfError(SendReceive( op ));
-	}
-
-EXPORT_C void RMemSpySession::SwitchOutputToTraceL()
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSwitchOutputSinkTrace));
-	}
-    
-EXPORT_C void RMemSpySession::SwitchOutputToFileL(const TDesC& aRootFolder)
-	{
-	TIpcArgs args;
-	if (aRootFolder.Length())
-		{
-		args.Set(0, &aRootFolder);
-		}
-	
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSwitchOutputSinkFile, args));
-	}
-
-EXPORT_C void RMemSpySession::OutputStackInfoL(TThreadId aThreadId)
-	{
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpStackInfo | KMemSpyOpFlagsIncludesThreadId,
-			TIpcArgs(aThreadId)));
-	}
-
-EXPORT_C void RMemSpySession::OutputStackDataL(TThreadId aThreadId, TMemSpyDriverDomainType aType )
-	{
-	TInt op;
-	if( aType == EMemSpyDriverDomainUser )
-		op = EMemSpyClientServerOpStackDataUser;
-	else
-		op = EMemSpyClientServerOpStackDataKernel;
-	
-	User::LeaveIfError(SendReceive( op | KMemSpyOpFlagsIncludesThreadId,
-			TIpcArgs(aThreadId, aType)));
-		
-	}
-
-EXPORT_C void RMemSpySession::OutputThreadInfoHandlesL(TThreadId aThreadId)
-	{
-	TPckgBuf<TThreadId> id(aThreadId);
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpOutputInfoHandles, TIpcArgs( &id )));	
-	}
-
-EXPORT_C void RMemSpySession::OutputAOListL(TThreadId aId, TMemSpyThreadInfoItemType aType)
-	{
-	TPckgBuf<TThreadId> id(aId);
-	TPckgBuf<TMemSpyThreadInfoItemType> type(aType);
-	
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpOutputAOList, TIpcArgs( &id, &type )));
-	}
-
-EXPORT_C void RMemSpySession::OutputKernelObjectsL()
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpEnumerateKernelContainerAll));
-	}
-
-EXPORT_C void RMemSpySession::OutputCompactStackInfoL()
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpStackInfoCompact)); 
-	}
-
-EXPORT_C void RMemSpySession::OutputCompactHeapInfoL()
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpHeapInfoCompact)); 
-	}
-// Asynchronous operations
-EXPORT_C void RMemSpySession::OutputPhoneInfo(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpSummaryInfo | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputDetailedPhoneInfo(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpSummaryInfoDetailed | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputHeapInfo(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpHeapInfo | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputCompactHeapInfo(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpHeapInfoCompact | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputHeapCellListing(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpHeapCellListing | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputHeapData(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpHeapData | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-// synchronous version of the operation - for CLI
-EXPORT_C void RMemSpySession::OutputHeapData()
-	{
-	SendReceive(EMemSpyClientServerOpHeapData);
-	}
-
-EXPORT_C void RMemSpySession::OutputStackInfo(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpStackInfo | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputCompactStackInfo(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpStackInfoCompact | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputUserStackData(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpStackDataUser | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-EXPORT_C void RMemSpySession::OutputKernelStackData(TRequestStatus& aStatus)
-	{	
-	SendReceive(EMemSpyClientServerOpStackDataKernel | KMemSpyOpFlagsAsyncOperation, TIpcArgs(), aStatus);
-	}
-
-// Synchronous operations
-EXPORT_C void RMemSpySession::OutputPhoneInfo()
-	{	
-	SendReceive( EMemSpyClientServerOpSummaryInfo , TIpcArgs() );
-	}
-
-EXPORT_C TInt RMemSpySession::GetSwmtCyclesCount()
-	{
-	TPckgBuf<TInt> count;
-	TIpcArgs args( &count );
-		
-	User::LeaveIfError(SendReceive( EMemSpyClientServerOpGetMemoryTrackingCycleCount, args ));
-	
-	return count();
-	}
-
-EXPORT_C void RMemSpySession::SetSwmtAutoStartProcessList( CArrayFixFlat<TUid>* aList )
-	{
-	TInt count = aList->Count();
-	TIpcArgs args( &aList, &count );
-	
-	SendReceive( EMemSpyClientServerOpSetSwmtAutoStartProcessList, args );
-	}
-
-EXPORT_C void RMemSpySession::SwmtResetTracking()
-	{
-	SendReceive( EMemSpyClientServerOpSystemWideMemoryTrackingReset );
-	}
-
-EXPORT_C void RMemSpySession::GetOutputSink( TMemSpySinkType& aType )
-	{
-	TPckgBuf<TMemSpySinkType> type( aType );
-	TIpcArgs args( &type );
-	
-	SendReceive( EMemSpyClientServerOpGetOutputSink, args );
-	
-	aType = type();
-	}
-
-EXPORT_C void RMemSpySession::NotifyDeviceWideOperationProgress(TMemSpyDeviceWideOperationProgress &aProgress, TRequestStatus &aStatus)
-	{
-	SendReceive(EMemSpyClientServerOpNotifyDeviceWideOperationProgress | KMemSpyOpFlagsAsyncOperation,
-			TIpcArgs(&aProgress.iProgress, &aProgress.iDescription), 
-			aStatus);
-	}
-
-EXPORT_C void RMemSpySession::CancelDeviceWideOperationL()
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpCancelDeviceWideOperation));
-	}
-
-// SWMT operations
-EXPORT_C void RMemSpySession::SetSwmtCategoriesL(TInt aCategories)
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingCategoriesSet,
-			TIpcArgs(aCategories)));
-	}
-
-EXPORT_C void RMemSpySession::SetSwmtHeapDumpsEnabledL(TBool aEnabled)
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingHeapDumpSet,
-			TIpcArgs(aEnabled)));
-	}
-
-EXPORT_C void RMemSpySession::SetSwmtMode(TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode aMode)
-	{
-	TPckgBuf<TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode> mode( aMode );
-	TIpcArgs args(&mode);
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingModeSet, args));
-	}
-
-EXPORT_C TBool RMemSpySession::IsSwmtRunningL()
-	{
-	TPckgBuf<TBool> ret;
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpIsSwmtRunning, TIpcArgs(&ret)));
-	
-	return ret();
-	}
-
-EXPORT_C void RMemSpySession::StartSwmtTimerL(TInt aPeriod)
-	{
-	SetSwmtTimerIntervalL(aPeriod);
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingTimerStart));
-	}
-
-EXPORT_C void RMemSpySession::StartSwmtTimerL()
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingTimerStart));
-	}
-
-EXPORT_C void RMemSpySession::SetSwmtTimerIntervalL(TInt aPeriod)
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingTimerPeriodSet,
-			TIpcArgs(aPeriod)));
-	}
-
-EXPORT_C void RMemSpySession::StopSwmtTimerL()
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingTimerStop));
-	}
-
-
-EXPORT_C void RMemSpySession::ForceSwmtUpdateL()
-	{
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingForceUpdate));
-	}
-
-EXPORT_C void RMemSpySession::ForceSwmtUpdate(TRequestStatus& aStatus)
-	{
-	SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingForceUpdate, 
-			TIpcArgs(),
-			aStatus);
-	}
-
-EXPORT_C void RMemSpySession::SetSwmtFilter( const TDesC& aFilter )
-	{	
-	TIpcArgs args( &aFilter );
-	User::LeaveIfError( SendReceive( EMemSpyClientServerOpSystemWideMemoryTrackingThreadNameFilterSet, args ) );
-	}
-
-EXPORT_C void RMemSpySession::GetSwmtFilter( TName& aFilter )
-	{
-    TPckgBuf<TName> name;
-    TIpcArgs args( &name );
-		User::LeaveIfError( SendReceive( EMemSpyClientServerOpSystemWideMemoryTrackingThreadNameFilterGet, args ) );
-	aFilter = name();
-	}
-        
-EXPORT_C void RMemSpySession::GetSwmtCategoriesL(TInt& aCategories)
-	{
-	TPckgBuf<TInt> cat;	
-	TIpcArgs args( &cat );
-		User::LeaveIfError( SendReceive( EMemSpyClientServerOpSystemWideMemoryTrackingCategoriesGet, args ) );
-	aCategories = cat();
-	}
-
-EXPORT_C void RMemSpySession::GetSwmtHeapDumpsEnabledL(TBool& aEnabled)
-	{
-	TPckgBuf<TBool> enabled;
-	TIpcArgs args( &enabled );
-		User::LeaveIfError( SendReceive( EMemSpyClientServerOpSystemWideMemoryTrackingHeapDumpGet, args ) );
-		
-	aEnabled = enabled();
-	}
-        
-EXPORT_C void RMemSpySession::GetSwmtMode(TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode& aMode)
-	{
-	TPckgBuf<TMemSpyEngineHelperSysMemTrackerConfig::TMemSpyEngineSysMemTrackerMode> mode;
-	TIpcArgs args( &mode );
-		User::LeaveIfError( SendReceive( EMemSpyClientServerOpSystemWideMemoryTrackingModeGet, args ) );
-	aMode = mode();
-	}
-    
-EXPORT_C void RMemSpySession::GetSwmtTimerIntervalL(TInt& aPeriod)
-	{
-	TPckgBuf<TInt> time;
-	TIpcArgs args( &time );
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpSystemWideMemoryTrackingTimerPeriodGet,
-			args));
-	aPeriod = time();
-	}
-
-EXPORT_C TInt TMemSpyDeviceWideOperationProgress::Progress() const 
-	{
-	return iProgress();
-	}
-
-EXPORT_C const TDesC& TMemSpyDeviceWideOperationProgress::Description() const
-	{
-	return iDescription;
-	}
-
-// Servers
-EXPORT_C void RMemSpySession::GetServersL(RArray<CMemSpyApiServer*> &aServers)
-    {
-    TPckgBuf<TInt> count;
-    User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetServerCount, TIpcArgs(&count)));
-    
-    TInt requestedCount = count();
-    HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyServerData));
-    TPtr8 bufferPtr(buffer->Des());
-    
-    User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetServers, TIpcArgs(&count, &bufferPtr)));
-    aServers.Reset();
-    
-    TInt receivedCount = Min(count(), requestedCount);
-    for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyServerData))
-        {
-        TPckgBuf<TMemSpyServerData> data;
-        data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyServerData));
-        aServers.AppendL(CMemSpyApiServer::NewLC(data()));
-        }
-    CleanupStack::Pop(aServers.Count());
-    CleanupStack::PopAndDestroy(buffer);
-    }
-
-EXPORT_C void RMemSpySession::GetServersL(RArray<CMemSpyApiServer*> &aServers, TSortType aSortType)
-	{
-	TPckgBuf<TInt> count;
-	TPckgBuf<TSortType> sort( aSortType );
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetServerCount, TIpcArgs(&count)));
-	    	
-	TInt requestedCount = count();
-	HBufC8* buffer = HBufC8::NewLC(requestedCount * sizeof(TMemSpyServerData));
-	TPtr8 bufferPtr(buffer->Des());
-	    
-	User::LeaveIfError(SendReceive(EMemSpyClientServerOpGetSortedServers, TIpcArgs(&count, &bufferPtr, &sort)));
-	aServers.Reset();
-	    
-	TInt receivedCount = Min(count(), requestedCount);
-	for(TInt i=0, offset = 0; i<requestedCount; i++, offset+=sizeof(TMemSpyServerData))
-		{
-		TPckgBuf<TMemSpyServerData> data;
-		data.Copy(bufferPtr.Ptr()+offset, sizeof(TMemSpyServerData));
-		aServers.AppendL(CMemSpyApiServer::NewLC(data()));
-		}
-	CleanupStack::Pop(aServers.Count());
-	CleanupStack::PopAndDestroy(buffer);
-	}
-
-EXPORT_C void RMemSpySession::ServerListOutputGenericL( TBool aDetailed )
-	{
-	TPckgBuf<TBool> detailed( aDetailed );
-	TIpcArgs args( &detailed );
-	User::LeaveIfError( SendReceive( EMemSpyClientServerOpServerListOutputGeneric, args ) );
-	}
-
--- a/memspy/MemSpyServer/Source/MemSpyServerMain.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,75 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-* MemSpyServer Main class
-*/
-
-// System includes
-#include <e32std.h>
-#include <e32base.h>
-#include <f32file.h>
-
-// Engine includes
-#include <memspy/engine/memspyengine.h>
-
-// User includes
-//#include "MemSpyServer.h"
-
-static void RunServerL()
-    {
-    // Scheduler
-    CActiveScheduler* scheduler = new (ELeave) CActiveScheduler();
-    CleanupStack::PushL( scheduler );    
-    CActiveScheduler::Install( scheduler );    
-    
-    // F32
-    RFs fsSession;
-    User::LeaveIfError(fsSession.Connect());
-    CleanupClosePushL(fsSession);
-    
-    // MemSpyEngine initialization
-    CMemSpyEngine* engine = CMemSpyEngine::NewL(fsSession);
-    CleanupStack::PushL(engine);
-    
-    // Play nicely with external processes
-    RProcess::Rendezvous( KErrNone );       
-
-    // Start wait loop.
-    CActiveScheduler::Start();
-    
-    // Tidy up
-    CleanupStack::PopAndDestroy( 3, scheduler );
-    }
-
-TInt E32Main()
-    {
-    __UHEAP_MARK;
-
-    CTrapCleanup* cleanupTrap = CTrapCleanup::New();
-    
-	TInt r = KErrNoMemory;
-	if ( cleanupTrap )
-		{
-		TRAPD(err, RunServerL());		
-		if  ( err != KErrNone )
-		        {
-		        RDebug::Print(_L("[MemSpyCmdLine] E32Main() - MemSpyServer - error: %d"), err);
-		        }
-		delete cleanupTrap;
-		}  
-
-    __UHEAP_MARKEND;
-
-    return r;
-    }
--- a/memspy/MemSpyServer/data/MemSpyEComInterfaceIds.xml	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,18 +0,0 @@
-<?xml version="1.0" standalone="yes"?>
-<memspy_ecom_sections>
-
-    <category name="Messaging">
-		<interface uid="0xABCD1234" name="Watchers" />
-    </category>
-
-    <category name="App-Protocols">
-		<interface uid="0x101F446D" name="HTTP Filters" />
-		<interface uid="0x1000A449" name="HTTP Protocol" />
-    </category>
-
-    <category name="S60 AIW">
-		<interface uid="0x101F8650" name="AIW Class Base" />
-		<interface uid="0x101F8652" name="AIW Class Menu" />
-    </category>
-
-</memspy_ecom_sections>
\ No newline at end of file
--- a/memspy/MemSpyServer/group/MemSpyServer.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,58 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-#include <bldvariant.hrh>
-#include <data_caging_paths.hrh>
-#include <platform_paths.hrh>
-
-TARGETTYPE EXE
-TARGET MemSpyServer.exe
-UID 0 0x2002EA8D
-SECUREID     0xE5883BC2
-VENDORID	 0x101FB657 // Nokia
-
-EPOCSTACKSIZE 0x4000
-EPOCHEAPSIZE 0x100000 0x4000000
-
-
-SOURCEPATH ../Source
-SOURCE		MemSpyServerMain.cpp 
-
-USERINCLUDE ../Include
-
-CAPABILITY ReadUserData WriteUserData ReadDeviceData WriteDeviceData PowerMgmt
-
-OS_LAYER_SYSTEMINCLUDE
-
-APP_LAYER_SYSTEMINCLUDE
-
-LIBRARY         MemSpyDriverClient.lib
-LIBRARY         MemSpyEngine.lib
-
-LIBRARY 		euser.lib
-LIBRARY			ecom.lib
-LIBRARY			efsrv.lib
-LIBRARY			estor.lib
-LIBRARY			bafl.lib
-LIBRARY			ws32.lib
-LIBRARY			cone.lib
-LIBRARY			eikcore.lib
-LIBRARY			fbscli.lib 
-LIBRARY 		PlatformEnv.lib
-LIBRARY 		flogger.lib
-LIBRARY			apgrfx.lib
-
--- a/memspy/MemSpyServer/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,26 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:
-*
-*/
-
-PRJ_PLATFORMS
-DEFAULT
-
-PRJ_EXPORTS
-../data/MemSpyEComInterfaceIds.xml									z:/private/E5883BC2/memspyecominterfaceids.xml
-
-
-PRJ_MMPFILES
-MemSpyServer.mmp
--- a/memspy/group/ReleaseNotes_MemSpy.txt	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/group/ReleaseNotes_MemSpy.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -1,7 +1,7 @@
 ===============================================================================
 
-RELEASE NOTES - MEMSPY v2.2.0
-RELEASED 24th August 2010 
+RELEASE NOTES - MEMSPY v1.2.1
+RELEASED 15th June 2010 
 
 SUPPORTS S60 5.0+
 
@@ -28,11 +28,10 @@
 
 ===============================================================================
 
-What's New in v2.2.0
+What's New in v1.2.1
 ====================
-- Feature: Servers view to display a list of running servers.
-- Feature: ECom view to display ECom categories, interfaces and implementations.
-- Feature: Processes can be now terminated.
+- Fix: Stack dumps fixed.
+
 
 ===============================================================================
 
@@ -94,19 +93,8 @@
 
 Version History:
 ================
-
-Version 2.1.0 - 15th June 2010 
+Version 1.2.0 - 27th October 2009
 ------------------------------
-- Feature: Folder where log files are saved can now be set in settings.
-- Feature: Introduced new Orbit based user interface.
-- Change: Servers, Ecom, Window groups, System info and Automatic Capture were
-  removed.
-- Change: Console interface was removed.
-- Change: Command line interface commands were changed to be more user 
-  friendly.
-
-Version 1.2.0 - 27th October 2009 
----------------------------------
 - Feature: Tracking modes introduced for simplify System Wide Memory Tracking
   settings.
 - Feature: System Wide Memory Tracking categories can now be selected.
--- a/memspy/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -29,12 +29,10 @@
 // Commandline includes
 #include "../CommandLine/group/bld.inf"
 
-// MemSpyServer
-#include "../MemSpyServer/group/bld.inf"
+// Console UI
+#include "../Console/group/bld.inf"
 
-// MemSpyClient
-#include "../MemSpyClient/group/bld.inf"
 
 PRJ_EXPORTS
 ../rom/memspy.iby      CORE_IBY_EXPORT_PATH(tools,memspy.iby)
-../rom/memspy_rom.iby  CORE_IBY_EXPORT_PATH(tools/rom,memspy_rom.iby)
\ No newline at end of file
+../rom/memspy_rom.iby  CORE_IBY_EXPORT_PATH(tools/rom,memspy_rom.iby)
--- a/memspy/memspy_plat/memspy_api/include/MemSpyEngineClientInterface.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/MemSpyEngineClientInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -45,12 +45,11 @@
 const TInt KMemSpyOpFlagsInclusionMask          = 0xFFFF0000;
 const TInt KMemSpyOpFlagsIncludesThreadId       = 0x00010000;
 const TInt KMemSpyOpFlagsIncludesThreadName     = 0x00020000;
-const TInt KMemSpyOpFlagsAsyncOperation         = 0x00040000;
+
 // Literal constants
 _LIT( KMemSpyServerName, "MemSpyServer" );
-_LIT( KMemSpyProcessName0, "MemSpyServer.exe" );
 _LIT( KMemSpyProcessName1, "MemSpyUI.exe" );
-//_LIT( KMemSpyProcessName2, "MemSpyConsole.exe" );
+_LIT( KMemSpyProcessName2, "MemSpyConsole.exe" );
 
 //
 // Supported MemSpy operation types
@@ -257,143 +256,14 @@
      * [INTERNAL REQUEST]
      */
     EMemSpyClientServerOpSystemWideMemoryTrackingHeapDumpSet,
-        
+    
     /**
      * [INTERNAL REQUEST]
      */
-    EMemSpyClientServerOpSystemWideMemoryTrackingModeSet,        
-    
-    /**
-	 * [INTERNAL REQUEST]
-	 */
-	EMemSpyClientServerOpMarkerUiFirst,
-	
-	EMemSpyClientServerOpGetProcessCount = EMemSpyClientServerOpMarkerUiFirst,
-	
-	EMemSpyClientServerOpGetProcesses,
-	
-	EMemSpyClienServerOpGetProcessIdByName,
-	
-	EMemSpyClientServerOpGetThreadCount,
-	
-	EMemSpyClientServerOpGetThreads,
-	
-	EMemSpyClientServerOpSetThreadPriority,
-	
-	EMemSpyClientServerOpProcessSystemPermanentOrCritical,
-	
-	EMemSpyClientServerOpEndProcess,
-	
-	EMemSpyClientServerOpSwitchToProcess,
-	
-	//Threads operations
-	EMemSpyClientServerOpThreadSystemPermanentOrCritical,
-	
-	EMemSpyClientServerOpEndThread,
-	
-	EMemSpyClientServerOpSwitchToThread,
-	
-	EMemSpyClientServerOpGetInfoItemType,
-	
-	EMemSpyClientServerOpGetProcessIdByThreadId,
-	
-	EMemSpyClientServerOpGetThreadInfoItemsCount,
-	
-	EMemSpyClientServerOpGetThreadInfoItems,
-	
-	EMemSpyClientServerOpOutputInfoHandles,
-	
-	EMemSpyClientServerOpOutputAOList,
-		
-	
-	//Kernel Objects operations
-	EMemSpyClientServerOpGetKernelObjectCount,
-	
-	EMemSpyClientServerOpGetKernelObjects,
-	
-	EMemSpyClientServerOpGetKernelObjectItemCount,
-	
-	EMemSpyClientServerOpGetKernelObjectItems,
-	
-	EMemSpyClientServerOpGetHeap,
-	
-	EMemSpyClientServerOpGetMemoryTrackingCycleCount,
-	
-	EMemSpyClientServerOpGetMemoryTrackingCycles,
-	
-	EMemSpyClientServerOpGetMemoryTrackingMdcaCount,
-	/**
-	 * [INTERNAL REQUEST]
-	 * Register for notifications of device wide operation progress.
-	 */
-	EMemSpyClientServerOpNotifyDeviceWideOperationProgress,
-	
-	/**
-	 * [INTERNAL REQUEST]
-	 * Cancel current device wide operation
-	 */
-	EMemSpyClientServerOpCancelDeviceWideOperation,	
-	
-	EMemSpyClientServerOpOutputAllContainerContents,
-	    
-	EMemSpyClientServerOpDumpKernelHeap,
-	
-	EMemSpyClientServerOpSetSwmtAutoStartProcessList,
-		
-	EMemSpyClientServerOpGetOutputSink,
-	
-	/**
-	 * [INTERNAL REQUEST]
-	 * Check if system wide memory tracking timer is running.
-	 */
-	EMemSpyClientServerOpIsSwmtRunning,
-	
-	EMemSpyClientServerOpSystemWideMemoryTrackingTimerPeriodGet,
-
-	EMemSpyClientServerOpSystemWideMemoryTrackingThreadNameFilterGet,
-    
-    EMemSpyClientServerOpSystemWideMemoryTrackingCategoriesGet,
-    
-    EMemSpyClientServerOpSystemWideMemoryTrackingHeapDumpGet,
-
-    EMemSpyClientServerOpSystemWideMemoryTrackingModeGet,   
-	
-    //Servers methods
-	EMemSpyClientServerOpGetServerCount,
-	
-	EMemSpyClientServerOpGetServers,
-	
-	EMemSpyClientServerOpGetSortedServers,
-	
-	EMemSpyClientServerOpServerListOutputGeneric,
-	
-	EMemSpyClientServerOpGetEComCategoryCount,
-	    
-	EMemSpyClientServerOpGetEComCategories,
-	
-	EMemSpyClientServerOpGetEComInterfaceCount,
-	        
-	EMemSpyClientServerOpGetEComInterfaces,
-	
-	EMemSpyClientServerOpGetEComImplementationCount,
-	            
-	EMemSpyClientServerOpGetEComImplementations,
-	
-	EMemSpyClientServerOpMarkerUiLast,		
-	
-	/**
-	 * [INTERNAL REQUEST]
-	 */
     EMemSpyClientServerOpMarkerLast,
     };
 
 
-enum TMemSpyEndType
-	{
-	ETerminate,
-	EKill,
-	EPanic
-	};
 
 
 
--- a/memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverEnumerationsShared.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverEnumerationsShared.h	Wed Oct 13 16:17:58 2010 +0300
@@ -24,24 +24,12 @@
 // Enumerations
 enum TMemSpyDriverCellType
 	{
-	EMemSpyDriverAllocatedCellMask	= 0x000000FF,
-	EMemSpyDriverFreeCellMask		= 0x0000FF00,
-	EMemSpyDriverBadCellMask		= 0xFF000000,
-
-	EMemSpyDriverHeapAllocation		= 0x00000001,
-	EMemSpyDriverDlaAllocation		= 0x00000002,
-	EMemSpyDriverPageAllocation		= 0x00000003,
-	EMemSpyDriverSlabAllocation		= 0x00000004,
-	
-	EMemSpyDriverHeapFreeCell		= 0x00000100,
-	EMemSpyDriverDlaFreeCell		= 0x00000200,
-	EMemSpyDriverSlabFreeCell		= 0x00000300, // Used to track free cells in partially-filled slabs
-	EMemSpyDriverSlabFreeSlab		= 0x00000400, // Used to track entirely empty slabs (that don't have a specific cell size)
-
-	EMemSpyDriverHeapBadFreeCellAddress			= 0x01000000,
-	EMemSpyDriverHeapBadFreeCellSize			= 0x02000000,
-	EMemSpyDriverHeapBadAllocatedCellSize		= 0x03000000,
-	EMemSpyDriverHeapBadAllocatedCellAddress	= 0x04000000,
+	EMemSpyDriverGoodAllocatedCell = 0,
+	EMemSpyDriverGoodFreeCell,
+	EMemSpyDriverBadAllocatedCellSize,
+	EMemSpyDriverBadAllocatedCellAddress,
+	EMemSpyDriverBadFreeCellAddress,
+	EMemSpyDriverBadFreeCellSize
 	};
 
 
--- a/memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverObjectsShared.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverObjectsShared.h	Wed Oct 13 16:17:58 2010 +0300
@@ -349,8 +349,7 @@
     enum THeapImplementationType
         {
         ETypeUnknown = 0,
-        ETypeRHeap = 1,
-		ETypeRHybridHeap = 2,
+        ETypeRHeap
         };
 
 public: // Constructor & destructor
@@ -427,19 +426,17 @@
     };
 
 
+
 /**
- * cell information
+ * Free cell information
  */
 class TMemSpyDriverFreeCell
-	{
+    {
 public:
-	TMemSpyDriverCellType iType;
-	TAny* iAddress;
-	TInt iLength;
-	};
-
-// For compatibility I can't change TMemSpyDriverCell to be the class and typdef/derive TMemSpyDriverFreeCell. Sigh...
-typedef TMemSpyDriverFreeCell TMemSpyDriverCell;
+    TInt iType;
+    TAny* iAddress;
+    TInt iLength;
+    };
 
 
 /** 
--- a/memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverObjectsSharedRHeap.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/driver/shared/MemSpyDriverObjectsSharedRHeap.h	Wed Oct 13 16:17:58 2010 +0300
@@ -35,6 +35,80 @@
 class CTrapCleanup;
 
 
+
+class TMemSpyHeapObjectDataRHeap
+    {
+public:
+    inline TMemSpyHeapObjectDataRHeap()
+        : iAccessCount( 0 ),
+          iHandleCount( 0 ),
+          iHandles( NULL ),
+          iFlags( 0 ),
+          iCellCount( 0 ),
+          iTotalAllocSize ( 0 ),
+          //
+          iMinLength( 0 ),
+          iMaxLength( 0 ),
+          iOffset ( 0 ),
+          iGrowBy( 0 ),
+          iChunkHandle ( 0 ),
+          iBase( NULL ),
+          iTop( NULL ),
+          iAlign( 0 ),
+          iMinCell( 0 ),
+          iPageSize( 0 ),
+          iNestingLevel( 0 ),
+          iAllocCount( 0 ),
+          iFailRate( 0 ),
+          iFailed( EFalse ),
+          iFailAllocCount( 0 ),
+          iRand( 0 ),
+          iTestData( NULL )
+        {
+        }
+
+public: // API
+    inline TUint8* Base() const { return iBase; }
+    inline TUint Size() const { return iTop - iBase; }
+
+public: // From RAllocator
+	TInt iAccessCount;
+	TInt iHandleCount;
+	TInt* iHandles;
+	TUint32 iFlags;
+	TInt iCellCount;
+	TInt iTotalAllocSize;
+
+public: // From RHeap
+	TInt iMinLength;
+	TInt iMaxLength;
+	TInt iOffset;
+	TInt iGrowBy;
+	TInt iChunkHandle;
+    RFastLock iLock;
+	TUint8* iBase;
+	TUint8* iTop;
+	TInt iAlign;
+	TInt iMinCell;
+	TInt iPageSize;
+#ifdef __SYMBIAN_KERNEL_HYBRID_HEAP__
+	struct SCell { TInt len; SCell* next };
+    SCell iFree;
+#else
+    RHeap::SCell iFree;
+#endif
+	TInt iNestingLevel;
+	TInt iAllocCount;
+    RAllocator::TAllocFail iFailType;
+	TInt iFailRate;
+	TBool iFailed;
+	TInt iFailAllocCount;
+	TInt iRand;
+	TAny* iTestData;
+    };
+
+
+
 /**
  * Base class for MemSpy RHeap statistics
  */
@@ -131,6 +205,33 @@
     TUint32 iChecksum;
     };
 
+
+
+
+
+/**
+ * RHeap statistics for common cell types
+ */
+class TMemSpyHeapStatisticsRHeapCommon
+    {
+public: // Constructors
+    inline TMemSpyHeapStatisticsRHeapCommon()
+        : iTotalCellCount( 0 )
+        {
+        }
+
+public:
+    inline TUint TotalCellCount() const { return iTotalCellCount; }
+    inline void SetTotalCellCount( TUint aValue ) { iTotalCellCount = aValue; }
+
+private:
+    TUint iTotalCellCount;
+    };
+
+
+
+
+
 /**
  * RHeap statistics class
  */
@@ -138,7 +239,6 @@
     {
 public: // Constructors
     inline TMemSpyHeapStatisticsRHeap()
-		: iCommittedFreeSpace(0)
         {
         }
 
@@ -148,14 +248,14 @@
     //
     inline TMemSpyHeapStatisticsRHeapAllocated& StatsAllocated() { return iStatisticsAllocated; }
     inline const TMemSpyHeapStatisticsRHeapAllocated& StatsAllocated() const { return iStatisticsAllocated; }
-
+    //
+    inline TMemSpyHeapStatisticsRHeapCommon& StatsCommon() { return iStatisticsCommon; }
+    inline const TMemSpyHeapStatisticsRHeapCommon& StatsCommon() const { return iStatisticsCommon; }
 
 private: // Data members
+    TMemSpyHeapStatisticsRHeapCommon iStatisticsCommon;
     TMemSpyHeapStatisticsRHeapFree iStatisticsFree;
     TMemSpyHeapStatisticsRHeapAllocated iStatisticsAllocated;
-
-public: // I am fed up of all these pointless inline accessors...
-	TInt iCommittedFreeSpace; // The amount of committed memory that isn't payload data in allocated or free cells
     };
 
 
@@ -175,15 +275,10 @@
           iChunkHandle( NULL ),
           iChunkBaseAddress( NULL ),
           iDebugAllocator( EFalse ),
-          //iHeaderSizeFree( 0 ),
-          //iHeaderSizeAllocated( 0 ),
+          iHeaderSizeFree( 0 ),
+          iHeaderSizeAllocated( 0 ),
           iIsUserThread( ETrue ),
-		  iVTable(0),
-          iSharedHeap( EFalse ),
-          iHeapSize(0),
-          iAllocatorAddress(NULL),
-		  iMinHeapSize(0),
-		  iMaxHeapSize(0)
+          iSharedHeap( EFalse )
         {
         }
 
@@ -263,6 +358,12 @@
     inline TAny* ChunkBaseAddress() const { return iChunkBaseAddress; }
     inline void SetChunkBaseAddress( TAny* aValue ) { iChunkBaseAddress = aValue; }
     //
+    inline TUint HeaderSizeFree() const { return iHeaderSizeFree; }
+    inline void SetHeaderSizeFree( TUint aValue ) { iHeaderSizeFree = aValue; }
+    //
+    inline TUint HeaderSizeAllocated() const { return iHeaderSizeAllocated; }
+    inline void SetHeaderSizeAllocated( TUint aValue ) { iHeaderSizeAllocated = aValue; }
+    //
     inline TBool IsDebugAllocator() const { return iDebugAllocator; }
     inline void SetDebugAllocator( TBool aValue ) { iDebugAllocator = aValue; }
     //
@@ -274,24 +375,30 @@
     //
     inline TUint VTable() const { return iVTable; }
     inline void SetVTable( TUint aValue ) { iVTable = aValue; }
+    //
+    inline TUint ClassSize() const { return iClassSize; }
+    inline void SetClassSize( TUint aValue ) { iClassSize = aValue; }
 
 private: // Data members
     TBuf8< KMaxFullName * 2 > iChunkName;
-public:
     TUint iChunkSize;
     TAny* iChunkHandle;
     TAny* iChunkBaseAddress;
     TBool iDebugAllocator;
+    TUint iHeaderSizeFree;
+    TUint iHeaderSizeAllocated;
     TBool iSharedHeap;
     TBool iIsUserThread;
     TUint iVTable;
-	TUint iHeapSize; // Committed size - generally the same as iChunkSize (except maybe for kernel heap)
-	TAny* iAllocatorAddress; // replacement for things using the RHeap base address
-	TUint iMinHeapSize; // Minimum committed size
-	TUint iMaxHeapSize; // Max committed size
+    TUint iClassSize;
     };
 
 
+
+
+
+
+
 /**
  *
  */
@@ -306,17 +413,15 @@
     inline TMemSpyHeapMetaDataRHeap& MetaData() { return iMetaData; }
     inline const TMemSpyHeapMetaDataRHeap& MetaData() const { return iMetaData; }
     //
-    //inline TMemSpyHeapObjectDataRHeap& ObjectData() { return iObjectData; }
-    //inline const TMemSpyHeapObjectDataRHeap& ObjectData() const { return iObjectData; }
+    inline TMemSpyHeapObjectDataRHeap& ObjectData() { return iObjectData; }
+    inline const TMemSpyHeapObjectDataRHeap& ObjectData() const { return iObjectData; }
     //
     inline TMemSpyHeapStatisticsRHeap& Statistics() { return iStatistics; }
     inline const TMemSpyHeapStatisticsRHeap& Statistics() const { return iStatistics; }
 
-	inline TInt Overhead() const { return iMetaData.iHeapSize - iStatistics.StatsAllocated().TypeSize() - iStatistics.iCommittedFreeSpace; }
-
 private: // Data members
     TMemSpyHeapMetaDataRHeap iMetaData;
-    //TMemSpyHeapObjectDataRHeap iObjectData;
+    TMemSpyHeapObjectDataRHeap iObjectData;
     TMemSpyHeapStatisticsRHeap iStatistics;
     };
 
--- a/memspy/memspy_plat/memspy_api/include/memspy/driver/user/MemSpyDriverClient.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/driver/user/MemSpyDriverClient.h	Wed Oct 13 16:17:58 2010 +0300
@@ -157,7 +157,6 @@
      */
     IMPORT_C TInt GetHeapInfoUser( TMemSpyHeapInfo& aInfo, TUint aTid );
     IMPORT_C TInt GetHeapInfoUser( TMemSpyHeapInfo& aInfo, TUint aTid, RArray<TMemSpyDriverFreeCell>& aFreeCells );
-	IMPORT_C TInt GetHeapInfoUser(TMemSpyHeapInfo& aInfo, TUint aTid, RArray<TMemSpyDriverCell>& aCells, TBool aCollectAllocatedCellsAsWellAsFree);
 
     /**
      *
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperECom.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperECom.h	Wed Oct 13 16:17:58 2010 +0300
@@ -194,7 +194,6 @@
     inline const TDesC& Name() const { return *iName; }
     inline const TDesC& Caption() const { return *iCaption; }
     inline CMemSpyEngineEComInterface& Interface() const { return iInterface; }
-    inline CImplementationInformation& Info() const { return *iInfo; }
 
 public: // From MDesCArray
     IMPORT_C TInt MdcaCount() const;
@@ -213,4 +212,4 @@
 
 
 
-#endif
+#endif
\ No newline at end of file
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperFbServ.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperFbServ.h	Wed Oct 13 16:17:58 2010 +0300
@@ -74,7 +74,7 @@
     HBufC8* LocateBitmapArrayHeapCellDataLC( TAny*& aArrayCellAddress, TInt aArrayAllocCount );
     void ReadCObjectConInfoL( TAny* aCellAddress, RArray<TAny*>& aContainerObjects, TInt& aCount, TInt& aAllocated );
     static void ParseCellDataAndExtractHandlesL( const TDesC8& aData, RArray<TInt>& aHandles, TInt aArrayEntryCount );
-    static TBool VerifyCorrectHeapCellL( const TDesC8& aData, TAny* aCellAddress, TAny* aPayloadAddress, TUint aHeapStartingAddress, TUint aHeapMaxSize );
+    static TBool VerifyCorrectHeapCellL( const TDesC8& aData, TAny* aCellAddress, TAny* aPayloadAddress, TUint aHeapStartingAddress, TUint aHeapSize );
     static TUint OffsetToCObjectConBitmapCon();
     static TUint OffsetToCObjectConFontCon();
     static TUint OffsetToBitmapHandleArray();
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperHeap.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperHeap.h	Wed Oct 13 16:17:58 2010 +0300
@@ -26,9 +26,6 @@
 // Driver includes
 #include <memspy/driver/memspydriverobjectsshared.h>
 
-// MemSpyClient includes
-#include <memspy/engine/memspyheapdata.h>
-
 // Classes referenced
 class CMemSpyThread;
 class CMemSpyEngine;
@@ -47,8 +44,7 @@
     void ConstructL();
 
 public: // API - User Heap 
-    IMPORT_C void GetHeapInfoUserL( const TProcessId& aProcess, const TThreadId& aThread, TMemSpyHeapInfo& aInfo, RArray<TMemSpyDriverCell>* aCells = NULL );
-	IMPORT_C void GetHeapInfoUserL(const TProcessId& aProcess, const TThreadId& aThread, TMemSpyHeapInfo& aInfo, RArray<TMemSpyDriverCell>* aCells, TBool aCollectAllocatedCellsAsWellAsFree);
+    IMPORT_C void GetHeapInfoUserL( const TProcessId& aProcess, const TThreadId& aThread, TMemSpyHeapInfo& aInfo, RArray<TMemSpyDriverFreeCell>* aFreeCells = NULL );
     IMPORT_C void GetHeapInfoUserL( const CMemSpyProcess& aProcess, RArray<TMemSpyHeapInfo >& aInfos );
     IMPORT_C void OutputHeapInfoUserL( const CMemSpyThread& aThread );
     IMPORT_C void OutputHeapDataUserL( const CMemSpyThread& aThread );
@@ -61,12 +57,10 @@
     IMPORT_C void OutputHeapDataKernelL();
 
 public: // API - Common
-    IMPORT_C void OutputHeapInfoL( const TMemSpyHeapInfo& aInfo, const TDesC& aThreadName, const RArray<TMemSpyDriverCell>* aCells = NULL );
+    IMPORT_C void OutputHeapInfoL( const TMemSpyHeapInfo& aInfo, const TDesC& aThreadName, const RArray<TMemSpyDriverFreeCell>* aFreeCells = NULL );
     IMPORT_C void OutputHeapInfoForDeviceL( TBool aIncludeKernel = ETrue );
     IMPORT_C CMemSpyEngineOutputList* NewHeapSummaryShortLC( const TMemSpyHeapInfo& aInfo );
-    IMPORT_C CMemSpyEngineOutputList* NewHeapSummaryExtendedLC( const TMemSpyHeapInfo& aInfo, const RArray<TMemSpyDriverCell>* aCells = NULL );
-    //cigasto    
-    IMPORT_C TMemSpyHeapData NewHeapRawInfo( const TMemSpyHeapInfo& aInfo ); //not formatted heap info
+    IMPORT_C CMemSpyEngineOutputList* NewHeapSummaryExtendedLC( const TMemSpyHeapInfo& aInfo, const RArray<TMemSpyDriverFreeCell>* aFreeCells = NULL );
 
 public: // But not exported
     void OutputHeapDataKernelL( TBool aCreateDataStream );
@@ -76,8 +70,9 @@
 private:
     static TUint DescriptorAsDWORD( const TDesC8& aItem );
     void AppendMetaDataL( const TMemSpyHeapInfo& aInfo, CMemSpyEngineOutputList& aList );
+    void AppendObjectDataL( const TMemSpyHeapInfo& aInfo, CMemSpyEngineOutputList& aList );
     void AppendStatisticsL( const TMemSpyHeapInfo& aInfo, CMemSpyEngineOutputList& aList );
-	void AppendCellsL(const RArray<TMemSpyDriverCell>& aCells, CMemSpyEngineOutputList& aList);
+    void AppendFreeCellsL( const RArray<TMemSpyDriverFreeCell>& aFreeCells, CMemSpyEngineOutputList& aList );
     void OutputCSVEntryL( TInt aIndex, const TMemSpyHeapInfo& aInfo, const TDesC& aThreadName, const TDesC& aProcessName );
     void UpdateSharedHeapInfoL( const TProcessId& aProcess, const TThreadId& aThread, TMemSpyHeapInfo& aInfo );
 
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperKernelContainers.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/Helpers/MemSpyEngineHelperKernelContainers.h	Wed Oct 13 16:17:58 2010 +0300
@@ -87,8 +87,6 @@
     IMPORT_C static TPtrC TypeAsString( TMemSpyDriverContainerType aType );
     IMPORT_C TPtrC Name() const;
     IMPORT_C void OutputL( CMemSpyEngineOutputSink& aSink ) const;
-    IMPORT_C TInt Size() const;
-    IMPORT_C TInt ItemsCount() const;
 
 public: // But not exported
     TAny* HandleAt( TInt aIndex ) const;
@@ -139,5 +137,4 @@
 
 
 
-#endif
-
+#endif
\ No newline at end of file
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/MemSpyEngine.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/MemSpyEngine.h	Wed Oct 13 16:17:58 2010 +0300
@@ -60,7 +60,6 @@
     {
 public:
     IMPORT_C static CMemSpyEngine* NewL( RFs& aFsSession );
-    IMPORT_C static CMemSpyEngine* NewL( RFs& aFsSession, TBool aStartServer );
     IMPORT_C ~CMemSpyEngine();
 
 private:
@@ -81,8 +80,6 @@
     IMPORT_C CMemSpyEngineOutputSink& Sink();
     IMPORT_C TMemSpySinkType SinkType();
     IMPORT_C void InstallSinkL( TMemSpySinkType aType );
-    IMPORT_C void InstallDebugSinkL();
-    IMPORT_C void InstallFileSinkL( const TDesC& aRootFolder );
 
 public: // Misc
     IMPORT_C void ListOpenFilesL();
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/MemSpyEngineImp.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/MemSpyEngineImp.h	Wed Oct 13 16:17:58 2010 +0300
@@ -80,7 +80,6 @@
     CMemSpyEngineOutputSink& Sink();
     TMemSpySinkType SinkType();
     void InstallSinkL( TMemSpySinkType aType );
-    void InstallSinkL( TMemSpySinkType aType, const TDesC& aRootFolder );
 
 public: // Misc
     void ListOpenFilesL();
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/Sink/MemSpyEngineOutputSink.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/Sink/MemSpyEngineOutputSink.h	Wed Oct 13 16:17:58 2010 +0300
@@ -48,16 +48,13 @@
     IMPORT_C static CMemSpyEngineSinkMetaData* NewL();
     IMPORT_C static CMemSpyEngineSinkMetaData* NewL( const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp );
     IMPORT_C static CMemSpyEngineSinkMetaData* NewL( const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp, const TTime& aFolderTimeStamp );
-    IMPORT_C static CMemSpyEngineSinkMetaData* NewL( const TDesC& aRoot, const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp );
-    IMPORT_C static CMemSpyEngineSinkMetaData* NewL( const TDesC& aRoot, const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, TBool aOverwrite, TBool aUseFileTimeStamp, const TTime& aFolderTimeStamp );
     IMPORT_C ~CMemSpyEngineSinkMetaData();
 
 private:
     CMemSpyEngineSinkMetaData( TBool aOverwrite, TBool aUseTimeStamp );
-    void ConstructL( const TDesC& aRoot, const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, const TTime& aFolderTime );
+    void ConstructL( const TDesC& aContext, const TDesC& aFolder, const TDesC& aExtension, const TTime& aFolderTime );
 
 public: // Access
-    inline const TDesC& Root() const { return *iRoot; }
     inline const TDesC& Context() const { return *iContext; }
     inline const TDesC& Folder() const { return *iFolder; }
     inline const TDesC& Extension() const { return *iExtension; }
@@ -66,7 +63,6 @@
     inline const TBool UseFileTimeStamp() const { return iUseFileTimeStamp; }
 
 private: // Data members
-    HBufC* iRoot;
     HBufC* iContext;
     HBufC* iFolder;
     HBufC* iExtension;
@@ -150,4 +146,4 @@
 
 
 
-#endif
+#endif
\ No newline at end of file
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/SysMemTracker/MemSpyEngineHelperSysMemTracker.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/SysMemTracker/MemSpyEngineHelperSysMemTracker.h	Wed Oct 13 16:17:58 2010 +0300
@@ -58,10 +58,9 @@
     //
     IMPORT_C const RPointerArray< CMemSpyEngineHelperSysMemTrackerCycle >& CompletedCycles() const;
 
-    IMPORT_C void CheckForChangesNowL();
-
 public: // But not exported
     void Reset();
+    void CheckForChangesNowL();
 
 public: // From MDesCArray
     IMPORT_C TInt MdcaCount() const;
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/SysMemTracker/MemSpyEngineHelperSysMemTrackerConfig.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/SysMemTracker/MemSpyEngineHelperSysMemTrackerConfig.h	Wed Oct 13 16:17:58 2010 +0300
@@ -23,7 +23,6 @@
 
 // Constants
 const TInt KMemSpySysMemTrackerConfigMinTimerPeriod = 30; // Seconds
-const TInt KMemSpySysMemTrackerConfigMaxTimerPeriod = 60; // Seconds
 
 
 NONSHARABLE_CLASS( TMemSpyEngineHelperSysMemTrackerConfig )
@@ -91,4 +90,4 @@
     };
 
 
-#endif
+#endif
\ No newline at end of file
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectProcess.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectProcess.h	Wed Oct 13 16:17:58 2010 +0300
@@ -65,11 +65,7 @@
     IMPORT_C TBool IsDead() const;
     IMPORT_C TUint32 SID() const;
     IMPORT_C TUint32 VID() const;
-    IMPORT_C TProcessPriority Priority() const;
-    IMPORT_C TExitCategoryName ExitCategory() const;
-    IMPORT_C TInt ExitReason() const;
-    IMPORT_C TExitType ExitType() const;
-    
+
 public: // API - misc
     IMPORT_C void KillL();
     IMPORT_C void TerminateL();
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectThread.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectThread.h	Wed Oct 13 16:17:58 2010 +0300
@@ -56,7 +56,6 @@
     IMPORT_C TBool IsSystemPermanent() const;
     IMPORT_C TBool IsSystemCritical() const;
     IMPORT_C TBool IsDead() const;
-    IMPORT_C TThreadPriority Priority() const;
 
 public: // API - misc
     IMPORT_C void KillL();
@@ -106,4 +105,4 @@
 
 
 
-#endif
+#endif
\ No newline at end of file
--- a/memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectThreadInfoObjects.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/memspy_plat/memspy_api/include/memspy/engine/ThreadAndProcess/MemSpyEngineObjectThreadInfoObjects.h	Wed Oct 13 16:17:58 2010 +0300
@@ -98,8 +98,6 @@
 public: // From MDesCArray
     IMPORT_C TInt MdcaCount() const;
     IMPORT_C TPtrC MdcaPoint(TInt aIndex) const;
-    IMPORT_C TPtrC Caption(TInt aIndex ) const;
-    IMPORT_C TPtrC Value(TInt aIndex ) const;
 
 protected:
     class CItem : public CBase
@@ -506,8 +504,7 @@
 
 private: // Internal methods
     static TBool CompareEntries( const CSessionInfoEntry& aLeft, const CSessionInfoEntry& aRight );
-    TInt FindServerL( const TDesC& aName ) const;
-    
+
 private:
     RPointerArray<CSessionInfoEntry> iServerNames;
     };
--- a/memspy/rom/memspy.iby	Wed Sep 15 13:53:27 2010 +0300
+++ b/memspy/rom/memspy.iby	Wed Oct 13 16:17:58 2010 +0300
@@ -22,17 +22,12 @@
 file=ABI_DIR\BUILD_DIR\MemSpyDriverClient.dll									SHARED_LIB_DIR\MemSpyDriverClient.dll
 file=ABI_DIR\BUILD_DIR\MemSpyEngine.dll											SHARED_LIB_DIR\MemSpyEngine.dll
 
-// Client - server
-file=ABI_DIR\BUILD_DIR\MemSpyServer.exe											SHARED_LIB_DIR\MemSpyServer.exe
-file=ABI_DIR\BUILD_DIR\MemSpyClient.dll											SHARED_LIB_DIR\MemSpyClient.dll
-data=ZPRIVATE\\E5883BC2\MemSpyEComInterfaceIds.xml							    \private\E5883BC2\MemSpyEComInterfaceIds.xml
-
 // Commandline
 file=ABI_DIR\BUILD_DIR\MemSpy.exe									            SHARED_LIB_DIR\MemSpy.exe
 
 // Console UI
-//file=ABI_DIR\BUILD_DIR\MemSpyConsole.exe										SHARED_LIB_DIR\MemSpyConsole.exe
-//data=ZPRIVATE\\2002129E\MemSpyEComInterfaceIds.xml							    \private\2002129E\MemSpyEComInterfaceIds.xml
-//data=ZPRIVATE\\2002129E\MemSpyProcessMemoryTrackingAutoStartConfig.xml		    \private\2002129E\MemSpyProcessMemoryTrackingAutoStartConfig.xml
+file=ABI_DIR\BUILD_DIR\MemSpyConsole.exe										SHARED_LIB_DIR\MemSpyConsole.exe
+data=ZPRIVATE\\2002129E\MemSpyEComInterfaceIds.xml							    \private\2002129E\MemSpyEComInterfaceIds.xml
+data=ZPRIVATE\\2002129E\MemSpyProcessMemoryTrackingAutoStartConfig.xml		    \private\2002129E\MemSpyProcessMemoryTrackingAutoStartConfig.xml
 
 #endif
--- a/piprofiler/engine/inc/SamplerController.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/engine/inc/SamplerController.h	Wed Oct 13 16:17:58 2010 +0300
@@ -81,7 +81,7 @@
 
 	TInt GetPluginList(TDes* aList);
 	
-    TInt SetSamplerSettingsL(TInt aUid, TSamplerAttributes& aAttributes);
+    TInt SetSamplerSettingsL(TInt aUid, TSamplerAttributes aAttributes);
 
     void GetSamplerAttributesL(CArrayFixFlat<TSamplerAttributes>* aAttributes);
 	
--- a/piprofiler/engine/src/ProfilerEshell.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/engine/src/ProfilerEshell.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -35,7 +35,7 @@
 static void PrintUsageInfo(const TDesC& aAdditionalInfo)
     {
     _LIT(KConsoleName, "Console");
-    _LIT(KLegalNote, "PIProfiler Version 2.2.2 Copyright @ 2009 Nokia\n");
+    _LIT(KLegalNote, "PIProfiler Version 2.2.0.2 Copyright @ 2009 Nokia\n");
     _LIT(KUsageNote, "Usage: PIProfiler [start/end/timed] settingsfile [time to run]\n");
     _LIT(KExample, "Example: PIProfiler timed C:\\data\\piprofilersettings.txt 60\n");
 
--- a/piprofiler/engine/src/SamplerController.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/engine/src/SamplerController.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -129,7 +129,7 @@
     return err;
     }
 
-TInt CSamplerController::SetSamplerSettingsL(TInt aUid, TSamplerAttributes& aAttributes)
+TInt CSamplerController::SetSamplerSettingsL(TInt aUid, TSamplerAttributes aAttributes)
     {
     // parse right plugin based on UID
     CSamplerPluginInterface* plugin = GetPlugin(TUid::Uid(aUid));
Binary file piprofiler/group/ReleaseNotes_PIProfiler.txt has changed
--- a/piprofiler/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -26,15 +26,8 @@
 #include "../plugins/DebugOutputWriterPlugin/group/bld.inf"
 #include "../plugins/DiskWriterPlugin/group/bld.inf"
 
-#if ( SYMBIAN_VERSION_SUPPORT >= SYMBIAN_3 )
-    #include "../plugins/PWRPlugin/group/bld.inf"
-#endif
 
 PRJ_EXPORTS
-#if ( SYMBIAN_VERSION_SUPPORT >= SYMBIAN_3 )
-    ../rom/piprofiler.iby CORE_IBY_EXPORT_PATH(tools,piprofiler.iby)
-#else
-    ../rom/piprofiler_s2.iby CORE_IBY_EXPORT_PATH(tools,piprofiler.iby)
-#endif
+../rom/piprofiler.iby CORE_IBY_EXPORT_PATH(tools,piprofiler.iby)
 ../rom/piprofiler_ldd.iby CORE_IBY_EXPORT_PATH(tools/rom,piprofiler_ldd.iby)
 
--- a/piprofiler/piprofiler_plat/inc/SamplerPluginInterface.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/piprofiler_plat/inc/SamplerPluginInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -174,7 +174,7 @@
     * Method for setting configurations of single sampler attributes
     * @param aAttributes contains settings of a single sampler plugin 
     */
-    virtual TInt SetAttributesL(TSamplerAttributes& aAttributes) = 0; 
+    virtual TInt SetAttributesL(TSamplerAttributes aAttributes) = 0; 
     
     /**
     * Method for parsing text formatted settings block and converting
--- a/piprofiler/plugins/BUPplugin/inc/BupPlugin.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/plugins/BUPplugin/inc/BupPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -84,7 +84,7 @@
     TInt    GetSamplerType();
 	
 	void    GetAttributesL(CArrayFixFlat<TSamplerAttributes>* aAttributes);
-    TInt    SetAttributesL(TSamplerAttributes& aAttributes);
+    TInt    SetAttributesL(TSamplerAttributes aAttributes);
     void    InitiateSamplerAttributesL();
 	
     TInt    ConvertRawSettingsToAttributes(CDesC8ArrayFlat* aSingleSettingArray);
--- a/piprofiler/plugins/BUPplugin/src/BupPlugin.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/plugins/BUPplugin/src/BupPlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -116,7 +116,7 @@
     aAttributes->AppendL(iSamplerAttributes->At(0));
     }
 
-TInt CBupPlugin::SetAttributesL(TSamplerAttributes& aAttributes)
+TInt CBupPlugin::SetAttributesL(TSamplerAttributes aAttributes)
     {
     TSamplerAttributes attr;
 
--- a/piprofiler/plugins/GeneralsPlugin/inc/GeneralsPlugin.h	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/plugins/GeneralsPlugin/inc/GeneralsPlugin.h	Wed Oct 13 16:17:58 2010 +0300
@@ -110,7 +110,7 @@
 	TInt 	SubId( TUid aSubId ) const;	// internal
 
 	void    GetAttributesL(CArrayFixFlat<TSamplerAttributes>* aAttributes);
-	TInt    SetAttributesL(TSamplerAttributes& aAttributes);
+	TInt    SetAttributesL(TSamplerAttributes aAttributes);
 	void    InitiateSamplerAttributesL();
 	
 	TInt    ConvertRawSettingsToAttributes(CDesC8ArrayFlat* aSingleSettingArray);
--- a/piprofiler/plugins/GeneralsPlugin/src/GeneralsPlugin.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/plugins/GeneralsPlugin/src/GeneralsPlugin.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -275,7 +275,7 @@
         }
     }
 
-TInt CGeneralsPlugin::SetAttributesL(TSamplerAttributes& aAttributes)
+TInt CGeneralsPlugin::SetAttributesL(TSamplerAttributes aAttributes)
     {
     TSamplerAttributes attr;
 
--- a/piprofiler/plugins/GeneralsPlugin/src/GppSamplerImpl.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/plugins/GeneralsPlugin/src/GppSamplerImpl.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -76,7 +76,7 @@
 	{
 	LOGTEXT("GppSamplerImpl::Reset");
 	iLastPc = 0;
-	iLastThread = 0xfffffffe;
+	iLastThread = 0;
 	iRepeat = 0;
 	iIsaStatus = 0;
 	iIsaStart = 0;
--- a/piprofiler/plugins/GeneralsPlugin/src/MemSamplerImpl.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/plugins/GeneralsPlugin/src/MemSamplerImpl.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -339,6 +339,7 @@
             // this chunk has not been tagged yet
             name.Zero();
             c->TraceAppendName(name,false);
+            const TUint8* ptr = name.Ptr();
             
             TAG(c) = (PROFILER_CHUNK_MARK);
             this->heapChunkNamesToReport[iNewChunkCount] = c;
@@ -462,6 +463,7 @@
             // this library has not been tagged yet
             name.Zero();
             l->TraceAppendName(name,false);
+            const TUint8* ptr = name.Ptr();
             
             TAG(l) = (PROFILER_LIBRARY_MARK);
             this->libraryNamesToReport[iNewLibraryCount] = l;
--- a/piprofiler/plugins/PWRplugin/data/2001E5B9.rss	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  
-*
-*/
-
-
-#include <ecom/registryinfo.rh>
-
-// Declares info for two implementations
-RESOURCE REGISTRY_INFO theInfo
-    {
-    // UID for the DLL. See mmp files
-    //__SERIES60_3X__ can't be used in resource files
-    dll_uid = 0x2001E5B9;
-
-    // Declare array of interface info. This dll contains implementations for 
-    // only one interface (CSamplerInterfaceDefinition).
-    interfaces = 
-        {
-        INTERFACE_INFO
-            {
-            // UID of interface that is implemented
-            interface_uid = 0x2001E5BC;
-
-            implementations = 
-                {
-                IMPLEMENTATION_INFO
-                    {
-                    implementation_uid = 0x2001E5B9;
-
-                    version_no = 1;
-                    display_name = "PWR Sampler";
-                    default_data = "pwr";
-                    opaque_data = "10";
-                    }
-                };
-            }
-        };
-    }
--- a/piprofiler/plugins/PWRplugin/group/PWRPlugin.mmp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,53 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  
-*
-*/
-
-
-#include <platform_paths.hrh>
-
-
-TARGET          PIProfilerPWR.dll
-TARGETTYPE      PLUGIN
-UID             0x10009D8D 0x2001E5B9
-VENDORID        VID_DEFAULT
-CAPABILITY      ALL -TCB
-SMPSAFE
-
-OS_LAYER_SYSTEMINCLUDE
-USERINCLUDE     ../inc
-USERINCLUDE     ../../../inc
-SOURCEPATH      ../src
-
-START RESOURCE  ../data/2001E5B9.rss
-TARGET PIProfilerPWR.rsc
-END
-
-SOURCE          PwrPluginImplementationTable.cpp
-SOURCE          PwrPlugin.cpp
-
-LIBRARY     euser.lib
-LIBRARY     ecom.lib
-LIBRARY     apparc.lib
-LIBRARY     cone.lib
-LIBRARY     gdi.lib
-LIBRARY     ws32.lib
-LIBRARY     efsrv.lib
-LIBRARY     charconv.lib
-LIBRARY     CommonEngine.lib
-LIBRARY     flogger.lib
-LIBRARY     centralrepository.lib
-LIBRARY     HWRMPowerClient.lib
-LIBRARY     HWRMLightClient.lib
--- a/piprofiler/plugins/PWRplugin/group/bld.inf	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  
-*
-*/
-
-#ifndef SBSV2
-PRJ_PLATFORMS
-DEFAULT
-#endif
-
-PRJ_MMPFILES
-#ifdef MARM
-  #ifndef __SERIES60_30__
-    PWRPlugin.mmp
-  #endif
-#endif
--- a/piprofiler/plugins/PWRplugin/inc/PwrPlugin.h	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,167 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  
-*
-*/
-
-#ifndef BAPPEA_PWR_SAMPLER_H
-#define BAPPEA_PWR_SAMPLER_H
-
-//#define PWR_SAMPLER_BACKLIGHT
-
-//#include "PIProfilerConfigInternal.h"
-
-// system definitions
-#include <w32std.h>
-#include <e32std.h>
-
-#include <e32property.h>
-#include <HWRMPower.h>
-#include <HWRMLight.h>
-
-// user definitions
-#include <piprofiler/SamplerPluginInterface.h>
-#include <piprofiler/ProfilerGenericClassesUsr.h>
-
-// caption definitions
-_LIT8(KPWRShortName, "pwr");
-_LIT8(KPWRMediumName, "Power sampler");
-_LIT8(KPWRLongName, "Power usage sampler");
-_LIT8(KPWRDescription, "Power sampler: \nSampling power consumption on Nokia S60 devices\nHW dep: N/A\nSW dep: S60 3.0\n");
-
-// Minimum allowed sampling interval (in ms). 0 means undefined.
-const TInt KMinSampleInterval = 250;
-const TInt KReportingPeriodInfinite = 0;
-
-const TUid KGppPropertyCat={0x20201F70};
-enum TGppPropertyKeys
-    {
-    EGppPropertySyncSampleNumber
-    };
-
-const TUid KPwrNotifierUid = { 0x2001E5B9 };
-class CProfilerPowerListener;
-
-/*
- *
- * PWR sampler plug-in definition
- *
- */
-
-class CPwrPlugin : public CSamplerPluginInterface
-{
-public:
-    static  CPwrPlugin* NewL(const TUid aImplementationUid, TAny* aInitParams);
-            ~CPwrPlugin();
-
-    TInt    ResetAndActivateL(CProfilerSampleStream& aStream);
-    TInt    StopSampling();
-    TBool   Enabled() { return iEnabled; }
-    void    SetEnabled(TBool aEnabled);
-    TInt    GetSamplerType();
-
-    TInt    CreateFirstSample();
-
-    void    GetAttributesL(CArrayFixFlat<TSamplerAttributes>* aAttributes);
-    TInt    SetAttributesL(TSamplerAttributes& aAttributes);
-    void    InitiateSamplerAttributesL();
-
-    TInt    ConvertRawSettingsToAttributes(CDesC8ArrayFlat* aSingleSettingArray);
-
-    TInt    DoSetSamplerSettings(CDesC8ArrayFlat* aAllSettings, TDesC8& aSamplerName, TInt aIndex);
-    void    SaveSettingToAttributes(const TDesC8& aSetting, TInt aIndex);
-
-    TUid    Id(TInt aSubId) const;
-
-    // subsampler settings, i.e. samplers implemented within a plugin
-    // no sub samplers, from CSamplerPluginInterface
-    TInt    SubId(TUid aId) const {return KErrNotFound;}
-    TInt    GetSubSamplers(TDes* aDes){return KErrNotFound;}
-
-private:
-            CPwrPlugin();
-    void    ConstructL();
-
-private:
-    TUint8                  iVersion[20];
-    TPtr8                   iVersionDescriptor;
-
-    TInt                    iSamplerType;
-
-    CProfilerPowerListener* iPowerListener;
-
-    TInt                    iPeriod;
-    CArrayFixFlat<TSamplerAttributes>* iSamplerAttributes;
-public:
-    TUint32*                iSampleTime;
-};
-
-#ifdef PWR_SAMPLER_BACKLIGHT
-class CProfilerPowerListener : public CBase, public MHWRMBatteryPowerObserver, public MHWRMLightObserver
-#else
-class CProfilerPowerListener : public CBase, public MHWRMBatteryPowerObserver
-#endif
-{
-public:
-    static  CProfilerPowerListener* NewL(CPwrPlugin* aSampler);
-            ~CProfilerPowerListener();
-
-private:
-            CProfilerPowerListener(CPwrPlugin* aSampler);
-    void    ConstructL();
-
-public:
-    TInt    StartL(const TDesC8& aBuf);
-    TInt    Stop();
-    TInt    DisplayNotifierL(const TDesC& aLine1, const TDesC& aLine2, const TDesC& aButton1, const TDesC& aButton2);
-
-    // From MHWRMBatteryPowerObserver
-    virtual void PowerMeasurement(TInt aErr, CHWRMPower::TBatteryPowerMeasurementData& aMeasurement);
-#ifdef PWR_SAMPLER_BACKLIGHT
-    // From MHWRMLightObserver
-    virtual void LightStatusChanged(TInt aTarget, CHWRMLight::TLightStatus aStatus);
-#endif
-
-private:
-    void    Sample();
-
-public:
-    TInt                    iPwrSamplingPeriod;
-    TInt                    iSampleStartTime;
-    // Value that is read from Central Repository and restored after sampling
-    TInt                    iOriginalReportingPeriod;
-
-private:
-
-#ifdef PWR_SAMPLER_BACKLIGHT
-    TUint8                  iSample[13];
-#else
-    TUint8                  iSample[12];
-#endif
-
-    TUint16                 iNominalCapa;
-    TUint16                 iVoltage;
-    TUint16                 iCurrent;
-
-    CPwrPlugin*             iSampler;
-    CHWRMPower*             iPowerAPI;
-
-#ifdef PWR_SAMPLER_BACKLIGHT
-    CHWRMLight*             iLightAPI;
-    CHWRMLight::TLightStatus iBackLightStatus;
-#endif
-};
-
-#endif
-
--- a/piprofiler/plugins/PWRplugin/sis/PWRPlugin.pkg	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,44 +0,0 @@
-;
-; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-; All rights reserved.
-; This component and the accompanying materials are made available
-; under the terms of "Eclipse Public License v1.0"
-; which accompanies this distribution, and is available
-; at the URL "http://www.eclipse.org/legal/epl-v10.html".
-;
-; Initial Contributors:
-; Nokia Corporation - initial contribution.
-;
-; Contributors:
-;
-; Description:
-;
-; ShapeImplementation_30_gcce.pkg
-;
-
-;Language - standard language definitions
-&EN
-
-; standard sis file header
-#{"Shape plugin"},(0xE01F614F),2,0,0
-
-
-;
-;Localised Vendor name
-;
-%{"Forum Nokia"}
-
-;
-;Unique Vendor name
-;
-:"Forum Nokia"
-
-;
-;Supports Series 60 v 3.0
-;
-[0x101F7961], 0, 0, 0, {"Series60ProductID"}
-
-
-;Files to include. Check the source paths they match your SDK setup. 
-"\Symbian\9.1\S60_3rd_MR\Epoc32\release\gcce\urel\shapeimplementation.dll"     -   "!:\sys\bin\shapeimplementation.dll"
-"\Symbian\9.1\S60_3rd_MR\epoc32\data\Z\Resource\plugins\shapeimplementation.rsc"   -   "!:\Resource\Plugins\shapeimplementation.RSC"
--- a/piprofiler/plugins/PWRplugin/src/PwrPlugin.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,623 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  
-*
-*/
-
-#include "PwrPlugin.h"
-#include <piprofiler/ProfilerTraces.h>
-
-#include <centralrepository.h>
-#include <HWRMPower.h>
-#include <HWRMLight.h>
-#include <hwrm/hwrmpowerdomaincrkeys.h>
-
-
-// texts for notes
-_LIT(KPowerTextLine1, "Power sampler:");
-_LIT(KPowerTextLine2, "Failed to start power measurement");
-_LIT(KPowerTextErrorSampling, "Error receiving measurement data");
-_LIT(KButtonOk, "Ok");
-
-// LITERALS
-
-_LIT8(KSamplingPeriodMs, "sampling_period_ms");
-
-// CONSTANTS
-// Use this UID if plugin is PwrPlugin:
-const TUid KSamplerPwrPluginUid = { 0x2001E5B9 };
-
-/*
- *
- * class CPwrPlugin implementation
- * 
- */
- 
-CPwrPlugin* CPwrPlugin::NewL(const TUid /*aImplementationUid*/, TAny* aInitParams)
-    {
-    LOGTEXT(_L("CPwrPlugin::NewL() - entry"));
-    CPwrPlugin* self = new (ELeave) CPwrPlugin();
-    CleanupStack::PushL( self );
-    self->ConstructL();
-    CleanupStack::Pop();
-    LOGTEXT(_L("CPwrPlugin::NewL() - exit"));
-    return self;
-    }
-
-CPwrPlugin::CPwrPlugin() :
-    iVersionDescriptor(&(this->iVersion[1]),0,19),
-    iSamplerType(PROFILER_USER_MODE_SAMPLER)
-    {
-    iPeriod = 250;
-    iSamplerId = PROFILER_PWR_SAMPLER_ID;
-    iEnabled = EFalse;
-    iPowerListener = NULL;
-    LOGTEXT(_L("CPwrPlugin::CPwrPlugin() - konstruktori"));
-
-    }
-
-void CPwrPlugin::ConstructL() 
-    {
-    LOGTEXT(_L("CPwrPlugin::ConstructL() - entry"));
-    // initiate sampler attributes array
-    iSamplerAttributes = new(ELeave) CArrayFixFlat<TSamplerAttributes>(1); // only one sampler
-
-    // insert default attributes to array
-    InitiateSamplerAttributesL();
-
-    LOGTEXT(_L("CPwrPlugin::ConstructL() - exit"));
-    }
-
-CPwrPlugin::~CPwrPlugin()
-    {
-    LOGTEXT(_L("CPwrPlugin::~CPwrPlugin() - entry"));
-    if(iPowerListener)
-        {
-        if(Enabled())
-            {
-            iPowerListener->Stop();
-            }
-        delete iPowerListener;
-        iPowerListener = NULL;
-        }
-
-    if(iSamplerAttributes)
-        {
-        iSamplerAttributes->Reset();
-        delete iSamplerAttributes;
-        iSamplerAttributes = NULL;
-        }
-
-    LOGTEXT(_L("CPwrPlugin::~CPwrPlugin() - exit"));
-    }
-
-TUid CPwrPlugin::Id(TInt /*aSubId*/) const
-    {
-    LOGSTRING2( "CPwrPlugin::Id():0x%X", KSamplerPwrPluginUid.iUid );
-    return KSamplerPwrPluginUid;
-    }
-
-void CPwrPlugin::InitiateSamplerAttributesL()
-    {
-    // create TSamplerAttributes
-    TSamplerAttributes attr(KSamplerPwrPluginUid.iUid,
-            KPWRShortName(),
-            KPWRLongName(),
-            KPWRDescription(),
-            250,
-            EFalse,
-            EFalse,
-            0); 
-    this->iSamplerAttributes->AppendL(attr);
-    }
-
-void CPwrPlugin::SetEnabled(TBool aEnabled)
-    {
-    iEnabled = aEnabled;
-    }
-
-// returns setting array
-void CPwrPlugin::GetAttributesL(CArrayFixFlat<TSamplerAttributes>* aAttributes)
-    {
-    aAttributes->AppendL(iSamplerAttributes->At(0));
-    }
-
-TInt CPwrPlugin::SetAttributesL(TSamplerAttributes& aAttributes)
-    {
-    TSamplerAttributes attr;
-
-    attr = iSamplerAttributes->At(0);
-    // replace the old attribute container
-    iSamplerAttributes->Delete(0);
-    iSamplerAttributes->InsertL(0, aAttributes);
-    return KErrNone;
-    }
-
-/* 
- * Method for parsing and transforming text array settings into TSamplerAttributes (per each sub sampler),
- * called by CSamplerController class
- * 
- * @param array of raw text setting lines, e.g. [gpp]\nenabled=true\nsampling_period_ms=1\n
- */
-TInt CPwrPlugin::ConvertRawSettingsToAttributes(CDesC8ArrayFlat* aAllSettingsArray)
-    {
-    // local literals
-    _LIT8(KPWRShort, "pwr");
-
-    TInt err(KErrNone);
-    TBuf8<16> samplerSearchName;
-    samplerSearchName.Copy(KPWRShort);
-
-    // get sampler specific settings  
-    err = DoSetSamplerSettings(aAllSettingsArray, samplerSearchName, 0);
-
-    // returns KErrNone if settings found, otherwise KErrNotFound
-    return err;
-    }
-
-TInt CPwrPlugin::DoSetSamplerSettings(CDesC8ArrayFlat* aAllSettings, TDesC8& aSamplerName, TInt aIndex)
-    {
-    // 
-    TBuf8<16> samplerSearch;
-    samplerSearch.Copy(KBracketOpen);
-    samplerSearch.Append(aSamplerName);
-    samplerSearch.Append(KBracketClose);
-
-    // read a line
-    for (TInt i(0); i<aAllSettings->MdcaCount(); i++)
-        {
-        // check if this line has a setting block start, i.e. contains [xxx] in it
-        if (aAllSettings->MdcaPoint(i).CompareF(samplerSearch) == 0)
-            {
-            // right settings block found, now loop until the next block is found
-            for(TInt j(i+1);j<aAllSettings->MdcaCount();j++)
-                {
-                // check if the next settings block was found
-                if(aAllSettings->MdcaPoint(j).Left(1).CompareF(KBracketOpen) != 0)
-                    {
-                    // save found setting value directly to its owners attributes
-                    SaveSettingToAttributes(aAllSettings->MdcaPoint(j), aIndex);
-                    }
-                else
-                    {
-                    // next block found, return KErrNone
-                    return KErrNone;
-                    }
-                }
-            }
-        }
-
-    return KErrNotFound;
-    }
-
-/**
- * Method for setting a specific descriptor (from settings file) to attribute structure
- * 
- * @param aSetting  
- * @param aName  
- */
-void CPwrPlugin::SaveSettingToAttributes(const TDesC8& aSetting, TInt aIndex)
-    {
-    // find the equal mark from the setting line
-    TInt sepPos = aSetting.Find(KSettingItemSeparator);
-    // check that '=' is found
-    if (sepPos > 0)
-        {
-        // check that the element matches
-        if (aSetting.Left(sepPos).CompareF(KEnabled) == 0)
-            {
-            TBool en;
-            CSamplerPluginInterface::Str2Bool(aSetting.Right(aSetting.Length()-sepPos-1), en);
-            if(en != iSamplerAttributes->At(aIndex).iEnabled)
-                {
-                iSamplerAttributes->At(aIndex).iEnabled = en;
-                }
-            }
-        else if (aSetting.Left(sepPos).CompareF(KSamplingPeriodMs) == 0)
-            {
-            TInt sr;
-            CSamplerPluginInterface::Str2Int(aSetting.Right(aSetting.Length()-sepPos-1), sr);
-            if(sr != iSamplerAttributes->At(aIndex).iSampleRate)
-                {
-                iSamplerAttributes->At(aIndex).iSampleRate = sr;
-                }
-            }
-        }
-    }
-
-TInt CPwrPlugin::GetSamplerType()
-    {
-    return iSamplerType;
-    }
-
-TInt CPwrPlugin::ResetAndActivateL(CProfilerSampleStream& aStream) 
-    {
-    LOGTEXT(_L("CPwrPlugin::ResetAndActivate() - entry"));
-    // check if sampler enabled
-    if(iSamplerAttributes->At(0).iEnabled)
-        {
-        // create a new listener instance for every trace, destroy it on stop
-        iPowerListener = CProfilerPowerListener::NewL(this);
-
-        iStream = &aStream;
-        TInt length = this->CreateFirstSample();
-        iVersion[0] = (TUint8)length;
-        LOGSTRING2("CPwrPlugin::ResetAndActivate() - AddSample, length %d", length);
-        TInt ret = this->AddSample(iVersion, length+1, 0);
-
-        LOGSTRING2("CPwrPlugin::ConstructL() - sampling period %d", this->iPeriod);
-
-        HBufC8* iBufRes = HBufC8::NewMaxLC(10);
-        TPtr8 iPtrRes = iBufRes->Des();
-
-        // check if sampling rate set to something reasonable, relevant only in SYNC case
-        if(iSamplerAttributes->At(0).iSampleRate != -1)
-            {
-            iPtrRes.Num(iSamplerAttributes->At(0).iSampleRate);
-            }
-        else
-            {
-            iPtrRes.Append(KNullDesC8);
-            }
-
-        // set disabled
-        SetEnabled(ETrue); 
-
-        // activate power listener
-        ret = iPowerListener->StartL(iPtrRes);
-        LOGTEXT(_L("CPwrPlugin::ResetAndActivate() - exit"));
-
-        CleanupStack::PopAndDestroy();
-        
-        if(ret != KErrNone)
-            return ret;
-        }
-    return KErrNone;
-    }
-
-TInt CPwrPlugin::CreateFirstSample() 
-    {
-    LOGTEXT(_L("CPwrPlugin::CreateFirstSample - entry"));
-    this->iVersionDescriptor.Zero();
-    this->iVersionDescriptor.Append(_L8("Bappea_PWR_V"));
-    this->iVersionDescriptor.Append(PROFILER_PWR_SAMPLER_VERSION);
-    LOGTEXT(_L("CPwrPlugin::CreateFirstSample - exit"));
-    return (TInt)(this->iVersionDescriptor.Length());
-    }
-
-TInt CPwrPlugin::StopSampling() 
-    {
-    if(iPowerListener)
-        {
-        iPowerListener->Stop();
-        delete iPowerListener;
-        iPowerListener = NULL;
-        }
-
-    // set disabled
-    SetEnabled(EFalse);
-
-    return KErrNone;
-    }
-
-
-/*
- *
- * class CProfilerPowerListener implementation
- * 
- */
-
-CProfilerPowerListener::CProfilerPowerListener(CPwrPlugin* aSampler) :
-    iPwrSamplingPeriod(0),
-    iOriginalReportingPeriod(0),
-    iNominalCapa(0),
-    iVoltage(0), 
-    iCurrent(0),
-    iPowerAPI(0)
-#ifdef PWR_SAMPLER_BACKLIGHT
-    ,iLightAPI(0),
-    iBackLightStatus(CHWRMLight::ELightStatusUnknown)
-#endif
-
-    {
-    LOGTEXT(_L("CProfilerPowerListener::CProfilerPowerListener() - konstuktori"));
-    this->iSampler = aSampler;
-    LOGTEXT(_L("CProfilerPowerListener::CProfilerPowerListener() - konstuktori exit"));
-    }
-
-CProfilerPowerListener* CProfilerPowerListener::NewL(CPwrPlugin* aSampler)
-    {
-    LOGTEXT(_L("CProfilerPowerListener::NewL() - entry"));
-    CProfilerPowerListener* self = new (ELeave) CProfilerPowerListener(aSampler);
-    CleanupStack::PushL( self );
-    self->ConstructL();
-    CleanupStack::Pop();
-    LOGTEXT(_L("CProfilerPowerListener::NewL() - exit"));
-    return self;
-    }
-
-void CProfilerPowerListener::ConstructL()
-    {
-    LOGTEXT(_L("CProfilerPowerListener::ConstructL() - entry"));
-    iSampleStartTime = 0;
-    LOGTEXT(_L("CProfilerPowerListener::ConstructL() - exit"));
-    }
-
-CProfilerPowerListener::~CProfilerPowerListener() 
-    {
-    LOGTEXT(_L("CProfilerPowerListener::~CProfilerPowerListener() - entry"));
-
-    if (iPowerAPI)
-        {
-        delete iPowerAPI;
-        iPowerAPI = 0;
-        }
-#ifdef PWR_SAMPLER_BACKLIGHT
-    if (iLightAPI)
-        {
-        delete iLightAPI;
-        iLightAPI = 0;
-        }
-#endif
-
-    LOGTEXT(_L("CProfilerPowerListener::~CProfilerPowerListener() - exit"));
-    }
-
-TInt CProfilerPowerListener::DisplayNotifierL(const TDesC& aLine1, const TDesC& aLine2, const TDesC& aButton1, const TDesC& aButton2)
-    {
-    RNotifier notifier;
-    TRequestStatus stat;
-
-    TInt buttonValue(0);
-
-    User::LeaveIfError(notifier.Connect());
-
-    notifier.Notify(aLine1, aLine2, aButton1, aButton2, buttonValue, stat);
-    User::WaitForRequest(stat);
-
-    notifier.Close();
-    return buttonValue;
-    }
-
-
-TInt CProfilerPowerListener::StartL(const TDesC8& aBuf)
-    {
-    LOGTEXT(_L("CProfilerPowerListener::StartL() - entry"));
-
-    // get the property value
-    TInt r = RProperty::Get(KGppPropertyCat, EGppPropertySyncSampleNumber, iSampleStartTime);
-    if(r != KErrNone)
-        {
-        LOGSTRING2("CProfilerPowerListener::StartL() - getting iSyncOffset failed, error %d", r);
-        }
-
-   // check if given sampling period is valid
-    if(aBuf.CompareF(KNullDesC8)!= 0)
-        {
-        TLex8* lex = new TLex8(aBuf);
-        lex->Val(iPwrSamplingPeriod);
-        delete lex;
-        }
-    else
-        {
-        // set default period
-        iPwrSamplingPeriod = 250;
-        }
-
-    // Check that sampling period is in allowed range
-    if (KMinSampleInterval > 0 && iPwrSamplingPeriod < KMinSampleInterval)
-        {
-        iPwrSamplingPeriod = KMinSampleInterval;
-        }
-
-    LOGSTRING2("CProfilerPowerListener::StartL() - Sampling period %d", iPwrSamplingPeriod);
-
-    // Start monitoring voltage and current
-    iPowerAPI = CHWRMPower::NewL();
-    iPowerAPI->SetPowerReportObserver(this);
-
-    // Read HWRM reporting settings from central repository
-    CRepository* centRep = CRepository::NewL(KCRUidPowerSettings);
-    TInt baseInterval(0);
-    User::LeaveIfError(centRep->Get(KPowerBaseTimeInterval, baseInterval));
-    User::LeaveIfError(centRep->Get(KPowerMaxReportingPeriod, iOriginalReportingPeriod));
-
-    LOGSTRING2("CProfilerPowerListener::StartL() - HWRM base power report interval: %d", baseInterval);
-    LOGSTRING2("CProfilerPowerListener::StartL() - Original HWRM max power reporting period: %d", iOriginalReportingPeriod);
-
-    User::LeaveIfError(centRep->Set(KPowerMaxReportingPeriod, KReportingPeriodInfinite));
-
-    // Power reporting interval reading may return too low value sometimes. Minimum value expected to be 250ms.
-    if ( baseInterval < KMinSampleInterval )
-        {
-        baseInterval = KMinSampleInterval;
-        LOGSTRING2("CProfilerPowerListener::StartL() - Power report interval too low. Changed to: %d", baseInterval);
-        }
-
-    // Power reporting period is multiplier of HWRM base period
-    TInt intervalMultiplier = iPwrSamplingPeriod / baseInterval;
-
-    if (intervalMultiplier < 1)
-        {
-        intervalMultiplier = 1;
-        }
-
-    LOGSTRING2("CProfilerPowerListener::StartL() - Reporting period multiplier: %d", intervalMultiplier);
-
-    TRequestStatus status(KRequestPending);
-    iPowerAPI->StartAveragePowerReporting(status, intervalMultiplier);
-    User::WaitForRequest(status);
-
-    if (status.Int() != KErrNone)
-        {
-        LOGTEXT(_L("CProfilerPowerListener::StartL() - Failed to initialize power reporting"));
-
-        DisplayNotifierL(KPowerTextLine1, KPowerTextLine2, KButtonOk, KNullDesC);
-
-        return status.Int();
-        }
-
-#ifdef PWR_SAMPLER_BACKLIGHT
-    // Start monitoring backlight status
-    iLightAPI = CHWRMLight::NewL(this);
-#endif
-
-    LOGTEXT(_L("CProfilerPowerListener::StartL() - exit"));
-    return KErrNone;
-    }
-
-void CProfilerPowerListener::Sample()
-    {
-    LOGTEXT(_L("CProfilerPowerListener::Sample() - entry"));
-
-    TRequestStatus status;
-    CHWRMPower::TBatteryConsumptionData consumptionData;
-
-    iPowerAPI->GetBatteryInfo(status, consumptionData);
-    User::WaitForRequest(status);
-
-    // Data is valid only if status == KErrNone 
-    if (status.Int() != KErrNone)
-        {
-        LOGSTRING2("CProfilerPowerListener::Sample() - Getting battery info failed with code: ", status.Int());
-        iNominalCapa = 0;
-        }
-    else
-        {
-        iNominalCapa = consumptionData.iNominalCapacity;
-        }
-
-    // Space for GPP sample time        
-    //TUint32 sampleTime = iSampler->iStream->iSampler->GetSampleTime();
-    TUint32 sampleTime = User::NTickCount() - iSampleStartTime;
-    LOGSTRING2("CProfilerPowerListener::Sample() - Sample time: %d", sampleTime);
-    LOGSTRING2("CProfilerPowerListener::Sample() - Nominal capacitance: %d", iNominalCapa);
-    LOGSTRING2("CProfilerPowerListener::Sample() - Voltage: %d", iVoltage);
-    LOGSTRING2("CProfilerPowerListener::Sample() - Current: %d", iCurrent);
-#ifdef PWR_SAMPLER_BACKLIGHT
-    LOGSTRING2("CProfilerPowerListener::Sample() - Backlight status: %d", (TUint8)iBackLightStatus);
-#endif
-
-    iSample[0] = iNominalCapa;
-    iSample[1] = iNominalCapa >> 8;
-    iSample[2] = iVoltage;
-    iSample[3] = iVoltage >> 8;
-    iSample[4] = iCurrent;
-    iSample[5] = iCurrent >> 8;
-    iSample[6] = iCurrent >> 16;
-    iSample[7] = iCurrent >> 24;
-#ifdef PWR_SAMPLER_BACKLIGHT
-    iSample[8] = (TUint8)iBackLightStatus;
-    iSample[9] = sampleTime;
-    iSample[10] = sampleTime >> 8;
-    iSample[11] = sampleTime >> 16;
-    iSample[12] = sampleTime >> 24;
-
-    iSampler->AddSample(iSample, 13, 0);
-#else
-    iSample[8] = sampleTime;
-    iSample[9] = sampleTime >> 8;
-    iSample[10] = sampleTime >> 16;
-    iSample[11] = sampleTime >> 24;
-
-    iSampler->AddSample(iSample, 12, 0);
-#endif
-
-    LOGTEXT(_L("CProfilerPowerListener::Sample() - exit"));
-    }
-
-TInt CProfilerPowerListener::Stop() 
-    {
-    LOGTEXT(_L("CProfilerPowerListener::Stop() - entry"));
-
-    if (iPowerAPI)
-        {
-        TRAPD(err, iPowerAPI->StopAveragePowerReportingL());
-        if(err != KErrNone)
-            {
-            LOGSTRING2("CProfilerPowerListener::Stop() - Failed to stop power reporting: %d", err);
-            }
-        else
-            {
-            LOGTEXT(_L("CProfilerPowerListener::Stop() - Stopped power monitoring"));
-            }
-        delete iPowerAPI;
-        iPowerAPI = 0;
-
-        // Restore original value to max sampling period
-        CRepository* centRep = 0;
-        TRAP(err, centRep = CRepository::NewL(KCRUidPowerSettings));
-        if (err != KErrNone)
-            {
-            LOGSTRING2("CProfilerPowerListener::Stop() - Failed to open Central Repository: %d", err);
-            }
-        else
-            {
-            err = centRep->Set(KPowerMaxReportingPeriod, iOriginalReportingPeriod);
-            if(err != KErrNone)
-                {
-                LOGSTRING2("CProfilerPowerListener::Stop() - Failed to restore max sampling period: %d", err);
-                }
-            }
-        }
-#ifdef PWR_SAMPLER_BACKLIGHT
-    if (iLightAPI)
-        {
-        delete iLightAPI;
-        iLightAPI = 0;
-        }
-#endif
-
-    LOGTEXT(_L("CProfilerPowerListener::Stop() - exit"));
-    return KErrNone;
-    }
-
-void CProfilerPowerListener::PowerMeasurement(TInt aErr, CHWRMPower::TBatteryPowerMeasurementData& aMeasurement)
-    {
-    LOGTEXT(_L("CProfilerPowerListener::PowerMeasurement - entry"));
-
-    if (aErr == KErrNone)
-        {
-        LOGSTRING3("CProfilerPowerListener::PowerMeasurement - Previous values - Voltage: %d Current: %d", iVoltage, iCurrent);
-        iVoltage = aMeasurement.iAverageVoltage;
-        iCurrent = aMeasurement.iAverageCurrent;
-        LOGSTRING3("CProfilerPowerListener::PowerMeasurement - New values - Voltage: %d Current: %d", iVoltage, iCurrent);
-
-        this->Sample();
-        }
-    else
-        {
-        LOGSTRING2("CProfilerPowerListener::PowerMeasurement - Failed with error code: %d", aErr);
-        DisplayNotifierL(KPowerTextLine1, KPowerTextErrorSampling, KButtonOk, KNullDesC);
-        }
-    LOGTEXT(_L("CProfilerPowerListener::PowerMeasurement - exit"));
-    }
-
-#ifdef PWR_SAMPLER_BACKLIGHT
-void CProfilerPowerListener::LightStatusChanged(TInt aTarget, CHWRMLight::TLightStatus aStatus)
-    {
-    LOGTEXT(_L("CProfilerPowerListener::LightStatusChanged - entry"));
-    LOGSTRING3("CProfilerPowerListener::LightStatusChanged - Target: %d Status: %d", aTarget, aStatus);
-
-    if (aTarget == CHWRMLight::EPrimaryDisplay)
-        {
-        LOGSTRING2("CProfilerPowerListener::LightStatusChanged - Previous light status: %d", iBackLightStatus);
-        iBackLightStatus = aStatus;
-        LOGSTRING2("CProfilerPowerListener::LightStatusChanged - New light status: %d", iBackLightStatus);
-
-        this->Sample();
-        }
-    LOGTEXT(_L("CProfilerPowerListener::LightStatusChanged - exit"));
-    }
-#endif
--- a/piprofiler/plugins/PWRplugin/src/PwrPluginImplementationTable.cpp	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,39 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  
-*
-*/
-
-
-// INCLUDE FILES
-#include <e32std.h>
-#include <ecom/implementationproxy.h>
-
-#include "PwrPlugin.h"
-
-
-// Provides a key value pair table, this is used to identify
-// the correct construction function for the requested interface.
-const TImplementationProxy ImplementationTable[] =
-{
-         IMPLEMENTATION_PROXY_ENTRY(0x2001E5B9,  CPwrPlugin::NewL),
-};
-
-// Function used to return an instance of the proxy table.
-EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
-{
-    aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
-    return ImplementationTable;
-}
-
--- a/piprofiler/rom/piprofiler.iby	Wed Sep 15 13:53:27 2010 +0300
+++ b/piprofiler/rom/piprofiler.iby	Wed Oct 13 16:17:58 2010 +0300
@@ -22,11 +22,11 @@
 // PI Profiler Engine itself 
 file=ABI_DIR\BUILD_DIR\PIProfilerEngine.exe						sys\bin\PIProfilerEngine.exe
 file=ABI_DIR\BUILD_DIR\PIProfiler.exe							sys\bin\PIProfiler.exe
+data=ZSYSTEM\Install\PIProfiler_stub.sis						system\install\PIProfiler_stub.sis
 
 // sampler plugins
 // NOTE: Mandatory kernel driver included in piprofiler_ldd.iby
 ECOM_PLUGIN(PIProfilerGenerals.dll, PIProfilerGenerals.rsc)
-ECOM_PLUGIN(PIProfilerPWR.dll, PIProfilerPWR.rsc)
 
 ECOM_PLUGIN(PIProfilerBUP.dll, PIProfilerBUP.rsc)
 file=ABI_DIR\BUILD_DIR\PIProfilerTouchEventAnim.dll				sys\bin\PIProfilerTouchEventAnim.dll
--- a/piprofiler/rom/piprofiler_s2.iby	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,37 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description:  
-*
-*/
-
-
-#ifndef __PIPROFILER__
-#define __PIPROFILER__
-
-// PI Profiler Engine itself 
-file=ABI_DIR\BUILD_DIR\PIProfilerEngine.exe						sys\bin\PIProfilerEngine.exe
-file=ABI_DIR\BUILD_DIR\PIProfiler.exe							sys\bin\PIProfiler.exe
-
-// sampler plugins
-// NOTE: Mandatory kernel driver included in piprofiler_ldd.iby
-ECOM_PLUGIN(PIProfilerGenerals.dll, PIProfilerGenerals.rsc)
-
-ECOM_PLUGIN(PIProfilerBUP.dll, PIProfilerBUP.rsc)
-file=ABI_DIR\BUILD_DIR\PIProfilerTouchEventAnim.dll				sys\bin\PIProfilerTouchEventAnim.dll
-
-// Writer plugins
-ECOM_PLUGIN(piprofilerdebugwriter.dll, piprofilerdebugwriter.rsc)
-ECOM_PLUGIN(piprofilerdiskwriter.dll, piprofilerdiskwriter.rsc)
-
-#endif //__PIPROFILER__
--- a/piprofiler/symbian_version.hrh	Wed Sep 15 13:53:27 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "Eclipse Public License v1.0"
-* which accompanies this distribution, and is available
-* at the URL "http://www.eclipse.org/legal/epl-v10.html".
-*
-* Initial Contributors:
-* Nokia Corporation - initial contribution.
-*
-* Contributors:
-*
-* Description: Symbian version configuration file 
-*
-*/
-
-#ifndef __SYMBIAN_VERSION_HRH
-#define __SYMBIAN_VERSION_HRH
-
-// S60 and Symbian version number enumeration definitions
-
-#define S60_30                                              30
-#define S60_31                                              31
-#define S60_32                                              32
-#define S60_50                                              50
-#define S60_51                                              91
-#define S60_52                                              92
-#define SYMBIAN_1                                           50
-#define SYMBIAN_2                                           91
-#define SYMBIAN_3                                           92
-#define SYMBIAN_4                                           101
-
-
-/**
- * Defines the S60 or Symbian version used by this component. This flag can be
- * used to variate the source code based on the SDK in use. The value of the
- * flag should be always changed to reflect the current build environment.
- */
-#define SYMBIAN_VERSION_SUPPORT                              SYMBIAN_3
-
-
-#endif  // __SYMBIAN_VERSION_HRH
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSInterface/group/ATSInterface.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's ATSInterface app.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET      	ATSInterface.exe
+TARGETTYPE  	exe
+
+UID		0x1000007a
+
+CAPABILITY	AllFiles CommDD
+VENDORID 	0x101FB657
+SECUREID        0x102073D8
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+
+SOURCE		ATSInterface.cpp 
+SOURCE		ATSInterfaceRunner.cpp
+
+LIBRARY		euser.lib
+LIBRARY		stiftestengine.lib
+LIBRARY		stiftestinterface.lib
+
+// In case of large amount of test cases, bigger heap size is required. 
+// Heap sizes can be changed using EPOCHEAPSIZE statement, where the first
+// parameter is heap's minimum size and the latter the maximum size.
+EPOCHEAPSIZE    0x10000 0x300000
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSInterface/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for STIF ATSInterface.
+*/
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+	ATSInterface.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSInterface/inc/ATSInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,192 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CATSInterface.
+*
+*/
+
+#ifndef ATS_INTERFACE_H
+#define ATS_INTERFACE_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include "TestEngineClient.h"
+#include "TestModuleInfo.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+class CATSInterfaceRunner;
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+// CATSInterface is the main class of ATS Interface
+
+class CATSInterface
+        : public CBase
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None    
+
+    public: // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CATSInterface* NewL();
+        
+        /**
+        * Destructor.
+        */
+        ~CATSInterface();
+
+    public: // New functions
+        
+        /**
+        * Run test cases
+        */
+        void RunTestsL();
+
+        /**
+        * Test case is completed
+        */
+        void TestCompleted( TInt aError );
+
+        /**
+        * Return handle to Test Engine Server.
+        */
+        RTestEngineServer& TestEngineServer();
+
+        /**
+        * Return handle to Test Engine.
+        */
+        RTestEngine& TestEngine();
+
+    public: // Functions from base classes
+        // None
+
+    protected: // New functions
+        // None
+
+    protected: // Functions from base classes
+        // None
+
+    private: // New functions
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * C++ default constructor.
+        */
+        CATSInterface();
+
+        /**
+        * Parse command line
+        */
+        void ParseCommandLineL();
+
+        /**
+        * Run all test cases
+        */
+        void RunAllTestCasesL();
+
+        /**
+        * Run the test case specified by aTestInfo.
+        */
+        void RunTestCaseL( TTestInfo& aTestInfo );
+
+        /**
+        * Run a test case
+        */
+        TInt RunATestCaseL( CATSInterfaceRunner* aTestCase );
+
+        /**
+        * Log errors and leave.
+        */
+        void LogErrorAndLeaveL( const TDesC& aFunction, 
+                                const TDesC& aDescription,
+                                const TInt aError );
+
+        /**
+        * Parse and search for module info and fill list of modules.
+        */
+        void ParseTestModulesL(CStifParser* aParser, CTestModuleList* aModuleList, const TDesC& aSectionStart, const TDesC& aSectionEnd);
+
+    protected: // Data
+        // None
+
+    private: // Data
+
+        // Console window
+        CConsoleBase*           iConsole;
+
+        // Handle to Test Engine Server
+        RTestEngineServer       iTestEngineServ;
+
+        // Handle to Test Engine
+        RTestEngine             iTestEngine;
+
+        // Complete error for test case
+        TInt                    iTestCompletedError;
+
+        // Test Module
+        TName                   iTestModule;
+
+        // Name of the Test Module's config file
+        TFileName               iConfigFile;
+
+        // Name of the Test Engine's ini file
+        TFileName               iEngineIniFile;
+
+        // Name of the Test Module's ini file
+        TFileName               iModuleIniFile;
+
+        // List of found modules (included from module given in parameters)
+        CTestModuleList*        iModuleList;
+
+    public: // Friend classes
+        // None
+
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        // None
+
+    };
+
+
+#endif // ATS_INTERFACE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSInterface/inc/ATSInterfaceRunner.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,257 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CATSInterfaceRunner.
+*
+*/
+
+#ifndef ATS_INTERFACE_RUNNER_H
+#define ATS_INTERFACE_RUNNER_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include "ATSInterface.h"
+
+// CONSTANTS
+
+// Interval for timer printing
+const TInt KPrintInterval = 1000000;
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+// None
+
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+// CATSInterfaceRunner is a class that is used to run test cases using
+// STIF Test Framework.
+
+class CATSInterfaceRunner
+        : public CActive
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public: // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CATSInterfaceRunner* NewL( CATSInterface* aATSInterface,
+             TTestInfo& aTestInfo );
+
+        /**
+        * Destructor of CATSInterfaceRunner.
+        */
+        ~CATSInterfaceRunner();
+
+    public: // New functions
+
+        /**
+        * Run Tests.
+        */
+        TInt RunTestsL();
+
+        /**
+        * Start testing.
+        */
+        void StartTestL();
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive RunL handles request completion.
+        */
+        void RunL();
+
+        /**
+        * From CActive DoCancel handles request cancellation.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive RunError handles error situations.
+        */
+        TInt RunError( TInt aError );
+
+    protected: // New functions
+        // None
+
+    protected: // Functions from base classes
+        // None
+
+    private: // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CATSInterfaceRunner( CATSInterface* aATSInterface,
+            TTestInfo& aTestInfo );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+
+    public: //Data
+        // None
+    
+    protected: // Data
+        // None
+
+    private: // Data
+        
+        // Pointer to ATSInterface
+        CATSInterface*                  iATSInterface;
+
+        // Handle to Test Engine Server
+        RTestEngineServer               iTestEngineServ;
+
+        // Handle to Test Engine
+        RTestEngine                     iTestEngine;
+
+        // Handle to Test Case
+        RTestCase                       iTestCase;
+
+        // Test info and package
+        TTestInfo                       iTestInfo;
+        TTestInfoPckg                   iTestInfoPckg;
+
+        // Test result and package
+        TFullTestResult                 iFullTestResult;
+        TFullTestResultPckg             iFullTestResultPckg;
+
+    public: // Friend classes
+        // None
+
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        // None
+
+    };
+
+
+// DESCRIPTION
+// CActiveTimer is used to print running seconds to Console window
+class CActiveTimer
+        : public CTimer
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public: // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CActiveTimer* NewL( CConsoleBase* aConsole );
+
+        /**
+        * Destructor of CActiveTimer.
+        */
+        ~CActiveTimer();
+
+    public: // New functions
+
+        /**
+        * Start timer.
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive RunL handles request completion.
+        */
+        void RunL();
+
+        /**
+        * From CActive DoCancel handles request cancellation.
+        */
+        void DoCancel();
+
+    protected: // New functions
+        // None
+
+    protected: // Functions from base classes
+        // None
+
+    private: // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CActiveTimer( CConsoleBase* aConsole );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+
+    public: // Data
+        // None
+    
+    protected: // Data
+        // None
+
+    private: // Data
+        
+        // Pointer to Console
+        CConsoleBase*                   iConsole;
+
+        // Start Time
+        TTime                           iStartTime;
+
+        // Console position
+        TInt                            iXPos;
+        TInt                            iYPos;
+
+    public: // Friend classes
+        // None
+
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        // None
+
+    };
+
+#endif // ATS_INTERFACE_RUNNER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSInterface/src/ATSInterface.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1109 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CATSInterface: This object executes test cases from 
+* STIF Test Framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+#include "ATSInterface.h"
+#include "ATSInterfaceRunner.h"
+
+#include "StifTestInterface.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS ========================================= 
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: CATSInterface
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CATSInterface::CATSInterface()
+    {
+    // Initialize buffers to zero
+    iEngineIniFile.Zero();
+    iModuleIniFile.Zero();
+    iConfigFile.Zero();
+    iTestModule.Zero();
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving functions leaves
+                       Leaves each time the LogErrorAndLeaveL is called
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterface::ConstructL()
+    {
+    RDebug::Print(_L("Creating module list object"));
+    TRAPD(err, iModuleList = CTestModuleList::NewL(NULL));
+    if(err != KErrNone)
+        {
+        LogErrorAndLeaveL(_L("CATSInterface::ConstructL"), _L("CTestModuleList::NewL"), err);
+        return;
+        }
+    if(!iModuleList)
+        {
+        LogErrorAndLeaveL(_L("CATSInterface::ConstructL"), _L("CTestModuleList::NewL - iModuleList is NULL"), KErrGeneral);
+        return;
+        }
+
+    // Read command line
+    ParseCommandLineL();
+
+    // Add to module list info about module taken from command line
+    RDebug::Print(_L("Adding command line module to list"));
+    TName moduleName;
+    moduleName.Copy(iTestModule);
+    moduleName.LowerCase();
+    err = iModuleList->AddTestModule(moduleName);
+    if(err != KErrNone && err != KErrAlreadyExists)
+        {
+        LogErrorAndLeaveL(_L("CATSInterface::ConstructL"), _L("CTestModuleList::AddTestModule - Could not add module to list of modules"), err);
+        return;
+        }
+
+    //Get added module
+    CTestModuleInfo* moduleInfo = iModuleList->GetModule(moduleName);
+    if(!moduleInfo)
+        {
+        LogErrorAndLeaveL(_L("CATSInterface::ConstructL"), _L("CTestModuleList::GetModule - Could not add get module info from list"), KErrGeneral);
+        return;
+        }
+
+    //Add ini file if given
+    if(iModuleIniFile.Length() > 0)
+        {
+        TFileName filename;
+        filename.Copy(iModuleIniFile);
+        filename.LowerCase();
+        moduleInfo->SetIniFile(filename);
+        }
+
+    //Add config file if given
+    if(iConfigFile.Length() > 0)
+        {
+        TFileName filename;
+        filename.Copy(iConfigFile);
+        filename.LowerCase();
+        moduleInfo->AddCfgFile(filename);
+        }
+
+    //Now check all config files if there are included modules
+    _LIT(KIncludeModuleStart, "[New_Include_Module]");
+    _LIT(KIncludeModuleEnd, "[End_Include_Module]");
+
+    RDebug::Print(_L("Start parsing included modules"));
+    CTestCaseFileInfo* finfo = iModuleList->GetUncheckedCfgFile();
+    while(finfo)
+        {
+        TFileName fname;
+        finfo->GetCfgFileName(fname);
+
+        RDebug::Print(_L("Checking file: '%S'"), &fname);
+        finfo->SetChecked();
+
+        CStifParser* parser = NULL;
+
+        TRAP(err, parser = CStifParser::NewL(_L(""), fname));
+        if(err != KErrNone)
+            {
+            LogErrorAndLeaveL(_L("CATSInterface::ConstructL"), _L("CStifParser::NewL - Could not create parser"), err);
+            return;
+            }
+        CleanupStack::PushL(parser);
+
+        ParseTestModulesL(parser, iModuleList, KIncludeModuleStart, KIncludeModuleEnd);
+
+        CleanupStack::PopAndDestroy(parser);
+        finfo = iModuleList->GetUncheckedCfgFile();
+        }
+    RDebug::Print(_L("End parsing included modules"));
+
+    // Create Test Engine
+    RDebug::Print(_L("Creating test engine"));
+    TInt ret = iTestEngineServ.Connect();
+    if ( ret != KErrNone )
+        {
+        // Log error
+        LogErrorAndLeaveL( _L("CATSInterface::ConstructL"), _L("iTestEngineServ.Connect"), ret );
+        return;
+        }
+
+    ret = iTestEngine.Open( iTestEngineServ, iEngineIniFile );
+    if ( ret != KErrNone )
+        {
+        // Log error
+        LogErrorAndLeaveL( _L("CATSInterface::ConstructL"), _L("iTestEngine.Open"), ret );
+        return;
+        }
+
+/*
+    // Add test module
+    ret = iTestEngine.AddTestModule( iTestModule, iModuleIniFile );
+    if ( ret != KErrNone && ret != KErrAlreadyExists )
+        {
+        // Log error
+        LogErrorAndLeaveL( _L("CATSInterface::ConstructL"), _L("iTestEngine.AddTestModule"), ret );
+        return;
+        }
+*/
+    // Add all test modules and config files
+    RDebug::Print(_L("Start creating test modules"));
+    moduleInfo = NULL;
+    TInt i;
+    TInt modCnt = iModuleList->Count();
+
+    for(i = 0; i < modCnt; i++)
+        {
+        RDebug::Print(_L("Processing module"));
+        // Get module
+        moduleInfo = iModuleList->GetModule(i);
+        if(!moduleInfo)
+            {
+            RDebug::Print(_L("Could not get module info at index %d"), i);
+            continue;
+            }
+
+        // Get module name
+        TName moduleName;
+        moduleInfo->GetModuleName(moduleName);
+        RDebug::Print(_L("module name: '%S'"), &moduleName);
+
+        // Get ini file, if exists
+        TFileName ini;
+        moduleInfo->GetIniFileName(ini);
+        if(ini.Length() == 0)
+            {
+            RDebug::Print(_L("ini file not found"));
+            }
+        else
+            {
+            RDebug::Print(_L("ini file: '%S'"), &ini);
+            }
+
+        // Create test module
+        RDebug::Print(_L("Adding module to test engine"));
+        ret = iTestEngine.AddTestModule(moduleName, ini);
+        if(ret != KErrNone && ret != KErrAlreadyExists)
+            {
+            LogErrorAndLeaveL(_L("CATSInterface::ConstructL"), _L("iTestEngine.AddTestModule"), ret);
+            return;
+            }
+
+        //Add test case files
+        TInt cfgCnt = moduleInfo->CountCfgFiles();
+        TInt j;
+        TFileName cfgFile;
+        for(j = 0; j < cfgCnt; j++)
+            {
+            moduleInfo->GetCfgFileName(j, cfgFile);
+            if(cfgFile.Length() > 0)
+                {
+                RDebug::Print(_L("config file: '%S'"), &cfgFile);
+
+                ret = iTestEngine.AddConfigFile(moduleName, cfgFile);
+                if(ret != KErrNone && ret != KErrAlreadyExists)
+                    {
+                    // Log error
+                    LogErrorAndLeaveL(_L("CATSInterface::ConstructL"), _L("RTestEngine::AddConfigFile"), ret);
+                    return;
+                    }
+                }
+            else
+                {
+                RDebug::Print(_L("Got empty cfg file"));
+                }
+            }
+        if(cfgCnt == 0)
+            {
+            RDebug::Print(_L("cfg file not found"));
+            }
+
+        RDebug::Print(_L("Module '%S' processed correctly"), &moduleName);
+        }
+
+    RDebug::Print(_L("End creating test modules"));
+
+    // Create console screen
+    iConsole = Console::NewL(
+        iTestModule, TSize( KConsFullScreen, KConsFullScreen ) );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: None
+
+    Return Values: CATSInterface* : pointer to created CATSInterface object
+
+    Errors/Exceptions: Leaves if memory allocation for CATSInterface fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CATSInterface* CATSInterface::NewL()
+    {
+    // Create CATSInterface and return it
+    CATSInterface* self =  new ( ELeave ) CATSInterface();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: ~CATSInterface
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CATSInterface::~CATSInterface()
+    {
+    // Close Test Engine
+    iTestEngine.Close();
+    iTestEngineServ.Close();
+
+    delete iModuleList;
+    delete iConsole;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: ParseTestModulesL
+
+    Description: Parse and search for module info and fill list of modules.
+
+    Parameters: CStifParser*     aParser:       in: CStifParser object
+                CTestModuleList* aModuleList:   in: list of modules
+                TPtrC&           aSectionStart: in: descriptor with start of section string
+                TPTrC&           aSectionEnd:   in: descriptor with end of section string
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CATSInterface::ParseTestModulesL(CStifParser* aParser, CTestModuleList* aModuleList, const TDesC& aSectionStart, const TDesC& aSectionEnd)
+    {
+    //First let's find all modules given in Stif's ini file and store that info in CTestModuleList object
+    CStifSectionParser* sectionParser = NULL;
+    CStifItemParser* item = NULL;
+
+    sectionParser = aParser->SectionL(aSectionStart, aSectionEnd);
+
+    while(sectionParser)
+        {
+        RDebug::Print(_L("Found '%S' and '%S' sections"), &aSectionStart, &aSectionEnd);
+        CleanupStack::PushL(sectionParser);
+        RDebug::Print(_L("Starting to read module information"));
+
+        // Get name of module
+        _LIT(KModuleName, "ModuleName=");
+        item = sectionParser->GetItemLineL(KModuleName);
+        CleanupStack::PushL(item);
+        if(!item)
+            {
+            CleanupStack::PopAndDestroy(item);
+            LogErrorAndLeaveL(_L("CATSInterface::ParseTestModulesL"), _L("CStifItemParser::GetItemLineL - line not found from module section"), KErrNotFound);
+            return;
+            }
+        else
+            {
+            RDebug::Print(_L("'%S' found"), &KModuleName);
+            }
+
+        TPtrC name;
+        TName moduleName;
+        TInt ret(KErrNone);
+        ret = item->GetString(KModuleName, name);
+        if(ret != KErrNone)
+            {
+            CleanupStack::PopAndDestroy(item);
+            LogErrorAndLeaveL(_L("CATSInterface::ParseTestModulesL"), _L("CStifItemParser::GetString - Module name parsing left with error"), ret);
+            return;
+            }
+        else
+            {
+            RDebug::Print(_L("Module '%S' found from ini-file"), &name);
+            moduleName.Copy(name);
+            moduleName.LowerCase();
+            ret = aModuleList->AddTestModule(moduleName);
+            if(ret != KErrNone && ret != KErrAlreadyExists)
+                {
+                LogErrorAndLeaveL(_L("CATSInterface::ParseTestModulesL"), _L("CTestModuleList::AddTestModule - Could not add module to list of modules"), ret);
+                return;
+                }
+            }
+        CleanupStack::PopAndDestroy(item);
+
+        //Get pointer to added module
+        CTestModuleInfo* moduleInfo = aModuleList->GetModule(moduleName);
+        if(!moduleInfo)
+            {
+                LogErrorAndLeaveL(_L("CATSInterface::ParseTestModulesL"), _L("CTestModuleList::GetModule - Could not add get module info from list"), KErrNotFound);
+                return;
+            }
+
+        // Get ini file, if it exists
+        RDebug::Print(_L("Start parsing ini file"));
+        _LIT(KIniFile, "IniFile=");
+        item = sectionParser->GetItemLineL(KIniFile);
+        if(item)
+            {
+            RDebug::Print(_L("'%S' found"), &KIniFile);
+            CleanupStack::PushL(item);
+            TPtrC iniFile;
+            ret = item->GetString(KIniFile, iniFile);
+            if(ret == KErrNone)
+                {
+                RDebug::Print(_L("Initialization file '%S' found, file can be empty"), &iniFile);
+                TFileName filename;
+                filename.Copy(iniFile);
+                filename.LowerCase();
+                TStifUtil::CorrectFilePathL( filename );
+                moduleInfo->SetIniFile(filename);
+                }
+            else
+                {
+                RDebug::Print(_L("Initialization file not found"));
+                }
+            CleanupStack::PopAndDestroy(item);
+            }
+        else
+            {
+            RDebug::Print(_L("'%S' not found"), &KIniFile);
+            }
+
+        // Get config (testcase) file
+        RDebug::Print(_L("Start parsing cfg files"));
+        TPtrC cfgTag;
+        for(TInt i = 0; i < 2; i++)
+            {
+            //Set tag for config files
+            if(i == 0)
+                {
+                cfgTag.Set(_L("ConfigFile="));
+                }
+                else
+                {
+                cfgTag.Set(_L("TestCaseFile="));
+                }
+            //Read data
+            item = sectionParser->GetItemLineL(cfgTag);
+            while(item)
+                {
+                CleanupStack::PushL(item);
+                RDebug::Print(_L("Item '%S' found"), &cfgTag);
+                TPtrC cfgFile;
+                ret = item->GetString(cfgTag, cfgFile);
+                if(ret == KErrNone)
+                    {
+                    TFileName ifile;
+                    ifile.Copy(cfgFile);
+                    ifile.LowerCase();
+                    TStifUtil::CorrectFilePathL( ifile );
+                    RDebug::Print(_L("Configuration file '%S' found"), &ifile);
+                    moduleInfo->AddCfgFile(ifile);
+                    }
+                else
+                    {
+                    RDebug::Print(_L("Configuration file not found"));
+                    }
+                CleanupStack::PopAndDestroy(item);
+                item = sectionParser->GetNextItemLineL(cfgTag);
+                }
+            }
+
+        RDebug::Print(_L("Module '%S' information read correctly"), &moduleName);
+
+        // Get next section
+        CleanupStack::PopAndDestroy(sectionParser);
+        sectionParser = aParser->NextSectionL(aSectionStart, aSectionEnd);
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: ParseCommandLineL
+
+    Description: Parse command line parameters
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if module name not found from command line
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterface::ParseCommandLineL()
+    {
+    // Command line params
+    _LIT( KTestModule, "-testmodule" );
+    _LIT( KConfigFile, "-config" );
+    _LIT( KEngineIniFile, "-engineini" );
+    _LIT( KModuleIniFile, "-moduleini" );
+
+	const TInt length = User::CommandLineLength();
+
+    HBufC* cmdLine = HBufC::NewLC( length );
+    TPtr ptr = cmdLine->Des();
+
+	User::CommandLine( ptr );
+
+    TBool moduleFound( EFalse );
+    TLex lex( ptr );
+    // Parse the command line
+    while ( !lex.Eos() )
+        {
+        TPtrC tmpPtr = lex.NextToken();
+        // Check the test module name
+        if ( tmpPtr == KTestModule )
+            {
+            TPtrC module = lex.NextToken();
+            if ( module.Ptr() )
+                {
+                iTestModule.Copy( module );
+                moduleFound = ETrue;
+                }
+            }
+        // Check the module's config file
+        else if ( tmpPtr == KConfigFile )
+            {
+            TPtrC config = lex.NextToken();
+            if ( config.Ptr() )
+                {
+                iConfigFile.Copy( config );
+                TStifUtil::CorrectFilePathL( iConfigFile );
+                }
+            }
+        // Check the engine's ini file
+        else if ( tmpPtr == KEngineIniFile )
+            {
+            TPtrC iniFile = lex.NextToken();
+            if ( iniFile.Ptr() )
+                {
+                iEngineIniFile.Copy( iniFile );
+                TStifUtil::CorrectFilePathL( iEngineIniFile );
+                }
+            }
+        // Check the module's ini file
+        else if ( tmpPtr == KModuleIniFile )
+            {
+            TPtrC iniFile = lex.NextToken();
+            if ( iniFile.Ptr() )
+                {
+                iModuleIniFile.Copy( iniFile );
+                TStifUtil::CorrectFilePathL( iModuleIniFile );
+                }
+            }
+        else
+            {
+            // Skip unknown commands
+            }
+        } // while
+
+    // Destroy command line buffer
+    CleanupStack::PopAndDestroy( cmdLine );
+
+    // Module name has to exists
+    if ( !moduleFound )
+        {
+        User::Leave( KErrArgument );
+        }
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: RunTestsL
+
+    Description: Starts testing
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if RunAllTestCasesL leaves
+                       Leaves if RemoveTestModule returns error
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterface::RunTestsL()
+    {
+    // Run all test cases
+    RunAllTestCasesL();
+
+    /*
+    // Remove test module
+    User::LeaveIfError( iTestEngine.RemoveTestModule( iTestModule ) );
+    */
+    RDebug::Print(_L("Start removing test modules"));
+    CTestModuleInfo* moduleInfo = NULL;
+    TInt i;
+    TInt modCnt = iModuleList->Count();
+
+    for(i = 0; i < modCnt; i++)
+        {
+        RDebug::Print(_L("Processing module"));
+        // Get module
+        moduleInfo = iModuleList->GetModule(i);
+        if(!moduleInfo)
+            {
+            RDebug::Print(_L("Could not get module info at index %d"), i);
+            continue;
+            }
+
+        // Get module name
+        TName moduleName;
+        moduleInfo->GetModuleName(moduleName);
+        RDebug::Print(_L("module name: '%S'"), &moduleName);
+
+        // Remove test module
+        User::LeaveIfError(iTestEngine.RemoveTestModule(moduleName));
+        RDebug::Print(_L("Module '%S' removed"), &moduleName);
+        }
+
+    RDebug::Print(_L("End removing test modules"));
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: RunAllTestCasesL
+
+    Description: Run all test cases from test module.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CATSInterface::RunAllTestCasesL()
+    {
+    TInt ret( KErrNone );
+
+    /*
+    // Add given config file to test module
+    if ( iConfigFile.Length() > 0 )
+        {
+        ret = iTestEngine.AddConfigFile( iTestModule, iConfigFile );
+        if ( ret != KErrNone && ret != KErrAlreadyExists )
+            {
+            // Log error
+            LogErrorAndLeaveL( _L("CATSInterface::RunAllTestCasesL"), _L("iTestEngine.AddConfigFile"), ret );
+            return;
+            }
+        }
+    */
+
+    // Enumerate test cases
+    TCaseCount caseCount;
+    TRequestStatus status;
+    iTestEngine.EnumerateTestCases( caseCount, status );
+    User::WaitForRequest( status );
+
+    // Check that enumerate succeeded
+    if ( status != KErrNone )
+        {
+        // Log error 
+        LogErrorAndLeaveL( _L("CATSInterface::RunAllTestCasesL"), _L("iTestEngine.EnumerateTestCases"), status.Int() );
+        return;
+        }
+
+    // Get test cases to buffer
+    CFixedFlatArray<TTestInfo>* testCases = 
+        CFixedFlatArray<TTestInfo>::NewL( caseCount() );
+    CleanupStack::PushL( testCases );
+
+    ret = iTestEngine.GetTestCases( *testCases );
+    if ( ret != KErrNone )
+        {
+        // Log error 
+        LogErrorAndLeaveL( _L("CATSInterface::RunAllTestCasesL"), _L("iTestEngine.GetTestCases"), status.Int() );
+        return;
+        }
+
+    //variables used to get version of STIF
+    TInt majorV;
+    TInt minorV;
+    TInt buildV;
+    TBuf<30> relDate;
+    TStifUtil::STIFVersion(majorV, minorV, buildV, relDate);
+    
+    TBuf<50> version;
+    version.Format(_L("STIF v%d.%d.%d - "), majorV, minorV, buildV);
+    version.Append(relDate);
+    version.Append(_L("\n"));
+    
+    iConsole->Printf(version);	//printing STIF version information (version and release date)
+    iConsole->Printf( _L("Test case count: [%d]\n\n"), testCases->Count() );
+
+    // Loop through all test cases in buffer and run them
+    const TInt count = testCases->Count();
+    for ( TInt i = 0; i < count; i++ )
+        {
+#ifdef _DEBUG
+        RDebug::Print( ( *testCases)[i].iTestCaseInfo.iTitle );
+#endif
+        iConsole->Printf( _L("Now running test case: [%d] [%S] "), i+1,
+            &( *testCases )[i].iTestCaseInfo.iTitle );
+
+        // Run test case
+        RunTestCaseL( ( *testCases )[i] );
+        }
+
+    // End test set
+    CleanupStack::PopAndDestroy( testCases );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: RunTestCaseL
+
+    Description: Run test case
+
+    Parameters: TTestInfo& aTestInfo: in: TTestInfo: Test info
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CATSInterface::RunTestCaseL( TTestInfo& aTestInfo )
+    {
+    TInt testResult( KErrNone );
+    CATSInterfaceRunner* runner;
+
+    // Trap to catch errors from test case executing
+    TRAPD( trapError,
+        runner = CATSInterfaceRunner::NewL( this, aTestInfo );
+        CleanupStack::PushL( runner );
+
+        testResult = RunATestCaseL( runner );
+
+        CleanupStack::PopAndDestroy( runner );
+        );
+
+    if ( trapError != KErrNone )
+        {
+        testResult = trapError;
+        }
+
+    if ( testResult != KErrNone ) // Test case is FAILED
+        {
+        // Test case failed, print out the error
+        iConsole->Printf( _L("\nTest case FAILED! err=[%d]\n"), testResult );
+        }
+
+    else // Test case is PASSED
+        {
+        iConsole->Printf( _L("\nTest case PASSED!\n") );
+        testResult = KErrNone;
+        }
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: RunATestCaseL
+
+    Description: Run a test case
+
+    Parameters: CATSInterfaceRunner* aTestCase: in: Pointer to test case runner
+
+    Return Values: TInt KErrNone: Test case passed
+                   other error code: Test case failed or cannot be executed
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CATSInterface::RunATestCaseL( CATSInterfaceRunner* aTestCase )
+    {
+    iTestCompletedError = KErrNone;
+
+    // Create timer
+    CActiveTimer* timer = CActiveTimer::NewL( iConsole );
+    CleanupStack::PushL( timer );
+
+    // Start test case and timer
+    aTestCase->StartTestL();
+    timer->StartL();
+
+    // Wait for test case completed
+    CActiveScheduler::Start();
+
+    timer->Cancel();
+    CleanupStack::PopAndDestroy( timer );
+
+    // test completion error is set in TestCompleted method
+    return iTestCompletedError;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: TestEngineServer
+
+    Description: Return handle to Test Engine Server.
+
+    Parameters: None
+    
+    Return Values: RTestEngineServer&: Reference to RTestEngineServer handle
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+RTestEngineServer& CATSInterface::TestEngineServer()
+    {
+    return iTestEngineServ;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: TestEngine
+
+    Description: Return handle to Test Engine.
+
+    Parameters: None
+    
+    Return Values: RTestEngine&: reference to RTestEngine handle
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+RTestEngine& CATSInterface::TestEngine()
+    {
+    return iTestEngine;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: TestCompleted
+
+    Description: Test case completed
+
+    This method is called when test case is completed or error occurred
+    during the test.
+
+    Parameters: TInt aError: in: Symbian OS error: Test result
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterface::TestCompleted( TInt aError )
+    {
+    // Store completion error
+    iTestCompletedError = aError;
+
+    // Stop the scheduler
+    CActiveScheduler::Stop();
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterface
+
+    Method: LogErrorAndLeaveL
+
+    Description: Write error Logger and leave.
+
+    This function is called if some function returns error and the error cannot
+    be logged another way Logger, e.g. RTestEngineServer and
+    RTestEngine methods.
+
+    Parameters: const TDesC& aFunction: in: any string: Function where the error
+                 occurred
+                const TDesC& aDescription: in: any string: Description for error
+                const TInt aError: in: Symbian OS error: Test result
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterface::LogErrorAndLeaveL( const TDesC& aFunction, 
+                                      const TDesC& aDescription, 
+                                      const TInt aError )
+    {
+
+    RDebug::Print( _L("%S: %S [%d]"), &aFunction, &aDescription, aError );
+    User::Leave( aError );
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+
+/*
+-------------------------------------------------------------------------------
+   
+    Function: E32Main
+
+    Description: Main function called by E32.
+
+    Parameters: None
+
+    Return Values: TInt: KErrNone :No errors occurred
+                   TInt: Other Symbian OS Error :Error catch by TRAP
+
+    Errors/Exceptions: TRAP is used to catch errors from leaving methods.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+GLDEF_C TInt E32Main()
+    {
+ 
+    TInt processHandleCountBefore;
+    TInt threadHandleCountBefore;
+    RThread().HandleCount( processHandleCountBefore, threadHandleCountBefore );
+    TInt reqsBefore = RThread().RequestCount();
+
+    TInt processHandleCountAfter;
+    TInt threadHandleCountAfter;
+    TInt reqsAfter;
+
+    __UHEAP_MARK;
+
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    if ( cleanup == NULL )
+        {
+        __UHEAP_MARKEND;
+        return KErrNoMemory;
+        }
+
+    CActiveScheduler* activeScheduler = new CActiveScheduler;
+    if ( activeScheduler == NULL )
+        {
+        delete cleanup;
+        __UHEAP_MARKEND;
+        return KErrNoMemory;
+        }
+    CActiveScheduler::Install( activeScheduler );
+
+    // Construct the test client
+    CATSInterface* test = NULL;
+    TRAPD( err, test = CATSInterface::NewL() );
+    if ( err != KErrNone )
+        {
+#ifdef _DEBUG
+        RDebug::Print(_L("ATSInterface construction failed %d: "), err );
+#endif
+        delete cleanup;
+        delete activeScheduler;
+        __UHEAP_MARKEND;
+        return err;
+        }
+
+    // Run tests
+    TRAP( err, test->RunTestsL() );
+    if ( err != KErrNone )
+        {
+#ifdef _DEBUG
+        RDebug::Print(_L("RunTestsL left with %d: "), err );
+#endif
+        }
+
+
+    // Deallocate resources
+    delete test;
+    delete activeScheduler;
+    delete cleanup;
+
+    reqsAfter = RThread().RequestCount();
+    RThread().HandleCount( processHandleCountAfter, threadHandleCountAfter );
+
+    if ( reqsAfter != reqsBefore )
+        {
+#ifdef _DEBUG
+        RDebug::Print(_L("Request count not matching! %d vs. %d: "),
+            reqsBefore, reqsAfter );
+#endif
+        }
+    if ( threadHandleCountAfter != threadHandleCountBefore )
+        {
+#ifdef _DEBUG
+        RDebug::Print(_L("Handle count not matching! %d vs. %d: "),
+            threadHandleCountBefore, threadHandleCountAfter );
+#endif
+        }
+
+    __UHEAP_MARKEND;
+
+    return err;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSInterface/src/ATSInterfaceRunner.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,568 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CATSInterfaceRunner: This object executes test 
+* cases from Test Framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+#include "ATSInterface.h"
+#include "ATSInterfaceRunner.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS ========================================= 
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    CATSInterfaceRunner: This object executes test cases from Test Framework.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterfaceRunner
+
+    Method: CATSInterfaceRunner
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CATSInterfaceRunner::CATSInterfaceRunner( CATSInterface* aATSInterface,
+                                   TTestInfo& aTestInfo ) : 
+    CActive( CActive::EPriorityStandard ),
+    iATSInterface( aATSInterface ),
+    iTestInfo( aTestInfo ),
+    iTestInfoPckg( iTestInfo ),
+    iFullTestResultPckg( iFullTestResult )
+    {
+    __ASSERT_ALWAYS( aATSInterface, User::Panic( _L("Null pointer"), KErrGeneral ) );
+
+    CActiveScheduler::Add( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterfaceRunner
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterfaceRunner::ConstructL()
+    {
+    iTestEngineServ = iATSInterface->TestEngineServer();
+    iTestEngine = iATSInterface->TestEngine();
+
+    User::LeaveIfError( iTestCase.Open( iTestEngineServ, iTestInfoPckg ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterfaceRunner
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+    
+    Parameters: CATSInterface* aATSInterface: in: pointer to ATS Interface
+                TTestInfo& aTestInfo: in: Test info
+
+    Return Values: CATSInterfaceRunner* : pointer to created runner object
+
+    Errors/Exceptions: Leaves if memory allocation for CATSInterfaceRunner fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CATSInterfaceRunner* CATSInterfaceRunner::NewL( CATSInterface* aATSInterface,
+                                         TTestInfo& aTestInfo )
+    {
+    CATSInterfaceRunner* self =  
+        new ( ELeave ) CATSInterfaceRunner( aATSInterface, aTestInfo );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterfaceRunner
+
+    Method: ~CATSInterfaceRunner
+
+    Description: Destructor
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/    
+CATSInterfaceRunner::~CATSInterfaceRunner()
+    {
+    Cancel();
+    iTestCase.Close();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterfaceRunner
+
+    Method: StartTestL
+
+    Description: Starts testing
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterfaceRunner::StartTestL()
+    {
+#ifdef _DEBUG
+    RDebug::Print(_L("Start test case %d: "), iTestInfo.iTestCaseInfo.iCaseNumber );
+#endif
+
+    if ( IsActive() )
+        Cancel();
+
+    iTestCase.RunTestCase( iFullTestResultPckg, iStatus );
+
+    SetActive();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterfaceRunner
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone, error is handled in
+                       RunError called by CActiveObject
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterfaceRunner::RunL()
+    {
+#ifdef _DEBUG
+    RDebug::Print(_L("RunTestCase completed: [%d] "), iStatus.Int() );
+#endif
+    // Check if the test case could not be executed, error handled in RunError
+    User::LeaveIfError ( iStatus.Int() );
+
+    // Check if the test case crashed, error handler in RunError
+    if ( iFullTestResult.iCaseExecutionResultType !=
+         TFullTestResult::ECaseExecuted )
+        {
+#ifdef _DEBUG
+        RDebug::Print(_L("Test case execution failed: [%d] "), 
+            iFullTestResult.iCaseExecutionResultCode );
+#endif
+        // Complete with the result of the test case
+        iATSInterface->TestCompleted( iFullTestResult.iCaseExecutionResultCode );
+
+        }
+    else
+        {
+#ifdef _DEBUG
+        // Debug test result
+        RDebug::Print( _L("Test case execution completed[%d]: %S"), 
+                            iFullTestResult.iTestResult.iResult,  
+                            &iFullTestResult.iTestResult.iResultDes);
+#endif
+
+        // Complete with the result of the test case
+        iATSInterface->TestCompleted( iFullTestResult.iTestResult.iResult );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterfaceRunner
+
+    Method: DoCancel
+
+    Description: Cancel active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CATSInterfaceRunner::DoCancel()
+    {
+    // Cancel the active request
+    iTestCase.CancelAsyncRequest( ETestCaseRunTestCase );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CATSInterfaceRunner
+
+    Method: RunError
+
+    Description: Handle errors from TestFramework
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+    
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CATSInterfaceRunner::RunError( TInt aError )
+    {
+#ifdef _DEBUG
+    RDebug::Print(_L("Test case execution failed: [%d] "), 
+            aError );
+#endif
+    iATSInterface->TestCompleted ( aError );
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    CActiveTimer: This object prints running seconds to console screen.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CActiveTimer
+
+    Method: CActiveTimer
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: CConsoleBase* aConsole: in: Pointer to CConsoleBase
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CActiveTimer::CActiveTimer( CConsoleBase* aConsole ) : 
+    CTimer( CActive::EPriorityStandard ),
+    iConsole( aConsole )
+    {
+    CActiveScheduler::Add( this );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CActiveTimer
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CActiveTimer::ConstructL()
+    {
+    //Base class 2nd phase constructor
+    CTimer::ConstructL();
+
+    // Set console positions
+    iXPos = 0;
+    iYPos = 1;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CActiveTimer
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+    
+    Parameters: CConsoleBase* aConsole: in: Pointer to CConsoleBase
+
+    Return Values: CActiveTimer* : pointer to created CActiveTimer object
+
+    Errors/Exceptions: Leaves if memory allocation for CATSInterface fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CActiveTimer* CActiveTimer::NewL( CConsoleBase* aConsole )
+    {
+    CActiveTimer* self =  
+        new ( ELeave ) CActiveTimer( aConsole );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CActiveTimer
+
+    Method: ~CActiveTimer
+
+    Description: Destructor
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/    
+CActiveTimer::~CActiveTimer()
+    {
+    Cancel();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CActiveTimer
+
+    Method: StartTestL
+
+    Description: Starts testing
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CActiveTimer::StartL()
+    {
+    iStartTime.HomeTime();
+    // Wait a moment
+    CTimer::After( KPrintInterval );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CActiveTimer
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CActiveTimer::RunL()
+    {
+    // Print time
+    TTimeIntervalSeconds seconds;
+    TTime time;
+    time.HomeTime();
+    time.SecondsFrom( iStartTime, seconds );
+
+    TInt x = iConsole->WhereX();
+    TInt y = iConsole->WhereY();
+
+    // Print time to screen
+    iConsole->SetPos( iXPos, iYPos );
+    iConsole->ClearToEndOfLine();
+    iConsole->Printf( _L("[Time: %d] "), seconds.Int() );
+
+    iConsole->SetPos( x, y );
+    // Wait a moment
+    CTimer::After( KPrintInterval );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CActiveTimer
+
+    Method: DoCancel
+
+    Description: Cancel
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CActiveTimer::DoCancel()
+    {
+    // Print time
+    TTimeIntervalSeconds seconds;
+    TTime time;
+    time.HomeTime();
+    time.SecondsFrom( iStartTime, seconds );
+
+    // Print time to screen
+    iConsole->Printf( _L("Total Time: [%d] "), seconds.Int() );
+    // Cancel the active request
+    CTimer::DoCancel();
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSLogger/Bmarm/ATSLOGGERU.DEF	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,38 @@
+EXPORTS
+	"_._10CAtsLogger" @ 1 NONAME R3UNUSED ; CAtsLogger::~CAtsLogger(void)
+	BeginTestCaseL__10CAtsLoggerRC7TDesC16iT1T1 @ 2 NONAME ; CAtsLogger::BeginTestCaseL(TDesC16 const &, int, TDesC16 const &, TDesC16 const &)
+	BeginTestCaseReportL__10CAtsLoggerRC7TDesC16T1RC5TTimeT1T1 @ 3 NONAME ; CAtsLogger::BeginTestCaseReportL(TDesC16 const &, TDesC16 const &, TTime const &, TDesC16 const &, TDesC16 const &)
+	BeginTestCaseReportL__10CAtsLoggerRC7TDesC16iRC5TTimeT1T1 @ 4 NONAME ; CAtsLogger::BeginTestCaseReportL(TDesC16 const &, int, TTime const &, TDesC16 const &, TDesC16 const &)
+	BeginTestReportL__10CAtsLogger @ 5 NONAME R3UNUSED ; CAtsLogger::BeginTestReportL(void)
+	BeginTestSetL__10CAtsLoggerRC7TDesC16N31 @ 6 NONAME ; CAtsLogger::BeginTestSetL(TDesC16 const &, TDesC16 const &, TDesC16 const &, TDesC16 const &)
+	CloseL__10CAtsLogger @ 7 NONAME R3UNUSED ; CAtsLogger::CloseL(void)
+	CommentL__10CAtsLoggerGt11TRefByValue1ZC7TDesC16e @ 8 NONAME ; CAtsLogger::CommentL(TRefByValue<TDesC16 const>,...)
+	CommentL__10CAtsLoggerRC7TDesC16 @ 9 NONAME R3UNUSED ; CAtsLogger::CommentL(TDesC16 const &)
+	ContinueAfterRebootL__10CAtsLogger @ 10 NONAME R3UNUSED ; CAtsLogger::ContinueAfterRebootL(void)
+	DebugL__10CAtsLoggerGt11TRefByValue1ZC7TDesC16e @ 11 NONAME ; CAtsLogger::DebugL(TRefByValue<TDesC16 const>,...)
+	DebugL__10CAtsLoggerRC7TDesC16 @ 12 NONAME R3UNUSED ; CAtsLogger::DebugL(TDesC16 const &)
+	DebugOutput__10CAtsLoggerRC7TDesC16 @ 13 NONAME R3UNUSED ; CAtsLogger::DebugOutput(TDesC16 const &)
+	EndTestCaseL__10CAtsLogger @ 14 NONAME R3UNUSED ; CAtsLogger::EndTestCaseL(void)
+	EndTestReportL__10CAtsLogger @ 15 NONAME R3UNUSED ; CAtsLogger::EndTestReportL(void)
+	EndTestSetL__10CAtsLogger @ 16 NONAME R3UNUSED ; CAtsLogger::EndTestSetL(void)
+	ErrorL__10CAtsLoggerGt11TRefByValue1ZC7TDesC16e @ 17 NONAME ; CAtsLogger::ErrorL(TRefByValue<TDesC16 const>,...)
+	ErrorL__10CAtsLoggerRC7TDesC16 @ 18 NONAME R3UNUSED ; CAtsLogger::ErrorL(TDesC16 const &)
+	ErrorMessage__10CAtsLoggerRCi @ 19 NONAME R3UNUSED ; CAtsLogger::ErrorMessage(int const &)
+	IsValid__10CAtsLogger @ 20 NONAME R3UNUSED ; CAtsLogger::IsValid(void)
+	NewL__10CAtsLoggerRC7TDesC16i @ 21 NONAME R3UNUSED ; CAtsLogger::NewL(TDesC16 const &, int)
+	RawLogL__10CAtsLoggerGt11TRefByValue1ZC7TDesC16e @ 22 NONAME ; CAtsLogger::RawLogL(TRefByValue<TDesC16 const>,...)
+	RawLogL__10CAtsLoggerRC7TDesC16 @ 23 NONAME R3UNUSED ; CAtsLogger::RawLogL(TDesC16 const &)
+	SaveForRebootL__10CAtsLogger @ 24 NONAME R3UNUSED ; CAtsLogger::SaveForRebootL(void)
+	SetDebugOutput__10CAtsLoggeri @ 25 NONAME R3UNUSED ; CAtsLogger::SetDebugOutput(int)
+	SetFullReporting__10CAtsLoggeri @ 26 NONAME R3UNUSED ; CAtsLogger::SetFullReporting(int)
+	SetIndentation__10CAtsLoggeri @ 27 NONAME R3UNUSED ; CAtsLogger::SetIndentation(int)
+	SetTestCaseResultL__10CAtsLoggerRC7TDesC16 @ 28 NONAME R3UNUSED ; CAtsLogger::SetTestCaseResultL(TDesC16 const &)
+	SetTestCaseResultL__10CAtsLoggeri @ 29 NONAME R3UNUSED ; CAtsLogger::SetTestCaseResultL(int)
+	TestCaseFailed__10CAtsLogger @ 30 NONAME R3UNUSED ; CAtsLogger::TestCaseFailed(void)
+	TestCaseNa__10CAtsLogger @ 31 NONAME R3UNUSED ; CAtsLogger::TestCaseNa(void)
+	TestCasePassed__10CAtsLogger @ 32 NONAME R3UNUSED ; CAtsLogger::TestCasePassed(void)
+	TestCaseSkipped__10CAtsLogger @ 33 NONAME R3UNUSED ; CAtsLogger::TestCaseSkipped(void)
+	WarningL__10CAtsLoggerGt11TRefByValue1ZC7TDesC16e @ 34 NONAME ; CAtsLogger::WarningL(TRefByValue<TDesC16 const>,...)
+	WarningL__10CAtsLoggerRC7TDesC16 @ 35 NONAME R3UNUSED ; CAtsLogger::WarningL(TDesC16 const &)
+	BeginTestCaseL__10CAtsLoggerRC7TDesC16N31 @ 36 NONAME ; CAtsLogger::BeginTestCaseL(TDesC16 const &, TDesC16 const &, TDesC16 const &, TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSLogger/Bwins/ATSLOGGERU.DEF	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,38 @@
+EXPORTS
+	??1CAtsLogger@@UAE@XZ @ 1 NONAME ; CAtsLogger::~CAtsLogger(void)
+	?BeginTestCaseL@CAtsLogger@@QAEXABVTDesC16@@000@Z @ 2 NONAME ; void CAtsLogger::BeginTestCaseL(class TDesC16 const &, class TDesC16 const &, class TDesC16 const &, class TDesC16 const &)
+	?BeginTestCaseL@CAtsLogger@@QAEXABVTDesC16@@H00@Z @ 3 NONAME ; void CAtsLogger::BeginTestCaseL(class TDesC16 const &, int, class TDesC16 const &, class TDesC16 const &)
+	?BeginTestCaseReportL@CAtsLogger@@QAEXABVTDesC16@@0ABVTTime@@00@Z @ 4 NONAME ; void CAtsLogger::BeginTestCaseReportL(class TDesC16 const &, class TDesC16 const &, class TTime const &, class TDesC16 const &, class TDesC16 const &)
+	?BeginTestCaseReportL@CAtsLogger@@QAEXABVTDesC16@@HABVTTime@@00@Z @ 5 NONAME ; void CAtsLogger::BeginTestCaseReportL(class TDesC16 const &, int, class TTime const &, class TDesC16 const &, class TDesC16 const &)
+	?BeginTestReportL@CAtsLogger@@QAEXXZ @ 6 NONAME ; void CAtsLogger::BeginTestReportL(void)
+	?BeginTestSetL@CAtsLogger@@QAEXABVTDesC16@@000@Z @ 7 NONAME ; void CAtsLogger::BeginTestSetL(class TDesC16 const &, class TDesC16 const &, class TDesC16 const &, class TDesC16 const &)
+	?CloseL@CAtsLogger@@QAEXXZ @ 8 NONAME ; void CAtsLogger::CloseL(void)
+	?CommentL@CAtsLogger@@QAAXV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 9 NONAME ; void CAtsLogger::CommentL(class TRefByValue<class TDesC16 const >, ...)
+	?CommentL@CAtsLogger@@QAEXABVTDesC16@@@Z @ 10 NONAME ; void CAtsLogger::CommentL(class TDesC16 const &)
+	?ContinueAfterRebootL@CAtsLogger@@QAEXXZ @ 11 NONAME ; void CAtsLogger::ContinueAfterRebootL(void)
+	?DebugL@CAtsLogger@@QAAXV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 12 NONAME ; void CAtsLogger::DebugL(class TRefByValue<class TDesC16 const >, ...)
+	?DebugL@CAtsLogger@@QAEXABVTDesC16@@@Z @ 13 NONAME ; void CAtsLogger::DebugL(class TDesC16 const &)
+	?DebugOutput@CAtsLogger@@QAEXABVTDesC16@@@Z @ 14 NONAME ; void CAtsLogger::DebugOutput(class TDesC16 const &)
+	?EndTestCaseL@CAtsLogger@@QAEXXZ @ 15 NONAME ; void CAtsLogger::EndTestCaseL(void)
+	?EndTestReportL@CAtsLogger@@QAEXXZ @ 16 NONAME ; void CAtsLogger::EndTestReportL(void)
+	?EndTestSetL@CAtsLogger@@QAEXXZ @ 17 NONAME ; void CAtsLogger::EndTestSetL(void)
+	?ErrorL@CAtsLogger@@QAAXV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 18 NONAME ; void CAtsLogger::ErrorL(class TRefByValue<class TDesC16 const >, ...)
+	?ErrorL@CAtsLogger@@QAEXABVTDesC16@@@Z @ 19 NONAME ; void CAtsLogger::ErrorL(class TDesC16 const &)
+	?ErrorMessage@CAtsLogger@@SA?BVTPtrC16@@ABH@Z @ 20 NONAME ; class TPtrC16 const CAtsLogger::ErrorMessage(int const &)
+	?IsValid@CAtsLogger@@QAEHXZ @ 21 NONAME ; int CAtsLogger::IsValid(void)
+	?NewL@CAtsLogger@@SAPAV1@ABVTDesC16@@H@Z @ 22 NONAME ; class CAtsLogger * CAtsLogger::NewL(class TDesC16 const &, int)
+	?RawLogL@CAtsLogger@@QAAHV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 23 NONAME ; int CAtsLogger::RawLogL(class TRefByValue<class TDesC16 const >, ...)
+	?RawLogL@CAtsLogger@@QAEHABVTDesC16@@@Z @ 24 NONAME ; int CAtsLogger::RawLogL(class TDesC16 const &)
+	?SaveForRebootL@CAtsLogger@@QAEXXZ @ 25 NONAME ; void CAtsLogger::SaveForRebootL(void)
+	?SetDebugOutput@CAtsLogger@@QAEXH@Z @ 26 NONAME ; void CAtsLogger::SetDebugOutput(int)
+	?SetFullReporting@CAtsLogger@@QAEXH@Z @ 27 NONAME ; void CAtsLogger::SetFullReporting(int)
+	?SetIndentation@CAtsLogger@@QAEXH@Z @ 28 NONAME ; void CAtsLogger::SetIndentation(int)
+	?SetTestCaseResultL@CAtsLogger@@QAEXABVTDesC16@@@Z @ 29 NONAME ; void CAtsLogger::SetTestCaseResultL(class TDesC16 const &)
+	?SetTestCaseResultL@CAtsLogger@@QAEXH@Z @ 30 NONAME ; void CAtsLogger::SetTestCaseResultL(int)
+	?TestCaseFailed@CAtsLogger@@QAEXXZ @ 31 NONAME ; void CAtsLogger::TestCaseFailed(void)
+	?TestCaseNa@CAtsLogger@@QAEXXZ @ 32 NONAME ; void CAtsLogger::TestCaseNa(void)
+	?TestCasePassed@CAtsLogger@@QAEXXZ @ 33 NONAME ; void CAtsLogger::TestCasePassed(void)
+	?TestCaseSkipped@CAtsLogger@@QAEXXZ @ 34 NONAME ; void CAtsLogger::TestCaseSkipped(void)
+	?WarningL@CAtsLogger@@QAAXV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 35 NONAME ; void CAtsLogger::WarningL(class TRefByValue<class TDesC16 const >, ...)
+	?WarningL@CAtsLogger@@QAEXABVTDesC16@@@Z @ 36 NONAME ; void CAtsLogger::WarningL(class TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSLogger/eabi/atsloggeru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,42 @@
+EXPORTS
+	_ZN10CAtsLogger10TestCaseNaEv @ 1 NONAME
+	_ZN10CAtsLogger11DebugOutputERK7TDesC16 @ 2 NONAME
+	_ZN10CAtsLogger11EndTestSetLEv @ 3 NONAME
+	_ZN10CAtsLogger12EndTestCaseLEv @ 4 NONAME
+	_ZN10CAtsLogger12ErrorMessageERKi @ 5 NONAME
+	_ZN10CAtsLogger13BeginTestSetLERK7TDesC16S2_S2_S2_ @ 6 NONAME
+	_ZN10CAtsLogger14BeginTestCaseLERK7TDesC16S2_S2_S2_ @ 7 NONAME
+	_ZN10CAtsLogger14BeginTestCaseLERK7TDesC16iS2_S2_ @ 8 NONAME
+	_ZN10CAtsLogger14EndTestReportLEv @ 9 NONAME
+	_ZN10CAtsLogger14SaveForRebootLEv @ 10 NONAME
+	_ZN10CAtsLogger14SetDebugOutputEi @ 11 NONAME
+	_ZN10CAtsLogger14SetIndentationEi @ 12 NONAME
+	_ZN10CAtsLogger14TestCaseFailedEv @ 13 NONAME
+	_ZN10CAtsLogger14TestCasePassedEv @ 14 NONAME
+	_ZN10CAtsLogger15TestCaseSkippedEv @ 15 NONAME
+	_ZN10CAtsLogger16BeginTestReportLEv @ 16 NONAME
+	_ZN10CAtsLogger16SetFullReportingEi @ 17 NONAME
+	_ZN10CAtsLogger18SetTestCaseResultLERK7TDesC16 @ 18 NONAME
+	_ZN10CAtsLogger18SetTestCaseResultLEi @ 19 NONAME
+	_ZN10CAtsLogger20BeginTestCaseReportLERK7TDesC16S2_RK5TTimeS2_S2_ @ 20 NONAME
+	_ZN10CAtsLogger20BeginTestCaseReportLERK7TDesC16iRK5TTimeS2_S2_ @ 21 NONAME
+	_ZN10CAtsLogger20ContinueAfterRebootLEv @ 22 NONAME
+	_ZN10CAtsLogger4NewLERK7TDesC16i @ 23 NONAME
+	_ZN10CAtsLogger6CloseLEv @ 24 NONAME
+	_ZN10CAtsLogger6DebugLE11TRefByValueIK7TDesC16Ez @ 25 NONAME
+	_ZN10CAtsLogger6DebugLERK7TDesC16 @ 26 NONAME
+	_ZN10CAtsLogger6ErrorLE11TRefByValueIK7TDesC16Ez @ 27 NONAME
+	_ZN10CAtsLogger6ErrorLERK7TDesC16 @ 28 NONAME
+	_ZN10CAtsLogger7IsValidEv @ 29 NONAME
+	_ZN10CAtsLogger7RawLogLE11TRefByValueIK7TDesC16Ez @ 30 NONAME
+	_ZN10CAtsLogger7RawLogLERK7TDesC16 @ 31 NONAME
+	_ZN10CAtsLogger8CommentLE11TRefByValueIK7TDesC16Ez @ 32 NONAME
+	_ZN10CAtsLogger8CommentLERK7TDesC16 @ 33 NONAME
+	_ZN10CAtsLogger8WarningLE11TRefByValueIK7TDesC16Ez @ 34 NONAME
+	_ZN10CAtsLogger8WarningLERK7TDesC16 @ 35 NONAME
+	_ZN10CAtsLoggerD0Ev @ 36 NONAME
+	_ZN10CAtsLoggerD1Ev @ 37 NONAME
+	_ZN10CAtsLoggerD2Ev @ 38 NONAME
+	_ZTI10CAtsLogger @ 39 NONAME ; #<TI>#
+	_ZTV10CAtsLogger @ 40 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSLogger/group/atsloggerdll.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,41 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's atslogger module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET         atslogger.dll
+TARGETTYPE     dll
+
+UID            0x101FE86F
+
+CAPABILITY	ALL -TCB
+VENDORID 	0x101FB657
+SECUREID        0x102073D9
+
+USERINCLUDE    ../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH	   ../src
+
+SOURCE         atslogger.cpp
+
+LIBRARY        euser.lib 
+LIBRARY        efsrv.lib
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSLogger/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for ATS Logger.
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	atsloggerdll.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ATSLogger/src/atslogger.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1116 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* CAtsLogger class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include "atslogger.h"
+
+CAtsLogger::CAtsLogger(const TDesC& aName) :
+	iReportStage(EUninitialized),
+	iName(aName),
+	iIndentLevel(0),
+	iRawLog(EFalse),
+	iXmlLog(EFalse),
+	iValid(EFalse),
+	iLineFeedDone(EFalse),
+	iInTestCase(EFalse),
+	iClosed(EFalse),
+	iFullReportingMode(ETrue),
+	iDoDebugOutput(EFalse),
+	iDoIndentation(ETrue)
+	{
+	}
+
+void CAtsLogger::ConstructL( TBool aAfterReboot )
+	{
+	TChar xmlDrive;
+	iXmlLog = CheckDirectoryL(KAtsLoggerXmlDirectory, xmlDrive);
+	TChar rawDrive;
+	iRawLog = CheckDirectoryL(KAtsLoggerRawDirectory, rawDrive);
+	if (iXmlLog)
+		{
+		iXmlLogFileName.Copy(_L("?:"));		
+		iXmlLogFileName.Append(KAtsLoggerXmlDirectory);
+		iXmlLogFileName.Append(iName);
+		iXmlLogFileName.Append(KAtsLoggerXmlSuffix);
+		iXmlLogFileName[0] = (TUint8)xmlDrive;
+		if( aAfterReboot )
+		    {
+		    User::LeaveIfError(OpenExistingFileL(iXmlLogFileName));
+		    }
+		else
+		    {
+		    User::LeaveIfError(ReplaceFileL(iXmlLogFileName));
+		    }
+		iValid = ETrue;
+		}
+	else
+		{
+		iValid = EFalse;
+		}
+	if (iRawLog)
+		{
+		iRawLogFileName.Copy(_L("?:"));		
+		iRawLogFileName.Append(KAtsLoggerRawDirectory);
+		iRawLogFileName.Append(iName);
+		iRawLogFileName.Append(KAtsLoggerRawSuffix);
+		iRawLogFileName[0] = (TUint8)rawDrive;
+		if( aAfterReboot )
+		    {
+		    User::LeaveIfError(OpenExistingFileL(iRawLogFileName));
+		    }
+		else
+		    {
+		    User::LeaveIfError(ReplaceFileL(iRawLogFileName));
+		    }
+		}
+	iXmlBuffer = CBufSeg::NewL(KAtsLoggerBufferSegmentGranularity);
+	iXmlBufferLength = 0;
+	}
+
+
+TBool CAtsLogger::CheckDirectoryL(const TDesC& aDirName, TChar& aDrive)
+	{
+	User::LeaveIfError(iRfs.Connect());
+	TDriveList driveList;
+	iRfs.DriveList(driveList);
+	TBool dirFound = EFalse;
+	TFileName dir;
+	for (TInt i = 0; i < driveList.Length() && !dirFound; i++)
+		{
+		TChar drive;
+		if (driveList[i] != 0)
+			{
+			iRfs.DriveToChar(i, drive);
+			dir.Copy(_L("?:"));
+			dir.Append(aDirName);
+			dir[0] = (TUint8)drive;
+			RDir rDir;
+			TInt error = rDir.Open(iRfs, dir, KEntryAttNormal);
+			if (error == KErrNone)
+				{
+				dirFound = ETrue;
+				aDrive = drive;
+				}
+			else 
+				{
+				dirFound = EFalse;
+				aDrive = '?';
+				}
+			rDir.Close();
+			}
+		}
+	iRfs.Close();
+	return dirFound;
+	}
+
+TInt CAtsLogger::ReplaceFileL(const TDesC& aFileName)
+	{
+	User::LeaveIfError(iRfs.Connect());
+	RFile file;
+	TInt err = file.Replace(iRfs, aFileName, EFileWrite | EFileShareAny);
+	file.Close();
+	iRfs.Close();
+	return err;
+	}
+	
+TInt CAtsLogger::OpenExistingFileL(const TDesC& aFileName)
+	{
+	User::LeaveIfError(iRfs.Connect());
+	RFile file;
+	TInt err = file.Open(iRfs, aFileName, EFileWrite | EFileShareAny);
+	file.Close();
+	iRfs.Close();
+	return err;
+	}
+	
+EXPORT_C CAtsLogger::~CAtsLogger()
+	{
+	if (!iClosed)
+		{
+		CloseL();
+		}
+	if (iXmlBuffer)
+		{
+		delete iXmlBuffer;
+		iXmlBuffer = NULL;
+		}
+	}
+
+EXPORT_C void CAtsLogger::CloseL()
+	{
+	if (iClosed)
+		{
+		return;
+		}
+	User::LeaveIfError(iRfs.Connect());
+	if (iXmlLog)
+		{
+		RFile file;
+		TInt err = file.Open(iRfs, iXmlLogFileName, EFileWrite | EFileShareAny);
+		if (err == KErrNone)
+			{
+			TInt fileSize = 0;
+			file.Size(fileSize);
+			file.Close();
+			if (fileSize == 0)
+				{
+				iRfs.Delete(iXmlLogFileName);
+				}
+			}
+		}
+	if (iRawLog)
+		{
+		RFile file;
+		TInt err = file.Open(iRfs, iRawLogFileName, EFileWrite | EFileShareAny);
+		if (err == KErrNone)
+			{
+			TInt fileSize = 0;
+			file.Size(fileSize);
+			file.Close();
+			if (fileSize == 0)
+				{
+				iRfs.Delete(iRawLogFileName);
+				}
+			}
+		}
+	iRfs.Close();
+	iClosed = ETrue;
+	}
+
+
+EXPORT_C CAtsLogger* CAtsLogger::NewL( const TDesC& aName,
+                                       TBool aAfterReboot )
+	{
+	__ASSERT_ALWAYS(aName.Length() > 0, User::Leave(KErrBadName));
+	RFs rfs;
+	User::LeaveIfError(rfs.Connect());
+	__ASSERT_ALWAYS(rfs.IsValidName(aName), User::Leave(KErrBadName));
+	rfs.Close();
+	CAtsLogger* self = new (ELeave) CAtsLogger(aName);
+	CleanupStack::PushL(self);
+	self->ConstructL( aAfterReboot );
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+
+EXPORT_C TBool CAtsLogger::IsValid()
+	{
+	return iValid;
+	}
+
+EXPORT_C void CAtsLogger::BeginTestReportL()
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(EBeginTestReport))
+			{
+			User::Leave(EBeginTestReport);
+			}
+		iReportStage = EBeginTestReport;
+		OpenTagIndentL(KAtsLoggerTagTestReport());
+		}
+	else
+		{
+		//iTestSet.iStartTime = TTime();
+		iTestSet.iStartTime.HomeTime();
+		}
+	}
+
+EXPORT_C void CAtsLogger::EndTestReportL()
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(EEndTestReport))
+			{
+			User::Leave(EEndTestReport);
+			}
+		iReportStage = EEndTestReport;
+		CloseTagIndentL(KAtsLoggerTagTestReport());
+		}
+	if (iDoDebugOutput)
+		{
+		WriteBufferToDebugPortL(iXmlBuffer);
+		}
+	if (iXmlLog && !iInTestCase && iXmlBufferLength > 0)
+		{
+		WriteBufferToFileL(iXmlBuffer, iXmlLogFileName);
+		}
+	iXmlBuffer->Reset();
+	iXmlBufferLength = 0;
+	}
+
+EXPORT_C void CAtsLogger::BeginTestSetL(const TDesC& aFactory,
+									    const TDesC& aComponent,
+									    const TDesC& aVersion,
+									    const TDesC& aDescription)
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(EBeginTestSet))
+			{
+			User::Leave(EBeginTestSet);
+			}
+		iReportStage = EBeginTestSet;
+		//iTestSet.iStartTime = TTime();
+		iTestSet.iStartTime.HomeTime();
+		TDateTime date(iTestSet.iStartTime.DateTime());
+		OpenTagIndentL(KAtsLoggerTagTestSet());
+		OpenTagIndentL(KAtsLoggerTagTestSetInit());
+		TagL(KAtsLoggerTagDescription(), aDescription);
+		HBufC* stamp;
+		stamp = FormatDateLC(date);
+		TagL(KAtsLoggerTagDate(), *stamp);
+		CleanupStack::PopAndDestroy(stamp);
+		TagL(KAtsLoggerTagFactory(), aFactory);
+		OpenTagIndentL(KAtsLoggerTagComponent());
+		TagL(KAtsLoggerTagName(), aComponent);
+		TagL(KAtsLoggerTagVersion(), aVersion);
+		CloseTagIndentL(KAtsLoggerTagComponent());
+		CloseTagIndentL(KAtsLoggerTagTestSetInit());
+		}
+	}
+
+EXPORT_C void CAtsLogger::SaveForRebootL()
+	{
+	if (iFullReportingMode)
+		{
+		iReportStage = EEndTestReport;
+		}
+	if (iDoDebugOutput)
+		{
+		WriteBufferToDebugPortL(iXmlBuffer);
+		}
+	if (iXmlLog && !iInTestCase && iXmlBufferLength > 0)
+		{
+		WriteBufferToFileL(iXmlBuffer, iXmlLogFileName);
+		}
+	iXmlBuffer->Reset();
+	iXmlBufferLength = 0;
+	}
+
+EXPORT_C void CAtsLogger::ContinueAfterRebootL()
+	{
+	if (iFullReportingMode)
+		{
+		iIndentLevel += 2;
+		iLineFeedDone = ETrue;
+		iReportStage = EBeginTestSet;
+		//iTestSet.iStartTime = TTime();
+		iTestSet.iStartTime.HomeTime();
+		}
+	}
+
+
+EXPORT_C void CAtsLogger::EndTestSetL()
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(EEndTestSet))
+			{
+			User::Leave(EEndTestSet);
+			}
+		iReportStage = EEndTestSet;
+		OpenTagIndentL(KAtsLoggerTagTestSetResult());
+		TTime current;
+		current.HomeTime();
+		HBufC* time;
+		time = FormatTimeLC(current.MicroSecondsFrom(iTestSet.iStartTime));
+		TagL(KAtsLoggerTagRunTime(), *time);
+		CleanupStack::PopAndDestroy(time);
+		CloseTagIndentL(KAtsLoggerTagTestSetResult());
+		CloseTagIndentL(KAtsLoggerTagTestSet());
+		}
+	}
+
+EXPORT_C void CAtsLogger::BeginTestCaseL(const TDesC& aId,
+									     const TDesC& aExpected,
+								    	 const TDesC& aInfo,
+										 const TDesC& aVersion)
+	{
+	TTime current;
+	current.HomeTime();	
+	BeginTestCaseReportL( aId, aExpected, current, aInfo, aVersion );
+	}
+
+EXPORT_C void CAtsLogger::BeginTestCaseL(const TDesC& aId,
+										 const TInt aExpected,
+										 const TDesC& aInfo,
+										 const TDesC& aVersion)
+	{
+		TBuf<16> res;
+		res.Format(_L("%d"), aExpected);
+		BeginTestCaseL(aId, res, aInfo, aVersion);
+	}
+	
+EXPORT_C void CAtsLogger::BeginTestCaseReportL( const TDesC& aId,
+										        const TDesC& aExpected,
+										        const TTime& aStartTime,
+										        const TDesC& aInfo,
+										        const TDesC& aVersion )
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(EBeginTestCase))
+			{
+			User::Leave(EBeginTestCase);
+			}
+		iReportStage = EBeginTestCase;
+	}		
+	
+	iTestCase.iStartTime = aStartTime;
+	
+	HBufC* time;
+	time = FormatTimeLC(aStartTime.MicroSecondsFrom(iTestSet.iStartTime));
+	OpenTagIndentL(KAtsLoggerTagTestCase(), KAtsLoggerTimeStamp(), *time);
+	CleanupStack::PopAndDestroy(time);
+	OpenTagIndentL(KAtsLoggerTagTestCaseInit());
+	TagL(KAtsLoggerTagVersion, aVersion);
+	TagL(KAtsLoggerTagId(), aId);
+	TagL(KAtsLoggerTagExpected(), aExpected, KAtsLoggerTagDescription(), aInfo);
+	CloseTagIndentL(KAtsLoggerTagTestCaseInit());
+	iTestCase.iStatus.Set(KAtsLoggerNa());
+	iInTestCase = ETrue;
+	}
+	
+EXPORT_C void CAtsLogger::BeginTestCaseReportL( const TDesC& aId,
+										        const TInt aExpected,
+										        const TTime& aStartTime,
+										        const TDesC& aInfo,
+										        const TDesC& aVersion )
+	{
+	TBuf<16> res;
+	res.Format(_L("%d"), aExpected);
+	BeginTestCaseReportL( aId, res, aStartTime, aInfo, aVersion );
+    }
+    
+EXPORT_C void CAtsLogger::EndTestCaseL()
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(EEndTestCase))
+			{
+			User::Leave(EEndTestCase);
+			}
+		iReportStage = EEndTestCase;
+	}
+	TTime current;
+	current.HomeTime();
+	OpenTagIndentL(KAtsLoggerTagTestCaseResult(), KAtsLoggerTagStatus(), iTestCase.iStatus);
+	if (iTestCase.iResult)
+		{
+		TagL(KAtsLoggerTagActual(), *iTestCase.iResult);
+		delete iTestCase.iResult;
+		iTestCase.iResult = NULL;
+		}
+	else
+		{
+		TagL(KAtsLoggerTagActual(), KAtsLoggerEmpty());
+		}
+	HBufC* time;
+	time = FormatTimeLC(current.MicroSecondsFrom(iTestCase.iStartTime));
+	TagL(KAtsLoggerTagRunTime(), *time);
+	CleanupStack::PopAndDestroy(time);
+	CloseTagIndentL(KAtsLoggerTagTestCaseResult());	
+	CloseTagIndentL(KAtsLoggerTagTestCase());
+	iInTestCase = EFalse;
+	if (iDoDebugOutput)
+		{
+		WriteBufferToDebugPortL(iXmlBuffer);
+		}
+	if (iXmlLog)
+		{
+		WriteBufferToFileL(iXmlBuffer, iXmlLogFileName);
+		}
+	iXmlBuffer->Reset();
+	iXmlBufferLength = 0;
+	}
+
+EXPORT_C void CAtsLogger::TestCasePassed()
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(ESetTestCaseVerdict))
+			{
+			User::Leave(ESetTestCaseVerdict);
+			}
+		iReportStage = ESetTestCaseVerdict;
+	}
+	iTestCase.iStatus.Set(KAtsLoggerPassed());
+	}
+
+EXPORT_C void CAtsLogger::TestCaseFailed()
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(ESetTestCaseVerdict))
+			{
+			User::Leave(ESetTestCaseVerdict);
+			}
+		iReportStage = ESetTestCaseVerdict;
+	}
+	iTestCase.iStatus.Set(KAtsLoggerFailed());
+	}
+
+EXPORT_C void CAtsLogger::TestCaseNa()
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(ESetTestCaseVerdict))
+			{
+			User::Leave(ESetTestCaseVerdict);
+			}
+		iReportStage = ESetTestCaseVerdict;
+	}
+	iTestCase.iStatus.Set(KAtsLoggerNa());
+	}
+
+EXPORT_C void CAtsLogger::TestCaseSkipped()
+	{
+	if (iFullReportingMode)
+		{
+		if (!IsTransitionLegal(ESetTestCaseVerdict))
+			{
+			User::Leave(ESetTestCaseVerdict);
+			}
+		iReportStage = ESetTestCaseVerdict;
+	}
+	iTestCase.iStatus.Set(KAtsLoggerSkipped());
+	}
+
+EXPORT_C void CAtsLogger::SetTestCaseResultL(const TDesC& aResult)
+	{
+	if (iTestCase.iResult)
+		{
+		delete iTestCase.iResult;
+		iTestCase.iResult = NULL;
+		}
+	HBufC* newResult = HBufC::NewL(aResult.Length());
+	
+	CleanupStack::PushL(newResult);
+	TPtr ptr(newResult->Des());
+	ptr.Copy(aResult);
+	CleanupStack::Pop(newResult);
+	
+	iTestCase.iResult = newResult;
+	}
+
+EXPORT_C void CAtsLogger::SetTestCaseResultL(const TInt aResult)
+	{
+	if (iTestCase.iResult)
+		{
+		delete iTestCase.iResult;
+		iTestCase.iResult = NULL;
+		}
+	HBufC* newResult = HBufC::NewL(16);
+		
+	CleanupStack::PushL(newResult);
+	TPtr ptr(newResult->Des());
+	ptr.Format(_L("%d"), aResult);
+	CleanupStack::Pop(newResult);
+	
+	iTestCase.iResult = newResult;
+	}
+
+EXPORT_C void CAtsLogger::DebugL(TRefByValue<const TDesC> aFmt,...)
+	{
+	VA_LIST list;
+	VA_START(list, aFmt);
+	TBuf<0x100> buf;
+	buf.AppendFormatList(aFmt, list, NULL);
+	DebugL(buf);
+	}
+
+EXPORT_C void CAtsLogger::DebugL(const TDesC& aMsg)
+	{
+	if (iInTestCase)
+		{
+		TimeStampedMessageL(KAtsLoggerTagDebug(), aMsg);
+		}
+	else
+		{
+		CommentL(aMsg);
+		}
+	}
+
+EXPORT_C void CAtsLogger::WarningL(TRefByValue<const TDesC> aFmt,...)
+	{
+	VA_LIST list;
+	VA_START(list, aFmt);
+	TBuf<0x100> buf;
+	buf.AppendFormatList(aFmt, list, NULL);
+	WarningL(buf);
+	}
+
+EXPORT_C void CAtsLogger::WarningL(const TDesC& aMsg)
+	{
+	if (iInTestCase)
+		{
+		TimeStampedMessageL(KAtsLoggerTagWarning(), aMsg);
+		}
+	else
+		{
+		CommentL(aMsg);
+		}
+	}
+
+EXPORT_C void CAtsLogger::ErrorL(TRefByValue<const TDesC> aFmt,...)
+	{
+	VA_LIST list;
+	VA_START(list, aFmt);
+	TBuf<0x100> buf;
+	buf.AppendFormatList(aFmt, list, NULL);
+	ErrorL(buf);
+	}
+
+EXPORT_C void CAtsLogger::ErrorL(const TDesC& aMsg)
+	{
+	if (iInTestCase)
+		{
+		TimeStampedMessageL(KAtsLoggerTagError(), aMsg);
+		}
+	else
+		{
+		CommentL(aMsg);
+		}
+	}
+
+EXPORT_C void CAtsLogger::CommentL(TRefByValue<const TDesC> aFmt,...)
+	{
+	VA_LIST list;
+	VA_START(list, aFmt);
+	TBuf<0x100> buf;
+	buf.AppendFormatList(aFmt, list, NULL);
+	CommentL(buf);
+	}
+
+EXPORT_C void CAtsLogger::CommentL(const TDesC& aMsg)
+	{
+	WriteL(KAtsLoggerCommentOpen());
+	WriteL(aMsg);
+	WriteL(KAtsLoggerCommentClose());
+	LineFeedL();
+	}
+
+EXPORT_C TInt CAtsLogger::RawLogL(TRefByValue<const TDesC> aFmt,...)
+	{
+	VA_LIST list;
+	VA_START(list, aFmt);
+	TBuf<0x100> buf;
+	buf.AppendFormatList(aFmt, list, NULL);
+	RawLogL(buf);
+	return KErrNone;
+	}
+
+EXPORT_C TInt CAtsLogger::RawLogL(const TDesC& aMsg)
+	{
+	if (iRawLog)
+		{
+		TBool lfStatus = iLineFeedDone;
+		iLineFeedDone = EFalse;
+		User::LeaveIfError(iRfs.Connect());
+		RFile file;
+		TInt err = file.Open(iRfs, iRawLogFileName, EFileWrite | EFileShareAny);
+		if (err == KErrNotFound)
+			{
+			User::LeaveIfError(file.Create(iRfs, iRawLogFileName, EFileWrite | EFileShareAny));
+			}
+		else
+			{
+			TInt pos = 0;
+			file.Seek(ESeekEnd, pos);
+			}
+		WriteL(aMsg, file);
+		file.Close();
+		iRfs.Close();
+		iLineFeedDone = lfStatus;
+		}
+	return KErrNone;
+	}
+
+EXPORT_C void CAtsLogger::DebugOutput(const TDesC& aMsg)
+	{
+	RDebug::Print(_L("%S"), &aMsg);
+	}
+
+EXPORT_C void CAtsLogger::SetFullReporting(TBool aFlag)
+	{
+	iFullReportingMode = aFlag;
+	}
+
+EXPORT_C void CAtsLogger::SetDebugOutput(TBool aFlag)
+	{
+	iDoDebugOutput = aFlag;
+	}
+
+EXPORT_C void CAtsLogger::SetIndentation(TBool aFlag)
+	{
+	iDoIndentation = aFlag;
+	}
+
+HBufC* CAtsLogger::FormatDateLC(TDateTime aDate)
+	{
+	HBufC* buf = HBufC::NewL(19);
+	CleanupStack::PushL(buf);
+	TPtr ptr(buf->Des());
+	ptr.Format(_L("%d-%02d-%02d %02d:%02d:%02d"), aDate.Year(),
+		                                          aDate.Month(),
+												  aDate.Day(),
+												  aDate.Hour(),
+												  aDate.Minute(),
+												  aDate.Second());	
+	return buf;
+	}
+
+HBufC* CAtsLogger::FormatTimeLC(TTimeIntervalMicroSeconds aTime)
+	{	
+    //@js<--remove--> TInt seconds1 = (aTime.Int64() / TInt64(1000000)).GetTInt();
+    TInt seconds = (I64INT(aTime.Int64()) / I64INT(TInt64(1000000)));
+	
+	TInt hours = seconds / (60*60);
+	TInt minutes = (seconds / 60) % 60;
+	seconds = (seconds) % 60;
+	HBufC* buf = HBufC::NewL(10);
+	CleanupStack::PushL(buf);
+	TPtr ptr(buf->Des());
+	ptr.Format(_L("%02d:%02d:%02d"), hours, minutes, seconds);
+	return buf;
+	}
+
+	
+void CAtsLogger::TimeStampedMessageL(const TDesC& aTag, const TDesC& aMsg)
+	{
+	TTime current;
+	current.HomeTime();
+	HBufC* time;
+	time = FormatTimeLC(current.MicroSecondsFrom(iTestSet.iStartTime));
+	TagL(aTag, aMsg, KAtsLoggerTimeStamp(), *time);
+	CleanupStack::PopAndDestroy(time);
+	}
+
+void CAtsLogger::OpenTagL(const TDesC& aTag)
+	{
+	WriteL(KAtsLoggerTagOpen());
+	WriteL(aTag);
+	WriteL(KAtsLoggerTagPost());
+	}
+
+void CAtsLogger::OpenTagL(const TDesC& aTag,
+						  const TDesC& aAttribute,
+						  const TDesC& aValue)
+	{
+	WriteL(KAtsLoggerTagOpen());
+	WriteL(aTag);
+	WriteL(KAtsLoggerSpace());
+	WriteL(aAttribute);
+	WriteL(KAtsLoggerAttr());
+	HBufC* encoded;
+	encoded = EncodeLC(aValue);
+	WriteL(encoded->Des());
+	CleanupStack::PopAndDestroy(encoded);
+	WriteL(KAtsLoggerAttrClose());
+	}
+
+void CAtsLogger::OpenTagIndentL(const TDesC& aTag)
+	{
+	OpenTagL(aTag);
+	LineFeedL();
+	iIndentLevel++;
+	}
+
+void CAtsLogger::OpenTagIndentL(const TDesC& aTag,
+							    const TDesC& aAttribute,
+							    const TDesC& aValue)
+	{
+	OpenTagL(aTag, aAttribute, aValue);
+	LineFeedL();
+	iIndentLevel++;
+	}
+
+void CAtsLogger::CloseTagL(const TDesC& aTag)
+	{
+	WriteL(KAtsLoggerTagClose());
+	WriteL(aTag);
+	WriteL(KAtsLoggerTagPost());
+	}
+
+void CAtsLogger::CloseTagIndentL(const TDesC& aTag)
+	{
+	iIndentLevel--;
+	CloseTagL(aTag);
+	LineFeedL();
+	}
+
+void CAtsLogger::TagL(const TDesC& aTag, const TDesC& aMsg)
+	{
+	OpenTagL(aTag);
+	HBufC* encoded;
+	encoded = EncodeLC(aMsg);
+	WriteL(encoded->Des());
+	CleanupStack::PopAndDestroy(encoded);
+	CloseTagL(aTag);
+	LineFeedL();
+	}
+
+void CAtsLogger::TagL(const TDesC& aTag,
+					  const TDesC& aMsg,
+					  const TDesC& aAttribute,
+					  const TDesC& aValue)
+	{
+	OpenTagL(aTag, aAttribute, aValue);
+	HBufC* encoded;
+	encoded = EncodeLC(aMsg);
+	WriteL(encoded->Des());
+	CleanupStack::PopAndDestroy(encoded);
+	CloseTagL(aTag);
+	LineFeedL();
+	}
+
+void CAtsLogger::LineFeedL()
+	{
+	WriteL(KAtsLoggerLf());
+	iLineFeedDone = ETrue;
+	}
+
+HBufC* CAtsLogger::EncodeLC(const TDesC& aMsg)
+	{
+	TInt length = aMsg.Length();
+	HBufC* buf = HBufC::NewL(length);
+	*buf = aMsg;
+	TPtr ptr(buf->Des());
+	TInt index = 0;
+	TInt offset = 0;
+	while (index < length)
+		{
+		TPtrC16 p;
+		switch (ptr[index + offset])
+			{
+			case '"':
+				p.Set(KAtsLoggerQuot().Ptr());
+				break;
+			case '\'':
+				p.Set(KAtsLoggerApos().Ptr());
+				break;
+			case '<':
+				p.Set(KAtsLoggerLt().Ptr());
+				break;
+			case '>':
+				p.Set(KAtsLoggerGt().Ptr());
+				break;
+			case '&':
+				p.Set(KAtsLoggerAmp().Ptr());
+				break;
+			default:
+				p.Set(KAtsLoggerEmpty().Ptr());
+				break;
+			}
+		if (p.Length() > 0)
+			{
+			TInt len = ptr.Length() + p.Length();
+			HBufC* tmp = buf;
+			CleanupStack::PushL(tmp);
+			buf = buf->ReAllocL(len);
+			CleanupStack::Pop(tmp);
+			tmp = NULL;
+			ptr.Set(buf->Des());
+			ptr.Replace(index + offset, 1, p);
+
+			// offset has to be decrement by one because
+			// we have replaced a char and index remains the
+			// same.
+			offset += p.Length() - 1;
+			}
+		else
+			{
+			index++;
+			}
+		}
+	CleanupStack::PushL(buf);
+	return buf;
+	}
+
+TInt CAtsLogger::BufferL(CBufBase* aBufBase, TInt& aLength, const TDesC& aBuf)
+	{
+	TInt length = aBuf.Length();
+	if (iDoIndentation && iLineFeedDone)
+		{
+		iLineFeedDone = EFalse;
+		TInt maxIndentLength = iIndentLevel * KAtsLoggerIndent8().Length();
+		TInt indentLength = KAtsLoggerIndent8().Length();
+		aBufBase->ExpandL(aLength, length + maxIndentLength);
+		for (TInt i = 0; i < iIndentLevel; i++)
+			{
+			aBufBase->Write(aLength + (i * indentLength), KAtsLoggerIndent8());
+			}
+		aLength += maxIndentLength;
+		}
+	else
+		{
+		aBufBase->ExpandL(aLength, length);
+		}
+	HBufC8* hBufC8;
+	hBufC8 = HBufC8::NewL(aBuf.Length());
+	CleanupStack::PushL(hBufC8);
+	TPtr8 ptr8(hBufC8->Des());
+	for (TInt i = 0; i < length; i++)
+		{
+		if (aBuf[i] != '\n' && aBuf[i] != '\r')
+			{
+			ptr8.Append((TInt8)(aBuf[i] & 0xff));
+			}
+		else
+			{
+			ptr8.Append((TInt8)('\n'));
+			}
+		}
+	aBufBase->Write(aLength, *hBufC8);
+	CleanupStack::PopAndDestroy(hBufC8);
+	aLength += length;
+	return KErrNone;
+	}
+
+TInt CAtsLogger::WriteBufferToFileL(CBufBase* aCBufBase, const TDesC& aFileName)
+	{
+	User::LeaveIfError(iRfs.Connect());
+	RFile file;
+	TInt err = file.Open(iRfs, aFileName, EFileWrite | EFileShareAny);
+	if (err == KErrNotFound)
+		{
+		User::LeaveIfError(file.Create(iRfs, aFileName, EFileWrite | EFileShareAny));
+		}
+	else
+		{
+		TInt pos = 0;
+		file.Seek(ESeekEnd, pos);
+		}
+	TInt i = 0;
+	TPtrC8 ptr = aCBufBase->Ptr(i);
+	while (ptr.Length() > 0)
+		{
+		file.Write(ptr, ptr.Length());
+		i += ptr.Length();
+		ptr.Set(aCBufBase->Ptr(i));
+		}
+	file.Close();
+	iRfs.Close();
+	return KErrNone;
+	}	
+
+TInt CAtsLogger::WriteBufferToDebugPortL(CBufBase* aCBufBase)
+	{
+	TInt i = 0;
+	TPtrC8 ptr = aCBufBase->Ptr(i);
+	while (ptr.Length() > 0)
+		{
+		TBuf<KAtsLoggerBufferSegmentGranularity> debug;
+		for (TInt j = 0; j < ptr.Length(); j++)
+			{
+			debug.AppendFormat(_L("%c"), ptr[j]);
+			}
+		DebugOutput(debug);
+		i += ptr.Length();
+		ptr.Set(aCBufBase->Ptr(i));
+		}
+	return KErrNone;
+	}	
+
+void CAtsLogger::WriteL(const TDesC& aMsg)
+	{
+	if (iXmlLog || iDoDebugOutput)
+		{
+		BufferL(iXmlBuffer, iXmlBufferLength, aMsg);
+		iXmlBuffer->Compress();
+		}
+	}
+
+void CAtsLogger::WriteL(const TDesC& aMsg, RFile& aFile)
+	{
+	if (iLineFeedDone)
+		{
+		iLineFeedDone = EFalse;
+		for (TInt i = 0; i < iIndentLevel; i++)
+			{
+			WriteL(KAtsLoggerIndent(), aFile);
+			}
+		}
+	HBufC8* hBufC8 = HBufC8::NewL(aMsg.Length());
+	CleanupStack::PushL(hBufC8);
+	TPtr8 ptr8(hBufC8->Des());
+	TInt length = aMsg.Length();
+	for (TInt i = 0; i < length; i++)
+		{
+		if (aMsg[i] != '\n' && aMsg[i] != '\r')
+			{
+			ptr8.Append((TInt8)(aMsg[i] & 0xff));
+			}
+		else
+			{
+			ptr8.Append((TInt8)('\n'));
+			}
+		}
+	TRequestStatus status;
+	aFile.Write(*hBufC8, length, status);
+	User::WaitForRequest(status);
+	CleanupStack::PopAndDestroy(hBufC8);
+	}
+
+TBool CAtsLogger::IsTransitionLegal(const TReportStage& aNewStage)
+	{
+	switch (iReportStage)
+		{
+		case EUninitialized:
+			return (aNewStage == EUninitialized || aNewStage == EBeginTestReport);
+		case EBeginTestReport:
+			return (aNewStage == EBeginTestSet || aNewStage == EEndTestReport);
+		case EBeginTestSet:
+			return (aNewStage == EBeginTestCase || aNewStage == EEndTestSet);
+		case EBeginTestCase:
+			return (aNewStage == ESetTestCaseVerdict);
+		case ESetTestCaseVerdict:
+			return (aNewStage == EEndTestCase);
+		case EEndTestCase:
+			return (aNewStage == EEndTestSet || aNewStage == EBeginTestCase);
+		case EEndTestSet:
+			return (aNewStage == EEndTestReport || aNewStage == EBeginTestSet);
+		case EEndTestReport:
+			return (aNewStage == EFinished);
+		case EFinished:
+		default:
+			break;
+		}
+	return EFalse;
+	}
+
+EXPORT_C const TPtrC CAtsLogger::ErrorMessage(const TInt& aError)
+	{
+	switch (aError)
+		{
+		case EUninitialized:
+			return _L("Invalid report stage transition to EUninitialized");
+		case EBeginTestReport:
+			return _L("Invalid report stage transition to EBeginTestReport");
+		case EBeginTestSet:
+			return _L("Invalid report stage transition to EBeginTestSet");
+		case EBeginTestCase:
+			return _L("Invalid report stage transition to EBeginTestCase");
+		case ESetTestCaseVerdict:
+			return _L("Invalid report stage transition to ESetTestCaseVerdict");
+		case EEndTestCase:
+			return _L("Invalid report stage transition to EEndTestCase");
+		case EEndTestSet:
+			return _L("Invalid report stage transition to EEndTestSet");
+		case EEndTestReport:
+			return _L("Invalid report stage transition to EEndTestReport");
+		case EFinished:
+			return _L("Invalid report stage transition to EFinished");
+		case KErrNone:
+			return _L("KErrNone");
+		case KErrNotFound:
+			return _L("KErrNotFound");
+		case KErrGeneral:
+			return _L("KErrGeneral");
+		case KErrCancel:
+			return _L("KErrCancel");
+		case KErrNoMemory:
+			return _L("KErrNoMemory");
+		case KErrNotSupported:
+			return _L("KErrNotSupported");
+		case KErrArgument:
+			return _L("KErrArgument");
+		case KErrTotalLossOfPrecision:
+			return _L("KErrTotalLossOfPrecision");
+		case KErrBadHandle:
+			return _L("KErrBadHandle");
+		case KErrOverflow:
+			return _L("KErrOverflow");
+		case KErrUnderflow:
+			return _L("KErrUnderflow");
+		case KErrAlreadyExists:
+			return _L("KErrAlreadyExists");
+		case KErrPathNotFound:
+			return _L("KErrPathNotFound");
+		case KErrDied:
+			return _L("KErrDied");
+		case KErrInUse:
+			return _L("KErrInUse");
+		case KErrServerTerminated:
+			return _L("KErrServerTerminated");
+		case KErrServerBusy:
+			return _L("KErrServerBusy");
+		case KErrCompletion:
+			return _L("KErrCompletion");
+		case KErrNotReady:
+			return _L("KErrNotReady");
+		case KErrUnknown:
+			return _L("KErrUnknown");
+		case KErrCorrupt:
+			return _L("KErrCorrupt");
+		case KErrAccessDenied:
+			return _L("KErrAccessDenied");
+		case KErrLocked:
+			return _L("KErrLocked");
+		case KErrWrite:
+			return _L("KErrWrite");
+		case KErrDisMounted:
+			return _L("KErrDisMounted");
+		case KErrEof:
+			return _L("KErrEof");
+		case KErrDiskFull:
+			return _L("KErrDiskFull");
+		case KErrBadDriver:
+			return _L("KErrBadDriver");
+		case KErrBadName:
+			return _L("KErrBadName");
+		case KErrCommsLineFail:
+			return _L("KErrCommsLineFail");
+		case KErrCommsFrame:
+			return _L("KErrCommsFrame");
+		case KErrCommsOverrun:
+			return _L("KErrCommsOverrun");
+		case KErrCommsParity:
+			return _L("KErrCommsParity");
+		case KErrTimedOut:
+			return _L("KErrTimedOut");
+		case KErrCouldNotConnect:
+			return _L("KErrCouldNotConnect");
+		case KErrCouldNotDisconnect:
+			return _L("KErrCouldNotDisconnect");
+		case KErrDisconnected:
+			return _L("KErrDisconnected");
+		case KErrBadLibraryEntryPoint:
+			return _L("KErrBadLibraryEntryPoint");
+		case KErrBadDescriptor:
+			return _L("KErrBadDescriptor");
+		case KErrAbort:
+			return _L("KErrAbort");
+		case KErrTooBig:
+			return _L("KErrTooBig");
+		case KErrDivideByZero:
+			return _L("KErrDivideByZero");
+		case KErrBadPower:
+			return _L("KErrBadPower");
+		case KErrDirFull:
+			return _L("KErrDirFull");
+		case KErrHardwareNotAvailable:
+			return _L("KErrHardwareNotAvailable");
+		default:
+			return _L("Unknown error to ATS logger.");
+		}
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ConsoleUI/group/ConsoleUI.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Consoleui app.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          ConsoleUI.exe
+TARGETTYPE      exe
+
+CAPABILITY	AllFiles CommDD
+VENDORID 	0x101FB657
+SECUREID        0x102073DA
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+USERINCLUDE     ../../StifTFwIf/inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+/* Source files */
+SOURCEPATH      ../src
+
+SOURCE          ConsoleUI.cpp
+SOURCE          Consolemenus.cpp
+SOURCE          ConsoleNotify.cpp
+
+/* Used libraries */
+LIBRARY         euser.lib
+LIBRARY		efsrv.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftfwif.lib
+LIBRARY     	  stiftestengine.lib
+
+// In case of large amount of test cases, bigger heap size is required. 
+// Heap sizes can be changed using EPOCHEAPSIZE statement, where the first
+// parameter is heap's minimum size and the latter the maximum size.
+EPOCHEAPSIZE    0x10000 0x300000
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ConsoleUI/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for STIF Test Framework's Console UI.
+*/
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	ConsoleUI.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ConsoleUI/inc/CallBack.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,211 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CCallBack 
+* class.
+*
+*/
+
+#ifndef CALLBACK_H
+#define CALLBACK_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Simple class for callbacks.
+
+class CCallBack 
+    :public CAsyncCallBack
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * C++ constructor.
+        */
+        CCallBack( TInt aPriority ):CAsyncCallBack( aPriority ) {}
+
+        /**
+        * C++ constructor.
+        */
+        CCallBack( TCallBack& aCallBack, TInt aPriority ):
+            CAsyncCallBack( aCallBack, aPriority ) {}
+    
+    public: // New functions
+        /**
+        * Return reference to TRequestStatus member.
+        */
+        TRequestStatus& Status(){ return iStatus; }
+
+        /**
+        * Set CCallBack active.
+        */
+        void SetActive()
+            { 
+            iStatus = KRequestPending; 
+            CActive::SetActive(); 
+            };
+    
+    public: // Functions from base classes
+   
+        /**
+        *
+        */
+        void RunL(){ iCallBack.CallBack(); }
+
+    protected:  // New functions
+        
+    protected:  // Functions from base classes
+        
+    private:
+
+	public:     // Data
+    
+	protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+
+template <class T>
+class CActiveCallback 
+        :public CActive
+    {
+    public: // Enumerations
+
+        /**
+        * Callback function type definitions
+        */
+       typedef void (T::* TestFunction)();    
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * C++ constructor.
+        */
+        CActiveCallback ( T* aClass, TestFunction aFunction ) : CActive (EPriorityStandard)
+            {
+            iMethod = aFunction;
+            iClass = aClass;
+            iCompleted = EFalse;
+            }
+    
+    public: // New functions
+        /**
+        * Return reference to TRequestStatus member.
+        */
+        TRequestStatus& Status(){ return iStatus; }
+
+        /**
+        * Set active object to active and return reference to TRequestStatus member
+        */
+        TRequestStatus& Activate()
+            {        
+            iCompleted = EFalse;
+            SetActive();
+            return iStatus;
+            }
+
+        /**
+        * Is callback completed?
+        */
+        TBool isCompleted()
+            {
+            return iCompleted;
+            }
+    
+    public: // Functions from base classes
+   
+        /**
+        * Call the callback
+        */
+        void RunL()
+            {
+            iCompleted = ETrue;
+            if ( iMethod != NULL )
+                {
+                (iClass->*iMethod) ();
+                }        
+            }
+
+        /**
+        * Just forward errors to framework
+        */
+        TInt RunError ( TInt aError )
+            {
+            return aError;
+            }
+
+        /**
+        * Cancel is not supported.
+        */
+        void DoCancel ()
+            {  
+            }
+
+    protected:  // New functions
+        
+    protected:  // Functions from base classes
+        
+    private:
+
+
+
+	public:     // Data
+    
+	protected:  // Data
+
+    private:    // Data
+        TestFunction iMethod;           // Pointer to method to be called
+        T* iClass;                      // Pointer to calls to be called
+        TBool iCompleted;               // Is callback completed?
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // CALLBACK_H  
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ConsoleUI/inc/ConsoleMenus.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1912 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CMenu 
+* derived classes.
+*
+*/
+
+
+#ifndef CONSOLE_MENUS_H
+#define CONSOLE_MENUS_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <stifinternal/UIStoreIf.h>
+#include <stifinternal/UIStoreContainer.h>
+#include <stifinternal/UIEngineContainer.h>
+
+#include "CallBack.h"
+
+// CONSTANTS
+const TInt KMenuOverhead = 4;
+
+// Numeric key ascii code values for ConsoleUI's menu
+const TInt KMyKeyDownAsciiCode = 56; // Ascii code for number '8'
+const TInt KMyKeyLeftAsciiCode = 52; // Ascii code for number '4'
+const TInt KMyKeyRightAsciiCode = 54; // Ascii code for number '6'
+const TInt KMyKeyUpAsciiCode = 50;  // Ascii code for number '2'
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CMenu;
+class CConsoleMain;
+class CCaseOperationMenu;
+class CCaseExecutionView;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Main menu
+class CMenu
+        :public CBase
+    {
+    public:  // Enumerations
+        enum TUpdateType
+            {
+            EMenuPrint,
+            EMenuRefresh,
+            };
+
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMenu* NewL( CConsoleMain* aConsole,
+                            CMenu* aParent,
+                            const TDesC& aName);
+
+       /**
+        * Destructor of CConsoleMain.
+        */
+        virtual ~CMenu();
+
+    public: // New functions
+    
+        /** 
+        * Return menu name
+        */
+        virtual const TDesC& Name() const;
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Set parent menu
+        */
+        virtual void SetParent ( CMenu* aMenu );
+
+        /** 
+        * Print line
+        */
+        virtual void Print( const TDesC& aPrint);
+
+        /** 
+        * Multi line print
+        */
+        virtual void PrintMulti( const TDesC& aPrint );
+
+        /** 
+        * Add item to menu
+        */
+        virtual void AddItemL ( CMenu* aItem );
+        
+        /** 
+        * Signals test completion
+        */
+        virtual void SignalL ( CStartedTestCase* /*aContainer*/ ){};
+		
+        /** 
+        * Update display from timer
+        */
+		virtual void TimerUpdate();
+		
+		/**
+		* Append text before original text.
+		*/
+		virtual void AppendBefore(  TInt aLineNum, TDes& aLine );
+		
+		/**
+		* Get menu type.
+		*/
+		inline TInt Type(){ return iType; };
+		
+		/**
+		* Map KeyCode 
+		*/
+		void MapKeyCode(TKeyCode &aSelection);
+
+		/**
+		 * Recalculates visible menu elements.
+		 */
+		void Recalculate( TInt aItemCount );
+		
+    public: // Functions from base classes
+        // None
+
+    protected:  // New functions
+        // None
+
+    private:   // New functions
+        /**
+        * Changes internal variables to move cursor in the menu.
+        */
+        void MovePosition(TInt aDelta);
+
+    protected:  // Functions from base classes
+        // None    
+
+        /** 
+        * C++ default constructor.
+        */
+        CMenu();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         const TDesC& aHeader = KNullDesC);
+    
+    private:   // Functions from base classes
+        // None
+
+    public:   // Data
+        // None
+
+    protected:  // Data    
+    
+        CConsoleBase*           iConsole;      // Pointer to console
+        CConsoleMain*           iMain;         // Pointer to main console
+        CMenu*                  iParent;       // Pointer to parent menu
+        TName                   iName;         // Menu name
+    	TName					iHeader;	   // Used to display STIF version information
+
+        RPointerArray<CMenu>    iItems;        // Menu items
+
+        TInt                    iPosOnScreen;  // Position on display
+        TInt                    iPrevPosOnScreen; // Previous position on display
+        TInt                    iMenuItemsListStartIndex;    // Y-index of the first line containing menu item
+        TInt                    iMenuItemsListEndIndex;    // Y-index of the last line containing menu item
+        TInt                    iFirst;        // First displayed item
+        TInt                    iLast;         // Last displayed item
+        TBool                   iPreventClearScreen;  // In case of moving cursor "in screen" cleaning screen is not needed
+        TInt                    iItemCount;    // Last Item
+        TSize                   iSize;         // Display size
+        TInt                    iScreenSize;   // "Work area" size
+		TInt                    iDirection;    // Scrolling direction
+		TInt                    iStart;        // Scrolling position
+		TInt                    iPrevPos;      // Previous position in scrolling
+
+        // Menu type (which updates must cause console update) 
+        // Flags from CUIStoreIf::TUpdateFlags 
+        TInt                    iType;
+        
+        // Update type set from PrintMenuL
+		TUpdateType             iUpdateType;
+		
+    private:    // Data
+        TName           iScrolledLine; //Original value of line, that was recently scrolled
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+
+// CONSTANTS
+_LIT( KSelectMenuTxt, "Select module to load, if using ini or test case file use testframework.ini" );
+
+// DESCRIPTION
+// Filename query menu
+class CFileNameQueryView 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CFileNameQueryView* NewL( CConsoleMain* aConsole, 
+                                         CMenu* aParent, 
+                                         const TDesC& aName);
+
+        ~CFileNameQueryView();
+        
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+        
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+    protected:  // New functions
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent, 
+                         const TDesC& aName );
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+    public:   // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // List of module names
+        RPointerArray<TDesC>    iTestModuleNames;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KAddMenuTxt,  "Add test module" );
+_LIT( KLoadMenuTxt,  "Load all test modules" );
+
+// DESCRIPTION
+// Module list menu
+class CModuleListView 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TModuleListMenu
+            {
+            EAddMenuTxtItem,
+            ELoadMenuTxtItem,
+            };
+            
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CModuleListView* NewL( CConsoleMain* aConsole,
+                                      CMenu* aParent,
+                                      const TDesC& aName );
+
+       /**
+        * Destructor
+        */
+        ~CModuleListView();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+        
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, 
+                                TBool& aContinue );
+ 
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+        
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CMenu*                     iModuleAdd;
+
+    public:     // Friend classes
+         // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// Test case starting menu
+class CCaseStartMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCaseStartMenu* NewL( CConsoleMain* aConsole, 
+                                     CMenu* aParent, 
+                                     const TDesC& aName,
+                                     TBool aShowOutput = EFalse);
+
+        /**
+        * Destructor.
+        */
+		~CCaseStartMenu();
+
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, 
+                                TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         TBool aShowOutput = EFalse);
+
+    private:
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // Test case array
+        RRefArray<CTestInfo> iTestCases;
+
+    private:    // Data
+        // Show output automaticly after test case is started
+        TBool iShowOutput;
+        
+        // Map table. Translates indexes from filtered to all loaded from module  
+        RArray<TInt> iMapFilteredToAll;
+        
+        // Keeps filter name converted to lower case
+        TFileName iFilterLowerCase;
+        
+        // Keeps title of test case converted to lower case
+        TFileName iTitleLowerCase;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KChangeAll, "Change all");
+_LIT( KCancelSet, "Cancel set execution" );
+
+// Test set creation menu
+class CMultipleBaseMenu 
+    :public CCaseStartMenu
+  
+    {
+    public:  // Enumerations
+         enum TMenuIndex
+		    {  
+		    EChangeAll = 0,
+		    ECancelSet = 0,
+		    };
+        enum TRunType
+            {
+            ERunSequential,
+            ERunParallel,
+            ERunRepeatSequential,
+            };
+		    
+    protected: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMultipleBaseMenu* NewL( CConsoleMain* aConsole, 
+                                        CMenu* aParent, 
+                                        const TDesC& aName);
+        
+        /**
+        * Destructor.
+        */
+		~CMultipleBaseMenu();
+
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+		/** 
+        * Signals test completion
+        */
+        virtual void SignalL ( CStartedTestCase* aContainer );
+        
+        /** 
+        * Append text before line print.
+        */
+        virtual void AppendBefore( TInt aLineNum, TDes& aLine );
+        
+    protected:  // New functions
+
+        //inline void SetRunType( TRunType aRunType )
+        //    { iRunType = aRunType; };
+            
+        /**
+        * Update iTestCases();
+        */ 
+        virtual TInt UpdateTestCases();
+        TBool CheckIfAnyCaseIsSelected(TInt aCount);
+                      
+    protected:  // Functions from base classes
+
+        /**
+        * Constructor.
+        */
+		CMultipleBaseMenu();
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+       
+    public:     // Data
+
+    protected:  // Data
+		RArray<TBool>       iSetState;
+		TInt                iCurrentRunPos;
+		TBool               iSetFinished;
+		CStartedTestCase*   iOngoingCaseContainer;
+		TRunType            iRunType;
+				
+		// Number of items in "static" menu (including derived classes)
+		TInt                iMenuTotCount;
+
+    private:    // Data
+		// Number of items in "static" menu of this class
+		// (excluding derived classes)  
+		TInt                iMenuCount;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// CONSTANTS
+_LIT( KRunSequentially, "Run selection sequentially");
+_LIT( KRunParallel, "Run selection parallel");
+_LIT( KRepeatRunSequentially, "Repeat run selection sequentially");
+
+_LIT( KSelectFromTo, "Select all between already selected"); 
+
+// Test set creation menu
+class CMultipleCaseMenu 
+    :public CMultipleBaseMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TMultipleMenuIndex
+		    {  
+		    ERunSelection = 0,
+		    ERunSelectionParaller = 1,
+		    ERepeatRunSelection = 2,
+		    ESelectFromTo = 3,
+		    };
+		    
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMultipleCaseMenu* NewL( CConsoleMain* aConsole, 
+                                        CMenu* aParent, 
+                                        const TDesC& aName);
+        
+        /**
+        * Destructor.
+        */
+		~CMultipleCaseMenu();
+
+    public: // New functions
+       /**
+       * Start running.
+       */
+       virtual void StartRunningL( TRunType aRunType, 
+                                   const TDesC& aModule = KNullDesC, 
+                                   const TDesC& aTestCaseFile = KNullDesC );
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+    
+        /**
+        * Constructor.
+        */
+		CMultipleCaseMenu();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+       
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Number of items in "static" menu of this class
+		// (excluding derived classes)  
+		TInt                iMenuItemsCount;
+		
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+// CONSTANTS
+_LIT( KExitTxt,     "Exit" );
+
+// DESCRIPTION
+// The main menu class
+class CMainMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMainMenu* NewL( CConsoleMain* aConsole, 
+                                CMenu* aParent, 
+                                const TDesC& aName,
+                                const TDesC& aHeader );
+
+        /**
+        * Destructor
+        */
+        ~CMainMenu();
+
+    public: // New functions
+        /**
+        * Creates CaseOperationMenu and CaseExecutionView.
+        * Used when after test case starting its output view needs to be shown.
+        */
+        CMenu* CreateOutputViewL(CMenu* aParent);
+
+    public: // Functions from base classes    
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         const TDesC& aHeader );
+
+    private:
+
+    public:   //Data
+
+    protected:  // Data
+
+    private:    // Data
+        // Menu representing output view, used to show it after test case is started
+        CCaseExecutionView* iOutputView;
+
+        // Operation menu used to show output view after test case is started
+        CCaseOperationMenu* iOperationMenu;
+		
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+
+// DESCRIPTION
+// The case list (passed/failed/...) menu class
+class CCaseMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCaseMenu* NewL( CConsoleMain* aConsole, 
+                                CMenu* aParent, 
+                                const TDesC& aName, 
+                                TInt aType );
+
+        /**
+        * Destructor
+        */
+        ~CCaseMenu();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes    
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+        
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+        /**
+        * Append text before original text.
+        */
+        virtual void AppendBefore(TInt aLineNum, TDes& aLine);
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent, 
+                         const TDesC& aName, 
+                         TInt aType );
+
+    private:    // Data
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        CCaseOperationMenu*             iCaseOperationMenu;    // Submenu
+        RRefArray<CStartedTestCase>     iTestCases;
+
+    private:    // Data
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KOutputViewDes,   "View Output");
+_LIT( KPauseCaseDes,    "Pause");
+_LIT( KResumeCaseDes,   "Resume");
+_LIT( KAbortCaseDes,    "Abort case");
+_LIT( KRestartCaseDes,  "Restart");
+
+// DESCRIPTION
+// Case specific operations, like pause, abort etc.
+class CCaseOperationMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TCaseOperationMenu
+            {
+            ERestartCase,
+            EOutputView,
+            EPauseResume,
+            EAbortCase,   
+            };
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCaseOperationMenu* NewL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName, 
+                            const CStartedTestCase* aCaseContainer );
+        
+        /**
+        * Destructor.
+        */
+        ~CCaseOperationMenu();
+        
+    public: // New functions
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         const CStartedTestCase* aCaseContainer );
+
+    private:    // Functions from base classes
+        // None
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Case container
+        const CStartedTestCase* iCaseContainer; 
+        // Execution view                       
+        CCaseExecutionView*     iView;
+        
+    public:     // Friend classes
+        // None        
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+class CCaseExecutionView 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCaseExecutionView* NewL( CConsoleMain* aConsole, 
+                                         CMenu* aParent, 
+                                         const TDesC& aName, 
+                                         const CStartedTestCase* aCase);
+
+         /**
+        * Destructor.
+        */
+        ~CCaseExecutionView();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+        
+        /**
+        * Get current testcase info.
+        */ 
+        inline const CStartedTestCase* TestCase(){ return iCase; };
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         const CStartedTestCase* aCase );
+
+    private:   // Functions from base classes
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        const CStartedTestCase* iCase;
+
+        /**
+        * Indicates current selected line.
+        */
+        TInt                    iLine;
+        /**
+        * Indicates will line show.
+        */
+        TBool                   iShowLine;
+        /**
+        * Line to be show.
+        */
+        HBufC*                  iLineTextBuf;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CMenu notifier class shows dialogs in UI.
+class CMenuNotifier
+        :public CBase
+    {
+    public:  // Enumerations
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMenuNotifier* NewL( const TDesC& aError, 
+                                    CConsoleMain* aMain );
+
+       /**
+        * Destructor of CConsoleMain.
+        */
+        virtual ~CMenuNotifier();
+
+    public: // New functions  
+            
+    public: // Functions from base classes
+        // None
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None    
+
+        /** 
+        * C++ default constructor.
+        */
+        CMenuNotifier( CConsoleMain* aMain );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aError );
+    
+    private:   // Functions from base classes
+        // None
+
+    private:   // New functions
+        /** 
+        * C++ default constructor.
+        */
+        void Run1();	
+
+    public:   // Data
+        // None
+
+    protected:  // Data      
+
+    private:    // Data
+        CActiveCallback <CMenuNotifier> iCallBack1;
+        CActiveCallback <CMenuNotifier> iCallBack2;
+        RTimer iTimer;
+        CConsoleBase* iConsole;
+        CConsoleMain* iMain;        
+        TInt iCompletionCode; 
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CMenu dialog class shows dialogs in UI and waits for keypress.
+class CMenuDialog
+    :public CBase
+    {
+    public:  // Enumerations
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMenuDialog* NewL( CConsoleMain* aMain, 
+                                  const TDesC& aMessage, 
+                                  const TDesC& aInstruction,
+                                  TInt aTimeInSecs );
+
+       /**
+        * Destructor.
+        */
+        virtual ~CMenuDialog();
+
+    public: // New functions  
+            
+    public: // Functions from base classes
+        
+        TInt WaitForKeypress( TKeyCode& aKeyCode, 
+                              TRequestStatus& aStatus  );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None    
+
+        /** 
+        * C++ default constructor.
+        */
+        CMenuDialog( CConsoleMain* aMain );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aMessage, 
+                         const TDesC& aInstruction, 
+                         TInt aTimeInSecs );
+    
+    private:   // Functions from base classes
+        // None
+
+    private:   // New functions
+        /**
+        * Handle completions.
+        */
+        void Run1();	
+
+    public:   // Data
+        // None
+
+    protected:  // Data      
+
+    private:    // Data
+        // Backpointer
+        CConsoleMain* iMain;        
+        CConsoleBase* iConsole;
+
+        // Timer support
+        CActiveCallback <CMenuDialog> iCallBack1;
+        RTimer iTimer;
+        
+        // Reading
+        CActiveCallback <CMenuDialog> iCallBack2;
+        
+        // For reading keys        
+        TRequestStatus* iStatus;
+        TKeyCode*     iKeyCode;
+    
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KTestSetMenu,     "CTestSetMenu" );
+
+_LIT( KDefaultSetName,  "ConsoleUI.set" );
+
+_LIT( KSetCreate,       "Create test set" );
+_LIT( KSetLoad,         "Load test set" );
+
+_LIT( KSetShow,         "Show started test sets" );
+_LIT( KSetUnload,       "Unload test set" );
+_LIT( KSetRemove,       "Remove test set" );
+_LIT( KSetCaseAdd,      "Add test case to test set" );
+_LIT( KSetCaseRemove,   "Remove test case from test set" );
+_LIT( KSetSave,         "Save test set" );
+
+_LIT( KSetStartSeq,     "Start sequential test set execution" );
+_LIT( KSetStartPar,     "Start parallel test set execution" );
+//_LIT( KSetStartRep,     "Start repeating test set execution" );
+
+_LIT( KSetStartSeqNotRun, "Start sequentially not started tests" );
+
+// DESCRIPTION
+// Test set menu
+class CTestSetMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        
+    private: // Enumerations
+        
+        enum TCreateMenu
+            {
+            ESetCreate,
+            ESetLoad,    
+            };
+            
+        enum TEditMenu
+            {
+            ESetShow,
+ 
+            ESetStartSeq,
+            ESetStartPar,
+            //ESetStartRep,
+ 
+            ESetUnload,
+            ESetRemove,
+            ESetSave,
+            ESetCaseAdd,
+            ESetCaseRemove,
+            
+            ESetStartSeqNotRun,
+            
+
+            ESetLAST //This entry must remain LAST in this menu
+            };
+            
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetMenu* NewL( CConsoleMain* aConsole,
+                                   CMenu* aParent,
+                                   const TDesC& aName );
+
+       /**
+        * Destructor
+        */
+        ~CTestSetMenu();
+
+    public: // New functions
+        /**
+        * Set test set file name.
+        */
+        void SetTestSetFileName( const TFileName& aTestSetFileName ); 
+        
+        /**
+        * Set test set state created.
+        */
+        void SetCreated(){ iTestSetCreated = ETrue; };
+         
+    public: // Functions from base classes
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+        
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, 
+                                TBool& aContinue );
+ 
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+        /**
+        * Constructor
+        */
+        CTestSetMenu();
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        TBool               iTestSetCreated;
+        TFileName           iTestSetName;
+        
+        CMenu*              iSubMenu;
+        
+    public:     // Friend classes
+         // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+    // CONSTANTS
+    _LIT( KTestSetChoice,     "CTestSetChoiceMenu" );
+    _LIT( KSetSelect,       "Select Test Set" );
+
+
+    // DESCRIPTION
+    // Test set choice menu
+    class CTestSetChoiceMenu 
+        :public CMenu
+
+        {
+        public:  // Enumerations
+            
+        private: // Enumerations
+            
+            
+                
+        public:  // Constructors and destructor
+
+            /**
+            * NewL is first phase of two-phased constructor.
+            */
+            static CTestSetChoiceMenu* NewL( CConsoleMain* aConsole,
+                                       CMenu* aParent,
+                                       const TDesC& aName );
+
+           /**
+            * Destructor
+            */
+            ~CTestSetChoiceMenu();
+
+        public: // New functions
+             
+        public: // Functions from base classes
+
+            /** 
+            * Return item texts.
+            */
+           virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+            
+            /** 
+            * Process keypresses on this menu
+            */
+            virtual CMenu* SelectL( TKeyCode aSelectLion, 
+                                    TBool& aContinue );
+     
+            /** 
+            * Prints the menu
+            */
+            virtual void PrintMenuL( TUpdateType  aType );
+            
+        protected:  // New functions
+
+        protected:  // Functions from base classes
+            /**
+            * Constructor
+            */
+            CTestSetChoiceMenu();
+           
+            /**
+            * By default Symbian OS constructor is private.
+            */
+            void ConstructL( CConsoleMain* aConsole, 
+                             CMenu* aParent,
+                             const TDesC& aName );
+
+        private:
+
+        public:   //Data
+            // None
+
+        protected:  // Data
+            // None
+
+        private:    // Data
+            TFileName           iTestSetName;
+            RPointerArray<HBufC> iFileList;
+            
+        public:     // Friend classes
+             // None
+
+        protected:  // Friend classes
+            // None
+
+        private:    // Friend classes
+            // None
+
+        };
+    
+// CONSTANTS
+_LIT( KAddSelected, "Add selected cases");
+
+// Test set case add menu
+class CTestSetAddCaseMenu 
+    :public CMultipleBaseMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TTestSetAddCaseMenuIndex
+		    {  
+		    EAddSelected = 0,
+		    };
+		    
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetAddCaseMenu* NewL( CConsoleMain* aConsole, 
+                                         CMenu* aParent, 
+                                         const TDesC& aName,
+                                         TDesC& aTestSetName );
+        
+        /**
+        * Destructor.
+        */
+		~CTestSetAddCaseMenu();
+
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+    
+        /**
+        * Constructor.
+        */
+		CTestSetAddCaseMenu( TDesC& aTestSetName );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+       
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Number of items in "static" menu of this class
+		// (excluding derived classes)  
+		TInt    iMenuItemsCount;
+		
+        TPtrC   iTestSetName;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KRemoveSelected, "Remove selected cases");
+
+// Test set case add menu
+class CTestSetRemoveCaseMenu 
+    :public CMultipleBaseMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TTestSetRemoveCaseMenuIndex
+		    {  
+		    ERemoveSelected = 0,
+		    };
+		    
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetRemoveCaseMenu* NewL( CConsoleMain* aConsole, 
+                                             CMenu* aParent, 
+                                             const TDesC& aName,
+                                             TDesC& aTestSetName );
+        
+        /**
+        * Destructor.
+        */
+		~CTestSetRemoveCaseMenu();
+
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+        
+        /**
+        * Update iTestCases;
+        */ 
+        virtual TInt UpdateTestCases();
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+    
+        /**
+        * Constructor.
+        */
+		CTestSetRemoveCaseMenu( TDesC& aTestSetName );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+       
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Number of items in "static" menu of this class
+		// (excluding derived classes)  
+		TInt        iMenuItemsCount;
+		
+        TPtrC       iTestSetName;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };    
+
+// DESCRIPTION
+// The case list (passed/failed/...) menu class
+class CTestSetCaseMenu  
+    :public CCaseMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetCaseMenu* NewL( CConsoleMain* aConsole, 
+                                       CMenu* aParent, 
+                                       const TDesC& aName,
+                                       CStartedTestSet& aTestSet );
+
+        /**
+        * Destructor
+        */
+        ~CTestSetCaseMenu();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes    
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+        /** 
+        * Prints the menu
+        */
+        void AppendBefore( TInt aLineNum, TDes& aLine );
+        
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );     
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+       
+
+    private:    // Data
+    
+        CTestSetCaseMenu( CStartedTestSet& aTestSet );
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent, 
+                         const TDesC& aName );
+    public:     // Data
+        // None
+
+    protected:  // Data
+
+    private:    // Data
+        CStartedTestSet& iTestSet;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KCancelTestSet, "Cancel test set");
+        
+// DESCRIPTION
+// Started test sets (passed/failed/...) menu class
+class CStartedTestSetMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CStartedTestSetMenu* NewL( CConsoleMain* aConsole, 
+                                          CMenu* aParent, 
+                                          const TDesC& aName );
+
+        /**
+        * Destructor
+        */
+        ~CStartedTestSetMenu();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes    
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+        
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+
+        /** 
+        * Prints the menu
+        */
+        void AppendBefore( TInt aLineNum, TDes& aLine );
+        
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+       
+
+    private:    // Data
+    
+        CStartedTestSetMenu();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent, 
+                         const TDesC& aName );
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CTestSetCaseMenu*           iCaseMenu;    // Submenu
+        RRefArray<CStartedTestSet>  iTestSets;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// Menu which shows available filters for test case titles
+class CFilterMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CFilterMenu* NewL(CConsoleMain* aConsole, 
+                                 CMenu* aParent, 
+                                 const TDesC& aName);
+
+        /**
+        * Destructor.
+        */
+        ~CFilterMenu();
+
+    public: // New functions
+        /**
+        * Set test case menu, so it can be shown when user selects filter
+        */
+        void SetTestCaseMenu(CMenu* aTestCaseMenu);
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL(TKeyCode aSelectLion, 
+                               TBool& aContinue);
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts(RRefArray<TDesC>& aArray);
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        /** 
+        * C++ default constructor.
+        */
+        CFilterMenu();
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL(CConsoleMain* aConsole,
+                        CMenu* aParent,
+                        const TDesC& aName);
+
+    private:    // Functions
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+        
+    private:    // Data
+        /**
+        * Test case menu. It will be shown when user selects filter.
+        */
+        CMenu *iTestCaseMenu;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+   
+#endif // CONSOLE_MENUS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ConsoleUI/inc/ConsoleUI.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,435 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the ConsoleUI.
+*
+*/
+
+#ifndef CONSOLE_UI_H
+#define CONSOLE_UI_H
+
+
+//  INCLUDE
+#include <e32std.h>
+#include <e32base.h>
+
+#include <stifinternal/UIStoreIf.h>
+#include <stifinternal/UIStore.h>
+#include <stifinternal/UIEngine.h>
+
+#include "CallBack.h"
+
+#include "TestModuleInfo.h"
+
+#include "ConsoleMenus.h"
+
+// CONSTANTS
+const TInt KMaxLineLength = 80;            // Longest supported line length
+const TInt KScrollPeriod = 300000;		   // Scrolling speed
+
+// MACROS
+
+// DATA TYPES
+
+// Case state
+// Menu update type
+enum TConsoleUIPanic
+    {
+    EInvalidCaseCompletion,
+    };
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CMenu;
+class CConsoleMain;
+class CConsoleReader;
+class CMenuDialog;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CModule contains a test module data
+
+class CScrollerTimer
+        :public CActive
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CScrollerTimer* NewL( CConsoleMain* aMain );
+
+        /**
+        * Destructor of CModule.
+        */
+        ~CScrollerTimer();
+
+    public: // New functions
+
+		/** 
+        * StartL
+        */
+		void StartL();
+
+		/** 
+        * RunL
+        */
+		void RunL();
+
+		/** 
+        * DoCancel
+        */
+		void DoCancel();
+
+		/** 
+        * RunError
+        */
+		TInt RunError ( TInt aError );
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CScrollerTimer();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aMain );
+
+    public:   //Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CConsoleMain*     iMain;            // Pointer to main console
+		RTimer            iTimer;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// Console UI main class
+class CConsoleMain
+        :public CUIStoreIf
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TStartCasesOnStart
+            {
+            EStartCaseNo = 0,
+            EStartSingleCase,
+            EStartCasesSeq,
+            EStartCasesPar,
+            };
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CConsoleMain* NewL();
+
+        /**
+        * Start
+        */
+        TInt StartL();
+
+        /**
+        * Destructor of CConsoleMain.
+        */
+        ~CConsoleMain();
+
+
+    public: // New functions
+    
+    
+        /**
+        * Receives output update notification from CUIStore.
+        */
+        void Update( CStartedTestCase* aTestCase, 
+                     TInt aFlags );
+                                                                      
+        /**
+        * Function is called when test framework prints error.
+        */
+        void Error( TErrorNotification& aError );
+        
+        /**
+        * Function is called when testframework 
+        * wants to print a popup window.
+        */
+        TInt PopupMsg( const TDesC& aLine1, 
+                       const TDesC& aLine2, 
+                       TInt aTimeInSecs );
+        
+        /**
+        * Function is called when testframework 
+        * wants to print a popup window and 
+        * get the key pressed.
+        */
+        TInt PopupMsg( const TDesC& aLine1, 
+                       const TDesC& aLine2, 
+                       TInt aTimeInSecs,
+                       TKeyCode& aKey,
+                       TRequestStatus& aStatus );
+
+        /**
+        * Close instance.
+        */
+        void Close( TInt aHandle );
+                
+        /**
+        * Console UI panic function
+        */
+        static void Panic( TConsoleUIPanic aPanic );
+
+        /**
+        * Return pointer to console
+        */
+        CConsoleBase* GetConsole();
+
+        /**
+        * Called from timer to perform scrolling
+        */
+        void TimerUpdate();
+                
+        /**
+        * Process keystokes.
+        */
+        void KeyPressed();
+
+        /**
+         * Displays no memory error message and closes ConsoleUI
+         */
+        void ExitWithNoMemoryErrorMessage();
+        
+        /**
+         * Returns MainMenu of console
+         */
+        CMainMenu* GetMainMenu();
+        
+        /**
+         * Get filter array for reading purpose
+         */
+        const RPointerArray<TDesC>& GetFilterArray(void) const;
+        
+        /**
+         * Set info about which index filter is used
+         */
+        void SetFilterIndex(TInt aFilterIndex);
+
+        /**
+         * Get info about which index filter is used
+         */
+        TInt GetFilterIndex(void);
+        
+    public: // Functions from base classes
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CConsoleMain();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+
+        /**
+        * Print error from ConsoleUI.
+        */  
+        void UiError( const TDesC& aInfo );
+        
+        /**
+        * Process command line parameters.
+        */
+        void ProcessCommandlineL( TFileName& aIniFile );
+
+        /**
+        * Parse and search for module info and fill list of modules.
+        */
+        void ParseTestModulesL(CStifParser* aParser, CTestModuleList* aModuleList, const TDesC& aSectionStart, const TDesC& aSectionEnd);
+        
+    public:   //Data
+        RPointerArray<CMenuDialog> iDialogs;
+        
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CConsoleBase*       iConsole;       // Pointer to console
+
+        CMenu*              iMainMenu;      // Root menu
+        CMenu*              iCurrentMenu;   // Current menu
+
+        CScrollerTimer*     iScroller;
+        
+        CConsoleReader*     iReader;        // Console reader                   
+    
+        // For starting runnning multiple cases upon start
+        TStartCasesOnStart  iStartCases;
+        HBufC*              iTestModule;
+        HBufC*              iTestModuleIni;
+        HBufC*              iTestCaseFile;
+        TInt                iTestCaseNum;
+        HBufC*              iTestSetName;
+
+        // List of found modules (included from module given in parameters)
+        CTestModuleList*    iModuleList;
+        
+        // List of filters (for test cases title)
+        RPointerArray<TDesC> iFilters;
+        
+        // Chosen filter index
+        TInt iChosenFilterIndex;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+    
+// DESCRIPTION
+// Read keystrokes from console
+class CConsoleReader
+    :public CActive
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CConsoleReader* NewL( CConsoleMain* aMain, 
+                                     CConsoleBase* aConsole );
+
+        /**
+        * Start
+        */
+        void StartL();
+
+        /**
+        * Destructor of CConsoleReader.
+        */
+        ~CConsoleReader();
+
+
+    public: // New functions
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+        /**
+        * RunError derived from CActive handles errors from active object
+        */        
+        virtual TInt RunError(TInt aError);
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CConsoleReader( CConsoleMain* aMain, 
+                        CConsoleBase* iConsole );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CConsoleBase*   iConsole;   // Pointer to console
+        CConsoleMain*   iMain;      // Backpointer
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif // CONSOLEUI_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ConsoleUI/src/ConsoleNotify.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,474 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CMenuNotifier 
+* and CMenuDialog class implementations.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+#include <f32file.h>
+#include "ConsoleUI.h"
+#include "ConsoleMenus.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+const TInt KDefaultTime = 2;
+
+// MACROS
+#ifndef __WINS__
+  #define GETPTR &
+#else
+  #define GETPTR
+#endif
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+   
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuNotifier
+
+    Method: NewL
+
+    Description: Constructs new menu notifier
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenuNotifier* CMenuNotifier::NewL( const TDesC& aError, CConsoleMain* aMain )
+    {
+
+    CMenuNotifier* self = new ( ELeave ) CMenuNotifier( aMain );
+    CleanupStack::PushL( self );
+    self->ConstructL( aError );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuNotifier
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenuNotifier::ConstructL( const TDesC& aError )
+    {
+    
+    TSize size = iMain->GetConsole()->ScreenSize();
+    size.iWidth = Min( size.iWidth - KMenuOverhead, 
+                       aError.Length() );
+    size.iHeight = aError.Length()/size.iWidth + 2;
+    
+    iConsole = Console::NewL( _L("Error note"), size );
+    
+    iConsole->Printf( _L("Error:") );    
+    iConsole->Printf( aError ); 
+    iConsole->Printf( _L("\n") );
+    iConsole->Printf( _L("Press any key") );
+
+    iTimer.CreateLocal();
+
+    CActiveScheduler::Add ( &iCallBack1 );
+    CActiveScheduler::Add ( &iCallBack2 );
+
+    // Get timer
+    iTimer.After( iCallBack1.Activate(), 10000000 );
+
+    // Poll keypresses
+    iConsole->Read ( iCallBack2.Activate() );        
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuNotifier
+
+    Method: CMenuNotifier
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+#pragma warning( disable : 4355 )       // Incomplete this usage
+CMenuNotifier::CMenuNotifier( CConsoleMain* aMain ): 
+    iCallBack1 ( this, GETPTR CMenuNotifier::Run1 ),
+    iCallBack2 ( this, GETPTR CMenuNotifier::Run1 ),
+    iMain( aMain )          
+    {
+    }
+#pragma warning( default : 4355 )
+
+/*
+-------------------------------------------------------------------------------
+e
+    Class: CMenuNotifier
+
+    Method: ~CMenuNotifier
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CMenuNotifier::~CMenuNotifier()
+    {
+    iTimer.Close();
+    delete iConsole;    
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuNotifier
+
+    Method: Run1
+
+    Description: Callback function. Closes dialog
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenuNotifier::Run1()
+    {
+
+    if ( iCallBack1.isCompleted() && iCallBack2.isCompleted() )
+        {
+        // Both callback have been done, delete this object
+        delete this;
+        return;
+        }
+    else
+        {
+        // One callback finished, stop listening anything else
+        iConsole->ReadCancel();
+        iTimer.Cancel();
+        }
+    }  
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: NewL
+
+    Description: Constructs new menu dialog
+
+    Parameters: const TDesC& aMessage: in: Message to dialog
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenuDialog* CMenuDialog::NewL( CConsoleMain* aMain,
+                                const TDesC& aLine1, 
+                                const TDesC& aLine2, 
+                                TInt aTimeInSecs )
+    {
+
+    CMenuDialog* self = new ( ELeave ) CMenuDialog( aMain );
+    CleanupStack::PushL( self );
+    self->ConstructL( aLine1, aLine2, aTimeInSecs );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: const TDesC& aMessage: in: Message to dialog
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenuDialog::ConstructL( const TDesC& aLine1, 
+                              const TDesC& aLine2, 
+                              TInt aTimeInSecs )
+    {
+    
+    TSize size = iMain->GetConsole()->ScreenSize();
+    size.iWidth = Min( size.iWidth - KMenuOverhead, 
+                       Max( aLine1.Length(), aLine2.Length() ) );
+    size.iHeight = aLine1.Length()/size.iWidth + aLine2.Length()/size.iWidth + 2;
+    
+    iConsole = Console::NewL( _L("Info"), size );
+    
+    if( aLine1.Length() > 0 )
+        {
+        iConsole->Printf( aLine1 );
+        }
+    if( aLine2.Length() > 0 )
+        {
+        iConsole->Printf( _L("\n") );
+        iConsole->Printf( aLine2 );
+        }
+    
+    if( aTimeInSecs == 0 )
+        {
+        aTimeInSecs = KDefaultTime;
+        }
+    iTimer.CreateLocal();
+
+    CActiveScheduler::Add ( &iCallBack1 );
+    // Get timer
+    iTimer.After( iCallBack1.Activate(), aTimeInSecs*1000*1000 );
+           
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: CMenuDialog
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+#pragma warning( disable : 4355 )       // Incomplete this usage
+CMenuDialog::CMenuDialog( CConsoleMain* aMain ):  
+    iMain( aMain ),      
+    iCallBack1 ( this, GETPTR CMenuDialog::Run1 ), 
+    iCallBack2 ( this, GETPTR CMenuDialog::Run1 )
+    {
+    }
+#pragma warning( default : 4355 )
+
+/*
+-------------------------------------------------------------------------------
+e
+    Class: CMenuDialog
+
+    Method: ~CMenuDialog
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CMenuDialog::~CMenuDialog()
+    {
+ 
+    //if( iCallBack1.IsActive() )
+    //    {
+        iTimer.Cancel();
+        iTimer.Close();
+        iCallBack1.Cancel();
+    //    }
+        
+    if( iCallBack2.IsActive() )
+        {
+        User::RequestComplete( iStatus, KErrCancel );
+		if( iConsole != NULL )
+			{
+			iConsole->ReadCancel();    
+			}
+        iCallBack2.Cancel();
+        }
+        
+    delete iConsole;    
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: Run1
+
+    Description: Callback function. Closes dialog
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenuDialog::Run1()
+    {
+
+    if ( iCallBack2.isCompleted() )
+        {            
+        *iKeyCode = iConsole->KeyCode();
+    
+        User::RequestComplete( iStatus, iCallBack2.Status().Int() );
+        }
+        
+    TInt index = iMain->iDialogs.Find( this );
+    if( index >= 0 )
+        {
+        iMain->iDialogs.Remove( index );
+        }
+    // Timeout, delete this object
+    delete this;
+    return;
+
+    }  
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: WaitForKeypress
+
+    Description: Wait for keypress
+
+    Parameters: None
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CMenuDialog::WaitForKeypress( TKeyCode& aKeyCode, 
+                                   TRequestStatus& aStatus )
+    {
+    
+    aStatus = KRequestPending;
+    iKeyCode = &aKeyCode;
+    iStatus = &aStatus;
+    
+    CActiveScheduler::Add ( &iCallBack2 );
+     
+    // Poll keypresses
+    iConsole->Read( iCallBack2.Activate() );        
+
+    return KErrNone;
+    
+    }  
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ConsoleUI/src/ConsoleUI.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2132 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CConsoleMain 
+* and CModule class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+#include <f32file.h>
+
+#include <stifinternal/UIStoreIf.h>
+
+#include "ConsoleUI.h"
+#include "ConsoleMenus.h"
+
+#include "StifTestInterface.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+_LIT(KNameTxt,"STIF");
+_LIT( KConsoleMain, "CConsoleMain" );
+
+// Commandline params
+_LIT( KTestModule,      "-testmodule" );
+_LIT( KTestModuleIni,   "-testmoduleini" );
+_LIT( KTestCaseFile,    "-testcasefile" );
+_LIT( KTestSet,         "-testset" );
+_LIT( KTestRun,         "-run" );
+_LIT( KTestRunAll,      "all" );
+_LIT( KTestRunSeq,      "sequential" );
+_LIT( KTestRunPar,      "parallel" );
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+LOCAL_C void MainL();
+
+
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: NewL
+
+    Description: Construct the console main class
+
+    Parameters: None
+
+    Return Values: CConsoleMain*                    New object
+
+    Errors/Exceptions: Leaves if memory allocation fails or
+                       ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleMain* CConsoleMain::NewL( )
+    {
+
+    CConsoleMain* self = new ( ELeave ) CConsoleMain();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Construct the console
+    Construct module and case containers
+    Retrieve command line parameters
+    Connect to test engine
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation fails or fileserver or
+                       test engine can't be connected.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::ConstructL( )
+    {
+    
+    CUIStoreIf::ConstructL();
+
+    // Construct the console
+    iConsole = Console::NewL( KNameTxt,
+                             TSize( KConsFullScreen, KConsFullScreen ) );
+
+    RDebug::Print(_L("Creating module list object"));
+    TRAPD(err, iModuleList = CTestModuleList::NewL(NULL));
+    if(err != KErrNone)
+        {
+        RDebug::Print(_L("Could not create module list (%d)"), err);
+        UiError(_L("Could not create module list (err)"));
+        User::Leave(err);
+        }
+    if(!iModuleList)
+        {
+        RDebug::Print(_L("Could not create module list (NULL)"));
+        UiError(_L("Could not create module list (NULL)"));
+        User::Leave(KErrGeneral);
+        }
+
+    // Get command line parameters
+    TFileName iniFile; // TestFramework initialization file
+                    
+    ProcessCommandlineL( iniFile );
+
+    if(iTestModule)
+        {
+        // Add to module list info about module taken from command line
+        RDebug::Print(_L("Adding command line module to list"));
+        TName moduleName;
+        moduleName.Copy(iTestModule->Des());
+        moduleName.LowerCase();
+        err = iModuleList->AddTestModule(moduleName);
+        if(err != KErrNone && err != KErrAlreadyExists)
+            {
+            RDebug::Print(_L("Could not add module to list of modules (%d)"), err);
+            UiError(_L("Could not add module to list of modules (err)"));
+            User::Leave(err);
+            }
+
+        //Get added module
+        CTestModuleInfo* moduleInfo = iModuleList->GetModule(moduleName);
+        if(!moduleInfo)
+            {
+            RDebug::Print(_L("Could not add get module info from list"));
+            UiError(_L("Could not add get module info from list"));
+            User::Leave(KErrGeneral);
+            }
+
+        //Add ini file if given
+        if(iTestModuleIni && iTestModuleIni->Length() > 0)
+            {
+            TFileName filename;
+            filename.Copy(iTestModuleIni->Des());
+            filename.LowerCase();
+            moduleInfo->SetIniFile(filename);
+            }
+
+        //Add config file if given
+        if(iTestCaseFile && iTestCaseFile->Length() > 0)
+            {
+            TFileName filename;
+            filename.Copy(iTestCaseFile->Des());
+            filename.LowerCase();
+            moduleInfo->AddCfgFile(filename);
+            }
+
+        //Now check all config files if there are included modules
+        _LIT(KIncludeModuleStart, "[New_Include_Module]");
+        _LIT(KIncludeModuleEnd, "[End_Include_Module]");
+
+        RDebug::Print(_L("Start parsing included modules"));
+        CTestCaseFileInfo* finfo = iModuleList->GetUncheckedCfgFile();
+        while(finfo)
+            {
+            TFileName fname;
+            finfo->GetCfgFileName(fname);
+
+            RDebug::Print(_L("Checking file: '%S'"), &fname);
+            finfo->SetChecked();
+
+            CStifParser* parser = NULL;
+ 
+            TRAP(err, parser = CStifParser::NewL(_L(""), fname));
+            if(err != KErrNone)
+                {
+                RDebug::Print(_L("Could not create parser to read content of config file (%d)"), err);
+                UiError(_L("Could not create parser to read content of config file (err)"));
+                User::Leave(err);
+                }
+            CleanupStack::PushL(parser);
+
+            ParseTestModulesL(parser, iModuleList, KIncludeModuleStart, KIncludeModuleEnd);
+
+            CleanupStack::PopAndDestroy(parser);
+            finfo = iModuleList->GetUncheckedCfgFile();
+            }
+        RDebug::Print(_L("End parsing included modules"));
+        }
+
+    iConsole->Printf(_L("\nTest Framework starting\n"));
+
+    // CUIStore open
+    User::LeaveIfError( UIStore().Open( iniFile ) );
+    
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: CConsoleMain
+
+    Description: Constructor.
+    Initialize non-zero member variables.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleMain::CConsoleMain( ):iStartCases( EStartCaseNo )
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ~CConsoleMain
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleMain::~CConsoleMain( )
+    {	
+
+    iDialogs.ResetAndDestroy();
+    iDialogs.Close();
+ 
+    // CUIStore close
+    UIStore().Close();
+    
+    delete iReader;
+    iReader = NULL;
+    
+	delete iScroller;
+	iScroller = NULL;
+    
+    delete iConsole;
+    iConsole = NULL;
+
+    delete iMainMenu;
+    iMainMenu = NULL;
+
+    delete iTestModule;
+    iTestModule = 0;
+    
+    delete iTestModuleIni;
+    iTestModuleIni = 0;
+    
+    delete iTestCaseFile;
+    iTestCaseFile = 0;
+    
+    delete iTestSetName;
+    iTestSetName = 0;
+
+    delete iModuleList;
+    iModuleList = 0;
+    
+    iFilters.ResetAndDestroy();
+    iFilters.Close();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ProcessCommandlineL
+
+    Description: Process commandline parameters.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves on error.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::ProcessCommandlineL( TFileName& aIniFile )
+    {
+
+	User me;
+    TInt lineLength = me.CommandLineLength();
+    HBufC* lineBuf = HBufC::NewLC( lineLength );
+    TPtr line( lineBuf->Des() );
+    TBool firstTime = ETrue;
+    TInt offset = 0;
+    TPtrC param;
+    TChar c;
+    
+    me.CommandLine( line );
+    TLex lex( line );
+    
+    while( offset < lineLength )
+        {    
+        // Get first charecter of the parameter
+        lex.SkipSpace();
+        c = lex.Peek();
+        if( c == 0 )
+            {
+            // End of line
+            break;
+            }
+        
+        // Get the whole parameter 
+        param.Set( lex.NextToken() );
+        if( firstTime )
+            {
+            // Filebrowser workaround. It gives the exe name as command line param
+            // verify that it is not the same as the executable name
+            //@spe TFileName exePath = me.FileName();
+			TFileName exePath = RProcess().FileName();
+            if ( param == exePath )
+                {
+                // Discard command line parameters when using filebrowser
+                break;
+                }
+
+            firstTime = EFalse;
+            }
+        // Check if -param option
+        if( c == '-' )
+            {
+            // This is option
+            if( param == KTestModule )
+                {
+                // Get test module name
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test module name not given"));
+                    break;
+                    }
+                if( param.Length() > KMaxName )
+                    {
+                    UiError( _L("Test module name too long"));
+                    break;
+                    }
+                iTestModule = param.AllocL();
+                }
+            else if( param == KTestModuleIni )
+                {
+                // Get test module initialization file
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test module initialization file name not given"));
+                    break;
+                    }
+                if( param.Length() > KMaxFileName )
+                    {
+                    UiError( _L("Test module initialization file name too long"));
+                    break;
+                    }
+                TFileName tmpTestModuleIni( param );
+                TStifUtil::CorrectFilePathL( tmpTestModuleIni );
+                iTestModuleIni = tmpTestModuleIni.AllocL();
+                }
+            else if( param == KTestCaseFile )
+                {
+                // Get test case file name
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test case file name not given"));
+                    break;
+                    }
+                if( param.Length() > KMaxFileName )
+                    {
+                    UiError( _L("Test case file name too long"));
+                    break;
+                    }
+                TFileName tmpTestCaseFile( param );
+                TStifUtil::CorrectFilePathL( tmpTestCaseFile );
+                iTestCaseFile = tmpTestCaseFile.AllocL();
+                }
+            else if( param == KTestSet )
+                {
+                // Get test set name
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test set name not given"));
+                    break;
+                    }
+                if( param.Length() > KMaxFileName )
+                    {
+                    UiError( _L("Test set name too long"));
+                    
+                    break;
+                    }
+                iTestSetName = param.AllocL();
+                }
+            else if( param == KTestRun )
+                {
+                if( iStartCases )
+                    {
+                    UiError( _L("Only one -run option allowed") );
+                    // Do not start anything
+                    iStartCases = EStartCaseNo;
+                    break;
+                    }
+                // Get run type
+                lex.Mark();
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test set name not given"));
+                    break;
+                    }
+                if( ( param == KTestRunAll ) ||
+                    ( param == KTestRunSeq ) )
+                    {
+                    iStartCases = EStartCasesSeq;
+                    }
+                else if( param == KTestRunPar )
+                    {
+                    iStartCases = EStartCasesPar;
+                    }
+                else
+                    {
+                    lex.UnGetToMark();
+                    lex.SkipSpace();
+                    if( lex.Val( iTestCaseNum ) != KErrNone )
+                        { 
+                        UiError( _L("Unknown run type given, valid values are all/sequential/parallel/test case number"));
+                        }
+                    else
+                        {
+                        iStartCases = EStartSingleCase;
+                        }    
+                    break;
+                    }
+                }            
+            }
+        else 
+            {
+            // This is Test Framework ini file
+            aIniFile = param;
+            TStifUtil::CorrectFilePathL( aIniFile );
+            // ini file is last option
+            break;
+            }
+        
+        }
+      
+    CleanupStack::PopAndDestroy( lineBuf );
+
+    }
+    
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: Panic
+
+    Description: Console UI panic function
+
+    Parameters: TInt
+
+    Return Values: 
+
+    Errors/Exceptions: Does not return.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::Panic(TConsoleUIPanic aPanic )
+    {
+        
+    User::Panic (_L("STIF TestFramework Console UI panic"), aPanic );
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: StartL
+
+    Description: Construct menu objects and start the menu handling
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions:
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CConsoleMain::StartL()
+    {
+    
+    // Construct keystroke reader
+    iReader           = CConsoleReader::NewL( this, iConsole );
+
+    // Construct the main menu
+    TInt majorV;
+    TInt minorV;
+    TInt buildV;
+    TBuf<30> relDate;
+    TStifUtil::STIFVersion(majorV, minorV, buildV, relDate);
+    
+    TBuf<128> version;
+    version.Format(_L("STIF v%d.%d.%d - "), majorV, minorV, buildV);
+    version.Append(relDate);
+    version.Append(_L("\n"));
+    iMainMenu = CMainMenu::NewL( this, NULL, _L("Main menu"), version );
+
+    // Add the case menu
+    CMenu* caseMenu   = CMenu::NewL( this, iMainMenu, _L("Case menu") );
+    iMainMenu->AddItemL ( caseMenu );
+
+    // Add the module menu
+    CMenu* moduleMenu = CModuleListView::NewL( this, iMainMenu, _L("Module menu") );
+    iMainMenu->AddItemL ( moduleMenu );
+
+    // Add test set menu
+    CTestSetMenu* testSetMenu = CTestSetMenu::NewL( this, iMainMenu, _L("Test set menu") );
+    iMainMenu->AddItemL ( testSetMenu );
+ 
+    // Construct the case menus
+    CMenu* casestart  = NULL;
+    CMenu* casestartshow  = NULL;
+    
+    // Load filters
+    UIStore().ReadFiltersL(iFilters);
+    
+    // If there are no filters defined, then construct menu without filter's menu
+    if(iFilters.Count() == 0)
+        {
+        casestart = CCaseStartMenu::NewL(this, caseMenu, _L("Start new case"));
+        caseMenu->AddItemL(casestart);
+    CMenu* casestartshow  = NULL;
+        casestartshow = CCaseStartMenu::NewL(this, caseMenu, _L("Start & show output"), ETrue);
+        caseMenu->AddItemL(casestartshow);
+        }
+    else // if there are filters defined, create also filter's menu
+        {
+        CFilterMenu* filtercasestart = NULL;
+        CFilterMenu* filtercasestartshow = NULL;
+        
+        filtercasestart = CFilterMenu::NewL(this, caseMenu, _L("Start new case (filter)"));
+        caseMenu->AddItemL(filtercasestart);
+        casestart = CCaseStartMenu::NewL(this, caseMenu, _L("Start new case"));
+        filtercasestart->SetTestCaseMenu(casestart);
+        
+        filtercasestartshow = CFilterMenu::NewL(this, caseMenu, _L("Start & show output (filter)"));
+        caseMenu->AddItemL(filtercasestartshow);
+        casestartshow = CCaseStartMenu::NewL(this, caseMenu, _L("Start & show output"), ETrue);
+        filtercasestartshow->SetTestCaseMenu(casestartshow);
+        }
+
+	CMultipleCaseMenu* multicasestart =
+	    CMultipleCaseMenu::NewL (this, caseMenu, _L("Run multiple tests") );
+    caseMenu->AddItemL( multicasestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Ongoing cases"), 
+        CUIStoreIf::EStatusRunning );
+    caseMenu->AddItemL( casestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Executed cases"), 
+        CUIStoreIf::EStatusExecuted );
+    caseMenu->AddItemL( casestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Passed cases"), 
+        CUIStoreIf::EStatusPassed );
+    caseMenu->AddItemL( casestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Failed cases"), 
+        CUIStoreIf::EStatusFailed );
+    caseMenu->AddItemL( casestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Aborted/Crashed cases"), 
+        ( CUIStoreIf::EStatusAborted | CUIStoreIf::EStatusCrashed) );
+    caseMenu->AddItemL( casestart );
+    //Add "test set choice" menu
+    CTestSetChoiceMenu* testChoiceMenu = CTestSetChoiceMenu::NewL( this, testSetMenu, _L("Load test set") );
+ 	testSetMenu->AddItemL( testChoiceMenu );
+
+    // Start stuff according to command line parameters
+    if( iTestSetName )
+        { 
+        // Set test set name
+        testSetMenu->SetTestSetFileName( iTestSetName->Des() );
+        
+        // Load test set
+        if( UIStore().LoadTestSet( iTestSetName->Des() ) != KErrNone )
+ 	       {
+           UiError( _L("Test set loading failed"));
+           }
+        else 
+           {
+           // Inform test set menu that set is loaded
+           testSetMenu->SetCreated();
+    
+            // Check if test set should be started
+    	    if( ( iStartCases == EStartCasesPar ) || 
+    	    	( iStartCases == EStartCasesSeq ))         	
+            	{
+            
+	            // Check set starting type
+    	    	CStartedTestSet::TSetType setType = 
+       	        CStartedTestSet::ESetSequential;
+       	        
+                if( iStartCases == EStartCasesPar )
+                    {
+                    setType = 
+                        CStartedTestSet::ESetParallel;
+                    }
+                    
+                // Start test set
+                RRefArray<CTestSetInfo> setInfos;
+                TInt ret = UIStore().TestSets( setInfos );
+                if( (  ret != KErrNone ) ||
+                    ( setInfos.Count() != 1 ) )
+                    {
+                    // Should never ever happen
+                    User::Panic( KConsoleMain, KErrGeneral );
+                    }
+                
+                const CTestSetInfo& set = setInfos[0];
+                setInfos.Reset();
+                setInfos.Close();
+                
+                TInt index;
+                ret = UIStore().StartTestSet( set, index, setType );
+                if( ret != KErrNone )
+                    {
+                    UiError( _L("Test set starting failed") );
+                    }
+                } 
+            }
+        delete iTestSetName;
+        iTestSetName = 0;     
+        }
+    if( iTestModule )
+        {
+        TPtrC module( iTestModule->Des() ); 
+
+        // Add all test modules and config files
+        RDebug::Print(_L("Start creating test modules"));
+        CTestModuleInfo* moduleInfo = NULL;
+        TInt i;
+        TInt modCnt = iModuleList->Count();
+        TInt ret;
+
+        for(i = 0; i < modCnt; i++)
+            {
+            RDebug::Print(_L("Processing module"));
+            // Get module
+            moduleInfo = iModuleList->GetModule(i);
+            if(!moduleInfo)
+                {
+                RDebug::Print(_L("Could not get module info at index %d"), i);
+                continue;
+                }
+
+            // Get module name
+            TName moduleName;
+            moduleInfo->GetModuleName(moduleName);
+            RDebug::Print(_L("module name: '%S'"), &moduleName);
+
+            // Get ini file, if exists
+            TFileName ini;
+            moduleInfo->GetIniFileName(ini);
+            if(ini.Length() == 0)
+                {
+                RDebug::Print(_L("ini file not found"));
+                }
+            else
+                {
+                RDebug::Print(_L("ini file: '%S'"), &ini);
+                }
+
+            // Create test module
+            RDebug::Print(_L("Adding module to UI store"));
+            ret = UIStore().AddTestModule(moduleName, ini);
+            if(ret != KErrNone && ret != KErrAlreadyExists)
+                {
+                RDebug::Print(_L("Test module adding failed (%d)"), ret);
+                UiError(_L("Test module adding failed"));
+                continue;
+                }
+
+            //Add test case files
+            TInt cfgCnt = moduleInfo->CountCfgFiles();
+            TInt j;
+            TFileName cfgFile;
+            for(j = 0; j < cfgCnt; j++)
+                {
+                moduleInfo->GetCfgFileName(j, cfgFile);
+                if(cfgFile.Length() > 0)
+                    {
+                    RDebug::Print(_L("config file: '%S'"), &cfgFile);
+
+                    ret = UIStore().AddTestCaseFile(moduleName, cfgFile);
+                    if(ret != KErrNone)
+                        {
+                        // Log error
+                        RDebug::Print(_L("Test case file adding failed (%d)"), ret);
+                        UiError(_L("Test case file adding failed"));
+                        continue;
+                        }
+                    }
+                else
+                    {
+                    RDebug::Print(_L("Got empty cfg file"));
+                    }
+                }
+            if(cfgCnt == 0)
+                {
+                RDebug::Print(_L("cfg file not found"));
+                }
+
+            RDebug::Print(_L("Module '%S' processed correctly"), &moduleName);
+            }
+
+        RDebug::Print(_L("End creating test modules"));
+
+        if( ( iStartCases == EStartCasesPar ) ||
+            ( iStartCases == EStartCasesSeq ) )
+            {
+            // Start running
+            CMultipleBaseMenu::TRunType runType = 
+                CMultipleBaseMenu::ERunSequential;
+            if( iStartCases == EStartCasesPar )
+                {
+                runType = CMultipleBaseMenu::ERunParallel;
+                }
+            TRAPD( err,
+                //multicasestart->StartRunningL( runType, module, file );
+                multicasestart->StartRunningL(runType, KNullDesC, KNullDesC);
+                );
+            if( err != KErrNone )
+                {
+                UiError( _L("Stating test cases failed") );
+                }
+            }
+        else if( iStartCases == EStartSingleCase )
+            {
+            // Get test case
+            RRefArray<CTestInfo> testCases;
+            //ret = UIStore().TestCases( testCases, module, file );
+            ret = UIStore().TestCases(testCases, KNullDesC, KNullDesC);
+            if( ret == KErrNone )
+                {
+                if( ( iTestCaseNum < 0 ) ||
+                    ( iTestCaseNum >= testCases.Count() ) )
+                    {
+                    ret = KErrNotFound;
+                    }
+                else
+                    {         
+                    TInt index;           
+                    // Start single test case
+                    ret = UIStore().StartTestCase( testCases[iTestCaseNum], index );
+                    }                                       
+                }
+            testCases.Reset();       
+            testCases.Close();
+            if( ret != KErrNone )
+                {
+                UiError( _L("Starting test case failed"));        
+                }
+            }
+
+        delete iTestCaseFile;
+        iTestCaseFile = 0;
+        delete iTestModuleIni;
+        iTestModuleIni = 0;
+        delete iTestModule;
+        iTestModule = 0;
+        }
+        
+    iStartCases = EStartCaseNo;
+    
+    // Load testcase if some stored 
+    UIStore().LoadSavedTestCases();
+           
+	iScroller = CScrollerTimer::NewL ( this );
+	iScroller->StartL();	
+
+    // Print the main menu
+    iCurrentMenu = iMainMenu;
+    iCurrentMenu->PrintMenuL( CMenu::EMenuPrint );
+
+    // Start to process keyboard events
+    iReader->StartL();
+    
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: KeyPressed
+
+    Description: Process keyboard events. Print new menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if SelectL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::KeyPressed()
+    {
+
+    TBool cont = ETrue;
+
+    // Read the key
+    TKeyCode key = iConsole->KeyCode();
+    CMenu* tmp = iCurrentMenu;
+
+    // Let the menu handle the key press
+    TRAPD( err, 
+        iCurrentMenu = iCurrentMenu->SelectL( key, cont );
+        );
+    if( err != KErrNone )
+        {
+        User::InfoPrint( 
+            _L("Processing keystroke failed") );  
+        }
+            
+    if ( iCurrentMenu == NULL )
+        {
+        iCurrentMenu = tmp;
+        }
+
+   // If "not-exit" key pressed, continue
+    if ( cont )
+        {
+
+        // Either only update old menu or new menu.
+        if ( tmp == iCurrentMenu )
+            {
+            TRAP( err, iCurrentMenu->PrintMenuL( CMenu::EMenuRefresh ); );
+            }
+        else
+            {
+            TRAP( err, iCurrentMenu->PrintMenuL( CMenu::EMenuPrint ); )
+            }
+        
+        if( err != KErrNone )
+            {
+            if ( err == KErrNoMemory )
+            	{            	
+            	ExitWithNoMemoryErrorMessage();                
+            	}
+            else
+            	{
+	            User::InfoPrint( 
+	                _L("Printing menu failed") );
+            	}
+            }
+
+        // Enable keystrokes
+        iReader->StartL();
+
+        }
+    else
+        {
+        // "Exit", stop scheduler and exit
+        CActiveScheduler::Stop();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ExitWithNoMemoryErrorMessage
+
+    Description: Displays no memory error message and closes ConsoleUI
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::ExitWithNoMemoryErrorMessage()
+	{
+    // "Exit", stop scheduler and exit
+    CActiveScheduler::Stop();
+
+    _LIT( KErrorTitle, "Error:\n" );
+    _LIT( KErrorMessage, "Test cases execution have been stopped. ConsoleUI does not have enough memory to store information about executed test cases.  Results of executed test cases can be found in TestReport file. ConsoleUI will be closed now." );
+    _LIT( KErrorPressAnyKey, "\n\nPress any key" );
+    
+    TSize size = GetConsole()->ScreenSize();
+    size.iWidth = Min( size.iWidth - KMenuOverhead, 
+                       KErrorMessage().Length() );
+    size.iHeight = ( KErrorTitle().Length() + KErrorMessage().Length() + 
+    				 KErrorPressAnyKey().Length() ) / size.iWidth + 3;
+    
+    CConsoleBase* console = NULL;
+    TRAPD( err, console = Console::NewL( _L("Error note"), size ) );
+    if ( err != KErrNone )
+    	{
+    	// We can't create console, exit without displaying error message
+    	return;
+    	}
+    
+    console->Printf( KErrorTitle );    
+    console->Printf( KErrorMessage ); 
+    console->Printf( KErrorPressAnyKey );
+        
+    console->Getch();
+    
+    delete console;    
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: UiError
+
+    Description: Function is called when UI hit an error.
+    
+    Parameters: const TDesC& aInfo: in: information
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+void CConsoleMain::UiError( const TDesC& aInfo )
+    {
+    
+    // Error note deletes itself when it completes
+    CMenuNotifier::NewL( aInfo, this );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: Update
+
+    Description: Receives output update notification from CUIStore.
+    
+    Parameters: CStartedTestCase* aTestCase: in: Test case information
+                TInt aFlags: in: Update reason flags
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::Update( CStartedTestCase* aTestCase, TInt aFlags )
+    {
+    
+   	TInt err( KErrNone );
+    
+    // First check if some menu should be signaled 
+    if( ( aFlags & CUIStoreIf::EStatusExecuted ) &&
+        ( aTestCase->iBackPtr ) )
+        {
+        CMenu* menu = ( CMenu* )aTestCase->iBackPtr;
+        TRAP( err, 
+            menu->SignalL( aTestCase ); 
+            );            
+        }
+
+    // Update console if needed
+    if( iCurrentMenu && ( iCurrentMenu->Type() & aFlags ) )
+        {
+        if( aFlags & CUIStoreIf::EPrintUpdate )
+            {
+            CCaseExecutionView* view = 
+                ( CCaseExecutionView* )iCurrentMenu;
+            if( view->TestCase() == aTestCase )
+                {
+                TRAP( err, iCurrentMenu->PrintMenuL( CMenu::EMenuRefresh ) );
+                }
+            }
+        else
+            {
+            TRAP( err, iCurrentMenu->PrintMenuL( CMenu::EMenuRefresh ); )
+            }
+        }
+    
+    	if ( err != KErrNone )
+    		{
+    		if ( err == KErrNoMemory )
+    			{
+    			ExitWithNoMemoryErrorMessage();
+    			}
+    		}
+    
+    }
+                                                              
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: Error
+
+    Description: Function is called when test framework prints error.
+    
+    Parameters: TErrorNotification& aError: in: Error description
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+void CConsoleMain::Error( TErrorNotification& aError )
+    {
+    
+    // Error note deletes itself when it completes
+    CMenuNotifier::NewL( aError.iText, this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: PopupMsg
+
+    Description: Function is called when testframework 
+        wants to print a popup window.
+    
+    Parameters: TDesC& aMsg: in: message
+                
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+TInt CConsoleMain::PopupMsg( const TDesC& aLine1, 
+                             const TDesC& aLine2, 
+                             TInt aTimeInSecs )
+    {
+    
+    TInt ret = KErrNone;
+    
+    CMenuDialog* dialog = NULL;
+
+    TRAP( ret, dialog = CMenuDialog::NewL( this, aLine1, aLine2, aTimeInSecs ); );
+
+    if( ret == KErrNone )
+        {
+        iDialogs.Append( dialog ); 
+        return (TInt)dialog;
+        }
+
+    return ret;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: PopupMsg
+
+    Description: Function is called when testframework 
+        wants to print a popup window.
+    
+    Parameters: TDesC& aMsg: in: message
+                
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+TInt CConsoleMain::PopupMsg( const TDesC& aLine1, 
+                             const TDesC& aLine2, 
+                             TInt aTimeInSecs,
+                             TKeyCode& aKey,
+                             TRequestStatus& aStatus )
+    {
+    
+    TInt ret = PopupMsg( aLine1, aLine2, aTimeInSecs );
+    if( ret < 0 )
+        {
+        return ret;
+        }    
+        
+    CMenuDialog* dialog = (CMenuDialog*) ret; 
+    ret = dialog->WaitForKeypress( aKey, aStatus );
+
+    return (TInt) dialog;
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: Close
+
+    Description: Close instance.
+    
+    Parameters: TInt aHandle: in: handle to open instance.                
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::Close( TInt aHandle )
+    {
+    
+    if( aHandle < 0 )
+        {
+        return;
+        }
+    CMenuDialog* dialog = (CMenuDialog*) aHandle;
+    TInt index = iDialogs.Find( dialog );
+    if( index >= 0 )
+        {
+        delete dialog;
+        iDialogs.Remove( index );
+        }
+        
+    }
+           
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: GetConsole
+
+    Description: Returns the console
+
+    Parameters: None
+
+    Return Values: CConsoleBase*                    Console
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleBase* CConsoleMain::GetConsole()
+    {
+
+    return iConsole;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: TimerUpdate
+
+    Description: Updates current menu from timer
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::TimerUpdate()
+    {
+
+	iCurrentMenu->TimerUpdate();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ParseTestModulesL
+
+    Description: Parse and search for module info and fill list of modules.
+
+    Parameters: CStifParser*     aParser:       in: CStifParser object
+                CTestModuleList* aModuleList:   in: list of modules
+                TPtrC&           aSectionStart: in: descriptor with start of section string
+                TPTrC&           aSectionEnd:   in: descriptor with end of section string
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::ParseTestModulesL(CStifParser* aParser, CTestModuleList* aModuleList, const TDesC& aSectionStart, const TDesC& aSectionEnd)
+    {
+    //First let's find all modules given in Stif's ini file and store that info in CTestModuleList object
+    CStifSectionParser* sectionParser = NULL;
+    CStifItemParser* item = NULL;
+
+    sectionParser = aParser->SectionL(aSectionStart, aSectionEnd);
+
+    while(sectionParser)
+        {
+        RDebug::Print(_L("Found '%S' and '%S' sections"), &aSectionStart, &aSectionEnd);
+        CleanupStack::PushL(sectionParser);
+        RDebug::Print(_L("Starting to read module information"));
+
+        // Get name of module
+        _LIT(KModuleName, "ModuleName=");
+        item = sectionParser->GetItemLineL(KModuleName);
+        CleanupStack::PushL(item);
+        if(!item)
+            {
+            CleanupStack::PopAndDestroy(item);
+            UiError(_L("Line not found from module section"));
+            User::Leave(KErrGeneral);
+            }
+        else
+            {
+            RDebug::Print(_L("'%S' found"), &KModuleName);
+            }
+
+        TPtrC name;
+        TName moduleName;
+        TInt ret(KErrNone);
+        ret = item->GetString(KModuleName, name);
+        if(ret != KErrNone)
+            {
+            CleanupStack::PopAndDestroy(item);
+            RDebug::Print(_L("Module name parsing left with error (%d)"), ret);
+            UiError(_L("Module name parsing left with error (err)"));
+            User::Leave(ret);
+            }
+        else
+            {
+            RDebug::Print(_L("Module '%S' found from ini-file"), &name);
+            moduleName.Copy(name);
+            moduleName.LowerCase();
+            ret = aModuleList->AddTestModule(moduleName);
+            if(ret != KErrNone && ret != KErrAlreadyExists)
+                {
+                RDebug::Print(_L("Could not add module to list of modules (%d)"), ret);
+                UiError(_L("Could not add module to list of modules (err)"));
+                User::Leave(ret);
+                }
+            }
+        CleanupStack::PopAndDestroy(item);
+
+        //Get pointer to added module
+        CTestModuleInfo* moduleInfo = aModuleList->GetModule(moduleName);
+        if(!moduleInfo)
+            {
+                RDebug::Print(_L("Could not add get module info from list"));
+                UiError(_L("Could not add get module info from list"));
+                User::Leave(KErrNotFound);
+            }
+
+        // Get ini file, if it exists
+        RDebug::Print(_L("Start parsing ini file"));
+        _LIT(KIniFile, "IniFile=");
+        item = sectionParser->GetItemLineL(KIniFile);
+        if(item)
+            {
+            RDebug::Print(_L("'%S' found"), &KIniFile);
+            CleanupStack::PushL(item);
+            TPtrC iniFile;
+            ret = item->GetString(KIniFile, iniFile);
+            if(ret == KErrNone)
+                {
+                RDebug::Print(_L("Initialization file '%S' found, file can be empty"), &iniFile);
+                TFileName filename;
+                filename.Copy(iniFile);
+				TStifUtil::CorrectFilePathL(filename);
+                filename.LowerCase();
+                moduleInfo->SetIniFile(filename);
+                }
+            else
+                {
+                RDebug::Print(_L("Initialization file not found"));
+                }
+            CleanupStack::PopAndDestroy(item);
+            }
+        else
+            {
+            RDebug::Print(_L("'%S' not found"), &KIniFile);
+            }
+
+        // Get config (testcase) file
+        RDebug::Print(_L("Start parsing cfg files"));
+        TPtrC cfgTag;
+        for(TInt i = 0; i < 2; i++)
+            {
+            //Set tag for config files
+            if(i == 0)
+                {
+                cfgTag.Set(_L("ConfigFile="));
+                }
+                else
+                {
+                cfgTag.Set(_L("TestCaseFile="));
+                }
+            //Read data
+            item = sectionParser->GetItemLineL(cfgTag);
+            while(item)
+                {
+                CleanupStack::PushL(item);
+                RDebug::Print(_L("Item '%S' found"), &cfgTag);
+                TPtrC cfgFile;
+                ret = item->GetString(cfgTag, cfgFile);
+                if(ret == KErrNone)
+                    {
+                    RDebug::Print(_L("Configuration file '%S' found"), &cfgFile);
+                    TFileName ifile;
+                    ifile.Copy(cfgFile);
+					TStifUtil::CorrectFilePathL(ifile);
+                    ifile.LowerCase();
+                    moduleInfo->AddCfgFile(ifile);
+                    }
+                else
+                    {
+                    RDebug::Print(_L("Configuration file not found"));
+                    }
+                CleanupStack::PopAndDestroy(item);
+                item = sectionParser->GetNextItemLineL(cfgTag);
+                }
+            }
+
+        RDebug::Print(_L("Module '%S' information read correctly"), &moduleName);
+
+        // Get next section
+        CleanupStack::PopAndDestroy(sectionParser);
+        sectionParser = aParser->NextSectionL(aSectionStart, aSectionEnd);
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: GetMainMenu
+
+    Description: Return main menu of console.
+
+    Parameters: None
+
+    Return Values: CMainMenu*  pointer to main menu
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CMainMenu* CConsoleMain::GetMainMenu()
+    {
+    return dynamic_cast<CMainMenu*>(iMainMenu);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: GetFilterArray
+
+    Description: Get filter array for reading purposes
+
+    Parameters: None
+
+    Return Values: const RPointerArray<TDesC>&  array with filters
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+const RPointerArray<TDesC>& CConsoleMain::GetFilterArray(void) const
+    {
+    return iFilters;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: SetFilterIndex
+
+    Description: Set info about which index filter is used
+
+    Parameters: TInt aFilterIndex: filter index selected by user
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::SetFilterIndex(TInt aFilterIndex)
+    {
+    iChosenFilterIndex = aFilterIndex;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: GetFilterIndex
+
+    Description: Get info about which index filter is used
+
+    Parameters: None
+
+    Return Values: TInt: filter index selected by user
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CConsoleMain::GetFilterIndex(void)
+    {
+    return iChosenFilterIndex;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: NewL
+
+    Description: Construct a new CScrollerTimer object
+
+    Parameters: CConsoleMain*             :in:      Pointer to main console               
+
+    Return Values: CScrollerTimer*                         New CScrollerTimer object
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CScrollerTimer* CScrollerTimer::NewL( CConsoleMain* aMain )
+    {
+
+    CScrollerTimer* self = new ( ELeave ) CScrollerTimer();
+    CleanupStack::PushL( self );
+    self->ConstructL( aMain );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: ConstructL
+
+    Description: Second level constructor
+
+    Parameters: CConsoleMain*             :in:      Pointer to main console
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CScrollerTimer::ConstructL( CConsoleMain* aMain )
+    {
+
+    // Store module information
+    iMain = aMain;
+	iTimer.CreateLocal();
+
+	CActiveScheduler::Add ( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: CScrollerTimer
+
+    Description: Constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CScrollerTimer::CScrollerTimer() : CActive (CActive::EPriorityStandard)
+    {
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: ~CScrollerTimer
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CScrollerTimer::~CScrollerTimer( )
+    {
+
+	Cancel();
+	iTimer.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: StartL
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CScrollerTimer::StartL( )
+    {
+
+	SetActive();
+	iTimer.After ( iStatus, KScrollPeriod );	
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: RunL
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CScrollerTimer::RunL( )
+    {
+
+	iMain->TimerUpdate();
+
+	// Restart request
+	SetActive();
+	iTimer.After ( iStatus, KScrollPeriod );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: DoCancel
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CScrollerTimer::DoCancel( )
+    {
+
+	iTimer.Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: RunError
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CScrollerTimer::RunError( TInt aError)
+    {
+    if ( aError == KErrNoMemory )
+    	{
+    	iMain->ExitWithNoMemoryErrorMessage();
+    	}
+  
+	return aError;
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CConsoleReader class.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: NewL
+
+    Description: Construct the console main class
+
+    Parameters: CConsoleMain* aMain: in: Pointer to main console
+                CConsoleBase* aConsole: in: Console pointer
+
+    Return Values: CConsoleReader*                    New object
+
+    Errors/Exceptions: Leaves if memory allocation fails or
+                       ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleReader* CConsoleReader::NewL( CConsoleMain* aMain, 
+                                      CConsoleBase* aConsole )
+    {
+
+    CConsoleReader* self = 
+        new ( ELeave ) CConsoleReader( aMain, aConsole );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: 
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleReader::ConstructL( )
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: CConsoleReader
+
+    Description: Constructor.
+
+    Parameters: CConsoleMain* aMain: in: Pointer to main console
+                CConsoleBase* aConsole: in: Console pointer
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleReader::CConsoleReader( CConsoleMain* aMain, 
+                                CConsoleBase* aConsole ): 
+    CActive( EPriorityStandard )
+    {
+    
+    iMain = aMain;
+    iConsole = aConsole;
+    
+    CActiveScheduler::Add( this );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: ~CConsoleReader
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleReader::~CConsoleReader( )
+    {	
+    
+    Cancel();    
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: StartL
+
+    Description: Construct menu objects and start the menu handling
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions:
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleReader::StartL( )
+    {
+
+    // Start to process keyboard events
+    SetActive();
+    iConsole->Read(iStatus);
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: RunError
+
+    Description: None
+
+    Parameters: TInt aError
+
+    Return Values: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/    
+TInt CConsoleReader::RunError(TInt aError)
+    {
+    return aError;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: RunL
+
+    Description: Process keyboard events. Print new menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if SelectL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleReader::RunL()
+    {
+
+    iMain->KeyPressed();
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: DoCancel
+
+    Description: Cancel request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleReader::DoCancel()
+    {
+    
+    iConsole->ReadCancel();
+    
+    }
+
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: MainL
+
+    Description: The main function that can leave.
+    Create the CMainConsole object and create, initialise and 
+    start active scheduler.
+
+    When active scheduler is stopped, clean up memory and exit.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation or CConsoleMain construction
+                       leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+LOCAL_C void MainL()
+    {
+
+    // Construct and install active scheduler
+    CActiveScheduler* scheduler=new ( ELeave ) CActiveScheduler;
+    CleanupStack::PushL( scheduler );
+    CActiveScheduler::Install( scheduler );
+
+    // Construct the console
+    CConsoleMain* mainConsole = CConsoleMain::NewL();
+    CleanupStack::PushL( mainConsole );
+
+    // Start the console
+    mainConsole->StartL();
+
+    // Start handling requests
+    CActiveScheduler::Start();
+    // Execution continues from here after CActiveScheduler::Stop()
+
+    // Clean-up
+    CleanupStack::PopAndDestroy( mainConsole );
+    CleanupStack::PopAndDestroy( scheduler );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: E32Main
+
+    Description: The main function. Execution starts from here.
+    Create clean-up stack and trap the MainL function which does the
+    real work.
+
+    Parameters: None
+
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+GLDEF_C TInt E32Main()
+    {
+
+    __UHEAP_MARK;
+
+    // Get clean-up stack
+    CTrapCleanup* cleanup=CTrapCleanup::New();
+
+    // Call the main function
+    TRAPD( error, MainL() );
+
+    // Clean-up
+    delete cleanup; 
+    cleanup = NULL;
+
+    __UHEAP_MARKEND;
+
+    return error;
+
+    }
+
+#if defined(__WINS__)
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: WinsMain
+
+    Description: The WinsMain function.
+
+    Parameters: None
+
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt WinsMain()
+	{
+	E32Main();
+	return KErrNone;
+	}
+
+#endif // __WINS__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/ConsoleUI/src/Consolemenus.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,5700 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CMenu-derived classes.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+
+#include <f32file.h>
+#include <stifinternal/UIEngineContainer.h>
+
+#include "ConsoleUI.h"
+#include "ConsoleMenus.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+LOCAL_C void LimitedAppend( TDes& aOriginal, const TDesC& aAppend);
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+LOCAL_C void LimitedAppend( TDes& aOriginal, const TDesC& aAppend)
+    {
+
+    TInt spaceLeft = aOriginal.MaxLength() - aOriginal.Length();
+    
+    if (spaceLeft > aAppend.Length())
+        {
+        aOriginal.Append ( aAppend );
+        }
+    else
+        {       
+        aOriginal.Append ( aAppend.Left ( spaceLeft ) );
+        }
+
+    }
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMenu::NewL( CConsoleMain* aConsole,
+                    CMenu* aParent,
+                    const TDesC& aName
+                  )
+    {
+
+    CMenu* self = new ( ELeave ) CMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+				const TDesC& aHeader	  :in:		Text containing STIF version info
+				
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::ConstructL( CConsoleMain* aConsole,
+                        CMenu* aParent,
+                        const TDesC& aName,
+                        const TDesC& aHeader
+                      )
+    {
+ 
+    // Store the parameters
+    iMain = aConsole;
+    iConsole = aConsole->GetConsole();
+    iParent = aParent;
+    iName = aName;
+    iHeader = aHeader;
+
+    // Get display size
+    const TInt KOverHead = 5;
+    iSize = iConsole->ScreenSize();
+    iScreenSize = iSize.iHeight - KOverHead;   // Size available for menus
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: CMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu::CMenu()
+    {
+    iDirection = 1;
+    iPrevPos  = -1;     // Invalid starting value
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: ~CMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CMenu::~CMenu()
+    {
+    
+    iItems.ResetAndDestroy();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: TimerUpdate
+
+    Description: TimerUpdate
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenu::TimerUpdate()
+    {    
+    iScrolledLine.Zero();
+    RRefArray<TDesC> texts;
+    User::LeaveIfError( ItemTexts( texts ) );
+    
+    TInt count = texts.Count();
+    // If list is empty, do not scroll.
+    if ( count < 1 )
+        {
+        texts.Close();
+        return;
+        }
+    
+    // Recalculate visible part of menu
+    Recalculate( count );
+
+    // If menu selection is updated, then restart scrolling
+    if (iPrevPos != iFirst + iPosOnScreen)
+        {
+        iPrevPos = iFirst + iPosOnScreen;
+        iStart = 0;
+        iDirection = 1;
+        }
+
+
+    // If menu item have not been changed after last timer, then
+    // start scrolling  
+    const TDesC& name = texts[ iFirst + iPosOnScreen ];
+    if ( name.Length() > ( iSize.iWidth - KMenuOverhead ) )
+        {
+
+        TInt y = iConsole->WhereY();
+        TInt x = iConsole->WhereX();
+        TBuf<80> iTmp;              
+
+        iStart = iStart + iDirection;
+
+        // "Right end"
+        if ( iStart + iSize.iWidth > name.Length() + KMenuOverhead + 2)
+            {
+            iStart--;
+            iDirection = -1;
+            }
+        
+        // "Left end"
+        if ( iStart == -1 )
+            {
+            iStart++;
+            iDirection = 1;
+            }
+        
+        if( iStart > name.Length() )
+            {
+            iStart = 0;
+            }
+
+        iTmp=_L(" *");
+        LimitedAppend( iTmp, name.Mid ( iStart ) );
+            
+        iConsole->SetPos( 0, iPosOnScreen+1);       
+        Print(iTmp);
+        iScrolledLine.Copy(texts[iFirst + iPosOnScreen].Left(iScrolledLine.MaxLength())); 
+
+        iConsole->SetPos(x,y);
+        }
+    texts.Close();
+
+    }
+    
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number 
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenu::AppendBefore( TInt aLineNum, TDes& aLine )
+    {
+    
+    if( ( aLine.MaxLength() - aLine.Length() ) < 2 )
+        {
+        return;
+        }        
+    
+    // If printing active line, print the marker
+    if ( aLineNum == iPosOnScreen + iFirst )
+        {
+        aLine.Append( _L(" *") );
+        }
+    else
+        {
+        aLine.Append( _L("  ") );
+        }
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenu::PrintMenuL( TUpdateType aType )
+    {
+
+    iUpdateType = aType;
+    
+    TBuf<KMaxLineLength> line;
+    
+    //if we are moving between items located on the same page clearing screen is not needed
+    if(!iPreventClearScreen)
+        {
+        // Clear display
+        iConsole->ClearScreen();
+        
+        //Print STIF version information, only when defined (i.e. in main menu)
+        if(iHeader != _L(""))
+           Print(iHeader);
+        
+        // Print menu title
+        Print( Name() );
+        
+        RRefArray<TDesC> texts;
+        User::LeaveIfError( ItemTexts( texts ) );
+        
+        // Recalculate visible part of menu
+        Recalculate( texts.Count() );
+        
+        //needed for setting cursor at correct line 
+        iMenuItemsListStartIndex = iConsole->CursorPos().iY;
+        
+        // Print items
+        for ( TInt i = iFirst; i <= iLast; i++ )
+            {
+            line.Zero();
+            
+            // Append text before line
+            AppendBefore( i, line );
+        
+            // Get the menu line
+            LimitedAppend ( line, texts[i] );
+        
+            // Print the line
+            Print(line);
+            }
+        texts.Close();
+        
+        //needed for setting cursor at correct line 
+        iMenuItemsListEndIndex = iConsole->CursorPos().iY;
+        }
+    else
+        {
+        //removing "*" sign from the previous cursor position
+        iConsole->SetPos(0, iPrevPosOnScreen + iMenuItemsListStartIndex);
+        //line.Append( _L("  ") );
+        AppendBefore(iPrevPosOnScreen + iFirst, line);
+        LimitedAppend(line, iScrolledLine);
+        //iConsole->Printf(line);
+        Print(line);
+        iConsole->SetPos(0, iPosOnScreen + iMenuItemsListStartIndex);
+        line.Zero();
+        iScrolledLine.Zero();
+        
+        //writing "*" sign before the currently selected line
+        line.Append( _L(" *") );
+        iConsole->Printf(line);
+        iConsole->SetPos(0, iMenuItemsListEndIndex);
+        iPreventClearScreen = EFalse;
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: SelectL
+
+    Description: Common method to count all variables needed for printing
+                 page of the screen.
+
+    Parameters: TInt aDelta       :in:      where to move current position
+                 Value > 0 stands for moving down the menu.
+                 Value < 0 stands for moving up the menu.
+
+    Return Values: 
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::MovePosition(TInt aDelta)
+    {
+    if(iItemCount > 0 && aDelta != 0)
+        {
+        // Valid screen size
+        TInt screenSize = iScreenSize + 1;
+        TInt realPosition = iFirst + iPosOnScreen;
+
+        // Number of all pages and items in the last page
+        TInt rest = iItemCount % screenSize;
+        TInt pages = (iItemCount / screenSize) + ((rest == 0) ? (0) : (1));
+
+        // Current page
+        TInt currPage = realPosition / screenSize;
+        
+        // New page
+        TInt newRealPosition = realPosition + aDelta;
+        while(newRealPosition < 0)
+            newRealPosition += iItemCount;
+        newRealPosition %= iItemCount;
+        TInt newPage = newRealPosition / screenSize;
+        
+        // Change position
+        iFirst = newPage * screenSize;
+        iLast = iFirst + screenSize - 1;
+        if(iLast >= iItemCount)
+            iLast = iItemCount - 1;
+        iPrevPosOnScreen = iPosOnScreen;
+        iPosOnScreen = newRealPosition % screenSize;
+        if(newPage == pages - 1 && iPosOnScreen >= rest)
+            iPosOnScreen = rest - 1;
+            
+        // Prevent refreshing
+        iPreventClearScreen = (currPage == newPage);
+        }
+    else
+        iPreventClearScreen = ETrue;    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Either updates position in
+    menu or returns new menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    switch ( (TInt) aSelection )
+    {
+
+    // Exit
+    case EKeyEscape:
+        aContinue = EFalse;
+        return this;
+
+    // SelectL item
+    case EKeyEnter:
+    case EKeyRightArrow:
+        return iItems[iPosOnScreen];
+
+    // Going back
+    case EKeyLeftArrow:
+        return iParent;
+
+    // Go down
+    case EKeyDownArrow:
+        MovePosition(1);
+        break;
+        
+    // Go Up
+    case EKeyUpArrow:
+        MovePosition(-1);
+        break;
+
+    // Additional keys
+    case EKeyHome:
+    case '3':
+        MovePosition(-iFirst - iPosOnScreen);
+        break;
+
+    case EKeyEnd:
+    case '9':
+        MovePosition(iItemCount - 1 - iFirst - iPosOnScreen);
+        break;
+
+    case EKeyPageUp:
+    case '1':
+        MovePosition((iFirst + iPosOnScreen - iScreenSize - 1 >= 0) ? (-iScreenSize - 1) : (-iFirst - iPosOnScreen));
+        break;
+
+    case EKeyPageDown:
+    case '7':
+        MovePosition((iFirst + iPosOnScreen + iScreenSize + 1 < iItemCount) ? (iScreenSize + 1) : (iItemCount - 1 - iFirst - iPosOnScreen));
+        break;
+    default:  // Bypass the keypress
+        break;
+    }
+
+    // Continue normally and keep in the same menu
+    aContinue = ETrue;
+    return this;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    TInt count = iItems.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aArray.Append( iItems[i]->Name() ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    return KErrNone;
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: SetParent
+
+    Description: Sets menu parent menu.
+
+    Parameters: CMenu* aMenu              :in:      Menu parent
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::SetParent ( CMenu* aMenu )
+    {
+
+    iParent = aMenu;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: Print
+
+    Description: Prints one line text and changes to next line. If line is
+    too long, overhead is not printed..
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenu::Print( const TDesC& aPrint )
+    {
+    
+    iConsole->Write ( aPrint.Left( iSize.iWidth - KMenuOverhead ) );
+    iConsole->Write(_L("\n"));
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: PrintMulti
+
+    Description: Prints text. If line is too long, it will be continued to
+    following lines.
+
+    Parameters: const TDesC& aPrint       :in:      Text to print
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::PrintMulti( const TDesC& aPrint )
+    {
+
+    // Get current line
+    const TInt KMenuOverHead = 2;
+    TInt y = iConsole->WhereY();
+
+    const TInt KLineLen =iSize.iWidth -4;
+    TBuf<KMaxLineLength+1> oneLine;
+
+    // Loop through the line
+    for (TInt i = 0; i < aPrint.Length(); i++)
+        {
+        oneLine.Append( aPrint[i] );
+
+        // Print one line
+        if (oneLine.Length() == KLineLen )
+            {
+            oneLine.Append (_L("\n"));
+            iConsole->Printf(oneLine);
+            oneLine=_L("");
+            y++;
+            }
+    
+        // Prevent display scrolling
+        if ( y == iScreenSize + KMenuOverHead )
+            {
+            oneLine=_L("");
+            break;
+            }
+        }
+
+    // Print last part if required
+    if ( oneLine.Length() != 0 )
+        {
+        oneLine.Append (_L("\n"));
+        iConsole->Printf(oneLine);
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: AddItem
+
+    Description: Add new item to menu
+
+    Parameters: CMenu* aMenu              :in:      Menu to be added
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if can't add item to menu
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::AddItemL( CMenu* aMenu )
+    {
+
+    User::LeaveIfError ( iItems.Append (aMenu) );
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: Name
+
+    Description: Returns menu name
+
+    Parameters: None
+
+    Return Values: const TDesC&                     Menu name
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CMenu::Name( ) const
+    {
+
+    return iName;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: MapKeyCode
+
+    Description: Maps numeric keycodes to proper TKeyCode values
+
+    Parameters: TKeyCode 
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+void CMenu::MapKeyCode(TKeyCode &aSelection)
+    {
+    
+    TInt asciiCode = (TInt) aSelection;
+    
+    // Handling numeric keys 2,4,6 and 8
+    
+    if(asciiCode == KMyKeyUpAsciiCode)
+        {
+        aSelection = EKeyUpArrow;
+        }
+        
+    if(asciiCode == KMyKeyLeftAsciiCode)
+        {
+        aSelection = EKeyLeftArrow;
+        }
+
+    if(asciiCode == KMyKeyRightAsciiCode)
+        {
+        aSelection = EKeyEnter;
+        }
+
+    if(asciiCode == KMyKeyDownAsciiCode)
+        {
+        aSelection = EKeyDownArrow;
+        }
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: Recalculate
+
+    Description: Recalculates visible menu elements
+
+    Parameters: TInt aItemCount    :in:      Menu items count
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::Recalculate( TInt aItemCount )
+	{    
+    TInt oldItemCount = iItemCount;
+     
+    iItemCount = aItemCount;
+ 
+    // If first time in menu, update start and end positions
+    if ( ( iFirst == 0 ) && ( iLast == 0 ) || (iItemCount == 0)) //if there are no items, update start and end positions too
+    	{
+    	if ( iItemCount - 1 > iScreenSize  )
+    		{
+    		iLast = iScreenSize;
+    		}
+    	else
+    		{
+    		iLast = iItemCount - 1;
+    		}
+    	iPosOnScreen = 0;
+    	}
+    // New menu entry added, update last visible element if needed
+    else if ( oldItemCount < iItemCount )
+    	{
+    	if ( iFirst + iScreenSize < iItemCount )
+    		{
+    		iLast = iFirst + iScreenSize;
+    		}
+    	else
+    		{
+    		iLast = iItemCount - 1;
+    		}
+    	}
+    // Menu entry removed, update last visible element if needed
+    else if ( oldItemCount > iItemCount )
+    	{
+    	if ( iFirst + iScreenSize < iItemCount )
+    		{
+    		iLast = iFirst + iScreenSize;
+    		}
+    	else if ( iFirst > iItemCount - 1 )
+    		{
+    		iFirst = iItemCount - 1 - iScreenSize;
+    		if ( iFirst < 0 )
+    			{
+    			iFirst = 0;
+    			}
+    		iLast = iItemCount - 1;
+    		iPosOnScreen = iFirst - iLast;
+    		}
+    	else
+    		{
+    		iLast = iItemCount - 1;
+    		}
+    	
+    	if ( iFirst + iPosOnScreen > iLast )
+    		{
+    		iPosOnScreen = iLast - iFirst;
+    		}
+    	}
+    
+    if (iFirst < 0)
+        {
+        iFirst = 0;
+        }
+    if (iLast > iItemCount)
+        {
+        iLast = iItemCount - 1;
+        }
+    if ( iFirst + iScreenSize < iItemCount )
+        {
+        iLast = iFirst + iScreenSize;
+        }
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CFileNameQueryView* CFileNameQueryView::NewL( CConsoleMain* aConsole,
+                                              CMenu* aParent,
+                                              const TDesC& aName )
+    {
+
+    CFileNameQueryView* self = new ( ELeave ) CFileNameQueryView();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CFileNameQueryView::ConstructL( CConsoleMain* aConsole, 
+                                     CMenu* aParent, 
+                                     const TDesC& aName 
+                                    )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: ~CFileNameQueryView
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CFileNameQueryView::~CFileNameQueryView()
+    {
+
+    iTestModuleNames.ResetAndDestroy();
+    iTestModuleNames.Close();
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: ItemText
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CFileNameQueryView::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    iTestModuleNames.ResetAndDestroy();    
+    
+    // Add loaded module names to menu
+    TInt ret = iMain->UIStore().ListAllModules( iTestModuleNames );
+
+    if( ret != KErrNone )
+        {                 
+        return ret;
+        }
+        
+    TInt count = iTestModuleNames.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aArray.Append( *iTestModuleNames[i] ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    return KErrNone; 
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Just return the parent menu
+
+    Parameters: TKeyCode aSelection       :in:      Not used
+                TBool& aContinue          :out:     Has user pressed "Quit"?
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CFileNameQueryView::SelectL( TKeyCode aSelection, 
+                                    TBool& aContinue )
+    {  
+    
+    MapKeyCode(aSelection);
+
+    if (aSelection == EKeyEnter || aSelection == EKeyRightArrow )
+        {
+        if( iPosOnScreen < iTestModuleNames.Count() )
+            {
+            TInt ret = 
+                iMain->UIStore().AddTestModule( *iTestModuleNames[iPosOnScreen] );
+            if( ret != KErrNone )
+                {
+                TErrorNotification error;
+                error.iModule.Copy( _L("ConsoleUI") );
+                error.iText.Copy( _L("Failed to load test module ") );
+                error.iText.Append( *iTestModuleNames[iPosOnScreen] );
+                error.iText.Append( _L(" error "));
+                error.iText.AppendNum( ret );
+                iMain->Error( error );
+                }
+        return iParent;
+            }
+        else
+            {
+            return this;
+            }
+        }  
+
+    return CMenu::SelectL( aSelection, aContinue );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                const TDesC& aHeader	  :in:		Text containing STIF version information
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMainMenu* CMainMenu::NewL( CConsoleMain* aConsole,
+                            CMenu* aParent,
+                            const TDesC& aName,
+                            const TDesC& aHeader)
+    {
+
+    CMainMenu* self = new ( ELeave ) CMainMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aHeader );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMainMenu
+
+    Method: ~CMainMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMainMenu::~CMainMenu()
+    {
+    delete iOutputView;
+    iOutputView = NULL;
+    delete iOperationMenu;
+    iOperationMenu = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text. Add "Exit" to normal SelectLion
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMainMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    TInt ret = CMenu::ItemTexts( aArray );
+    if ( ret != KErrNone )
+    	{
+    	return ret;
+    	}
+    // Add Exit to last one in menu
+    if( aArray.Append( KExitTxt ) != KErrNone )
+        {
+        return KErrNoMemory;
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                const TDesC& aHeader	  :in:		Text containing STIF version information
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMainMenu::ConstructL( CConsoleMain* aConsole, 
+                            CMenu* aParent,
+                            const TDesC& aName,
+                            const TDesC& aHeader
+                          )
+    {
+    CMenu::ConstructL( aConsole, aParent, aName, aHeader);
+    iOutputView = NULL;
+    iOperationMenu = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle SelectLion in this
+    method, other keys are handles in CMenu class.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMainMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    // If SelectLion == "exit" and right or enter
+    if (aSelection == EKeyEnter || aSelection == EKeyRightArrow )
+        {
+        if ( iPosOnScreen == iItemCount-1 )
+            {
+            // Exit
+            aContinue = EFalse;
+            return this;
+            }
+        }
+
+    // Normal menu handling
+    CMenu* tmp = CMenu::SelectL(aSelection, aContinue);
+    return tmp;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: CreateOutputViewL
+
+    Description: Creates test case output view.
+
+    Parameters: CMenu* aParent: parent menu for case operation menu
+
+    Return Values: CMenu*        New menu
+
+    Errors/Exceptions: Leaves is CCaseExecutionView menu leaves during creation
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMainMenu::CreateOutputViewL(CMenu* aParent)
+    {
+    // Get test cases that have been run
+    RRefArray<CStartedTestCase> startedTestCases;
+    CleanupClosePushL(startedTestCases);
+    CMenu* res = NULL;
+
+    startedTestCases.Reset();
+    if(iMain->UIStore().StartedTestCases(startedTestCases, CUIStoreIf::EStatusAll) == KErrNone)
+        {                 
+        TInt count = startedTestCases.Count();
+        if(count > 0)
+            {
+            // Create menu with execution info
+            const CStartedTestCase* caseContainer = &startedTestCases[count - 1];
+            delete iOutputView;
+            iOutputView = NULL;
+            delete iOperationMenu;
+            iOperationMenu = NULL;
+
+            iOperationMenu = CCaseOperationMenu::NewL(iMain,
+                                                      aParent, //back to parent menu
+                                                      caseContainer->TestInfo().TestCaseTitle(),
+                                                      caseContainer
+                                                     );
+
+            iOutputView = CCaseExecutionView::NewL(iMain,
+                                                   iOperationMenu, //back to Case Operation Menu
+                                                   caseContainer->TestInfo().TestCaseTitle(),
+                                                   caseContainer
+                                                  );
+            res = iOutputView;
+            }
+        }
+        
+    CleanupStack::PopAndDestroy(&startedTestCases);
+    return res;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CModuleListView* CModuleListView::NewL( CConsoleMain* aConsole,
+                                        CMenu* aParent,
+                                        const TDesC& aName )
+    {    
+
+    CModuleListView* self = new ( ELeave ) CModuleListView();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: ~CModuleListView
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CModuleListView::~CModuleListView()
+    {
+    delete iModuleAdd;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: ConstructL
+
+    Description: Second level constructor. 
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if module can't be appended to list
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CModuleListView::ConstructL( CConsoleMain* aConsole,
+                                  CMenu* aParent,
+                                  const TDesC& aName
+                                 )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+   
+    // Construct module menu
+    iModuleAdd  = CFileNameQueryView::NewL ( iMain, this, KSelectMenuTxt );    
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: ItemText
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CModuleListView::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    // Add also "Add module" text
+    if( aArray.Append( KAddMenuTxt ) != KErrNone )
+        {
+        return KErrNoMemory;
+        }
+    if( aArray.Append( KLoadMenuTxt ) != KErrNone )
+        {
+        return KErrNoMemory;
+        } 
+        
+    return KErrNone; 
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CModuleListView
+
+    Method: PrintMenuL
+
+    Description: Prints the menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CModuleListView::PrintMenuL( TUpdateType aType )
+    {
+    
+    // Get module names
+    RRefArray<TDesC> modules;
+    TInt ret = iMain->UIStore().Modules( modules );
+
+    CMenu::PrintMenuL( aType );
+    
+    // Add loaded module names to menu
+    if( ret != KErrNone )
+        {
+        modules.Reset();
+        modules.Close();
+        return;
+        }
+        
+    TBuf<KMaxLineLength> line;
+    TInt count = modules.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        line = _L("    ");
+        LimitedAppend ( line, modules[i] );
+
+        // Print the line
+        Print(line);
+        }
+    modules.Reset();
+    modules.Close();
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle right arrow and enter
+                 here, others in parent menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CModuleListView::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+    
+    MapKeyCode(aSelection);
+
+    if( ( aSelection == EKeyRightArrow ||
+            aSelection == EKeyEnter ) )
+        {
+        if( iPosOnScreen == EAddMenuTxtItem )
+            {
+            return iModuleAdd;
+            }
+        else if( iPosOnScreen == ELoadMenuTxtItem )
+            {
+            iMain->UIStore().LoadAllModules();
+            return this;
+            }
+        else 
+            {
+            return this;
+            }
+        }
+
+    return CMenu::SelectL( aSelection, aContinue );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseStartMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TBool aShowOutput         :in:      Show output after test case is run
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseStartMenu* CCaseStartMenu::NewL( CConsoleMain* aConsole,
+                                      CMenu* aParent,
+                                      const TDesC& aName,
+                                      TBool aShowOutput)
+    {
+
+    CCaseStartMenu* self = new ( ELeave ) CCaseStartMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aShowOutput );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseStartMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseStartMenu::ConstructL( CConsoleMain* aConsole,
+                                 CMenu* aParent,
+                                 const TDesC& aName,
+                                 TBool aShowOutput
+                               )
+    {
+
+    iShowOutput = aShowOutput;
+    CMenu::ConstructL( aConsole, aParent, aName);
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CCaseStartMenu
+
+    Method: ~CCaseStartMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseStartMenu::~CCaseStartMenu()
+    {
+    iTestCases.Close();
+
+    iMapFilteredToAll.Reset();
+    iMapFilteredToAll.Close();
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseStartMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CCaseStartMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+    iTestCases.Reset();
+    TInt ret = iMain->UIStore().TestCases( iTestCases );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    const RPointerArray<TDesC> &filters = iMain->GetFilterArray();
+    const TInt filterindex = iMain->GetFilterIndex(); 
+    iMapFilteredToAll.Reset();
+    
+    TInt count = iTestCases.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        //If user has chosen filter, let's apply it
+        if(filterindex > 0) //skip the first filter which always is "No filter"
+            {
+            //Check whether test title is matching the applied filter
+            iTitleLowerCase.Copy(iTestCases[i].TestCaseTitle());
+            iTitleLowerCase.LowerCase();
+            iFilterLowerCase.Copy(*filters[filterindex]);
+            iFilterLowerCase.LowerCase();
+
+            if(iTitleLowerCase.Match(iFilterLowerCase) != KErrNotFound)
+                {
+                ret = aArray.Append(iTestCases[i].TestCaseTitle());
+                if(ret != KErrNone)
+                    {
+                    return ret;
+                    }
+                ret = iMapFilteredToAll.Append(i);
+                if(ret != KErrNone)
+                    {
+                    return ret;
+                    }                
+                }
+            }
+        else
+            {
+            ret = aArray.Append( iTestCases[i].TestCaseTitle() );
+            if(ret != KErrNone)
+                {
+                return ret;
+                }
+            ret = iMapFilteredToAll.Append(i);
+            if(ret != KErrNone)
+                {
+                return ret;
+                }                
+            }
+        }
+        
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseStartMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CCaseStartMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    switch ( aSelection )
+        {
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            // Start the case
+            if ( (iFirst + iPosOnScreen) < iMapFilteredToAll.Count() ) //changed from iTestCases to iMapFilteredToAll, because first table keeps info about all test cases, and second one about filtered cases
+                {
+                TInt index;
+                User::LeaveIfError( 
+                    iMain->UIStore().StartTestCase( 
+                        iTestCases[iMapFilteredToAll[iFirst + iPosOnScreen]], index ) );
+                // Create output screen (menu) if needed
+                if(iShowOutput)
+                    {
+                    CMenu* m = iMain->GetMainMenu()->CreateOutputViewL(iParent);
+                    if(m)
+                        return m;
+                    }
+                return iParent;
+                }
+            else
+                {
+                return this;
+                }
+            }
+
+        default:
+            return CMenu::SelectL( aSelection, aContinue);
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleBaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleBaseMenu* CMultipleBaseMenu::NewL( CConsoleMain* aConsole,
+                                            CMenu* aParent,
+                                            const TDesC& aName )
+    {
+
+    CMultipleBaseMenu* self = new ( ELeave ) CMultipleBaseMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleBaseMenu
+
+    Method: CMultipleBaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleBaseMenu::CMultipleBaseMenu(): 
+    iSetFinished( ETrue ),
+    iRunType( ERunSequential ),
+    iMenuTotCount( 0 ),
+    iMenuCount( 0 )
+    {
+    
+    iMenuCount = EChangeAll + 1;
+    iMenuTotCount = iMenuCount;
+    
+    }   
+    
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleBaseMenu
+
+    Method: ~CMultipleBaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleBaseMenu::~CMultipleBaseMenu()
+    {
+    
+    iSetState.Close();
+    
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMultipleBaseMenu::ConstructL( CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName 
+                             )
+    {
+
+    CCaseStartMenu::ConstructL( aConsole, aParent, aName );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMultipleBaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+    if ( iSetFinished )
+        {
+        if( aArray.Append( KChangeAll ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        
+        if( iUpdateType ==  EMenuPrint )
+            {   
+            TInt ret = UpdateTestCases();
+            if( ret != KErrNone )
+                {                 
+                return ret;
+                }
+            }
+        TInt count = iTestCases.Count();
+        for( TInt j=0; j<count; j++ )
+            {
+            if( aArray.Append( iTestCases[j].TestCaseTitle() ) 
+                != KErrNone )
+                {
+                return KErrNoMemory;
+                }
+            if( aArray.Count() > iSetState.Count())
+                {
+                // Appends iSetState only if aArray's size is bigger @js
+                if( iSetState.Append(EFalse) != KErrNone )
+                    {
+                    return KErrNoMemory;
+                    }
+                }
+            }
+        }
+    else
+        {
+        if( aArray.Append( KCancelSet ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMultipleBaseMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number 
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMultipleBaseMenu::AppendBefore( TInt aLineNum, TDes& aLine )
+    {
+    
+    CMenu::AppendBefore( aLineNum, aLine );
+    if( ( aLine.MaxLength() - aLine.Length() ) < 2 )
+        {
+        return;
+        }        
+    
+    if( aLineNum >= iMenuTotCount )
+        {
+        if ( iSetState[ aLineNum - iMenuTotCount ] )
+            {
+            aLine.Append(_L("S "));
+            }
+        else
+            {
+            aLine.Append(_L("  "));
+            }
+        }
+   
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMultipleBaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    if ( iSetFinished )
+        {
+
+        if ( ( aSelection == EKeyEnter  ) || ( aSelection == EKeyRightArrow ) )
+            {
+            // CMultipleBaseMenu relative position 
+            TInt pos = iFirst + iPosOnScreen - iMenuTotCount + iMenuCount;
+            if( pos  == EChangeAll )
+                {
+                TInt count = iTestCases.Count();    
+
+                // Change all                                       
+                for (TInt i = 0; i < count; i++)
+                    {
+                    iSetState[i] = !iSetState[i];
+                    }
+
+                return this;
+                }
+            else
+                {
+                // Normal item, change state...
+                iSetState[ iFirst + iPosOnScreen - iMenuTotCount ] = 
+                    !iSetState[ iFirst + iPosOnScreen - iMenuTotCount ];
+                return this;
+                }            
+            
+            }
+
+		return CMenu::SelectL( aSelection, aContinue );
+        }
+    else
+        {
+
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {
+                if ( iOngoingCaseContainer != NULL )
+                    {
+                    iOngoingCaseContainer->UIEngineContainer().CancelTest();
+                    }
+                iSetFinished = ETrue;
+                iFirst = 0;
+                iLast = 0;
+                return this;
+                }
+            default:
+                return CMenu::SelectL( aSelection, aContinue );
+            }
+
+
+
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: CheckIfAnyCaseIsSelected
+
+    Description: Checks if any of testcases was selected in multiple selection menu
+
+    Parameters: TInt aCount number of testcases in multiple selection menu
+
+    Return Values: ETrue if any testcase was selected, EFalse if none of testcases was selected
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CMultipleBaseMenu::CheckIfAnyCaseIsSelected(TInt aCount)
+{
+	TInt currentPos = 0;
+	for(; currentPos<aCount; currentPos++)	
+	{
+		//if any of testcases was selected then return true
+		if (iSetState[currentPos])
+			return ETrue;
+	}
+	//if none of testcases was selected then return false
+	return EFalse;
+}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: SignalL
+
+    Description: Handle test case starts
+
+    Parameters: CStartedTestCase* aContainer: in: CStartedTestCase container
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CMultipleBaseMenu::SignalL( CStartedTestCase* /*aContainer*/ )
+    {
+
+    TInt count = iTestCases.Count();
+    
+    TBool started = EFalse;
+    TInt index;
+    TInt err = KErrNone;
+
+    // Counter to prevent infinite loop when cases can't be started at all
+    // when running cases in repeat mode.
+    TInt casesChecked = 0;
+
+    // If cases are not aborted or not in last case and at least one test
+    // case was selected, start a new one
+    if ( !iSetFinished && iCurrentRunPos != count && CheckIfAnyCaseIsSelected(count) )
+        {
+        // Search next case from set and execute it.
+        while( iCurrentRunPos < count )
+            {
+            if ( iSetState[iCurrentRunPos] )
+                {       
+                err = iMain->UIStore().StartTestCase( 
+                    iTestCases[ iCurrentRunPos ], 
+                    index );
+
+                iCurrentRunPos++;
+                casesChecked++;
+
+                // Go to start of list, if running cases in repeat mode. 
+                // In other modes, just get out from the main loop
+                if( ( iRunType == ERunRepeatSequential ) &&
+                    ( iCurrentRunPos >= count ) )
+                    {
+                    // Restart from first one on next time.
+                    iCurrentRunPos = 0;
+                    }
+
+                // Handle out of memory error separately, because there is
+                // always new test case result display constructed when
+                // starting case => Starting more new cases uses more memory
+                // and it will not work, so stop starting new cases.
+                if( err == KErrNoMemory )
+                    {
+                    iSetFinished = ETrue;
+                    break;
+                    }
+
+                // Get pointer to ongoing case in case that user wants to
+                // cancel it.
+                iOngoingCaseContainer = 
+                    &iMain->UIStore().StartedTestCaseL( index );
+
+                // Store pointer to this object to allow 
+                // SignalL call when test case is completed
+                iOngoingCaseContainer->iBackPtr = (TAny*)this;
+
+                if( err != KErrNone )
+                    {
+                    TFullTestResult result;  
+                    result.iTestResult.iResult = err;
+                    result.iTestResult.iResultDes.Copy( 
+                                            _L("Failed to start testcase") );
+                    // Prevent infinite loop in case, where
+                    // ERunRepeatSequential and ALL cases fail to start.
+                    if ( iRunType == ERunRepeatSequential && 
+                                            casesChecked == count )
+                        {
+                        // In this state, started = EFalse so final check
+                        // stops running
+                        break;
+                        }
+                    }
+                else if( ( iRunType == ERunSequential ) ||
+                         ( iRunType == ERunRepeatSequential ) )
+                    {
+                    started = ETrue;
+                    break;
+                    }
+                }
+            else 
+                {
+                iCurrentRunPos++;
+                casesChecked++;
+
+                // Go to start of list, if running cases in repeat mode. 
+                // In other modes, just get out from the main loop
+                if( ( iRunType == ERunRepeatSequential ) &&
+                    ( iCurrentRunPos >= count ) )
+                    {
+                    // Restart from first one
+                    iCurrentRunPos = 0;
+                    }
+                }
+            }
+        }
+
+    if ( err == KErrNoMemory )
+    	{
+    	iMain->ExitWithNoMemoryErrorMessage();
+    	}
+    
+    // If nothing was selected, then mark set as finished. 
+    // Or running cases at same time, so all have been started.
+    if ( started == EFalse )
+        {
+        iFirst = 0;
+        iLast = 0;
+        iSetFinished = ETrue;
+        iCurrentRunPos = 0;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: UpdateTestCases
+
+    Description: 
+
+    Parameters: 
+
+    Return Values: 
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMultipleBaseMenu::UpdateTestCases()
+    {
+
+    // Update test cases
+    iTestCases.Reset();
+    iSetState.Reset();
+    return iMain->UIStore().TestCases( iTestCases );
+            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleCaseMenu* CMultipleCaseMenu::NewL( CConsoleMain* aConsole,
+                                            CMenu* aParent,
+                                            const TDesC& aName )
+    {
+
+    CMultipleCaseMenu* self = new ( ELeave ) CMultipleCaseMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleCaseMenu
+
+    Method: CMultipleCaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleCaseMenu::CMultipleCaseMenu()    
+    {
+    
+    iMenuItemsCount = ERepeatRunSelection + 1;
+    iMenuItemsCount++; //Select all between already selected
+    iMenuTotCount += iMenuItemsCount;
+    
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleCaseMenu
+
+    Method: ~CMultipleCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleCaseMenu::~CMultipleCaseMenu()
+    {
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMultipleCaseMenu::ConstructL( CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName 
+                             )
+    {
+
+    CCaseStartMenu::ConstructL( aConsole, aParent, aName );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleCaseMenu
+
+    Method: StartRunningL
+
+    Description: Start running multiple cases.
+
+    Parameters: TRunType aRunType: in: Running type
+                const TDesC& aModule: in: module name 
+                const TDesC& aTestCaseFile: in: test case file name 
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves on error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMultipleCaseMenu::StartRunningL( TRunType aRunType, 
+                                       const TDesC& aModule, 
+                                       const TDesC& aTestCaseFile )
+    {
+    
+    // Update test cases
+    iTestCases.Reset();
+    iSetState.Reset();
+    User::LeaveIfError( 
+        iMain->UIStore().TestCases( iTestCases, aModule, aTestCaseFile ) );
+    
+    // Select all for running
+    TInt count = iTestCases.Count();
+    for( TInt j=0; j<count; j++ )
+        {
+        User::LeaveIfError( iSetState.Append(ETrue) );
+        }
+        
+    // Start running
+    iCurrentRunPos = 0;
+    iSetFinished = EFalse;
+    iRunType = aRunType;
+    SignalL ( NULL );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMultipleCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+    if ( iSetFinished )
+        {
+        if( aArray.Append( KRunSequentially ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if( aArray.Append( KRunParallel ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if( aArray.Append( KRepeatRunSequentially ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if(aArray.Append(KSelectFromTo) != KErrNone)
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    TInt ret = CMultipleBaseMenu::ItemTexts(aArray);
+    if(ret != KErrNone)
+        {
+        return ret;
+        }
+    
+    return KErrNone;    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMultipleCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    if ( iSetFinished )
+        {
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {
+
+                if ( iFirst + iPosOnScreen == ERunSelection )
+                    {
+                    // Start the first one
+                    iCurrentRunPos = 0;
+                    iSetFinished = EFalse;
+                    iRunType = ERunSequential;
+                    SignalL ( NULL );
+
+                    return iParent;
+                    }
+                else if ( iFirst + iPosOnScreen == ERunSelectionParaller )
+                    {
+                    // Start the first one
+                    iCurrentRunPos = 0;
+                    iSetFinished = EFalse;
+                    iRunType = ERunParallel;
+                    SignalL ( NULL );
+
+                    return iParent;
+                    }
+                else if ( iFirst + iPosOnScreen == ERepeatRunSelection )
+                    {
+                    // Start the first one
+                    iCurrentRunPos = 0;
+                    iSetFinished = EFalse;
+                    iRunType = ERunRepeatSequential;
+                    SignalL ( NULL );
+
+                    return iParent;
+                    }
+                else if(iFirst + iPosOnScreen == ESelectFromTo)
+                    {
+                    TInt count = iTestCases.Count();
+                    TInt indexFirst = count;
+                    TInt indexLast = count - 1;
+                    TInt i;
+                    
+                    // Find first test case which is set
+                    for(i = 0; i < count; i++)
+                        {
+                        if(iSetState[i])
+                            {
+                            indexFirst = i;
+                            break;
+                            }
+                        }
+                    
+                    // Find last test case which is set
+                    if(indexFirst < count)
+                        {
+                        for(i = count - 1; i > indexFirst; i--)
+                            {
+                            if(iSetState[i])
+                                {
+                                indexLast = i;
+                                break;
+                                }
+                            }
+                        
+                        // Set test cases between first and last
+                        for(i = indexFirst; i <= indexLast; i++)
+                            {
+                            iSetState[i] = ETrue;
+                            }
+                        }
+
+                    return this;
+                    }
+                }
+                break;
+            default:
+                break;
+            }
+        }   
+        
+    return CMultipleBaseMenu::SelectL( aSelection, aContinue );
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseMenu* CCaseMenu::NewL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName, 
+                            TInt aType )
+    {
+
+    CCaseMenu* self = new ( ELeave ) CCaseMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aType );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if memory allocation fails
+                       Leaves if CCaseOperation menu NewL leaves
+                       Leaves if UpcateCaseListL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseMenu::ConstructL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName, 
+                            TInt aType
+                          )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+    iType = aType;
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: ~CCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CCaseMenu::~CCaseMenu()
+    {
+
+    delete iCaseOperationMenu;
+    iCaseOperationMenu = 0;
+    
+    iTestCases.Close();
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    iTestCases.Reset();
+    
+    TInt ret = iMain->UIStore().StartedTestCases( iTestCases, iType );
+    if ( ret != KErrNone )
+    	{
+    	return ret;
+    	}
+
+    TInt count = iTestCases.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aArray.Append( iTestCases[i].TestInfo().TestCaseTitle() ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CCaseMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseMenu::AppendBefore(TInt aLineNum, TDes& aLine)
+    {
+    CMenu::AppendBefore(aLineNum, aLine);
+
+    //START of --Add number to the test case title--
+    //First check how much space we need
+    TInt additionalSpace = 0;
+    TInt currentCount = aLineNum + 1;
+
+    if(currentCount >= 10000) additionalSpace = 10; //f.e. "10157521. "
+    else if(currentCount >= 1000) additionalSpace = 6; //f.e. "1157. "
+    else if(currentCount >= 100) additionalSpace = 5; //f.e. "101. "
+    else if(currentCount >= 10) additionalSpace = 4; //f.e. "15. "
+    else additionalSpace = 3; //f.e. "1. "
+
+ //Create descriptor, add content to it, and finally append to line
+    TBuf<20> num;
+
+    if(iTestCases[aLineNum].Status() == CUIStoreIf::EStatusRunning )
+ 	   {
+    if( iTestCases[aLineNum].UIEngineContainer().State() == CUIEngineContainer::EPaused)
+     	{
+     	  //If not enough space, return
+     	if((aLine.MaxLength() - aLine.Length()) < additionalSpace + 4)
+     	     {
+     	     return;
+     	     }
+     		num.Format(_L("%d.(P) "), currentCount);
+     	}
+     else
+     	{
+        //If not enough space, return
+     	if((aLine.MaxLength() - aLine.Length()) < additionalSpace)
+     		{
+     	  	return;
+     	     }     		  			
+     	num.Format(_L("%d."), currentCount);
+     	}
+ 	   }
+    aLine.Append(num);
+    }
+    //END of --Add number to test case title--
+    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle Enter and Right Arrow
+    here, other will be handled in CMenu::SelectL
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    switch (aSelection)
+        {
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            if ( iFirst + iPosOnScreen < iTestCases.Count() )
+                {
+                delete iCaseOperationMenu;
+                iCaseOperationMenu = 0;
+                iCaseOperationMenu = CCaseOperationMenu::NewL( 
+                    iMain, 
+                    this, 
+                    iTestCases[iFirst + iPosOnScreen].TestInfo().TestCaseTitle(), 
+                    &iTestCases[iFirst + iPosOnScreen] );   
+
+                return iCaseOperationMenu;
+                }
+            }
+            return this;
+        default:
+            // Let the parent class handle rest
+            return CMenu::SelectL(aSelection, aContinue);
+        }
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseOperationMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                CStartedTestCase* aCaseContainer:in: Case container
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseOperationMenu* CCaseOperationMenu::NewL( CConsoleMain* aConsole,
+                                 CMenu* aParent,
+                                 const TDesC& aName,
+                                 const CStartedTestCase* aCaseContainer
+                               )
+    {
+
+    CCaseOperationMenu* self = new ( ELeave ) CCaseOperationMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aCaseContainer );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseOperationMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                CStartedTestCase* aCaseContainer:in: Case container
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseOperationMenu::ConstructL( CConsoleMain* aConsole,
+                                     CMenu* aParent,
+                                     const TDesC& aName,
+                                     const CStartedTestCase* aCaseContainer
+                                   )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName); 
+    iCaseContainer = aCaseContainer;
+    
+    // Indicate that this menu contains prints, update when needed
+    iType = CUIStoreIf::EStatusExecuted;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: ~CMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CCaseOperationMenu::~CCaseOperationMenu()
+    {
+    delete iView;
+    iView = 0;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseOperationMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CCaseOperationMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    if( iCaseContainer->Status() & CUIStoreIf::EStatusRunning )
+        {
+        if( aArray.Append( KOutputViewDes ) != KErrNone )
+            {
+            return KErrNoMemory; 
+            }
+                
+        // Set resume/pause text
+        if( iCaseContainer->UIEngineContainer().State() == 
+            CUIEngineContainer::EPaused )
+            {
+            if( aArray.Append( KResumeCaseDes ) != KErrNone )
+                {
+                return KErrNoMemory; 
+                }
+            }
+        else
+            {
+            if( aArray.Append( KPauseCaseDes ) != KErrNone )
+                {
+                return KErrNoMemory; 
+                }
+            }
+        if( aArray.Append( KAbortCaseDes ) != KErrNone )
+            {
+            return KErrNoMemory; 
+            }
+        }
+    else
+        {
+        if(aArray.Append(KRestartCaseDes) != KErrNone)
+            {
+            return KErrNoMemory; 
+            }
+        if( aArray.Append( KOutputViewDes ) != KErrNone )
+            {
+            return KErrNoMemory; 
+            }
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu and test case specific information after that.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if FormatL leaves
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CCaseOperationMenu::PrintMenuL( TUpdateType  aType )
+    {
+
+    // Print menu
+    CMenu::PrintMenuL( aType );
+    
+    // Print the result description + result code
+    // If case is finished, print also result string
+    TInt state = iCaseContainer->Status();
+    if  ( ! ( state & CUIStoreIf::EStatusRunning ) )
+        {        
+
+        TName resultLine;
+        
+        Print (_L(""));
+        resultLine.Append(_L("Result info: ") );
+
+        if( state & CUIStoreIf::EStatusPassed )
+            {
+            resultLine.Append( _L("Passed" ) );
+            } 
+        else if( state & CUIStoreIf::EStatusFailed )
+            {
+            resultLine.Append( _L("Failed" ) );
+            } 
+        else if( state & CUIStoreIf::EStatusAborted )
+            {
+            resultLine.Append( _L("Aborted" ) );
+            } 
+        else if( state & CUIStoreIf::EStatusCrashed )
+            {
+            resultLine.Append( _L("Crashed" ) );
+            }
+        PrintMulti( resultLine );
+        resultLine.Zero();             
+
+        // Print test results
+        if( !( ( state & CUIStoreIf::EStatusAborted ) || 
+               ( state & CUIStoreIf::EStatusCrashed ) || 
+               ( state & CUIStoreIf::EStatusPassed ) ) )
+            {
+
+            resultLine.Format(_L("Result code %d"), 
+                iCaseContainer->Result().iTestResult.iResult );
+            PrintMulti ( resultLine );            
+            }
+
+        if( iCaseContainer->Result().iCaseExecutionResultType == 
+            TFullTestResult::ECaseErrorFromModule )
+            {
+            PrintMulti ( _L("Error from RunTestCase():"));
+            }
+
+        // Print result descriptor if that is available
+        const TDesC& des = iCaseContainer->Result().iTestResult.iResultDes;
+        if ( des.Length() >0 )
+            {
+            PrintMulti(des);
+            }
+
+        // Print abort code if that is available
+        if( ( state & CUIStoreIf::EStatusAborted ) ||
+            ( state & CUIStoreIf::EStatusCrashed ) )
+            {
+            // Print abort type, if that is available
+            TFullTestResult::TCaseExecutionResult res = 
+                iCaseContainer->Result().iCaseExecutionResultType;
+            
+            if ( res == TFullTestResult::ECaseLeave ||
+                 res == TFullTestResult::ECasePanic ||
+                 res == TFullTestResult::ECaseException || 
+                 res == TFullTestResult::ECaseErrorFromModule ||
+                 res == TFullTestResult::ECaseSuicided )
+                {
+                TInt code = iCaseContainer->Result().iCaseExecutionResultCode;
+                resultLine.Format(_L("Code %d (0x%x)"), code, code );
+                PrintMulti ( resultLine );
+                }
+            }
+
+        // Print start and end times
+        const TInt KTimeFieldLength = 30;
+        TBuf<KTimeFieldLength> time;
+        _LIT(KDateString,"%-B%:0%J%:1%T%:2%S%.%*C4%:3%+B");
+
+        resultLine = _L("Started:");
+        iCaseContainer->Result().iStartTime.FormatL(time,KDateString);
+        resultLine.Append(time);
+        PrintMulti (resultLine);
+
+        resultLine = _L("Completed:");
+        iCaseContainer->Result().iEndTime.FormatL(time,KDateString);
+        
+        resultLine.Append(time);
+        PrintMulti (resultLine);
+
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseOperationMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle Enter and right arrow
+    here, others are handled in parent menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CCaseOperationMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {   
+
+    MapKeyCode(aSelection);
+    
+    if (aSelection == EKeyEnter || aSelection == EKeyRightArrow )
+        {        
+        // restartOptionModifier is used because when test case is running
+        // restart option is not available (and visible) and that's why
+        // we need to modify switch by 1.
+        // When test case is finished, restart option becomes available
+        // and is put at the first place.
+        TInt restartOptionModifier = 0;
+        if(iCaseContainer->Status() & CUIStoreIf::EStatusRunning)
+            restartOptionModifier = 1;
+        
+        switch (iPosOnScreen + iFirst + restartOptionModifier)
+        {
+        case ERestartCase:
+            {
+            TInt index;
+            User::LeaveIfError(iMain->UIStore().StartTestCase(iCaseContainer->TestInfo(), index));
+            // Create output screen
+            CMenu* m = iMain->GetMainMenu()->CreateOutputViewL(iParent);
+            return m;
+            }
+        case EOutputView:
+            {
+            delete iView;
+            iView = 0;
+            iView = CCaseExecutionView::NewL( 
+                iMain, 
+                this, 
+                iCaseContainer->TestInfo().TestCaseTitle(), 
+                iCaseContainer );
+
+            return iView;
+            }
+
+        case EPauseResume:
+
+            if( iCaseContainer->UIEngineContainer().State() == 
+                CUIEngineContainer::ERunning )
+                {    
+                // Pausing a running case
+                iCaseContainer->UIEngineContainer().PauseTest();
+
+                }
+            else if( iCaseContainer->UIEngineContainer().State() == 
+                     CUIEngineContainer::EPaused )
+                {
+                // Resuming a paused case
+                iCaseContainer->UIEngineContainer().ResumeTest();
+
+                }
+            // No other possibilities
+            return this;
+
+        case EAbortCase:
+            iCaseContainer->UIEngineContainer().CancelTest();
+            break;
+
+        }
+        
+        return this;
+        }
+    else
+        {
+        return CMenu::SelectL(aSelection, aContinue);
+        }
+        
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseExecutionView
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                CStartedTestCase* aCase :in:      Case container
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseExecutionView* CCaseExecutionView::NewL( CConsoleMain* aConsole,
+                                              CMenu* aParent,
+                                              const TDesC& aName,
+                                              const CStartedTestCase* aCase )
+    {
+
+    CCaseExecutionView* self = new ( ELeave ) CCaseExecutionView();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aCase );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseExecutionView
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                CStartedTestCase* aCase :in:      Case container
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseExecutionView::ConstructL( CConsoleMain* aConsole,
+                                     CMenu* aParent,
+                                     const TDesC& aName,
+                                     const CStartedTestCase* aCase
+                                    )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName );
+
+    iCase = aCase;
+    
+    // Indicate that this menu contains prints, update when needed
+    iType = CUIStoreIf::EPrintUpdate;
+
+    iLine = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CCaseExecutionView
+
+    Method: ~CCaseExecutionView
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseExecutionView::~CCaseExecutionView()
+    {
+    delete iLineTextBuf;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu. Show the test status and the test case
+    print statements.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseExecutionView::PrintMenuL( TUpdateType  /*aType*/ )
+    {
+    
+    if( iShowLine )
+        {
+        // User want to see whole line 
+        iConsole->ClearScreen();
+        this->PrintMulti( iLineTextBuf->Des() );
+        return;
+        }
+
+    // Print the status
+    TName tmp;
+    TInt state = iCase->Status();
+    if( state & CUIStoreIf::EStatusRunning )
+        {
+        if( iCase->UIEngineContainer().State() == 
+            CUIEngineContainer::EPaused )
+            {
+            tmp = _L("Paused");
+            }
+        else
+            {
+            tmp = _L("Running");
+            }
+        }
+    else if( state & CUIStoreIf::EStatusPassed )
+        {
+        tmp = _L("Passed");
+        }
+    else if( state & CUIStoreIf::EStatusFailed )
+        {
+        tmp = _L("Failed");
+        }
+    else if( state & CUIStoreIf::EStatusAborted )
+        {
+        tmp = _L("Aborted");
+        }
+    else if( state & CUIStoreIf::EStatusCrashed )
+        {
+        tmp = _L("Aborted");
+        }
+    else
+        {
+        tmp = _L("Unknown");
+        }
+    
+    // Clear screen.
+    iConsole->ClearScreen();
+    TBuf<KMaxLineLength> line;
+
+    line.Append(_L(" : "));
+    LimitedAppend(line, iCase->TestInfo().TestCaseTitle() );
+    Print( line );
+
+    const RPointerArray<CTestProgress>& prints = iCase->PrintArray();
+
+    Recalculate( prints.Count() );
+
+    // Print the print statements.
+    for ( TInt i = iFirst; i <= iLast; i++ )
+        {
+        line.Zero();
+        if( iLine == i )
+            {
+            line = _L( "*" ); // For indicating current line
+            }
+        line.Append( prints[i]->iDescription );
+        line.Append(_L(" : "));
+        LimitedAppend(line, prints[i]->iText );
+
+        // Print the line
+        TSize screenSize;
+        screenSize = iConsole->ScreenSize();
+        Print ( line.Left(screenSize.iWidth ) );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseExecutionView
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Either updates position in
+    menu or returns new menu.
+
+    Parameters: TKeyCode aSelection: in: Key
+                TBool& aContinue: out: Has user pressed "Quit"
+
+    Return Values: CMenu* New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CCaseExecutionView::SelectL( TKeyCode aSelection, TBool& /*aContinue*/ )
+    {
+    iShowLine = EFalse;
+    MapKeyCode(aSelection);
+
+    // Take prints
+    const RPointerArray<CTestProgress>& prints = iCase->PrintArray();
+
+    switch( aSelection  )
+        {        
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            // Check that not out of range(too many EKeyUpArrow or EKeyDownArrow)
+            if( iLine >= prints.Count() || iLine < 0)
+                {
+                // do nothing
+                break;
+                }
+            TInt extra = 3; // ' : '
+            TInt length( 0 );
+            length = length + prints[iLine]->iDescription.Length();
+            length = length + prints[iLine]->iText.Length();
+            // Selected print line in seperate(operation will do in
+            // CCaseExecutionView::PrintMenuL() method )
+            delete iLineTextBuf;
+			iLineTextBuf = NULL;
+            TRAPD( ret, iLineTextBuf = HBufC::NewL( length + extra ) );
+            if( ret != KErrNone )
+                {
+                User::InfoPrint( _L("Line show failed, maybe out of memory!!!") );
+                break;
+                }
+            TPtr ptr = iLineTextBuf->Des();
+            ptr.Copy( prints[iLine]->iDescription );
+            ptr.Append( _L( " : " ) );
+            ptr.Append( prints[iLine]->iText );
+            iShowLine = ETrue;
+            break;
+            }
+        case EKeyLeftArrow:
+            {
+            return iParent;
+            }
+		// Go down
+		case EKeyDownArrow:
+			{
+			if ( iFirst + iPosOnScreen == iItemCount - 1 )
+				{
+				// If end of the list, go to beginning
+				iPosOnScreen = 0;
+				iFirst = 0;
+				iLast = iScreenSize;
+				if ( iLast > iItemCount - 1 )
+					{
+					iLast = iItemCount - 1;
+					}
+				iLine = 0;
+				}
+			else 
+				{
+				if ( iPosOnScreen == iScreenSize )
+					{
+					iLast++;
+					iFirst++;
+					}
+				else
+					{
+					// Going down "in-screen", no need to update items
+					iPosOnScreen++;
+					}
+				iLine++;
+				}			
+			break;
+			}
+			
+		// Go Up
+		case EKeyUpArrow:
+			{
+			if ( iFirst + iPosOnScreen == 0 )
+				{
+				// If in the beginning of the list
+
+				iLast = iItemCount - 1;
+				iFirst = iLast - iScreenSize;
+				if ( iFirst < 0 )
+					{
+					iFirst = 0;            	
+					}
+				iPosOnScreen = iLast - iFirst;
+				iLine = iItemCount - 1;
+				}
+			else 
+				{
+				if ( iPosOnScreen == 0 )
+					{
+					iLast--;
+					iFirst--;
+					}
+				else
+					{
+					iPosOnScreen--;
+					}
+				iLine--;
+			}
+			break;
+			}
+		// Additional keys
+		case EKeyHome:
+		case '3':
+			iPosOnScreen = 0;
+			iLine = 0;
+			iFirst = 0;
+			iLast = iScreenSize;
+
+			if ( iLast > iItemCount - 1 )
+				{
+				iLast = iItemCount - 1;
+				}
+			break;
+
+		case EKeyEnd:
+		case '9':
+			iLast = iItemCount - 1;
+			iFirst = iLast - iScreenSize;
+			iLine = iItemCount - 1;
+			
+			if ( iFirst < 0 )
+				{
+				iFirst = 0;
+				}
+			iPosOnScreen = iLast - iFirst;        
+			break;
+
+		case EKeyPageUp:
+		case '1':
+			iFirst = iFirst - iScreenSize;
+			iLast = iLast - iScreenSize;
+
+			if ( iFirst < 0 )
+				{
+				iFirst = 0;
+				iLast = iScreenSize;
+				if ( iLast > iItemCount - 1 )
+					{
+					iLast = iItemCount - 1;
+					}
+				iPosOnScreen = 0;
+				}
+			
+			iLine = iLine - iScreenSize;
+			if ( iLine < 0 )
+				{
+				iLine = 0;
+				}
+			break;
+
+		case EKeyPageDown:
+		case '7':
+			iFirst = iFirst + iScreenSize;
+			iLast = iLast + iScreenSize;
+
+			// Going too far
+			if ( iLast > iItemCount - 1 )
+				{
+				iLast = iItemCount - 1;
+				iFirst = iLast - iScreenSize;
+				if ( iFirst < 0 )
+					{
+					iFirst = 0;
+					}
+				iPosOnScreen = iLast - iFirst;
+				}
+
+			iLine = iLine + iScreenSize;
+			if ( iLine > iItemCount - 1 )
+				{
+				iLine = iItemCount - 1;
+				}
+			break;
+        default:
+            {
+            break;
+            }
+        }
+    
+    return this;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetMenu* CTestSetMenu::NewL( CConsoleMain* aConsole,
+                                        CMenu* aParent,
+                                        const TDesC& aName )
+    {    
+
+    CTestSetMenu* self = new ( ELeave ) CTestSetMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+       
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: CTestSetMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetMenu::CTestSetMenu():
+    iTestSetCreated( EFalse )
+    {
+    
+    iTestSetName.Copy( KDefaultSetName );    
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: ~CTestSetMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestSetMenu::~CTestSetMenu()
+    {
+    
+    delete iSubMenu;
+    iSubMenu = 0;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor. 
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if module can't be appended to list
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetMenu::ConstructL( CConsoleMain* aConsole,
+                                  CMenu* aParent,
+                                  const TDesC& aName
+                                 )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+   
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: SetTestSetName
+
+    Description: Set test set name.
+
+    Parameters: const TFileName& aTestSetName: in: Test set name
+
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetMenu::SetTestSetFileName( const TFileName& aTestSetName )
+    {
+    
+    iTestSetName.Copy( aTestSetName );    
+    
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    if( !iTestSetCreated )
+        {
+        if( aArray.Append( KSetCreate ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if( aArray.Append( KSetLoad ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }        
+        }
+    else
+        {
+        if( aArray.Append( KSetShow ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetStartSeq ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetStartPar ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if( aArray.Append( KSetUnload ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                        
+        if( aArray.Append( KSetRemove ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetSave ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetCaseAdd ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetCaseRemove ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetStartSeqNotRun ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        }
+        
+    return KErrNone; 
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CTestSetMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestSetMenu::PrintMenuL( TUpdateType aType )
+    {
+    
+    if( iTestSetCreated )
+        {
+        RRefArray<CTestSetInfo> setInfos;
+        TInt ret = iMain->UIStore().TestSets( setInfos );
+
+        CMenu::PrintMenuL( aType );
+
+        if( (  ret != KErrNone ) ||
+            ( setInfos.Count() != 1 ) )
+            {
+            // Should never ever happen
+            User::Panic( KTestSetMenu, KErrGeneral );
+            return;
+            }
+        const CTestSetInfo& set = setInfos[0];
+        setInfos.Reset();
+        setInfos.Close();
+        
+        const RRefArray<const CTestInfo> testCases = set.TestCases();
+        
+        TBuf<KMaxLineLength> line;
+        TInt count = testCases.Count();
+        for(TInt i = 0; i < count && i + ESetLAST <= iScreenSize; i++)
+            {
+            line = _L("    ");
+            LimitedAppend ( line, testCases[i].TestCaseTitle() );
+
+            // Print the line
+            Print(line);
+            }
+        }
+    else
+        {
+        CMenu::PrintMenuL( aType );
+        }    
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle right arrow and enter
+                 here, others in parent menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+    TBuf<32> currSetName;
+    MapKeyCode(aSelection);    
+    
+    if( ( aSelection != EKeyRightArrow ) &&
+        ( aSelection != EKeyEnter ) )
+        {
+        return CMenu::SelectL( aSelection, aContinue );
+        }            
+    
+    TInt ret = KErrNone;        
+    if( !iTestSetCreated )
+        {
+        switch( iPosOnScreen )
+            {
+            case ESetCreate:
+                ret = iMain->UIStore().CreateTestSet( iTestSetName );
+                if( ret != KErrNone )
+                    {
+                    User::InfoPrint( _L("Test set creation failed") );
+                    }
+                break;
+            case ESetLoad: 
+            
+            	return iItems[0];
+            } 
+        if( ret == KErrNone )
+            {
+            iTestSetCreated = ETrue;
+            }      
+        }
+    else
+        {
+        CStartedTestSet::TSetType setType = CStartedTestSet::ESetSequential;
+        switch( iPosOnScreen )
+            {
+            case ESetShow:   
+            // Add the test sets menu
+                delete iSubMenu;
+                iSubMenu = 0;
+                iSubMenu = CStartedTestSetMenu::NewL( iMain, 
+                                        this, 
+                                        _L("Started test sets menu"));
+                return iSubMenu;
+            case ESetUnload:
+                ret = iMain->UIStore().UnloadTestSet( iTestSetName );
+                if( ret != KErrNone )
+                    {
+                    User::InfoPrint( _L("Test set unload failed") );
+                    }
+                iTestSetCreated = EFalse;                  
+                break;
+            case ESetRemove: 
+                ret = iMain->UIStore().RemoveTestSet( iTestSetName );
+                if( ret != KErrNone )
+                    {
+                    User::InfoPrint( _L("Test set remove failed") );
+                    }
+                iTestSetCreated = EFalse;  
+                break;
+            case ESetCaseAdd:   
+                delete iSubMenu;
+                iSubMenu = 0;
+                iSubMenu = CTestSetAddCaseMenu::NewL( 
+                                iMain, 
+                                this, 
+                                _L("Add test cases to test set"),
+                                iTestSetName );
+                                
+                return iSubMenu;
+            case ESetCaseRemove: 
+                delete iSubMenu;
+                iSubMenu = 0;
+                iSubMenu =  CTestSetRemoveCaseMenu::NewL( 
+                                iMain, 
+                                this, 
+                                _L("Remove test cases from test set"),
+                                iTestSetName );
+                                
+                                
+                return iSubMenu;  
+            case ESetSave:   
+                // during the save operation default set name (ConsoleUI.set) is replaced with
+                // new name created base on current date.
+                // Set is the reloaded to make sure that 
+                // old test set with default name will not affect test execution
+                currSetName.Copy( iTestSetName );
+                ret = iMain->UIStore().SaveTestSet2( iTestSetName );
+                if( ret != KErrNone )
+                    {
+                    User::InfoPrint( _L("Test set saving failed at saving test set") );
+                    } 
+                
+                break;
+  
+  			default:          
+//            case ESetStartPar:   
+//                setType = CStartedTestSet::ESetParallel;
+//            case ESetStartSeq: 
+            //case ESetStartRep: 
+            	if( iPosOnScreen == ESetStartPar )
+                  {
+	            		setType = CStartedTestSet::ESetParallel;
+                  }
+              if( iPosOnScreen == ESetStartSeq || iPosOnScreen == ESetStartSeqNotRun)
+	                {
+	                RRefArray<CTestSetInfo> setInfos;
+	                ret = iMain->UIStore().TestSets( setInfos );
+	                if( (  ret != KErrNone ) ||
+	                    ( setInfos.Count() != 1 ) )
+	                    {
+	                    // Should never ever happen
+	                    User::Panic( KTestSetMenu, KErrGeneral );
+	                    }
+	                const CTestSetInfo& set = setInfos[0];
+	                setInfos.Reset();
+	                setInfos.Close();
+	                
+	                TInt index;
+	                ret = KErrGeneral;
+	                if(iPosOnScreen == ESetStartSeq)
+	                    {
+                        ret = iMain->UIStore().StartTestSet(set, index, setType);
+                        }
+                    else if(iPosOnScreen == ESetStartSeqNotRun)
+                        {
+	                    ret = iMain->UIStore().StartTestSet(set, index, setType, ETrue);
+	                    }
+	                if( ret != KErrNone )
+	                    {
+	                    User::InfoPrint( _L("Test set starting failed") );
+	                    }                 
+	                }    
+                break;
+            }
+        }
+        
+    return this;
+
+    }
+/**
+-------------------------------------------------------------------------------
+
+Class: CTestSetChoiceMenu
+
+Method: NewL
+
+Description: Constructs new menu.
+
+Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+            CMenu* aParent            :in:      Parent menu
+            const TDesC& aName        :in:      Menu name
+
+Return Values: CMenu*                           New menu
+
+Errors/Exceptions: Leaves if memory allocation fails
+                   Leaves if ConstructL leaves.
+
+Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetChoiceMenu* CTestSetChoiceMenu::NewL( CConsoleMain* aConsole,
+                                    CMenu* aParent,
+                                    const TDesC& aName )
+{    
+
+	CTestSetChoiceMenu* self = new ( ELeave ) CTestSetChoiceMenu();
+	CleanupStack::PushL( self );
+	self->ConstructL( aConsole, aParent, aName );
+	CleanupStack::Pop( self );
+	return self;
+
+}
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: CTestSetChoiceMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetChoiceMenu::CTestSetChoiceMenu()
+    
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: ~CTestSetChoiceMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestSetChoiceMenu::~CTestSetChoiceMenu()
+    {
+    
+    
+
+    iFileList.ResetAndDestroy();
+    iFileList.Close();
+
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor. 
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if module can't be appended to list
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetChoiceMenu::ConstructL( CConsoleMain* aConsole,
+                                  CMenu* aParent,
+                                  const TDesC& aName
+                                 )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetChoiceMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+   TInt ret = iMain->UIStore().GetTestSetsList( aArray );
+
+	if ( ret != KErrNone )
+		{
+		return ret;
+		}
+
+   iFileList.ResetAndDestroy();
+   TRAPD( err,
+	//Assign aArray to iFileList, it is used in LoadTestSet
+   for( TInt i=0 ; i < aArray.Count(); i++)
+	  {
+	  iFileList.AppendL(aArray[i].AllocL());
+	  }
+     ); // TRAPD
+   return err;       
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CTestSetChoiceMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestSetChoiceMenu::PrintMenuL( TUpdateType aType )
+    {
+    
+    iUpdateType = aType;
+    
+    TBuf<KMaxLineLength> line;
+    
+    // Clear display
+    iConsole->ClearScreen();
+
+    // Print menu title
+    Print( Name() );
+    
+    RRefArray<TDesC> texts;
+    if(  iMain->UIStore().GetTestSetsList( texts ) != KErrNone )
+        {
+        return;
+        }
+    
+    TInt oldItemCount = iItemCount;
+     
+    iItemCount = texts.Count();
+
+    // If first time in menu, update start and end positions
+    if( (iFirst == iLast) ||        // First time here..
+        ( iLast >= iItemCount ) ||
+        ( oldItemCount != iItemCount ) )      // Menu size changed
+        {
+        iLast = iItemCount - 1;
+        iPosOnScreen = 0;
+
+        // If "overflow", then adjust the end
+        if (iLast > iScreenSize )
+            {
+            iLast = iScreenSize;
+            }
+        }
+    
+    // Print items
+    for ( TInt i = iFirst; i <= iLast; i++ )
+        {
+        line.Zero();
+        
+        // Append text before line
+        AppendBefore( i, line );
+
+        // Get the menu line
+        LimitedAppend ( line, texts[i] );
+
+        // Print the line
+        Print(line);
+
+        }
+    texts.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle right arrow and enter
+                 here, others in parent menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetChoiceMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+    
+    //return CMenu::SelectL( aSelection, aContinue );    
+    //return iParent;
+	    MapKeyCode(aSelection);
+	    TInt ret = 0;
+
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {           
+                if(iPosOnScreen < iFileList.Count())
+                    {
+                    ret = iMain->UIStore().LoadTestSet( iFileList.operator [](iPosOnScreen)->Des() );
+                    if (ret == KErrNone)
+                        {
+                        ((CTestSetMenu*)iParent)->SetCreated();
+                        ((CTestSetMenu*)iParent)->SetTestSetFileName(iFileList.operator [](iPosOnScreen)->Des());
+                        }
+                    return iParent;
+                    }
+                else
+                    {
+                    return this;
+                    }
+                }
+            default:
+                break;
+            }
+            
+    return CMenu::SelectL( aSelection, aContinue );    
+
+    }
+
+
+
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetAddCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetAddCaseMenu* CTestSetAddCaseMenu::NewL( CConsoleMain* aConsole,
+                                            CMenu* aParent,
+                                            const TDesC& aName,
+                                            TDesC& aTestSetName )
+    {
+
+    CTestSetAddCaseMenu* self = 
+        new ( ELeave ) CTestSetAddCaseMenu( aTestSetName );
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetAddCaseMenu
+
+    Method: CTestSetAddCaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetAddCaseMenu::CTestSetAddCaseMenu( TDesC& aTestSetName ):
+    iTestSetName( aTestSetName )    
+    {
+    
+    iMenuItemsCount = EAddSelected + 1;
+    iMenuTotCount += iMenuItemsCount;
+    
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetAddCaseMenu
+
+    Method: ~CTestSetAddCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetAddCaseMenu::~CTestSetAddCaseMenu()
+    {
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetAddCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetAddCaseMenu::ConstructL( CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName )
+    {
+
+    CCaseStartMenu::ConstructL( aConsole, aParent, aName );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetAddCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetAddCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    if ( iSetFinished )
+        {
+        if( aArray.Append( KAddSelected ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    return CMultipleBaseMenu::ItemTexts( aArray );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetAddCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetAddCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    if ( iSetFinished )
+        {
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {
+
+                if ( iFirst + iPosOnScreen == EAddSelected )
+                    {
+                    TInt count = iTestCases.Count();    
+                    for( TInt i=0; i<count; i++ )
+                        {
+                        if ( iSetState[i] )
+                            {
+                            TInt ret = 
+                                iMain->UIStore().AddToTestSet( iTestSetName,
+                                                               iTestCases[i] );
+                            if( ret != KErrNone )
+                                {
+                                User::InfoPrint( _L("Test case adding failed") );
+                                }   
+                            }
+                        } 
+                    return iParent;
+                    }               
+                }
+                break;
+            default:
+                break;
+            }
+        }   
+        
+    return CMultipleBaseMenu::SelectL( aSelection, aContinue );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetAddCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetRemoveCaseMenu* CTestSetRemoveCaseMenu::NewL( CConsoleMain* aConsole,
+                                            CMenu* aParent,
+                                            const TDesC& aName,
+                                            TDesC& aTestSetName )
+    {
+
+    CTestSetRemoveCaseMenu* self = 
+        new ( ELeave ) CTestSetRemoveCaseMenu( aTestSetName );
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetRemoveCaseMenu
+
+    Method: CTestSetRemoveCaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetRemoveCaseMenu::CTestSetRemoveCaseMenu( TDesC& aTestSetName ):
+    iTestSetName( aTestSetName )    
+    {
+    
+    iMenuItemsCount = ERemoveSelected + 1;
+    iMenuTotCount += iMenuItemsCount;
+    
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetRemoveCaseMenu
+
+    Method: ~CTestSetRemoveCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetRemoveCaseMenu::~CTestSetRemoveCaseMenu()
+    {
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetRemoveCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetRemoveCaseMenu::ConstructL( CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName )
+    {
+
+    CCaseStartMenu::ConstructL( aConsole, aParent, aName );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetRemoveCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetRemoveCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+    if ( iSetFinished )
+        {
+        if( aArray.Append( KRemoveSelected ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    return CMultipleBaseMenu::ItemTexts( aArray );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetRemoveCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetRemoveCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    if ( iSetFinished )
+        {
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {
+
+                if ( iFirst + iPosOnScreen == ERemoveSelected )
+                    {
+                    TInt count = iTestCases.Count();    
+                    for( TInt i=0; i<count; i++ )
+                        {
+                        if ( iSetState[i] )
+                            {
+                            TInt ret = 
+                                iMain->UIStore().RemoveFromTestSet( iTestSetName,
+                                                                    iTestCases[i] );
+                            if( ret != KErrNone )
+                                {
+                                User::InfoPrint( _L("Test case adding failed") );
+                                }   
+                            }
+                        } 
+                    return iParent;
+                    }               
+                }
+                break;
+            default:
+                break;
+            }
+        }   
+        
+    return CMultipleBaseMenu::SelectL( aSelection, aContinue );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetRemoveCaseMenu
+
+    Method: UpdateTestCases
+
+    Description: 
+
+    Parameters: 
+
+    Return Values: 
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetRemoveCaseMenu::UpdateTestCases()
+    {
+    
+    TRAPD( err,
+        const CTestSetInfo& set = iMain->UIStore().TestSetL( iTestSetName );                
+        const RRefArray<const CTestInfo>& testCases = set.TestCases();
+
+        // Update test cases
+        iTestCases.Reset();
+        iSetState.Reset();
+        
+        TInt count = testCases.Count();
+        for( TInt i=0; i<count; i++ )
+            {
+            err = iTestCases.Append( testCases[i] );
+            if( err != KErrNone )
+                {
+                break;
+                }
+            }
+
+        ); // TRAPD
+                
+    return err;
+                
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestSetMenu* CStartedTestSetMenu::NewL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName )
+    {
+
+    CStartedTestSetMenu* self = new ( ELeave ) CStartedTestSetMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: CStartedTestSetMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestSetMenu::CStartedTestSetMenu()
+    {
+    iType = CUIStoreIf::ESetAll;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if memory allocation fails
+                       Leaves if CCaseOperation menu NewL leaves
+                       Leaves if UpcateCaseListL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CStartedTestSetMenu::ConstructL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: ~CStartedTestSetMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CStartedTestSetMenu::~CStartedTestSetMenu()
+    {
+
+    delete iCaseMenu;
+    iCaseMenu = 0;
+    
+    iTestSets.Reset();
+    iTestSets.Close();
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStartedTestSetMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    iTestSets.Reset();
+    
+    TInt ret = iMain->UIStore().StartedTestSets( iTestSets, iType );
+    if ( ret != KErrNone )
+    	{
+    	return ret;
+    	}
+
+    TInt count = iTestSets.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aArray.Append( iTestSets[i].TestSetInfo().Name() ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CStartedTestSetMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number 
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CStartedTestSetMenu::AppendBefore( TInt aLineNum, TDes& aLine )
+    {
+    
+    CMenu::AppendBefore( aLineNum, aLine );
+    
+    if( ( aLine.MaxLength() - aLine.Length() ) < 2 )
+        {
+        return;
+        }        
+    if( iTestSets[aLineNum].Status() & CUIStoreIf::ESetRunning )
+        {
+        aLine.Append( _L("O ") );
+        }
+    else if( iTestSets[aLineNum].Status() & CUIStoreIf::ESetPassed )
+        {
+        aLine.Append( _L("P ") );
+        }    
+    else if( iTestSets[aLineNum].Status() & CUIStoreIf::ESetFailed )
+        {
+        aLine.Append( _L("F ") );
+        }    
+            
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle Enter and Right Arrow
+    here, other will be handled in CMenu::SelectL
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CStartedTestSetMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    switch (aSelection)
+        {
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            if ( iFirst + iPosOnScreen < iTestSets.Count() )
+                {
+                delete iCaseMenu;
+                iCaseMenu = 0;
+                iCaseMenu = CTestSetCaseMenu::NewL( 
+                    iMain, 
+                    this, 
+                    iTestSets[iFirst + iPosOnScreen].TestSetInfo().Name(), 
+                    iTestSets[iFirst + iPosOnScreen] ); 
+
+                return iCaseMenu;
+                }
+            }
+            return this;
+        default:
+            break;
+        }   
+        
+    // Let the parent class handle rest
+    return CMenu::SelectL(aSelection, aContinue);
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetCaseMenu* CTestSetCaseMenu::NewL( CConsoleMain* aConsole, 
+                                          CMenu* aParent, 
+                                          const TDesC& aName,
+                                          CStartedTestSet& aTestSet  )
+    {
+
+    CTestSetCaseMenu* self = new ( ELeave ) CTestSetCaseMenu( aTestSet );
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: CTestSetCaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetCaseMenu::CTestSetCaseMenu( CStartedTestSet& aTestSet ):
+    iTestSet( aTestSet )
+    {
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if memory allocation fails
+                       Leaves if CCaseOperation menu NewL leaves
+                       Leaves if UpcateCaseListL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetCaseMenu::ConstructL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName )
+    {
+
+    CCaseMenu::ConstructL( aConsole, aParent, aName, 
+                           CUIStoreIf::EStatusAll );
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: ~CTestSetCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestSetCaseMenu::~CTestSetCaseMenu()
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    if ( iTestSet.Status() & CUIStoreIf::ESetRunning )
+        {
+        if( aArray.Append( KCancelTestSet ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    const RRefArray<CStartedTestCase>& testCases = iTestSet.TestCases();
+        
+    iTestCases.Reset();
+    
+    TInt count = testCases.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( iTestCases.Append( testCases[i] ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }  
+        if( aArray.Append( testCases[i].TestInfo().TestCaseTitle() ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }   
+        }
+
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CTestSetCaseMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number 
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestSetCaseMenu::AppendBefore( TInt aLineNum, TDes& aLine )
+    {
+    
+    CMenu::AppendBefore( aLineNum, aLine );
+   
+    TInt testCaseNum = aLineNum; 
+    if( iTestSet.Status() & CUIStoreIf::ESetRunning ) 
+        {
+        if( aLineNum == 0 )
+            {
+            // "Cancel test set" row
+            return;
+            }
+        testCaseNum--;
+        }
+        
+    if( ( aLine.MaxLength() - aLine.Length() ) < 2 )
+        {
+        return;
+        }        
+    
+   if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusRunning )
+        {
+        aLine.Append( _L("O ") );
+        }
+    else if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusPassed )
+        {
+        aLine.Append( _L("P ") );
+        }
+    else if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusFailed )
+        {
+        aLine.Append( _L("F ") );
+        }
+    else if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusAborted )
+        {
+        aLine.Append( _L("A ") );
+        }
+    else if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusCrashed )
+        {
+        aLine.Append( _L("C ") );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+    
+    MapKeyCode(aSelection);
+
+    if( ( aSelection == EKeyEnter ) || ( aSelection == EKeyRightArrow ) )
+        {
+        TInt pos = iFirst + iPosOnScreen; 
+        if( iTestSet.Status() & CUIStoreIf::ESetRunning )
+            {
+            pos--;
+            }               
+        if( pos == -1 )
+            {
+            User::LeaveIfError( 
+                iMain->UIStore().AbortTestSet( iTestSet ) );
+            return iParent;             
+            }
+        else if( pos < iTestCases.Count() )
+            {
+            delete iCaseOperationMenu;
+            iCaseOperationMenu = 0;
+            iCaseOperationMenu = CCaseOperationMenu::NewL( 
+                iMain, 
+                this, 
+                iTestCases[pos].TestInfo().TestCaseTitle(), 
+                &iTestCases[pos] ); 
+
+            return iCaseOperationMenu;
+            }
+        }
+
+        // Let the parent class handle rest
+    return CMenu::SelectL(aSelection, aContinue);
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CFilterMenu* CFilterMenu::NewL(CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName)
+    {
+    CFilterMenu* self = new (ELeave) CFilterMenu();
+    CleanupStack::PushL(self);
+    self->ConstructL(aConsole, aParent, aName);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CFilterMenu::ConstructL(CConsoleMain* aConsole,
+                             CMenu* aParent,
+                             const TDesC& aName
+                            )
+    {
+    CMenu::ConstructL(aConsole, aParent, aName);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CFilterMenu
+
+    Method: CFilterMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CFilterMenu::CFilterMenu()
+    {
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    CFilterMenu
+
+    Method: ~CFilterMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CFilterMenu::~CFilterMenu()
+    {
+    delete iTestCaseMenu;
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CFilterMenu::ItemTexts(RRefArray<TDesC>& aArray)
+    {
+    const RPointerArray<TDesC> &filters = iMain->GetFilterArray();
+    TInt ret;
+    
+    TInt count = filters.Count();
+    for(TInt i = 0; i < count; i++)
+        {    
+        ret = aArray.Append(*filters[i]);
+        if(ret != KErrNone)
+            {
+            return ret;
+            }
+        }
+        
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CFilterMenu::SelectL(TKeyCode aSelection, TBool& aContinue)
+    {
+    const RPointerArray<TDesC> &filters = iMain->GetFilterArray();
+    
+    MapKeyCode(aSelection);
+    
+    switch ( aSelection )
+        {
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            // Start the case
+            if((iFirst + iPosOnScreen) < filters.Count())
+                {
+                // Show test cases menu
+                iMain->SetFilterIndex(iFirst + iPosOnScreen);
+                if(iTestCaseMenu)
+                    {
+                    return iTestCaseMenu;
+                    }
+                else
+                    {
+                    RDebug::Print(_L("STIF: CFilterMenu::SelectL: test case menu is not set, however it should be"));
+                    return this;
+                    }
+                }
+            else
+                {
+                return this;
+                }
+            }
+
+        default:
+            return CMenu::SelectL( aSelection, aContinue);
+        }
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: SetTestCaseMenu
+
+    Description: Set pointer to test case menu, so it can be shown when user
+                 selects filter.
+                 This menu will be deleted along with the filter menu.
+
+    Parameters: CMenu* aTestCaseMenu      :in:      test case menu
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CFilterMenu::SetTestCaseMenu(CMenu* aTestCaseMenu)
+    {
+    if(iTestCaseMenu)
+        {
+        RDebug::Print(_L("STIF: CFilterMenu::SetTestCaseMenu: test case menu is already set!"));
+        delete iTestCaseMenu;
+        iTestCaseMenu = NULL;
+        }
+    iTestCaseMenu = aTestCaseMenu;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/DemoModule/BMARM/Demomoduleu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	LibEntryL__Fv @ 1 NONAME R3UNUSED ; LibEntryL(void)
+	SetRequirements__FRP16CTestModuleParamRUl @ 2 NONAME R3UNUSED ; SetRequirements(CTestModuleParam *&, unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/DemoModule/BWINS/Demomoduleu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	?LibEntryL@@YAPAVCTestModuleBase@@XZ @ 1 NONAME ; class CTestModuleBase * __cdecl LibEntryL(void)
+	?SetRequirements@@YAHAAPAVCTestModuleParam@@AAK@Z @ 2 NONAME ; int __cdecl SetRequirements(class CTestModuleParam * &,unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/DemoModule/eabi/Demomoduleu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	_Z9LibEntryLv @ 1 NONAME
+	_Z15SetRequirementsRP16CTestModuleParamRm @ 2 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/DemoModule/group/Demomodule.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Demomodule.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET      Demomodule.dll
+TARGETTYPE  dll
+DEFFILE     Demomodule.def
+
+CAPABILITY	ALL -TCB
+VENDORID 	0x101FB657
+SECUREID        0x102073DB
+
+USERINCLUDE     ../inc 
+USERINCLUDE     ../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          DemoModule.cpp
+SOURCE          Demomodulecases.cpp
+
+LIBRARY     euser.lib
+LIBRARY     stiftestinterface.lib
+LIBRARY     stiftestengine.lib
+
+// First UID is DLL UID, Second UID is STIF Test Framework UID
+UID             0x1000008D 0x101FB3E7
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/DemoModule/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	Build information for STIF Test Framework's DemoModule.
+*/
+
+PRJ_PLATFORMS
+
+	DEFAULT
+
+PRJ_TESTEXPORTS
+
+PRJ_EXPORTS
+
+PRJ_TESTMMPFILES
+
+PRJ_MMPFILES
+
+	Demomodule.mmp
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/DemoModule/inc/DemoModule.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,327 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of DemoModule of 
+* STIF TestFramework.
+*
+*/
+
+#ifndef DEMOMODULE_H
+#define DEMOMODULE_H
+
+// INCLUDES
+#include "StifTestModule.h"
+#include <StifLogger.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// Logging path
+_LIT( KDemoModuleLogPath, "\\logs\\testframework\\DemoModule\\" ); 
+// Log file
+_LIT( KDemoModuleLogFile, "DemoModule.txt" ); 
+_LIT( KDemoModuleLogFileWithTitle, "DemoModule_[%S].txt" ); 
+
+// Function pointer related internal definitions
+#define GETPTR &  
+#define ENTRY(str,func) {_S(str), GETPTR func,0,0,0}
+#define FUNCENTRY(func) {_S(#func), GETPTR func,0,0,0}
+#define OOM_ENTRY(str,func,a,b,c) {_S(str), GETPTR func,a,b,c}
+#define OOM_FUNCENTRY(func,a,b,c) {_S(#func), GETPTR func,a,b,c}
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CDemoModule;
+
+// DATA TYPES
+// None
+
+// A typedef for function that does the actual testing,
+// function is a type 
+// TInt CDemoModule::<NameOfFunction> ( TTestResult& aResult )
+typedef TInt (CDemoModule::* TestFunction)(TTestResult&);    
+
+// CLASS DECLARATION
+
+/**
+*  An internal structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TCaseInfoInternal
+    {
+    public:
+        const TText* iCaseName;
+        TestFunction iMethod;
+        TBool           iIsOOMTest;
+        TInt            iFirstMemoryAllocation;
+        TInt            iLastMemoryAllocation;
+    };
+
+// CLASS DECLARATION
+
+/**
+*  A structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TCaseInfo
+    {
+    public:
+        TPtrC iCaseName;    
+        TestFunction iMethod;
+        TBool           iIsOOMTest;
+        TInt            iFirstMemoryAllocation;
+        TInt            iLastMemoryAllocation;
+
+    TCaseInfo( const TText* a ) : iCaseName( (TText*) a )
+        {        
+        };
+
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  This a DemoModule class.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS(CDemoModule) : public CTestModuleBase
+    {
+    public:  // Constructors and destructor
+
+
+        /**
+        * Two-phased constructor.
+        */
+        static CDemoModule* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CDemoModule();
+
+    public: // New functions
+    // None
+
+    public: // Functions from base classes
+
+        /**
+        * From CTestModuleBase InitL is used to initialize the 
+        *       DemoModule. It is called once for every instance of 
+        *       TestModuleDemoModule after its creation.
+        * @since ?Series60_version
+        * @param aIniFile Initialization file for the test module (optional)
+        * @param aFirstTime Flag is true when InitL is executed for first 
+        *               created instance of DemoModule.
+        * @return Symbian OS error code
+        */
+        TInt InitL( TFileName& aIniFile, TBool aFirstTime );
+
+        /**
+        * From CTestModuleBase GetTestCasesL is used to inquiry test cases 
+        *   from DemoModule. 
+        * @since ?Series60_version
+        * @param aTestCaseFile Test case file (optional)
+        * @param aTestCases  Array of TestCases returned to test framework
+        * @return Symbian OS error code
+        */
+        TInt GetTestCasesL( const TFileName& aTestCaseFile, 
+                            RPointerArray<TTestCaseInfo>& aTestCases );
+    
+        /**
+        * From CTestModuleBase RunTestCaseL is used to run an individual 
+        *   test case. 
+        * @since ?Series60_version
+        * @param aCaseNumber Test case number
+        * @param aTestCaseFile Test case file (optional)
+        * @param aResult Test case result returned to test framework (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error, which is 
+        *           not reported in aResult parameter as test case failure).
+        */   
+        TInt RunTestCaseL( const TInt aCaseNumber, 
+                           const TFileName& aTestCaseFile,
+                           TTestResult& aResult );
+
+        /**
+        * From CTestModuleBase; OOMTestQueryL is used to specify is particular
+        * test case going to be executed using OOM conditions
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailureType OOM failure type (optional)
+        * @param aFirstMemFailure The first heap memory allocation failure value (optional)
+        * @param aLastMemFailure The last heap memory allocation failure value (optional)
+        * @return TBool
+        */
+        virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */, 
+                                     const TInt /* aCaseNumber */, 
+                                     TOOMFailureType& aFailureType,
+                                     TInt& /* aFirstMemFailure */, 
+                                     TInt& /* aLastMemFailure */ );
+
+        /**
+        * From CTestModuleBase; OOMTestInitializeL may be used to initialize OOM
+        * test environment
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        */
+        virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */, 
+                                    const TInt /* aCaseNumber */ ); 
+        /**
+        * From CTestModuleBase; OOMTestFinalizeL may be used to finalize OOM
+        * test environment
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        */
+        virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */, 
+                                       const TInt /* aCaseNumber */ );
+
+        /**
+        * From CTestModuleBase; OOMHandleWarningL
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailNextValue FailNextValue for OOM test execution (optional)
+        * @return None
+        */
+        virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
+                                        const TInt /* aCaseNumber */, 
+                                        TInt& /* aFailNextValue */);
+    protected:  // New functions    
+    // None
+
+    protected:  // Functions from base classes
+    // None
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CDemoModule();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+        /**
+        * Function returning test case name and pointer to test case function.
+        * @since ?Series60_version
+        * @param aCaseNumber test case number
+        * @return TCaseInfo 
+        */
+        const TCaseInfo Case ( const TInt aCaseNumber ) const;
+
+        /**
+        * Simple math calculation test.
+        */
+        TInt SimpleMathTest( TTestResult& aResult );
+
+        /**
+        * Math calculation test.
+        */
+        TInt MathTest( TTestResult& aResult );
+
+        /**
+        * Actual Hardcoded test case functions are listed below.
+        */
+
+        /**
+        * Printing test case.
+        * @since ?Series60_version
+        * @param aResult Test case result (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error 
+        *   that is not returned as test case result in aResult)
+        */
+        TInt PrintTest( TTestResult& aResult );
+
+        /**
+        * Printing loop test case.
+        * @since ?Series60_version
+        * @param aResult Test case result (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error 
+        *   that is not returned as test case result in aResult)
+        */
+        TInt LoopTest( TTestResult& aResult );
+
+        /**
+        * Test case for heap memory allocation
+        * @since ?Series60_version
+        * @param aResult Test case result (PASS/FAIL)
+        * @return panic or Symbian OS error code (test case execution error 
+        *   that is not returned as test case result in aResult)
+        */
+        TInt HeapMemoryAllocation( TTestResult& aResult );
+
+    public:     // Data
+    // None
+
+    protected:  // Data
+    // None
+
+    private:    // Data
+        // Pointer to test (function) to be executed
+        TestFunction iMethod;
+
+        // Pointer to logger
+        CStifLogger * iLog;
+
+        // Normal logger
+        CStifLogger* iStdLog;
+
+        // Test case logger
+        CStifLogger* iTCLog;
+
+        // Flag saying if test case title should be added to log file name
+        TBool iAddTestCaseTitleToLogName;
+
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+    // None
+
+    protected:  // Friend classes
+    // None
+
+    private:    // Friend classes
+    // None
+
+    };
+
+#endif      // DEMOMODULE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/DemoModule/src/DemoModule.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,594 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file (DemoModule.cpp) contains all test 
+* framework related parts of this test module. Actual test cases 
+* are implemented in file DemoModuleCases.cpp.
+*
+* CTestModuleDemo is an example of test module implementation. This example
+* uses hard coded test cases (i.e it does not have any test case
+* configuration file).
+*
+* Example uses function pointers to call test cases. This provides an easy
+* method to add new test cases.
+*
+* See function Cases in file DemoModuleCases.cpp for instructions how to
+* add new test cases. It is not necessary to modify this file when adding
+* new test cases.
+*
+* To take this module into use, add following lines to test framework
+* initialisation file:
+*
+* # Demo module
+* [New_Module]
+* ModuleName= DemoModule
+* [End_Module]
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "DemoModule.h"
+#include <e32math.h>
+#include "SettingServerClient.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: CDemoModule
+
+    Description: C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CDemoModule::CDemoModule()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: ConstructL
+
+    Description: Symbian 2nd phase constructor that can leave.
+
+    Note: If OOM test case uses STIF Logger, then STIF Logger must be created
+    with static buffer size parameter (aStaticBufferSize). Otherwise Logger 
+    allocates memory from heap and therefore causes error situations with OOM 
+    testing. For more information about STIF Logger construction, see STIF 
+    Users Guide.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CDemoModule::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+    iAddTestCaseTitleToLogName = loggerSettings.iAddTestCaseTitle;
+    
+    // Constructing static buffer size logger, needed with OOM testing because
+    // normally logger allocates memory from heap!
+    iStdLog = CStifLogger::NewL( KDemoModuleLogPath, 
+                              KDemoModuleLogFile,
+                              CStifLogger::ETxt,
+                              CStifLogger::EFile,
+                              ETrue,
+                              ETrue,
+                              ETrue,
+                              EFalse,
+                              ETrue,
+                              EFalse,
+                              100 );
+    iLog = iStdLog;
+    
+    // Sample how to use logging
+    _LIT( KLogInfo, "DemoModule logging starts!" );
+    iLog->Log( KLogInfo );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleDemo
+
+    Method: NewL
+
+    Description: Two-phased constructor. Constructs new CTestModuleDemo
+    instance and returns pointer to it.
+
+    Parameters:    None
+
+    Return Values: CTestModuleDemo*: new object.
+
+    Errors/Exceptions: Leaves if memory allocation fails or ConstructL leaves.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CDemoModule* CDemoModule::NewL()
+    {
+    CDemoModule* self = new (ELeave) CDemoModule;
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleDemo
+
+    Method: ~CTestModuleDemo
+
+    Description: Destructor.
+
+    Parameters:    None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CDemoModule::~CDemoModule()
+    { 
+    iLog = NULL;
+    delete iStdLog;
+    iStdLog = NULL;
+    delete iTCLog;
+    iTCLog = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CTestModuleDemo
+
+    Method: InitL
+
+    Description: Method for test case initialization
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+-------------------------------------------------------------------------------
+*/
+TInt CDemoModule::InitL( TFileName& /*aIniFile*/, 
+                         TBool /*aFirstTime*/ )
+    {
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleDemo
+
+    Method: GetTestCases
+
+    Description: GetTestCases is used to inquire test cases 
+    from the test module. Because this test module has hard coded test cases
+    (i.e cases are not read from file), paramter aConfigFile is not used.
+
+    This function loops through all cases defined in Cases() function and 
+    adds corresponding items to aTestCases array.
+
+    Parameters: const TFileName&  : in: Configuration file name. Not used                                                       
+                RPointerArray<TTestCaseInfo>& aTestCases: out: 
+                      Array of TestCases.
+    
+    Return Values: KErrNone: No error
+
+    Errors/Exceptions: Function leaves if any memory allocation operation fails
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/      
+TInt CDemoModule::GetTestCasesL( const TFileName& /*aConfig*/, 
+                                 RPointerArray<TTestCaseInfo>& aTestCases )
+    {
+    // Loop through all test cases and create new
+    // TTestCaseInfo items and append items to aTestCase array    
+    for( TInt i = 0; Case(i).iMethod != NULL; i++ )
+        {
+        // Allocate new TTestCaseInfo from heap for a testcase definition.
+        TTestCaseInfo* newCase = new( ELeave ) TTestCaseInfo();
+    
+        // PushL TTestCaseInfo to CleanupStack.    
+        CleanupStack::PushL( newCase );
+
+        // Set number for the testcase.
+        // When the testcase is run, this comes as a parameter to RunTestCaseL.
+        newCase->iCaseNumber = i;
+
+        // Set title for the test case. This is shown in UI to user.
+        newCase->iTitle.Copy( Case(i).iCaseName );
+
+        // Append TTestCaseInfo to the testcase array. After appended 
+        // successfully the TTestCaseInfo object is owned (and freed) 
+        // by the TestServer. 
+        User::LeaveIfError(aTestCases.Append ( newCase ) );
+        
+        // Pop TTestCaseInfo from the CleanupStack.
+        CleanupStack::Pop( newCase );
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleDemo
+
+    Method: RunTestCase
+
+    Description: Run a specified testcase.
+
+    Function runs a test case specified by test case number. Test case file
+    parameter is not used.
+
+    If case number is valid, this function runs a test case returned by
+    function Cases(). 
+
+    Parameters: const TInt aCaseNumber: in: Testcase number 
+                const TFileName& : in: Configuration file name. Not used
+                TTestResult& aResult: out: Testcase result
+
+    Return Values: KErrNone: Testcase ran.
+                   KErrNotFound: Unknown testcase
+
+    Errors/Exceptions: None
+    
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CDemoModule::RunTestCaseL( const TInt aCaseNumber,
+                                const TFileName& /* aConfig */,
+                                TTestResult& aResult )
+    {
+    // Return value
+    TInt execStatus = KErrNone;
+
+    // Get the pointer to test case function
+    TCaseInfo tmp = Case ( aCaseNumber );
+
+    _LIT( KLogInfo, "Starting testcase [%S]" );
+    iLog->Log( KLogInfo, &tmp.iCaseName);
+
+    // Check that case number was valid
+    if ( tmp.iMethod != NULL )
+        {
+        //Open new log file with test case title in file name
+        if(iAddTestCaseTitleToLogName)
+            {
+            //delete iLog; //Close currently opened log
+            //iLog = NULL;
+            //Delete test case logger if exists
+            if(iTCLog)
+                {
+                delete iTCLog;
+                iTCLog = NULL;
+                }
+                
+            TFileName logFileName;
+            TName title;
+            TestModuleIf().GetTestCaseTitleL(title);
+        
+            logFileName.Format(KDemoModuleLogFileWithTitle, &title);
+
+            iTCLog = CStifLogger::NewL(KDemoModuleLogPath, 
+                                     logFileName,
+                                     CStifLogger::ETxt,
+                                     CStifLogger::EFile,
+                                     ETrue,
+                                     ETrue,
+                                     ETrue,
+                                     EFalse,
+                                     ETrue,
+                                     EFalse,
+                                     100);
+            iLog = iTCLog;
+            }
+
+        // Valid case was found, call it via function pointer
+        iMethod = tmp.iMethod;        
+        //execStatus  = ( this->*iMethod )( aResult );
+        TRAPD(err, execStatus  = ( this->*iMethod )( aResult ));
+        if(iAddTestCaseTitleToLogName)
+            {
+            //Restore standard log and destroy test case logger
+            iLog = iStdLog;
+            delete iTCLog; //Close currently opened log
+            iTCLog = NULL;
+            }
+        User::LeaveIfError(err);
+        
+        }
+    else
+        {
+        // Valid case was not found, return error.
+        execStatus = KErrNotFound;
+        }
+
+    // Return case execution status (not the result of the case execution)
+    return execStatus;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: OOMTestQueryL
+
+    Description: Checks test case information for OOM execution. 
+
+    Return Values: TBool
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CDemoModule::OOMTestQueryL( const TFileName& /* aTestCaseFile */, 
+                                  const TInt aCaseNumber, 
+                                  TOOMFailureType& /* aFailureType */, 
+                                  TInt& aFirstMemFailure, 
+                                  TInt& aLastMemFailure ) 
+    {
+    _LIT( KLogInfo, "CDemoModule::OOMTestQueryL" );
+    iLog->Log( KLogInfo ); 
+
+    aFirstMemFailure = Case( aCaseNumber ).iFirstMemoryAllocation;
+    aLastMemFailure = Case( aCaseNumber ).iLastMemoryAllocation;
+
+    return Case( aCaseNumber ).iIsOOMTest;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: OOMTestInitializeL
+
+    Description: Used to perform the test environment setup for a particular
+    OOM test case. Test Modules may use the initialization file to read 
+    parameters for Test Module initialization but they can also have their own
+    configure file or some other routine to initialize themselves. 
+
+    NOTE: User may add implementation for OOM test environment initialization.
+    Usually no implementation is required.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CDemoModule::OOMTestInitializeL( const TFileName& /* aTestCaseFile */, 
+                                      const TInt /* aCaseNumber */ )
+    {
+    _LIT( KLogInfo, "CDemoModule::OOMTestInitializeL" );
+    iLog->Log( KLogInfo ); 
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: OOMHandleWarningL
+
+    Description: Used in OOM testing to provide a way to the derived TestModule 
+    to handle warnings related to non-leaving or TRAPped allocations.
+
+    In some cases the allocation should be skipped, either due to problems in 
+    the OS code or components used by the code being tested, or even inside the
+    tested components which are implemented this way on purpose (by design), so
+    it is important to give the tester a way to bypass allocation failures.
+
+    NOTE: User may add implementation for OOM test warning handling. Usually no
+    implementation is required.    
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CDemoModule::OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
+                                     const TInt /* aCaseNumber */, 
+                                     TInt& /* aFailNextValue */ )
+    {
+    _LIT( KLogInfo, "CDemoModule::OOMHandleWarningL" );
+    iLog->Log( KLogInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: OOMTestFinalizeL
+
+    Description: Used to perform the test environment cleanup for a particular OOM 
+    test case.
+
+    NOTE: User may add implementation for OOM test environment finalization.
+    Usually no implementation is required.   
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CDemoModule::OOMTestFinalizeL( const TFileName& /* aTestCaseFile */, 
+                                    const TInt /* aCaseNumber */ )
+    {
+    _LIT( KLogInfo, "CDemoModule::OOMTestFinalizeL" );
+    iLog->Log( KLogInfo );
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point
+// Returns: CTestModuleBase*: Pointer to Test Module object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CTestModuleBase* LibEntryL()
+    {
+    return CDemoModule::NewL();
+
+    }
+
+// -----------------------------------------------------------------------------
+// SetRequirements handles test module parameters(implements evolution
+// version 1 for test module's heap and stack sizes configuring).
+// Returns: TInt: Symbian error code.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt SetRequirements( CTestModuleParam*& /*aTestModuleParam*/, 
+                                TUint32& /*aParameterValid*/ )
+    {
+
+    /* --------------------------------- NOTE ---------------------------------
+    USER PANICS occurs in test thread creation when:
+    1) "The panic occurs when the value of the stack size is negative."
+    2) "The panic occurs if the minimum heap size specified is less
+       than KMinHeapSize".
+       KMinHeapSize: "Functions that require a new heap to be allocated will
+       either panic, or will reset the required heap size to this value if
+       a smaller heap size is specified".
+    3) "The panic occurs if the minimum heap size specified is greater than
+       the maximum size to which the heap can grow".
+    Other:
+    1) Make sure that your hardware or Symbian OS is supporting given sizes.
+       e.g. Hardware might support only sizes that are divisible by four.
+    ------------------------------- NOTE end ------------------------------- */
+
+    // Normally STIF uses default heap and stack sizes for test thread, see:
+    // KTestThreadMinHeap, KTestThreadMinHeap and KStackSize.
+    // If needed heap and stack sizes can be configured here by user. Remove
+    // comments and define sizes.
+
+/*
+    aParameterValid = KStifTestModuleParameterChanged;
+
+    CTestModuleParamVer01* param = CTestModuleParamVer01::NewL();
+    // Stack size
+    param->iTestThreadStackSize= 16384; // 16K stack
+    // Heap sizes
+    param->iTestThreadMinHeap = 4096;   // 4K heap min
+    param->iTestThreadMaxHeap = 1048576;// 1M heap max
+
+    aTestModuleParam = param;
+*/
+    return KErrNone;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/DemoModule/src/Demomodulecases.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,495 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* CTestModuleDemo class member functions that does the actual 
+* tests.
+*
+*/
+
+// INCLUDE FILES
+#include <e32math.h>
+#include "DemoModule.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: Case
+
+    Description: Returns a test case by number.
+
+    This function contains an array of all available test cases 
+    i.e pair of case name and test function. If case specified by parameter
+    aCaseNumber is found from array, then that item is returned.
+
+    The reason for this rather complicated function is to specify all the
+    test cases only in one place. It is not necessary to understand how
+    function pointers to class member functions works when adding new test
+    cases. See function body for instructions how to add new test case.
+    
+    Parameters:    const TInt aCaseNumber :in:      Test case number
+
+    Return Values: const TCaseInfo Struct containing case name & function
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/ 
+const TCaseInfo CDemoModule::Case ( 
+    const TInt aCaseNumber ) const 
+     {
+
+    /*
+    * To add new test cases, implement new test case function and add new 
+    * line to KCases array specify the name of the case and the function 
+    * doing the test case
+    * In practice, do following
+    *
+    * 1) Make copy of existing test case function and change its name
+    *    and functionality. Note that the function must be added to 
+    *    OOMHard.cpp file and to OOMHard.h 
+    *    header file.
+    *
+    * 2) Add entry to following KCases array either by using:
+    *
+    * 2.1: FUNCENTRY or ENTRY macro
+    * ENTRY macro takes two parameters: test case name and test case 
+    * function name.
+    *
+    * FUNCENTRY macro takes only test case function name as a parameter and
+    * uses that as a test case name and test case function name.
+    *
+    * Or
+    *
+    * 2.2: OOM_FUNCENTRY or OOM_ENTRY macro. Note that these macros are used
+    * only with OOM (Out-Of-Memory) testing!
+    *
+    * OOM_ENTRY macro takes five parameters: test case name, test case 
+    * function name, TBool which specifies is method supposed to be run using
+    * OOM conditions, TInt value for first heap memory allocation failure and 
+    * TInt value for last heap memory allocation failure.
+    * 
+    * OOM_FUNCENTRY macro takes test case function name as a parameter and uses
+    * that as a test case name, TBool which specifies is method supposed to be
+    * run using OOM conditions, TInt value for first heap memory allocation 
+    * failure and TInt value for last heap memory allocation failure. 
+    */ 
+
+    static TCaseInfoInternal const KCases[] =
+        {
+        // To add new test cases, add new items to this array
+        
+        // NOTE: When compiled to GCCE, there must be Classname::
+        // declaration in front of the method name, e.g. 
+        // CDemoModule::PrintTest. Otherwise the compiler
+        // gives errors.
+                
+        ENTRY( "Loop test", CDemoModule::LoopTest ),
+        ENTRY( "Simple math test", CDemoModule::SimpleMathTest ),
+        ENTRY( "Math test", CDemoModule::MathTest ),
+        ENTRY( "Print test", CDemoModule::PrintTest ),
+        // Example how to use OOM functionality
+        OOM_ENTRY( "Heap memory allocation with OOM (aborts)", CDemoModule::HeapMemoryAllocation, ETrue, 1, 2 ),
+        ENTRY( "Heap memory allocation (passes)", CDemoModule::HeapMemoryAllocation )
+        };
+
+    // Verify that case number is valid
+    if( (TUint) aCaseNumber >= sizeof( KCases ) / 
+                               sizeof( TCaseInfoInternal ) )
+        {
+
+        // Invalid case, construct empty object
+        TCaseInfo null( (const TText*) L"" );
+        null.iMethod = NULL;
+        null.iIsOOMTest = EFalse;
+        null.iFirstMemoryAllocation = 0;
+        null.iLastMemoryAllocation = 0;
+        return null;
+
+        } 
+
+    // Construct TCaseInfo object and return it
+    TCaseInfo tmp ( KCases[ aCaseNumber ].iCaseName );
+    tmp.iMethod = KCases[ aCaseNumber ].iMethod;
+    tmp.iIsOOMTest = KCases[ aCaseNumber ].iIsOOMTest;
+    tmp.iFirstMemoryAllocation = KCases[ aCaseNumber ].iFirstMemoryAllocation;
+    tmp.iLastMemoryAllocation = KCases[ aCaseNumber ].iLastMemoryAllocation;
+    return tmp;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: SimpleMathTest
+
+    Description: Simple Math testing.
+
+    Parameters:  TTestResult& aErrorDescription: out:   
+                    Test result and on error case a short description of error
+
+    Return Values: TInt: Always KErrNone to indicate that test was valid
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CDemoModule::SimpleMathTest( TTestResult& aResult )
+    {
+    /* Test with mathematic calculations and printing */
+    _LIT( KDefinion , "RunTestCase");
+    _LIT( KData , "Simple Math calculations");
+    TestModuleIf().Printf( 0, KDefinion, KData );
+
+    // Random number.
+    TReal num = Math::Random(); 
+    // Intermediate result
+    TReal sqrt = 0;
+    // Result
+    TReal result = 0;
+
+    // Take square root of the number
+    TInt ret = Math::Sqrt( sqrt, num );
+    if( ret != KErrNone )
+        {
+        // Return error if Sqrt failed
+        _LIT( KResult ,"Math::Sqrt failed");
+        aResult.iResultDes.Copy( KResult );
+        aResult.iResult = KErrGeneral;
+
+        // Case was executed but failed
+        return KErrNone;
+        }
+
+    // Take power of two from the previous result
+    ret = Math::Pow( result, sqrt, 2 );
+    if( ret != KErrNone )
+        {
+        // Return error if Pow failed
+        _LIT( KResult ,"Math::Pow failed");
+        aResult.iResultDes.Copy( KResult );
+        aResult.iResult = KErrGeneral;
+        
+        // Case was executed but failed
+        return KErrNone;
+        }
+
+    // Compare final result to the original value, 
+    // rounded values should usually be same.
+    TInt32 a1;
+    TInt32 a2;
+    TInt r = Math::Int(a1, result);
+
+    if (r != KErrNone )
+        {
+        _LIT( KResult ,"1st conversion failed");
+        aResult.iResultDes.Copy( KResult );
+        aResult.iResult = r;
+        return KErrNone;
+        }
+
+    r = Math::Int(a2, num);
+    if (r != KErrNone )
+        {
+        _LIT( KResult ,"2nd conversion failed");
+        aResult.iResultDes.Copy( KResult );
+        aResult.iResult = r;
+        return KErrNone;
+        }
+
+    if(  a1 != a2 )
+        {
+        _LIT( KResult ,"Calculation doesn't match");
+        // Return error if comparison failed
+        aResult.iResultDes.Copy( KResult );
+        aResult.iResult = KErrGeneral;
+        // Case was executed but failed
+        return KErrNone;
+        }
+
+
+    // Test case passed
+
+    // Sets test case result and description(Maximum size is KStifMaxResultDes)
+    _LIT( KDescription , "Test case passed");
+    aResult.SetResult( KErrNone, KDescription );
+    //aResult.iResult = KErrNone;
+    //aResult.iResultDes = KDescription;
+
+    // Case was executed
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: MathTest
+
+    Description: Print loop test. Actually does not test anything, just
+    demonstrate how to print. Test is always pased.
+  
+    Parameters:  TTestResult& aErrorDescription: out:   
+                    Test result and on error case a short description of error
+
+    Return Values: TInt: Always KErrNone to indicate that test was valid
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CDemoModule::LoopTest( TTestResult& aResult )
+    {
+
+    /* Simple print and wait loop */
+    _LIT( KDefinion ,"State");
+    _LIT( KData ,"Looping");
+    TestModuleIf().Printf( 0, KDefinion, KData );
+    for( TInt i=0; i<10; i++)
+        {
+        _LIT( KRunning ,"Running");
+        _LIT( KLoop ,"%d");
+        TestModuleIf().Printf( 0, KRunning, KLoop, i);
+        User::After( 1000000 );
+        }
+    _LIT( KData2 ,"Finished");
+    TestModuleIf().Printf( 0, KDefinion, KData2 );
+
+    // Test case passed
+
+    // Sets test case result and description(Maximum size is KStifMaxResultDes)
+    _LIT( KDescription , "Test case passed");
+    aResult.SetResult( KErrNone, KDescription );
+    //aResult.iResult = KErrNone;
+    //aResult.iResultDes = KDescription;
+
+    // Case was executed
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: MathTest
+
+    Description: Math testing.
+  
+    Parameters:  TTestResult& aErrorDescription: out:   
+                    Test result and on error case a short description of error
+
+    Return Values: TInt: Always KErrNone to indicate that test was valid
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CDemoModule::MathTest( TTestResult& aResult )
+    {
+    /* Test with mathematic calculations and printing */
+    _LIT( KDefinion ,"RunTestCase");
+    _LIT( KData ,"Math calculations");
+    TestModuleIf().Printf( 0, KDefinion, KData );
+    // Result
+    TRealX res;
+    // Random numbers
+    TInt rand[6];
+    TRealX coef[5];
+    TInt i;
+    TInt j;
+    for( i=0; i<10; i++ )
+        {
+        for(j=0; j<6; j++)
+            rand[j] = Math::Random(); 
+        for(j=0; j<5; j++)
+            coef[j] = rand[j];
+        Math::PolyX(res, rand[5], 5, coef );
+
+        _LIT( KResult ,"Result %d");
+        TestModuleIf().Printf( 0, KDefinion, KResult, ( TInt )res);
+        }
+
+    // Test case passed
+
+    // Sets test case result and description(Maximum size is KStifMaxResultDes)
+    _LIT( KDescription , "Test case passed");
+    aResult.SetResult( KErrNone, KDescription );
+    //aResult.iResult = KErrNone;
+    //aResult.iResultDes = KDescription;
+
+    // Case was executed
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: PrintTest
+
+    Description: Printing testing.
+
+    Parameters:  TTestResult& aErrorDescription: out:   
+                    Test result and on error case a short description of error
+
+    Return Values: TInt: Always KErrNone to indicate that test was valid
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CDemoModule::PrintTest( TTestResult& aResult )
+    {
+    /* Tests printing with high intencity and different priority */ 
+    _LIT( KDefinion ,"CTestModuleDemo::RunTestCase");
+    _LIT( KData ,"Heavy print looping");
+    TestModuleIf().Printf( 0, KDefinion, KData );
+    TInt j;
+    for( TInt i=0; i<10; i++)
+        {
+
+        for(j=0; j<2; j++)
+            {
+            _LIT( KTmp ,"RunTestCase");
+            TBuf<15> tmp;
+            tmp.Copy( KTmp );
+            tmp.AppendNum( j );
+            _LIT( KNewData ,"p");
+            TestModuleIf().Printf(3, tmp, KNewData );
+            }
+
+        for(j=0; j<500; j++)
+            {
+             _LIT( KNewDefinion ,"RunTestCase");
+             _LIT( KNewData ,"%c");
+            TestModuleIf().Printf(1+(Math::Random() % 12),
+                KNewDefinion, 
+                KNewData, 'a'+(j%('z'-'a')) );
+            }
+
+        _LIT( KNewDefinion ,"RunTestCase");
+        _LIT( KNewData ,"Running %d");
+        TestModuleIf().Printf( 2, KNewDefinion,KNewData, i);
+        User::After( 1000000 );
+        }
+
+    // Test case passed
+
+    // Sets test case result and description(Maximum size is KStifMaxResultDes)
+    _LIT( KDescription , "Test case passed");
+    aResult.SetResult( KErrNone, KDescription );
+    //aResult.iResult = KErrNone;
+    //aResult.iResultDes = KDescription;
+
+    // Case was executed
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDemoModule
+
+    Method: HeapMemoryAllocation
+
+    Description: Allocates heap descriptor.
+  
+    Parameters: TTestResult& aError
+
+    Return Values: TInt
+
+    Errors/Exceptions: Leaves with KErrNoMemory if heap allocation fails
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CDemoModule::HeapMemoryAllocation( TTestResult& aResult )
+    {
+    _LIT( KLogInfo , "CDemoModule::HeapMemoryAllocation" );
+    iLog->Log( KLogInfo );
+
+    // Allocate heap descriptor
+    HBufC * buffer = HBufC::New( 10 );
+    if( buffer == NULL )
+        {
+        // Allocation failed
+        _LIT( KNewLogInfo , "buffer was NULL");
+        iLog->Log( KNewLogInfo );
+        User::Leave( KErrNoMemory );
+        }
+    else
+        {
+        // Descriptor creation was ok
+        _LIT( KNewLogInfo ,"buffer was allocated properly" );
+        iLog->Log( KNewLogInfo );
+        }
+
+    delete buffer;
+
+    _LIT( KDescription , "Test case passed");
+    aResult.SetResult( KErrNone, KDescription );
+    return KErrNone;
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/DataLogger.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,125 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CDataLogger.
+*
+*/
+
+#ifndef DATALOGGER_H
+#define DATALOGGER_H
+
+//  INCLUDES
+#include "StifLogger.h"
+#include "FileOutput.h"
+#include "RDebugOutput.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class COutput;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CDataLogger is a STIF Test Framework StifLogger class.
+// Class contains a file logging operations.
+
+class CDataLogger
+            :public CStifLogger
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CDataLogger* NewL( const TDesC& aTestPath,
+                                    const TDesC& aTestFile,
+                                    TLoggerType aLoggerType,
+                                    TOutput aOutput,
+                                    TBool aOverWrite,
+                                    TBool aWithTimeStamp,
+                                    TBool aWithLineBreak,
+                                    TBool aWithEventRanking,
+                                    TBool aThreadIdToLogFile,
+                                    TBool aCreateLogDir,
+                                    TInt aStaticBufferSize,
+                                    TBool aUnicode );
+
+        /**
+        * Destructor.
+        */
+        ~CDataLogger();
+
+    public:     // New functions
+
+        /**
+        * Sent data to the output module. 16 bit. 
+        * aStyle parameter is not supporter in data logging.
+        */
+        TInt Send( TInt /*aStyle*/, const TDesC& aData );
+
+        /**
+        * Sent data to the output module. 8 bit.
+        * aStyle parameter is not supporter in data logging.
+        */
+        TInt Send( TInt /*aStyle*/, const TDesC8& aData );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CDataLogger( COutput* output );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // DATALOGGER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/FileOutput.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,258 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CFileOutput.
+*
+*/
+
+#ifndef FILEOUTPUT_H
+#define FILEOUTPUT_H
+
+//  INCLUDES
+#include <f32file.h>
+
+#include "Output.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CFileOutput is a STIF Test Framework StifLogger class.
+// Class contains a file logging operations.
+class CFileOutput 
+            :public COutput
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CFileOutput* NewL( const TDesC& aTestPath,
+                                    const TDesC& aTestFile,
+                                    CStifLogger::TLoggerType aLoggerType,
+                                    TBool aOverWrite,
+                                    TBool aWithTimeStamp,
+                                    TBool aWithLineBreak,
+                                    TBool aWithEventRanking,
+                                    TBool aThreadIdToLogFile,
+                                    TBool aCreateLogDir,
+                                    TInt  aStaticBufferSize,
+                                    TBool aUnicode );
+
+        /**
+        * Destructor.
+        */
+        ~CFileOutput();
+
+    public:     // New functions
+
+        /**
+        * Create a directory.
+        */
+        void CreateDirectoryL( const TDesC& aTestPath );
+
+        /**
+        * Open an existing file.
+        */
+        void OpenExistingFileL( const TDesC& aTestPath,
+                                const TDesC& aTestFile );
+
+        /**
+        * Create a new file.
+        */
+        void CreateNewFileL( const TDesC& aTestPath, const TDesC& aTestFile );
+
+        /**
+        * Write log information or data to the file.
+        * 16 bit.
+        */
+        TInt Write( TBool aWithTimeStamp,
+                    TBool aWithLineBreak,
+                    TBool aWithEventRanking,
+                    const TDesC& aData );
+
+        /**
+        * Write log information or data to the file.
+        * 8 bit.
+        */
+        TInt Write( TBool aWithTimeStamp,
+                    TBool aWithLineBreak,
+                    TBool aWithEventRanking,
+                    const TDesC8& aData );
+
+        /**
+        * Add event ranking, specify number to line (1-byte version).
+        */
+        void EventRanking( TPtr8& aData );
+
+        /**
+        * Add event ranking, specify number to line (2-byte version).
+        */
+        void EventRanking( TPtr& aData );
+
+        /**
+        * Add date, time and line break to data (1-byte version).
+        */
+        void AddTimeStampToData( TPtr8& aData );
+
+        /**
+        * Add date, time and line break to data (2-byte version).
+        */
+        void AddTimeStampToData( TPtr& aData );
+
+        /**
+        * Get date and time.
+        */
+        void GetDateAndTime( TStifLoggerTimeStamp& aDataAndTime );
+
+        /**
+        * Make file type.
+        */
+        void FileType( const TDesC& aTestFile, TFileType& aFileType );
+
+        /**
+        * Generate thread id to test file name.
+        */
+        void TestFileWithThreadId( const TDesC& aTestFile,
+                                    TFileName& aNewTestFile );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CFileOutput( CStifLogger::TLoggerType aLoggerType,
+                        TBool aWithTimeStamp,
+                        TBool aWithLineBreak,
+                        TBool aWithEventRanking,
+                        TBool aThreadIdToLogFile );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aTestPath,
+                            const TDesC& aTestFile,
+                            TBool aOverWrite,
+                            TBool aCreateLogDir,
+                            TInt aStaticBufferSize,
+                            TBool aUnicode );
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+        /**
+        * Log file directory name, file name and file type.
+        */
+        TFileName iFileAndDirName;
+
+        /**
+        * Indicates file type.
+        */
+        CStifLogger::TLoggerType iLoggerType;
+
+        /**
+        * Time stamp indicator.
+        */
+        TBool iWithTimeStamp;
+
+        /**
+        * Line break indicator.
+        */
+        TBool iWithLineBreak;
+
+        /**
+        * Event ranking indicator.
+        */
+        TBool iWithEventRanking;
+
+        /**
+        * Indicator to thread id adding to end of the log file
+        */
+        TBool iThreadIdToLogFile;
+
+        /**
+        * Indicator to thread id adding to end of the log file
+        */
+        TBool iCreateLogDir;
+
+        /**
+        * For the file handling
+        */
+        RFile iFile;
+
+        /**
+        * For the file session handling
+        */
+        RFs iFileSession;
+
+        /**
+        * Is file open indicator
+        */
+        TInt iIsFileOpen;
+
+       /**
+        * DataHBuf for logging purposes
+        */
+        HBufC8 * iDataHBuf8;
+
+		// @js
+        TInt iStaticBufferSize;
+
+       /**
+        * Determines if file has to be in unicode format
+        */
+        TBool iUnicode;
+
+       /**
+        * DataHBuf for logging purposes
+        */
+        HBufC16* iDataHBuf16;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // FILEOUTPUT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/HtmlLogger.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CHtmlLogger.
+*
+*/
+
+#ifndef HTMLLOGGER_H
+#define HTMLLOGGER_H
+
+//  INCLUDES
+#include "StifLogger.h"
+#include "FileOutput.h"
+#include "RDebugOutput.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class COutput;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CHtmlLogger is a STIF Test Framework StifLogger class.
+// Class contains a file logging operations.
+
+class CHtmlLogger
+            :public CStifLogger
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHtmlLogger* NewL( const TDesC& aTestPath,
+                                    const TDesC& aTestFile,
+                                    TLoggerType aLoggerType,
+                                    TOutput aOutput,
+                                    TBool aOverWrite,
+                                    TBool aWithTimeStamp,
+                                    TBool aWithLineBreak,
+                                    TBool aWithEventRanking,
+                                    TBool aThreadIdToLogFile,
+                                    TBool aCreateLogDir,
+                                    TInt aStaticBufferSize,
+                                    TBool aUnicode );
+
+        /**
+        * Destructor.
+        */
+        ~CHtmlLogger();
+
+    public:     // New functions
+
+        /**
+        * Initialize html page.
+        */
+        void StartHtmlPage( const TDesC& aTestFile, TBool aThreadIdToLogFile );
+
+        /**
+        * Finalize html page.
+        */
+        void EndHtmlPage();
+
+        /**
+        * Start style information logging.
+        */
+        void StyleStarting( TInt aStyle, TBool& aTimeStamp,
+                                TBool& aEventRanking );
+
+        /**
+        * End style information logging.
+        */
+        void StyleEnding( TInt aStyle );
+
+        /**
+        * Send style information and data to the output module.
+        * 16 bit.
+        */
+        TInt Send( TInt aStyle, const TDesC& aData );
+
+        /**
+        * Send style information and data to the output module.
+        * 8 bit.
+        */
+        TInt Send( TInt aStyle, const TDesC8& aData );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CHtmlLogger( COutput* output,
+                        const TDesC& aTestFile,
+                        TBool aThreadIdToLogFile );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // HTMLLOGGER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/LoggerOverFlow.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,187 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* TDesLoggerOverflowHandler and TDes8LoggerOverflowHandler.
+*
+*/
+
+#ifndef LOGGEROVERFLOW_H
+#define LOGGEROVERFLOW_H
+
+//  INCLUDES
+#include "StifLogger.h"
+#include "Output.h"
+#include "RDebugOutput.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TDesLoggerOverflowHandler is a STIF Test Framework StifLogger class.
+// Class contains an over flow operations.
+
+class TDesLoggerOverflowHandler 
+        :public TDes16Overflow
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+    public:     // New functions
+
+        /**
+        * C++ default constructor.
+        */
+        TDesLoggerOverflowHandler( CStifLogger* aLogger, TInt aOverFlowSource );
+
+        /**
+        * C++ default constructor.
+        */
+        // For future needs
+        // TDesLoggerOverflowHandler( CRDebugOutput* aRDebugOutput,
+        //                         TInt aOverFlowSource );
+
+        /**
+        * Simple overflow handling(16 bit)
+        */
+        void Overflow( TDes16& aDes );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+    public:     // Data
+
+        /**
+        * Pointer to CStifLogger class object
+        */
+        CStifLogger* iLogger;
+
+        /**
+        * Pointer to CRDebugOutput class object
+        */
+        CRDebugOutput* iRDebugOutput;
+
+        /**
+        * Over flow source
+        */
+        TInt iOverFlowSource;
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TDes8LoggerOverflowHandler is a STIF Test Framework StifLogger class.
+// Class contains an over flow operations.
+
+class TDes8LoggerOverflowHandler 
+        :public TDes8Overflow
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+    public:     // New functions
+
+        /**
+        * C++ default constructor.
+        */
+        TDes8LoggerOverflowHandler( CStifLogger* aLogger, TInt aOverFlowSource );
+
+        /**
+        * C++ default constructor.
+        */
+        // For future needs
+        // TDes8LoggerOverflowHandler( CRDebugOutput* aRDebugOutput,
+        //                        TInt aOverFlowSource );
+
+        /**
+        * Simple overflow handling(8 bit)
+        */
+        void Overflow( TDes8& aDes );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+    public:     // Data
+
+        /**
+        * Pointer to CStifLogger class object
+        */
+        CStifLogger* iLogger;
+
+        /**
+        * Pointer to CRDebugOutput class object
+        */
+        // For future needs
+        // CRDebugOutput* iRDebugOutput;
+
+        /**
+        * Over flow source
+        */
+        TInt iOverFlowSource;
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // LOGGEROVERFLOW_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/LoggerTracing.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the tracing operations for the 
+* CStifLogger and COutput.
+*
+*/
+
+#ifndef LOGGERTRACING_H
+#define LOGGERTRACING_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+const TUint KError           = 0x1;
+const TUint KInfo            = 0x2;
+const TUint KAlways          = 0xFFFFFFFF;
+const TUint KDebugLevel      = ( KError );
+
+// MACROS
+#ifdef _DEBUG
+#define __TRACING_ENABLED
+#endif
+
+#ifdef __TRACING_ENABLED
+// Disable conditional expression is constant -warning
+#pragma warning( disable : 4127 )
+#define __TRACE(level,p) if ( (level) & KDebugLevel) { RDebug::Print p ;}
+#else
+#define __TRACE(level,p);
+#endif
+
+#endif // LOGGERTRACING_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/NullOutput.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,120 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CNullOutput.
+*
+*/
+
+#ifndef NULLOUTPUT_H
+#define NULLOUTPUT_H
+
+//  INCLUDES
+#include "Output.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+// None
+
+// DESCRIPTION
+// CNullOutput is a STIF Test Framework StifLogger class.
+// CNullOutput's methods purpose is to look like logging although it don't
+// do any logging operations.
+
+class CNullOutput 
+            :public COutput
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CNullOutput* NewL();
+
+        /**
+        * Destructor.
+        */
+        ~CNullOutput();
+
+    public:     // New functions
+
+        /**
+        * C++ default constructor.
+        */
+        CNullOutput();
+
+        /**
+        * Write log information or data to the file.
+        * 16 bit.
+        */
+        TInt Write( TBool aWithTimeStamp,
+                    TBool aWithLineBreak,
+                    TBool aWithEventRanking,
+                    const TDesC& aData );
+
+        /**
+        * Write log information or data to the file.
+        * 8 bit.
+        */
+        TInt Write( TBool aWithTimeStamp,
+                    TBool aWithLineBreak,
+                    TBool aWithEventRanking,
+                    const TDesC8& aData );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // NULLOUTPUT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/Output.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,158 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the COutput.
+*
+*/
+
+#ifndef OUTPUT_H
+#define OUTPUT_H
+
+//  INCLUDES
+
+#include "StifLogger.h"
+#include "LoggerTracing.h"
+
+// CONSTANTS
+// Maximum length of the event ranking
+const TInt KMaxEventRanking = 5;
+
+// Maximum length of the space
+const TInt KMaxSpace = 1;
+
+// Maximum length of the HTML line break('<BR>' + '\n')
+const TInt KMaxHtmlLineBreak = 6;
+
+// Maximum length of the line break(13 or '\' and 10 or 'n' in Symbian OS)
+const TInt KMaxLineBreak = 2;
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// COutput is a STIF Test Framework StifLogger class.
+// Class contains a file logging operations.
+
+class COutput
+        :public CBase
+    {
+    public:     // Enumerations
+            
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static COutput* NewL( const TDesC& aTestPath,
+                                const TDesC& aTestFile,
+                                CStifLogger::TLoggerType aLoggerType,
+                                CStifLogger::TOutput aOutput,
+                                TBool aOverWrite,
+                                TBool aWithTimeStamp,
+                                TBool aWithLineBreak,
+                                TBool aWithEventRanking,
+                                TBool aThreadIdToLogFile,
+                                TBool aCreateLogDir,
+                                TInt aStaticBufferSize,
+                                TBool aUnicode );
+
+        /**
+        * Destructor.
+        */
+        virtual ~COutput();
+
+    public:     // New functions
+
+        /**
+        * C++ default constructor.
+        */
+        COutput();
+
+        /**
+        * Pure virtual. Write log information or data to the file.
+        * 16 bit.
+        */
+        virtual TInt Write( TBool /* aWithTimeStamp */,
+                            TBool /* aWithTimeLineBreak */,
+                            TBool /* aWithEventRanking */,
+                            const TDesC& /* aData */ ) = 0;
+
+        /**
+        * Pure virtual. Write log information or data to the file.
+        * 8 bit.
+        */
+        virtual TInt Write( TBool /* aWithTimeStamp */,
+                            TBool /* aWithTimeLineBreak */,
+                            TBool /* aWithEventRanking */,
+                            const TDesC8& /* aData */ ) = 0;
+
+        /**
+        * Return output type.
+        */
+        inline TInt OutputCreationResult( CStifLogger::TOutput& aType )
+            { 
+            aType = iType;  
+            return iCreationResult; 
+            };
+            
+        /**
+        * Set output type.
+        */
+        inline void SetOutputCreationResult( TInt aResult, 
+                                                CStifLogger::TOutput aType )
+            { 
+            iType = aType;  
+            iCreationResult = aResult; 
+            };
+        
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+    public:     // Data
+
+    protected:  // Data
+        // Output type
+        CStifLogger::TOutput    iType;
+        TInt                    iCreationResult;
+
+    private:    // Data        
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // OUTPUT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/RDebugOutput.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,194 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CRDebugOutput.
+*
+*/
+
+#ifndef RDEBUGOUTPUT_H
+#define RDEBUGOUTPUT_H
+
+//  INCLUDES
+#include <f32file.h>
+
+#include "StifLogger.h"
+#include "Output.h"
+#include "LoggerTracing.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CRDebugOutput is a STIF Test Framework StifLogger class.
+// Class contains a RDebug logging operations.
+class CRDebugOutput 
+            :public COutput
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CRDebugOutput* NewL( const TDesC& /* aTestPath */,
+                                    const TDesC& /* aTestFile */,
+                                    CStifLogger::TLoggerType aLoggerType,
+                                    TBool /* aOverWrite */,
+                                    TBool aWithTimeStamp,
+                                    TBool aWithLineBreak,
+                                    TBool aWithEventRanking,
+                                    TBool /* aThreadIdToLogFile */,
+                                    TBool /* aCreateLogDir */,
+                                    TInt aStaticBufferSize );
+
+        /**
+        * Destructor.
+        */
+        ~CRDebugOutput();
+
+    public:     // New functions
+
+        /**
+        * Write RDebug information.
+        * 16 bit.
+        */
+        TInt Write( TBool aWithTimeStamp,
+                    TBool aWithLineBreak,
+                    TBool aWithEventRanking,
+                    const TDesC& aData );
+
+        /**
+        * Write RDebug information.
+        * 8 bit.
+        */
+        TInt Write( TBool aWithTimeStamp,
+                    TBool aWithLineBreak,
+                    TBool aWithEventRanking,
+                    const TDesC8& aData );
+
+        /**
+        * Event ranking and time stamp combimer.
+        */
+        void EventAndTimeCombiner( TPtr& aLogInfo,
+                                    TPtr& aData,
+                                    TBool aWithTimeStamp,
+                                    TBool aWithLineBreak,
+                                    TBool aWithEventRanking );
+
+        /**
+        * Add event ranking, specify number to line.
+        */
+        void EventRanking( TPtr& aData );
+                    
+        /**
+        * Add date, time and line break to data.
+        */
+        void AddTimeStampToData( TPtr& aData );
+
+        /**
+        * Get date and time.
+        */
+        void GetDateAndTime( TStifLoggerTimeStamp8& aDataAndTime );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CRDebugOutput( CStifLogger::TLoggerType aLoggerType,
+                        TBool aWithTimeStamp,
+                        TBool aWithLineBreak,
+                        TBool aWithEventRanking );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TInt aStaticBufferSize );
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+        /**
+        * Data buffer
+        */
+        HBufC* iDataHBuf;
+
+        /**
+        * Indicates file type.
+        */
+        CStifLogger::TLoggerType iLoggerType;
+
+        /**
+        * Time stamp indicator.
+        */
+        TBool iWithTimeStamp;
+
+        /**
+        * Line break indicator.
+        */
+        TBool iWithLineBreak;
+
+        /**
+        * Event ranking indicator.
+        */
+        TBool iWithEventRanking;
+
+        /**
+        * DataHBuf for logging purposes
+        */      
+        HBufC * iDataHBuf1;      
+
+        /**
+        * DataHBuf for logging purposes
+        */      
+        HBufC * iDataHBuf2;      
+        
+        TInt iStaticBufferSize;
+       
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // RDEBUGOUTPUT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/inc/TxtLogger.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,125 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CTxtLogger.
+*
+*/
+
+#ifndef TXTLOGGER_H
+#define TXTLOGGER_H
+
+//  INCLUDES
+#include "StifLogger.h"
+#include "FileOutput.h"
+#include "RDebugOutput.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class COutput;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTxtLogger is a STIF Test Framework StifLogger class.
+// Class contains a file logging operations.
+
+class CTxtLogger
+            :public CStifLogger
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTxtLogger* NewL( const TDesC& aTestPath,
+                                    const TDesC& aTestFile,
+                                    TLoggerType aLoggerType,
+                                    TOutput aOutput,
+                                    TBool aOverWrite,
+                                    TBool aWithTimeStamp,
+                                    TBool aWithLineBreak,
+                                    TBool aWithEventRanking,
+                                    TBool aThreadIdToLogFile,
+                                    TBool aCreateLogDir,
+                                    TInt  aStaticBufferSize,
+                                    TBool aUnicode );
+
+        /**
+        * Destructor.
+        */
+        ~CTxtLogger();
+
+    public:     // New functions
+
+        /**
+        * Send style information and data to the output module.
+        * aStyle parameter is not supporter in txt printing.
+        */
+        TInt Send( TInt aStyle, const TDesC& aData );
+
+        /**
+        * Send style information and data to the output module.
+        * aStyle parameter is not supporter in txt printing.
+        */
+        TInt Send( TInt aStyle, const TDesC8& aData );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CTxtLogger( COutput* output );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+    
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // TXTLOGGER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/DataLogger.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,270 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CDataLogger 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "DataLogger.h"
+#include "Output.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDataLogger
+
+    Method: CDataLogger
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: COutput* output: in: Output source
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CDataLogger::CDataLogger( COutput* output )
+    {
+    	iOutput = output;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDataLogger
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CDataLogger::ConstructL()
+    {
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDataLogger
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: const TDesC& aTestPath: in: Log path
+                const TDesC& aTestFile: in: Log filename
+                TLoggerType aLoggerType: in: File type
+                TOutput aOutput: in: Output source
+                TBool aOverWrite: in: For file overwrite
+                TBool aWithTimeStamp: in: For timestamp
+                TBool aWithLineBreak: in: For line break
+                TBool aWithEventRanking: in: For events ranking to file
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+                TBool aCreateLogDir: in: Indicator to directory creation
+                TInt  aStaticBufferSize
+                TBool aUnicode: not used: Indicator if file has to be in unicode format.
+
+    Return Values: CDataLogger*: pointer to CDataLogger object
+
+    Errors/Exceptions: Leaves if called COutput::NewL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CDataLogger* CDataLogger::NewL( const TDesC& aTestPath,
+                                const TDesC& aTestFile,
+                                TLoggerType aLoggerType,
+                                TOutput aOutput,
+                                TBool aOverWrite,
+                                TBool aWithTimeStamp,
+                                TBool aWithLineBreak,
+                                TBool aWithEventRanking,
+                                TBool aThreadIdToLogFile,
+                                TBool aCreateLogDir,
+                                TInt aStaticBufferSize,
+                                TBool /*aUnicode*/ )
+    {
+    __TRACE( KInfo, ( _L( "STIFLOGGER: Creating data logger" ) ) );
+
+    aWithTimeStamp = EFalse;    // Time stamp not allowed in data logging
+    aWithLineBreak = EFalse;    // Line break not allowed in data logging
+    aWithEventRanking = EFalse; // Event ranking not allowed in data logging
+
+    TBool aUnicode(EFalse); //For data type unicode is not allowed
+    // Create COutput object output
+    COutput* output = COutput::NewL( aTestPath,
+                                        aTestFile,
+                                        aLoggerType,
+                                        aOutput,
+                                        aOverWrite,
+                                        aWithTimeStamp,
+                                        aWithLineBreak,
+                                        aWithEventRanking,
+                                        aThreadIdToLogFile,
+                                        aCreateLogDir,
+                                        aStaticBufferSize,
+                                        aUnicode );
+                                        
+    CleanupStack::PushL( output ); 
+
+	__ASSERT_ALWAYS( output != NULL, User::Leave( KErrNotFound ) );
+    // Create CDataLogger object dataLogger and bind to COutput
+    CDataLogger* dataLogger = new (ELeave) CDataLogger( output );
+    // DATA logger owns output object and it will be destroyed in STIFLogger
+    // destructor.
+    CleanupStack::Pop( output ); 
+
+    CleanupStack::PushL( dataLogger );
+    dataLogger->ConstructL();
+    CleanupStack::Pop( dataLogger );
+    
+    
+    return dataLogger;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDataLogger
+
+    Method: ~CDataLogger
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CDataLogger::~CDataLogger()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDataLogger
+
+    Method: Send
+
+    Description: Send style information and 16 bit data to the output module.
+
+    Parameters: TInt TStyle: in: Text forming
+                const TDesC& aData: in: Data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CDataLogger::Send( TInt /*TStyle*/, const TDesC& aData )
+    {
+    // No text styling implemented
+    return iOutput->Write( EFalse, ETrue, EFalse, aData );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CDataLogger
+
+    Method: Send
+
+    Description: Send style information and 8 bit data to the output module.
+
+    Parameters: TInt TStyle: in: Text forming
+                const TDesC8& aData: in: Data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CDataLogger::Send( TInt /*TStyle*/, const TDesC8& aData )
+    {
+    // No text styling implemented
+    return iOutput->Write( EFalse, ETrue, ETrue, aData );
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/FileOutput.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1214 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CFileOutput 
+* class member functions.
+*
+*/
+
+
+// INCLUDE FILES
+#include "FileOutput.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+//#define RDEBUG_FILEWRITECRASH(a) RDebug::Print(a)
+#define RDEBUG_FILEWRITECRASH(a)
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: CFileOutput
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: TLoggerType aLoggerType: in: File type
+                TBool aWithTimeStamp: in: For timestamp
+                TBool aWithLineBreak: in: For line break
+                TBool aWithEventRanking: in: For events ranking to file
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CFileOutput::CFileOutput( CStifLogger::TLoggerType aLoggerType,
+                            TBool aWithTimeStamp,
+                            TBool aWithLineBreak,
+                            TBool aWithEventRanking,
+                            TBool aThreadIdToLogFile ) :
+    COutput()
+    {
+    // Indicates file type
+    iLoggerType = aLoggerType;
+
+    // Time stamp indicator
+    iWithTimeStamp = aWithTimeStamp;
+
+    // Line break indicator
+    iWithLineBreak = aWithLineBreak;
+
+    // Log event ranking indicator
+    iWithEventRanking = aWithEventRanking;
+
+    // Indicator to thread id adding to end of the log file
+    iThreadIdToLogFile = aThreadIdToLogFile;
+
+    // Is file open indicator
+    iIsFileOpen = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: const TDesC& aTestPath: in: Log path
+                const TDesC& aTestFile: in: Log filename
+                TBool aOverWrite: in: For file overwrite
+                TBool aCreateLogDir: in: Indicator to directory creation
+                TInt  aStaticBufferSize
+                TBool aUnicode: in: Indicator if file has to be in unicode format
+
+    Return Values: None
+
+    Errors/Exceptions:  Leaves if called CreateNewFileL method fails
+                        Leaves if called OpenExistingFileL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::ConstructL( const TDesC& aTestPath,
+                                const TDesC& aTestFile,
+                                TBool aOverWrite,
+                                TBool aCreateLogDir,
+                                TInt aStaticBufferSize,
+                                TBool aUnicode)
+    {
+    iUnicode = aUnicode;
+
+    // Open file session
+    User::LeaveIfError( iFileSession.Connect() );
+
+    // Create a log directory
+    if( aCreateLogDir )
+        {
+        CreateDirectoryL( aTestPath );
+        }
+
+    // Create a new file
+    if ( aOverWrite )
+        {
+        CreateNewFileL( aTestPath, aTestFile );
+        }
+    // Open an existing file
+    else 
+        {
+        OpenExistingFileL( aTestPath, aTestFile );
+        }
+        
+    if( aStaticBufferSize != 0)
+        {
+        iDataHBuf8 = HBufC8::NewL( aStaticBufferSize );
+        iDataHBuf16 = HBufC::NewL(aStaticBufferSize);
+        iStaticBufferSize = aStaticBufferSize;
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: const TDesC& aTestPath: in: Log path
+                const TDesC& aTestFile: in: Log filename
+                TLoggerType aLoggerType: in: File type
+                TBool aOverWrite: in: For file overwrite
+                TBool aWithTimeStamp: in: For timestamp
+                TBool aWithLineBreak: in: For line break
+                TBool aWithEventRanking: in: For events ranking to file
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+                TBool aCreateLogDir: in: Indicator to directory creation
+                TInt  aStaticBufferSize
+                TBool aUnicode: in: Indicator if file has to be in unicode format
+
+    Return Values: CFileOutput*: pointer to CFileOutput object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CFileOutput* CFileOutput::NewL( const TDesC& aTestPath,
+                                const TDesC& aTestFile,
+                                CStifLogger::TLoggerType aLoggerType,
+                                TBool aOverWrite,
+                                TBool aWithTimeStamp,
+                                TBool aWithLineBreak,
+                                TBool aWithEventRanking,
+                                TBool aThreadIdToLogFile,
+                                TBool aCreateLogDir,
+                                TInt  aStaticBufferSize,
+                                TBool aUnicode )
+    {
+    // Create CFileOutput object fileWriter
+    CFileOutput* fileWriter = new (ELeave) CFileOutput( aLoggerType,
+                                                        aWithTimeStamp,
+                                                        aWithLineBreak,
+                                                        aWithEventRanking,
+                                                        aThreadIdToLogFile );
+
+    CleanupStack::PushL( fileWriter );
+    fileWriter->ConstructL( aTestPath, aTestFile, aOverWrite, aCreateLogDir, aStaticBufferSize,
+                            aUnicode );
+    CleanupStack::Pop( fileWriter );
+
+    return fileWriter;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: ~CFileOutput
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CFileOutput::~CFileOutput()
+    {
+    // Close file
+    iFile.Close();
+    // Close file session
+    iFileSession.Close();
+
+    delete iDataHBuf8;
+    delete iDataHBuf16;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: FileType
+
+    Description: Check file type.
+
+    Check is file type set with a aTestFile's name. If file type is not set
+    the type will set according to StifLogger's type.
+
+    Parameters: const TDesC& aTestFile: in: Log filename
+                TFileType& fileType: inout: Generated file type
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/    
+void CFileOutput::FileType( const TDesC& aTestFile,
+                            TFileType& aFileType )
+    {
+    TBool fileTypeIsSet( EFalse ); // File type indicator
+
+    // Check is file type set to aTestFile parameter
+    TInt ret = aTestFile.Find( _L( "." ) );
+    if( ret != KErrNotFound )
+        {
+        fileTypeIsSet = ETrue;
+        }
+    // If not, add thread id name if allowed
+    else if ( iThreadIdToLogFile )
+        {
+        // Thread id maximum length is 8 in hexadesimal format
+        // Construct unique thread name
+        aFileType.Append( _L("_") );
+        RThread threadHandle;                   // A handle to a thread
+        TThreadId id = threadHandle.Id();       // Encapsulates the 
+                                                // Id of a thread
+        // Appends id in hexadesimal format             
+        aFileType.AppendFormat( _L( "%x" ), (TInt)id );
+        }
+
+    // Add file type after the thread id name
+    if ( iLoggerType == CStifLogger::ETxt && !fileTypeIsSet )
+        {
+        // ".txt"
+        aFileType.Append( _L( "." ) );
+        aFileType.Append( _L( "txt" ) );
+        }
+    else if ( iLoggerType == CStifLogger::EHtml && !fileTypeIsSet )
+        {
+        // ".html"
+        aFileType.Append( _L( "." ) );
+        aFileType.Append( _L( "html" ) );
+        }
+    // EData file type comes from the aTestFile name. If not the file type 
+    // will be empty
+    else if ( iLoggerType == CStifLogger::EData )
+        {
+        aFileType.Append( _L( "" ) );
+        }
+    else
+        {
+        aFileType.Append( _L( "" ) );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: TestFileWithThreadId
+
+    Description: Generate thread id
+
+    Generate thread id name between the test file name and test file type.
+
+    Parameters: TDesC& aTestFile: in: Test file name
+                TFileName& aNewTestFile: inout: Generated test file name 
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::TestFileWithThreadId( const TDesC& aTestFile, 
+                                        TFileName& aNewTestFile )
+    {
+    for( TInt a = 0; a < aTestFile.Length(); a++ )
+        {
+        // Find a dot
+        if( aTestFile[a] == '.' )
+            {
+            TPtrC parsedFileType = aTestFile.Mid( a );  // Take rest of the 
+                                                        // aTestFile
+            aNewTestFile.Append( _L( "_" ) );
+            RThread threadHandle;                       // A handle to a thread
+            TThreadId id = threadHandle.Id();           // Encapsulates the 
+                                                        // Id of a thread
+            aNewTestFile.AppendFormat( _L( "%x" ), (TInt)id );// Appends id in
+                                                        // hexadesimal format
+            aNewTestFile.Append( parsedFileType );
+            break;
+            }
+        // Dot not found yet
+        else
+            {
+            aNewTestFile.Append( aTestFile[a] );
+            }
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: CreateDirectoryL
+
+    Description: Create a log directory.
+
+    Method creates directory if not allready exist.
+
+    Parameters: const TDesC& aTestPath: in: Test path definition
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if directory creation fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::CreateDirectoryL( const TDesC& aTestPath )
+    {
+    __TRACE( KInfo, ( _L( "STIFLOGGER: Create a directory" ) ) );
+
+    TInt ret = iFileSession.MkDirAll( aTestPath );
+	if( ret != KErrNone && ret != KErrAlreadyExists )
+        {
+        __TRACE( KError, 
+            ( _L( "STIFLOGGER: Directory creation fails with error: %d" ), ret ) );
+		User::Leave( ret );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: OpenExistingFileL
+
+    Description: Open an existing file.
+
+    Method is used when is need for log new information after the existing
+    log file.
+
+    Parameters: const TDesC& aTestPath: in: Test path definition
+                const TDesC& aTestFile: in: Test file name
+
+    Return Values: None
+
+    Errors/Exceptions:  Leaves if path or file lengths are over KMaxFileName
+                        Leaves if file Replace method fails
+                        Leaves if file Open method fails
+                        Leaves if file path not found
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::OpenExistingFileL( const TDesC& aTestPath, 
+                                        const TDesC& aTestFile )
+    {
+    __TRACE( KInfo, ( _L( "STIFLOGGER: Opening an existing file for logging" ) ) );
+
+    // If path and file name lengths are over KMaxFileName(TFileName)
+    __ASSERT_ALWAYS(
+        ( aTestPath.Length() + aTestFile.Length() ) < KMaxFileName,
+        User::Leave( KErrArgument ) );
+
+    // Check file type and generate threat id name
+    TFileType fileType;
+    FileType( aTestFile, fileType );
+
+    // File directory name, file name and file type definitions
+    TPtrC dirNamePrt( aTestPath );
+    iFileAndDirName.Copy( dirNamePrt );
+
+    TInt isDotFound = aTestFile.Find( _L( "." ) );
+    // If dot is found and iThreadIdToLogFile is true
+    if( isDotFound != KErrNotFound && iThreadIdToLogFile )
+        {
+        TFileName testFileWithThreadId;
+        // Generate thread id name
+        TestFileWithThreadId( aTestFile, testFileWithThreadId );
+        iFileAndDirName.Insert( 
+            iFileAndDirName.Length(), testFileWithThreadId );
+        }
+    else
+        {
+        TPtrC txtPrt( fileType );
+        iFileAndDirName.Insert( iFileAndDirName.Length(), aTestFile );
+        iFileAndDirName.Insert( iFileAndDirName.Length(), txtPrt );
+        }
+
+//  TBool isOpen( EFalse );
+    TInt ret( KErrNone );
+
+  
+    iIsFileOpen=iFile.Open( iFileSession, iFileAndDirName,
+            EFileWrite | EFileStreamText |
+                    EFileShareAny );
+    if( iIsFileOpen == KErrNotFound )
+        {
+        ret =  iFile.Create( iFileSession, iFileAndDirName, 
+                                    EFileWrite | EFileStreamText |
+                                    EFileShareAny );
+        if(iUnicode && ret == KErrNone)
+            {
+            char FF = 0xFF;
+            char FE = 0xFE;
+            TBuf8<2> beg;
+            beg.Append(FF);
+            beg.Append(FE);
+            if(iFile.Write(beg) == KErrNone)
+                iFile.Flush();
+            }
+        }
+    else if( iIsFileOpen == KErrNone )
+        {
+      
+        ret=KErrNone;
+        }
+    // Probably path not found
+    else
+        {
+        User::Leave( iIsFileOpen );
+        }
+
+    if ( ret != KErrNone )
+        {
+        User::Leave( ret );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: CreateNewFileL
+
+    Description: Create a new file.
+
+    Method creates new file to the log information.
+
+    Parameters: const TDesC& aTestPath: in: Test path definition
+                const TDesC& aTestFile: in: Test file name
+
+    Return Values: None
+
+    Errors/Exceptions:  Leaves if path or file lengths are over KMaxFileName
+                        Leaves if file server Connect method fails
+                        Leaves if file Replace method fails
+                        Leaves if file Open method fails
+                        Leaves if file path not found
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::CreateNewFileL( const TDesC& aTestPath,
+                                    const TDesC& aTestFile )
+    {
+    __TRACE( KInfo, ( _L( "STIFLOGGER: Create a new file for logging" ) ) );
+
+    // If path and file name lengths are over KMaxFileName(TFileName)
+    __ASSERT_ALWAYS(
+        ( aTestPath.Length() + aTestFile.Length() ) < KMaxFileName,
+        User::Leave( KErrArgument ) );
+
+    // Check file type and generate threat id name
+    TFileType fileType;
+    FileType( aTestFile, fileType );
+
+    // File directory name, file name and file type definitions
+    TPtrC dirNamePrt( aTestPath );
+    iFileAndDirName.Copy( dirNamePrt );
+
+    TInt isDotFound = aTestFile.Find( _L( "." ) );
+    // If dot is found and iThreadIdToLogFile is true
+    if( isDotFound != KErrNotFound && iThreadIdToLogFile )
+        {
+        TFileName testFileWithThreadId;
+        // Generate thread id name
+        TestFileWithThreadId( aTestFile, testFileWithThreadId );
+        iFileAndDirName.Insert( 
+            iFileAndDirName.Length(), testFileWithThreadId );
+        }
+    else
+        {
+        TPtrC txtPrt( fileType );
+        iFileAndDirName.Insert( iFileAndDirName.Length(), aTestFile );
+        iFileAndDirName.Insert( iFileAndDirName.Length(), txtPrt );
+        }
+
+    // Delete file if exist
+    iFileSession.Delete( iFileAndDirName );
+
+    TBool isOpen( EFalse );
+    TInt ret( KErrNone );
+
+    iIsFileOpen = iFileSession.IsFileOpen( iFileAndDirName, isOpen );
+    if( ( iIsFileOpen == KErrNotFound ) ||
+        ( iIsFileOpen == KErrNone ) )
+        {
+        ret = iFile.Replace( iFileSession, iFileAndDirName,
+                                    EFileWrite | EFileStreamText |
+                                    EFileShareAny );
+        if(iUnicode && ret == KErrNone)
+            {
+            char FF = 0xFF;
+            char FE = 0xFE;
+            TBuf8<2> beg;
+            beg.Append(FF);
+            beg.Append(FE);
+            if(iFile.Write(beg) == KErrNone)
+                iFile.Flush();
+            }
+        }
+    // Probably path not found
+    else
+        {
+        User::Leave( iIsFileOpen );
+        }
+
+    if ( ret != KErrNone )
+        {
+        User::Leave( ret );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: Write
+
+    Description: Write log information or data to the file. 16 bit.
+
+    Parameters: TBool aWithTimeStamp: in: Is time stamp flag used
+                TBool aWithLineBreak: in: Is line break flag used
+                TBool aWithEventRanking: in: Is event ranking flag used
+                const TDesC& aData: in: Logged or saved data
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CFileOutput::Write( TBool aWithTimeStamp, TBool aWithLineBreak,
+                            TBool aWithEventRanking, const TDesC& aData )
+    {
+    TInt extraLength( 0 );  // Line and/or event required length
+
+    TPtr data16(0, 0);
+    TPtr8 data8(0, 0);
+
+    // Extra space calculation
+    if( iWithEventRanking && aWithEventRanking )
+        {
+        extraLength = extraLength + KMaxEventRanking + KMaxSpace;
+        }
+    if( ( iLoggerType == CStifLogger::EHtml ) && iWithLineBreak && aWithLineBreak )
+        {
+        extraLength = extraLength + KMaxHtmlLineBreak;
+        }
+    if( iWithLineBreak && aWithLineBreak )
+        {
+        extraLength = extraLength + KMaxLineBreak;
+        }
+    if( aWithTimeStamp && iWithTimeStamp )
+        {
+        extraLength = extraLength + KMaxTimeStamp;
+        }
+
+    // Calculated space
+    TInt space = aData.Length();
+
+    HBufC8* dataHBuf8 = NULL;
+    HBufC16* dataHBuf16 = NULL;
+
+    if( iDataHBuf8 != NULL )
+        {
+        // We'll use HBufC created in ConstructL
+        data8.Set(iDataHBuf8->Des());
+        data16.Set(iDataHBuf16->Des());
+        data16.Copy(_L("")); // Initialize aData buffer
+        
+        if( (aData.Length() + extraLength) > iStaticBufferSize )
+            {
+             RDebug::Print(_L("Warning: buffer size too small, not able to log!"));
+             return KErrOverflow;
+            }        
+        }
+    else
+        {        
+        // We'll create a local HBufC, deleting it in the end of this method
+        dataHBuf8 = HBufC8::New( space + extraLength );
+        if( dataHBuf8 == NULL )
+            {
+            return KErrNoMemory;
+            }
+        dataHBuf16 = HBufC16::New(space + extraLength);
+        if(dataHBuf16 == NULL)
+            {
+            delete dataHBuf8;
+            return KErrNoMemory;
+            }
+        data8.Set(dataHBuf8->Des());
+        data16.Set(dataHBuf16->Des());
+        }
+
+    // Event ranking
+    if( iWithEventRanking && aWithEventRanking && !iWithTimeStamp )
+        {
+        EventRanking( data16 );      // Event ranking to data
+        data16.Append( aData );      // Unicode aData to normal text
+        }
+    // Time stamp
+    else if( iWithTimeStamp && aWithTimeStamp )
+        {
+        // With event ranking
+        if( iWithEventRanking && aWithEventRanking )
+            {
+            EventRanking( data16 );  // Event ranking to data
+            }
+        AddTimeStampToData( data16 );// Add time stamp
+        data16.Append( aData );      // Unicode aData to normal text
+        }
+    else
+        {
+        data16.Copy( aData );        // Unicode aData to normal text
+        }
+
+    // NOTE: If need some special line break do it with logging phase
+
+    // If html logging and line break is used add the line break.
+    if (( iLoggerType == CStifLogger::EHtml ) && iWithLineBreak && aWithLineBreak )
+        {
+        data16.Append( _L( "<BR>" ) );
+        data16.Append( _L( "\n" ) );  // To make html file more readable
+                                    // with text editor
+        }
+
+    // Other cases line break is normal '\n' if logging is used
+    else if( iWithLineBreak && aWithLineBreak )
+        {
+        data16.Append( 0x0D ); // 13 or '\' in Symbian OS
+        data16.Append( 0x0A ); // 10 or 'n' in Symbian OS
+        }
+
+    // Write the data to file
+    TInt tmp = 0;
+    if( iFile.Seek( ESeekEnd, tmp ) == KErrNone )
+        {
+        RDEBUG_FILEWRITECRASH(_L("iFile.Write 1 in"));
+        TPtrC8 dataToFile(0, 0);
+        if(iUnicode)
+            {
+            dataToFile.Set((TUint8 *)(data16.Ptr()), data16.Length() * 2);
+            }
+        else
+            {
+            data8.Copy(data16);
+            dataToFile.Set(data8);
+            }
+        if(iFile.Write(dataToFile) == KErrNone)
+            iFile.Flush();
+        RDEBUG_FILEWRITECRASH(_L("iFile.Write 1 out"));
+        }
+    if( iDataHBuf8 == NULL )
+        {
+        delete dataHBuf8;
+        dataHBuf8 = 0;
+        delete dataHBuf16;
+        dataHBuf16 = 0;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: Write
+
+    Description: Write log information or data to the file. 8 bit.
+
+    Parameters: TBool aWithTimeStamp: in: Is time stamp flag used
+                TBool aWithLineBreak: in: Is line break flag used
+                TBool aWithEventRanking: in: Is event ranking flag used
+                const TDesC8& aData: in: Logged or saved data
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CFileOutput::Write( TBool aWithTimeStamp, TBool aWithLineBreak,
+                            TBool aWithEventRanking, const TDesC8& aData )
+    {
+    TInt extraLength( 0 );  // Line and/or event required length
+
+    TPtr data16(0, 0);
+    TPtr8 data8(0, 0);
+
+    // Extra space calculation
+    if( iWithEventRanking && aWithEventRanking )
+        {
+        extraLength = extraLength + KMaxEventRanking + KMaxSpace;
+        }
+    if( ( iLoggerType == CStifLogger::EHtml ) && iWithLineBreak && aWithLineBreak )
+        {
+        extraLength = extraLength + KMaxHtmlLineBreak;
+        }
+    if( iWithLineBreak && aWithLineBreak )
+        {
+        extraLength = extraLength + KMaxLineBreak;
+        }
+    if( aWithTimeStamp && iWithTimeStamp )
+        {
+        extraLength = extraLength + KMaxTimeStamp;
+        }
+
+    // aData straight to the file
+    if ( extraLength == 0 && !iUnicode)
+        {
+        // Write the data to file
+        TInt tmp = 0;
+        if( iFile.Seek( ESeekEnd, tmp ) == KErrNone )
+            {
+            RDEBUG_FILEWRITECRASH(_L("iFile.Write 2 in"));
+            if( iFile.Write( aData ) == KErrNone )
+                iFile.Flush();
+            RDEBUG_FILEWRITECRASH(_L("iFile.Write 2 out"));
+            }
+        return KErrNone;
+        }
+
+    // Calculated space
+    TInt space = aData.Length();
+    HBufC8* dataHBuf8 = NULL;
+    HBufC* dataHBuf16 = NULL;
+
+    if( iDataHBuf8 != NULL )
+        {
+        // We'll use HBufC created in ConstructL
+        data8.Set(iDataHBuf8->Des());
+        data8.Copy(_L("")); // Initialize aData buffer
+        data16.Set(iDataHBuf16->Des());
+        
+        if( (aData.Length() + extraLength) > iStaticBufferSize )
+            {
+             RDebug::Print(_L("Warning: buffer size too small, not able to log!"));
+             return KErrOverflow;
+            }        
+        }
+    else
+        {        
+        // We'll create a local HBufC, deleting it in the end of this method
+        dataHBuf8 = HBufC8::New( space + extraLength );
+        if( dataHBuf8 == NULL )
+            {
+            return KErrNoMemory;
+            }
+        dataHBuf16 = HBufC16::New(space + extraLength);
+        if(dataHBuf16 == NULL)
+            {
+            delete dataHBuf8;
+            return KErrNoMemory;
+            }
+        data8.Set(dataHBuf8->Des());  // Memory allocation for data
+        data16.Set(dataHBuf16->Des());  // Memory allocation for data
+        }
+
+    // Event ranking
+    if( iWithEventRanking && aWithEventRanking && !iWithTimeStamp )
+        {
+        EventRanking( data8 );      // Event ranking to data
+        data8.Append( aData );      // Unicode aData to normal text
+        }
+    // Time stamp
+    else if( iWithTimeStamp && aWithTimeStamp )
+        {
+        // With event ranking
+        if( iWithEventRanking && aWithEventRanking )
+            {
+            EventRanking( data8 );  // Event ranking to data
+            }
+        AddTimeStampToData( data8 );// Add time stamp
+        data8.Append( aData );      // Unicode aData to normal text
+        }
+    else
+        {
+        data8.Copy( aData );        // Unicode aData to normal text
+        }
+
+    // NOTE: If need some special line break do it with logging phase
+
+    // If html logging and line break is used add the line break.
+    if ( ( iLoggerType == CStifLogger::EHtml ) && iWithLineBreak && aWithLineBreak )
+        {
+        data8.Append( _L( "<BR>" ) );
+        data8.Append( _L( "\n" ) );  // To make html file more readable
+                                    // with text editor
+        }
+
+    // Other cases line break is normal '\n' if logging is used
+    else if( iWithLineBreak && aWithLineBreak )
+        {
+        data8.Append( 0x0D ); // 13 or '\' in Symbian OS
+        data8.Append( 0x0A ); // 10 or 'n' in Symbian OS
+        }
+
+    // Write the data to file
+    TInt tmp = 0;
+    if( iFile.Seek( ESeekEnd, tmp ) == KErrNone )
+        {
+        RDEBUG_FILEWRITECRASH(_L("iFile.Write 3 in"));
+        TPtrC8 dataToFile(0, 0);
+        if(iUnicode)
+            {
+            data16.Copy(data8);
+            dataToFile.Set((TUint8 *)(data16.Ptr()), data16.Length() * 2);
+            }
+        else
+            {
+            dataToFile.Set(data8);
+            }
+        if(iFile.Write(dataToFile) == KErrNone)
+            iFile.Flush();
+        RDEBUG_FILEWRITECRASH(_L("iFile.Write 3 out"));
+        }
+    if( iDataHBuf8 == NULL )
+        {
+        delete dataHBuf8;
+        dataHBuf8 = 0;
+        delete dataHBuf16;
+        dataHBuf16 = 0;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: EventRanking
+
+    Description: For event ranking logging.
+
+    Parameters: TPtr& aData: inout: Data with event ranking
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::EventRanking( TPtr& aData )
+    {
+    // Returns the machine's current tick count.
+    TUint tick = User::TickCount();
+    tick &= 0xffff;
+    aData.AppendNum( tick );
+    aData.Append( _L( " " ) );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: EventRanking
+
+    Description: For event ranking logging.
+
+    Parameters: TPtr8& aData: inout: Data with event ranking
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::EventRanking( TPtr8& aData )
+    {
+    // Returns the machine's current tick count.
+    TUint tick = User::TickCount();
+    tick &= 0xffff;
+    aData.AppendNum( tick );
+    aData.Append( _L8( " " ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: AddTimeStampToData
+
+    Description: For date and time logging.
+
+    Parameters: TPtr& aData: inout: Data with time stamps
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::AddTimeStampToData( TPtr& aData )
+    {
+    TStifLoggerTimeStamp timeStamp;
+    GetDateAndTime( timeStamp );
+
+    TStifLoggerTimeStamp8 tStamp16;
+    tStamp16.Copy(timeStamp);
+
+    aData.Append( tStamp16 );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: AddTimeStampToData
+
+    Description: For date and time logging.
+
+    Parameters: TPtr8& aData: inout: Data with time stamps
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::AddTimeStampToData( TPtr8& aData )
+    {
+    TStifLoggerTimeStamp timeStamp;
+    GetDateAndTime( timeStamp );
+    aData.Append( timeStamp );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: GetDateAndTime
+
+    Description: For date and time logging.
+
+    Parameters: TStifLoggerTimeStamp& aDataAndTime: inout: Generated date and time
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CFileOutput::GetDateAndTime( TStifLoggerTimeStamp& aDataAndTime )
+    {
+    TInt num( 0 );
+    TInt microseconds( 0 );
+
+    // Append date
+    TTime time;
+    time.HomeTime();
+    TDateTime dateTime( time.DateTime() );
+
+    num = dateTime.Day() + 1;
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    // Append month
+    aDataAndTime.AppendNum( num );
+    aDataAndTime.Append( '.' );
+    num = 0;
+    num = dateTime.Month();
+    switch( num )
+        {
+        case EJanuary:      // 1
+            {
+             aDataAndTime.Append( _L( "Jan" ) );
+             break;
+            }
+        case EFebruary:     // 2
+            {
+             aDataAndTime.Append( _L( "Feb" ) );
+             break;
+            }
+        case EMarch:        // 3
+            {
+             aDataAndTime.Append( _L( "Mar" ) );
+             break;
+            }
+        case EApril:        // 4
+            {
+             aDataAndTime.Append( _L( "Apr" ) );
+             break;
+            }
+        case EMay:          // 5
+            {
+             aDataAndTime.Append( _L( "May" ) );
+             break;
+            }
+        case EJune:         // 6
+            {
+             aDataAndTime.Append( _L( "Jun" ) );
+             break;
+            }
+        case EJuly:         // 7
+            {
+             aDataAndTime.Append( _L( "Jul" ) );
+             break;
+            }
+        case EAugust:       // 8
+            {
+             aDataAndTime.Append( _L( "Aug" ) );
+             break;
+            }
+        case ESeptember:    // 9
+            {
+             aDataAndTime.Append( _L( "Sep" ) );
+             break;
+            }
+        case EOctober:      // 10
+            {
+             aDataAndTime.Append( _L( "Oct" ) );
+             break;
+            }
+        case ENovember:     // 11
+            {
+             aDataAndTime.Append( _L( "Nov" ) );
+             break;
+            }
+        case EDecember:     // 12
+            {
+             aDataAndTime.Append( _L( "Dec" ) );
+             break;
+            }
+        default:
+            {
+             aDataAndTime.Append( '-' );
+             break;
+            }
+        }
+   // Append year
+    aDataAndTime.Append( '.' );
+    aDataAndTime.AppendNum( dateTime.Year() );
+
+    // Append time
+    aDataAndTime.Append( ' ' );
+    num = dateTime.Hour();
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    aDataAndTime.AppendNum( num );
+    aDataAndTime.Append( ':' );
+    num = dateTime.Minute();
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    aDataAndTime.AppendNum( num );
+    aDataAndTime.Append( ':' );
+
+    num = dateTime.Second();                // Seconds
+    microseconds = dateTime.MicroSecond();  // Microseconds
+
+    // Seconds
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    aDataAndTime.AppendNum( num );
+
+    // Milliseconds
+    aDataAndTime.Append( '.' );
+    aDataAndTime.AppendNumFixedWidth( microseconds, EDecimal, 3 );
+
+    // NOTE: If you add more spaces etc. remember increment KMaxTimeStamp size!
+
+    if ( iLoggerType == CStifLogger::EHtml )
+        {
+        aDataAndTime.Append( _L("....") );
+        }
+    else
+        {
+        aDataAndTime.Append( _L("    ") );
+        }
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/HtmlLogger.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,570 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CHtmlLogger 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "HtmlLogger.h"
+#include "Output.h"
+#include "LoggerTracing.h"
+#include "LoggerOverFlow.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: CHtmlLogger
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: COutput* output: in: Output source
+                const TDesC& aTestFile: in: Log filename
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CHtmlLogger::CHtmlLogger( COutput* output,
+                          const TDesC& aTestFile,
+                          TBool aThreadIdToLogFile )
+    {
+    iOutput = output;
+    StartHtmlPage( aTestFile, aThreadIdToLogFile );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CHtmlLogger::ConstructL()
+    {
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: const TDesC& aTestPath: in: Log path
+                const TDesC& aTestFile: in: Log filename
+                TLoggerType aLoggerType: in: File type
+                TOutput aOutput: in: Output source
+                TBool aOverWrite: in: For file overwrite
+                TBool aWithTimeStamp: in: For timestamp
+                TBool aWithLineBreak: in: For line break
+                TBool aWithEventRanking: in: For events ranking to file
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+                TBool aCreateLogDir: in: Indicator to directory creation
+                TInt  aStaticBufferSize
+                TBool aUnicode: in: Indicator if file has to be in unicode format
+
+    Return Values: CHtmlLogger*: pointer to CHtmlLogger object
+
+    Errors/Exceptions: Leaves if called COutput::NewL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CHtmlLogger* CHtmlLogger::NewL( const TDesC& aTestPath,
+                                const TDesC& aTestFile,
+                                TLoggerType aLoggerType,
+                                TOutput aOutput,
+                                TBool aOverWrite,
+                                TBool aWithTimeStamp,
+                                TBool aWithLineBreak,
+                                TBool aWithEventRanking,
+                                TBool aThreadIdToLogFile,
+                                TBool aCreateLogDir,
+                                TInt aStaticBufferSize,
+                                TBool aUnicode )
+    {
+    __TRACE( KInfo, ( _L( "STIFLOGGER: Creating html logger" ) ) );
+
+    // Create COutput object output
+    COutput* output = COutput::NewL( aTestPath,
+                                        aTestFile,
+                                        aLoggerType,
+                                        aOutput,
+                                        aOverWrite,
+                                        aWithTimeStamp,
+                                        aWithLineBreak,
+                                        aWithEventRanking,
+                                        aThreadIdToLogFile,
+                                        aCreateLogDir,
+                                        aStaticBufferSize,
+                                        aUnicode );
+
+    CleanupStack::PushL( output ); 
+    __ASSERT_ALWAYS( output != NULL, User::Leave( KErrNotFound ) );
+    // Create CTxtLogger object htmlLogger and bind to COutput
+    CHtmlLogger* htmlLogger = new (ELeave) CHtmlLogger( output,
+                                                        aTestFile,
+                                                        aThreadIdToLogFile );
+    // HTML logger owns output object and it will be destroyed in STIFLogger
+    // destructor.
+    CleanupStack::Pop( output ); 
+    
+    CleanupStack::PushL( htmlLogger );
+    htmlLogger->ConstructL();
+    CleanupStack::Pop( htmlLogger );
+
+    return htmlLogger;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: ~CHtmlLogger
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CHtmlLogger::~CHtmlLogger()
+    {
+
+    EndHtmlPage();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: StartHtmlPage
+
+    Description: Initialize html page.
+
+    Parameters: const TDesC& aTestFile: in: Log filename
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+
+    Return Values: None
+
+    Errors/Exceptions:  TDesLoggerOverflowHandler called if logged data is 
+                        over KMaxFileName.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CHtmlLogger::StartHtmlPage( const TDesC& aTestFile,
+                                    TBool aThreadIdToLogFile )
+    {
+    TFileName title;
+
+    // Create overflow handler.
+    TDesLoggerOverflowHandler overFlowHandler( this, 4 );
+
+    // Title
+    if( aTestFile.Length() < KMaxFileName )
+        {
+        title.Append( aTestFile );
+        }    
+    else
+        {
+        // If the title size is over the KMaxFileName rest of the title
+        // will cut. Use normal overflowhandler to print overflow information.
+        TBuf<4> empty; // Not really used.
+        overFlowHandler.Overflow( empty );
+        TPtrC cuttedtitle = aTestFile.Left( KMaxFileName );
+        title.Append( cuttedtitle );
+        }        
+        
+    // Add Thread id to title if enough space and test file is given and 
+    // aThreadIdToLogFile is true
+    if( title.Length() <  ( KMaxFileName - 3 ) && aTestFile.Length() > 0 &&
+        aThreadIdToLogFile )
+        {
+        title.Append( _L( "_" ) );
+        RThread threadHandle;                   // A handle to a thread
+        TThreadId id = threadHandle.Id();       // Encapsulates the 
+                                                // Id of a thread
+        // Appends id in hexadesimal format                           
+        title.AppendFormat( _L( "%x" ), (TInt)id );   
+        }
+
+    // Html start tags to whole page and header section
+    iOutput->Write( EFalse, EFalse, EFalse,
+                    _L8( "\n<html>\n<head>\n<title>" ) );
+    // Html file title
+    iOutput->Write( EFalse, EFalse, EFalse, title );
+    // Html header section end tags and start tag to body section
+    iOutput->Write( EFalse, EFalse, EFalse,
+                    _L8( "</title>\n</head>\n\n\n<body>\n" ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: EndHtmlPage
+
+    Description: Finalize html page.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CHtmlLogger::EndHtmlPage()
+    {
+    // Html page and body section end tags
+    iOutput->Write( EFalse, EFalse, EFalse,
+                    _L8( "\n\n\n</html>\n</body>\n\n\n" ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: StyleStarting
+
+    Description: Start style information logging.
+
+    Parameters: TInt aStyle: in: Style information
+                TBool aTimeStamp: inout: Time stamp indicator
+                TBool aEventRanking: inout: Event ranking indicator
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CHtmlLogger::StyleStarting( TInt aStyle, TBool& aTimeStamp,
+                                    TBool& aEventRanking )
+    {
+    if ( 0x00020 <= aStyle ||       // ERed, 0x00020 => 32
+            0x00040 <= aStyle ||    // EImportant, 0x00040 => 64
+            0x00080 <= aStyle ||    // EWarning, 0x00080 => 128
+            0x00100 <= aStyle )     // EError, 0x00100 => 256
+        {
+        iOutput->Write( EFalse, EFalse, EFalse,
+                                        _L8( "<FONT COLOR='#FF0000'>" ) );
+        if ( 0x00100 <= aStyle )
+            {
+            iOutput->Write( aTimeStamp, EFalse, aEventRanking,
+                                        _L8( "ERROR..." ) );
+            aStyle -= 0x00100;
+            aTimeStamp = EFalse;    // Time stamp added no time stamp to the
+                                    // forward operations
+            aEventRanking = EFalse; // Event ranking added no event ranking
+                                    // to the forward operations
+            }
+        if ( 0x00080 <= aStyle )
+            {
+            iOutput->Write( aTimeStamp, EFalse, aEventRanking,
+                                        _L8( "WARNING..." ) );
+            aStyle -= 0x00080;
+            aTimeStamp = EFalse;    // Time stamp added no time stamp to the 
+                                    // forward operations
+            aEventRanking = EFalse; // Event ranking added no event ranking
+                                    // to the forward operations
+            }
+        if ( 0x00040 <= aStyle )
+            {
+            iOutput->Write( aTimeStamp, EFalse, aEventRanking,
+                                        _L8( "IMPORTANT..." ) );
+            aStyle -= 0x00040;
+            aTimeStamp = EFalse;    // Time stamp added no time stamp to the 
+                                    // forward operations
+            aEventRanking = EFalse; // Event ranking added no event ranking
+                                    // to the forward operations
+            }
+        if ( 0x00020 <= aStyle )
+            {
+            aStyle -= 0x00020;
+            }
+        }
+    // EGreen, 0x00010 => 16
+    if ( 0x00010 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse,
+                        _L8( "<FONT COLOR='#009900'>" ) );
+        aStyle -= 0x00010;
+        }
+    // EBlue, 0x00008 => 8
+    if ( 0x00008 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse,
+                        _L8( "<FONT COLOR='#3333FF'>" ) );
+        aStyle -= 0x00008;
+        }
+    // EUnderline, 0x00004 => 4
+    if ( 0x00004 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "<U>" ) );
+        aStyle -= 0x00004;
+        }
+    // ECursive, 0x00002 => 2
+    if ( 0x00002 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "<I>" ) );
+        aStyle -= 0x00002;
+        }
+    // EBold, 0x00001 => 1
+    if ( 0x00001 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "<B>" ) );
+        aStyle -= 0x00001;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: StyleEnding
+
+    Description: Ends style information logging.
+
+    Parameters: TInt aStyle: in: Style information
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CHtmlLogger::StyleEnding( TInt aStyle )
+    {
+    if ( 0x00020 <= aStyle ||       // ERed, 0x00020 => 32
+            0x00040 <= aStyle ||    // EImportant, 0x00040 => 64
+            0x00080 <= aStyle ||    // EWarning, 0x00080 => 128
+            0x00100 <= aStyle )     // EError, 0x00100 => 256
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "</FONT>" ) );
+        if ( 0x00100 <= aStyle )
+            {
+            aStyle -= 0x00100;
+            }
+        if ( 0x00080 <= aStyle )
+            {
+            aStyle -= 0x00080;
+            }
+        if ( 0x00040 <= aStyle )
+            {
+            aStyle -= 0x00040;
+            }
+        if ( 0x00020 <= aStyle )
+            {
+            aStyle -= 0x00020;
+            }
+        }
+    // EGreen, 0x00010 => 16
+    if ( 0x00010 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "</FONT>" ) );
+        aStyle -= 0x00010;
+        }
+    // EBlue, 0x00008 => 8
+    if ( 0x00008 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "</FONT>" ) );
+        aStyle -= 0x00008;
+        }
+    // EUnderline, 0x00004 => 4
+    if ( 0x00004 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "</U>" ) );
+        aStyle -= 0x00004;
+        }
+    // ECursive, 0x00002 => 2
+    if ( 0x00002 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "</I>" ) );
+        aStyle -= 0x00002;
+        }
+    // EBold, 0x00001 => 1
+    if ( 0x00001 <= aStyle )
+        {
+        iOutput->Write( EFalse, EFalse, EFalse, _L8( "</B>" ) );
+        aStyle -= 0x00001;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: Send
+
+    Description: Send style information and 16 bit data to the output module
+
+    Parameters: TInt TStyle: in: Text forming
+                const TDesC& aData: in: Data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CHtmlLogger::Send( TInt aStyle, const TDesC& aData )
+    {
+    // Time stamp indicator
+    TBool timestamp( ETrue );
+    // Event ranking indicator
+    TBool eventranking( ETrue );
+
+    StyleStarting( aStyle, timestamp, eventranking );
+
+    TInt ret = iOutput->Write( timestamp, ETrue, eventranking, aData );
+
+    StyleEnding( aStyle );
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CHtmlLogger
+
+    Method: Send
+
+    Description: Send style information and 8 bit data to the output module
+
+    Parameters: TInt TStyle: in: Text forming
+                const TDesC8& aData: in: Data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CHtmlLogger::Send( TInt aStyle, const TDesC8& aData )
+    {
+    // Time stamp indicator
+    TBool timestamp( ETrue );
+    // Event ranking indicator
+    TBool eventranking( ETrue );
+
+    StyleStarting( aStyle, timestamp, eventranking );
+
+    TInt ret = iOutput->Write( timestamp, ETrue, eventranking, aData );
+
+    StyleEnding( aStyle );
+
+    return ret;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/LoggerOverFlow.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,296 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* TDesLoggerOverflowHandler class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "LoggerOverFlow.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TDesLoggerOverflowHandler
+
+    Method: TDesLoggerOverflowHandler
+
+    Description: Default constructor
+
+    Parameters: CStifLogger* aLogger: in: Pointer to CStifLogger object
+                TInt aOverFlowSource: in: Over flow source
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TDesLoggerOverflowHandler::TDesLoggerOverflowHandler( CStifLogger* aLogger,
+                                            TInt aOverFlowSource )
+    {
+    iLogger = aLogger;
+    iOverFlowSource = aOverFlowSource;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TDesLoggerOverflowHandler
+
+    Method: TDesLoggerOverflowHandler
+
+    Description: Default constructor
+
+    Parameters: CRDebugOutput* aRDebugOutput: in: Pointer to CFileOutput object
+                TInt aOverFlowSource: in: Over flow source
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+// For future needs
+// TDesLoggerOverflowHandler::TDesLoggerOverflowHandler(
+//                                             CRDebugOutput* aRDebugOutput,
+//                                             TInt aOverFlowSource )
+//     {
+//     iRDebugOutput = aRDebugOutput;
+//     iOverFlowSource = aOverFlowSource;
+// 
+//     }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TDesLoggerOverflowHandler
+
+    Method: Overflow
+
+    Description: Simple overflow handling(16 bit)
+
+    Parameters: TDes16 &aDes: in: Reference to over flow data
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void TDesLoggerOverflowHandler::Overflow( TDes16& aDes )
+    {
+    __TRACE( KError, ( _L( "STIFLOGGER: Over flow" ) ) );
+
+    // If overflow
+    TInt len( 0 );
+    len = aDes.Length();
+
+    // const TInt to TInt avoiding warnings
+    TInt maxLogData = KMaxLogData;
+    TInt maxTestFileName = KMaxFileName;
+
+    // Overflow: Log() without aStyle or Log() with aStyle
+    if ( ( iOverFlowSource == 1 || iOverFlowSource == 2 )
+            &&  maxLogData > 60 )
+        {
+        // Log overflow info if info is in allowed limits
+        aDes[len-2] = 13;   // 13 or '\' in Symbian OS
+        aDes[len-1] = 10;   // 10 or 'n' in Symbian OS
+        // ~60
+        iLogger->Send( 0, _L("Log() OVERFLOW: Check aLogInfo and KMaxLogData !!!") );
+        }
+    // Overflow: WriteDelimiter()
+    if ( iOverFlowSource == 3 &&  maxLogData > 70 )
+        {
+        // Log overflow info if info is in allowed limits, ~70
+        iLogger->Send( 0, _L( "WriteDelimiter() OVERFLOW: Check delimiter and KMaxLogData !!!" ) );
+        }
+    // Overflow: StartHtmlPage()
+    if ( iOverFlowSource == 4 &&  maxTestFileName > 70 )
+        {
+        // Log overflow info if info is in allowed limits, ~70
+        iLogger->Send( 0, _L( "aTestFile OVERFLOW: Check aTestFile and KMaxFileName !!!" ) );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of TDes8LoggerOverflowHandler class
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TDes8OverflowHandler
+
+    Method: TDes8LoggerOverflowHandler
+
+    Description: Default constructor
+
+    Parameters: CStifLogger* aLogger: in: Pointer to CStifLogger object
+                TInt aOverFlowSource: in: Over flow source
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TDes8LoggerOverflowHandler::TDes8LoggerOverflowHandler( CStifLogger* aLogger,
+                                                        TInt aOverFlowSource )
+    {
+    iLogger = aLogger;
+    iOverFlowSource = aOverFlowSource;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TDes8LoggerOverflowHandler
+
+    Method: TDes8LoggerOverflowHandler
+
+    Description: Default constructor
+
+    Parameters: CRDebugOutput* aRDebugOutput: in: Pointer to CFileOutput object
+                TInt aOverFlowSource: in: Over flow source
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+// For future needs
+// TDes8LoggerOverflowHandler::TDes8LoggerOverflowHandler( 
+//                                             CRDebugOutput* aRDebugOutput,
+//                                             TInt aOverFlowSource )
+//     {
+//     iRDebugOutput = aRDebugOutput;
+//     iOverFlowSource = aOverFlowSource;
+
+//     }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TDes8LoggerOverflowHandler
+
+    Method: Overflow
+
+    Description: Simple overflow handling(8 bit)
+
+    Parameters: TDes8 &aDes: in: Reference to over flow data
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void TDes8LoggerOverflowHandler::Overflow( TDes8& aDes )
+    {
+    __TRACE( KError, ( _L( "STIFLOGGER: Over flow" ) ) );
+
+    // If overflow
+    TInt len( 0 );
+    len = aDes.Length();
+
+    // const TInt to TInt avoiding warnings
+    TInt maxLogData = KMaxLogData;
+    TInt maxTestFileName = KMaxFileName;
+
+    // Overflow: Log() without aStyle or Log() with aStyle
+    if ( ( iOverFlowSource == 1 || iOverFlowSource == 2 )
+            &&  maxLogData > 60 )
+        {
+        // Log overflow info if info is in allowed limits
+        aDes[len-2] = 13;   // 13 or '\' in Symbian OS
+        aDes[len-1] = 10;   // 10 or 'n' in Symbian OS
+        // ~60
+        iLogger->Send( 0, _L("Log() OVERFLOW: Check aLogInfo and KMaxLogData !!!") );
+        }
+    // Overflow: WriteDelimiter()
+    if ( iOverFlowSource == 3 &&  maxLogData > 70 )
+        {
+        // Log overflow info if info is in allowed limits, ~70
+        iLogger->Send( 0, _L( "WriteDelimiter() OVERFLOW: Check delimiter and KMaxLogData !!!" ) );
+        }
+    // Overflow: StartHtmlPage()
+    if ( iOverFlowSource == 4 &&  maxTestFileName > 70 )
+        {
+        // Log overflow info if info is in allowed limits, ~70
+        iLogger->Send( 0, _L( "aTestFile OVERFLOW: Check aTestFile and KMaxFileName !!!" ) );
+        }
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/NullOutput.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,232 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CNullOutput 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include "Output.h"
+#include "NullOutput.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CNullOutput
+
+    Method: CNullOutput
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CNullOutput::CNullOutput()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CNullOutput
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CNullOutput::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CNullOutput
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: None
+
+    Return Values: CNullOutput*: pointer to CNullOutput object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CNullOutput* CNullOutput::NewL()
+    {
+    // Create CNullOutput object nullOutput
+    CNullOutput* nullOutput = new (ELeave) CNullOutput();
+
+    CleanupStack::PushL( nullOutput );
+    nullOutput->ConstructL();
+    CleanupStack::Pop( nullOutput );
+
+    return nullOutput;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CNullOutput
+
+    Method: ~CNullOutput
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CNullOutput::~CNullOutput()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CNullOutput
+
+    Method: Write
+
+    Description: Write log information or data to the file. 16 bit.
+
+    CNullOutput's Write() method purpose is to look like logging although it
+    don't do any logging operations.
+
+    Parameters: TBool aWithTimeStamp: in: Is time stamp flag used
+                TBool aWithLineBreak: in: Is line break flag used
+                TBool aWithEventRanking: in: Is event ranking flag used
+                const TDesC& aData: in: Logged or saved data
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CNullOutput::Write( TBool /* aWithTimeStamp */, 
+                            TBool /* aWithLineBreak */,
+                            TBool /* aWithEventRanking */,
+                            const TDesC& /* aData */ )
+    {
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CNullOutput
+
+    Method: Write
+
+    Description: Write log information or data to the file. 8 bit.
+
+    CNullOutput's Write() method purpose is to look like logging although it
+    don't do any logging operations.
+
+    Parameters: TBool aWithTimeStamp: in: Is time stamp flag used
+                TBool aWithLineBreak: in: Is line break flag used
+                TBool aWithEventRanking: in: Is event ranking flag used
+                const TDesC8& aData: in: Logged or saved data
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CNullOutput::Write(  TBool /* aWithTimeStamp */, 
+                            TBool /* aWithLineBreak */,
+                            TBool /* aWithEventRanking */,
+                            const TDesC8& /* aData */ )
+    {
+    return KErrNone;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/Output.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,243 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of COutput 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "Output.h"
+#include "FileOutput.h"
+#include "NullOutput.h"
+#include "LoggerOverFlow.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: COutput
+
+    Method: COutput
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+COutput::COutput()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: COutput
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    NOTE: At the moment there is only one output module implemented
+
+    Parameters: const TDesC& aTestPath: in: Path to logged information
+                const TDesC& aTestFile: in: Log name for information
+                TLoggerType aLoggerType: in: Log file type
+                TOutput aOutput: in: Output source
+                TBool aOverWrite: in: Indicator to file overwrite
+                TBool aWithTimeStamp: in: Indicator to time stamp
+                TBool aWithLineBreak: in: Indicator to line break
+                TBool aWithEventRanking: in: Indicator to event ranking
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+                TBool aCreateLogDir: in: Indicator to directory creation
+                TInt  aStaticBufferSize
+                TBool aUnicode: in: Indicator if file has to be in unicode format
+
+    Return Values: COutput*: pointer to COutput object
+
+    Errors/Exceptions:  Leaves if called CFileOutput::NewL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+COutput* COutput::NewL( const TDesC& aTestPath,
+                        const TDesC& aTestFile,
+                        CStifLogger::TLoggerType aLoggerType,
+                        CStifLogger::TOutput aOutput,
+                        TBool aOverWrite,
+                        TBool aWithTimeStamp,
+                        TBool aWithLineBreak,
+                        TBool aWithEventRanking,
+                        TBool aThreadIdToLogFile,
+                        TBool aCreateLogDir,
+                        TInt aStaticBufferSize,
+                        TBool aUnicode )
+    {
+
+    if ( aOutput == CStifLogger::EFile )
+        {
+        CFileOutput* fileOutput = NULL;
+        // Create CFileOutput object fileOutput
+        TRAPD( err, fileOutput = CFileOutput::NewL( aTestPath,
+                                                    aTestFile,
+                                                    aLoggerType,
+                                                    aOverWrite,
+                                                    aWithTimeStamp,
+                                                    aWithLineBreak,
+                                                    aWithEventRanking,
+                                                    aThreadIdToLogFile,
+                                                    aCreateLogDir,
+                                                    aStaticBufferSize,
+                                                    aUnicode ) );
+
+        // Probably path or file name is over allowed size
+        if ( err == KErrArgument )
+            {
+            User::Leave( KErrArgument );
+            return NULL; // Never return because leave above
+            }
+        // Not enough memory, @js
+        else if ( err == KErrNoMemory )
+            {
+            User::Leave( KErrNoMemory );
+            return NULL;
+            }                      
+        // If e.g. path not found so we create CNullOutput to avoiding leave
+        // operation. CNullOutput looks logging although it won't.
+        else if ( err != KErrNone )
+            {
+            CNullOutput* nullOutput = CNullOutput::NewL();
+            nullOutput->SetOutputCreationResult( err, aOutput );
+            return nullOutput;
+            }
+        // CFileOutput creation made succesfully
+        else
+            {
+            fileOutput->SetOutputCreationResult( err, aOutput );
+            return fileOutput;
+            }
+        }
+    else if ( aOutput == CStifLogger::ERDebug )
+        {
+        CRDebugOutput* rdebugOutput = NULL;
+        // Create CRDebugOutput object rdebugOutput
+        TRAPD( err, rdebugOutput = CRDebugOutput::NewL( aTestPath, 
+                                                        aTestFile,
+                                                        aLoggerType,
+                                                        aOverWrite,
+                                                        aWithTimeStamp,
+                                                        aWithLineBreak,
+                                                        aWithEventRanking,
+                                                        aThreadIdToLogFile,
+                                                        aCreateLogDir,
+                                                        aStaticBufferSize ) );
+
+        // Probably path or file name is over allowed size
+        if ( err == KErrArgument )
+            {
+            User::Leave( KErrArgument );
+            return NULL; // Never return because leave above
+            }
+        // If e.g. no memory so we create CNullOutput to avoiding leave
+        // operation. CNullOutput looks logging although it won't.
+        else if ( err != KErrNone )
+            {
+            CNullOutput* nullOutput = CNullOutput::NewL();
+            nullOutput->SetOutputCreationResult( err, aOutput );
+            return nullOutput;
+            }
+        // CRDebugOutput creation made succesfully
+        else
+            {
+            rdebugOutput->SetOutputCreationResult( err, aOutput );
+            return rdebugOutput;
+            }
+        }
+    else
+        {
+        User::Leave( KErrArgument );
+        return NULL; // Never return because leave above
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: COutput
+
+    Method: ~COutput
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+COutput::~COutput()
+    {
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/RDebugOutput.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,684 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CRDebugOutput 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "Output.h"
+#include "RDebugOutput.h"
+#include "LoggerOverFlow.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRDebugOutput
+
+    Method: CRDebugOutput
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: TLoggerType aLoggerType: in: File type
+                TBool aWithTimeStamp: in: For timestamp
+                TBool aWithLineBreak: in: For line break
+                TBool aWithEventRanking: in: For events ranking to file
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CRDebugOutput::CRDebugOutput( CStifLogger::TLoggerType aLoggerType,
+                                TBool aWithTimeStamp,
+                                TBool aWithLineBreak,
+                                TBool aWithEventRanking ) :
+    COutput()
+    {
+    // Indicates file type
+    iLoggerType = aLoggerType;
+
+    // Time stamp indicator
+    iWithTimeStamp = aWithTimeStamp;
+
+    // Line break indicator
+    iWithLineBreak = aWithLineBreak;
+
+    // Log event ranking indicator
+    iWithEventRanking = aWithEventRanking;
+
+    // Data buffer
+    iDataHBuf = NULL;
+    iDataHBuf1 = NULL;
+    iDataHBuf2 = NULL;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRDebugOutput
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CRDebugOutput::ConstructL( TInt aStaticBufferSize )
+    {
+    if( aStaticBufferSize != 0)
+        {
+        iDataHBuf1 = HBufC::NewL( aStaticBufferSize );      
+        iDataHBuf2 = HBufC::NewL( aStaticBufferSize );      
+        iStaticBufferSize = aStaticBufferSize;
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRDebugOutput
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: const TDesC& aTestPath: in: Log path
+                const TDesC& aTestFile: in: Log filename
+                TLoggerType aLoggerType: in: File type
+                TBool aOverWrite: in: For file overwrite
+                TBool aWithTimeStamp: in: For timestamp
+                TBool aWithLineBreak: in: For line break
+                TBool aWithEventRanking: in: For events ranking to file
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+                TBool aCreateLogDir: in: Indicator to directory creation
+
+    Return Values: CRDebugOutput*: pointer to CFileOutput object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CRDebugOutput* CRDebugOutput::NewL( const TDesC& /* aTestPath */,
+                                    const TDesC& /* aTestFile */,
+                                    CStifLogger::TLoggerType aLoggerType,
+                                    TBool /* aOverWrite */,
+                                    TBool aWithTimeStamp,
+                                    TBool aWithLineBreak,
+                                    TBool aWithEventRanking,
+                                    TBool /* aThreadIdToLogFile */,
+                                    TBool /* aCreateLogDir */,
+                                    TInt aStaticBufferSize)
+    {
+    // Create CFileOutput object fileWriter
+    CRDebugOutput* rdebugWriter = new (ELeave) CRDebugOutput( 
+                                                        aLoggerType,
+                                                        aWithTimeStamp,
+                                                        aWithLineBreak,
+                                                        aWithEventRanking );
+
+    CleanupStack::PushL( rdebugWriter );
+    rdebugWriter->ConstructL( aStaticBufferSize );
+    CleanupStack::Pop( rdebugWriter );
+
+    return rdebugWriter;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRDebugOutput
+
+    Method: ~CRDebugOutput
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CRDebugOutput::~CRDebugOutput()
+    {
+    delete iDataHBuf1;
+    delete iDataHBuf2;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRDebugOutput
+
+    Method: Write
+
+    Description: Write log information or data to the file. 16 bit.
+
+    Parameters: TBool aWithTimeStamp: in: Is time stamp flag used
+                TBool aWithLineBreak: in: Is line break flag used
+                TBool aWithEventRanking: in: Is event ranking flag used
+                const TDesC& aData: in: Logged or saved data
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CRDebugOutput::Write( TBool aWithTimeStamp,
+                            TBool aWithLineBreak,
+                            TBool aWithEventRanking,
+                            const TDesC& aData )
+    {
+    TInt currentEndPos( 0 );        // Current position in aData parsing
+                                    // to partitions
+
+    // a logInfo size must be at least the minimumSpace size
+    TInt minimumSpace = ( KMaxTimeStamp + KMaxHtmlLineBreak + KMaxLineBreak +
+                            KMaxEventRanking + KMaxSpace );
+        
+    TPtr logInfo(0, 0);
+    HBufC* dataHBuf = NULL;    
+    
+    if(iDataHBuf1 != NULL)                            
+        {
+        TInt messageLength = aData.Length() + minimumSpace;
+        if( messageLength > iStaticBufferSize )
+            {
+             RDebug::Print(_L("Warning: buffer size too small, not able to log!"));
+             return KErrOverflow;
+            }
+        // Using the HBufC created in ConstructL
+        logInfo.Set( iDataHBuf1->Des() ); // Memory allocation for data
+        
+        }
+    else
+        {
+        // Buffer size is minimum space plus aData(aData length may be 0 but
+        // time stamp is used)
+        if( ( aData.Length() + minimumSpace ) < ( KMaxLogData + minimumSpace ) )
+            {
+            dataHBuf = HBufC::New( aData.Length() + minimumSpace );
+            }
+        // Buffer size is over KMaxLogData
+        else
+            {
+            dataHBuf = HBufC::New( aData.Length() );
+            }
+        if( dataHBuf == NULL )
+            {
+            return KErrNoMemory;
+            }
+        logInfo.Set( dataHBuf->Des() ); // Memory allocation for data
+        }
+
+    logInfo.Copy( aData );          // Copy data
+    
+    TPtr data( 0, 0 );
+
+    // Add time stamp and/or event ranking if required
+    EventAndTimeCombiner( logInfo, data, aWithTimeStamp,
+                            aWithLineBreak, aWithEventRanking );
+
+    while( data.Length() > currentEndPos )
+        {
+        // In this loop round data length is/under 254
+        if( ( data.Length() - currentEndPos ) <= KMaxRDebug )
+            {
+            // Current positions to rest of data position
+            logInfo = data.Mid( currentEndPos, ( data.Length() - currentEndPos ) );
+            // Prevent rdebug from parsing text string as formating string
+            RDebug::Print( _L( "%S" ), &logInfo );
+            }
+        // In this loop round data length is over 254
+        else
+            {
+            // Current positions to KMaxRDebug that includes space for ' ->'
+            logInfo = data.Mid( currentEndPos, KMaxRDebug );
+            // Prevent rdebug from parsing text string as formating string
+            RDebug::Print( _L( "%S ->" ), &logInfo );
+            }
+        currentEndPos = currentEndPos + KMaxRDebug;
+        }
+
+    delete dataHBuf;
+
+    if(iDataHBuf2 == NULL)
+        {
+        delete iDataHBuf;
+        iDataHBuf = NULL;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRDebugOutput
+
+    Method: Write
+
+    Description: Write log information or data to the file. 8 bit.
+
+    Parameters: TBool aWithTimeStamp: in: Is time stamp flag used
+                TBool aWithLineBreak: in: Is line break flag used
+                TBool aWithEventRanking: in: Is event ranking flag used
+                const TDesC8& aData: in: Logged or saved data
+
+    Return Values: TInt
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CRDebugOutput::Write( TBool aWithTimeStamp,
+                            TBool aWithLineBreak,
+                            TBool aWithEventRanking,
+                            const TDesC8& aData )
+    {
+    TInt currentEndPos( 0 );        // Current position in aData parsing
+                                    // to partitions
+    TPtr logInfo(0, 0);
+
+    // a logInfo size must be at least the minimumSpace size
+    TInt minimumSpace = ( KMaxTimeStamp + KMaxHtmlLineBreak + KMaxLineBreak +
+                            KMaxEventRanking + KMaxSpace );
+    HBufC* dataHBuf = NULL;
+    if(iDataHBuf1 != NULL)                            
+        {
+        if( ( aData.Length() + minimumSpace ) > iStaticBufferSize )
+            {
+             RDebug::Print(_L("Warning: buffer size too small, not able to log!"));
+             return KErrOverflow;
+            }       
+        logInfo.Set( iDataHBuf1->Des() ); // Memory allocation for data
+        }
+    else
+        {
+        // 8 bit data to 16 bit because RDebug::Print don't support 8 bit printing
+        
+        // Buffer size is minimum space plus aData(aData length may be 0 but
+        // time stamp is used)
+        if( ( aData.Length() + minimumSpace ) < ( KMaxLogData + minimumSpace ) )
+            {
+            dataHBuf = HBufC::New( aData.Length() + minimumSpace );
+            }
+        // Buffer size is over KMaxLogData
+        else
+            {
+            dataHBuf = HBufC::New( aData.Length() );
+            }
+        if( dataHBuf == NULL )
+            {
+            return KErrNoMemory;
+            }
+        logInfo.Set( dataHBuf->Des() ); // Memory allocation for data
+        }
+        
+    logInfo.Copy( aData );          // Copy data
+
+    TPtr data( 0, 0 );
+
+    // Add time stamp and/or event ranking if required
+    EventAndTimeCombiner( logInfo, data, aWithTimeStamp,
+                            aWithLineBreak, aWithEventRanking );
+    while( data.Length() > currentEndPos )
+        {
+        // In this loop round data length is/under 254
+        if( ( data.Length() - currentEndPos ) <= KMaxRDebug )
+            {
+            // Current positions to rest of data position
+            logInfo = data.Mid( currentEndPos, ( data.Length() - currentEndPos ) );
+            // Prevent rdebug from parsing text string as formating string
+            RDebug::Print( _L( "%S" ), &logInfo );
+            }
+        // In this loop round data length is over 254
+        else
+            {
+            // Current positions to KMaxRDebug that includes space for ' ->'
+            logInfo = data.Mid( currentEndPos, KMaxRDebug );
+            // Prevent rdebug from parsing text string as formating string
+            RDebug::Print( _L( "%S ->" ), &logInfo );
+            }
+        currentEndPos = currentEndPos + KMaxRDebug;
+        }
+
+    delete dataHBuf;
+
+    if(iDataHBuf2 == NULL)
+       {
+       delete iDataHBuf;
+       iDataHBuf = NULL;
+       }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRDebugOutput
+
+    Method: EventAndTimeCombiner    
+
+    Description: Event ranking and time stamp combimer.
+
+    Parameters: TLogInfo aLogInfo: inout: Overflowed data
+                TPtr8& aData: inout: Combined data
+                TBool aWithTimeStamp: in: Is time stamp flag used
+                TBool aWithLineBreak: in: Is line break flag used
+                TBool aWithEventRanking: in: Is event ranking flag used
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CRDebugOutput::EventAndTimeCombiner( TPtr& aLogInfo,
+                                            TPtr& aData,
+                                            TBool aWithTimeStamp,
+                                            TBool aWithLineBreak,
+                                            TBool aWithEventRanking )
+    {
+    TInt extraLength( 0 );
+
+    // Extra space calculation
+    if( iWithEventRanking && aWithEventRanking )
+        {
+        extraLength = extraLength + KMaxEventRanking + KMaxSpace;
+        }
+    if( ( iLoggerType == CStifLogger::EHtml ) && iWithLineBreak && aWithLineBreak )
+        {
+        extraLength = extraLength + KMaxHtmlLineBreak;
+        }
+    if( iWithLineBreak && aWithLineBreak )
+        {
+        extraLength = extraLength + KMaxLineBreak;
+        }
+    if( aWithTimeStamp && iWithTimeStamp )
+        {
+        extraLength = extraLength + KMaxTimeStamp;
+        }
+
+    // Calculated space
+    TInt space = aLogInfo.Length();
+
+    if(iDataHBuf2 != NULL)                            
+        {
+        aData.Set( iDataHBuf2->Des() );  // Memory allocation for data
+        aData.Copy( _L("") ); // Initialize aData buffer
+        }
+    else
+    {        
+        iDataHBuf = HBufC::New( space + extraLength );
+        if( iDataHBuf == NULL )
+            {
+            return;
+            }
+        aData.Set( iDataHBuf->Des() );  // Memory allocation for data
+    }
+
+    // Event ranking
+    if( iWithEventRanking && aWithEventRanking && !iWithTimeStamp )
+        {
+        EventRanking( aData );          // Event ranking to data
+        aData.Append( aLogInfo );       // Unicode aData to normal text
+        }
+    // Time stamp
+    else if( iWithTimeStamp && aWithTimeStamp )
+        {
+        // With event ranking
+        if( iWithEventRanking && aWithEventRanking )
+            {
+            EventRanking( aData );      // Event ranking to data
+            }
+        AddTimeStampToData( aData );    // Add time stamp
+        aData.Append( aLogInfo );       // Unicode aData to normal text
+        }
+    else
+        {
+        aData.Copy( aLogInfo );         // Unicode aData to normal text
+        }
+
+    // NOTE: If need some special line break do it with logging phase
+
+    // If html logging and line break is used add the line break.
+    if ( ( iLoggerType == CStifLogger::EHtml ) && iWithLineBreak && aWithLineBreak )
+        {
+        aData.Append( _L( "<BR>" ) );
+        aData.Append( _L( "\n" ) );  // To make html file more readable
+                                    // with text editor
+        }
+
+    // Other cases line break is normal '\n' if logging is used
+    else if( iWithLineBreak && aWithLineBreak )
+        {
+        aData.Append( 0x0D ); // 13 or '\' in Symbian OS
+        aData.Append( 0x0A ); // 10 or 'n' in Symbian OS
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: EventRanking
+
+    Description: For event ranking logging.
+
+    Parameters: TPtr8& aData: inout: Data with event ranking
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CRDebugOutput::EventRanking( TPtr& aData )
+    {
+    // Returns the machine's current tick count.
+    TUint tick = User::TickCount();
+    tick &= 0xffff;
+    aData.AppendNum( tick );
+    aData.Append( _L( " " ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: DateAndTime
+
+    Description: For date and time logging.
+
+    Parameters: TPtr8& aData: inout: Data with time stamps
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CRDebugOutput::AddTimeStampToData( TPtr& aData )
+    {
+    TStifLoggerTimeStamp8 timeStamp;
+    GetDateAndTime( timeStamp );
+    aData.Append( timeStamp );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileOutput
+
+    Method: GetDateAndTime
+
+    Description: For date and time logging.
+
+    Parameters: TStifLoggerTimeStamp& aDataAndTime: inout: Generated date and time
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CRDebugOutput::GetDateAndTime( TStifLoggerTimeStamp8& aDataAndTime )
+    {
+    TInt num( 0 );
+    TInt microseconds( 0 );
+
+    // Append date
+    TTime time;
+    time.HomeTime();
+    TDateTime dateTime( time.DateTime() );
+
+    num = dateTime.Day() + 1;
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    // Append month
+    aDataAndTime.AppendNum( num );  
+    num = dateTime.Month() + 1;     // returns enum
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    aDataAndTime.AppendNum( num );
+    aDataAndTime.AppendNum( dateTime.Year() );
+
+    // Append time
+    aDataAndTime.Append( ' ' );
+    num = dateTime.Hour();
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    aDataAndTime.AppendNum( num );
+    num = dateTime.Minute();
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    aDataAndTime.AppendNum( num );
+
+    num = dateTime.Second();
+    microseconds = dateTime.MicroSecond();  // Microseconds
+
+    // Seconds
+    if( num < 10 )
+        {
+        aDataAndTime.Append( '0' );
+        }
+    aDataAndTime.AppendNum( num );
+
+   // Milliseconds
+    aDataAndTime.Append( '.' );
+    aDataAndTime.AppendNumFixedWidth( microseconds, EDecimal, 3 );
+
+    // NOTE: If you add more spaces etc. remember increment KMaxTimeStamp size!
+
+    if ( iLoggerType == CStifLogger::EHtml )
+        {
+        aDataAndTime.Append( _L("....") );
+        }
+    else
+        {
+        aDataAndTime.Append( _L("    ") );
+        }
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/StifLogger.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1111 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CStifLogger 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "StifLogger.h"
+#include "TxtLogger.h"
+#include "HtmlLogger.h"
+#include "DataLogger.h"
+#include "LoggerTracing.h"
+#include "LoggerOverFlow.h"
+#include "SettingServerClient.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: CStifLogger
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifLogger::CStifLogger()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: const TDesC& aTestPath: in: Path to logged information
+                const TDesC& aTestFile: in: Log name for information
+                TLoggerType aLoggerType: in: Log file type(txt, html,
+                                             data)
+                TOutput aOutput: in: Output source(File)
+                TBool aOverWrite: in: Indicator to file overwrite
+                TBool aWithTimeStamp: in: Indicator to time stamp
+                TBool aWithLineBreak: in: Indicator to line break
+                TBool aWithEventRanking: in: Indicator to event ranking
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+                TBool aCreateLogDir: in: Indicator to directory creation
+                TInt  aStaticBufferSize
+                TBool aUnicode: in: Indicator if file has to be in unicode format
+
+    Return Values: CStifLogger* logger: pointer to CStifLogger object
+
+    Errors/Exceptions: Leaves if aTestPath or aTestFile length is over KMaxName
+                       Leaves if called serv.Connect() method fails
+                       Leaves if called CHtmlLogger::NewL method fails
+                       Leaves if called CDataLogger::NewL method fails
+                       Leaves if called CTxtLogger::NewL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifLogger* CStifLogger::NewL( const TDesC& aTestPath,
+                                            const TDesC& aTestFile,
+                                            TLoggerType aLoggerType,
+                                            TOutput aOutput,
+                                            TBool aOverWrite,
+                                            TBool aWithTimeStamp,
+                                            TBool aWithLineBreak,
+                                            TBool aWithEventRanking,
+                                            TBool aThreadIdToLogFile,
+                                            TBool aCreateLogDir,
+                                            TInt  aStaticBufferSize,
+                                            TBool aUnicode )
+    {
+    if( KMaxName < aTestPath.Length() || KMaxName < aTestFile.Length() )
+        {
+        User::Leave( KErrArgument );
+        }
+
+    // Handle to Setting server.
+    RSettingServer settingServer;
+    // Connect to the Setting server and create session
+    TInt ret = settingServer.Connect();
+    if ( ret != KErrNone )
+        {
+        User::Leave( ret );
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings( loggerSettings );
+    if ( ret != KErrNone )
+        {
+        User::Leave( ret );
+        } 
+
+    TName testPath = aTestPath;
+    TName testFile = aTestFile;
+
+    // Take in use the overwrite parameters
+    OverwriteLoggerSettings( loggerSettings, testPath, testFile, aLoggerType,
+                                aOutput, aOverWrite, aWithTimeStamp,
+                                aWithLineBreak, aWithEventRanking,
+                                aThreadIdToLogFile, aCreateLogDir,
+                                aUnicode );
+
+    // Close Setting server session
+    settingServer.Close();
+
+    // Html file logging
+    if ( aLoggerType == EHtml )
+        {
+        // Create CHtmlLogger object logger
+        CHtmlLogger* logger = CHtmlLogger::NewL( testPath,
+                                                    testFile,
+                                                    aLoggerType,
+                                                    aOutput,
+                                                    aOverWrite,
+                                                    aWithTimeStamp,
+                                                    aWithLineBreak,
+                                                    aWithEventRanking,
+                                                    aThreadIdToLogFile,
+                                                    aCreateLogDir,
+                                                    aStaticBufferSize,
+                                                    aUnicode );
+        return (CStifLogger*)logger;
+        }
+    // Data file
+    else if ( aLoggerType == EData )
+        {
+        // Create CDataLogger object logger
+        CDataLogger* logger = CDataLogger::NewL( testPath,
+                                                    testFile,
+                                                    aLoggerType,
+                                                    aOutput,
+                                                    aOverWrite,
+                                                    aWithTimeStamp,
+                                                    aWithLineBreak,
+                                                    aWithEventRanking,
+                                                    aThreadIdToLogFile,
+                                                    aCreateLogDir,
+                                                    aStaticBufferSize,
+                                                    aUnicode );
+        return (CStifLogger*)logger;
+        }
+    // For default: text file logging
+    else
+        {
+        // Create CTxtLogger object logger
+        CTxtLogger* logger = CTxtLogger::NewL( testPath,
+                                                testFile,
+                                                aLoggerType,
+                                                aOutput,
+                                                aOverWrite,
+                                                aWithTimeStamp,
+                                                aWithLineBreak,
+                                                aWithEventRanking,
+                                                aThreadIdToLogFile,
+                                                aCreateLogDir,
+                                                aStaticBufferSize,
+                                                aUnicode );
+        return (CStifLogger*)logger;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    TestEngine's and TestServer's are friend. For TestEngine's and
+    TestServer's StifLogger creation.
+
+    Parameters: const TDesC& aTestPath: in: Path to logged information
+                const TDesC& aTestFile: in: Log name for information
+                TLoggerSettings& aLoggerSettings: in: Struct for StifLogger
+                                                      settigs
+
+    Return Values: CStifLogger* logger: pointer to CStifLogger object
+
+    Errors/Exceptions:  Leaves if called CHtmlLogger::NewL method fails
+                        Leaves if called CDataLogger::NewL method fails
+                        Leaves if called CTxtLogger::NewL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifLogger* CStifLogger::NewL( const TDesC& aTestPath,
+                                            const TDesC& aTestFile,
+                                            TLoggerSettings& aLoggerSettings )
+    {
+    TInt cpu( 0 );
+    HAL::Get( HALData::ECPU, cpu );
+
+    // HW environment
+    if ( cpu == HALData::ECPU_ARM )
+        {
+        // Html file logging
+        if ( aLoggerSettings.iHardwareFormat == EHtml )
+            {
+            // Create CHtmlLogger object logger
+            CHtmlLogger* logger = CHtmlLogger::NewL( aTestPath,
+                                    aTestFile,
+                                    aLoggerSettings.iHardwareFormat,
+                                    aLoggerSettings.iHardwareOutput,
+                                    aLoggerSettings.iOverwrite,
+                                    aLoggerSettings.iTimeStamp,
+                                    aLoggerSettings.iLineBreak,
+                                    aLoggerSettings.iEventRanking,
+                                    aLoggerSettings.iThreadId,
+                                    aLoggerSettings.iCreateLogDirectories,
+                                    0,
+                                    aLoggerSettings.iUnicode );
+            return (CStifLogger*)logger;
+            }
+        // Data file
+        else if ( aLoggerSettings.iHardwareFormat == EData )
+            {
+            // Create CDataLogger object logger
+            CDataLogger* logger = CDataLogger::NewL( aTestPath,
+                                    aTestFile,
+                                    aLoggerSettings.iHardwareFormat,
+                                    aLoggerSettings.iHardwareOutput,
+                                    aLoggerSettings.iOverwrite,
+                                    aLoggerSettings.iTimeStamp,
+                                    aLoggerSettings.iLineBreak,
+                                    aLoggerSettings.iEventRanking,
+                                    aLoggerSettings.iThreadId,
+                                    aLoggerSettings.iCreateLogDirectories,
+                                    0,
+                                    aLoggerSettings.iUnicode );
+            return (CStifLogger*)logger;
+            }
+        // For default: text file logging
+        else
+            {
+            // Create CTxtLogger object logger
+            CTxtLogger* logger = CTxtLogger::NewL( aTestPath,
+                                    aTestFile,
+                                    aLoggerSettings.iHardwareFormat,
+                                    aLoggerSettings.iHardwareOutput,
+                                    aLoggerSettings.iOverwrite,
+                                    aLoggerSettings.iTimeStamp,
+                                    aLoggerSettings.iLineBreak,
+                                    aLoggerSettings.iEventRanking,
+                                    aLoggerSettings.iThreadId,
+                                    aLoggerSettings.iCreateLogDirectories,
+                                    0,
+                                    aLoggerSettings.iUnicode );
+            return (CStifLogger*)logger;
+            }
+        } // End of HW environment branch
+
+    // Wins environment ( cpu == HALData::ECPU_X86 )
+    else
+        {
+        // Html file logging
+        if ( aLoggerSettings.iEmulatorFormat == EHtml )
+            {
+            // Create CHtmlLogger object logger
+            CHtmlLogger* logger = CHtmlLogger::NewL( aTestPath,
+                                    aTestFile,
+                                    aLoggerSettings.iEmulatorFormat,
+                                    aLoggerSettings.iEmulatorOutput,
+                                    aLoggerSettings.iOverwrite,
+                                    aLoggerSettings.iTimeStamp,
+                                    aLoggerSettings.iLineBreak,
+                                    aLoggerSettings.iEventRanking,
+                                    aLoggerSettings.iThreadId,
+                                    aLoggerSettings.iCreateLogDirectories,
+                                    0,
+                                    aLoggerSettings.iUnicode );
+            return (CStifLogger*)logger;
+            }
+        // Data file
+        else if ( aLoggerSettings.iEmulatorFormat == EData )
+            {
+            // Create CDataLogger object logger
+            CDataLogger* logger = CDataLogger::NewL( aTestPath,
+                                    aTestFile,
+                                    aLoggerSettings.iEmulatorFormat,
+                                    aLoggerSettings.iEmulatorOutput,
+                                    aLoggerSettings.iOverwrite,
+                                    aLoggerSettings.iTimeStamp,
+                                    aLoggerSettings.iLineBreak,
+                                    aLoggerSettings.iEventRanking,
+                                    aLoggerSettings.iThreadId,
+                                    aLoggerSettings.iCreateLogDirectories,
+                                    0,
+                                    aLoggerSettings.iUnicode );
+            return (CStifLogger*)logger;
+            }
+        // For default: text file logging
+        else
+            {
+            // Create CTxtLogger object logger
+            CTxtLogger* logger = CTxtLogger::NewL( aTestPath,
+                                    aTestFile,
+                                    aLoggerSettings.iEmulatorFormat,
+                                    aLoggerSettings.iEmulatorOutput,
+                                    aLoggerSettings.iOverwrite,
+                                    aLoggerSettings.iTimeStamp,
+                                    aLoggerSettings.iLineBreak,
+                                    aLoggerSettings.iEventRanking,
+                                    aLoggerSettings.iThreadId,
+                                    aLoggerSettings.iCreateLogDirectories,
+                                    0,
+                                    aLoggerSettings.iUnicode );
+            return (CStifLogger*)logger;
+            }
+        } // End of WINS environment branch
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: ~CStifLogger
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifLogger::~CStifLogger()
+    {
+
+    delete iOutput;
+    iOutput = 0;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: OverwriteLoggerSettings
+
+    Description: Local CStifLogger's method for StifLogger settings
+                 overwriting.
+
+    Overwrite parameters may set in TestFramework.ini file.
+
+    Parameters: TLoggerSettings& aLoggerSettings: inout; Overwrite parameters
+                TName& aTestPath: inout: Path to logged information
+                TName& aTestFile: inout: Log file name for information
+                TLoggerType& aLoggerType: inout: Log file type(txt, html, data)
+                TOutput& aOutput: inout: Output source(File)
+                TBool& aOverWrite: inout: Indicator to file overwrite
+                TBool& aWithTimeStamp: inout: Indicator to time stamp
+                TBool& aWithLineBreak: inout: Indicator to line break
+                TBool& aWithEventRanking: inout: Indicator to event ranking
+                TBool& aThreadIdToLogFile: inout: Indicator to thread id adding to
+                                                  end of the log file
+                TBool& aCreateLogDir: inout: Indicator to directory creation
+                TBool& aUnicode: inout: Indicator if log will be written to file in unicode format
+    
+    Return Values: None
+
+    Errors/Exceptions: None 
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifLogger::OverwriteLoggerSettings( TLoggerSettings& aLoggerSettings,
+                                            TName& aTestPath,
+                                            TName& aTestFile,
+                                            TLoggerType& aLoggerType,
+                                            TOutput& aOutput,
+                                            TBool& aOverWrite,
+                                            TBool& aWithTimeStamp,
+                                            TBool& aWithLineBreak,
+                                            TBool& aWithEventRanking,
+                                            TBool& aThreadIdToLogFile,
+                                            TBool& aCreateLogDir,
+                                            TBool& aUnicode )
+    {
+    // Which environment is in use
+    TInt cpu( 0 );
+
+    // Indicator is file type remove acceptable operation
+    TBool removeFileType( EFalse );
+
+    // Get environment
+    HAL::Get( HALData::ECPU, cpu );
+
+    // HW environment
+    if ( cpu == HALData::ECPU_ARM )
+        {
+        TInt pathLen = aTestPath.Length() + 
+                        aLoggerSettings.iHardwarePath.Length();
+
+        // Check that path overwrite setting is defined and length is legal
+        if( aLoggerSettings.iIsDefined.iHwPath && pathLen < KMaxName )
+            {
+            TName newPath;
+            newPath = aLoggerSettings.iHardwarePath;
+            // Check is '\' the last character
+            TInt ret( 0 );
+            ret = newPath.LocateReverse( 92 );
+            // Is '\' character founded
+            if( ret != KErrNotFound )
+                {
+                // Is '\' last character
+                if( ret == ( newPath.Length() - 1 ) )
+                    {
+                    // delete last '\'
+                    newPath.Delete( 
+                        ( aLoggerSettings.iHardwarePath.Length() -1 ), 1 );
+                    }
+                }
+            // Removes drive letter if given and appends implemented path 
+            TParse parse;
+            parse.Set( aTestPath, NULL, NULL );
+            // Path() return value starts with '\'
+            newPath.Append( parse.Path() );
+            aTestPath = newPath;
+            }
+        if( aLoggerSettings.iIsDefined.iHwFormat )
+            {
+            aLoggerType = aLoggerSettings.iHardwareFormat;
+            // Remove file type if it is set
+            removeFileType = ETrue;
+            }
+        if( aLoggerSettings.iIsDefined.iHwOutput )
+            {
+            aOutput = aLoggerSettings.iHardwareOutput;
+            }
+        }
+
+    // Wins environment ( cpu == HALData::ECPU_X86 )
+    else
+        {
+        TInt pathLen = aTestPath.Length() + 
+                        aLoggerSettings.iEmulatorPath.Length();
+
+        // Check that path overwrite setting is defined and length is legal
+        if( aLoggerSettings.iIsDefined.iPath  && pathLen < KMaxName )
+            {
+            TName newPath;
+            newPath = aLoggerSettings.iEmulatorPath;
+            // Check is '\' the last character
+            TInt ret( 0 );
+            ret = newPath.LocateReverse( 92 );
+            // Is '\' character founded
+            if( ret != KErrNotFound )
+                {
+                // Is '\' last character
+                if( ret == ( newPath.Length() - 1 ) )
+                    {
+                    // delete last '\'
+                    newPath.Delete( 
+                        ( aLoggerSettings.iEmulatorPath.Length() -1 ), 1 );
+                    }
+                }
+            // Removes drive letter if given and appends implemented path
+            TParse parse;
+            parse.Set( aTestPath, NULL, NULL );
+            // Path() return value starts with '\'
+            newPath.Append( parse.Path() );
+            aTestPath = newPath;
+            }
+        if( aLoggerSettings.iIsDefined.iFormat )
+            {
+            aLoggerType = aLoggerSettings.iEmulatorFormat;
+            // Remove file type if it is set
+            removeFileType = ETrue;
+            }
+        if( aLoggerSettings.iIsDefined.iOutput )
+            {
+            aOutput = aLoggerSettings.iEmulatorOutput;
+            }
+        }
+
+    // Rest of the overwrite values
+    if( aLoggerSettings.iIsDefined.iOverwrite )
+        {
+        aOverWrite = aLoggerSettings.iOverwrite;
+        }
+    if( aLoggerSettings.iIsDefined.iTimeStamp )
+        {
+        aWithTimeStamp = aLoggerSettings.iTimeStamp;
+        }
+    if( aLoggerSettings.iIsDefined.iLineBreak )
+        {
+        aWithLineBreak = aLoggerSettings.iLineBreak;
+        }
+    if( aLoggerSettings.iIsDefined.iEventRanking )
+        {
+        aWithEventRanking = aLoggerSettings.iEventRanking;
+        }
+    if( aLoggerSettings.iIsDefined.iThreadId )
+        {
+        aThreadIdToLogFile = aLoggerSettings.iThreadId;
+        }
+    if( aLoggerSettings.iIsDefined.iCreateLogDir )
+        {
+        aCreateLogDir = aLoggerSettings.iCreateLogDirectories;
+        }
+    if( aLoggerSettings.iIsDefined.iUnicode )
+        {
+        aUnicode = aLoggerSettings.iUnicode;
+        }
+
+    // Remove file type if allowed and if file type is set to filename
+    if( removeFileType )
+        {
+        // Remove file type '.XXX' from file name if exist
+        if( aTestFile.Find( _L( "." ) ) )
+            {
+            TParse parse;
+            parse.Set( aTestFile, NULL, NULL );
+            // Type length
+            TInt length( 0 );
+            // '.XXX'
+            length = parse.Ext().Length();
+            // Delete type
+            aTestFile.Delete ( aTestFile.Length()-length, length );
+            }
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: Log
+
+    Description: Log a 16 bit information.
+
+    This log method accepts only one parameters
+
+    Parameters: const TDesC aLogInfo: in: 8 bit data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::Log( const TDesC& aLogInfo )
+    {
+    // No text style info
+    return Send( ENoStyle, aLogInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: Log
+
+    Description: Log a 8 bit information.
+
+    This log method accepts only one parameters
+
+    Parameters: const TDesC8 aLogInfo: in: 8 bit data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::Log( const TDesC8& aLogInfo )
+    {
+    // No text style info
+    return Send( ENoStyle, aLogInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: Log
+
+    Description: Log a 16 bit information.
+
+    There is also parameter to styling text information e.g. text color.
+
+    Parameters: TInt aStyle: in: Logged text forming parameter
+                const TDesC aLogInfo: in: 16 bit data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::Log( TInt aStyle, const TDesC& aLogInfo )
+    {
+    return Send( aStyle, aLogInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: Log
+
+    Description: Log a 8 bit information.
+
+    There is also parameter to styling text information e.g. text color.
+
+    Parameters: TInt aStyle: in: Logged text forming parameter
+                const TDesC8 aLogInfo: in: 8 bit data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::Log( TInt aStyle, const TDesC8& aLogInfo )
+    {
+    return Send( aStyle, aLogInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: Log
+
+    Description: Log a 16 bit information.
+
+    This log method accepts several parameters.
+
+    Parameters: TRefByValue<const TDesC> aLogInfo: in: A templated class which 
+                encapsulates a reference to an object within a wrapper
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  TDesLoggerOverflowHandler called if logged information
+                        is over KMaxLogData
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::Log( TRefByValue<const TDesC> aLogInfo,... )
+    {
+    VA_LIST list;
+    VA_START( list, aLogInfo );
+    TLogInfo logInfo;
+
+    // Create overflow handler. If the log information size is over the
+    // KMaxLogData rest of the information will cut.
+    TDesLoggerOverflowHandler overFlowHandler( this, 1 );
+
+    // Parse parameters
+    logInfo.AppendFormatList( aLogInfo, list, &overFlowHandler );
+
+    // No text style info
+    return Send( ENoStyle, logInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: Log
+
+    Description: Log a 8 bit information.
+
+    This log method accepts several parameters.
+
+    Parameters: TRefByValue<const TDesC8> aLogInfo: in: A templated class which 
+                encapsulates a reference to an object within a wrapper
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  TDes8LoggerOverflowHandler called if logged information is 
+                        over KMaxLogData
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::Log( TRefByValue<const TDesC8> aLogInfo,... )
+    {
+    VA_LIST list;
+    VA_START( list, aLogInfo );
+    TLogInfo8 logInfo;
+
+    // Create overflow handler. If the log information size is over the
+    // KMaxLogData rest of the information will cut.
+    TDes8LoggerOverflowHandler overFlowHandler( this, 1 );
+
+    // Parse parameters
+    logInfo.AppendFormatList( aLogInfo, list, &overFlowHandler );
+
+    // No text style info
+    return Send( ENoStyle, logInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: Log
+
+    Description: Log a 16 bit information.
+
+    This log method accepts several parameters. There is also parameter to
+    styling text information e.g. text color.
+
+    Parameters: TInt aStyle: in: Logged text forming parameter
+                TRefByValue<const TDesC> aLogInfo: in: A templated class 
+                which encapsulates a reference to an object
+                within a wrapper
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  TDesOverflowHandler called if logged information is
+                        over KMaxLogData
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::Log( TInt aStyle, 
+                           TRefByValue<const TDesC> aLogInfo,... )
+    {
+    VA_LIST list;
+    VA_START( list, aLogInfo );
+    TLogInfo logInfo;
+
+    // Create overflow handler. If the log information size is over the
+    // KMaxLogData rest of the information will cut.
+    TDesLoggerOverflowHandler overFlowHandler( this, 2 );
+
+    // Parse parameters
+    logInfo.AppendFormatList( aLogInfo, list, &overFlowHandler );
+
+    return Send( aStyle, logInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: Log
+
+    Description: Log a 8 bit information.
+
+    This log method accepts several parameters. There is also parameter to
+    styling text information e.g. text color.
+
+    Parameters: TInt aStyle: in: Logged text forming parameter
+                TRefByValue<const TDesC8> aLogInfo: in: A templated class 
+                which encapsulates a reference to an object
+                within a wrapper
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  TDes8LoggerOverflowHandler called if logged information is
+                        over KMaxLogData
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::Log( TInt aStyle, 
+                           TRefByValue<const TDesC8> aLogInfo,... )
+    {
+    VA_LIST list;
+    VA_START( list, aLogInfo );
+    TLogInfo8 logInfo;
+
+    // Create overflow handler. If the log information size is over the
+    // KMaxLogData rest of the information will cut.
+    TDes8LoggerOverflowHandler overFlowHandler( this, 2 );
+
+    // Parse parameters
+    logInfo.AppendFormatList( aLogInfo, list, &overFlowHandler );
+
+    return Send( aStyle, logInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: WriteDelimiter
+
+    Description: Log a 16 bit delimiter.
+
+    Log a delimiters required locations to the log information.
+    This will be used if parameters are not given when calling this method.
+
+    Parameters: const TDesC& aDelimiter: in: Logged delimiter(e.g. '#' or 'XO')
+                TInt aCount: in: Repeated count for delimiter
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  TDesLoggerOverflowHandler called if logged information
+                        is over KMaxLogData.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::WriteDelimiter( const TDesC& aDelimiter, TInt aCount )
+    {
+    TLogInfo delimiter;
+
+    // Create overflow handler. If the delimiter size expands over the
+    // KMaxLogData the TDesLoggerOverflowHandler will call.
+    TDesLoggerOverflowHandler overFlowHandler( this, 3 );
+
+    // Create a delimiter
+    for( TInt a = 0; a < aCount; a++ )
+        {
+        // If delimiter creation keeps under the KMaxLogData.
+        // If not we use TDesLoggerOverflowHandler.
+        if( ( a * aDelimiter.Length() ) < KMaxLogData ) 
+            {
+            delimiter.Append( aDelimiter );
+            }
+        // KMaxLogData is exceeded
+        else
+            {
+            // If the title size is over the KMaxLogData default delimiter will
+            // use. Use normal overflowhandler to print overflow information.
+            TBuf<4> empty; // Not really used.
+            overFlowHandler.Overflow( empty );
+            delimiter.Copy( 
+                _L( "##################################################" ) );
+            break;
+            }
+        }
+
+    // No text style info
+    return Send( ENoStyle, delimiter );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: WriteDelimiter
+
+    Description: Log a 8 bit delimiter.
+
+    Log a delimiters required locations to the log information.
+
+    Parameters: const TDesC8& aDelimiter: in: Logged delimiter
+                                              (e.g. '#' or 'XO')
+                TInt aCount: in: Repeated count for delimiter
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  TDes8LoggerOverflowHandler called if logged information is
+                        over KMaxLogData.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::WriteDelimiter( const TDesC8& aDelimiter, TInt aCount )
+    {
+    TLogInfo8 delimiter;
+
+    // Create overflow handler. If the delimiter size expands over the
+    // KMaxLogData the TDesLoggerOverflowHandler will call.
+    TDes8LoggerOverflowHandler overFlowHandler( this, 3 );
+
+    // Create a delimiter
+    for( TInt a = 0; a < aCount; a++ )
+        {
+        // If delimiter creation keeps under the KMaxLogData.
+        // If not we use TDesLoggerOverflowHandler.
+        if( ( a * aDelimiter.Length() ) < KMaxLogData ) 
+            {
+            delimiter.Append( aDelimiter );
+            }
+        // KMaxLogData is exceeded
+        else
+            {
+            // If the title size is over the KMaxLogData default delimiter will
+            // use. Use normal overflowhandler to print overflow information.
+            TBuf8<4> empty; // Not really used.
+            overFlowHandler.Overflow( empty );
+            delimiter.Copy( 
+                _L8( "##################################################" ) );
+            break;
+            }
+        }
+
+    // No text style info
+    return Send( ENoStyle, delimiter );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: SaveData
+
+    Description: Save file or data( 16 bit ).
+
+    Used when is need to save file or data to storage e.g. web page.
+
+    Parameters: TDesC& aData: in: Data to be saved
+    
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::SaveData( TDesC& aData )
+    {
+    // No text style info
+    return Send( ENoStyle, aData );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: SaveData
+
+    Description: Save file or data( 8 bit ).
+
+    Used when is need to save file or data to storage e.g. web page.
+
+    Parameters: TDesC8& aData: in: Data to be saved
+    
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions:  None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::SaveData( TDesC8& aData )
+    {
+    // No text style info
+    return Send( ENoStyle, aData );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: CreationResult
+
+    Description: Return StifLogger creation result.
+
+    Parameters: None
+    
+    Return Values: StifLogger creation result
+
+    Errors/Exceptions:  None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifLogger::CreationResult()
+    {
+     
+    TOutput outputType;
+    return iOutput->OutputCreationResult( outputType );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifLogger
+
+    Method: OutputType
+
+    Description: Get output type. Valid only if CreationResult returns KErrNone.
+
+    Parameters: TOutput& aOutput
+    
+    Return Values: StifLogger creation result
+
+    Errors/Exceptions:  None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifLogger::TOutput CStifLogger::OutputType()
+    {
+    
+    TOutput outputType;
+    iOutput->OutputCreationResult( outputType );
+    return outputType;
+    
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Logger/src/TxtLogger.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,336 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CTxtLogger 
+* class member functions
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "TxtLogger.h"
+#include "Output.h"
+#include "LoggerTracing.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTxtLogger
+
+    Method: CTxtLogger
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: COutput* output: in: Output source
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTxtLogger::CTxtLogger( COutput* output )
+    {
+    
+    iOutput = output;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTxtLogger
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTxtLogger::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTxtLogger
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: const TDesC& aTestPath: in: Log path
+                const TDesC& aTestFile: in: Log filename
+                TLoggerType aLoggerType: in: File type
+                TOutput aOutput: in: Output source
+                TBool aOverWrite: in: For file overwrite
+                TBool aWithTimeStamp: in: For timestamp
+                TBool aWithLineBreak: in: For line break
+                TBool aWithEventRanking: in: For events ranking to file
+                TBool aThreadIdToLogFile: in: Indicator to thread id adding to
+                                              end of the log file
+                TBool aCreateLogDir: in: Indicator to directory creation
+                TInt  aStaticBufferSize
+                TBool aUnicode: in: Indicator if file has to be in unicode format
+
+    Return Values: CTxtLogger*: pointer to CTxtLogger object
+
+    Errors/Exceptions: Leaves if called COutput::NewL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTxtLogger* CTxtLogger::NewL( const TDesC& aTestPath, 
+                                const TDesC& aTestFile,
+                                TLoggerType aLoggerType,
+                                TOutput aOutput,
+                                TBool aOverWrite,
+                                TBool aWithTimeStamp,
+                                TBool aWithLineBreak,
+                                TBool aWithEventRanking,
+                                TBool aThreadIdToLogFile,
+                                TBool aCreateLogDir,
+                                TInt aStaticBufferSize,
+                                TBool aUnicode )
+    {
+    __TRACE( KInfo, ( _L( "STIFLOGGER: Creating txt logger" ) ) );
+
+    // Create COutput object output
+    COutput* output = COutput::NewL( aTestPath,
+                                        aTestFile,
+                                        aLoggerType,
+                                        aOutput,
+                                        aOverWrite,
+                                        aWithTimeStamp,
+                                        aWithLineBreak,
+                                        aWithEventRanking,
+                                        aThreadIdToLogFile,
+                                        aCreateLogDir,
+                                        aStaticBufferSize,
+                                        aUnicode );
+
+    CleanupStack::PushL( output );
+    __ASSERT_ALWAYS( output != NULL, User::Leave( KErrNotFound ) );
+    // Create CTxtLogger object txtLogger and bind to COutput
+    CTxtLogger* txtLogger = new (ELeave) CTxtLogger( output );
+    // TXT logger owns output object and it will be destroyed in STIFLogger
+    // destructor.
+    CleanupStack::Pop( output );
+    
+    CleanupStack::PushL( txtLogger );
+    txtLogger->ConstructL();
+    CleanupStack::Pop( txtLogger );
+    
+    
+    return txtLogger;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTxtLogger
+
+    Method: ~CTxtLogger
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTxtLogger::~CTxtLogger()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTxtLogger
+
+    Method: Send
+
+    Description: Send style information and 16 bit data to the output module.
+
+    Parameters: TInt TStyle: in: Text forming
+                const TDesC& aData: in: Data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTxtLogger::Send( TInt aStyle, const TDesC& aData )
+    {
+    // Time stamp indicator
+    TBool timestamp( ETrue );
+    // Event ranking indicator
+    TBool eventranking( ETrue );
+
+    // Only EError, EWarning and EImportant styles are supporter in txt logging
+    if ( 0x00100 <= aStyle )    // EError, 0x00100 => 256
+        {
+        iOutput->Write( timestamp, EFalse, eventranking, _L( "ERROR    " ) );
+        aStyle -= 0x00100;
+        timestamp = EFalse;     // Time stamp added no time stamp to the
+                                // forward operations
+        eventranking = EFalse;  // Event ranking added no event ranking to the
+                                // forward operations
+        }
+    if ( 0x00080 <= aStyle )    // EWarning, 0x00080 => 128
+        {
+        iOutput->Write( timestamp, EFalse, eventranking,
+                                                    _L( "WARNING    " ) );
+        aStyle -= 0x00080;
+        timestamp = EFalse;     // Time stamp added no time stamp to the 
+                                // forward operations
+        eventranking = EFalse;  // Event ranking added no event ranking to the
+                                // forward operations
+        }
+    if ( 0x00040 <= aStyle )    // EImportant, 0x00040 => 64
+        {
+        iOutput->Write( timestamp, EFalse, eventranking,
+                                                    _L( "IMPORTANT    " ) );
+        aStyle -= 0x00040;
+        timestamp = EFalse;     // Time stamp added no time stamp to the 
+                                // forward operations
+        eventranking = EFalse;  // Event ranking added no event ranking to the
+                                // forward operations
+        }
+
+    return iOutput->Write( timestamp, ETrue, eventranking, aData );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTxtLogger
+
+    Method: Send
+
+    Description: Send style information and 8 bit data to the output module.
+
+    Parameters: TInt TStyle: in: Text forming
+                const TDesC8& aData: in: Data to be logged
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTxtLogger::Send( TInt aStyle, const TDesC8& aData )
+    {
+    // Time stamp indicator
+    TBool timestamp( ETrue );
+    // Event ranking indicator
+    TBool eventranking( ETrue );
+
+    // Only EError, EWarning and EImportant styles are supporter in txt logging
+    if ( 0x00100 <= aStyle )    // EError, 0x00100 => 256
+        {
+        iOutput->Write( timestamp, EFalse, eventranking, _L8( "ERROR    " ) );
+        aStyle -= 0x00100;
+        timestamp = EFalse;     // Time stamp added no time stamp to the
+                                // forward operations
+        eventranking = EFalse;  // Event ranking added no event ranking to the
+                                // forward operations
+        }
+    if ( 0x00080 <= aStyle )    // EWarning, 0x00080 => 128
+        {
+        iOutput->Write( timestamp, EFalse, eventranking,
+                                                    _L8( "WARNING    " ) );
+        aStyle -= 0x00080;
+        timestamp = EFalse;     // Time stamp added no time stamp to the 
+                                // forward operations
+        eventranking = EFalse;  // Event ranking added no event ranking to the
+                                // forward operations
+        }
+    if ( 0x00040 <= aStyle )    // EImportant, 0x00040 => 64
+        {
+        iOutput->Write( timestamp, EFalse, eventranking,
+                                                    _L8( "IMPORTANT    " ) );
+        aStyle -= 0x00040;
+        timestamp = EFalse;     // Time stamp added no time stamp to the 
+                                // forward operations
+        eventranking = EFalse;  // Event ranking added no event ranking to the
+                                // forward operations
+        }
+
+    return iOutput->Write( timestamp, ETrue, eventranking, aData );
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Parser/inc/ParserTracing.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the tracing operations for the 
+* CStifParser, CStifSectionParser and CStifItemParser
+*
+*/
+
+#ifndef STIFPARSERTRACING_H
+#define STIFPARSERTRACING_H
+
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+const TUint KError           = 0x1;
+const TUint KInfo            = 0x2;
+const TUint KAlways          = 0xFFFFFFFF;
+const TUint KDebugLevel      = ( KError );
+
+// MACROS
+#ifdef _DEBUG
+#define __TRACING_ENABLED
+#endif
+
+#ifdef __TRACING_ENABLED
+// Disable conditional expression is constant -warning
+#pragma warning( disable : 4127 )
+#define __TRACE(level,p) if ( (level) & KDebugLevel) { RDebug::Print p ;}
+#else
+#define __TRACE(level,p);
+#endif
+
+#endif // STIFPARSERTRACING_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Parser/inc/StifFileParser.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,238 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CStifFileParser.
+*
+*/
+
+#ifndef STIF_FILE_PARSER_H
+#define STIF_FILE_PARSER_H
+
+//  INCLUDES
+#include <f32file.h>
+#include <e32std.h>
+#include <e32base.h>
+#include "cstackdeprecated.h"
+#include <StifTestModule.h>
+#include "StifParser.h"
+
+// CONSTANTS
+_LIT(KIncludeKeyword, "INCLUDE");
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CStifFileParser is a STIF Test Framework StifParser class.
+// Class contains a configuration file parsing operations without loading it into memory.
+
+
+NONSHARABLE_CLASS (CStifFileParser) : public CBase
+{
+    public:     // Enumerations
+		// Indication what kind of char sequence is to be found
+        enum TWhatToFind
+      	{
+        	EStart,             // '//' or '/*' or '"' signs
+        	EQuota,             // '"' sign
+        	EEndOfComment       // '*/' sequence
+    	};
+
+		// Indication if beginning or end of section is to be found
+        enum TSectionFind
+        {
+        	ESectionStart,
+        	ESectionEnd
+        };
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * Creating parser with given handle to file. For default all
+        * information will be parsed(ENoComments).
+        */
+        static CStifFileParser* NewL(RFs& aFs,
+                                     RFile &aFile,
+                                     TBool aIsUnicode,
+                                     CStifParser::TCommentType aCommentType = CStifParser::ENoComments);
+
+        /**
+        * Destructor.
+        */
+        ~CStifFileParser();
+
+    public:     // New functions
+
+        /**
+        * Open and read configuration source and parses a required section.
+        * This method will parse next section after the earlier section if
+        * aSeeked parameter is equal 1.
+        * If configuration file includes several sections with both start and
+        * end tags so aSeeked parameter seeks the required section. The aSeeked
+        * parameters indicates section that will be parsed.
+        * If start tag is not given, returned section begins from the beginning of
+        * the file. If end tag is not given, returned sections ends at the end of
+        * the file.
+        * If section is not found and first occurence of section is seeked, function
+        * will return NULL, but if second (or further) occurence is seeked, function
+        * will leave with KErrNotFound (for compability with CStifParser::NextSectionL
+		* reason).
+        */
+		HBufC* NextSectionL(const TDesC& aStartTag,
+                            const TDesC& aEndTag,
+                            TInt& aOffset,
+                            TInt aSeeked = 1);
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CStifFileParser(CStifParser::TCommentType aCommentType);
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL(RFs& aFs,
+                        RFile &aFile,
+                        TBool aIsUnicode);
+
+        /**
+        * Reads configuration source and returns a complete line.
+        * This method will return also and end of line sequence.
+        */
+		TBool ReadLineL(TPtr& aLineBuffer,
+		                TPtr& aEndOfLineBuffer);
+
+        /**
+        * Parses a given line and removes all c-style comments from it (and #-style comments).
+        * Result is passed in destination buffer.
+        */
+		void ReplaceCommentsLineL(TPtr& aSrcBufPtr,
+		                          TPtr& aDstBufPtr,
+								  TWhatToFind& aFind);
+
+        /**
+        * Parses a given line and removes all #-style comments.
+        * Result is passed in destination buffer.
+        */
+	 	void ReplaceHashCommentsLineL(TPtr& aSrcBufPtr,
+ 	                                  TPtr& aDstBufPtr);
+
+        /**
+        * Closes all files on file stack and clears the stack.
+        */
+ 	    void ClearFileStack(void);
+
+        /**
+        * Pops RFile handle from file stack and sets correct current file handle.
+        */
+        void PopFromFileStack(void);
+
+        /**
+        * Opens file and pushes it to stack.
+        */
+        void PushFileToStackL(const TDesC& aFileName);
+
+        /**
+        * Deletes all descriptors assigned to array and empties array.
+        */
+        void ClearSectionLinesArray(void);
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+        /**
+        * For file opening.
+        */
+        RFs         iFileServer;
+
+        /**
+        * For file opening. This is the first (base) file. Later other files may be opened if
+        * they are included to base one.
+        */
+        RFile       iBaseFile;
+
+        /**
+        * Comment type's indication.
+        */
+        CStifParser::TCommentType iCommentType;
+
+        /**
+        * Flag indicating if file is unicode.
+        */
+        TBool       iIsUnicode;
+        
+        /**
+        * How many bytes per char in file (2 for unicode, 1 for non-unicode).
+        */
+        TInt 		iBytesPerChar;
+        
+        /**
+        * Handle to file which is currently read.
+        */
+        RFile*      iCurrentFile;
+
+        /**
+        * Stack of opened files (it does not contain base file).
+        */
+        CStackDeprecated<RFile, EFalse>* iFileStack;
+
+        /**
+        * Array of lines belonging to seeked section.
+        */
+		RPointerArray<HBufC> iSectionLines;
+
+		/**
+		* Array of already included files (to avoid loop in includes).
+		*/
+		RPointerArray<HBufC> iFileNames;
+
+		/**
+		* Buffer with eol sequence. Filled when include found and used after last line of inlcuded file.
+		*/
+		TBuf<2>     iEolBuf;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+};
+
+#endif      // STIF_FILE_PARSER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Parser/inc/cstackdeprecated.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2000-2007 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+// CStackDeprecated class was part of Symbian enviroment(as a CStack.h), but now it is deprecated. 
+
+#ifndef __CSTACKDEPRECATED_H__
+#define __CSTACKDEPRECATED_H__
+
+#include <e32base.h>
+
+#pragma warning (disable : 4127) // conditional expression is constant
+
+
+/**	
+	@file
+	@publishedAll
+	@released
+*/
+
+
+template <class T, TBool StackOwnsEntry>
+class CStackDeprecated : /*protected CArrayPtrSeg<T>*/ public CArrayPtrSeg<T>
+	{
+public:
+	inline CStackDeprecated();
+	inline ~CStackDeprecated();
+
+	inline void Clear();		
+	inline TBool IsEmpty() const;
+	inline void PushL(T* aItem);
+	inline T* Pop();
+	inline T* Head() const;
+	inline T* Last() const;		
+	};
+
+#include "cstackdeprecated.inl"
+
+#pragma warning ( default : 4127 ) // conditional expression is constant
+
+#endif // __CSTACK_HDEPRECATED__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Parser/inc/cstackdeprecated.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,107 @@
+/*
+* Copyright (c) 2000 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
+
+#ifndef __CSTACKDEPRECATED_INL__
+#define __CSTACKDEPRECATED_INL__
+
+// constants
+const TInt KStackGranularity=32;
+
+enum TCStackPanic
+	{
+	ECStackErrStackIsEmpty,
+	ECStackDeleteWhenNotOwner,
+	ECStackPopsWhenOwner
+	};
+
+_LIT(KCStackPanicName, "CStackDeprecated");
+
+inline void Panic(TCStackPanic aPanic)
+	{
+	User::Panic(KCStackPanicName, aPanic);
+	}
+
+//
+// CStack
+//
+
+template <class T, TBool StackOwnsEntry>
+inline CStackDeprecated<T, StackOwnsEntry>::CStackDeprecated()
+: CArrayPtrSeg<T>(KStackGranularity)
+	{
+	this->Reset();
+	}
+
+template <class T, TBool StackOwnsEntry>
+inline CStackDeprecated<T, StackOwnsEntry>::~CStackDeprecated()
+	{ 
+	Clear();
+	}
+
+template <class T, TBool StackOwnsEntry>
+inline void CStackDeprecated<T, StackOwnsEntry>::Clear() 
+	{ 
+	if (StackOwnsEntry) 
+		this->ResetAndDestroy(); 
+	else 
+		this->Reset(); 
+	}
+
+template <class T, TBool StackOwnsEntry>
+inline TBool CStackDeprecated<T, StackOwnsEntry>::IsEmpty() const 
+	{ 
+	return this->Count()==0;
+	}
+
+template <class T, TBool StackOwnsEntry>
+inline void CStackDeprecated<T, StackOwnsEntry>::PushL(T* aItem) 
+	{
+	if (StackOwnsEntry)
+		CleanupStack::PushL(aItem); 
+	this->AppendL(aItem); 
+	if (StackOwnsEntry)
+		CleanupStack::Pop();
+	}
+
+template <class T, TBool StackOwnsEntry>
+inline T* CStackDeprecated<T, StackOwnsEntry>::Pop() 
+	{
+	__ASSERT_DEBUG(!IsEmpty(), Panic(ECStackErrStackIsEmpty));
+	T* item=Head(); 
+	this->Delete(this->Count()-1);
+	return item;
+	}
+
+template <class T, TBool StackOwnsEntry>
+inline T* CStackDeprecated<T, StackOwnsEntry>::Head() const 
+	{
+	__ASSERT_DEBUG(!IsEmpty(), Panic(ECStackErrStackIsEmpty));
+	return this->At(this->Count()-1);
+	}
+
+template <class T, TBool StackOwnsEntry>
+inline T* CStackDeprecated<T, StackOwnsEntry>::Last() const 
+	{
+	__ASSERT_DEBUG(!IsEmpty(), Panic(ECStackErrStackIsEmpty));
+	return this->At(0);
+	}
+	
+
+#endif // __CSTACKDEPRECATED_INL__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Parser/src/StifFileParser.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,929 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CStifParser 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "StifFileParser.h"
+#include "StifTestInterface.h"
+#include "ParserTracing.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: CStifFileParser
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: TCommentType aCommentType: in: Comment type's indication
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifFileParser::CStifFileParser(CStifParser::TCommentType aCommentType)
+	{
+    iCommentType = aCommentType;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Sets variables.
+
+    Parameters: RFs& aFs:        in: Handle to valid file server
+                RFile& aFile:    in: Handle to the source file
+                TBool aIsUnicode in: Is file in unicode format
+
+    Return Values: None
+
+    Errors/Exceptions:  None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifFileParser::ConstructL(RFs& aFs,
+                                 RFile& aFile,
+                                 TBool aIsUnicode)
+	{
+	//Initialization
+	iFileServer = aFs;
+	iBaseFile = aFile;
+	iCurrentFile = &aFile;
+	iIsUnicode = aIsUnicode;
+	iBytesPerChar = iIsUnicode ? 2 : 1;
+
+	//Create file stack (INCLUDE feature)
+	iFileStack = new (ELeave) CStackDeprecated<RFile, EFalse>;
+
+	//Add base file to file names array
+	TFileName fn;
+	iCurrentFile->FullName(fn);
+	HBufC* newFile = fn.AllocLC();
+	User::LeaveIfError(iFileNames.Append(newFile));
+	CleanupStack::Pop(newFile);
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Starting creating parser with path and file information.
+
+    Parameters: RFs& aFs:                  in: Handle to file server
+                RFile& aFile:              in: Source path definition
+                TBool aIsUnicode           in: Is file in unicode format
+                TCommentType aCommentType: in: Comment type's indication
+
+    Return Values: CStifFileParser* : pointer to CStifFileParser object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CStifFileParser* CStifFileParser::NewL(RFs& aFs,
+                                       RFile& aFile,
+                                       TBool aIsUnicode,
+                                       CStifParser::TCommentType aCommentType)
+	{
+    // Create CStifParser object
+    CStifFileParser* parser = new (ELeave) CStifFileParser(aCommentType);
+
+    CleanupStack::PushL(parser);
+    parser->ConstructL(aFs, aFile, aIsUnicode);
+    CleanupStack::Pop(parser);
+
+    return parser;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: ~CStifFileParser
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CStifFileParser::~CStifFileParser()
+	{
+	//Close file stack
+	ClearFileStack();
+	delete iFileStack;
+
+	//Close section lines array
+	ClearSectionLinesArray();
+	iSectionLines.Close();
+	
+	//Close fila names array
+	while(iFileNames.Count() > 0)
+		{
+		delete iFileNames[0];
+		iFileNames.Remove(0);
+		}
+	iFileNames.Close();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: ReadLineL
+
+    Description: Reads line from source file
+
+    Parameters: TPtr& aLineBuffer:      in: Descriptor in which line loads
+                TPtr& aEndOfLineBuffer: in: Descriptor in which end of line sequence is loaded (0x0A or 0x0D 0x0A)
+
+    Return Values: TBool: determines whether line was readed or not
+
+    Errors/Exceptions:  Leaves if seek command leaves
+    					Leaves if buffer is too small
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CStifFileParser::ReadLineL(TPtr& aLineBuffer,
+                                 TPtr& aEndOfLineBuffer)
+	{
+	//Variables
+	TBuf8<128> buf8;
+	TBuf16<128> buf16;
+	TPtrC16 buf;
+	TInt pos;
+	TInt offset;
+	TChar char0x0A = 0x000A;
+	TChar char0x0D = 0x000D;
+
+	TBuf<1> b0x0A;
+	b0x0A.Append(char0x0A);
+
+	//Reset buffers
+	aLineBuffer.Zero();
+	aEndOfLineBuffer.Zero();
+
+	//Read from source
+	User::LeaveIfError(iCurrentFile->Read(buf8));
+	buf16.Copy(buf8);
+	if(iIsUnicode)
+		buf.Set((TUint16 *)(buf8.Ptr()), buf8.Length() / 2);
+	else
+		buf.Set(buf16.Ptr(), buf16.Length());
+
+	while(buf.Length())
+		{
+		//Search for end of line char
+		pos = buf.Find(b0x0A);
+
+		//If found, append readed data to output descriptor and move back file offset to correct position
+		if(pos >= 0)
+			{
+			offset = -((buf.Length() - pos - 1) * iBytesPerChar);
+			User::LeaveIfError(iCurrentFile->Seek(ESeekCurrent, offset));
+			buf.Set(buf.Ptr(), pos + 1);
+			aLineBuffer.Append(buf);
+			break;
+			}
+		//Otherwise, append whole buffer to output descriptor
+		else
+			{
+			aLineBuffer.Append(buf);
+			}
+		//Read next part of data
+		User::LeaveIfError(iCurrentFile->Read(buf8));
+		buf16.Copy(buf8);
+		if(iIsUnicode)
+			{
+			buf.Set((TUint16 *)(buf8.Ptr()), buf8.Length() / 2);
+			}
+		else
+			{
+			buf.Set(buf16.Ptr(), buf16.Length());
+			}
+		}
+
+	//Set correct end of line buffer
+	if(buf.Length() > 1)
+		{
+		if(buf[buf.Length() - 2] == char0x0D)
+			{
+			aEndOfLineBuffer.Append(char0x0D);
+			}
+		}
+	if(buf.Length() > 0)
+		{
+		if(buf[buf.Length() - 1] == char0x0A)
+			{
+			aEndOfLineBuffer.Append(char0x0A);
+			}
+		else
+			{
+			aEndOfLineBuffer.Zero();
+			}
+		}
+	if(aEndOfLineBuffer.Length())
+		{
+		aLineBuffer.SetLength(aLineBuffer.Length() - aEndOfLineBuffer.Length());
+		}
+
+	//If no data was found, try to get previous file from stack
+	if(aLineBuffer.Length() + aEndOfLineBuffer.Length() == 0)
+		{
+		//Pop file from stack. If stack is empty, then we achieved end of base file
+		if(!iFileStack->IsEmpty())
+			{
+			PopFromFileStack();
+			aEndOfLineBuffer.Copy(iEolBuf);
+			return aEndOfLineBuffer.Length();
+			}
+		}
+	//Check if this is include line
+	else
+		{
+		if(aLineBuffer.Find(KIncludeKeyword) == 0)
+			{
+			TFileName fn;
+			TLex lex(aLineBuffer);
+
+			fn.Copy(lex.NextToken()); //get INCLUDE keyword
+			fn.Copy(lex.NextToken()); //get cfg file name
+			if(fn.Length() > 0)
+				{
+				TStifUtil::CorrectFilePathL( fn );
+				PushFileToStackL(fn);
+				iEolBuf.Copy(aEndOfLineBuffer);
+				}
+			else
+				{
+				__TRACE(KError, (_L("No filename was given after INCLUDE. Ignoring")));
+				}
+
+			//Read next line
+			return ReadLineL(aLineBuffer, aEndOfLineBuffer);
+			}
+		}
+	
+	return aLineBuffer.Length() + aEndOfLineBuffer.Length();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: ReplaceCommentsLineL
+
+    Description: Replaces comments with spaces from line and copy it to destination buffer
+
+    Parameters: TPtr& aSrcBufPtr:        in:  Source line with comments
+                TPtr& aDstBufPtr:       out:  Destination line without comments
+                TWhatToFind& aFind:  in out:  Determines what method currently is looking for
+
+    Return Values: None
+
+    Errors/Exceptions:  None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifFileParser::ReplaceCommentsLineL(TPtr& aSrcBufPtr,
+                                           TPtr& aDstBufPtr,
+										   TWhatToFind& aFind)
+	{
+	//Variables
+	TLex lex(aSrcBufPtr);
+	TChar ch;
+	TChar chSpace(' ');
+	TChar chSlash('/');
+	TChar chQuota('\"');
+	TChar chMulti('*');
+	TChar chHash('#');
+
+	//Clean buffer
+	aDstBufPtr.Zero();
+
+	while(!lex.Eos())
+		{
+		ch = lex.Get();
+
+		//If the end of line, exit
+		if(!ch)
+			{
+			break;
+			}
+
+		//We're looking for start od quoted text or comment
+		if(aFind == EStart)
+			{
+			//Special character readed
+			if(ch == chQuota)
+				{
+				aFind = EQuota;
+				aDstBufPtr.Append(chSpace);
+				}
+			//Possible start of comment
+			else if(ch == chSlash)
+				{
+				//Comment to the end of line found
+				if(lex.Peek() == chSlash)
+					{
+					break;
+					}
+				//Beginning of a comment found
+				else if(lex.Peek() == chMulti)
+					{
+					aFind = EEndOfComment;
+					ch = lex.Get();
+					aDstBufPtr.Append(chSpace);
+					aDstBufPtr.Append(chSpace);
+					}
+				//No start of comment - add read slash
+				else
+					{
+					aDstBufPtr.Append(ch);
+					}
+				}
+			//Start of hash comment (to the end of line)
+			else if(ch == chHash)
+				{
+				break;
+				}
+			//Append readed character to the destination buffer
+			else
+				{
+				aDstBufPtr.Append(ch);
+				}
+			}
+		//We're looking for the end of quoted text
+		else if(aFind == EQuota)
+			{
+			if(ch == chQuota)
+				{
+				aFind = EStart;
+				aDstBufPtr.Append(chSpace);
+				}
+			else
+				{
+				aDstBufPtr.Append(chSpace);
+				}
+			}
+		//We're looking for the end of comment
+		else if(aFind == EEndOfComment)
+			{
+			//It may be the end of a comment
+			if(ch == chMulti)
+				{
+				ch = lex.Peek();
+				//It is the end of a comment
+				if(ch == chSlash)
+					{
+					aFind = EStart;
+					ch = lex.Get();
+					aDstBufPtr.Append(chSpace);
+					aDstBufPtr.Append(chSpace);
+					}
+				//It is not the end of a comment, add this character to the destinaton buffer
+				else
+					{
+					aDstBufPtr.Append(chSpace);
+					}
+				}
+			//It is not the end of a comment, add this character to the destinaton buffer
+			else
+				{
+				aDstBufPtr.Append(chSpace);
+				}
+			}
+		}
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: ReplaceHashCommentsLineL
+
+    Description: Copy line to destination buffer and deletes #-style comments
+
+    Parameters: TPtr& aSrcBufPtr:     in:  Source line with comments
+                TPtr& aDstBufPtr:    out: Destination line without comments
+
+    Return Values: None
+
+    Errors/Exceptions:  None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifFileParser::ReplaceHashCommentsLineL(TPtr& aSrcBufPtr,
+                                               TPtr& aDstBufPtr)
+	{
+	//Variables
+	TLex lex(aSrcBufPtr);
+	TChar ch;
+	TChar chHash('#');
+
+	//Prepare destination buffer
+	aDstBufPtr.Zero();
+
+	//Copy source line to destination until # char is found
+	while(!lex.Eos())
+		{
+		ch = lex.Get();
+
+		//If the end of line, exit
+		if(!ch)
+			{
+			break;
+			}
+
+		if(ch == chHash)
+			{
+			break;
+			}
+		else
+			{
+			aDstBufPtr.Append(ch);
+			}
+		}
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: NextSectionL
+
+    Description: Finds n-th (aSeeked) section in file starting from m-th (aOffset) position
+
+    Parameters: const TDesc& aStartTag: in:     Starting tag of a section
+                const TDesc& aEndTag:   in:     Ending tag of a section
+                TInt& aOffset:          in out: Current offset in file (*)
+                TInt aSeeked:           in:     Which section is to be found
+    
+    Notification: aOffset has different meaning than before adding INCLUDE functionality.
+                  If it has 0 value, that means that we need to remove files stack and go
+                  back to base file to the beginning. Otherwise we don't change current
+                  file read-handler position.
+
+    Return Values: HBufC *: address of a descriptor containing section. Section is returned without tags.
+                            Caller must take care about the freeing descriptor.
+
+    Errors/Exceptions:  Leaves if aSeeked is less than 1 or aOffset is negative
+    					Leaves if seek command leaves
+    					Leaves if cannot allocate buffers
+    					Leaves if cannot allocate section
+    					Leaves if length of readed line exceeds KMaxLineLength constant
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+HBufC* CStifFileParser::NextSectionL(const TDesC& aStartTag,
+                                     const TDesC& aEndTag,
+                                     TInt& aOffset,
+                                     TInt aSeeked)
+	{
+	// Check arguments
+	if(aSeeked < 1)
+		{		
+		User::Leave(KErrArgument);
+		}
+	if(aOffset < 0)
+		{		
+		User::Leave(KErrArgument);
+		}
+
+	TInt foundSection = 0;
+	TInt ret;
+
+	// Alloc buffers to read line
+	const TInt KMaxLineLength = 4096; //If length of readed line exceeds this constant, method will leave
+
+	HBufC* buf = HBufC::NewL(KMaxLineLength);
+	CleanupStack::PushL(buf);
+	TPtr bufPtr(buf->Des());
+
+	HBufC* withoutCommentsBuf = HBufC::NewL(KMaxLineLength);
+	CleanupStack::PushL(withoutCommentsBuf);
+	TPtr withoutCommentsBufPtr(withoutCommentsBuf->Des());
+
+	HBufC* endOfLine = HBufC::NewL(2);  //After reading a line it contains 0D0A or 0A or null (how readed line is ended)
+	CleanupStack::PushL(endOfLine);
+	TPtr endOfLinePtr(endOfLine->Des());
+
+	//Set valid position in file
+	//but only if offset shows to 0. Otherwise keep previus position
+	if(aOffset == 0)
+		{
+		User::LeaveIfError(iBaseFile.Seek(ESeekStart, aOffset));
+		ClearFileStack();
+		aOffset = 1;
+		}
+
+	//Prepare to read lines
+	TBool validSectionBeginFound = EFalse;
+	TBool validSectionEndFound = EFalse;
+	TSectionFind whatToFindSection = ESectionStart;
+	//If no start tag is given start to find end tag immediatly
+	if(aStartTag.Length() == 0)
+		{
+		foundSection++;
+		whatToFindSection = ESectionEnd;
+		validSectionBeginFound = ETrue;
+		}
+	if(aEndTag.Length() == 0)
+		{
+		validSectionEndFound = ETrue;
+		}
+	TWhatToFind whatToFind = EStart;
+
+	//Perform reading file
+	while(ReadLineL(bufPtr, endOfLinePtr))
+		{
+		if(iCommentType == CStifParser::ECStyleComments)
+			{				
+			ReplaceCommentsLineL(bufPtr, withoutCommentsBufPtr, whatToFind);
+			}
+		else
+			{
+			ReplaceHashCommentsLineL(bufPtr, withoutCommentsBufPtr);
+			}
+			if(whatToFindSection == ESectionStart)
+			{
+			//Find in line star tag (if start tag is not given, behave like we've found it)
+			if(aStartTag.Length() == 0)
+				{
+				ret = 0;
+				}
+			else
+				{
+				ret = withoutCommentsBuf->Find(aStartTag);
+				}
+			//If found remember position, move offset of file to actual position
+			if(ret >= 0)
+				{
+				whatToFindSection = ESectionEnd;
+				TInt offset = -(bufPtr.Length() + endOfLinePtr.Length() - ret - aStartTag.Length()) * iBytesPerChar;
+				User::LeaveIfError(iCurrentFile->Seek(ESeekCurrent, offset));
+
+				whatToFind = EStart; //reset marker, because if we've found tag, we couldn't be in the middle of comment or quota
+				foundSection++;
+				//Add this line to section lines array
+				if(foundSection == aSeeked)
+					{
+					validSectionBeginFound = ETrue;
+					}
+				continue;
+				}
+			}
+		else if(whatToFindSection == ESectionEnd)
+			{
+			//Find in line end tag (if end tag is not given, behave like we've found it)
+			if(aEndTag.Length() == 0)
+				{
+				ret = KErrNotFound;
+				}
+			else
+				{
+				ret = withoutCommentsBuf->Find(aEndTag);
+				}
+				//If found check if this is the one we're looking for
+			if(ret >= 0)
+				{
+				whatToFindSection = ESectionStart;
+				TInt offset = -(bufPtr.Length() + endOfLinePtr.Length() - ret - aEndTag.Length()) * iBytesPerChar;
+				User::LeaveIfError(iCurrentFile->Seek(ESeekCurrent, offset));
+
+				whatToFind = EStart; //reset marker, because if we've found tag, we couldn't be in the middle of comment or quota
+				if(foundSection == aSeeked)
+					{
+					//Add this line to section lines array
+					HBufC* line = HBufC::NewLC(bufPtr.Length());
+					TPtr linePtr(line->Des());
+					linePtr.Copy(bufPtr.MidTPtr(0, ret));
+					User::LeaveIfError(iSectionLines.Append(line));
+					CleanupStack::Pop(line);
+					validSectionEndFound = ETrue;
+					break;
+					}
+				else
+					{
+					continue;
+					}
+				}
+			else
+				{
+				//If we're in section we are looking for, add line to array
+				if(foundSection == aSeeked)
+					{
+					HBufC* line = HBufC::NewLC(bufPtr.Length() + endOfLinePtr.Length());
+					TPtr linePtr(line->Des());
+					linePtr.Copy(bufPtr);
+					linePtr.Append(endOfLinePtr);
+					User::LeaveIfError(iSectionLines.Append(line));
+					CleanupStack::Pop(line);
+					}
+				}
+			}
+		}
+
+	//Clean data
+	CleanupStack::PopAndDestroy(endOfLine);
+	CleanupStack::PopAndDestroy(withoutCommentsBuf);
+	CleanupStack::PopAndDestroy(buf);
+	
+	//Load into section if found
+	HBufC* section = NULL;
+
+	if(validSectionBeginFound && validSectionEndFound)
+		{
+		//Count amount of memory needed for section
+		TInt i;
+		TInt size = 0;
+		for(i = 0; i < iSectionLines.Count(); i++)
+			size += iSectionLines[i]->Length();
+		
+		//Copy section from array to buffer
+		section = HBufC::NewL(size);
+		CleanupStack::PushL(section);
+		TPtr sectionPtr(section->Des());
+
+		for(i = 0; i < iSectionLines.Count(); i++)
+			sectionPtr.Append(*iSectionLines[i]);
+
+		ClearSectionLinesArray();
+		
+		//Clean local data
+		CleanupStack::Pop(section);
+		
+		return section;
+		}
+	
+	ClearSectionLinesArray();
+
+	//If section was not found, then for compability with CSectionParser leave when not first section was seeking, return NULL when first section was seeking
+	if(foundSection != aSeeked)
+		{
+		if( aSeeked - foundSection > 1)
+			{			
+			User::Leave(KErrNotFound);
+			}
+		}
+
+    return section;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: ClearFileStack
+
+    Description: Closes all files on file stack and clears the stack
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions:  None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifFileParser::ClearFileStack(void)
+	{
+	while(!iFileStack->IsEmpty())
+		{
+		PopFromFileStack();
+		}
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: PopFromFileStack
+
+    Description: Pops RFile handle from file stack and sets correct current file handle
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions:  None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifFileParser::PopFromFileStack(void)
+	{
+	if(!iFileStack->IsEmpty())
+		{
+		//Pop from stack
+		iCurrentFile = iFileStack->Pop();
+
+		TFileName fn;
+		iCurrentFile->FullName(fn);
+
+		//And remove from file names array
+		for(TInt i = iFileNames.Count() - 1; i >= 0; i--)
+			{
+			if(fn.CompareF(iFileNames[i]->Des()) == KErrNone)
+				{
+				delete iFileNames[i];
+				iFileNames.Remove(i);
+				break;
+				}
+			}
+		__TRACE(KInfo, (_L("Closing file [%S]"), &fn));
+
+		//Close file
+		iCurrentFile->Close();
+		delete iCurrentFile;
+
+		//Set correct current file
+		if(iFileStack->IsEmpty())
+			{
+			iCurrentFile = &iBaseFile; //base file, because stack is empty
+			}
+		else
+			{
+			iCurrentFile = iFileStack->Last();
+			}
+		}
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: PushFileToStack
+
+    Description: Opens file and pushes it to stack
+
+    Parameters: TDesc& aFileName   in: name of file to open and add to stack
+
+    Return Values: None
+
+    Errors/Exceptions:  None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifFileParser::PushFileToStackL(const TDesC& aFileName)
+	{
+
+	//First check if file is not already included
+	for(TInt i = 0; i < iFileNames.Count(); i++)
+		{
+		if(aFileName.CompareF(iFileNames[i]->Des()) == KErrNone)
+			{
+			__TRACE(KError, (_L("File [%S] was already included. Ignoring"), &aFileName));
+			return;
+			}
+		}
+
+	//Open and add file to stack
+	RFile *nf = new RFile();
+
+	__TRACE(KInfo, (_L("Including file [%S]"), &aFileName));
+	TInt r = nf->Open(iFileServer, aFileName, EFileRead | EFileShareAny);
+	if(r == KErrNone)
+		{
+		//Add to stack
+		iFileStack->PushL(nf);
+
+		//And add to file names array
+		HBufC* newFile = aFileName.AllocLC();
+		User::LeaveIfError(iFileNames.Append(newFile));
+		CleanupStack::Pop(newFile);
+
+		//Set valid pointer of current file
+		iCurrentFile = nf;
+		}
+	else
+		{
+		__TRACE(KError, (_L("Could not open file [%S]. Error %d. Ignoring"), &aFileName, r));
+		}
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifFileParser
+
+    Method: ClearSectionLinesArray
+
+    Description: Deletes all descriptors assigned to array and empties array
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions:  None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifFileParser::ClearSectionLinesArray(void)
+	{
+	while(iSectionLines.Count() > 0)
+		{
+		delete iSectionLines[0];
+		iSectionLines.Remove(0);
+		}
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Parser/src/StifItemParser.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1247 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CStifItemParser 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "StifItemParser.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CStifItemParser class member
+    functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: CStifItemParser
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: TPtrC aSection: in: Parsed section
+                TInt aStartPos: in: Start point of parsing
+                TInt aLength: in: Length of parsed section
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifItemParser::CStifItemParser( TPtrC aSection,
+                                    TInt aStartPos,
+                                    TInt aLength ) :
+    iItemLineSection( aSection.Mid( aStartPos, aLength ) ),
+    iItemSkipAndMarkPos( 0 ),
+    iGetMethodsIndicator( EFalse ),
+    iParsingType( CStifItemParser::ENormalParsing ) // Mode ON
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CStifItemParser::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: TPtrC aSection: in: Parsed section
+                TInt aStartPos: in: Start point of parsing
+                TInt aLength: in: Length of parsed section
+
+    Return Values: CStifItemParser*: pointer to CStifItemParser object
+
+    Errors/Exceptions:  Leaves if memory allocation fails
+                        Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifItemParser* CStifItemParser::NewL( TPtrC aSection,
+                                                    TInt aStartPos,
+                                                    TInt aLength )
+    {
+    CStifItemParser* item = new (ELeave) CStifItemParser( aSection, aStartPos,
+                                                            aLength );
+
+    CleanupStack::PushL( item );
+    item->ConstructL();
+    CleanupStack::Pop( item );
+
+    return item;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: ~CStifItemParser
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/    
+CStifItemParser::~CStifItemParser()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: ParseStartAndEndPos
+
+    Description: Start and end position parser.
+                 Handles also quote feature parsing. EQuoteStyleParsing
+                 option removes correctly setted quotes(" and ").
+
+    Parameters: TPtrC aSection: in: Parsed section
+                const TDesC& aStartTag: in: Start tag of parsing
+                TInt& aStartPos: inout: Start point of parsing
+                TInt& aEndPos: inout: End point of parsing
+                TInt& aLength: inout: Length of parsed section
+                TInt& aExtraEndPos: inout: Used if end position needs to
+                                           set, e.g. used in quote cases.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+
+TInt CStifItemParser::ParseStartAndEndPos( TPtrC aSection,
+                                        const TDesC& aStartTag,
+                                        TInt& aStartPos,
+                                        TInt& aEndPos,
+                                        TInt& aLength,
+                                        TInt& aExtraEndPos )
+    {
+    aStartPos = 0;
+    aEndPos = 0;
+    aExtraEndPos = 0; // Normally this is 0    
+    
+    RBuf tag( aStartTag.AllocL() );
+    // Remove whitespaces at the begining and end of the tag
+    tag.Trim();
+    
+    // Create parser
+    TLex lex( aSection );
+    // Move parsing pointer to position from which parsing will start 
+    lex.SkipAndMark( iItemSkipAndMarkPos );
+    
+    TBool tagWithEqualMark = EFalse;
+    
+    // Check if tag is defined
+    if ( tag.Length() != 0 )
+    	{
+    	// Check if tag contains '=' character at the end.
+    	// If tag is "=" then we treat it as normal tag (not as tag with '=' 
+    	// character).
+        if ( ( tag.Length() > 1 ) && ( tag.Right( 1 ) == _L("=") ) )
+        	{
+        	// Tag contains '=' character. Remove '=' so only clean tag remains. 
+        	tagWithEqualMark = ETrue;
+        	tag.SetLength( tag.Length() - 1 );
+        	tag.Trim();
+        	}
+
+		// Search for specified tag in parsed text
+		while( !lex.Eos() )
+			{
+			lex.SkipSpaceAndMark();
+			TPtrC token = lex.NextToken();
+			if ( tagWithEqualMark ) 
+				{
+				if ( ( token == tag ) && ( !lex.Eos() ) ) // "tag = val" or "tag =val" 
+					{
+					lex.SkipSpaceAndMark();
+					TPtrC val = lex.NextToken();
+					lex.UnGetToMark();
+					if ( val == _L("=") ) // "tag = val"
+						{
+						lex.Inc();
+						break;
+						}
+					else	// "tag =val"
+						{
+						if ( val.Left( 1 ) == _L("=") )
+							{
+							// Skip "=" character.
+							lex.Inc();
+							break;
+							}
+						else // We didn't find any variation of "tag="
+							{
+							lex.UnGetToMark();
+							}
+						}
+					}
+				else // "tag=val" or "tag= val"
+					{
+					// It handles both situations
+					if ( ( token.Find( tag ) == 0 ) && ( token.Find( _L("=") ) == tag.Length() ) )
+						{
+						lex.UnGetToMark();
+						lex.SkipAndMark( tag.Length() + 1 );
+						lex.SkipSpace();
+						break;
+						}
+					}
+				}
+			else
+				{
+				// Tag without '=' character. Just compare.
+    			if ( token == tag )
+    				{
+    				break;
+    				}
+				}
+			}
+		
+		// Check if we are at the end of parsed text
+		if ( lex.Eos() )
+			{
+			// We are at the end of parsed text. Eaven if we found tag its value
+			// is not defined.
+			tag.Close();
+			return KErrNotFound;
+			}
+    		    	
+    	}
+    
+    tag.Close();       
+
+	if( iParsingType == CStifItemParser::ENormalParsing )
+		{
+        TPtrC ptr = lex.NextToken();
+        aEndPos = lex.Offset();             // End position
+        aStartPos = aEndPos - ptr.Length(); // Start position    		
+		}
+	else
+		{
+		lex.SkipSpaceAndMark();		
+		TPtrC token = lex.NextToken();
+		lex.UnGetToMark();
+		
+		if ( token.Length() == 0 )
+			{
+			return KErrNotFound;
+			}
+		
+		if ( token.Left( 1 ) == _L("\"") )
+			{
+			lex.Inc();
+			aStartPos = lex.Offset();
+			
+			TBool foundEndingQuoteMark = false;
+			while( !lex.Eos() )
+				{
+				if ( lex.Get() == '"' ) 
+					{
+					foundEndingQuoteMark = ETrue;
+					break;;
+					}
+				}
+
+			if ( foundEndingQuoteMark )
+				{
+				aEndPos = lex.Offset() - 1;
+				if ( aEndPos > aStartPos )
+					{
+					aExtraEndPos = 1;
+					}
+				else
+					{
+					aStartPos--;
+					aEndPos++;
+					}
+				}
+			else
+				{
+				lex.UnGetToMark();
+				aStartPos = lex.Offset();
+	            TPtrC ptr = lex.NextToken();
+	            aEndPos = lex.Offset();             // End position	            
+				}			
+			}
+		else
+			{
+            TPtrC ptr = lex.NextToken();
+            aEndPos = lex.Offset();             // End position
+            aStartPos = aEndPos - ptr.Length(); // Start position    		
+			}
+		}
+
+    aLength = ( aEndPos - aStartPos );      
+    
+    // aStartPos is negative (0 is allowed) or length is negative
+    if( ( aLength <= 0 ) && ( iParsingType == CStifItemParser::ENormalParsing ) )
+        {
+        return KErrNotFound;
+        }
+    
+    return KErrNone;    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetString
+
+    Description: Get a string.
+
+    Search an item from the section and return everything after the item until
+    separator cut the parsing.
+    If start tag is empty the first string will be parsed and returned.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TPtrC& aString: inout: Parsed string
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetString( const TDesC& aTag, TPtrC& aString )
+    {
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+
+    iItemSkipAndMarkPos = 0;
+    TInt ret = ParseStartAndEndPos( iItemLineSection, aTag, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret)
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos + extraEndPos;
+
+    // Take string
+    aString.Set( (TUint16*)&iItemLineSection[startPos], length );
+
+    // Indicator that GetString has been used
+    iGetMethodsIndicator = ETrue;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetNextString
+
+    Description: Get a next string.
+
+    Get next string until separator cut the parsing. GetString or GetInt or
+    GetChar must be called before call GetNextString method.
+
+    Parameters: TPtrC& aString: inout: Parsed string
+    
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetNextString( TPtrC& aString )
+    {
+    // GetString(), GetInt() or GetChar() is not called
+    if ( !iGetMethodsIndicator )
+        {
+        return KErrNotReady;
+        }
+
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+    TInt ret = ParseStartAndEndPos( iItemLineSection, KNullDesC, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret)
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos + extraEndPos;
+
+    // Take string
+    aString.Set( (TUint16*)&iItemLineSection[startPos], length );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetNextString
+
+    Description: Get a next string with tag.
+
+    Get next string with tag until separator cut the parsing. If start tag is
+    empty the next string will be parsed and returned.
+    GetString or GetInt or GetChar must be called before call GetNextString
+    method.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TPtrC& aString: inout: Parsed string
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetNextString( const TDesC& aTag,
+                                                TPtrC& aString )
+    {
+    // GetString(), GetInt() or GetChar() is not called
+    if ( !iGetMethodsIndicator )
+        {
+        return KErrNotReady;
+        }
+
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+    TInt ret = ParseStartAndEndPos( iItemLineSection, aTag, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret)
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos + extraEndPos;
+
+    // Take string
+    aString.Set( (TUint16*)&iItemLineSection[startPos], length );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetInt
+
+    Description: Get a integer.
+
+    Search an item from the section and return integer after the item until 
+    separator cut the parsing.
+    If start tag is empty the first integer will be parsed and returned.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TInt& aInteger: inout: Parsed integer
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetInt( const TDesC& aTag, TInt& aInteger )
+    {
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+
+    iItemSkipAndMarkPos = 0;
+    TInt ret = ParseStartAndEndPos( iItemLineSection, aTag, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos;
+
+    // Indicator that GetInt has been used
+    iGetMethodsIndicator = ETrue;
+
+    // Take integer
+    TLex lex( iItemLineSection );
+    // Mark to current position of parsing
+    lex.SkipAndMark( startPos );
+    lex.SkipSpace();
+    return lex.Val( aInteger );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetNextInt
+
+    Description: Get a next integer.
+
+    Get next integer until separator cut the parsing and returns it.
+    GetString or GetInt or GetChar must be called before call GetNextInt
+    method.
+
+    Parameters: TInt& aInteger: inout: Parsed integer
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetNextInt( TInt& aInteger )
+    {
+    // GetString(), GetInt() or GetChar() is not called
+    if ( !iGetMethodsIndicator )
+        {
+        return KErrNotReady;
+        }
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+    TInt ret = ParseStartAndEndPos( iItemLineSection, KNullDesC, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos;
+
+    // Take integer
+    TLex lex( iItemLineSection );
+    // Mark to current position of parsing
+    lex.SkipAndMark( startPos );
+    lex.SkipSpace();
+    return lex.Val( aInteger );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetNextInt
+
+    Description: Get a next integer with tag.
+
+    Get next integer with tag until separator cut the parsing. If start tag is
+    empty the next integer will be parsed and returned.
+    GetString or GetInt or GetChar must be called before call GetNextInt
+    method.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TInt& aInteger: inout: Parsed integer
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetNextInt( const TDesC& aTag, TInt& aInteger )
+    {
+    // GetString(), GetInt() or GetChar() is not called
+    if ( !iGetMethodsIndicator )
+        {
+        return KErrNotReady;
+        }
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+    TInt ret = ParseStartAndEndPos( iItemLineSection, aTag, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos;
+
+    // Take integer
+    TLex lex( iItemLineSection );
+    // Mark to current position of parsing
+    lex.SkipAndMark( startPos );
+    lex.SkipSpace();
+    return lex.Val( aInteger );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetInt
+
+    Description: Get a integer.
+
+    Search an item from the section and return integer after the item until 
+    separator cut the parsing.
+    If start tag is empty the first integer will be parsed and returned.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TUint& aInteger: inout: Parsed integer
+                TRadix aRadix: in: Convert a number into different
+                presentation. For default: EDecimal.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetInt( const TDesC& aTag,
+                                        TUint& aInteger,
+                                        TRadix aRadix )
+    {
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+
+    iItemSkipAndMarkPos = 0;
+    TInt ret = ParseStartAndEndPos( iItemLineSection, aTag, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos;
+
+    // Indicator that GetInt has been used
+    iGetMethodsIndicator = ETrue;
+
+    // Take integer
+    TLex lex( iItemLineSection );
+    // Mark to current position of parsing
+    lex.SkipAndMark( startPos );
+    lex.SkipSpace();
+    // NOTE: If parsed integer is e.g. '-1' and aRadix is EDesimal the lex will
+    // return error code -2(KErrGeneral). Main reason is for this new TUint
+    // method that cast operation does not work in above case and -2 returned.
+    // In this case use GetInt method that reference type is TInt.
+    return lex.Val( aInteger, aRadix );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetNextInt
+
+    Description: Get a next integer.
+
+    Get next integer until separator cut the parsing and returns it.
+    GetString or GetInt or GetChar must be called before call GetNextInt
+    method.
+
+    Parameters: TUint& aInteger: inout: Parsed integer
+                TRadix aRadix: in: Convert a number into different
+                presentation. For default: EDecimal.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetNextInt( TUint& aInteger,
+                                            TRadix aRadix )
+    {
+    // GetString(), GetInt() or GetChar() is not called
+    if ( !iGetMethodsIndicator )
+        {
+        return KErrNotReady;
+        }
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+    TInt ret = ParseStartAndEndPos( iItemLineSection, KNullDesC, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos;
+
+    // Take integer
+    TLex lex( iItemLineSection );
+    // Mark to current position of parsing
+    lex.SkipAndMark( startPos );
+    lex.SkipSpace();
+    // NOTE: If parsed integer is e.g. '-1' and aRadix is EDesimal the lex will
+    // return error code -2(KErrGeneral). Main reason is for this new TUint
+    // method that cast operation does not work in above case and -2 returned.
+    // In this case use GetNextInt method that reference type is TInt.
+    return lex.Val( aInteger, aRadix );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetNextInt
+
+    Description: Get a next integer with tag.
+
+    Get next integer with tag until separator cut the parsing. If start tag is
+    empty the next integer will be parsed and returned.
+    GetString or GetInt or GetChar must be called before call GetNextInt
+    method.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TUint& aInteger: inout: Parsed integer
+                TRadix aRadix: in: Convert a number into different
+                presentation. For default: EDecimal.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetNextInt( const TDesC& aTag,
+                                            TUint& aInteger,
+                                            TRadix aRadix )
+    {
+    // GetString(), GetInt() or GetChar() is not called
+    if ( !iGetMethodsIndicator )
+        {
+        return KErrNotReady;
+        }
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+    TInt ret = ParseStartAndEndPos( iItemLineSection, aTag, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = endPos;
+
+    // Take integer
+    TLex lex( iItemLineSection );
+    // Mark to current position of parsing
+    lex.SkipAndMark( startPos );
+    lex.SkipSpace();
+    // NOTE: If parsed integer is e.g. '-1' and aRadix is EDesimal the lex will
+    // return error code -2(KErrGeneral). Main reason is for this new TUint
+    // method that cast operation does not work in above case and -2 returned.
+    // In this case use GetNextInt method that reference type is TInt.
+    return lex.Val( aInteger, aRadix );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetChar
+
+    Description: Get a character.
+
+    Search an item from the section and return character after the item.
+    If start tag is empty the first character will be parsed and returned.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TChar& aCharacter: inout: Parsed character
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetChar( const TDesC& aTag, TChar& aCharacter )
+    {
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+
+    iItemSkipAndMarkPos = 0;
+    TInt ret = ParseStartAndEndPos( iItemLineSection, aTag, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = startPos + 1;
+
+    // Take character
+    aCharacter = iItemLineSection[startPos];
+
+    // Indicator that GetChar has been used
+    iGetMethodsIndicator = ETrue;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetNextChar
+
+    Description: Get a next character.
+
+    Get next character and returns it.
+    GetString or GetInt or GetChar must be called before call GetNextChar
+    method.
+
+    Parameters: TChar& aCharacter: inout: Parsed character
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetNextChar( TChar& aCharacter )
+    {
+    // GetString(), GetInt() or GetChar() is not called
+    if ( !iGetMethodsIndicator )
+        {
+        return KErrNotReady;
+        }
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+    TInt ret = ParseStartAndEndPos( iItemLineSection, KNullDesC, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = startPos + 1;
+
+    // Take character
+    aCharacter = iItemLineSection[startPos];
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: GetNextChar
+
+    Description: Get a next character with tag.
+
+    Get next character with tag until separator cut the parsing. If start tag
+    is empty the next character will be parsed and returned.
+    GetString or GetInt or GetChar must be called before call GetNextChar
+    method.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TChar& aCharacter: inout: Parsed character
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::GetNextChar( const TDesC& aTag,
+                                            TChar& aCharacter )
+    {
+    // GetString(), GetInt() or GetChar() is not called
+    if ( !iGetMethodsIndicator )
+        {
+        return KErrNotReady;
+        }
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    TInt extraEndPos( 0 );
+    TInt ret = ParseStartAndEndPos( iItemLineSection, aTag, startPos,
+                                    endPos, length, extraEndPos );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    // Current position for forward parsing operations
+    iItemSkipAndMarkPos = startPos + 1;
+
+    // Take character
+    aCharacter = iItemLineSection[startPos];
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: Remainder
+
+    Description: Get remaining strings in parsed line.
+                 
+                 Note: This method does not support the quote(TParsingType)
+                 feature, only GetString and GetNextString methods include
+                 support.
+
+    Parameters: TPtrC& aString: inout: Parsed string
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::Remainder( TPtrC& aString )
+    {
+    
+    if ( 0 == iItemLineSection.Length() )
+        {
+        // Probably parsering is failed
+        return KErrNotFound;
+        }
+
+    if( iItemLineSection.Length() <= iItemSkipAndMarkPos )
+        {
+        // Nothing to parse, check here to avoid lex's crash
+        return KErrNotFound;
+        }
+
+    // Skip space
+    TLex lex( iItemLineSection );
+    lex.SkipAndMark( iItemSkipAndMarkPos );
+    lex.SkipSpace();
+    
+    if( lex.Eos() )
+        {
+        // Remaining are only spaces. To avoid Set()'s panic
+        return KErrNotFound;
+        }
+
+    // Take string
+    aString.Set( (TUint16*)&iItemLineSection[ lex.Offset() ], 
+                 iItemLineSection.Length() - lex.Offset() );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: SetParsingType
+
+    Description: Parsing type can be given when parsing string(GetString and
+                 GetNextString). Please see TParsingType enumeration for more
+                 inforamtion.
+
+    Parameters: CStifItemParser::TParsingType aType: in: Sets a parsing type.
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifItemParser::SetParsingType( 
+                                    CStifItemParser::TParsingType aType )
+    {
+    iParsingType = aType;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifItemParser
+
+    Method: ParsingType
+
+    Description: Get current parsing type. Please see TParsingType enumeration
+                 for more inforamtion.
+
+    Parameters: None
+
+    Return Values: CStifItemParser::TParsingType: Current parsing type.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifItemParser::TParsingType CStifItemParser::ParsingType()
+    {
+    return iParsingType;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Parser/src/StifParser.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,891 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CStifParser 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "StifParser.h"
+#include "ParserTracing.h"
+#include "StifFileParser.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: CStifParser
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: TCommentType aCommentType: in: Comment type's indication
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CStifParser::CStifParser( TCommentType aCommentType ) :
+    iBuffer( 0, 0 )
+    {
+    iCommentType = aCommentType;
+
+    iParsingMode = EFileParsing;
+
+    iIsUnicode = EFalse;
+    
+    iFileParser = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Connecting and opening configuration file if path and file information is 
+    given. If path and file information is not given and information is given 
+    in buffer then create parser according to the buffer.
+    
+    Parameters: const TDesC& aPath: in: Source path definition
+                const TDesC& aConfig: in: Configuration filename
+                const TDesC& aBuffer: in: Buffer of the parsed information
+
+    Return Values: None
+
+    Errors/Exceptions:  Leaves if called Connect method fails
+                        Leaves if called SetSessionPath method fails
+                        Leaves if called Open method fails
+                        Leaves if HBufC::NewL operation leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifParser::ConstructL( const TDesC& aPath,
+                                const TDesC& aConfig,
+                                const TDesC& aBuffer)
+    {
+    if( aPath == KNullDesC && aConfig == KNullDesC && aBuffer != KNullDesC )
+        {
+        // Set mode
+        iParsingMode = EBufferParsing;
+
+        // Construct modifiable heap-based descriptor.
+        iBufferTmp = HBufC::NewL( aBuffer.Length() );
+        //iBuffer = iBufferTmp->Des();
+        iBuffer.Set( iBufferTmp->Des() );
+        // Copy content
+        iBuffer.Copy( aBuffer );
+        }
+
+    else
+        {
+        User::LeaveIfError( iFileServer.Connect() );
+    
+        __TRACE( KInfo, ( _L( "STIFPARSER: Open configfile '%S%S'" ),
+                &aPath, &aConfig ) );
+                
+        User::LeaveIfError( iFileServer.SetSessionPath( aPath ) );
+        User::LeaveIfError( iFile.Open( 
+                            iFileServer, aConfig, EFileRead | EFileShareAny ) );
+
+        //Check whether the file is unicoded
+        __TRACE(KInfo, (_L("STIFPARSER: Check if the file is unicode")));
+        _LIT(KUnicode, "#UNICODE");
+        const TInt KUnicodeLength(8 * 2 + 2); //times two, because we want to read unicode string using 8bit descriptor
+                                              //two characters more because on some systems FEFF is always added on the beginning of unicode file
+        TInt size(0);
+
+        User::LeaveIfError(iFile.Size(size));
+
+        if(size >= KUnicodeLength)
+            {
+            TBuf8<KUnicodeLength> buf;
+
+            User::LeaveIfError(iFile.Read(0, buf));
+            TPtrC16 bufuni((TUint16 *)(buf.Ptr()), buf.Length() / 2);
+            if(bufuni.Find(KUnicode) != KErrNotFound)
+                {
+                iIsUnicode = ETrue;
+                __TRACE(KInfo, (_L("STIFPARSER: File is unicode")));
+                }
+            }
+        
+        //Create file parser object
+        iFileParser = CStifFileParser::NewL(iFileServer, iFile, iIsUnicode, iCommentType);
+        }
+
+    iOffset = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Starting creating parser with path and file information.
+
+    Parameters: const TDesC& aPath: in: Source path definition
+                const TDesC& aConfig: in: Configuration filename
+                TCommentType aCommentType: in: Comment type's indication
+
+    Return Values: CStifParser* : pointer to CStifParser object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifParser* CStifParser::NewL( const TDesC& aPath,
+                                            const TDesC& aConfig,
+                                            TCommentType aCommentType )
+    {
+    __TRACE( KInfo, ( _L( "STIFPARSER: Debug information is used" ) ) );
+
+    // Create CStifParser object
+    CStifParser* parser = new (ELeave) CStifParser( aCommentType );
+
+    CleanupStack::PushL( parser );
+    parser->ConstructL( aPath, aConfig );
+    CleanupStack::Pop( parser );
+
+    return parser;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Starting creating parser with buffer information.
+
+    Parameters: const TDesC& aBuffer: in: Buffer of the parsed informations
+                TCommentType aCommentType: in: Comment type's indication
+
+    Return Values: CStifParser* : pointer to CStifParser object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifParser* CStifParser::NewL( const TDesC& aBuffer,
+                                            TCommentType aCommentType )
+    {
+    __TRACE( KInfo, ( _L( "STIFPARSER: Debug information is used" ) ) );
+
+    // Create CStifParser object
+    CStifParser* parser = new (ELeave) CStifParser( aCommentType );
+
+    CleanupStack::PushL( parser );
+    // No path and file name informations. Buffer is given
+    parser->ConstructL( KNullDesC, KNullDesC, aBuffer );
+    CleanupStack::Pop( parser );
+
+    return parser;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: ~CStifParser
+
+    Description: Destructor
+
+    Close file and the fileserver handles.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/    
+EXPORT_C CStifParser::~CStifParser()
+    {
+
+    if( iParsingMode == EBufferParsing )
+        {
+        delete iBufferTmp;
+        }
+    else
+        {
+        delete iFileParser;
+        iFile.Close();
+        iFileServer.Close();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: SectionL
+
+    Description: Parses sections from configuration files.
+
+    Open and read configuration source and parses a required section.
+    If start tag is empty the parsing starts beginning of the configuration
+    file. If end tag is empty the parsing goes end of configuration file.
+    This method starts always from beginning of configuration file and parses
+    first section if aSeeked parameters is not given.
+    If configuration file includes several sections with both start and end
+    tags so aSeeked parameter seeks the required section. The aSeeked
+    parameters indicates section that will be parsed.
+
+    Parameters: const TDesC& aStartTag: in: Indicates a start tag for parsing
+                const TDesC& aEndTag: in: Indicates an end tag for parsing
+                TInt aSeeked: in: a seeked section which will be parsed
+
+    Return Values:  See NextSectionL() method
+
+    Errors/Exceptions:  See NextSectionL() method
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifSectionParser* CStifParser::SectionL( const TDesC& aStartTag,
+                                                    const TDesC& aEndTag,
+                                                    TInt aSeeked )
+    {
+    iOffset = 0;
+    return NextSectionL( aStartTag, aEndTag, aSeeked );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: NextSectionL
+
+    Description: Parses sections from configuration files.
+
+    Open and read configuration source and parses a required section.
+    If start tag is empty the parsing starts beginning of the configuration
+    file. If end tag is empty the parsing goes end of configuration file.
+    This method will parse next section after the earlier section if aSeeked
+    parameter is not given.
+    If configuration file includes several sections with both start and end
+    tags so aSeeked parameter seeks the required section. The aSeeked
+    parameters indicates section that will be parsed.
+
+    Parameters: const TDesC& aStartTag: in: Indicates a start tag for parsing
+                const TDesC& aEndTag: in: Indicates an end tag for parsing
+                TInt aSeeked: in: a seeked section which will be parsed
+
+    Return Values:  CStifSectionParser* : pointer to CStifSectionParser object
+                    NULL will return if NextSectionFileL (or NextSectionMemoryL) returns NULL
+
+    Errors/Exceptions:  Leaves if NextSectionFileL leaves
+                        Leaves if NextSectionMemoryL leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifSectionParser* CStifParser::NextSectionL( const TDesC& aStartTag,
+                                                        const TDesC& aEndTag,
+                                                        TInt aSeeked )
+    {
+	//If parsing mode is set to file, we parse directly in the file
+	if(iParsingMode == EFileParsing)
+		{
+		return NextSectionFileL(aStartTag, aEndTag, aSeeked);
+		}
+
+	//If parsing mode is set to buffer, process in old way
+    return NextSectionMemoryL(aStartTag, aEndTag, aSeeked);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: NextSectionMemoryL
+
+    Description: Parses sections from configuration files.
+
+    Open and read configuration source and parses a required section.
+    If start tag is empty the parsing starts beginning of the configuration
+    file. If end tag is empty the parsing goes end of configuration file.
+    This method will parse next section after the earlier section if aSeeked
+    parameter is not given.
+    If configuration file includes several sections with both start and end
+    tags so aSeeked parameter seeks the required section. The aSeeked
+    parameters indicates section that will be parsed.
+
+    Parameters: const TDesC& aStartTag: in: Indicates a start tag for parsing
+                const TDesC& aEndTag: in: Indicates an end tag for parsing
+                TInt aSeeked: in: a seeked section which will be parsed
+
+    Return Values:  CStifSectionParser* : pointer to CStifSectionParser object
+                    NULL will return if file size or aSeeked is not positive
+                    NULL will return if start tag is not found
+                    NULL will return if end tag is not found
+                    NULL will return if parsed section length is not positive
+
+    Errors/Exceptions:  Leaves if called Size method fails
+                        Leaves if HBufC::NewLC method leaves
+                        Leaves if called Read method fails
+                        Leaves if CStifSectionParser::NewL methods leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CStifSectionParser* CStifParser::NextSectionMemoryL( const TDesC& aStartTag,
+                                                 	 const TDesC& aEndTag,
+                                                     TInt aSeeked )
+    {
+    TInt size( 0 );
+    // Parser is created straight with data
+    if( iParsingMode == EBufferParsing )
+        {
+        size = iBuffer.Length();
+        }
+    // Parser is created with path and file informations
+    else
+        {
+        User::LeaveIfError( iFile.Size( size ) );
+        }
+
+    // size or aSeeked cannot be 0 or negetive
+    if( size <= 0 || aSeeked <= 0)
+        {
+        __TRACE(
+            KInfo, ( _L( "STIFPARSER: NextSectionL method returns a NULL" ) ) );
+        return NULL;
+        }
+
+    const TInt tmpSize = 128;//--UNICODE-- KMaxName; // 128 - set to even value, because KMaxName may change in the future
+    TInt offset( 0 ); // Offset value to parts reading
+
+    // Construct modifiable heap-based descriptor. tmp to CleanupStack
+    HBufC* tmp = HBufC::NewLC( size );
+    TPtr wholeSection = tmp->Des();
+
+    // Construct modifiable heap-based descriptor. tmp2 to CleanupStack
+    HBufC8* tmp2 = HBufC8::NewLC( tmpSize );    // 128
+    TPtr8 buf = tmp2->Des();
+
+    // Construct modifiable heap-based descriptor. tmp3 to CleanupStack
+    HBufC* tmp3 = HBufC::NewLC( tmpSize );      // 128
+    TPtr currentSection = tmp3->Des();
+
+    // Parser is created straight with data
+    if( iParsingMode == EBufferParsing )
+        {
+        // If 8 bit copy changes to 16
+        wholeSection.Copy( iBuffer );
+        }
+    // Parser is created with path and file informations
+    else
+        {
+        TPtrC16 currentSectionUnicode;
+        do // Read data in parts(Maximum part size is KMaxName)
+            {
+            // Read data
+            User::LeaveIfError( iFile.Read( offset, buf, tmpSize ) );
+
+            // If file is unicode convert differently
+            if(iIsUnicode)
+                {
+                // 8 bit to 16 with unicode conversion - simply point to byte array as to double-byte array
+                currentSectionUnicode.Set((TUint16 *)(buf.Ptr()), buf.Length() / 2);
+                // Appends current section to whole section
+                wholeSection.Append( currentSectionUnicode );
+                }
+            else
+                {
+                // 8 bit to 16
+                currentSection.Copy( buf );
+                // Appends current section to whole section
+                wholeSection.Append( currentSection );
+                }
+
+            offset += tmpSize;
+
+            } while( offset < size );
+        }
+
+    CleanupStack::PopAndDestroy( tmp3 );
+    CleanupStack::PopAndDestroy( tmp2 );
+
+    // User wants section without c-style comments
+    if( iCommentType == ECStyleComments )
+        {
+        ParseCommentsOff( wholeSection );
+        }
+
+    TLex lex( wholeSection );
+    lex.SkipAndMark( iOffset );
+
+    // For the required section length and positions
+    TInt length( 0 );
+    TInt lengthStartPos( 0 );
+    TInt lengthEndPos( 0 );
+    TBool eos( EFalse );
+    TInt tagCount( 1 );
+
+    // Check is aStartTag given
+    if ( aStartTag.Length() == 0 )
+        {
+        // Skip line break, tabs, spaces etc.
+        lex.SkipSpace();
+        lengthStartPos = lex.Offset();
+        }
+    else
+        {
+        // While end of section
+        while ( !lex.Eos() )
+            {
+            TPtrC ptr = lex.NextToken();
+            // Start of the section is found and correct section
+            if ( ptr == aStartTag && tagCount == aSeeked )
+                {
+                lengthStartPos = lex.Offset();
+                break;
+                }
+            // Start tag is found but not correct section
+            else if ( ptr == aStartTag )
+                {
+                tagCount++;
+                }
+            }
+        }
+
+    // If we are end of section lex.Eos() and eos will be ETrue
+    eos = lex.Eos();
+
+    // Seeked section is not found
+    if ( tagCount != aSeeked )
+        {
+        __TRACE( KInfo, ( _L(
+            "STIFPARSER: NextSectionL method: Seeked section is not found" ) ) );
+        CleanupStack::PopAndDestroy( tmp );
+        User::Leave( KErrNotFound );
+        }
+
+    // Check is aEndTag given
+    if ( aEndTag.Length() == 0 )
+        {
+        lengthEndPos = wholeSection.Length();
+        }
+    else
+        {
+        // While end of section
+        while ( !lex.Eos() )
+            {
+            TPtrC ptr = lex.NextToken();
+            // End tag of the section is found
+            if ( ptr == aEndTag )
+                {
+                lengthEndPos = lex.Offset();
+                // Because Offset() position is after the aEndTag
+                lengthEndPos -= aEndTag.Length();
+                break;
+                }
+            }
+        }
+
+    // If we are end of section and lengthEndPos is 0
+    if ( lengthEndPos == 0 )
+        {
+        // lex.Eos() and eos will be ETrue
+        eos = lex.Eos();
+        }
+
+    // The length includes spaces and end of lines
+    length = ( lengthEndPos - lengthStartPos );
+
+    CStifSectionParser* section = NULL;
+
+    // If eos is true or length is negative
+    if ( eos || length <= 0  )
+        {
+        __TRACE(
+            KInfo, ( _L( "STIFPARSER: NextSectionL method returns a NULL" ) ) );
+        }
+    else
+        {
+        // Make CStifSectionParser object and alloc required length
+        section = CStifSectionParser::NewL( length );
+        CleanupStack::PushL( section );
+
+        // Copy required data to the section object
+        section->SetData( wholeSection, lengthStartPos, length );
+
+        //iOffset += lengthEndPos + aEndTag.Length();
+        iOffset = lex.Offset();
+
+        CleanupStack::Pop( section );
+        }
+    CleanupStack::PopAndDestroy( tmp );
+
+    return section;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: NextSectionFileL
+
+    Description: Parses sections from configuration files.
+
+    Open and read configuration source and parses a required section.
+    If start tag is empty the parsing starts beginning of the configuration
+    file. If end tag is empty the parsing goes end of configuration file.
+    This method will parse next section after the earlier section if aSeeked
+    parameter is not given.
+    If configuration file includes several sections with both start and end
+    tags so aSeeked parameter seeks the required section. The aSeeked
+    parameters indicates section that will be parsed.
+
+    Parameters: const TDesC& aStartTag: in: Indicates a start tag for parsing
+                const TDesC& aEndTag: in: Indicates an end tag for parsing
+                TInt aSeeked: in: a seeked section which will be parsed
+
+    Return Values:  CStifSectionParser* : pointer to CStifSectionParser object
+                    NULL will return if file size or aSeeked is not positive
+                    NULL will return if start tag is not found
+                    NULL will return if end tag is not found
+                    NULL will return if parsed section length is not positive
+
+    Errors/Exceptions:  Leaves if called Size method fails
+                        Leaves if HBufC::NewLC method leaves
+                        Leaves if called Read method fails
+                        Leaves if CStifSectionParser::NewL methods leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CStifSectionParser* CStifParser::NextSectionFileL( const TDesC& aStartTag,
+                                                   const TDesC& aEndTag,
+                                                   TInt aSeeked )
+    {
+	HBufC *bufSection = iFileParser->NextSectionL(aStartTag, aEndTag, iOffset, aSeeked);
+
+	if(bufSection)
+		{
+		CleanupStack::PushL(bufSection);
+		TPtr bufSectionPtr(bufSection->Des());
+
+		if(iCommentType == ECStyleComments)
+			{
+			ParseCommentsOff(bufSectionPtr);
+			}
+
+		// Make CStifSectionParser object and alloc required length
+		CStifSectionParser* section = CStifSectionParser::NewL(bufSection->Length());
+		CleanupStack::PushL(section);
+
+		// Copy required data to the section object
+		section->SetData(bufSectionPtr, 0, bufSection->Length());
+
+		// Clean
+		CleanupStack::Pop(section);
+		CleanupStack::PopAndDestroy(bufSection);
+
+		return section;
+		}
+
+	return NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifParser
+
+    Method: ParseCommentsOff
+
+    Description: Convert a section without comments.
+
+    Parameters: TPtr& aBuf: inout: section to parsed
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CStifParser::ParseCommentsOff( TPtr& aBuf )
+    {
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+    enum TSearchType
+        {
+        ENormalSearch,          // Search a '//' or a '/*'
+        ECStyleSlashs,          // Search is '//'
+        ECStyleSlashAndAsterisk,// Search is '/*'
+        EDoRemove,              // Remove comment
+        };
+
+    TSearchType searchType( ENormalSearch );
+
+    TLex lex( aBuf );
+
+    // Remove comments
+    do
+        {
+        switch( searchType )
+            {
+            case ENormalSearch:
+                {
+                if( lex.Get() == '/' )
+                    {
+                    // Peek next character( '/' )
+                    if( lex.Peek() == '/' )
+                        {
+                        startPos = lex.Offset();
+                        startPos--;
+                        lex.Inc();
+                        searchType = ECStyleSlashs;
+                        }
+                    // Peek next character( '*' )
+                    else if( lex.Peek() == '*' )
+                        {
+                        startPos = lex.Offset();
+                        startPos--;
+                        lex.Inc();
+                        searchType = ECStyleSlashAndAsterisk;
+                        }
+                    }
+                break;
+                }
+            case ECStyleSlashs:
+                {
+                // Peek next character(10 or '\n' in UNIX style )
+                if( lex.Peek() == 0x0A )
+                    {
+                    // Don't remove line break!!( Else this fails:
+                    // 1st line:"this is parsed text 1"
+                    // 2nd line:"this is parsed text 2 // this is comments"
+                    // 1st and 2nd lines will be together and following
+                    // operations may fail)
+                    endPos = lex.Offset();
+                    searchType = EDoRemove;
+                    break;
+                    }
+
+                // Peek next character(13 or '\r' in Symbian OS)
+                if ( lex.Peek() == 0x0D )
+                    {
+                    // Increment the lex position
+                    lex.Inc();
+                    // Peek next character(10 or '\n' in Symbian OS)
+                    if ( lex.Peek() == 0x0A )
+                        {
+                        // Don't remove line break!!( Else this fails:
+                        // 1st line:"this is parsed text 1"
+                        // 2nd line:"this is parsed text 2 // this is comments"
+                        // 1st and 2nd lines will be together and following
+                        // operations may fail)
+                        endPos = lex.Offset();
+                        endPos = endPos - 1; // Two line break characters
+                        searchType = EDoRemove;
+                        break;
+                        }
+                    // 0x0A not found, decrement position
+                    lex.UnGet();
+                    }
+                // Increment the lex position
+                lex.Inc();
+                // Take current end position
+                endPos = lex.Offset();
+                break;
+                }
+
+            case ECStyleSlashAndAsterisk:
+                {
+                // Peek next character( '*' )
+                if ( lex.Peek() == '*' )
+                    {
+                    // Increment the lex position
+                    lex.Inc();
+                    // Peek next character( '/')
+                    if ( lex.Peek() == '/' )
+                        {
+                        // End of the section is found and increment the lex position
+                        lex.Inc();
+                        endPos = lex.Offset();
+                        searchType = EDoRemove;
+                        break;
+                        }
+                    // '/' not found, decrement position
+                    lex.UnGet();
+                    }
+                // Increment the lex position
+                lex.Inc();
+
+                // Take current end position
+                endPos = lex.Offset();
+                break;
+                }
+            default:
+                {
+                searchType = ENormalSearch;
+                break;
+                }
+
+            } // End of switch
+
+            // Remove comment
+            if( searchType == EDoRemove )
+                {
+                length = endPos - startPos;
+                aBuf.Delete( startPos, length );
+                lex = aBuf;
+                searchType = ENormalSearch;
+                }
+
+        } while ( !lex.Eos() );
+
+    // If comment is started and configure file ends to eof we remove
+    // comments althougt there are no end of line or '*/' characters
+    if( searchType == ECStyleSlashs || searchType == ECStyleSlashs )
+        {
+        length = lex.Offset() - startPos;
+        aBuf.Delete( startPos, length );
+        }
+
+    HandleSpecialMarks( aBuf );
+
+    }
+
+//
+//-----------------------------------------------------------------------------
+//
+//    Class: CStifParser
+//
+//    Method: HandleSpecialMarks
+//
+//    Description: Handles special marks.( '\/' and '\*' ). This
+//         		   is used when ECStyleComments comment type is used.
+//
+//    Parameters: TPtr& aBuf: inout: section to parsed
+//
+//    Return Values: None
+//
+//    Errors/Exceptions: None
+//
+//    Status: Proposal
+//
+//-----------------------------------------------------------------------------
+//
+void CStifParser::HandleSpecialMarks( TPtr& aBuf )
+    {
+    TLex lex( aBuf );
+    TInt firstPos( 0 );
+    
+    //        Replace \/ with /
+    //        Replace \* with *
+    
+    do
+        {
+        //RDebug::Print( _L("Print : %S"), &aBuf );
+        firstPos = lex.Offset();
+        TChar get = lex.Get();
+        // Check is '\'
+        if( get == '\\' ) 
+            {
+            firstPos = (lex.Offset()-1);
+            // Peek next character( '/' or '*' )
+            if( lex.Peek() == '/' || lex.Peek() == '*')
+                {
+                aBuf.Delete (firstPos,1);
+                lex = aBuf;
+                }
+            }
+           
+        firstPos = 0;
+        } while ( !lex.Eos() );
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/Parser/src/StifSectionParser.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1107 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CStifSectionParser class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include "StifSectionParser.h"
+#include "ParserTracing.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: CStifSectionParser
+
+    Description: Default constructor.
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: const TInt aLength: in: Parsed section length
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifSectionParser::CStifSectionParser( const TInt aLength ) :
+    iSection( 0, 0 ),
+    iLength( aLength ),
+    iSkipAndMarkPos( 0 ),
+    iLineIndicator( EFalse )
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor.
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions:  Leaves if iLength is negative
+                        Leaves if called NewL method fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CStifSectionParser::ConstructL()
+    {
+    // Construct modifiable heap-based descriptor
+    iHBufferSection = HBufC::NewL( iLength );
+    iSection.Set(iHBufferSection->Des());
+
+    iSubOffset = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: const TInt aLength: in: Parsed section length
+
+    Return Values: CStifSectionParser* : pointer to CStifSectionParser object
+
+    Errors/Exceptions:  Leaves if section length is negative
+                        Leaves if construction fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifSectionParser* CStifSectionParser::NewL( const TInt aLength )
+    {
+    __TRACE( KInfo, ( _L( "STIFPARSER: Create a section" ) ) );
+    __ASSERT_ALWAYS( aLength > 0, User::Leave( KErrArgument ) );
+
+    CStifSectionParser* item = new (ELeave) CStifSectionParser( aLength );
+
+    CleanupStack::PushL( item );
+    item->ConstructL();
+    CleanupStack::Pop( item );
+
+    return item;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: ~CStifSectionParser
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/    
+CStifSectionParser::~CStifSectionParser()
+    {
+    __TRACE( KInfo, ( _L( "STIFPARSER: Call destructor '~CStifSectionParser'" ) ) );
+
+    delete iHBufferSection;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: ParseStartAndEndPos
+
+    Description: Start and end position parser.
+
+    Parameters: TPtrC aSection: in: Parsed section
+                const TDesC& aStartTag: in: Start tag of parsing
+                TTagToReturnValue aTagIndicator: in: Will aStartTag included to
+                the returned values
+                TInt& aStartPos: inout: Start point of parsing
+                TInt& aEndPos: inout: End point of parsing
+                TInt& aLength: inout: Length of parsed section
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifSectionParser::ParseStartAndEndPos( TPtrC aSection,
+                                            const TDesC& aStartTag,
+                                            TTagToReturnValue aTagIndicator,
+                                            TInt& aStartPos,
+                                            TInt& aEndPos,
+                                            TInt& aLength )
+    {
+    TLex lex( aSection );
+    lex.SkipAndMark( iSkipAndMarkPos );
+
+    // Check is aStartTag given
+    if ( aStartTag.Length() == 0 )
+        {
+        // Skip line break, tabs, spaces etc.
+        lex.SkipSpace();
+        aStartPos = lex.Offset();
+        }
+    else
+        {
+        // While end of section and aStartTag is given
+        while ( !lex.Eos() )
+            {
+            lex.SkipSpace();
+            TPtrC line = SubstractLine( lex.Remainder() );
+            TInt tagStartPos = 0;
+            TInt tagEndPos = 0;
+            if ( FindTag( line, aStartTag, tagStartPos, tagEndPos ) == KErrNone )
+            	{
+            	if ( aTagIndicator == ETag )
+            		{
+            		aStartPos = lex.Offset();
+            		}
+            	else
+            		{
+            		aStartPos = lex.Offset() + tagEndPos;
+            		if ( line.Length() - tagEndPos == 0 )
+            			{
+            			return KErrNotFound;
+            			}
+            		}
+            	break;
+            	}
+                
+            GotoEndOfLine( lex );
+            }
+        }
+
+    // End tag parsing starts and if we are end of the section
+    if( lex.Eos() )
+        {
+        return KErrNotFound;
+        }
+
+    // "Delete" white spaces(includes line break) 
+    aEndPos = GotoEndOfLine( lex );
+    // Position where start next parsing.(End position, includes white spaces)
+    iSkipAndMarkPos = lex.Offset();
+    // The length includes spaces and end of lines
+    aLength = ( aEndPos - aStartPos );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: SubstractLine
+
+    Description: Substracts line from selected text
+
+    Parameters: TPtrC& aText: in: text.
+
+    Return Values: TPtrC: Substracted line.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TPtrC CStifSectionParser::SubstractLine( const TPtrC& aText )
+	{
+	TLex lex( aText );
+	
+	while( !lex.Eos() )
+		{
+		if ( lex.Get() == 0x0A ) // "\n" character. Unix style
+			{
+			break;
+			}		
+		}
+	
+	return aText.Left( lex.Offset() );
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: FindTag
+
+    Description: Searches for selected tag in text
+
+    Parameters: const TPtrC& aText: in: text,
+				const TPtrC& aTag: in: tag,
+				TInt& aStartPos: out: tag start position,
+				TInt& aEndPos: out: tag end position.
+
+    Return Values: TInt: KErrNone, if tag was found. KErrNotFound if it was not found. 
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifSectionParser::FindTag( const TDesC& aText, const TDesC& aTag, TInt& aStartPos, TInt& aEndPos ) {
+	TBool tagWithEqualChar = EFalse;
+
+	HBufC* tagBuf = NULL;
+	TRAPD( err, tagBuf = aTag.AllocL() );
+	if ( err != KErrNone )
+		{
+		return err;
+		}
+
+	RBuf tag( tagBuf );
+	tag.Trim();
+	if ( tag.Right( 1 ) == _L("=") )
+		{
+		tagWithEqualChar = ETrue;
+		tag.SetLength( tag.Length() - 1 );
+		}
+	
+	TLex lex(aText);
+	lex.SkipSpaceAndMark();
+	TInt startPos = lex.Offset();
+	TPtrC token = lex.NextToken(); 
+	
+	
+	if ( !tagWithEqualChar )
+		{
+		if ( token == tag )
+			{
+			aStartPos = startPos;
+			lex.SkipSpace();
+			aEndPos = lex.Offset();
+			tag.Close();
+			return KErrNone;
+			}
+		}
+	else
+		{
+		lex.UnGetToMark();
+		TPtrC remText = lex.Remainder();
+		if ( remText.Find( tag ) == 0 )
+			{
+			lex.SkipAndMark( tag.Length() );
+			lex.SkipSpaceAndMark();
+			if ( !lex.Eos() )
+				{
+				if ( lex.Get() == '=' )
+					{
+					aStartPos = startPos;
+					lex.SkipSpace();					
+					aEndPos = lex.Offset();
+					tag.Close();
+					return KErrNone;
+					}
+				}
+			}
+		}
+	
+	tag.Close();
+	return KErrNotFound;
+}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: GotoEndOfLine
+
+    Description: Goes end of the line.
+
+    Parameters: TLex& lex: inout: Parsed line.
+
+    Return Values: TInt: Last item's end position.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifSectionParser::GotoEndOfLine( TLex& lex )
+    {
+    // End position of the last token(Initialized with current position)
+    TInt lastItemPosition( lex.Offset() );
+
+    // LINE BREAK NOTE:
+    // Line break in SOS, WIN:  '\r\n'
+    // Line break in UNIX:      '\n'
+
+    do
+        {
+        // Peek next character(10 or '\n' in UNIX style )
+        if( lex.Peek() == 0x0A )
+            {
+            lex.Inc();
+            break;
+            }
+
+        // Peek next character(13 or '\r' in Symbian OS)
+        if ( lex.Peek() == 0x0D )
+            {
+            // Increment the lex position
+            lex.Inc();
+            // Peek next character(10 or '\n' in Symbian OS)
+            if ( lex.Peek() == 0x0A )
+                {
+                // End of the section is found and increment the lex position
+                lex.Inc();
+                break;
+                }
+            // 0x0A not found, decrement position
+            lex.UnGet();
+            }
+        // Peek for tabulator(0x09) and space(0x20)
+        else if ( lex.Peek() == 0x09 || lex.Peek() == 0x20 )
+            {
+            // Increment the lex position
+            lex.Inc();
+            continue;
+            }
+        
+        // If white spaces not found take next token
+        lex.NextToken();
+        lastItemPosition = lex.Offset();    
+        
+        } while ( !lex.Eos() );
+        
+    return lastItemPosition;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: GetItemLineL
+
+    Description: Parses a line for items parsing.
+
+    If start tag is empty the parsing starts beging of the section.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point.
+                TTagToReturnValue aTagIndicator: in: Will aTag included to the
+                returned object(For default the tag will be added)
+
+    Return Values:  CStifItemParser* : pointer to CStifItemParser object
+                    NULL will return if ParseStartAndEndPos() method returns -1
+                    NULL will return if length is 0 or negative
+                    NULL will return if iStartPos is 0
+
+    Errors/Exceptions: Leaves if called CStifItemParser::NewL method fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifItemParser* CStifSectionParser::GetItemLineL( const TDesC& aTag,
+                                            TTagToReturnValue aTagIndicator )
+    {
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+
+    // Indicator that GetItemLineL has been used
+    iLineIndicator = ETrue;
+
+    iSkipAndMarkPos = 0;
+
+    TInt ret = ParseStartAndEndPos( iSection, aTag, aTagIndicator,
+                                    startPos, endPos, length );
+
+    // No parsing found
+    if ( KErrNone != ret || length <= 0 || startPos < 0 )
+        {
+        __TRACE( 
+            KInfo, ( _L( "STIFPARSER: GetItemLineL method returns a NULL" ) ) );
+        return NULL;
+        }
+
+    CStifItemParser* line = CStifItemParser::NewL(
+                                            iSection, startPos, length );
+
+    return line;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: GetNextItemLineL
+
+    Description: Parses a next line for items parsing.
+
+    Parameters: None
+
+    Return Values:  CStifItemParser* : pointer to CStifItemParser object
+                    NULL will return if iLineIndicator is false
+                    NULL will return if ParseStartAndEndPos() method returns -1
+                    NULL will return if length is 0 or negative
+                    NULL will return if iStartPos is 0
+
+    Errors/Exceptions: Leaves if called CStifItemParser::NewL method fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifItemParser* CStifSectionParser::GetNextItemLineL()
+    {
+    // GetLine() or GetItemLineL() method is not called
+    if ( !iLineIndicator )
+        {
+        __TRACE( KInfo, 
+            ( _L( "STIFPARSER: GetNextItemLineL method returns a NULL" ) ) );
+        return NULL;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+
+    // tagIndicator has no meaning in this method
+    TTagToReturnValue tagIndicator( ETag );
+
+    TInt ret = ParseStartAndEndPos( iSection, KNullDesC, tagIndicator,
+                                    startPos, endPos, length );
+
+    // No parsing found
+    if ( KErrNone != ret || length <= 0 || startPos < 0 )
+        {
+        __TRACE( KInfo, 
+            ( _L( "STIFPARSER: GetNextItemLineL method returns a NULL" ) ) );
+        return NULL;
+        }
+
+    CStifItemParser* line = CStifItemParser::NewL(
+                                            iSection, startPos, length );
+
+    return line;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: GetNextItemLineL
+
+    Description: Parses a next line for items parsing with a tag.
+
+    If start tag is empty the parsing starts beging of the section.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TTagToReturnValue aTagIndicator: in: Will aTag included to the
+                returned object(For default the tag will be added)
+
+    Return Values:  CStifItemParser* : pointer to CStifItemParser object
+                    NULL will return if iLineIndicator is false
+                    NULL will return if ParseStartAndEndPos() method returns -1
+                    NULL will return if length is 0 or negative
+                    NULL will return if iStartPos is 0
+
+    Errors/Exceptions: Leaves if called CStifItemParser::NewL method fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifItemParser* CStifSectionParser::GetNextItemLineL(
+                                            const TDesC& aTag,
+                                            TTagToReturnValue aTagIndicator )
+    {
+    // GetLine() or GetItemLineL() method is not called
+    if ( !iLineIndicator )
+        {
+        __TRACE( KInfo, 
+            ( _L( "STIFPARSER: GetNextItemLineL method returns a NULL" ) ) );
+        return NULL;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+
+    TInt ret = ParseStartAndEndPos( iSection, aTag, aTagIndicator,
+                                    startPos, endPos, length );
+    // No parsing found
+    if ( KErrNone != ret || length <= 0 || startPos < 0 )
+        {
+        __TRACE( KInfo, 
+            ( _L( "STIFPARSER: GetNextItemLineL method returns a NULL" )  ) );
+        return NULL;
+        }
+
+    CStifItemParser* line = CStifItemParser::NewL(
+                                            iSection, startPos, length );
+
+    return line;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: SubSectionL
+
+    Description: Parses sub sections from the main section.
+
+    If start tag is empty the parsing starts begin of the section.
+    If end tag is empty the parsing goes end of section.
+    This method starts always from beginning of parsed section and parses
+    first subsection if aSeeked parameters is not given.
+    If parsed section includes several subsections with both start and end
+    tags so aSeeked parameter seeks the required subsection. The aSeeked
+    parameters indicates subsection that will be parsed.
+
+    Parameters: const TDesC& aStartTag: in: Indicates parsing start point
+                const TDesC& aEndTag: in: Indicates parsing end point
+                TInt aSeeked: in: a seeked subsection which will be parsed
+
+    Return Values:  CStifItemParser* : pointer to CStifItemParser object
+                    NULL will return if end tag is not found
+                    NULL will return if length is 0 or negative
+                    NULL will return if lengthStart is 0
+
+    Errors/Exceptions: Leaves if called CStifSectionParser::NewL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifSectionParser* CStifSectionParser::SubSectionL( 
+                                                        const TDesC& aStartTag,
+                                                        const TDesC& aEndTag,
+                                                        TInt aSeeked )
+    {
+    
+    iSubOffset = 0;
+    return NextSubSectionL( aStartTag, aEndTag, aSeeked );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: SubSectionL
+
+    Description: Parses subsections from the main section.
+
+    If start tag is empty the parsing starts begin of the section.
+    If end tag is empty the parsing goes end of section.
+    This method will parse next subsection after the earlier subsection if
+    aSeeked parameter is not given.
+    If parser section includes several subsections with both start and end
+    tags so aSeeked parameter seeks the required subsection. The aSeeked
+    parameter indicates subsection that will be parsed.
+
+    Parameters: const TDesC& aStartTag: in: Indicates parsing start point
+                const TDesC& aEndTag: in: Indicates parsing end point
+                TInt aSeeked: in: a seeked subsection which will be parsed
+
+    Return Values:  CStifItemParser* : pointer to CStifItemParser object
+                    NULL will return if end tag is not found
+                    NULL will return if length is 0 or negative
+                    NULL will return if lengthStart is 0
+
+    Errors/Exceptions: Leaves if called CStifSectionParser::NewL method fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifSectionParser* CStifSectionParser::NextSubSectionL( 
+                                                    const TDesC& aStartTag,
+                                                    const TDesC& aEndTag,
+                                                    TInt aSeeked )
+    {
+    
+    TLex lex( iSection );
+
+    lex.SkipAndMark( iSubOffset );
+
+    // Get the required sub section length
+    TInt length( 0 );
+    TInt lengthStartPos( 0 );
+    TInt lengthEndPos( 0 );
+    TBool eos( EFalse );
+    TInt tagCount( 1 );
+
+    // Check is aStartTag given
+    if ( aStartTag.Length() == 0 )
+        {
+        // Skip line break, tabs, spaces etc.
+        lex.SkipSpace();
+        lengthStartPos = lex.Offset();
+        }
+    else
+        {
+        // While end of section and aStartTag is given
+        while ( !lex.Eos() )
+            {
+            TPtrC ptr = lex.NextToken();
+            // Start of the section is found and correct section
+            if ( ptr == aStartTag && tagCount == aSeeked )
+                {
+                // Start position
+                lengthStartPos = lex.Offset();
+                break;
+                }
+            // Start tag is found but not correct section
+            else if ( ptr == aStartTag )
+                {
+                tagCount++;
+                }
+            }
+        }
+
+    // If we are end of section lex.Eos() and eos will be ETrue
+    eos = lex.Eos();
+
+    // Seeked section is not found
+    if ( tagCount != aSeeked )
+        {
+        __TRACE( KInfo, ( _L( "STIFPARSER: NextSubSectionL method: Seeked subsection is not found" ) ) );
+        User::Leave( KErrNotFound );
+        }
+
+    // Check is aEndTag given
+    if ( aEndTag.Length() == 0 )
+        {
+        lengthEndPos = iSection.MaxLength();
+        }
+    else
+        {
+        // While end of section and aEndTag is given
+        while ( !lex.Eos() )
+            {
+            TPtrC ptr = lex.NextToken();
+            // End tag of the section is found
+            if ( ptr == aEndTag )
+                {
+                // End position
+                lengthEndPos = lex.Offset();
+                // Because Offset() position is after the aEndTag
+                lengthEndPos -= aEndTag.Length();
+                break;
+                }
+            }
+        }
+
+    // If we are end of section and lengthEndPos is 0
+    if ( lengthEndPos == 0 )
+        {
+        // lex.Eos() and eos will be ETrue
+        eos = lex.Eos();
+        }
+
+    // The length includes spaces and end of lines
+    length = ( lengthEndPos - lengthStartPos );
+
+    CStifSectionParser* section = NULL;
+
+    // If eos is true or length is negative
+    if ( eos || length <= 0  ) 
+        {
+        __TRACE( KInfo, 
+            ( _L( "STIFPARSER: SubSectionL method returns a NULL" ) ) );
+        }    
+    else
+        {
+        // Position where start next parsing.(End position,
+        // includes white spaces)
+        iSubOffset = lex.Offset();
+        
+        // Make CStifSectionParser object and alloc required length
+        section = CStifSectionParser::NewL( length );
+        CleanupStack::PushL( section );
+
+        // Copy required data to the section object
+        section->SetData( iSection, lengthStartPos, length );
+
+        CleanupStack::Pop( section );
+        }
+
+    return section;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: GetLine
+
+    Description: Get a line.
+
+    Search an item from the section and return rest of the line. If start tag 
+    is empty the parsing starts beging of the section.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TPtr& aLine: inout: Parsed line
+                TTagToReturnValue aTagIndicator: in: Will aTag included to the
+                returned value(For default the tag will be added)
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifSectionParser::GetLine( const TDesC& aTag,
+                                            TPtrC& aLine,
+                                            TTagToReturnValue aTagIndicator )
+    {
+    TInt ret( KErrNone );
+
+    if ( 0 == iSection.Length() )
+        {
+        return KErrNotFound;
+        }
+
+    // Indicator that GetLine has been used
+    iLineIndicator = ETrue;
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+
+    iSkipAndMarkPos = 0;
+
+    ret = ParseStartAndEndPos( iSection, aTag, aTagIndicator,
+                                startPos, endPos, length );
+
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    aLine.Set( &iSection[startPos], length );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: GetNextLine
+
+    Description: Get a line
+
+    Search an item from the section and return rest of the line.
+
+    Parameters: TPtr& aLine: inout: Parsed line
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifSectionParser::GetNextLine( TPtrC& aLine )
+    {
+    TInt ret( KErrNone );
+
+    // GetLine() or GetItemLineL() method is not called
+    if ( !iLineIndicator )
+        {
+        return KErrNotReady;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+
+    // tagIndicator has no meaning in this method
+    TTagToReturnValue tagIndicator( ETag );
+
+    ret = ParseStartAndEndPos( iSection, KNullDesC, tagIndicator,
+                                startPos, endPos, length );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    aLine.Set( &iSection[startPos], length );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: GetNextLine
+
+    Description: Get a line with tag
+
+    Search a next line with the required tag from the section. If start tag
+    is empty the parsing starts beging of the section.
+
+    Parameters: const TDesC& aTag: in: Indicates parsing start point
+                TPtr& aLine: inout: Parsed line
+                TTagToReturnValue aTagIndicator: in: Will aTag included to the
+                returned value(For default the tag will be added)
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifSectionParser::GetNextLine( const TDesC& aTag, TPtrC& aLine,
+                                            TTagToReturnValue aTagIndicator )
+    {
+    TInt ret( KErrNone );
+
+    // GetLine() or GetItemLineL() method is not called
+    if ( !iLineIndicator )
+        {
+        return KErrNotReady;
+        }
+
+    TInt startPos( 0 );
+    TInt endPos( 0 );
+    TInt length( 0 );
+
+    ret = ParseStartAndEndPos( iSection, aTag, aTagIndicator,
+                                startPos, endPos, length );
+    if ( KErrNone != ret )
+        {
+        // Nothing to parse
+        return ret;
+        }
+
+    aLine.Set( &iSection[startPos], length );
+
+    return KErrNone;
+
+    }
+
+ /*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: GetPosition
+
+    Description: Get current position.
+
+    Returns current parsing position, which
+    can be used as parameter for SetPosition afterwards to go back
+    to old parsing position.
+
+    Parameters: None
+    
+    Return Values: TInt: Current parsing position.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifSectionParser::GetPosition()
+    {
+    
+    return iSkipAndMarkPos;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: SetPosition
+
+    Description: Set current position.
+                
+    SetPosition can be used to set parsing position, e.g. to rewind 
+    back to some old position retrieved with GetPosition.
+    
+    Parameters: TInt aPos: in: new parsing position.
+    
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifSectionParser::SetPosition( TInt aPos )  
+    {
+    
+    if( aPos < 0 || aPos >= iSection.Length() )
+        {
+        return KErrArgument;
+        }
+        
+    iSkipAndMarkPos = aPos;    
+    
+    return KErrNone;
+    
+    }        
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: SetData
+
+    Description: Create a section.
+
+    Parameters: const TPtr aData: in: Data to be parsed
+                TInt aStartPos: in: Indicates parsing start position
+                TInt aLength: in: Indicates length of parsed section
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CStifSectionParser::SetData( TPtr aData,
+                                    TInt aStartPos,
+                                    TInt aLength )
+    {
+    iSection.Copy( aData.Mid( aStartPos, aLength ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifSectionParser
+
+    Method: Des
+
+    Description: Returns a section.
+
+    Parameters: None
+
+    Return Values: const TPtrC: Returns a current section
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+const TPtrC CStifSectionParser::Des()
+    {
+    return (TPtrC)iSection;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/SUEvent/Bmarm/SUEventu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	LibEntryL__Fv @ 1 NONAME R3UNUSED ; LibEntryL(void)
+	SetRequirements__FRP16CTestModuleParamRUl @ 2 NONAME R3UNUSED ; SetRequirements(CTestModuleParam *&, unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/SUEvent/Bwins/SUEventu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	?LibEntryL@@YAPAVCTestModuleBase@@XZ @ 1 NONAME ; class CTestModuleBase * __cdecl LibEntryL(void)
+	?SetRequirements@@YAHAAPAVCTestModuleParam@@AAK@Z @ 2 NONAME ; int __cdecl SetRequirements(class CTestModuleParam * &,unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/SUEvent/eabi/SUEventu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	_Z9LibEntryLv @ 1 NONAME
+	_Z15SetRequirementsRP16CTestModuleParamRm @ 2 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/SUEvent/group/SUEvent.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's remote events module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          SUEvent.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+
+//TARGETPATH      ?target_path
+DEFFILE         SUEvent.def
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          SUEvent.cpp
+SOURCE          SUEventCases.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// DEFFILE ?filename
+// AIF ?filename// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/SUEvent/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+PRJ_PLATFORMS
+// specify the platforms your component needs to be built for here
+// defaults to WINS MARM so you can ignore this if you just build these
+	
+	DEFAULT
+
+PRJ_TESTEXPORTS
+// NOTE: If using ARS requirements all export operations should be done under this.
+// 'abld test export'
+
+PRJ_EXPORTS
+// Specify the source file followed by its destination here
+// copy will be used to copy the source file to its destination
+// If there's no destination then the source file will be copied
+// to the same name in \epoc32\include
+// Example: 
+/*
+\agnmodel\inc\AGMCOMON.H
+*/
+
+PRJ_TESTMMPFILES
+// NOTE: If using ARS requirements .mmp file operation should be done under this.
+// 'abld test build'
+
+PRJ_MMPFILES
+// Specify the .mmp files required for building the important component
+// releasables.
+//
+// Specify "tidy" if the component you need to build doesn't need to be
+// released. Specify "ignore" if the MMP file exists but should be
+// ignored.
+// Example:
+/*
+\agnmodel\group\agnmodel.mmp
+#if defined(MARM)
+\agnmodel\group\agsvexe.mmp
+#endif
+*/
+	SUEvent.mmp
+
+//  End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/SUEvent/inc/SUEvent.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,317 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIF remote events module declaration
+*
+*/
+
+#ifndef SUEVENT_H
+#define SUEVENT_H
+
+// INCLUDES
+#include "StifTestModule.h"
+#include <StifLogger.h>
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// Logging path
+_LIT( KSUEventLogPath, "\\logs\\testframework\\SUEvent\\" ); 
+// Log file
+_LIT( KSUEventLogFile, "SUEvent.txt" ); 
+
+#define GETPTR &
+#define ENTRY(str,func) {_S(str), GETPTR func,0,0,0}
+#define FUNCENTRY(func) {_S(#func), GETPTR func,0,0,0}
+#define OOM_ENTRY(str,func,a,b,c) {_S(str), GETPTR func,a,b,c}
+#define OOM_FUNCENTRY(func,a,b,c) {_S(#func), GETPTR func,a,b,c}
+
+// FUNCTION PROTOTYPES
+//?type ?function_name(?arg_list);
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+class CSUEvent;
+
+// DATA TYPES
+//enum ?declaration
+//typedef ?declaration
+//extern ?data_type;
+// A typedef for function that does the actual testing,
+// function is a type 
+// TInt CSUEvent::<NameOfFunction> ( TTestResult& aResult )
+typedef TInt (CSUEvent::* TestFunction)(TTestResult&, const TFileName&);
+
+// CLASS DECLARATION
+
+/**
+*  An internal structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TCaseInfoInternal
+    {
+    public:
+        const TText*    iCaseName;
+        TestFunction    iMethod;
+        TBool           iIsOOMTest;
+        TInt            iFirstMemoryAllocation;
+        TInt            iLastMemoryAllocation;
+    };
+
+// CLASS DECLARATION
+
+/**
+*  A structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TCaseInfo
+    {
+    public:
+        TPtrC iCaseName;
+        TestFunction iMethod;
+        TBool           iIsOOMTest;
+        TInt            iFirstMemoryAllocation;
+        TInt            iLastMemoryAllocation;
+
+    TCaseInfo( const TText* a ) : iCaseName( (TText*) a )
+        {
+        };
+
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  This a SUEvent class.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS(CSUEvent) : public CTestModuleBase
+    {
+    public:  // Constructors and destructor
+
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSUEvent* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSUEvent();
+
+    public: // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * From CTestModuleBase InitL is used to initialize the 
+        *       SUEvent. It is called once for every instance of 
+        *       TestModuleSUEvent after its creation.
+        * @since ?Series60_version
+        * @param aIniFile Initialization file for the test module (optional)
+        * @param aFirstTime Flag is true when InitL is executed for first 
+        *               created instance of SUEvent.
+        * @return Symbian OS error code
+        */
+        TInt InitL( TFileName& aIniFile, TBool aFirstTime );
+
+        /**
+        * From CTestModuleBase GetTestCasesL is used to inquiry test cases 
+        *   from SUEvent. 
+        * @since ?Series60_version
+        * @param aTestCaseFile Test case file (optional)
+        * @param aTestCases  Array of TestCases returned to test framework
+        * @return Symbian OS error code
+        */
+        TInt GetTestCasesL( const TFileName& aTestCaseFile, 
+                            RPointerArray<TTestCaseInfo>& aTestCases );
+
+        /**
+        * From CTestModuleBase RunTestCaseL is used to run an individual 
+        *   test case. 
+        * @since ?Series60_version
+        * @param aCaseNumber Test case number
+        * @param aTestCaseFile Test case file (optional)
+        * @param aResult Test case result returned to test framework (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error, which is 
+        *           not reported in aResult parameter as test case failure).
+        */   
+        TInt RunTestCaseL( const TInt aCaseNumber, 
+                           const TFileName& aTestCaseFile,
+                           TTestResult& aResult );
+
+        /**
+        * From CTestModuleBase; OOMTestQueryL is used to specify is particular
+        * test case going to be executed using OOM conditions
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailureType OOM failure type (optional)
+        * @param aFirstMemFailure The first heap memory allocation failure value (optional)
+        * @param aLastMemFailure The last heap memory allocation failure value (optional)
+        * @return TBool
+        */
+        virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */, 
+                                     const TInt /* aCaseNumber */, 
+                                     TOOMFailureType& aFailureType, 
+                                     TInt& /* aFirstMemFailure */, 
+                                     TInt& /* aLastMemFailure */ );
+
+        /**
+        * From CTestModuleBase; OOMTestInitializeL may be used to initialize OOM
+        * test environment
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        */
+        virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */, 
+                                    const TInt /* aCaseNumber */ ); 
+
+        /**
+        * From CTestModuleBase; OOMHandleWarningL
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailNextValue FailNextValue for OOM test execution (optional)
+        * @return None
+        *
+        * User may add implementation for OOM test warning handling. Usually no
+        * implementation is required.           
+        */
+        virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
+                                        const TInt /* aCaseNumber */, 
+                                        TInt& /* aFailNextValue */); 
+
+        /**
+        * From CTestModuleBase; OOMTestFinalizeL may be used to finalize OOM
+        * test environment
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        *
+        */
+        virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */, 
+                                       const TInt /* aCaseNumber */ );
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CSUEvent();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+        /**
+        * Function returning test case name and pointer to test case function.
+        * @since ?Series60_version
+        * @param aCaseNumber test case number
+        * @return TCaseInfo 
+        */
+        const TCaseInfo Case ( const TInt aCaseNumber ) const;
+
+        /**
+        * Actual Hardcoded test case functions are listed below.
+        */
+
+        /**
+        * Printing test case.
+        * @since ?Series60_version
+        * @param aResult Test case result (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error 
+        *   that is not returned as test case result in aResult)
+        */
+		TInt SetEventState(TTestResult& aResult, const TFileName& aEventName);
+		TInt SetEventIndication(TTestResult& aResult, const TFileName& aEventName);
+		TInt UnsetEvent(TTestResult& aResult, const TFileName& aEventName);
+		TInt WaitEvent(TTestResult& aResult, const TFileName& aEventName);
+		TInt SetEventIndicationHard(TTestResult& aResult, const TFileName& /*aEventName*/);
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+        // Pointer to test (function) to be executed
+        TestFunction iMethod;
+
+        // Pointer to logger
+        CStifLogger * iLog; 
+
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+#endif      // SUEVENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/SUEvent/src/SUEvent.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,364 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains SUEvent implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "SUEvent.h"
+#include <e32svr.h>
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSUEvent::CSUEvent
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSUEvent::CSUEvent()
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::ConstructL
+// Symbian 2nd phase constructor can leave.
+//
+// Note: If OOM test case uses STIF Logger, then STIF Logger must be created
+// with static buffer size parameter (aStaticBufferSize). Otherwise Logger 
+// allocates memory from heap and therefore causes error situations with OOM 
+// testing. For more information about STIF Logger construction, see STIF Users 
+// Guide.
+// -----------------------------------------------------------------------------
+//
+void CSUEvent::ConstructL()
+    {
+    iLog = CStifLogger::NewL( KSUEventLogPath, 
+                          KSUEventLogFile);
+
+    // Sample how to use logging
+    _LIT( KLogStart, "SUEvent logging starts!" );
+    iLog->Log( KLogStart );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSUEvent* CSUEvent::NewL()
+    {
+    CSUEvent* self = new (ELeave) CSUEvent;
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+// Destructor
+CSUEvent::~CSUEvent()
+    {
+    delete iLog;
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::InitL
+// InitL is used to initialize the Test Module.
+// -----------------------------------------------------------------------------
+//
+TInt CSUEvent::InitL( 
+    TFileName& /*aIniFile*/, 
+    TBool /*aFirstTime*/ )
+    {
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::GetTestCasesL
+// GetTestCases is used to inquire test cases from the Test Module. Test
+// cases are stored to array of test cases. The Test Framework will be
+// the owner of the data in the RPointerArray after GetTestCases return
+// and it does the memory deallocation.
+// -----------------------------------------------------------------------------
+//
+TInt CSUEvent::GetTestCasesL(
+    const TFileName& /*aConfig*/,
+    RPointerArray<TTestCaseInfo>& aTestCases )
+    {
+
+    // Loop through all test cases and create new
+    // TTestCaseInfo items and append items to aTestCase array
+    for( TInt i = 0; Case(i).iMethod != NULL; i++ )
+        {
+
+        // Allocate new TTestCaseInfo from heap for a testcase definition.
+        TTestCaseInfo* newCase = new( ELeave ) TTestCaseInfo();
+
+        // PushL TTestCaseInfo to CleanupStack.
+        CleanupStack::PushL( newCase );
+
+        // Set number for the testcase.
+        // When the testcase is run, this comes as a parameter to RunTestCaseL.
+        newCase->iCaseNumber = i;
+
+        // Set title for the test case. This is shown in UI to user.
+        newCase->iTitle.Copy( Case(i).iCaseName );
+
+        // Append TTestCaseInfo to the testcase array. After appended 
+        // successfully the TTestCaseInfo object is owned (and freed) 
+        // by the TestServer. 
+        User::LeaveIfError(aTestCases.Append ( newCase ) );
+
+        // Pop TTestCaseInfo from the CleanupStack.
+        CleanupStack::Pop( newCase );
+
+        }
+
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::RunTestCaseL
+// RunTestCaseL is used to run an individual test case specified 
+// by aTestCase. Test cases that can be run may be requested from 
+// Test Module by GetTestCases method before calling RunTestCase.
+// -----------------------------------------------------------------------------
+//
+TInt CSUEvent::RunTestCaseL( 
+    const TInt aCaseNumber,
+    const TFileName& aConfig,
+    TTestResult& aResult )
+    {
+
+    // Return value
+    TInt execStatus = KErrNone;
+
+    // Get the pointer to test case function
+    TCaseInfo tmp = Case ( aCaseNumber );
+
+    _LIT( KLogStartTC, "Starting testcase [%S]" );
+    iLog->Log( KLogStartTC, &tmp.iCaseName);
+
+    // Check that case number was valid
+    if ( tmp.iMethod != NULL )
+        {
+        // Valid case was found, call it via function pointer
+        iMethod = tmp.iMethod;
+        execStatus  = ( this->*iMethod )( aResult, aConfig );
+        }
+    else
+        {
+        // Valid case was not found, return error.
+        execStatus = KErrNotFound;
+        }
+
+	RDebug::Print(_L(" CSUEvent::RunTestCaseL waiting"));
+
+	User::After(500000);
+	RDebug::Print(_L(" CSUEvent::RunTestCaseL running"));
+    // Return case execution status (not the result of the case execution)
+    return execStatus;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::OOMTestQueryL
+// Used to check if a particular test case should be run in OOM conditions and 
+// which memory allocations should fail.    
+// -----------------------------------------------------------------------------
+//
+TBool CSUEvent::OOMTestQueryL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt aCaseNumber, 
+                                TOOMFailureType& /* aFailureType */, 
+                                TInt& aFirstMemFailure, 
+                                TInt& aLastMemFailure ) 
+    {
+    _LIT( KLogOOMTestQueryL, "CSUEvent::OOMTestQueryL" );
+    iLog->Log( KLogOOMTestQueryL );     
+
+    aFirstMemFailure = Case( aCaseNumber ).iFirstMemoryAllocation;
+    aLastMemFailure = Case( aCaseNumber ).iLastMemoryAllocation;
+
+    return Case( aCaseNumber ).iIsOOMTest;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::OOMTestInitializeL
+// Used to perform the test environment setup for a particular OOM test case. 
+// Test Modules may use the initialization file to read parameters for Test 
+// Module initialization but they can also have their own configure file or 
+// some other routine to initialize themselves.  
+//
+// NOTE: User may add implementation for OOM test environment initialization.
+// Usually no implementation is required.
+// -----------------------------------------------------------------------------
+//
+void CSUEvent::OOMTestInitializeL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt /* aCaseNumber */ )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::OOMHandleWarningL
+// In some cases the heap memory allocation should be skipped, either due to
+// problems in the OS code or components used by the code being tested, or even 
+// inside the tested components which are implemented this way on purpose (by 
+// design), so it is important to give the tester a way to bypass allocation 
+// failures.
+//
+// NOTE: User may add implementation for OOM test warning handling. Usually no
+// implementation is required.
+// -----------------------------------------------------------------------------
+//
+void CSUEvent::OOMHandleWarningL( 
+                                const TFileName& /* aTestCaseFile */,
+                                const TInt /* aCaseNumber */, 
+                                TInt& /* aFailNextValue */ )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CSUEvent::OOMTestFinalizeL
+// Used to perform the test environment cleanup for a particular OOM test case.
+//
+// NOTE: User may add implementation for OOM test environment finalization.
+// Usually no implementation is required.
+// -----------------------------------------------------------------------------
+//
+void CSUEvent::OOMTestFinalizeL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt /* aCaseNumber */ )
+    {
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point
+// Returns: CTestModuleBase*: Pointer to Test Module object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CTestModuleBase* LibEntryL()
+    {
+    return CSUEvent::NewL();
+
+    }
+
+// -----------------------------------------------------------------------------
+// SetRequirements handles test module parameters(implements evolution
+// version 1 for test module's heap and stack sizes configuring).
+// Returns: TInt: Symbian error code.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt SetRequirements( CTestModuleParam*& /*aTestModuleParam*/, 
+                                TUint32& /*aParameterValid*/ )
+    {
+
+    /* --------------------------------- NOTE ---------------------------------
+    USER PANICS occurs in test thread creation when:
+    1) "The panic occurs when the value of the stack size is negative."
+    2) "The panic occurs if the minimum heap size specified is less
+       than KMinHeapSize".
+       KMinHeapSize: "Functions that require a new heap to be allocated will
+       either panic, or will reset the required heap size to this value if
+       a smaller heap size is specified".
+    3) "The panic occurs if the minimum heap size specified is greater than
+       the maximum size to which the heap can grow".
+    Other:
+    1) Make sure that your hardware or Symbian OS is supporting given sizes.
+       e.g. Hardware might support only sizes that are divisible by four.
+    ------------------------------- NOTE end ------------------------------- */
+
+    // Normally STIF uses default heap and stack sizes for test thread, see:
+    // KTestThreadMinHeap, KTestThreadMinHeap and KStackSize.
+    // If needed heap and stack sizes can be configured here by user. Remove
+    // comments and define sizes.
+
+/*
+    aParameterValid = KStifTestModuleParameterChanged;
+
+    CTestModuleParamVer01* param = CTestModuleParamVer01::NewL();
+    // Stack size
+    param->iTestThreadStackSize= 16384; // 16K stack
+    // Heap sizes
+    param->iTestThreadMinHeap = 4096;   // 4K heap min
+    param->iTestThreadMaxHeap = 1048576;// 1M heap max
+
+    aTestModuleParam = param;
+*/
+    return KErrNone;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/SUEvent/src/SUEventCases.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,313 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains SUEvent module implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <e32math.h>
+#include "SUEvent.h"
+#include <StifTestEventInterface.h>
+
+#include <e32svr.h>
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSUEvent::Case
+// Returns a test case by number.
+//
+// This function contains an array of all available test cases 
+// i.e pair of case name and test function. If case specified by parameter
+// aCaseNumber is found from array, then that item is returned.
+// 
+// The reason for this rather complicated function is to specify all the
+// test cases only in one place. It is not necessary to understand how
+// function pointers to class member functions works when adding new test
+// cases. See function body for instructions how to add new test case.
+// -----------------------------------------------------------------------------
+//
+const TCaseInfo CSUEvent::Case ( 
+    const TInt aCaseNumber ) const 
+     {
+
+    /**
+    * To add new test cases, implement new test case function and add new 
+    * line to KCases array specify the name of the case and the function 
+    * doing the test case
+    * In practice, do following
+    * 1) Make copy of existing test case function and change its name
+    *    and functionality. Note that the function must be added to 
+    *    SUEvent.cpp file and to SUEvent.h 
+    *    header file.
+    *
+    * 2) Add entry to following KCases array either by using:
+    *
+    * 2.1: FUNCENTRY or ENTRY macro
+    * ENTRY macro takes two parameters: test case name and test case 
+    * function name.
+    *
+    * FUNCENTRY macro takes only test case function name as a parameter and
+    * uses that as a test case name and test case function name.
+    *
+    * Or
+    *
+    * 2.2: OOM_FUNCENTRY or OOM_ENTRY macro. Note that these macros are used
+    * only with OOM (Out-Of-Memory) testing!
+    *
+    * OOM_ENTRY macro takes five parameters: test case name, test case 
+    * function name, TBool which specifies is method supposed to be run using
+    * OOM conditions, TInt value for first heap memory allocation failure and 
+    * TInt value for last heap memory allocation failure.
+    * 
+    * OOM_FUNCENTRY macro takes test case function name as a parameter and uses
+    * that as a test case name, TBool which specifies is method supposed to be
+    * run using OOM conditions, TInt value for first heap memory allocation 
+    * failure and TInt value for last heap memory allocation failure. 
+    */ 
+
+    static TCaseInfoInternal const KCases[] =
+        {
+        // To add new test cases, add new items to this array
+
+        // NOTE: When compiled to GCCE, there must be Classname::
+        // declaration in front of the method name, e.g.
+        // CSUEvent::PrintTest. Otherwise the compiler
+        // gives errors.
+
+		//sets event as state event
+        ENTRY("SetEventState",			CSUEvent::SetEventState),
+        //sets event as indication event
+        ENTRY("SetEventIndication",		CSUEvent::SetEventIndication),
+        //unsets event
+        ENTRY("UnsetEvent",				CSUEvent::UnsetEvent),
+        //waits for evenr
+        ENTRY("WaitEvent",				CSUEvent::WaitEvent),
+        //sets event as indication in hard mode
+        ENTRY("SetEventIndicationHard",	CSUEvent::SetEventIndicationHard),
+        // Example how to use OOM functionality
+        //OOM_ENTRY( "Loop test with OOM", CSUEvent::LoopTest, ETrue, 2, 3),
+        //OOM_FUNCENTRY( CSUEvent::PrintTest, ETrue, 1, 3 ),
+        };
+
+    // Verify that case number is valid
+    if( (TUint) aCaseNumber >= sizeof( KCases ) /
+                               sizeof( TCaseInfoInternal ) )
+        {
+        // Invalid case, construct empty object
+        TCaseInfo null( (const TText*) L"" );
+        null.iMethod = NULL;
+        null.iIsOOMTest = EFalse;
+        null.iFirstMemoryAllocation = 0;
+        null.iLastMemoryAllocation = 0;
+        return null;
+        }
+
+    // Construct TCaseInfo object and return it
+    TCaseInfo tmp ( KCases[ aCaseNumber ].iCaseName );
+    tmp.iMethod = KCases[ aCaseNumber ].iMethod;
+    tmp.iIsOOMTest = KCases[ aCaseNumber ].iIsOOMTest;
+    tmp.iFirstMemoryAllocation = KCases[ aCaseNumber ].iFirstMemoryAllocation;
+    tmp.iLastMemoryAllocation = KCases[ aCaseNumber ].iLastMemoryAllocation;
+    return tmp;
+
+    }
+
+//#0
+TInt CSUEvent::SetEventState(TTestResult& aResult, const TFileName& aEventName)
+    {
+//RDebug::Print(_L(" CSUEvent::SetEventState start event_name=%S (%d)"), &aEventName, RThread().Id().Id());
+	iLog->Log(_L("CSUEvent::SetEventState event=%S"), &aEventName);
+
+	//Set state event
+	TEventIf setEvent(TEventIf::ESetEvent, aEventName, TEventIf::EState);
+//RDebug::Print(_L(" CSUEvent::SetEventState call Event (%d)"), RThread().Id().Id());
+	TestModuleIf().Event(setEvent);
+	
+//RDebug::Print(_L(" CSUEvent::SetEventState call SetResult (%d)"), RThread().Id().Id());
+	aResult.SetResult(KErrNone, _L(""));
+
+//RDebug::Print(_L(" CSUEvent::SetEventState end (%d)"), RThread().Id().Id());
+    return KErrNone;
+    }
+
+//#1
+TInt CSUEvent::SetEventIndication(TTestResult& aResult, const TFileName& aEventName)
+    {
+//RDebug::Print(_L(" CSUEvent::SetEventIndication start event_name=%S (%d)"), &aEventName, RThread().Id().Id());
+	iLog->Log(_L("CSUEvent::SetEventIndication event=%S"), &aEventName);
+
+	//Set indication event
+	TEventIf setEvent(TEventIf::ESetEvent, aEventName, TEventIf::EIndication);
+//RDebug::Print(_L(" CSUEvent::SetEventIndication call Event (%d)"), RThread().Id().Id());
+	TestModuleIf().Event(setEvent);
+
+//RDebug::Print(_L(" CSUEvent::SetEventIndication call SetResult (%d)"), RThread().Id().Id());
+	aResult.SetResult(KErrNone, _L(""));
+//RDebug::Print(_L(" CSUEvent::SetEventIndication end (%d)"), RThread().Id().Id());
+    return KErrNone;
+    }
+
+//#2
+TInt CSUEvent::UnsetEvent(TTestResult& aResult, const TFileName& aEventName)
+    {
+RDebug::Print(_L("CSUEvent::UnsetEvent start event_name=%S"), &aEventName);
+	iLog->Log(_L("CSUEvent::UnsetEvent event=%S"), &aEventName);
+
+	//Unset event
+	TEventIf event(TEventIf::EUnsetEvent, aEventName, TEventIf::EState);
+RDebug::Print(_L("CSUEvent::UnsetEvent call Event"));
+	TestModuleIf().Event(event);
+
+RDebug::Print(_L("CSUEvent::UnsetEvent call SetResult"));
+	aResult.SetResult(KErrNone, _L(""));
+RDebug::Print(_L("CSUEvent::UnsetEvent end"));
+    return KErrNone;
+    }
+
+
+//#3
+TInt CSUEvent::WaitEvent(TTestResult& aResult, const TFileName& aEventName)
+    {
+//RDebug::Print(_L(" CSUEvent::WaitEvent start event name=%S (%d)"), &aEventName, RThread().Id().Id());
+	iLog->Log(_L("CSUEvent::WaitEvent event=%S"), &aEventName);
+
+	//Request, wait for, and release event
+//RDebug::Print(_L(" CSUEvent::WaitEvent set event request (%d)"), RThread().Id().Id());
+	TEventIf event(TEventIf::EReqEvent, aEventName, TEventIf::EState);
+//RDebug::Print(_L(" CSUEvent::WaitEvent call Event (%d)"), RThread().Id().Id());
+	TestModuleIf().Event(event);
+//RDebug::Print(_L(" CSUEvent::WaitEvent set event (%d)"), RThread().Id().Id());
+	event.SetType(TEventIf::EWaitEvent);
+//RDebug::Print(_L(" CSUEvent::WaitEvent call Event (%d)"), RThread().Id().Id());
+	TestModuleIf().Event(event);
+//RDebug::Print(_L(" CSUEvent::WaitEvent set event release (%d)"), RThread().Id().Id());
+	event.SetType(TEventIf::ERelEvent);
+//RDebug::Print(_L(" CSUEvent::WaitEvent call Event (%d)"), RThread().Id().Id());
+	TestModuleIf().Event(event);
+
+//RDebug::Print(_L(" CSUEvent::WaitEvent call SetResult (%d)"), RThread().Id().Id());
+	aResult.SetResult(KErrNone, _L(""));
+//RDebug::Print(_L(" CSUEvent::WaitEvent end (%d)"), RThread().Id().Id());
+    return KErrNone;
+    }
+
+
+//#4
+TInt CSUEvent::SetEventIndicationHard(TTestResult& aResult, const TFileName& /*aEventName*/)
+    {
+//RDebug::Print(_L(" CSUEvent::SetEventIndicationHard start (%d)"), RThread().Id().Id());
+	iLog->Log(_L("CSUEvent::SetEventIndicationHard"));
+
+	TBuf<20> eventName;
+	eventName.Copy(_L("event1"));
+	//Set indication event
+	TEventIf setEvent(TEventIf::ESetEvent, eventName, TEventIf::EIndication);
+//RDebug::Print(_L(" CSUEvent::SetEventIndicationHard call Event (%d)"), RThread().Id().Id());
+	TestModuleIf().Event(setEvent);
+
+//RDebug::Print(_L(" CSUEvent::SetEventIndicationHard call SetResult (%d)"), RThread().Id().Id());
+	aResult.SetResult(KErrNone, _L(""));
+//RDebug::Print(_L(" CSUEvent::SetEventIndicationHard end (%d)"), RThread().Id().Id());
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// ?classname::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?classname::?member_function(
+   ?arg_type arg,
+   ?arg_type arg )
+   {
+
+   ?code
+
+   }
+*/
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// ?function_name implements...
+// ?implementation_description.
+// Returns: ?value_1: ?description
+//          ?value_n: ?description
+//                    ?description
+// -----------------------------------------------------------------------------
+//
+/*
+?type  ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg )  // ?description
+    {
+
+    ?code
+
+    }
+*/
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifKernelTestClassBase/Bwins/StifKernelTestClassBase_eka1u.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,10 @@
+EXPORTS
+	??0DStifKernelTestClassBase@@QAE@PAVDLogicalDevice@@@Z @ 1 NONAME ; DStifKernelTestClassBase::DStifKernelTestClassBase(class DLogicalDevice *)
+	??0DStifKernelTestClassBaseDriver@@QAE@ABVTDesC16@@@Z @ 2 NONAME ; DStifKernelTestClassBaseDriver::DStifKernelTestClassBaseDriver(class TDesC16 const &)
+	??1DStifKernelTestClassBase@@UAE@XZ @ 3 NONAME ; DStifKernelTestClassBase::~DStifKernelTestClassBase(void)
+	??1DStifKernelTestClassBaseDriver@@UAE@XZ @ 4 NONAME ; DStifKernelTestClassBaseDriver::~DStifKernelTestClassBaseDriver(void)
+	?DoControl@DStifKernelTestClassBase@@EAEHHPAX0@Z @ 5 NONAME ; int DStifKernelTestClassBase::DoControl(int, void *, void *)
+	?GetCaps@DStifKernelTestClassBaseDriver@@UBEXAAVTDes8@@@Z @ 6 NONAME ; void DStifKernelTestClassBaseDriver::GetCaps(class TDes8 &) const
+	?Install@DStifKernelTestClassBaseDriver@@UAEHXZ @ 7 NONAME ; int DStifKernelTestClassBaseDriver::Install(void)
+	?RunInternalL@DStifKernelTestClassBase@@MAEHPBVTStifFunctionInfo@@HABVTDesC16@@1@Z @ 8 NONAME ; int DStifKernelTestClassBase::RunInternalL(class TStifFunctionInfo const *, int, class TDesC16 const &, class TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifKernelTestClassBase/Bwins/StifKernelTestClassBaseu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,10 @@
+EXPORTS
+	??0DStifKernelTestClassBase@@QAE@PAVDLogicalDevice@@@Z @ 1 NONAME ; DStifKernelTestClassBase::DStifKernelTestClassBase(class DLogicalDevice *)
+	??0DStifKernelTestClassBaseDriver@@QAE@ABVTDesC8@@@Z @ 2 NONAME ; DStifKernelTestClassBaseDriver::DStifKernelTestClassBaseDriver(class TDesC8 const &)
+	??1DStifKernelTestClassBase@@UAE@XZ @ 3 NONAME ; DStifKernelTestClassBase::~DStifKernelTestClassBase(void)
+	??1DStifKernelTestClassBaseDriver@@UAE@XZ @ 4 NONAME ; DStifKernelTestClassBaseDriver::~DStifKernelTestClassBaseDriver(void)
+	?GetCaps@DStifKernelTestClassBaseDriver@@UBEXAAVTDes8@@@Z @ 5 NONAME ; void DStifKernelTestClassBaseDriver::GetCaps(class TDes8 &) const
+	?HandleMsg@DStifKernelTestClassBase@@UAEXPAVTMessageBase@@@Z @ 6 NONAME ; void DStifKernelTestClassBase::HandleMsg(class TMessageBase *)
+	?Install@DStifKernelTestClassBaseDriver@@UAEHXZ @ 7 NONAME ; int DStifKernelTestClassBaseDriver::Install(void)
+	?RunInternalL@DStifKernelTestClassBase@@MAEHPBVTStifFunctionInfo@@HABVTDesC8@@1@Z @ 8 NONAME ; int DStifKernelTestClassBase::RunInternalL(class TStifFunctionInfo const *, int, class TDesC8 const &, class TDesC8 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifKernelTestClassBase/eabi/StifKernelTestClassBaseu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,18 @@
+EXPORTS
+	_ZN24DStifKernelTestClassBase12RunInternalLEPK17TStifFunctionInfoiRK6TDesC8S5_ @ 1 NONAME
+	_ZN24DStifKernelTestClassBase9HandleMsgEP12TMessageBase @ 2 NONAME
+	_ZN24DStifKernelTestClassBaseC2EP14DLogicalDevice @ 3 NONAME
+	_ZN24DStifKernelTestClassBaseD0Ev @ 4 NONAME
+	_ZN24DStifKernelTestClassBaseD1Ev @ 5 NONAME
+	_ZN24DStifKernelTestClassBaseD2Ev @ 6 NONAME
+	_ZN30DStifKernelTestClassBaseDriver7InstallEv @ 7 NONAME
+	_ZN30DStifKernelTestClassBaseDriverC2ERK6TDesC8 @ 8 NONAME
+	_ZN30DStifKernelTestClassBaseDriverD0Ev @ 9 NONAME
+	_ZN30DStifKernelTestClassBaseDriverD1Ev @ 10 NONAME
+	_ZN30DStifKernelTestClassBaseDriverD2Ev @ 11 NONAME
+	_ZNK30DStifKernelTestClassBaseDriver7GetCapsER5TDes8 @ 12 NONAME
+	_ZTI24DStifKernelTestClassBase @ 13 NONAME ; #<TI>#
+	_ZTI30DStifKernelTestClassBaseDriver @ 14 NONAME ; #<TI>#
+	_ZTV24DStifKernelTestClassBase @ 15 NONAME ; #<VT>#
+	_ZTV30DStifKernelTestClassBaseDriver @ 16 NONAME ; #<VT>#
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifKernelTestClassBase/group/StifKernelTestClassBase.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Kernel testclass
+* base module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+#include        "kernel/kern_ext.mmh"
+
+CAPABILITY      ALL
+VENDORID        0x101FB657
+SECUREID        0x102073DD
+EPOCALLOWDLLDATA
+
+TARGET          StifKernelTestClassBase.dll
+TARGETTYPE      kdll
+UID             0x1000008D 0x101FB3E3
+
+DEFFILE         StifKernelTestClassBase.def
+
+USERINCLUDE     ../inc 
+USERINCLUDE     ../../inc 
+
+OS_LAYER_KERNEL_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          StifKernelTestClassBase.cpp
+
+LANG            SC
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifKernelTestClassBase/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+#include <platform_paths.hrh>
+
+//
+// TO DO: (mandatory)
+//
+// Add here a definition for your port (as declared in E32PLAT.PM)
+//
+// WINSCW added for debugging test programs
+PRJ_PLATFORMS
+	WINSCW ARMV5
+
+PRJ_EXPORTS
+
+PRJ_MMPFILES
+	StifKernelTestClassBase.mmp
+
+//  End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifKernelTestClassBase/src/StifKernelTestClassBase.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,294 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains DStifKernelTestClassBaseDriver 
+* implementation.
+*
+*/
+
+// INCLUDE FILES
+#include "StifKernelTestClass.h"
+#include "StifKernelTestClassBase.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// DStifKernelTestClassBaseDriver::DStifKernelTestClassBaseDriver
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C DStifKernelTestClassBaseDriver::DStifKernelTestClassBaseDriver( 
+    const TDesC& aName )
+    {
+
+    __KTRACE_OPT(KHARDWARE, 
+       Kern::Printf("DStifKernelTestClassBaseDriver::DStifKernelTestClassBaseDriver()"));
+
+    iVersion=TVersion( RStifKernelTestClass::EMajorVersionNumber,
+                       RStifKernelTestClass::EMinorVersionNumber,
+                       RStifKernelTestClass::EBuildVersionNumber );
+ 
+    iName.Copy( aName.Left( KMaxName ) );
+
+    }
+
+// -----------------------------------------------------------------------------
+// DStifKernelTestClassBaseDriver::Install
+// Set name.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt DStifKernelTestClassBaseDriver::Install()
+    {
+
+    __KTRACE_OPT(KHARDWARE, 
+        Kern::Printf("DStifKernelTestClassBaseDriver::Install()"));
+ 
+
+    return SetName( &iName );       // Set our name and return error code.
+
+    }
+
+// -----------------------------------------------------------------------------
+// DStifKernelTestClassBaseDriver::~DStifKernelTestClassBaseDriver
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C DStifKernelTestClassBaseDriver::~DStifKernelTestClassBaseDriver()
+    {
+
+    __KTRACE_OPT(KHARDWARE, 
+        Kern::Printf("DStifKernelTestClassBaseDriver::~DStifKernelTestClassBaseDriver()"));
+
+    }
+
+// -----------------------------------------------------------------------------
+// DStifKernelTestClassBaseDriver::GetCaps
+// Returns the drivers capabilities, may be used by LDD
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void DStifKernelTestClassBaseDriver::GetCaps( TDes8& /* aDes */ ) const
+    {
+
+    __KTRACE_OPT(KHARDWARE, 
+        Kern::Printf("DStifKernelTestClassBaseDriver::GetCaps()"));
+  
+    }
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CStifKernelTestClassBase::CStifKernelTestClassBase
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+
+EXPORT_C DStifKernelTestClassBase::DStifKernelTestClassBase( DLogicalDevice* /* aDevice */ )
+    {
+    // Get pointer to client threads DThread object
+    iThread=&Kern::CurrentThread();
+
+    // Open a reference on client thread so it's control block can't dissapear until
+    // this driver has finished with it
+    ((DObject*)iThread)->Open();
+
+    __KTRACE_OPT(KHARDWARE, 
+        Kern::Printf("DStifKernelTestClassBase::DStifKernelTestClassBase()"));         
+    }
+            
+        
+// -----------------------------------------------------------------------------
+// DStifKernelTestClassBase::~DStifKernelTestClassBase()
+// Destructor
+// -----------------------------------------------------------------------------
+//
+
+EXPORT_C DStifKernelTestClassBase::~DStifKernelTestClassBase()
+    { 
+
+    __KTRACE_OPT(KHARDWARE, 
+        Kern::Printf("DStifKernelTestClassBase::~DStifKernelTestClassBase()"));
+
+    // Close our reference on the client thread
+    Kern::SafeClose((DObject*&)iThread,NULL);
+
+            
+    Delete();        
+    }
+
+// -----------------------------------------------------------------------------
+// CStifKernelTestClassBase::DoControl
+// Handle syncronous request,
+// -----------------------------------------------------------------------------
+//
+
+TInt DStifKernelTestClassBase::DoControl( 
+    TInt aFunction, 
+    TAny* a1, 
+    TAny* /* a2 */ )   
+    {
+
+    __KTRACE_OPT(KHARDWARE, 
+        Kern::Printf("DStifKernelTestClassBase::DoControl()")); 
+    
+    TInt ret = KErrNone;
+    switch( aFunction )
+        {
+        case RStifKernelTestClass::ERunMethod:
+            {
+            TStifRunMethodInfo methodInfo;
+            TPckg<TStifRunMethodInfo> methodInfoPckg( methodInfo );
+
+            TInt err = KErrNone;
+                                                          
+            ret = Kern::ThreadDesRead( iThread, a1, methodInfoPckg, 0, KChunkShiftBy0 );
+            if( ret != KErrNone )
+                {
+                __KTRACE_OPT(KHARDWARE, 
+                    Kern::Printf("DStifKernelTestClassBase::DoControl: ThreadDesRead fails! %d", 333));
+                return ret;
+                }                
+                            
+            // TRAP is not supported in EKA2 kernel, so we can't use it. However, it is not even needed 
+            // any longer because kernel test cases cannot leave either. Although RunMethodL's name 
+            // seems to allow leaves (L in the end of the name), it really doesn't!
+            ret = RunMethodL( methodInfo.iMethodName, methodInfo.iMethodParams );                                           
+                                     
+            if( err != KErrNone )
+                {
+                methodInfo.iResult = err;
+                methodInfo.iMethodResultDes.Copy( _L("RunMethodL leave: ") );
+                methodInfo.iMethodResultDes.AppendNum( err );
+                }
+            else if( ret != KErrNone )
+                {
+                methodInfo.iResult = ret;
+                methodInfo.iMethodResultDes.Copy( _L("RunMethodL returned error: ") );
+                methodInfo.iMethodResultDes.AppendNum( ret );
+                }
+            else
+                {
+                methodInfo.iResult = KErrNone;
+                }
+
+            ret = Kern::ThreadDesWrite( iThread, a1, methodInfoPckg, 0, 0, &Kern::CurrentThread() );
+
+            }
+            break;
+        default:
+            ret = KErrNotFound;
+        }
+        
+    return ret;
+    } 
+
+
+// -----------------------------------------------------------------------------
+// void DStifKernelTestClassBase::HandleMsg(TMessageBase* aMsg)
+// Processes the DoControl call in EKA2
+// -----------------------------------------------------------------------------
+//
+       
+EXPORT_C void DStifKernelTestClassBase::HandleMsg( TMessageBase* aMsg )
+    {       
+    __KTRACE_OPT(KHARDWARE, 
+        Kern::Printf("DStifKernelTestClassBase::HandleMsg"));
+    
+    TThreadMessage& m=*(TThreadMessage*)aMsg;
+
+    // Get the id
+    TInt id=m.iValue;
+   
+    if(id == (TInt)ECloseMsg)
+        {
+        // Lets close the channel
+        m.Complete( KErrNone, EFalse );
+        return;
+        }
+        
+    if (id == KMaxTInt)
+        {
+        // Cancel operations are not needed because we don't use async requests
+        m.Complete( KErrNone, ETrue );
+        return;
+        }
+   
+    if( id > 0 ) 
+        {
+        // Process the DoControl call
+        TInt r = DoControl( id, m.Ptr0(), m.Ptr1() );
+        m.Complete( r, ETrue );
+        return;
+        }        
+    }
+
+
+// -----------------------------------------------------------------------------
+// DStifKernelTestClassBase::RunInternalL( 
+//                        const TStifKernelFunctionInfo* const aFunctions, 
+//                        TInt aCount, 
+//                        const TDesC& aMethod, 
+//                        const TDesC& aParams )
+//
+// Executes the test case. In EKA2 this function cannot leave.
+// -----------------------------------------------------------------------------
+//
+
+EXPORT_C TInt DStifKernelTestClassBase::RunInternalL( 
+                        const TStifFunctionInfo* const aFunctions, 
+                        TInt aCount, 
+                        const TDesC& aMethod, 
+                        const TDesC& aParams )
+    {
+    
+    TInt ret = KErrNotFound;
+
+    TInt i = 0;
+    TName funcName;
+    
+    // Search function from table and call it
+    for ( i = 0; i < aCount; i++ )
+        {
+        funcName = aFunctions[i].iFunctionName;      
+        if ( aMethod == funcName )
+            {
+            ret  = ( this->*(aFunctions[i].iMethod) )( aParams );
+            break;            
+            }
+    
+        }
+
+    return ret;
+    
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/Bmarm/StifTFwIfu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,58 @@
+EXPORTS
+	__10CUIStoreIf @ 1 NONAME R3UNUSED ; CUIStoreIf::CUIStoreIf(void)
+	AddTestCaseFile__10CStifTFwIfR7TDesC16T1 @ 2 NONAME R3UNUSED ; CStifTFwIf::AddTestCaseFile(TDesC16 &, TDesC16 &)
+	AddTestCaseFile__8CUIStoreRC7TDesC16T1 @ 3 NONAME R3UNUSED ; CUIStore::AddTestCaseFile(TDesC16 const &, TDesC16 const &)
+	AddTestModule__10CStifTFwIfR7TDesC16T1 @ 4 NONAME R3UNUSED ; CStifTFwIf::AddTestModule(TDesC16 &, TDesC16 &)
+	AddTestModule__8CUIStoreRC7TDesC16T1 @ 5 NONAME R3UNUSED ; CUIStore::AddTestModule(TDesC16 const &, TDesC16 const &)
+	AddToTestSet__8CUIStoreRC7TDesC16RC9CTestInfo @ 6 NONAME R3UNUSED ; CUIStore::AddToTestSet(TDesC16 const &, CTestInfo const &)
+	AtsReceive__10CStifTFwIfRC7TDesC16 @ 7 NONAME R3UNUSED ; CStifTFwIf::AtsReceive(TDesC16 const &)
+	CancelTestCase__10CStifTFwIfi @ 8 NONAME R3UNUSED ; CStifTFwIf::CancelTestCase(int)
+	CancelTest__18CUIEngineContainer @ 9 NONAME R3UNUSED ; CUIEngineContainer::CancelTest(void)
+	Close__10CStifTFwIf @ 10 NONAME R3UNUSED ; CStifTFwIf::Close(void)
+	Close__8CUIStore @ 11 NONAME R3UNUSED ; CUIStore::Close(void)
+	ConstructL__10CUIStoreIf @ 12 NONAME R3UNUSED ; CUIStoreIf::ConstructL(void)
+	CreateTestSet__8CUIStoreRC7TDesC16 @ 13 NONAME R3UNUSED ; CUIStore::CreateTestSet(TDesC16 const &)
+	GetTestCases__10CStifTFwIfRt13RPointerArray1Z9CTestInfoR7TDesC16T2 @ 14 NONAME ; CStifTFwIf::GetTestCases(RPointerArray<CTestInfo> &, TDesC16 &, TDesC16 &)
+	GoingToReboot__8CStifTFwP18CUIEngineContainerR14TRequestStatus @ 15 NONAME R3UNUSED ; CStifTFw::GoingToReboot(CUIEngineContainer *, TRequestStatus &)
+	InsertToTestSet__8CUIStoreRC7TDesC16RC9CTestInfoi @ 16 NONAME ; CUIStore::InsertToTestSet(TDesC16 const &, CTestInfo const &, int)
+	ListAllModules__8CUIStoreRt13RPointerArray1Z7TDesC16 @ 17 NONAME R3UNUSED ; CUIStore::ListAllModules(RPointerArray<TDesC16> &)
+	LoadAllModules__8CUIStore @ 18 NONAME R3UNUSED ; CUIStore::LoadAllModules(void)
+	LoadSavedTestCases__8CUIStore @ 19 NONAME R3UNUSED ; CUIStore::LoadSavedTestCases(void)
+	LoadTestSet__8CUIStoreRC7TDesC16 @ 20 NONAME R3UNUSED ; CUIStore::LoadTestSet(TDesC16 const &)
+	Modules__8CUIStoreRt9RRefArray1Z7TDesC16 @ 21 NONAME R3UNUSED ; CUIStore::Modules(RRefArray<TDesC16> &)
+	NewL__9CTestInfo @ 22 NONAME R3UNUSED ; CTestInfo::NewL(void)
+	Open__10CStifTFwIfR7TDesC16 @ 23 NONAME R3UNUSED ; CStifTFwIf::Open(TDesC16 &)
+	Open__8CUIStoreRC7TDesC16 @ 24 NONAME R3UNUSED ; CUIStore::Open(TDesC16 const &)
+	PauseTestCase__10CStifTFwIfi @ 25 NONAME R3UNUSED ; CStifTFwIf::PauseTestCase(int)
+	PauseTest__18CUIEngineContainer @ 26 NONAME R3UNUSED ; CUIEngineContainer::PauseTest(void)
+	PrintProg__8CStifTFwP18CUIEngineContainerR13TTestProgress @ 27 NONAME R3UNUSED ; CStifTFw::PrintProg(CUIEngineContainer *, TTestProgress &)
+	RemoteMsg__8CStifTFwP18CUIEngineContainerRC7TDesC16 @ 28 NONAME R3UNUSED ; CStifTFw::RemoteMsg(CUIEngineContainer *, TDesC16 const &)
+	RemoveFromTestSet__8CUIStoreRC7TDesC16RC9CTestInfo @ 29 NONAME R3UNUSED ; CUIStore::RemoveFromTestSet(TDesC16 const &, CTestInfo const &)
+	RemoveTestCaseFile__10CStifTFwIfR7TDesC16T1 @ 30 NONAME R3UNUSED ; CStifTFwIf::RemoveTestCaseFile(TDesC16 &, TDesC16 &)
+	RemoveTestCaseFile__8CUIStoreRC7TDesC16T1 @ 31 NONAME R3UNUSED ; CUIStore::RemoveTestCaseFile(TDesC16 const &, TDesC16 const &)
+	RemoveTestModule__10CStifTFwIfR7TDesC16 @ 32 NONAME R3UNUSED ; CStifTFwIf::RemoveTestModule(TDesC16 &)
+	RemoveTestModule__8CUIStoreRC7TDesC16 @ 33 NONAME R3UNUSED ; CUIStore::RemoveTestModule(TDesC16 const &)
+	RemoveTestSet__8CUIStoreRC7TDesC16 @ 34 NONAME R3UNUSED ; CUIStore::RemoveTestSet(TDesC16 const &)
+	ResumeTestCase__10CStifTFwIfi @ 35 NONAME R3UNUSED ; CStifTFwIf::ResumeTestCase(int)
+	ResumeTest__18CUIEngineContainer @ 36 NONAME R3UNUSED ; CUIEngineContainer::ResumeTest(void)
+	SaveTestSet__8CUIStoreRC7TDesC16 @ 37 NONAME R3UNUSED ; CUIStore::SaveTestSet(TDesC16 const &)
+	SetAttribute__10CStifTFwIf10TAttributeRC7TDesC16 @ 38 NONAME R3UNUSED ; CStifTFwIf::SetAttribute(TAttribute, TDesC16 const &)
+	StartTestCase__10CStifTFwIfRiRC9CTestInfo @ 39 NONAME R3UNUSED ; CStifTFwIf::StartTestCase(int &, CTestInfo const &)
+	StartTestCase__8CUIStoreRC9CTestInfoRi @ 40 NONAME R3UNUSED ; CUIStore::StartTestCase(CTestInfo const &, int &)
+	StartTestSet__8CUIStoreRC12CTestSetInfoRiQ215CStartedTestSet8TSetType @ 41 NONAME ; CUIStore::StartTestSet(CTestSetInfo const &, int &, CStartedTestSet::TSetType)
+	StartedTestCaseL__8CUIStorei @ 42 NONAME R3UNUSED ; CUIStore::StartedTestCaseL(int)
+	StartedTestCases__8CUIStoreRt9RRefArray1Z16CStartedTestCaseiRC7TDesC16T3 @ 43 NONAME ; CUIStore::StartedTestCases(RRefArray<CStartedTestCase> &, int, TDesC16 const &, TDesC16 const &)
+	StartedTestSetL__8CUIStorei @ 44 NONAME R3UNUSED ; CUIStore::StartedTestSetL(int)
+	StartedTestSets__8CUIStoreRt9RRefArray1Z15CStartedTestSeti @ 45 NONAME R3UNUSED ; CUIStore::StartedTestSets(RRefArray<CStartedTestSet> &, int)
+	TestCaseFiles__8CUIStoreRt9RRefArray1Z7TDesC16RC7TDesC16 @ 46 NONAME R3UNUSED ; CUIStore::TestCaseFiles(RRefArray<TDesC16> &, TDesC16 const &)
+	TestCases__8CUIStoreRt9RRefArray1Z9CTestInfoRC7TDesC16T2 @ 47 NONAME ; CUIStore::TestCases(RRefArray<CTestInfo> &, TDesC16 const &, TDesC16 const &)
+	TestExecuted__8CStifTFwP18CUIEngineContainerR15TFullTestResult @ 48 NONAME R3UNUSED ; CStifTFw::TestExecuted(CUIEngineContainer *, TFullTestResult &)
+	TestSetL__8CUIStoreRC7TDesC16 @ 49 NONAME R3UNUSED ; CUIStore::TestSetL(TDesC16 const &)
+	TestSets__8CUIStoreRt9RRefArray1Z12CTestSetInfo @ 50 NONAME R3UNUSED ; CUIStore::TestSets(RRefArray<CTestSetInfo> &)
+	UIEngineContainer__C16CStartedTestCase @ 51 NONAME R3UNUSED ; CStartedTestCase::UIEngineContainer(void) const
+	UIStore__10CUIStoreIf @ 52 NONAME R3UNUSED ; CUIStoreIf::UIStore(void)
+	"_._10CStifTFwIf" @ 53 NONAME R3UNUSED ; CStifTFwIf::~CStifTFwIf(void)
+	"_._10CUIStoreIf" @ 54 NONAME R3UNUSED ; CUIStoreIf::~CUIStoreIf(void)
+	__10CStifTFwIf @ 55 NONAME R3UNUSED ; CStifTFwIf::CStifTFwIf(void)
+	AbortTestSet__8CUIStoreR15CStartedTestSet @ 56 NONAME R3UNUSED ; CUIStore::AbortTestSet(CStartedTestSet &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/Bwins/StifTFwIfu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,64 @@
+EXPORTS
+	??0CStifTFwIf@@IAE@XZ @ 1 NONAME ; CStifTFwIf::CStifTFwIf(void)
+	??0CUIStoreIf@@IAE@XZ @ 2 NONAME ; CUIStoreIf::CUIStoreIf(void)
+	??1CStifTFwIf@@UAE@XZ @ 3 NONAME ; CStifTFwIf::~CStifTFwIf(void)
+	??1CUIStoreIf@@UAE@XZ @ 4 NONAME ; CUIStoreIf::~CUIStoreIf(void)
+	?AbortTestSet@CUIStore@@QAEHAAVCStartedTestSet@@@Z @ 5 NONAME ; int CUIStore::AbortTestSet(class CStartedTestSet &)
+	?AddTestCaseFile@CStifTFwIf@@IAEHAAVTDesC16@@0@Z @ 6 NONAME ; int CStifTFwIf::AddTestCaseFile(class TDesC16 &, class TDesC16 &)
+	?AddTestCaseFile@CUIStore@@QAEHABVTDesC16@@0@Z @ 7 NONAME ; int CUIStore::AddTestCaseFile(class TDesC16 const &, class TDesC16 const &)
+	?AddTestModule@CStifTFwIf@@IAEHAAVTDesC16@@0@Z @ 8 NONAME ; int CStifTFwIf::AddTestModule(class TDesC16 &, class TDesC16 &)
+	?AddTestModule@CUIStore@@QAEHABVTDesC16@@0@Z @ 9 NONAME ; int CUIStore::AddTestModule(class TDesC16 const &, class TDesC16 const &)
+	?AddToTestSet@CUIStore@@QAEHABVTDesC16@@ABVCTestInfo@@@Z @ 10 NONAME ; int CUIStore::AddToTestSet(class TDesC16 const &, class CTestInfo const &)
+	?AtsReceive@CStifTFwIf@@IAEHABVTDesC16@@@Z @ 11 NONAME ; int CStifTFwIf::AtsReceive(class TDesC16 const &)
+	?CancelTest@CUIEngineContainer@@QAEHXZ @ 12 NONAME ; int CUIEngineContainer::CancelTest(void)
+	?CancelTestCase@CStifTFwIf@@IAEHH@Z @ 13 NONAME ; int CStifTFwIf::CancelTestCase(int)
+	?Close@CStifTFwIf@@IAEHXZ @ 14 NONAME ; int CStifTFwIf::Close(void)
+	?Close@CUIStore@@QAEHXZ @ 15 NONAME ; int CUIStore::Close(void)
+	?ConstructL@CUIStoreIf@@IAEXXZ @ 16 NONAME ; void CUIStoreIf::ConstructL(void)
+	?CreateTestSet@CUIStore@@QAEHABVTDesC16@@@Z @ 17 NONAME ; int CUIStore::CreateTestSet(class TDesC16 const &)
+	?GetTestCases@CStifTFwIf@@IAEHAAV?$RPointerArray@VCTestInfo@@@@AAVTDesC16@@1@Z @ 18 NONAME ; int CStifTFwIf::GetTestCases(class RPointerArray<class CTestInfo> &, class TDesC16 &, class TDesC16 &)
+	?GoingToReboot@CStifTFw@@EAEHPAVCUIEngineContainer@@AAVTRequestStatus@@@Z @ 19 NONAME ; int CStifTFw::GoingToReboot(class CUIEngineContainer *, class TRequestStatus &)
+	?InsertToTestSet@CUIStore@@QAEHABVTDesC16@@ABVCTestInfo@@H@Z @ 20 NONAME ; int CUIStore::InsertToTestSet(class TDesC16 const &, class CTestInfo const &, int)
+	?ListAllModules@CUIStore@@QAEHAAV?$RPointerArray@VTDesC16@@@@@Z @ 21 NONAME ; int CUIStore::ListAllModules(class RPointerArray<class TDesC16> &)
+	?LoadAllModules@CUIStore@@QAEHXZ @ 22 NONAME ; int CUIStore::LoadAllModules(void)
+	?LoadSavedTestCases@CUIStore@@QAEHXZ @ 23 NONAME ; int CUIStore::LoadSavedTestCases(void)
+	?LoadTestSet@CUIStore@@QAEHABVTDesC16@@@Z @ 24 NONAME ; int CUIStore::LoadTestSet(class TDesC16 const &)
+	?Modules@CUIStore@@QAEHAAV?$RRefArray@VTDesC16@@@@@Z @ 25 NONAME ; int CUIStore::Modules(class RRefArray<class TDesC16> &)
+	?NewL@CTestInfo@@SAPAV1@XZ @ 26 NONAME ; class CTestInfo * CTestInfo::NewL(void)
+	?Open@CStifTFwIf@@IAEHAAVTDesC16@@@Z @ 27 NONAME ; int CStifTFwIf::Open(class TDesC16 &)
+	?Open@CUIStore@@QAEHABVTDesC16@@@Z @ 28 NONAME ; int CUIStore::Open(class TDesC16 const &)
+	?PauseTest@CUIEngineContainer@@QAEHXZ @ 29 NONAME ; int CUIEngineContainer::PauseTest(void)
+	?PauseTestCase@CStifTFwIf@@IAEHH@Z @ 30 NONAME ; int CStifTFwIf::PauseTestCase(int)
+	?PrintProg@CStifTFw@@EAEHPAVCUIEngineContainer@@AAVTTestProgress@@@Z @ 31 NONAME ; int CStifTFw::PrintProg(class CUIEngineContainer *, class TTestProgress &)
+	?RemoteMsg@CStifTFw@@EAEHPAVCUIEngineContainer@@ABVTDesC16@@@Z @ 32 NONAME ; int CStifTFw::RemoteMsg(class CUIEngineContainer *, class TDesC16 const &)
+	?RemoveFromTestSet@CUIStore@@QAEHABVTDesC16@@ABVCTestInfo@@@Z @ 33 NONAME ; int CUIStore::RemoveFromTestSet(class TDesC16 const &, class CTestInfo const &)
+	?RemoveTestCaseFile@CStifTFwIf@@IAEHAAVTDesC16@@0@Z @ 34 NONAME ; int CStifTFwIf::RemoveTestCaseFile(class TDesC16 &, class TDesC16 &)
+	?RemoveTestCaseFile@CUIStore@@QAEHABVTDesC16@@0@Z @ 35 NONAME ; int CUIStore::RemoveTestCaseFile(class TDesC16 const &, class TDesC16 const &)
+	?RemoveTestModule@CStifTFwIf@@IAEHAAVTDesC16@@@Z @ 36 NONAME ; int CStifTFwIf::RemoveTestModule(class TDesC16 &)
+	?RemoveTestModule@CUIStore@@QAEHABVTDesC16@@@Z @ 37 NONAME ; int CUIStore::RemoveTestModule(class TDesC16 const &)
+	?RemoveTestSet@CUIStore@@QAEHABVTDesC16@@@Z @ 38 NONAME ; int CUIStore::RemoveTestSet(class TDesC16 const &)
+	?ResumeTest@CUIEngineContainer@@QAEHXZ @ 39 NONAME ; int CUIEngineContainer::ResumeTest(void)
+	?ResumeTestCase@CStifTFwIf@@IAEHH@Z @ 40 NONAME ; int CStifTFwIf::ResumeTestCase(int)
+	?SaveTestSet@CUIStore@@QAEHABVTDesC16@@@Z @ 41 NONAME ; int CUIStore::SaveTestSet(class TDesC16 const &)
+	?SetAttribute@CStifTFwIf@@IAEHW4TAttribute@@ABVTDesC16@@@Z @ 42 NONAME ; int CStifTFwIf::SetAttribute(enum TAttribute, class TDesC16 const &)
+	?StartTestCase@CStifTFwIf@@IAEHAAHABVCTestInfo@@@Z @ 43 NONAME ; int CStifTFwIf::StartTestCase(int &, class CTestInfo const &)
+	?StartTestCase@CUIStore@@QAEHABVCTestInfo@@AAH@Z @ 44 NONAME ; int CUIStore::StartTestCase(class CTestInfo const &, int &)
+	?StartTestSet@CUIStore@@QAEHABVCTestSetInfo@@AAHW4TSetType@CStartedTestSet@@@Z @ 45 NONAME ; int CUIStore::StartTestSet(class CTestSetInfo const &, int &, enum CStartedTestSet::TSetType)
+	?StartedTestCaseL@CUIStore@@QAEAAVCStartedTestCase@@H@Z @ 46 NONAME ; class CStartedTestCase & CUIStore::StartedTestCaseL(int)
+	?StartedTestCases@CUIStore@@QAEHAAV?$RRefArray@VCStartedTestCase@@@@HABVTDesC16@@1@Z @ 47 NONAME ; int CUIStore::StartedTestCases(class RRefArray<class CStartedTestCase> &, int, class TDesC16 const &, class TDesC16 const &)
+	?StartedTestSetL@CUIStore@@QAEAAVCStartedTestSet@@H@Z @ 48 NONAME ; class CStartedTestSet & CUIStore::StartedTestSetL(int)
+	?StartedTestSets@CUIStore@@QAEHAAV?$RRefArray@VCStartedTestSet@@@@H@Z @ 49 NONAME ; int CUIStore::StartedTestSets(class RRefArray<class CStartedTestSet> &, int)
+	?TestCaseFiles@CUIStore@@QAEHAAV?$RRefArray@VTDesC16@@@@ABVTDesC16@@@Z @ 50 NONAME ; int CUIStore::TestCaseFiles(class RRefArray<class TDesC16> &, class TDesC16 const &)
+	?TestCases@CUIStore@@QAEHAAV?$RRefArray@VCTestInfo@@@@ABVTDesC16@@1@Z @ 51 NONAME ; int CUIStore::TestCases(class RRefArray<class CTestInfo> &, class TDesC16 const &, class TDesC16 const &)
+	?TestExecuted@CStifTFw@@EAEXPAVCUIEngineContainer@@AAVTFullTestResult@@@Z @ 52 NONAME ; void CStifTFw::TestExecuted(class CUIEngineContainer *, class TFullTestResult &)
+	?TestSetL@CUIStore@@QAEABVCTestSetInfo@@ABVTDesC16@@@Z @ 53 NONAME ; class CTestSetInfo const & CUIStore::TestSetL(class TDesC16 const &)
+	?TestSets@CUIStore@@QAEHAAV?$RRefArray@VCTestSetInfo@@@@@Z @ 54 NONAME ; int CUIStore::TestSets(class RRefArray<class CTestSetInfo> &)
+	?UIEngineContainer@CStartedTestCase@@QBEAAVCUIEngineContainer@@XZ @ 55 NONAME ; class CUIEngineContainer & CStartedTestCase::UIEngineContainer(void) const
+	?UIStore@CUIStoreIf@@QAEAAVCUIStore@@XZ @ 56 NONAME ; class CUIStore & CUIStoreIf::UIStore(void)
+	?StartTestSet@CUIStore@@QAEHABVCTestSetInfo@@AAHW4TSetType@CStartedTestSet@@H@Z @ 57 NONAME ; int CUIStore::StartTestSet(class CTestSetInfo const &, int &, enum CStartedTestSet::TSetType, int)
+	?UpdateTestSet@CUIStore@@QAEHAAVCTestSetInfo@@@Z @ 58 NONAME ; int CUIStore::UpdateTestSet(class CTestSetInfo &)
+	?ReadFiltersL@CUIStore@@QAEXAAV?$RPointerArray@VTDesC16@@@@@Z @ 59 NONAME ; void CUIStore::ReadFiltersL(class RPointerArray<class TDesC16> &)
+	?GetTestSetsList@CUIStore@@QAEHAAV?$RRefArray@VTDesC16@@@@@Z @ 60 NONAME ; int CUIStore::GetTestSetsList(class RRefArray<class TDesC16> &)
+	?SaveTestSet2@CUIStore@@QAEHAAVTDes16@@@Z @ 61 NONAME ; int CUIStore::SaveTestSet2(class TDes16 &)
+	?UnloadTestSet@CUIStore@@QAEHABVTDesC16@@@Z @ 62 NONAME ; int CUIStore::UnloadTestSet(class TDesC16 const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/eabi/StifTFwIfu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,103 @@
+EXPORTS
+	_ZN10CStifTFwIf10AtsReceiveERK7TDesC16 @ 1 NONAME
+	_ZN10CStifTFwIf12GetTestCasesER13RPointerArrayI9CTestInfoER7TDesC16S5_ @ 2 NONAME
+	_ZN10CStifTFwIf12SetAttributeE10TAttributeRK7TDesC16 @ 3 NONAME
+	_ZN10CStifTFwIf13AddTestModuleER7TDesC16S1_ @ 4 NONAME
+	_ZN10CStifTFwIf13PauseTestCaseEi @ 5 NONAME
+	_ZN10CStifTFwIf13StartTestCaseERiRK9CTestInfo @ 6 NONAME
+	_ZN10CStifTFwIf14CancelTestCaseEi @ 7 NONAME
+	_ZN10CStifTFwIf14ResumeTestCaseEi @ 8 NONAME
+	_ZN10CStifTFwIf15AddTestCaseFileER7TDesC16S1_ @ 9 NONAME
+	_ZN10CStifTFwIf16RemoveTestModuleER7TDesC16 @ 10 NONAME
+	_ZN10CStifTFwIf18RemoveTestCaseFileER7TDesC16S1_ @ 11 NONAME
+	_ZN10CStifTFwIf4OpenER7TDesC16 @ 12 NONAME
+	_ZN10CStifTFwIf5CloseEv @ 13 NONAME
+	_ZN10CStifTFwIfC2Ev @ 14 NONAME
+	_ZN10CStifTFwIfD0Ev @ 15 NONAME
+	_ZN10CStifTFwIfD1Ev @ 16 NONAME
+	_ZN10CStifTFwIfD2Ev @ 17 NONAME
+	_ZN10CUIStoreIf10ConstructLEv @ 18 NONAME
+	_ZN10CUIStoreIf7UIStoreEv @ 19 NONAME
+	_ZN10CUIStoreIfC1Ev @ 20 NONAME
+	_ZN10CUIStoreIfC2Ev @ 21 NONAME
+	_ZN10CUIStoreIfD0Ev @ 22 NONAME
+	_ZN10CUIStoreIfD1Ev @ 23 NONAME
+	_ZN10CUIStoreIfD2Ev @ 24 NONAME
+	_ZN18CUIEngineContainer10CancelTestEv @ 25 NONAME
+	_ZN18CUIEngineContainer10ResumeTestEv @ 26 NONAME
+	_ZN18CUIEngineContainer9PauseTestEv @ 27 NONAME
+	_ZN8CStifTFw12TestExecutedEP18CUIEngineContainerR15TFullTestResult @ 28 NONAME
+	_ZN8CStifTFw13GoingToRebootEP18CUIEngineContainerR14TRequestStatus @ 29 NONAME
+	_ZN8CStifTFw9PrintProgEP18CUIEngineContainerR13TTestProgress @ 30 NONAME
+	_ZN8CStifTFw9RemoteMsgEP18CUIEngineContainerRK7TDesC16 @ 31 NONAME
+	_ZN8CUIStore11LoadTestSetERK7TDesC16 @ 32 NONAME
+	_ZN8CUIStore11SaveTestSetERK7TDesC16 @ 33 NONAME
+	_ZN8CUIStore12AbortTestSetER15CStartedTestSet @ 34 NONAME
+	_ZN8CUIStore12AddToTestSetERK7TDesC16RK9CTestInfo @ 35 NONAME
+	_ZN8CUIStore12StartTestSetERK12CTestSetInfoRiN15CStartedTestSet8TSetTypeE @ 36 NONAME
+	_ZN8CUIStore13AddTestModuleERK7TDesC16S2_ @ 37 NONAME
+	_ZN8CUIStore13CreateTestSetERK7TDesC16 @ 38 NONAME
+	_ZN8CUIStore13RemoveTestSetERK7TDesC16 @ 39 NONAME
+	_ZN8CUIStore13StartTestCaseERK9CTestInfoRi @ 40 NONAME
+	_ZN8CUIStore13TestCaseFilesER9RRefArrayI7TDesC16ERKS1_ @ 41 NONAME
+	_ZN8CUIStore14ListAllModulesER13RPointerArrayI7TDesC16E @ 42 NONAME
+	_ZN8CUIStore14LoadAllModulesEv @ 43 NONAME
+	_ZN8CUIStore15AddTestCaseFileERK7TDesC16S2_ @ 44 NONAME
+	_ZN8CUIStore15InsertToTestSetERK7TDesC16RK9CTestInfoi @ 45 NONAME
+	_ZN8CUIStore15StartedTestSetLEi @ 46 NONAME
+	_ZN8CUIStore15StartedTestSetsER9RRefArrayI15CStartedTestSetEi @ 47 NONAME
+	_ZN8CUIStore16RemoveTestModuleERK7TDesC16 @ 48 NONAME
+	_ZN8CUIStore16StartedTestCaseLEi @ 49 NONAME
+	_ZN8CUIStore16StartedTestCasesER9RRefArrayI16CStartedTestCaseEiRK7TDesC16S6_ @ 50 NONAME
+	_ZN8CUIStore17RemoveFromTestSetERK7TDesC16RK9CTestInfo @ 51 NONAME
+	_ZN8CUIStore18LoadSavedTestCasesEv @ 52 NONAME
+	_ZN8CUIStore18RemoveTestCaseFileERK7TDesC16S2_ @ 53 NONAME
+	_ZN8CUIStore4OpenERK7TDesC16 @ 54 NONAME
+	_ZN8CUIStore5CloseEv @ 55 NONAME
+	_ZN8CUIStore7ModulesER9RRefArrayI7TDesC16E @ 56 NONAME
+	_ZN8CUIStore8TestSetLERK7TDesC16 @ 57 NONAME
+	_ZN8CUIStore8TestSetsER9RRefArrayI12CTestSetInfoE @ 58 NONAME
+	_ZN8CUIStore9TestCasesER9RRefArrayI9CTestInfoERK7TDesC16S6_ @ 59 NONAME
+	_ZN9CTestInfo4NewLEv @ 60 NONAME
+	_ZNK16CStartedTestCase17UIEngineContainerEv @ 61 NONAME
+	_ZTI10CStifTFwIf @ 62 NONAME ; #<TI>#
+	_ZTI10CUIStoreIf @ 63 NONAME ; #<TI>#
+	_ZTI12CTestSetInfo @ 64 NONAME ; #<TI>#
+	_ZTI13CTestProgress @ 65 NONAME ; #<TI>#
+	_ZTI13CUIStorePopup @ 66 NONAME ; #<TI>#
+	_ZTI14CUIEngineEvent @ 67 NONAME ; #<TI>#
+	_ZTI15CStartedTestSet @ 68 NONAME ; #<TI>#
+	_ZTI15CUIEngineRemote @ 69 NONAME ; #<TI>#
+	_ZTI15CUIEngineRunner @ 70 NONAME ; #<TI>#
+	_ZTI16CStartedTestCase @ 71 NONAME ; #<TI>#
+	_ZTI16CUIEnginePrinter @ 72 NONAME ; #<TI>#
+	_ZTI18CUIEngineContainer @ 73 NONAME ; #<TI>#
+	_ZTI21CUIEngineErrorPrinter @ 74 NONAME ; #<TI>#
+	_ZTI8CStifTFw @ 75 NONAME ; #<TI>#
+	_ZTI8CUIStore @ 76 NONAME ; #<TI>#
+	_ZTI9CTestInfo @ 77 NONAME ; #<TI>#
+	_ZTI9CUIEngine @ 78 NONAME ; #<TI>#
+	_ZTV10CStifTFwIf @ 79 NONAME ; #<VT>#
+	_ZTV10CUIStoreIf @ 80 NONAME ; #<VT>#
+	_ZTV12CTestSetInfo @ 81 NONAME ; #<VT>#
+	_ZTV13CTestProgress @ 82 NONAME ; #<VT>#
+	_ZTV13CUIStorePopup @ 83 NONAME ; #<VT>#
+	_ZTV14CUIEngineEvent @ 84 NONAME ; #<VT>#
+	_ZTV15CStartedTestSet @ 85 NONAME ; #<VT>#
+	_ZTV15CUIEngineRemote @ 86 NONAME ; #<VT>#
+	_ZTV15CUIEngineRunner @ 87 NONAME ; #<VT>#
+	_ZTV16CStartedTestCase @ 88 NONAME ; #<VT>#
+	_ZTV16CUIEnginePrinter @ 89 NONAME ; #<VT>#
+	_ZTV18CUIEngineContainer @ 90 NONAME ; #<VT>#
+	_ZTV21CUIEngineErrorPrinter @ 91 NONAME ; #<VT>#
+	_ZTV8CStifTFw @ 92 NONAME ; #<VT>#
+	_ZTV8CUIStore @ 93 NONAME ; #<VT>#
+	_ZTV9CTestInfo @ 94 NONAME ; #<VT>#
+	_ZTV9CUIEngine @ 95 NONAME ; #<VT>#
+	_ZN8CUIStore12StartTestSetERK12CTestSetInfoRiN15CStartedTestSet8TSetTypeEi @ 96 NONAME
+	_ZN8CUIStore13UpdateTestSetER12CTestSetInfo @ 97 NONAME
+	_ZN8CUIStore12ReadFiltersLER13RPointerArrayI7TDesC16E @ 98 NONAME
+	_ZN8CUIStore15GetTestSetsListER9RRefArrayI7TDesC16E @ 99 NONAME
+	_ZN8CUIStore12SaveTestSet2ER6TDes16 @ 100 NONAME
+	_ZN8CUIStore13UnloadTestSetERK7TDesC16 @ 101 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/group/StifTFwIf.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's StifTfIf module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET      		StifTFwIf.dll
+TARGETTYPE  		dll
+
+
+CAPABILITY		ALL -TCB
+VENDORID 		0x101FB657
+SECUREID        0x102073DE
+
+
+DEFFILE     		StifTFwIf.def
+
+
+UID			0x1000007a
+
+USERINCLUDE     	../inc
+USERINCLUDE     	../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      	../src
+
+SOURCE          	StifTFwIf.cpp 
+SOURCE          	UIEngine.cpp
+SOURCE	    	    	UIEngineContainer.cpp
+SOURCE	    	    	UIEngineRunner.cpp
+SOURCE	    	    	UIEnginePrinter.cpp
+SOURCE	    	    	UIEngineError.cpp
+SOURCE	    	    	UIEngineEvent.cpp
+SOURCE	    	    	UIEngineRemote.cpp
+SOURCE	    	    	UIStore.cpp
+SOURCE	    	    	UIStoreContainer.cpp
+SOURCE	    	    	UIStorePopup.cpp
+
+LIBRARY			euser.lib
+LIBRARY     	   	stiftestengine.lib
+LIBRARY 		stiftestinterface.lib
+LIBRARY             	efsrv.lib
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for STIF Test Framework's 
+*	StifTFwIf.
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+	StifTFwIf.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/inc/Logging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains Logging macros for test combiner
+*
+*/
+
+#ifndef LOGGINGDEFS_H
+#define LOGGINGDEFS_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+
+// CONSTANTS
+const TUint KError              = 0x1;
+const TUint KInit               = 0x2;
+const TUint KPrint              = 0x4;
+const TUint KMessage            = 0x10;
+const TUint KFunction           = 0x20;
+const TUint KVerbose            = 0x40;
+const TUint KAlways             = 0xFFFFFFFF;
+const TUint KDebugLevel         = KAlways;//( KPrint | KError | KMessage | KFunction );
+
+// MACROS
+#define __TRACING_ENABLED
+
+#ifdef __TRACING_ENABLED
+
+     // Disable conditional expression is constant -warning
+    #pragma warning( disable : 4127 )
+
+    // General tracing function
+    #define __TRACE(level,p) if ( ( (level) & KDebugLevel ) && LOGGER )\
+                                          {LOGGER->Log p;}
+
+    // Direct RDebug::Print                            
+    #define __RDEBUG(p) if( KVerbose & KDebugLevel ){ RDebug::Print p ; } 
+
+
+     // Log function name
+    #define __TRACEFUNC() if( ( KFunction & KDebugLevel ) && LOGGER ){\
+                                const char* f = __FUNCTION__;\
+                                 TPtrC8 F((const unsigned char*)f);\
+                                 LOGGER->Log(F);}
+
+#else // __TRACING_ENABLED
+     // No tracing
+    #define __TRACE(level,p)
+    #define __RDEBUG(p)
+    #define __TRACEFUNC()
+#endif // __TRACING_ENABLED
+
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+#endif // LOGGINGDEFS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/inc/UIEngineError.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,139 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CUIEngineErrorPrinter.
+*
+*/
+
+#ifndef UI_ENGINE_ERROR_H
+#define UI_ENGINE_ERROR_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include "TestEngineClient.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+class CUIEngine;
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+
+// CUIEngineErrorPrinter is an active object which handles the error notifications
+// from the test framework.
+class CUIEngineErrorPrinter
+        :public CActive
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CUIEngineErrorPrinter* NewL( CUIEngine* aUIEngine );
+
+        /**
+        * Destructor of CTestCaseRunner.
+        */
+        virtual ~CUIEngineErrorPrinter();
+
+        /**
+        * Start
+        */
+        void StartL( RTestEngine& aTestCase );
+
+    public: // New functions
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+        /** 
+        * C++ default constructor.
+        */
+        CUIEngineErrorPrinter( CUIEngine* aUIEngine );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( );
+
+    private:   // Functions from base classes
+        // None
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to test case container
+        CUIEngine*                      iUIEngine;
+
+        // Testcase object handle
+        RTestEngine                     iTestEngine;
+        
+        // Test result package
+        TErrorNotification              iError;
+        TErrorNotificationPckg          iErrorPckg;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif // UI_ENGINE_ERROR_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/inc/UIEngineEvent.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,178 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CUIEngineEvent.
+*
+*/
+
+#ifndef STIF_TFW_IF_EVENT_H
+#define STIF_TFW_IF_EVENT_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifTestEventInterface.h>
+
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+class CUIEngine;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+
+// CUIEngineEvent is a class that is used to run test cases using
+// STIF Test Framework.
+class CUIEngineEvent
+        : public CActive
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // Object state
+        enum TEventState
+            {
+            EEventIdle,
+            EEventRequested,
+            EEventWait,
+            EEventWaitCompleted,
+            EEventReleased,
+            };
+
+    public: // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CUIEngineEvent* NewL( CUIEngine* aUIEngine );
+
+        /**
+        * Destructor of CUIEngineEvent.
+        */
+        ~CUIEngineEvent();
+
+    public: // New functions
+
+        /**
+        * Request request event.
+        */
+        TInt Request( TDesC& aEventName, TUint32 aMaster, TUint32 aSlave );
+
+        /**
+        * Release releases event.
+        */
+        TInt Release();
+        
+        /**
+        * Return master id.
+        */ 
+        TUint32 Master() const { return iMaster; }
+        
+        /**
+        * Return event name.
+        */ 
+        const TDesC& EventName() const { return iEvent.Name(); }
+
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive RunL handles request completion.
+        */
+        void RunL();
+
+        /**
+        * From CActive DoCancel handles request cancellation.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive RunError handles error situations.
+        */
+        TInt RunError( TInt aError );
+
+    protected: // New functions
+        // None
+
+    protected: // Functions from base classes
+        // None
+
+    private: // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CUIEngineEvent( CUIEngine* aUIEngine );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+
+    public: //Data
+        // None
+    
+    protected: // Data
+        // None
+
+    private: // Data
+    
+        // CUIEngineEvent State 
+        TEventState     iState;
+
+        // Pointer to UIEngine
+        CUIEngine*     iUIEngine;
+
+        // EventIf class for event control
+        TEventIf        iEvent;
+        TEventIfPckg    iEventPckg;
+        
+        // Master identifier
+        TUint32         iMaster;
+
+        // Slave identifier
+        TUint32         iSlave;
+
+    public: // Friend classes
+        // None
+
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        // None
+
+    };
+
+
+
+#endif // STIF_TFW_IF_EVENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/inc/UIEnginePrinter.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,147 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CUIEnginePrinter.
+*
+*/
+
+#ifndef STIF_TFW_IF_PRINTER_H
+#define STIF_TFW_IF_PRINTER_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <stifinternal/UIEngineContainer.h>
+
+// CONSTANTS
+
+// Interval for timer printing
+const TInt KPrintInterval = 1000000;
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+// None
+
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+
+// CUIEnginePrinter is an active object which handles the print notifications
+// from the test case.
+class CUIEnginePrinter
+        : public CActive
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CUIEnginePrinter* NewL( CUIEngineContainer* aUIEngineContainer );
+
+        /**
+        * Destructor of CTestCaseRunner.
+        */
+        virtual ~CUIEnginePrinter();
+
+        /**
+        * Start
+        */
+        void StartL( RTestCase& aTestCase );
+
+    public: // New functions
+    
+        inline TBool IsRunning(){ return iRunning; };
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+        /** 
+        * C++ default constructor.
+        */
+        CUIEnginePrinter( CUIEngineContainer* aUIEngineContainer );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( );
+
+    private:   // Functions from base classes
+        // None
+
+    public:   //Data
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to test case container
+        CUIEngineContainer*             iUIEngineContainer;
+
+        // Testcase object handle
+        RTestCase                       iTestCase;
+        
+        // Test result package
+        TTestProgress                   iProgress;
+        TTestProgressPckg               iProgressPckg;
+        
+        TBool                           iRunning;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+
+#endif // STIF_TFW_IF_PRINTER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/inc/UIEngineRemote.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,165 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CUIEngineRemote.
+*
+*/
+
+
+#ifndef STIF_TFW_IF_REMOTE_H
+#define STIF_TFW_IF_REMOTE_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <stifinternal/UIEngineContainer.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+// None
+
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+
+// CUIEngineRemote is a class that is used for remote protocol 
+// forwarding.
+class CUIEngineRemote
+        :public CActive
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TRemoteStatus
+            {
+            EIdle,
+            EPending,
+            EUIMsgPending,
+            };
+
+    public: // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CUIEngineRemote* NewL( CUIEngineContainer* aUIEngineContainer );
+
+        /**
+        * Destructor of CUIEngineRemote.
+        */
+        ~CUIEngineRemote();
+
+    public: // New functions
+
+        /**
+        * StartL starts testing.
+        */
+        void StartL( RTestCase& aTestCase );
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive RunL handles request completion.
+        */
+        void RunL();
+
+        /**
+        * From CActive DoCancel handles request cancellation.
+        */
+        void DoCancel();
+        /**
+        * RunError derived from CActive handles errors from active object 
+        * handler.
+        */        
+        TInt RunError(TInt aError);
+
+    protected: // New functions
+        // None
+
+    protected: // Functions from base classes
+        // None
+
+    private: // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CUIEngineRemote( CUIEngineContainer* aUIEngineContainer);
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+
+        /**
+        * Start request.
+        */
+        void Start();
+
+    public: //Data
+        // None
+    
+    protected: // Data
+        // None
+
+    private: // Data
+
+        // Pointer to UIEngine
+        CUIEngineContainer*             iUIEngineContainer;
+
+        // Handle to Test Case
+        RTestCase                       iTestCase;
+        
+        // Protocol message type
+        TStifCommand                    iRemoteType;
+        TStifCommandPckg                iRemoteTypePckg;
+
+        // Protocol message length
+        TInt                            iMsgLen;
+        TPckg<TInt>                     iMsgLenPckg;
+
+        TRemoteStatus                   iState;
+    public: // Friend classes
+        // None
+
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        // None
+
+    };
+
+
+
+#endif // STIF_TFW_IF_REMOTE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/inc/UIEngineRunner.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,150 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CUIEngineRunner.
+*
+*/
+
+
+#ifndef STIF_TFW_IF_RUNNER_H
+#define STIF_TFW_IF_RUNNER_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <stifinternal/UIEngineContainer.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+// None
+
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+
+// CUIEngineRunner is a class that is used to run test cases using
+// STIF Test Framework.
+class CUIEngineRunner
+        : public CActive
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public: // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CUIEngineRunner* NewL( CUIEngineContainer* aUIEngineContainer );
+
+        /**
+        * Destructor of CUIEngineRunner.
+        */
+        ~CUIEngineRunner();
+
+    public: // New functions
+
+        /**
+        * StartTestL starts testing.
+        */
+        void StartL( RTestCase& aTestCase );
+        
+        /**
+        * Test result.
+        */
+        inline TFullTestResult& FullResult(){ return iFullTestResult; };
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive RunL handles request completion.
+        */
+        void RunL();
+
+        /**
+        * From CActive DoCancel handles request cancellation.
+        */
+        void DoCancel();
+
+    protected: // New functions
+        // None
+
+    protected: // Functions from base classes
+        // None
+
+    private: // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CUIEngineRunner( CUIEngineContainer* aUIEngineContainer);
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+
+    public: //Data
+        // None
+    
+    protected: // Data
+        // None
+
+    private: // Data
+
+        // Pointer to UIEngine
+        CUIEngineContainer*            iUIEngineContainer;
+
+        // Handle to Test Case
+        RTestCase                       iTestCase;
+        
+        // Test result and package
+        TFullTestResult                 iFullTestResult;
+        TFullTestResultPckg             iFullTestResultPckg;
+
+    public: // Friend classes
+        // None
+
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        // None
+
+    };
+
+
+
+#endif // STIF_TFW_IF_RUNNER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/inc/UIStorePopup.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,182 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CUIStorePopup.
+*
+*/
+
+#ifndef STIF_TFW_IF_REMOTE_H
+#define STIF_TFW_IF_REMOTE_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <stifinternal/UIStore.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+// None
+
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+
+// CUIStorePopup is a class that is used for remote protocol 
+// forwarding.
+class CUIStorePopup
+        :public CActive
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public: // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CUIStorePopup* NewL( CUIStore* aUIStore,
+                                    CUIEngineContainer* aContainer,
+                                    CStifTFwIfProt* aRemoteMsg,
+                                    CUIStore::TPopupPriority aPopupPriority,
+                                    const TDesC& aMsg );
+
+        /**
+        * Destructor of CUIStorePopup.
+        */
+        ~CUIStorePopup();
+
+    public: // New functions
+    
+        TInt Start( const TDesC& aLine1, 
+                    const TDesC& aLine2 );
+                    
+        inline const CUIEngineContainer* Container()
+            { return iContainer; };
+        
+        inline TBool IsEventPopup()
+            { return ( iRemoteMsg->iCmdType == 
+                       CStifTFwIfProt::ECmdRequest ); }
+        
+        // Returns message
+        inline TDesC& GetMessage()
+            { 
+            if( iMsg == NULL )
+                {
+                User::Panic( _L("iMsg was NULL"), -1 );
+                }
+            return *iMsg;
+            };
+
+        // Returns popup priority
+        inline const CUIStore::TPopupPriority GetPriority()
+            { 
+            return iPopupPriority;
+            };
+        
+    public: // Functions from base classes
+
+        /**
+        * From CActive RunL handles request completion.
+        */
+        void RunL();
+
+        /**
+        * From CActive DoCancel handles request cancellation.
+        */
+        void DoCancel();
+
+    protected: // New functions
+        // None
+
+    protected: // Functions from base classes
+        // None
+
+    private: // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CUIStorePopup( CUIStore* aUIStore,
+                       CUIEngineContainer* aContainer,
+                       CStifTFwIfProt* aRemoteMsg,
+                       CUIStore::TPopupPriority aPopupPriority);
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aMsg );
+
+
+    public: //Data
+        // None
+    
+    protected: // Data
+        // None
+
+    private: // Data
+
+        // Pointer to UIEngine
+        CUIStore*                       iUIStore;
+
+        // Protocol message
+        CStifTFwIfProt*                 iRemoteMsg;
+        
+        // Keycode of the pressed key
+        TKeyCode                        iKey;
+        
+        // test case waiting our response
+        CUIEngineContainer*             iContainer;
+        
+        TInt                            iPopupWindow;
+        
+        // Popup priority
+        CUIStore::TPopupPriority        iPopupPriority;
+        
+        // Popup message
+        HBufC                           * iMsg;
+        
+    public: // Friend classes
+        // None
+
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        // None
+
+    };
+
+
+
+#endif // STIF_TFW_IF_REMOTE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/StifTFwIf.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1845 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CStifTFwIf: This object executes test cases from 
+* STIF Test Framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include "UIEngineEvent.h"
+#include <stifinternal/UIEngineContainer.h>
+#include "StifTFwIf.h"
+#include "StifTFw.h"
+#include "Logging.h"
+#include "StifPython.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iStifTFw->iLogger
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: CStifTFwIf
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifTFwIf::CStifTFwIf()
+    {
+    __RDEBUG( _L( "CStifTFwIf::CStifTFwIf()" ) );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: ~CStifTFwIf
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifTFwIf::~CStifTFwIf()
+    {
+    __RDEBUG( _L( "CStifTFwIf::~CStifTFwIf()" ) );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: Open
+
+    Description: Open test engine.
+
+    Parameters: TDesC& aTestFrameworkIni: in: Initialization file to Test Framework
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::Open( TDesC& aTestFrameworkIni )
+    {
+    RDebug::Print(_L("CStifTFwIf::Open"));
+    TInt err( KErrNone );
+    TRAP( err,
+        iStifTFw = CStifTFw::NewL( this );
+        )
+
+    return iStifTFw->iUIEngine->Open( aTestFrameworkIni );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: Close
+
+    Description: Close test engine.
+
+    Parameters: None
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::Close()
+    {
+    RDebug::Print(_L("CStifTFwIf::Close"));
+
+    iStifTFw->DeleteData(); //Delete objects before closing session to TestEngine server
+    iStifTFw->iUIEngine->Close();
+
+    delete iStifTFw;
+    iStifTFw = 0;
+
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: SetAttribute
+
+    Description: Used to set attributes for Test Framework.
+
+    Parameters: TAttribute aAttribute: in: Attribute type
+                TDesC& aValue: in: Attribute value
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::SetAttribute( TAttribute aAttribute,
+                                        const TDesC& aValue )
+    {
+    RDebug::Print(_L("CStifTFwIf::SetAttribute"));
+    // Check aValue max length
+    if( aValue.Length() > KMaxName )
+        {
+        __TRACE( KPrint, ( CStifLogger::EError, _L( "CStifTFwIf::SetAttribute() method's second parameter length is incorrect" ) ) );
+        return KErrArgument;
+        }
+
+    TInt ret = iStifTFw->iUIEngine->TestEngine().SetAttribute( aAttribute, aValue );
+
+    if ( ret != KErrNone )
+        {
+        __TRACE( KPrint, ( _L( "CStifTFwIf::SetAttribute() method fails with error:%d" ), ret  ) );
+        return ret;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: AddTestModule
+
+    Description: Add test module to module list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which is added to module list
+                TDesC& aIniFile: in: Initialization file to the test module
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::AddTestModule( TDesC& aModuleName,
+                                         TDesC& aIniFile )
+    {
+    RDebug::Print(_L("CStifTFwIf::AddTestModule"));
+
+    return iStifTFw->iUIEngine->AddTestModule( aModuleName, aIniFile );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: RemoveTestModule
+
+    Description: Add test module to module list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which is removed of module list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::RemoveTestModule( TDesC& aModuleName )
+    {
+    RDebug::Print(_L("CStifTFwIf::RemoveTestModule"));
+
+    return iStifTFw->iUIEngine->RemoveTestModule( aModuleName );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: AddTestCaseFile
+
+    Description: Add test case file to test case file list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which own test cases of test case list.
+                TDesC& aCaseFile: in: Test case list, which is added to test case list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::AddTestCaseFile( TDesC& aModuleName, TDesC& aCaseFile )
+    {
+    RDebug::Print(_L("CStifTFwIf::AddTestCaseFile"));
+
+    return iStifTFw->iUIEngine->AddTestCaseFile( aModuleName, aCaseFile );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: RemoveTestCaseFile
+
+    Description: Remove test case file of test case file list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which own test cases of test case list
+                TDesC& aCaseFile: in: Test case list, which is removed of test case list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::RemoveTestCaseFile( TDesC& aModuleName, TDesC& aCaseFile )
+    {
+    RDebug::Print(_L("CStifTFwIf::RemoveTestCaseFile"));
+
+    return iStifTFw->iUIEngine->RemoveTestCaseFile( aModuleName, aCaseFile );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: GetTestCases
+
+    Description: Get test cases of enumerated list of test engine. Method is copied
+                 list of test cases to aTestCaseInfo. Copied tests are test cases
+                 of test module (aTestModule) and defined
+                 in test case file (aTestCaseFile), which are given as argument
+
+                 Method copied all enumerated test cases if aTestModule
+                 and aTestCaseFile are not defined
+
+    Parameters: RPointerArray<CTestInfo>& aTestCaseInfo: inout: List of test cases
+                TDesC& aModuleName: in: Testmodule, which own test cases of test case list
+                TDesC& aTestCaseFile: in: Test case list, which is got of test case list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::GetTestCases( RPointerArray<CTestInfo>& aTestCaseInfo,
+                                        TDesC& aTestModule,
+                                        TDesC& aTestCaseFile )
+    {
+    RDebug::Print(_L("CStifTFwIf::GetTestCases"));
+
+    TRAPD( ret,
+        ret = iStifTFw->iUIEngine->GetTestCasesL( aTestCaseInfo,
+                                                  aTestModule,
+                                                  aTestCaseFile );
+        );
+
+    return ret;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: StartTestCase
+
+    Description: Start test case execution.
+
+    Parameters: TInt& aTestId: in: ID for test case. Test ID given of address of
+                current CStifTFwIfContainer.
+
+                const CTestInfo& aTestInfo: in: Test case information
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::StartTestCase( TInt& aTestId,
+                                         const CTestInfo& aTestInfo )
+    {
+    RDebug::Print(_L("CStifTFwIf::StartTestCase"));
+
+    CUIEngineContainer* container = NULL;
+
+    TInt ret = iStifTFw->iUIEngine->StartTestCase( container,
+                                                   aTestInfo );
+
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+
+    // Add container to test case execution table
+    ret = iStifTFw->iTestExecutionTable.Append( container );
+    if( ret != KErrNone )
+        {
+        iStifTFw->iUIEngine->AbortStartedTestCase( container );
+        return ret;
+        }
+
+    // Get test id.
+    aTestId = (TInt)container;
+
+    __TRACE( KPrint, (  _L( "aTestId: %d"), aTestId ) );
+    __TRACE( KPrint, (  _L( "aTest case: %S"), &(aTestInfo.TestCaseTitle()) ) );
+
+    return ret;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: CancelTestCase
+
+    Description: Cancel test case execution
+
+    Parameters: TInt& aTestId: in: ID for test case
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::CancelTestCase( TInt aTestId )
+    {
+    RDebug::Print(_L("CStifTFwIf::CancelTestCase"));
+    TInt ret(KErrNone);
+
+    // Find test case from execution table
+    TInt index = iStifTFw->iTestExecutionTable.Find( ( CUIEngineContainer* )aTestId );
+
+    // Check if test id is found
+    if( index < 0)
+        {
+        __TRACE( KPrint, (  _L( "CStifTFwIf::CancelTestCase. Container not found. TestId = %d"), aTestId ) );
+
+        return index;
+        }
+
+    // Cancel test
+    ret = iStifTFw->iTestExecutionTable[index]->CancelTest();
+    __TRACE( KPrint, (  _L( "CStifTFwIf::CancelTestCase. Canceled testId %d"), aTestId ) );
+
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: PauseTestCase
+
+    Description: Pause test case execution
+
+    Parameters: TInt& aTestId: in: ID for test case
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::PauseTestCase(  TInt aTestId  )
+    {
+    RDebug::Print(_L("CStifTFwIf::PauseTestCase"));
+    TInt ret(KErrNone);
+
+    // Find test case from execution table
+    TInt index = iStifTFw->iTestExecutionTable.Find( ( CUIEngineContainer*) aTestId );
+
+    // Check if test id is found
+    if( index < 0 )
+        {
+        __TRACE( KPrint, (  _L( "CStifTFwIf::PauseTestCase. Container not found: testId = %d"), aTestId ) );
+
+        return index;
+        }
+
+    // Pause test
+    ret = iStifTFw->iTestExecutionTable[index]->PauseTest();
+
+    __TRACE( KPrint, (  _L( "CStifTFwIf::PauseTest. Paused testId %d"), aTestId ) );
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: ResumeTestCase
+
+    Description: Resume test case execution
+
+    Parameters: TInt& aTestId: in: ID for test case
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::ResumeTestCase( TInt aTestId )
+    {
+    RDebug::Print(_L("CStifTFwIf::ResumeTestCase"));
+    TInt ret(KErrNone);
+
+    // Find test case from execution table
+    TInt index = iStifTFw->iTestExecutionTable.Find( ( CUIEngineContainer* ) aTestId );
+
+    // Check if test id is found
+    if( index < 0 )
+        {
+        __TRACE( KPrint, (  _L( "CStifTFwIf::ResumeTestCase. Container not found: TestId = %d"), aTestId ) );
+
+        return index;
+        }
+
+    // Resume test
+    ret = iStifTFw->iTestExecutionTable[index]->ResumeTest();
+
+    __TRACE( KPrint, ( _L( "CStifTFwIf::ResumeTestCase. Resumed testId %d"), aTestId ) );
+
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: AtsReceive
+
+    Description: Handles remote protocol message receives
+
+    Parameters: const TDesC& aMessage: in: Protocol message received
+
+    Return Values: Symbian OS error code: In oom and is protocol message header
+        parsing fails, i.e. error in <msgtype> <srcid> <dstid>
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIf::AtsReceive( const TDesC& aMessage )
+    {
+    RDebug::Print(_L("CStifTFwIf::AtsReceive"));
+
+    CStifTFwIfProt* msg = NULL;
+    CStifTFwIfProt* resp = NULL;
+    TRAPD( err, msg = CStifTFwIfProt::NewL(); );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+    TRAP( err, resp = CStifTFwIfProt::NewL(); );
+    if( err != KErrNone )
+        {
+        delete msg;
+        return err;
+        }
+    TInt error = KErrNone;
+    TInt ret = KErrNone;
+
+    // Parse received message
+    TRAP( err,
+        error = msg->SetL( aMessage )
+    );
+    if( err != KErrNone )
+        {
+        __TRACE( KError, ( _L( "AtsReceive: message header parsing failed [%d]"), err ) );
+        delete msg;
+        delete resp;
+        return err;
+        }
+
+    // Create response
+    TRAP( err, resp->CreateL(); );
+    if( err != KErrNone )
+        {
+        delete msg;
+        delete resp;
+        return err;
+        }
+
+    resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgResponse );
+
+    if( error != KErrNone )
+        {
+        __TRACE( KError, ( _L( "AtsReceive: message parsing failed [%d]"), error ) );
+        resp->AppendId( SETID( DevId(), 0 ) );
+        resp->AppendId( msg->SrcId() );
+        resp->Append( CStifTFwIfProt::MsgType, msg->iMsgType );
+        resp->Append( CStifTFwIfProt::RespParam, CStifTFwIfProt::ERespResult, error );
+        AtsSend( resp->Message() );
+
+        // Error reported with protocol message, return success
+        delete msg;
+        delete resp;
+        return KErrNone;
+        }
+
+    switch( msg->iMsgType )
+        {
+        case CStifTFwIfProt::EMsgReserve:
+            {
+            if( msg->iRemoteType != CStifTFwIfProt::ERemotePhone )
+                {
+                __TRACE( KError, ( _L( "AtsReceive: reserve for illegal type received") ) );
+                error = KErrGeneral;
+                }
+            // Check IDs
+            if( ( msg->SrcDevId() == 0 ) ||
+                ( msg->SrcTestId() == 0 ) )
+                {
+                __TRACE( KError, ( _L( "AtsReceive: reserve for illegal srcid received") ) );
+                error = KErrGeneral;
+                }
+            if( msg->DstId() != 0 )
+                {
+                // Not a broadcast
+                if( ( msg->DstDevId() != DevId() ) ||
+                    ( msg->DstTestId() != 0 ) )
+                    {
+                    __TRACE( KError, ( _L( "AtsReceive: reserve for illegal dstid received") ) );
+                    error = KErrGeneral;
+                    }
+                }
+            TInt index = iStifTFw->iMasterArray.Find( msg->SrcId() );
+            if( index >= 0 )
+                {
+                error = KErrInUse;
+                __TRACE( KError, ( _L( "AtsReceive: master has already reserved slave") ) );
+                }
+            else
+                {
+                iStifTFw->iMasterArray.Append( msg->SrcId() );
+                }
+
+            resp->AppendId( SETID( DevId(), 0 ) );
+            resp->AppendId( msg->SrcId() );
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgReserve );
+            if( error != KErrNone )
+                {
+                resp->Append( CStifTFwIfProt::RespParam, CStifTFwIfProt::ERespResult, error );
+                }
+            AtsSend( resp->Message() );
+
+            }
+            break;
+        case CStifTFwIfProt::EMsgRelease:
+            {
+            // Check protocol ids
+            if( ( msg->SrcDevId() == 0 ) ||
+                ( msg->SrcTestId() == 0 ) ||
+                ( msg->DstTestId() != 0 ) )
+                {
+                __TRACE( KError, ( _L( "AtsReceive: release for illegal srcid or dstid received") ) );
+                error = KErrGeneral;
+                }
+            else if( msg->DstDevId() != DevId() )
+                {
+                __TRACE( KError, ( _L( "AtsReceive: release for illegal dstid received") ) );
+                error = KErrNotFound;
+                }
+            else
+                {
+                // Check Master identifier
+                // First check that specific master has reserved us
+                TInt index = iStifTFw->iMasterArray.Find( msg->SrcId() );
+                if( index < 0 )
+                    {
+                    error = KErrNotFound;
+                    }
+                else
+                    {
+                    // Search test case from execution table
+                    TInt count = iStifTFw->iTestRemoteExecutionTable.Count();
+                    for( TInt ind = 0; ind < count; ind++ )
+                        {
+                        if( iStifTFw->iTestRemoteExecutionTable[ind]->RemoteId() ==
+                            msg->SrcId() )
+                            {
+                            __TRACE( KError, (  _L( "Release: test case running for %x"),
+                                msg->SrcId() ) );
+                            error = KErrInUse;
+                            break;
+                            }
+                        }
+                    if( error == KErrNone )
+                        {
+                        iStifTFw->iMasterArray.Remove( index );
+                        }
+                    }
+                }
+
+            resp->AppendId( msg->DstId() );
+            resp->AppendId( msg->SrcId() );
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRelease );
+
+            if( error != KErrNone )
+                {
+                resp->Append( CStifTFwIfProt::RespParam, CStifTFwIfProt::ERespResult, error );
+                }
+            AtsSend( resp->Message() );
+            }
+            break;
+        case CStifTFwIfProt::EMsgRemote:
+            {
+            // Check protocol ids
+            TInt index = iStifTFw->iMasterArray.Find( msg->SrcId() );
+            if( ( msg->SrcDevId() == 0 ) ||
+                ( msg->SrcTestId() == 0 ) ||
+                ( msg->DstDevId() == 0 ) )
+                {
+                __TRACE( KError, ( _L( "AtsReceive: remote for illegal srcid or dstid received") ) );
+                error = KErrGeneral;
+                }
+            else if( index < 0 )
+                {
+                __TRACE( KError, ( _L( "AtsReceive: remote for illegal srcid received") ) );
+                error = KErrNotFound;
+                }
+            else
+                {
+
+                __TRACE( KError, ( _L( "AtsReceive: Call AtsRemote") ) );
+                RDebug::Print(_L("CStifTFwIf::AtsReceive remote command received, calling AtsRemote"));
+                error = iStifTFw->AtsRemote( *msg, *resp );
+                RDebug::Print(_L("CStifTFwIf::AtsReceive remote command received, AtsRemote return"));
+                }
+
+            if( error != KErrNone )
+                {
+                resp->AppendId( msg->DstId() );
+                resp->AppendId( msg->SrcId() );
+                resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+                resp->Append( CStifTFwIfProt::CmdType, msg->iCmdType );
+                resp->Append( CStifTFwIfProt::RespParam,
+                             CStifTFwIfProt::ERespResult,
+                             error );
+                }
+            AtsSend( resp->Message() );
+            }
+            break;
+        case CStifTFwIfProt::EMsgResponse:
+            {
+            // Responses ae forwarded to master
+            CUIEngineContainer* container = NULL;
+            TInt count = iStifTFw->iTestRemoteExecutionTable.Count();
+            TInt index = 0;
+            for( index = 0 ; index < count; index++ )
+                {
+                if( iStifTFw->iTestRemoteExecutionTable[index]->MasterId() ==
+                    msg->SrcId() )
+                    {
+                    __TRACE( KError, (  _L( "Response for %x"),
+                        msg->SrcId() ) );
+                    container = iStifTFw->iTestRemoteExecutionTable[index];
+                    break;
+                    }
+                }
+            if( container == NULL )
+                {
+                count = iStifTFw->iTestExecutionTable.Count();
+                for( index = 0 ; index < count; index++ )
+                    {
+                    if( iStifTFw->iTestExecutionTable[index]->MasterId() ==
+                        msg->DstId() )
+                        {
+                        __TRACE( KError, (  _L( "Response for %x"),
+                            msg->SrcId() ) );
+                        container = iStifTFw->iTestExecutionTable[index];
+                        break;
+                        }
+                    }
+                }
+
+            if( container == NULL )
+                {
+                __TRACE( KError, ( _L( "AtsReceive: response to srcid %x that is not a running master"),
+                    msg->SrcId() ) );
+                ret = KErrNotFound;
+                }
+            else
+                {
+                ret = container->RemoteReceive( aMessage );
+                }
+            }
+            break;
+        default:
+            __TRACE( KError, ( _L( "AtsReceive: invalid message")) );
+            ret = KErrNotSupported;
+        }
+
+    delete msg;
+    delete resp;
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    CStifTFw: This object executes test cases from STIF Test Framework.
+
+-------------------------------------------------------------------------------
+*/
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iLogger
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: NewL
+
+    Description: Construct the CStifTFw class
+
+    Parameters: None
+
+    Return Values: CStifTFw*                    New object
+
+    Errors/Exceptions: Leaves if memory allocation fails or
+                       ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStifTFw* CStifTFw::NewL( CStifTFwIf* aStifTFwIf )
+    {
+    RDebug::Print(_L("CStifTFw::NewL"));
+
+    CStifTFw* self = new ( ELeave ) CStifTFw( aStifTFwIf );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves on error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CStifTFw::ConstructL()
+    {
+    RDebug::Print(_L("CStifTFw::ConstructL"));
+
+    iUIEngine = CUIEngine::NewL( (CUIIf*) this );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: CStifTFw
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStifTFw::CStifTFw( CStifTFwIf* aStifTFwIf ):
+    iStifTFwIf( aStifTFwIf )
+    {
+
+    __RDEBUG( _L( "CStifTFw::CStifTFw()" ) );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: ~CStifTFwIf
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStifTFw::~CStifTFw()
+    {
+    __RDEBUG( _L( "CStifTFw::~CStifTFw() begin" ) );
+
+    RDebug::Print(_L("CStifTFw::~CStifTFw resetting iTestExecutionTable cnt=%d"), iTestExecutionTable.Count());
+    iTestExecutionTable.Reset();
+    RDebug::Print(_L("CStifTFw::~CStifTFw resetting iTestRemoteExecutionTable cnt=%d"), iTestRemoteExecutionTable.Count());
+    iTestRemoteExecutionTable.Reset();
+    RDebug::Print(_L("CStifTFw::~CStifTFw resetting iEventArray cnt=%d"), iEventArray.Count());
+    iEventArray.ResetAndDestroy();
+    RDebug::Print(_L("CStifTFw::~CStifTFw resetting iMasterArray cnt=%d"), iMasterArray.Count());
+    iMasterArray.Reset();
+
+    RDebug::Print(_L("CStifTFw::~CStifTFw closing iTestExecutionTable cnt=%d"), iTestExecutionTable.Count());
+    iTestExecutionTable.Close();
+    RDebug::Print(_L("CStifTFw::~CStifTFw closing iTestRemoteExecutionTable cnt=%d"), iTestRemoteExecutionTable.Count());
+    iTestRemoteExecutionTable.Close();
+    RDebug::Print(_L("CStifTFw::~CStifTFw closing iEventArray cnt=%d"), iEventArray.Count());
+    iEventArray.Close();
+    RDebug::Print(_L("CStifTFw::~CStifTFw closing iMasterArray cnt=%d"), iMasterArray.Count());
+    iMasterArray.Close();
+
+    //Moved from the beginning of destructor, because objects from some arrays during resetting and/or closing
+    //have tried to call methods of iUIEngine.
+    RDebug::Print(_L("CStifTFw::~CStifTFw deleteing iUiEngine address=%d"), iUIEngine);
+    delete iUIEngine;
+
+    RDebug::Print(_L("CStifTFw::~CStifTFw end"));
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: AtsRemote
+
+    Description: Remote ATS call
+
+    Parameters: const TDesC& aMessage: in:
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifTFw::AtsRemote( CStifTFwIfProt& aReq, CStifTFwIfProt& aResp )
+    {
+    RDebug::Print(_L("CStifTFw::AtsRemote start, iCmdType=%d "), aReq.iCmdType);
+
+    TInt ret = KErrNone;
+
+    switch( aReq.iCmdType )
+        {
+        case CStifTFwIfProt::ECmdRun:
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemote iCmdType CStifTFwIfProt::ECmdRun "));
+            ret = AtsRemoteRun( aReq, aResp );
+            break;
+            }
+        case CStifTFwIfProt::ECmdPause:
+        case CStifTFwIfProt::ECmdResume:
+        case CStifTFwIfProt::ECmdCancel:
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemote iCmdType CStifTFwIfProt::ECmdPause,Resume,Cancel "));
+            ret = AtsRemoteTestCtl( aReq, aResp );
+            break;
+            }
+        case CStifTFwIfProt::ECmdRequest:
+        case CStifTFwIfProt::ECmdRelease:
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemote iCmdType CStifTFwIfProt::ECmdRequest,Release "));
+            ret = AtsRemoteEventCtl( aReq, aResp );
+            break;
+            }
+        case CStifTFwIfProt::ECmdSetEvent:
+        case CStifTFwIfProt::ECmdUnsetEvent:
+        	{
+            RDebug::Print(_L("CStifTFw::AtsRemote iCmdType CStifTFwIfProt::ECmdSetEvent,Unset start "));
+            ret = AtsRemoteEventCtl( aReq, aResp );
+            RDebug::Print(_L("CStifTFw::AtsRemote iCmdType CStifTFwIfProt::ECmdSetEvent,Unset end "));
+            break;
+			}
+        default:
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemote iCmdType UNSUPPORTED value=%d "), aReq.iCmdType);
+            return KErrNotSupported;
+            }
+        }
+
+    return ret;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFw
+
+     Method: GetCaseNumByTitle
+
+     Description: Enumerates test cases from given module and finds test case index by title
+
+     Parameters:    TDesC& aModule: in: module name
+                    TDesC& aTestCaseFile: in: cfg file
+	                TDesC& aTitle: in: test case title
+                    TInt& aCaseNum: in out: test case index
+
+     Return Values: KErrNone if everything is ok
+                    KErrNotFound if there is no such test case
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifTFw::GetCaseNumByTitle(TDesC& aModule, TDesC& aTestCaseFile, TDesC& aTitle, TInt& aCaseNum)
+    {
+    RDebug::Print(_L("CStifTFw::GetCaseNumByTitle looking for test case number module=[%S] cfg=[%S] title=[%S]"), &aModule, &aTestCaseFile, &aTitle);
+	//Allocate table
+    RPointerArray<CTestInfo> allTestInfos;
+    CleanupClosePushL(allTestInfos);
+    TInt ret = KErrNone;
+
+    //Enumerate test cases
+    RDebug::Print(_L("CStifTFw::GetCaseNumByTitle enumerating test cases"));
+    if(aTestCaseFile == _L("dummy.cfg"))
+        {
+		TName t = _L("");
+        ret = iStifTFwIf->GetTestCases(allTestInfos, aModule, t);
+		}
+    else
+        {
+        ret = iStifTFwIf->GetTestCases(allTestInfos, aModule, aTestCaseFile);
+		}
+
+    if(ret != KErrNone)
+        {
+		RDebug::Print(_L("Test cases enumeration from module [%S] and file [%S] has returned an error %d"), &aModule, &aTestCaseFile, ret);
+		}
+    else
+        {
+		//Searching through the table
+        RDebug::Print(_L("CStifTFw::GetCaseNumByTitle searching through the test cases table containing %d cases"), allTestInfos.Count());
+        ret = KErrNotFound;
+        for(TInt i = 0; i < allTestInfos.Count(); i++)
+            {
+            if(allTestInfos[i]->TestCaseTitle() == aTitle)
+                {
+                aCaseNum = i;
+                //TestScripter relies on 1-based indexing
+                if((aModule.Find(KTestScripterName) != KErrNotFound) || (aModule.Find(KPythonScripter) != KErrNotFound) || (aModule.Find(KTestCombinerName) != KErrNotFound)) 
+                    aCaseNum++;
+                ret = KErrNone;
+                break;
+                }
+            }
+		}
+	if(ret == KErrNotFound)
+	    {
+        RDebug::Print(_L("CStifTFw::GetCaseNumByTitle test case not found"));
+		}
+	else if(ret == KErrNone)
+	    {
+        RDebug::Print(_L("CStifTFw::GetCaseNumByTitle test case number found: %d"), aCaseNum);
+		}
+	else
+	    {
+        RDebug::Print(_L("CStifTFw::GetCaseNumByTitle error %d"), ret);
+		}
+
+    //Some cleaning
+    allTestInfos.Reset();
+    CleanupStack::PopAndDestroy();
+
+    return ret;
+    }
+
+/*
+    Class: CStifTFw
+
+    Method: AtsRemoteRun
+
+    Description: Remote run ATS call
+
+    Parameters: const TDesC& aMessage: in:
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifTFw::AtsRemoteRun( CStifTFwIfProt& aReq, CStifTFwIfProt& aResp )
+    {
+    RDebug::Print(_L("CStifTFw::AtsRemoteRun start"));
+
+    TInt ret = KErrNone;
+    TUint16 testid = 0;
+
+    if( ( aReq.DstDevId() == 0 ) ||
+        ( aReq.DstTestId() != 0 ) )
+        {
+        RDebug::Print(_L("CStifTFw::AtsRemoteRun Protocol violation"));
+        // Protocol violation
+        __TRACE( KError, ( _L( "AtsReceive: remote run for illegal dstid received") ) );
+        return KErrGeneral;
+        }
+
+    if ( aReq.DstDevId() != iStifTFwIf->DevId() )
+        {
+        RDebug::Print(_L("CStifTFw::AtsRemoteRun Not our protocol message"));
+        // Not our protocol message
+        __TRACE( KError, ( _L( "AtsReceive: remote run for illegal dstdevid received") ) );
+        return KErrNotFound;
+        }
+
+
+    if( aReq.iModule.Length() == 0 )
+        {
+        RDebug::Print(_L("CStifTFw::AtsRemoteRun No test module name given"));
+        __TRACE( KError, ( _L("No mandatory test module name given as run parameter") ) );
+        ret = KErrNotFound;
+        }
+    else if(aReq.iTestCaseNumber < 0 && aReq.iTitle.Length() == 0)
+        {
+        RDebug::Print(_L("CStifTFw::AtsRemoteRun No test case number given"));
+        __TRACE( KError, ( _L("No mandatory test case number given as run parameter") ) );
+        ret = KErrNotFound;
+        }
+    else
+        {
+        TBufC<KTestScripterNameLength> myTestscripter;
+        myTestscripter = KTestScripterName;
+
+        if( ( aReq.iModule.Find( myTestscripter ) != KErrNotFound ) )
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemoteRun TestScripter module"));
+            // If testmodule's type is testscripter, then iModule has name
+            // "testscripter_testcasefile". AddTestModule method takes
+            // testscripter type of module without _testcasefile, so we cannot
+            // give iModule name as parameter.
+
+            // Adding testscripter type of testmodule
+            RDebug::Print(_L("CStifTFw::AtsRemoteRun calling AddTestModule"));
+            ret = iStifTFwIf->AddTestModule( myTestscripter, aReq.iIniFile );
+            if( ret != KErrNone )
+                {
+                __TRACE( KError, ( _L( "CStifTFw::AtsRemoteRun: AddTestModule failed [%d]"), ret ) );
+
+                // It is ok if test module is already loaded to test engine
+                if( ret == KErrAlreadyExists )
+                    {
+                    __TRACE( KPrint, ( _L( "Test module already exists at testengine, no problem") ) );
+                    }
+                }
+            // Adding testscripter testcasefile
+            RDebug::Print(_L("CStifTFw::AtsRemoteRun calling AddTestCaseFile"));
+            ret = iStifTFwIf->AddTestCaseFile( myTestscripter, aReq.iTestCaseFile );
+            if( ret != KErrNone )
+                {
+                // It is ok if test case file is already loaded to test engine
+                if( ret == KErrAlreadyExists )
+                    {
+                    __TRACE( KPrint, ( _L( "Testcasefile already exists at testengine, no problem") ) );
+                    }
+                // Got other error, log info about it
+                else
+                    {
+                    __TRACE( KError, ( _L( "CStifTFw::AtsRemoteRun: AddTestCaseFile failed [%d]"), ret ) );
+                    __TRACE( KError, ( _L( "Testscripter needs to have test case file loaded successfully, please check path and file name!") ) );
+                    }
+                }
+            }
+        else
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemoteRun It is not a TestScripter module "));
+            // For testmodules other than testscripter
+            RDebug::Print(_L("CStifTFw::AtsRemoteRun calling AddTestModule "));
+            ret = iStifTFwIf->AddTestModule( aReq.iModule, aReq.iIniFile );
+            if( ret != KErrNone )
+                {
+                __TRACE( KError, ( _L( "CStifTFw::AtsRemoteRun: AddTestModule failed [%d]"), ret ) );
+
+                // It is ok if test module is already loaded to test engine
+                if( ret == KErrAlreadyExists )
+                    {
+                    __TRACE( KPrint, ( _L( "Test module already exists at testengine, no problem") ) );
+                    }
+                }
+            }
+        if(aReq.iTitle.Length() != 0)
+            {
+			aReq.iTestCaseNumber = -1;
+            //Get test case number from title
+            ret = GetCaseNumByTitle(aReq.iModule, aReq.iTestCaseFile, aReq.iTitle, aReq.iTestCaseNumber);
+            //Check test case number
+            if(aReq.iTestCaseNumber < 0)
+                {
+                RDebug::Print(_L("CStifTFw::AtsRemoteRun No test case number could be found using given title parameter"));
+                __TRACE(KError, (_L("No mandatory test case number could be found using given title parameter")));
+                return KErrNotFound;
+                }
+            }
+
+        CTestInfo *testCase = CTestInfo::NewL();
+        CleanupStack::PushL( testCase );
+        // Copy to CTestInfo.
+
+        if( ( aReq.iModule.Find( KTestScripterName ) != KErrNotFound ) )
+            {
+            testCase->SetModuleName( KTestScripterName );
+            }
+        else
+            {
+            testCase->SetModuleName(  aReq.iModule );
+            }
+        testCase->SetTestCaseNumber( aReq.iTestCaseNumber );
+        testCase->SetTestCaseFile( aReq.iTestCaseFile );
+
+        // Create container.
+        CUIEngineContainer* container = NULL;
+
+        RDebug::Print(_L("CStifTFw::AtsRemoteRun calling StartTestCase "));
+        ret = iUIEngine->StartTestCase( container,
+                                        *testCase );
+
+        CleanupStack::PopAndDestroy( testCase );
+
+        if( ret != KErrNone )
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemoteRun test case starting FAILED "));
+            __TRACE( KError, ( _L( "Test case starting failed [%d]"), ret ) );
+            }
+        else
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemoteRun Add container"));
+            // Add container to test case execution table
+            container->SetRemoteId( aReq.SrcId() );
+            testid = TESTID( (TInt)container );
+            ret = iTestRemoteExecutionTable.Append( container );
+            __TRACE( KError, ( _L( "Test case started [%x]"), testid ) );
+            }
+        }
+
+    aResp.AppendId( SETID( iStifTFwIf->DevId(), testid ) );
+    aResp.AppendId( aReq.SrcId() );
+    aResp.Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+    aResp.Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRun );
+    if( ret != KErrNone )
+        {
+        aResp.Append( CStifTFwIfProt::RunStatus,
+                     CStifTFwIfProt::ERunError );
+        aResp.Append( CStifTFwIfProt::RunStatusParams,
+                     CStifTFwIfProt::ERunResult, ret );
+        }
+    else
+        {
+        aResp.Append( CStifTFwIfProt::RunStatus,
+                     CStifTFwIfProt::ERunStarted );
+        }
+    // Response is created, return success
+    ret = KErrNone;
+
+    RDebug::Print(_L("CStifTFw::AtsRemoteRun end "));
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: AtsRemoteTestCtl
+
+    Description: Remote run ATS call
+
+    Parameters: const TDesC& aMessage: in:
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifTFw::AtsRemoteTestCtl( CStifTFwIfProt& aReq, CStifTFwIfProt& aResp )
+    {
+    RDebug::Print(_L("CStifTFw::AtsRemoteTestCtl"));
+
+    TInt ret = KErrNone;
+
+    if( ( aReq.DstDevId() == 0 ) ||
+        ( aReq.DstTestId() == 0 ) )
+        {
+        // Protocol violation
+        __TRACE( KError, ( _L( "AtsReceive: remote test control for illegal dstid received") ) );
+        return KErrGeneral;
+        }
+
+    if ( aReq.DstDevId() != iStifTFwIf->DevId() )
+        {
+        // Not our protocol message
+        __TRACE( KError, ( _L( "AtsReceive: remote test control for illegal dstdevid received") ) );
+        return KErrNotFound;
+        }
+
+    // Find test case from execution table
+    TInt count = iTestRemoteExecutionTable.Count();
+    TInt index = 0;
+    for(; index < count; index++ )
+        {
+        if( TESTID( iTestRemoteExecutionTable[index] ) ==
+            aReq.DstTestId() )
+            {
+            break;
+            }
+        }
+
+    // Check that test id is found
+    if( index == count )
+        {
+        __TRACE( KError, (  _L( "PauseTestCase. Container not found: testId: %x"),
+            aReq.DstTestId() ) );
+        return KErrNotFound;
+        }
+
+    switch( aReq.iCmdType )
+        {
+        case CStifTFwIfProt::ECmdPause:
+            // Pause test
+            __TRACE( KPrint, (  _L( "PauseTest: %x"), aReq.DstTestId() ) );
+            ret = iTestRemoteExecutionTable[index]->PauseTest();
+            break;
+        case CStifTFwIfProt::ECmdResume:
+            // Resume test
+            __TRACE( KPrint, (  _L( "ResumeTestCase: %x"), aReq.DstTestId() ) );
+            ret = iTestRemoteExecutionTable[index]->ResumeTest();
+            break;
+        case CStifTFwIfProt::ECmdCancel:
+            // Cancel test
+            __TRACE( KPrint, (  _L( "CancelTestCase: %x"), aReq.DstTestId() ) );
+            ret = iTestRemoteExecutionTable[index]->CancelTest();
+            break;
+        default:
+            return KErrNotSupported;
+        }
+    if( ret == KErrNone )
+        {
+        // Success response is created here
+        aResp.AppendId( aReq.DstId() );
+        aResp.AppendId( aReq.SrcId() );
+        aResp.Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+        aResp.Append( CStifTFwIfProt::CmdType, aReq.iCmdType );
+        }
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: AtsRemoteEventCtl
+
+    Description: Remote run ATS call
+
+    Parameters: const TDesC& aMessage: in:
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifTFw::AtsRemoteEventCtl( CStifTFwIfProt& aReq,
+                                    CStifTFwIfProt& aResp )
+    {
+    RDebug::Print(_L("CStifTFw::AtsRemoteEventCtl start "));
+
+    if( ( aReq.DstDevId() == 0 ) ||
+        ( aReq.DstTestId() != 0 ) )
+        {
+        // Protocol violation
+        __TRACE( KError, ( _L( "AtsReceive: remote event control for illegal dstid received") ) );
+        return KErrGeneral;
+        }
+
+    if ( aReq.DstDevId() != iStifTFwIf->DevId() )
+        {
+        // Not our protocol message
+        __TRACE( KError, ( _L( "AtsReceive: remote event control for illegal dstdevid received") ) );
+        return KErrNotFound;
+        }
+
+    if( aReq.iEventName.Length() == 0 )
+        {
+        __TRACE( KError, ( _L("No event name given") ) );
+        return KErrNotFound;
+    }
+
+    switch( aReq.iCmdType )
+        {
+        case CStifTFwIfProt::ECmdRequest:
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemoteEventCtl ECmdRequest "));
+            CUIEngineEvent* eventCtl = NULL;
+            TRAPD( err, eventCtl = CUIEngineEvent::NewL( iUIEngine ); );
+            if( err != KErrNone )
+                {
+                return err;
+                }
+            err = iEventArray.Append( eventCtl );
+            if( err != KErrNone )
+                {
+                delete eventCtl;
+                return err;
+                }
+
+            eventCtl->Request( aReq.iEventName, aReq.SrcId(),
+                               SETID( iStifTFwIf->DevId(), 0 ) );
+
+            aResp.AppendId( aReq.DstId() );
+            aResp.AppendId( aReq.SrcId() );
+            aResp.Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+            aResp.Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRequest );
+            aResp.Append( CStifTFwIfProt::EventStatus,
+                         CStifTFwIfProt::EEventActive );
+            aResp.Append( aReq.iEventName );
+
+            }
+            break;
+        case CStifTFwIfProt::ECmdRelease:
+            {
+            RDebug::Print(_L("CStifTFw::AtsRemoteEventCtl ECmdRelease "));
+            TInt count = iEventArray.Count();
+            TInt index = 0;
+            for(; index < count; index++ )
+                {
+                if( ( iEventArray[index]->EventName() == aReq.iEventName ) &&
+                    ( iEventArray[index]->Master() == aReq.SrcId() ) )
+                    {
+                    // Found correct event
+                    CUIEngineEvent* eventCtl = iEventArray[index];
+                    eventCtl->Release();
+                    iEventArray.Remove(index);
+                    delete eventCtl;
+                    break;
+                    }
+                }
+            if( index == count )
+                {
+                return KErrNotFound;
+                }
+
+            aResp.AppendId( aReq.DstId() );
+            aResp.AppendId( aReq.SrcId() );
+            aResp.Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+            aResp.Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRelease );
+            aResp.Append( aReq.iEventName );
+
+            }
+            break;
+        default:
+            RDebug::Print(_L("CStifTFw::AtsRemoteEventCtl NotSupported"));
+            return KErrNotSupported;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: TestExecuted
+
+    Description:
+
+    Parameters: CUIEngineContainer* aContainer: Address of current
+                CUIEngineContainer is test case ID.
+
+                TFullTestResult& aFullTestResult: in: Test result of executed test case
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CStifTFw::TestExecuted( CUIEngineContainer* aContainer,
+                                        TFullTestResult& aFullTestResult )
+    {
+    RDebug::Print(_L("CStifTFw::TestExecuted"));
+    TInt testExecutionResult = aFullTestResult.iCaseExecutionResultCode;
+    TTestResult testResult = aFullTestResult.iTestResult;
+
+    // Find Container from test execution table
+    TInt index = iTestExecutionTable.Find( aContainer );
+    if( index >= 0 )
+        {
+        // Remove Container from test case execution table
+        iTestExecutionTable.Remove( index );
+
+        iStifTFwIf->TestCompleted( (TInt)aContainer, testExecutionResult, testResult );
+        __TRACE( KPrint, ( _L( "CStifTFw::TestExecuted. TestID %d  executed"), (TInt)aContainer ) );
+        }
+     else
+        {
+        // Find Container from test remote execution table
+        index = iTestRemoteExecutionTable.Find( aContainer );
+        // Check if test id is found from remote tests
+        if( index >= 0 )
+            {
+            // Remove Container from test case execution table
+            iTestRemoteExecutionTable.Remove( index );
+
+            CStifTFwIfProt* resp = NULL;
+            TRAPD( err, resp = CStifTFwIfProt::NewL() );
+            if( err != KErrNone )
+                {
+                // oom
+                return;
+                }
+
+            // Create response
+            TRAP( err, resp->CreateL(); );
+            if( err != KErrNone )
+                {
+                delete resp;
+                // Oom
+                return;
+                }
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgResponse );
+            resp->AppendId( SETID( iStifTFwIf->DevId(), TESTID( (TInt) aContainer ) ) );
+            resp->AppendId( aContainer->RemoteId() );
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+            resp->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRun );
+            resp->Append( CStifTFwIfProt::RunStatus,
+                         CStifTFwIfProt::ERunReady );
+            if( testExecutionResult != KErrNone )
+                {
+                resp->Append( CStifTFwIfProt::RunStatusParams,
+                             CStifTFwIfProt::ERunResult,
+                             testExecutionResult );
+                switch( aFullTestResult.iCaseExecutionResultType )
+                    {
+                    case TFullTestResult::ECasePanic:
+                        resp->Append( CStifTFwIfProt::RunStatusParams,
+                                     CStifTFwIfProt::ERunCategory,
+                                     CStifTFwIfProt::ResultCategory,
+                                     CStifTFwIfProt::EResultPanic );
+                        break;
+                    case TFullTestResult::ECaseTimeout:
+                        resp->Append( CStifTFwIfProt::RunStatusParams,
+                                     CStifTFwIfProt::ERunCategory,
+                                     CStifTFwIfProt::ResultCategory,
+                                     CStifTFwIfProt::EResultTimeout );
+                        break;
+                    case TFullTestResult::ECaseLeave:
+                        resp->Append( CStifTFwIfProt::RunStatusParams,
+                                     CStifTFwIfProt::ERunCategory,
+                                     CStifTFwIfProt::ResultCategory,
+                                     CStifTFwIfProt::EResultLeave );
+                        break;
+                    case TFullTestResult::ECaseException:
+                        resp->Append( CStifTFwIfProt::RunStatusParams,
+                                     CStifTFwIfProt::ERunCategory,
+                                     CStifTFwIfProt::ResultCategory,
+                                     CStifTFwIfProt::EResultException );
+                        break;
+                    default:
+                        // The rest are normal execution results
+                        break;
+                    }
+                }
+            else
+                {
+                resp->Append( CStifTFwIfProt::RunStatusParams,
+                             CStifTFwIfProt::ERunResult,
+                             testResult.iResult );
+                }
+
+            iStifTFwIf->AtsSend( resp->Message() );
+            __TRACE( KPrint, ( _L( "TestExecuted: %x"), TESTID(aContainer) ) );
+            delete resp;
+            }
+        }
+
+    if( index >= 0 )
+        {
+        __TRACE( KPrint, ( _L( "Execution result %d"), testExecutionResult ) );
+        __TRACE( KPrint, ( _L( "Test result(%S) %d"), &testResult.iResultDes, testResult.iResult ) );
+        }
+    else
+        {
+        __TRACE( KPrint, ( _L( "CStifTFw::TestExecuted. Container not found: TestId = %d"),
+            (TInt)aContainer ) );
+        User::Panic( _L("CStifTFw"), KErrNotFound );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: PrintProg
+
+    Description:
+
+    Parameters: CUIEngineContainer* aContainer: in: Address of current
+                CUIEngineContainer is test case ID
+
+                TTestProgress& aProgress: in: Progress information from test case
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFw::PrintProg( CUIEngineContainer* aContainer,
+                                     TTestProgress& aProgress )
+    {
+    RDebug::Print(_L("CStifTFw::PrintProg"));
+
+    if( aContainer == NULL )
+        {
+        return KErrArgument;
+        }
+    if( ( aProgress.iDescription.Length() == 0 ) &&
+        ( aProgress.iText.Length() == 0 ) )
+
+        {
+        return KErrArgument;
+        }
+
+//Stif-50 - the following code has been commented out to get messages on slave
+//    // Find Container from test execution table and remove it
+//    TInt index = iTestExecutionTable.Find(aContainer);
+//
+//    // Check if test id is found
+//    if( index >= 0 )
+//        {
+//        // Forward if found, prints are not forwarded from slave to master
+        iStifTFwIf->Print( (TInt)aContainer, aProgress );
+//        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: RemoteMsg
+
+    Description:
+
+    Parameters: const TDesC& aMessage: in: Remote message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFw::RemoteMsg( CUIEngineContainer* /*aContainer*/,
+                                     const TDesC& aMessage)
+    {
+    RDebug::Print(_L("CStifTFw::RemoteMsg"));
+
+    if( aMessage.Length() == 0 )
+        {
+        return KErrArgument;
+        }
+    // Forward message
+    iStifTFwIf->AtsSend( aMessage );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: RemoteMsg
+
+    Description:
+
+    Parameters: const TDesC& aMessage: in: Remote message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFw::GoingToReboot( CUIEngineContainer* /*aContainer*/,
+                                         TRequestStatus& aStatus )
+    {
+    RDebug::Print(_L("CStifTFw::GoingToReboot"));
+
+    aStatus = KRequestPending;
+    // Forward reboot indication
+    iStifTFwIf->GoingToDoReset();
+    TRequestStatus* rs = &aStatus;
+    User::RequestComplete( rs, KErrNone );
+
+    return KErrNone;
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFw
+
+    Method: DeleteData
+
+    Description: Delete arrays before closing session to test engine server
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CStifTFw::DeleteData()
+    {
+    RDebug::Print(_L("CStifTFw::DeleteData resetting iTestExecutionTable cnt=%d"), iTestExecutionTable.Count());
+    iTestExecutionTable.Reset();
+    RDebug::Print(_L("CStifTFw::DeleteData resetting iTestRemoteExecutionTable cnt=%d"), iTestRemoteExecutionTable.Count());
+    iTestRemoteExecutionTable.Reset();
+    RDebug::Print(_L("CStifTFw::DeleteData resetting iEventArray cnt=%d"), iEventArray.Count());
+    iEventArray.ResetAndDestroy();
+    RDebug::Print(_L("CStifTFw::DeleteData resetting iMasterArray cnt=%d"), iMasterArray.Count());
+    iMasterArray.Reset();
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIEngine.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1310 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CUIEngine: This object executes test cases from 
+* STIF Test Framework.
+* 
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <collate.h>
+#include "UIEngineEvent.h"
+#include <stifinternal/UIEngineContainer.h>
+#include "UIEngineError.h"
+#include <stifinternal/UIEngine.h>
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+_LIT( KUIEngine, "CUIEngine" );
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iLogger
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: CUIEngine
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngine::CUIEngine( CUIIf* aUi  ):
+    iUi( aUi )
+    {
+
+    __RDEBUG( _L( "CUIEngine::CUIEngine()" ) );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngine::ConstructL()
+    {
+    // Logger's setting definitions
+    TLoggerSettings loggerSettings;
+    loggerSettings.iCreateLogDirectories = EFalse;
+    loggerSettings.iOverwrite = ETrue;
+    loggerSettings.iTimeStamp = ETrue;
+    loggerSettings.iLineBreak = ETrue;
+    loggerSettings.iEventRanking = EFalse;
+    loggerSettings.iThreadId = EFalse;
+    loggerSettings.iHardwareFormat = CStifLogger::ETxt;
+    loggerSettings.iHardwareOutput = CStifLogger::EFile;
+    loggerSettings.iEmulatorFormat = CStifLogger::ETxt;
+    loggerSettings.iEmulatorOutput = CStifLogger::EFile;
+    loggerSettings.iUnicode = EFalse;
+    loggerSettings.iAddTestCaseTitle = EFalse;
+
+    // Create Logger, Note: Use protected NewL because initialization file not
+    // readed yet.
+    iLogger = CStifLogger::NewL( KUiLogDir, KUiLogFile, loggerSettings );
+    
+    // Initialize logger    
+    iUi->InitializeLogger( iLogger );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+    
+    Parameters: None
+    
+    Return Values: CUIEngine* : Pointer to created UI engine object
+
+    Errors/Exceptions: Leaves if memory allocation for CUIEngine fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngine* CUIEngine::NewL( CUIIf* aUi )
+    {
+    
+    CUIEngine* self =  
+        new ( ELeave ) CUIEngine( aUi );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: ~CUIEngine
+
+    Description: Destructor
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngine::~CUIEngine()
+    {
+    
+    __RDEBUG( _L( "CUIEngine::~CUIEngine()" ) );
+    
+    // Delete all containers, cannot use ResetAndDestroy,
+    // because destructor is private
+    TInt count = iContainerArray.Count();
+    for( TInt i=0; i< count; i++ )
+        {
+        delete iContainerArray[i];
+        }
+    iContainerArray.Reset();    
+    iContainerArray.Close();
+
+    delete iLogger;
+    iLogger = NULL;
+    
+    delete iError;
+    iError = 0;
+        
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: VUIEngine
+
+    Method: Open
+
+    Description: Open test engine.
+
+    Parameters: TDesC& aTestFrameworkIni: in: Initialization file to Test Framework
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::Open( const TDesC& aTestFrameworkIni )
+    {
+    
+    if( ( iTestEngine.SubSessionHandle() != 0 ) ||
+        ( iTestEngineServ.Handle() != 0 ) )
+        {
+        __TRACE( KError, ( CStifLogger::EError, _L( "CUIEngine::Open() Already open" ) ) );
+        return KErrInUse;     
+        }
+
+    // Check aTestFrameworkIni max length
+    if( aTestFrameworkIni.Length() > KMaxFileName )
+        {
+        __TRACE( KPrint, ( CStifLogger::EError, _L( "CUIEngine::Open() method's parameter length is incorrect" ) ) );
+        return KErrArgument;        
+        }
+
+    // Create Test Engine
+    TInt ret = iTestEngineServ.Connect();
+
+    if ( ret != KErrNone )
+        {
+        __TRACE( KPrint, ( _L( "CUIEngine::Open. Engine server open failed: ret = %d"), ret ) );
+
+        return ret;
+        }
+
+    ret = iTestEngine.Open( iTestEngineServ, aTestFrameworkIni );
+
+    if ( ret != KErrNone )
+        {
+        __TRACE( KPrint, ( _L( "CUIEngine::Open. Engine. Open failed: ret = %d"), ret ) );
+
+        return ret;
+        }
+
+    TErrorNotification error;
+    if( ErrorPrint( error ) != KErrNotSupported )
+        {
+        // Start printer
+        iError = CUIEngineErrorPrinter::NewL( this );
+        iError->StartL( iTestEngine );
+        }
+
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: Close
+
+    Description: Close test engine.
+
+    Parameters: None
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::Close()
+    {
+    
+    delete iError;
+    iError = 0;
+    
+    // Delete all containers, cannot use ResetAndDestroy,
+    // because destructor is private
+    TInt count = iContainerArray.Count();
+    for( TInt i=0; i< count; i++ )
+        {
+        delete iContainerArray[i];
+		iContainerArray[i] = NULL;
+        }
+    iContainerArray.Reset();
+    
+    iTestEngine.Close();
+    iTestEngineServ.Close();
+
+    __TRACE( KPrint, ( _L( "CUIEngine::Close." ) ) );
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: AddTestModule
+
+    Description: Add test module to module list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which is added to module list
+                TDesC& aIniFile: in: Initialization file to the test module
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::AddTestModule( const TDesC& aModuleName, 
+                               const TDesC& aIniFile )
+    {
+    // Check aModuleName max length
+    if( aModuleName.Length() > KMaxName )
+        {
+        __TRACE( KPrint, ( CStifLogger::EError, _L( "CUIEngine::AddTestModule() method's first parameter length is incorrect" ) ) );
+        return KErrArgument;        
+        }
+    // Check aIniFile max length
+    if( aIniFile.Length() > KMaxFileName )
+        {
+        __TRACE( KPrint, ( CStifLogger::EError, _L( "CUIEngine::AddTestModule() method's second parameter length is incorrect" ) ) );
+        return KErrArgument;        
+        }    
+
+
+    TInt ret = iTestEngine.AddTestModule( aModuleName, aIniFile );
+
+    if ( ret != KErrNone && ret != KErrAlreadyExists )
+        {
+		__TRACE( KPrint, ( _L( "CUIEngine::AddTestModule. Add module failed: ret = %d" ), ret  ) );
+
+        return ret;
+        }
+
+    return KErrNone;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: RemoveTestModule
+
+    Description: Remove test module from test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which is removed of module list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::RemoveTestModule( const TDesC& aModuleName )
+    {
+    // Remove test module of module list of test engine
+    TInt ret = iTestEngine.RemoveTestModule( aModuleName );
+
+    if ( ret != KErrNone )
+        {
+        __TRACE( KPrint, ( _L( "CUIEngine::RemoveTestModule. Remove module failed: ret = %d"), ret  ) );
+
+        return ret;
+        }
+
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: AddTestCaseFile
+
+    Description: Add test case file to test case file list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which own test cases of test case list.
+                TDesC& aCaseFile: in: Test case list, which is added to test case list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::AddTestCaseFile( const TDesC& aModuleName, 
+                                 const TDesC& aCaseFile )
+    {
+    // Check aModuleName max length
+    if( aModuleName.Length() > KMaxName )
+        {
+        __TRACE( KPrint, ( CStifLogger::EError, _L( "CUIEngine::AddTestCaseFile() method's first parameter length is incorrect" ) ) );
+        return KErrArgument;        
+        }
+    // Check aCaseFile max length
+    if( aCaseFile.Length() > KMaxFileName )
+        {
+        __TRACE( KPrint, ( CStifLogger::EError, _L( "CUIEngine::AddTestCaseFile() method's second parameter length is incorrect" ) ) );
+        return KErrArgument;        
+        }
+    
+    TInt ret( KErrNone );
+
+    // Add given test case file to test module
+    if ( aCaseFile.Length() == 0 )
+        {
+        ret = KErrArgument;
+        __TRACE( KPrint, (  _L( "CUIEngine::AddTestCaseFile. Test case file not defined: ret = %d"), ret  ) );
+        }
+    else
+        {
+        // Add test case file to test case file list of test engine 
+        ret = iTestEngine.AddConfigFile( aModuleName, aCaseFile );
+
+        if ( ret != KErrNone && ret != KErrAlreadyExists )
+            {
+            __TRACE( KPrint, ( _L( "CUIEngine::AddTestCaseFile. Add test case file failed: ret = %d"), ret  ) );
+            }
+        }
+
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: RemoveTestCaseFile
+
+    Description: Remove test case file of test case file list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which own test cases of test case list
+                TDesC& aCaseFile: in: Test case list, which is removed of test case list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::RemoveTestCaseFile( const TDesC& aModuleName, 
+                                    const TDesC& aCaseFile )
+    {   
+    
+    TInt ret( KErrNone );
+
+    // Remove given test case file from test module
+    if ( aCaseFile.Length() == 0 )
+        {
+        ret = KErrArgument;
+        __TRACE( KPrint, (  _L( "CUIEngine::RemoveTestCaseFile. Test case file not defined: ret = %d"), ret  ) );
+        }
+    else
+        {
+        // Remove test case file  
+        ret = iTestEngine.RemoveConfigFile( aModuleName, aCaseFile );
+
+        if ( ret != KErrNone )
+            {
+            __TRACE( KPrint, ( _L( "CUIEngine::RemoveTestCaseFile. Remove test case file failed: ret = %d"), ret  ) );
+            }
+        }
+
+    return ret;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: GetTestCases
+
+    Description: Get test cases of enumerated list of test engine. Method is copied 
+                 list of test cases to aTestCaseInfo. Copied tests are test cases 
+                 of test module (aTestModule) and defined
+                 in test case file (aTestCaseFile), which are given as argument
+
+                 Method copied all enumerated test cases if aTestModule
+                 and aTestCaseFile are not defined
+    
+    Parameters: RPointerArray<CTestInfo>& aTestCaseInfo: inout: List of test cases
+                TDesC& aModuleName: in: Testmodule, which own test cases of test case list
+                TDesC& aTestCaseFile: in: Test case list, which is got of test case list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::GetTestCasesL( RPointerArray<CTestInfo>& aTestCaseInfo,
+                               const TDesC& aTestModule, 
+                               const TDesC& aTestCaseFile )
+    { 
+	__TRACE( KPrint, (  _L( "GetTestCasesL()") ) );
+
+    TInt ret(KErrNone);
+    TInt count(0);
+
+    // Enumerate test cases
+    TCaseCount caseCount;
+
+    TRequestStatus status;
+    iTestEngine.EnumerateTestCases( caseCount, status );
+    User::WaitForRequest( status );
+    ret = status.Int();
+
+    // Check that enumerate succeeded
+    if ( ret != KErrNone )
+        {
+        __TRACE( KPrint, (  _L( "CUIEngine::GetTestCases. Test case enumerate failed: ret = %d"), ret ) );
+        TErrorNotification error;
+        error.iText = _L("Can't get test cases");
+        iUi->ErrorPrint ( error );  
+        return ret;
+        }
+
+    CFixedFlatArray<TTestInfo>* testCases = NULL;
+
+    // Create test cases to buffer
+    TRAPD( err, testCases = CFixedFlatArray<TTestInfo>::NewL( caseCount() ) );
+    if( err != KErrNone )
+        {        
+        if( err == KErrNoMemory )
+            {
+            _LIT( KNotEnoughHeapMemory, 
+                "Not enough heap memory available. Either reduce the test case count or increase UI's heap size in mmp file using EPOCHEAPSIZE.");
+            RDebug::Print( KNotEnoughHeapMemory );
+        	__TRACE( KError, ( KNotEnoughHeapMemory ) );        
+        	}
+        else
+           {
+            _LIT( KGeneralError,
+                "CUIEngine::GetTestCasesL: CFixedFlatArray<TTestInfo>::NewL fails with value: %d");
+            RDebug::Print( KGeneralError, err );
+        	__TRACE( KError, ( KGeneralError, err ) );                   
+           }        	
+        User::Leave( err );
+        }    
+            
+    CleanupStack::PushL( testCases );
+
+    // Get test cases from Engine.
+    ret = iTestEngine.GetTestCases( *testCases );
+
+    if ( ret != KErrNone )
+        {
+        __TRACE( KPrint, (  _L( "CUIEngine::GetTestCases. Get test cases failed: ret = %d"), ret ) );
+
+        CleanupStack::PopAndDestroy( testCases );
+        return ret;
+        }
+
+    // count of test cases.
+    count = caseCount();
+
+    __TRACE( KPrint, (  _L( "Test case count: %d"), count ) );
+    
+    HBufC* moduleNameBuf = aTestModule.AllocLC();
+    TPtr moduleName( moduleNameBuf->Des() );
+    TCollationMethod method = 
+        *Mem::CollationMethodByIndex(0); // get the standard method
+    method.iFlags |= TCollationMethod::EFoldCase; // ignore case
+
+    moduleName.LowerCase();
+
+    // Remove optional '.DLL' from test module file name
+    TParse parse;
+    parse.Set( moduleName, NULL, NULL );
+    
+    if( !parse.Ext().CompareC(  _L(".dll"), 3, &method ) )
+        {
+        const TInt len = parse.Ext().Length();
+        moduleName.Delete ( moduleName.Length()-len, len );
+        }
+        
+    TBool found = EFalse;
+    // Update iTestCaseTable.
+    for (TInt j=0;j<count;j++, found = EFalse)
+        {
+        // Check, if module defined.
+        if ( aTestModule.Length() > 0 )
+            {
+            // Check, if test case defined.
+            if ( aTestCaseFile.Length() > 0)
+                {
+                if( moduleName == KTestScripterName )
+                    {
+                    if( !( *testCases )[j].iConfig.CompareC( aTestCaseFile, 3, &method ) )
+                        {
+                        found = ETrue;
+                        }
+                    }
+                if( !( *testCases )[j].iModuleName.CompareC( moduleName, 3, &method )
+                    && !( *testCases )[j].iConfig.CompareC( aTestCaseFile, 3, &method ) )
+                    {
+                    found = ETrue;
+                    }
+                }
+            else
+                {
+                if( moduleName == KTestScripterName )
+                    {
+                    // Test Module is TestScripter
+                    if( ( *testCases )[j].iModuleName.Find( KTestScripterName ) != KErrNotFound )
+                        {
+                        // iModuleName name is in 'testscripter_testcasefile'
+                        // format => Find()
+                        found = ETrue;
+                        }
+                    }
+                if( !( *testCases )[j].iModuleName.CompareC( 
+                                            moduleName, 3, &method ) )
+                    {
+                    found = ETrue;
+                    }
+                }
+            }
+        else
+            {
+            found = ETrue;
+            }
+        
+        if( found )
+            {
+            // Create tmpTestInfo.
+            CTestInfo *tmpTestInfo = CTestInfo::NewL();
+             
+            CleanupStack::PushL( tmpTestInfo );            
+
+            // Copy TTestInfo to CTestInfo.
+            tmpTestInfo->SetModuleName( ( *testCases )[j].iModuleName );
+            tmpTestInfo->SetTestCaseTitle( ( *testCases )[j].iTestCaseInfo.iTitle );
+            tmpTestInfo->SetTestCaseNumber( ( *testCases )[j].iTestCaseInfo.iCaseNumber );
+            tmpTestInfo->SetPriority( ( *testCases )[j].iTestCaseInfo.iPriority );
+            tmpTestInfo->SetTimeout( ( *testCases )[j].iTestCaseInfo.iTimeout );
+            tmpTestInfo->SetTestCaseFile( ( *testCases )[j].iConfig );
+            ret = aTestCaseInfo.Append(tmpTestInfo);
+            if( ret != KErrNone )
+                {
+                CleanupStack::PopAndDestroy( tmpTestInfo );
+                }
+            else
+                {
+                CleanupStack::Pop( tmpTestInfo );
+                }
+            }
+        }
+    
+    CleanupStack::PopAndDestroy( moduleNameBuf );
+
+    CleanupStack::PopAndDestroy( testCases );
+
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: StartTestCase
+
+    Description: Start test case execution.
+
+    Parameters: TInt& aTestId: in: ID for test case. Test ID given of address of
+                current UIEngineContainer.
+
+                const CTestInfo& aTestInfo: in: Test case information
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::StartTestCase( CUIEngineContainer*& aContainer,
+                              const CTestInfo& aTestInfo )
+    {
+    TInt ret( KErrNone );
+
+    // Copy CTestInfo to TTestInfo.
+    TTestInfo testCase; 
+    testCase.iModuleName = aTestInfo.ModuleName();
+    testCase.iTestCaseInfo.iTitle = aTestInfo.TestCaseTitle();
+    testCase.iTestCaseInfo.iCaseNumber = aTestInfo.TestCaseNum();
+    testCase.iTestCaseInfo.iPriority = aTestInfo.Priority();
+    testCase.iTestCaseInfo.iTimeout = aTestInfo.Timeout();
+    testCase.iConfig = aTestInfo.TestCaseFile();
+
+    CUIEngineContainer* container = NULL;
+    TRAP( ret,
+        // Create container.
+        container = 
+            CUIEngineContainer::NewL( this, testCase, iTestEngineServ, iTestEngine );
+    );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    ret = iContainerArray.Append( container );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, ( CStifLogger::EError, 
+            _L( "CUIEngine::StartTestCase() Append failed, cannot start test case" ) ) );
+        delete container;
+        return ret;
+        }
+        
+    // Call Container to starting test case execution.
+    TRAPD( trapError,
+    // Call Container to starting test case execution.
+    ret = container->StartContainerL();
+    );
+
+    if(trapError != KErrNone)
+        {
+        __TRACE( KPrint, (  _L( "CUIEngine::StartTestCase. Test case starting failed: trapError = %d"), ret ) );
+        delete container;
+        return trapError;
+        }
+        
+    aContainer = container;
+
+    return ret;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: AbortStartedTestCase
+
+    Description: Abort started test case execution.
+
+    Parameters: CUIEngineContainer* aContainer: in: Container running testcase
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: Panics if test case is not found or is already executed
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngine::AbortStartedTestCase( CUIEngineContainer* aContainer )
+    {
+    
+    // Locate container from array
+    TInt index = iContainerArray.Find( aContainer );
+    
+    if( ( index < 0) ||
+        ( aContainer->State() == CUIEngineContainer::EExecuted ) )
+        {
+        __TRACE( KError, ( CStifLogger::EError, 
+            _L( "CUIEngine::AbortStartedTestCase() Testcase executed" ) ) );
+        User::Panic( KUIEngine, KErrAccessDenied );
+        }
+        
+    // Remove and delete container
+    iContainerArray.Remove( index );
+    delete aContainer;
+    
+    }
+
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: TestExecuted
+
+    Description: 
+
+    Parameters: CUIEngineContainer* aUIEngineContainer: Address of current
+                CUIEngineContainer is test case ID.
+
+                TFullTestResult& aFullTestResult: in: Test result of executed test case
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngine::TestExecuted( CUIEngineContainer* aContainer, 
+                               TFullTestResult& aFullTestResult )
+    {
+     // Locate container from array
+    TInt index = iContainerArray.Find( aContainer );
+    
+    if( index < 0 )
+        {
+        __TRACE( KError, ( CStifLogger::EError, 
+            _L( "CUIEngine::TestExecuted() Testcase not found" ) ) );
+        User::Panic( KUIEngine, KErrNotFound );
+        }
+    
+    iUi->TestExecuted( aContainer, aFullTestResult );
+    
+    // Remove and delete container.
+    // It is safe to do here,
+    // because container and runner does not have any code after
+    // this function returns.
+    iContainerArray.Remove( index );
+    delete aContainer;
+   
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: PrintProg
+
+    Description: 
+
+    Parameters: CUIEngineContainer* aContainer: in: Address of current
+                CUIEngineContainer is test case ID
+
+                TTestProgress& aProgress: in: Progress information from test case
+
+    Return Values: SymbianOS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::PrintProg( CUIEngineContainer* aContainer, 
+                          TTestProgress& aProgress )
+    {
+
+    return iUi->PrintProg( aContainer, aProgress );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: ErrorPrint
+
+    Description: 
+
+    Parameters: TErrorNotification& aError: in: Error information from framework
+
+    Return Values: SymbianOS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::ErrorPrint( TErrorNotification& aError )
+    {
+
+    return iUi->ErrorPrint( aError );
+        
+    }
+   
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: RemoteMsg
+
+    Description: Forward Ats send.
+
+    Parameters: const TDesC& aMessage: in: message
+    
+    Return Values: SymbianOS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::RemoteMsg( CUIEngineContainer* aContainer, 
+                           const TDesC& aMessage )
+    {
+
+    return iUi->RemoteMsg( aContainer, aMessage );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngine
+
+    Method: GoingToReboot
+
+    Description: Forward reboot indication.
+
+    Parameters: None
+    
+    Return Values: SymbianOS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngine::GoingToReboot( CUIEngineContainer* aContainer,
+                               TRequestStatus& aStatus )
+    {
+
+    return iUi->GoingToReboot( aContainer, aStatus );
+        
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    CTestInfo: This object contains test case information.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: NewL
+
+    Description:
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestInfo* CTestInfo::NewL()
+    {
+    
+    //RDebug::Print(_L("CTestInfo::NewL()"));
+    CTestInfo* self =  
+        new ( ELeave ) CTestInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: CTestInfo
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestInfo::CTestInfo()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestInfo::ConstructL()
+    {   
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: ~CTestInfo
+
+    Description: Destructor
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestInfo::~CTestInfo()
+    {
+    
+    delete iModuleNameBuf;
+    delete iTitleBuf;
+    delete iTestCaseFileBuf;
+    iModuleNameBuf = 0;
+    iTitleBuf = 0;
+    iTestCaseFileBuf = 0;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: SetModuleName
+
+    Description: Set module name.
+    
+    Parameters: None
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestInfo::SetModuleName ( const TDesC& aModuleName ) 
+    {
+    
+    iModuleName.Set(0,0); 
+    delete iModuleNameBuf;
+
+    if( aModuleName.Length() < KTestScripterNameLength )
+		{
+		iModuleNameBuf = aModuleName.Alloc();
+		}
+    else
+        {
+        // Check is TestScripter
+	    TPtrC check( aModuleName.Mid( 0, KTestScripterNameLength ) );
+	    TInt ret = check.Compare( KTestScripterName );
+	    if( ret == KErrNone )
+		    {
+            iModuleNameBuf = ( aModuleName.Mid( 0, KTestScripterNameLength ) ).Alloc();
+		    }
+	    else
+		    {
+		    iModuleNameBuf = aModuleName.Alloc();
+		    }
+        }
+
+    if( iModuleNameBuf == NULL )
+        {
+        return KErrNoMemory;
+        }
+    
+    iModuleName.Set( iModuleNameBuf->Des() ); 
+    
+    return KErrNone;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: SetTestCaseTitle
+
+    Description: Set module name.
+    
+    Parameters: None
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestInfo::SetTestCaseTitle ( const TDesC& aTitle )
+    { 
+    
+    iTitle.Set(0,0); 
+    delete iTitleBuf;
+    iTitleBuf = aTitle.Alloc();
+    if( iTitleBuf == NULL )
+        {
+        return KErrNoMemory;
+        }
+    
+    iTitle.Set( iTitleBuf->Des() ); 
+    
+    return KErrNone;
+    
+    };
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: SetTestCaseFile
+
+    Description: Set test case file name.
+    
+    Parameters: None
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestInfo::SetTestCaseFile ( const TDesC& aTestCaseFile )
+    { 
+    iTestCaseFile.Set(0,0); 
+    delete iTestCaseFileBuf;
+    iTestCaseFileBuf = aTestCaseFile.Alloc();
+    if( iTestCaseFileBuf == NULL )
+        {
+        return KErrNoMemory;
+        }
+    
+    iTestCaseFile.Set( iTestCaseFileBuf->Des() );
+    
+    return KErrNone;
+     
+    };
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: CopyL
+
+    Description: Copy existing CTestInfo.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves on error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestInfo::CopyL( const CTestInfo& aTestInfo )
+    {
+
+    User::LeaveIfError( SetModuleName( aTestInfo.ModuleName() ));
+    User::LeaveIfError( SetTestCaseTitle( aTestInfo.TestCaseTitle() ));
+    User::LeaveIfError( SetTestCaseFile( aTestInfo.TestCaseFile() ));
+    
+    iCaseNumber = aTestInfo.TestCaseNum();
+    iPriority = aTestInfo.Priority();
+    iTimeout = aTestInfo.Timeout();
+    iExpectedResult = aTestInfo.ExpectedResult();
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestInfo
+
+    Method: SetTestCaseFile
+
+    Description: Set test case file name.
+    
+    Parameters: None
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestInfo::operator== ( const CTestInfo& aTestInfo ) const
+    {
+    
+    if( ( aTestInfo.ModuleName() == ModuleName() ) &&
+        ( aTestInfo.Priority() == Priority() ) &&
+        ( aTestInfo.TestCaseFile() == TestCaseFile() ) &&
+        ( aTestInfo.TestCaseNum() == TestCaseNum() ) &&
+        ( aTestInfo.Timeout() == Timeout() ) )
+        {
+        return ETrue;
+        }
+        
+             
+    return EFalse;
+    
+    }
+    
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIEngineContainer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,612 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CUIEngine: This object executes test cases from STIF 
+* Test Framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <stifinternal/UIEngine.h>
+#include <stifinternal/UIEngineContainer.h>
+#include "UIEnginePrinter.h"
+#include "UIEngineRunner.h"
+#include "UIEngineRemote.h"
+#include "Logging.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iUIEngine->iLogger
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: CUIEngineContainer
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters:  CUIEngine* aUIEngine: in: Pointer to CUIEngine interface
+                 TTestInfo& aTestInfo: in: Test information
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineContainer::CUIEngineContainer( CUIEngine* aUIEngine,
+                                   const TTestInfo& aTestInfo,
+                                   RTestEngineServer& aTestEngineServ,
+                                   RTestEngine& aTestEngine ) :
+    iUIEngine( aUIEngine ),
+    iTestInfo( aTestInfo ),
+    iTestInfoPckg( iTestInfo ),
+    iState( ENotStarted )
+    {
+    __TRACE( KPrint, (  _L( "CUIEngineContainer::CUIEngineContainer.") ) );
+
+    // Get handles to test engine
+    iTestEngineServ = aTestEngineServ;
+    iTestEngine = aTestEngine;
+
+    __ASSERT_ALWAYS( aUIEngine, User::Panic( _L("Null pointer"), KErrGeneral ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineContainer::ConstructL()
+    {
+    __TRACE( KPrint, (  _L( "CUIEngineContainer::ConstructL.") ) );
+
+    // Open test case
+    User::LeaveIfError( iTestCase.Open( iTestEngineServ, iTestInfoPckg ) );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CUIEngine* aUIEngine: in: pointer to CUIEngine Interface
+                TTestInfo& aTestInfo: in: Test info
+
+    Return Values: CUIEngineRunner* : pointer to created runner object
+
+    Errors/Exceptions: Leaves if memory allocation for CUIEngineRunner fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineContainer* CUIEngineContainer::NewL( CUIEngine* aUIEngine,
+                                            const TTestInfo& aTestInfo,
+                                            RTestEngineServer& aTestEngineServ,
+                                            RTestEngine& aTestEngine )
+    {
+    CUIEngineContainer* self =  
+        new ( ELeave ) CUIEngineContainer( aUIEngine,
+                                            aTestInfo,
+                                            aTestEngineServ,
+                                            aTestEngine );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: ~CUIEngineContainer
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/    
+CUIEngineContainer::~CUIEngineContainer()
+    {
+    
+    __TRACE( KPrint, (  _L( "CUIEngineContainer::~CUIEngineContainer.") ) );
+
+    delete iPrinter;
+    delete iRunner;
+    delete iRemote;
+    
+    // Close test case
+    iTestCase.Close();
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: StartContinerL
+
+    Description: StartContinerL call CUIEngineRunner to starting test case execution
+
+    Parameters: None
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngineContainer::StartContainerL()
+    {
+    
+    __TRACE( KPrint, ( _L( "CUIEngineContainer::StartContainerL. Running test case: %S"), 
+        &( iTestInfo.iTestCaseInfo.iTitle ) ) );
+        
+    // Start printer
+    iPrinter = CUIEnginePrinter::NewL( this );
+    iPrinter->StartL( iTestCase );
+
+    // Start remote
+    iRemote = CUIEngineRemote::NewL( this );
+    iRemote->StartL( iTestCase );
+
+    // Start runner
+    iRunner = CUIEngineRunner::NewL( this );
+    iRunner->StartL( iTestCase );
+
+    // Update state of test case
+    iState = ERunning;
+
+    __TRACE( KPrint, ( _L( "CUIEngineContainer::StartContainerL: started") ) );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: CancelTest
+
+    Description: CancelTest cancels test case execution
+
+    Parameters: None
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIEngineContainer::CancelTest()
+    {
+
+    if ( iState == ERunning || iState == EPaused )
+        {
+        __TRACE( KPrint, ( _L( "CUIEngineContainer::CancelTest") ) );
+
+        // Cancel test case execution
+        iTestCase.CancelAsyncRequest( ETestCaseRunTestCase );
+        
+        }
+
+    return KErrNone;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: PauseTest
+
+    Description: PauseTest pauses test case execution
+
+    Parameters: None
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIEngineContainer::PauseTest()
+    {
+    TInt ret(KErrNone);
+
+    if ( iState == ERunning )
+        {
+        ret = iTestCase.Pause();
+
+        __TRACE( KPrint, ( _L( "CUIEngineContainer::PauseTest. Ret = %d"), ret ) );
+
+        if ( ret == KErrNone)
+            {
+            iState = EPaused;
+            }
+        }
+
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: ResumeTest
+
+    Description: PauseTest resumes test case execution
+
+    Parameters: None
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIEngineContainer::ResumeTest()
+    {
+    TInt ret(KErrNone);
+
+    if ( iState == EPaused )
+        {
+        ret = iTestCase.Resume();
+
+        __TRACE( KPrint, ( _L( "CUIEngineContainer::ResumeTest. Ret = %d"), ret ) );
+
+        if ( ret == KErrNone)
+            {
+            iState = ERunning;
+            }
+        }
+
+    return ret;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: TestCaseExecuted
+
+    Description: TestCaseExecuted informs that test case is executed
+
+    Parameters: TFullTestResult& aFullTestResult: in: Full information of 
+                test case execution. Includes also test case results
+
+    Return Values: None
+
+    Errors/Exceptions: TInt KErrNone: Always returned KErrNone
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineContainer::TestCaseExecuted( TFullTestResult& aFullTestResult, 
+                                           TInt aStatus )
+    {
+        
+    iState = EExecuted;
+
+    // Set execution result
+    if( ( KErrNone != aStatus ) &&
+        ( aFullTestResult.iCaseExecutionResultCode == KErrNone ) &&
+        ( aFullTestResult.iTestResult.iResult == KErrNone ) )
+        {
+        aFullTestResult.iTestResult.iResultDes.Copy( 
+            _L("Completed with error") );
+        aFullTestResult.iCaseExecutionResultType = 
+            TFullTestResult::ECaseErrorFromModule;
+        aFullTestResult.iCaseExecutionResultCode = aStatus;
+        }
+
+    __TRACE( KPrint, ( _L( "CUIEngineContainer::TestCaseExecuted.") ) );
+
+    // Test execution is not completed before all prints are 
+    // delivered to UI.
+    if( !iPrinter->IsRunning() || 
+        ( aStatus != KErrNone ) || 
+        ( aFullTestResult.iCaseExecutionResultCode != KErrNone ) )
+        {        
+        // Call TestExecuted of CUIEngine interface
+        iUIEngine->TestExecuted(this, aFullTestResult);
+        // 1. This method is called from CUIEngineRunner::RunL() and it is 
+        // last operation => no other call to CUIEngineContainer class.
+        // 2. TestExecuted() method takes this pointer. Inside TestExecuted()
+        // will be deleted the this pointer => iUIEngine not valid anymore.
+        // 1 and 2 => Do not handle any CUIEngineContainer variable here
+        // because memory is not valid anymore.
+        //e.g. iState = EFinished; // illegal operation here->crash
+
+        }
+        
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: PrintProgress
+
+    Description: PrintProgress prints information from test case
+
+    Parameters: TTestProgress& aProgress: in: Progress info
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineContainer::PrintProgress( TTestProgress& aProgress )
+    {
+    if( iState == ERunning )
+        {
+        // Only running cases may print
+        iUIEngine->PrintProg( this, aProgress );
+        }
+    else
+        {
+        __TRACE( KPrint, 
+            ( _L("%S: %S"), &aProgress.iDescription, &aProgress.iText ) );
+        }
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: PrintsDone
+
+    Description: Signals that printing is completed
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineContainer::PrintsDone()
+    {
+    if( iState == EExecuted )
+        {
+        // Call TestExecuted of CUIEngine interface
+        iUIEngine->TestExecuted(this, iRunner->FullResult() );
+        }
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: RemoteSend
+
+    Description: RemoteSend forwards remote protocol messages from master
+
+    Parameters: 
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineContainer::RemoteSend( const TDesC& aRemoteMsg, 
+                                     TInt /* aStatus */ )
+    {
+
+    __TRACE( KPrint, ( _L( "CUIEngineContainer::RemoteSend.") ) );
+
+    // Save master id if doesn't exists already
+    if( iMasterId == 0 )
+        {
+        CStifTFwIfProt* msg = NULL;
+        TRAPD( err, 
+            msg = CStifTFwIfProt::NewL(); 
+            msg->SetL( aRemoteMsg );
+            );
+        if( err != KErrNone )
+            {
+            delete msg;
+            // oom
+            return;
+            }
+        iMasterId = msg->SrcId();
+        delete msg;
+        }
+            
+    // Call AtsSend of CUIEngine interface
+    iUIEngine->RemoteMsg( this, aRemoteMsg );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: GoingToReboot
+
+    Description: Inform UI that phone is going to rebooted
+
+    Parameters: 
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngineContainer::GoingToReboot( TRequestStatus& aStatus )
+    {
+
+    __TRACE( KPrint, ( _L( "CUIEngineContainer::GoingToReboot.") ) );
+    
+    // Forward            
+    return iUIEngine->GoingToReboot( this, aStatus );
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineContainer
+
+    Method: RemoteReceive
+
+    Description: RemoteReceive forwards remote protocol messages to master
+
+    Parameters: 
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngineContainer::RemoteReceive( const TDesC& aRemoteMsg )
+    {
+
+    __TRACE( KPrint, ( _L( "CUIEngineContainer::RemoteReceive.") ) );
+    
+    // Check master test case status, FIX110
+    if( iState != ERunning )
+        {
+        __TRACE( KError, ( _L( "Master case not running") ) );
+
+        return KErrNotFound;
+        }
+    
+    HBufC8* buf = HBufC8::New( aRemoteMsg.Length() );
+    if( buf == NULL )
+        { 
+        return KErrNoMemory;
+        }
+      
+    TPtr8 tmp = buf->Des();
+    tmp.Copy( aRemoteMsg );     
+    TInt ret = iTestCase.NotifyRemoteMsg( tmp, EStifCmdReceive );
+    delete buf;
+  
+    return ret;
+    
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIEngineError.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,275 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CUIEngineErrorPrinter handles error prints from 
+* test framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <stifinternal/UIEngineContainer.h>
+#include "UIEngineError.h"
+#include "Logging.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iUIEngine->iLogger
+
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineErrorPrinter
+
+    Method: NewL
+
+    Description: Create a testcase runner.
+
+    Parameters: CUIEngineContainer* aContainer: in: Pointer to testcase container
+    
+    Return Values: CUIEngineErrorPrinter* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CUIEngineErrorPrinter* CUIEngineErrorPrinter::NewL( 
+                                CUIEngine* aUIEngine )
+    {
+
+    CUIEngineErrorPrinter* self = 
+        new ( ELeave ) CUIEngineErrorPrinter( aUIEngine );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineErrorPrinter
+
+    Method: ConstructL
+
+    Description: Second phase constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CUIEngineErrorPrinter::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineErrorPrinter
+
+    Method: CUIEngineErrorPrinter
+
+    Description: Constructor.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CUIEngineErrorPrinter::CUIEngineErrorPrinter( CUIEngine* aUIEngine ): 
+    CActive( EPriorityStandard ),
+    iUIEngine( aUIEngine ),
+    iErrorPckg( iError )
+    {
+    
+     __TRACE( KPrint, ( _L( "CUIEngineErrorPrinter::CUIEngineErrorPrinter") ) );
+    __ASSERT_ALWAYS( aUIEngine, User::Panic( _L("Null pointer"), KErrGeneral ) );
+    
+    CActiveScheduler::Add( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineErrorPrinter
+
+    Method: ~CUIEngineErrorPrinter
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CUIEngineErrorPrinter::~CUIEngineErrorPrinter( )
+    {
+    
+    __TRACE( KPrint, ( _L( "CUIEngineErrorPrinter::~CUIEngineErrorPrinter") ) );
+    Cancel();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineErrorPrinter
+
+    Method: StartL
+
+    Description: Starts a test case and sets the active object to active.
+
+    Parameters: RTestCase& aTestCase: in: Reference to the testcase object
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineErrorPrinter::StartL( RTestEngine& aEngine )
+    {
+    
+    iTestEngine = aEngine;
+ 
+    if ( IsActive() )
+        User::Leave( KErrInUse );
+
+    SetActive();   
+    iTestEngine.ErrorNotification ( iErrorPckg, iStatus );
+    
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineErrorPrinter
+
+    Method: RunL
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineErrorPrinter::RunL()
+    {
+
+    if( iStatus != KErrNone )
+        {
+        return;
+        }
+        
+    iUIEngine->ErrorPrint( iError );
+    
+    // Set new request
+    SetActive();   
+    iTestEngine.ErrorNotification ( iErrorPckg, iStatus );
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineErrorPrinter
+
+    Method: DoCancel
+
+    Description: Cancels the asynchronous request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CUIEngineErrorPrinter::DoCancel()
+    {
+
+    iTestEngine.CancelAsyncRequest ( ETestEngineErrorNotification );
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIEngineEvent.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,481 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CUIEngineEvent: This object executes test cases 
+* from STIF Test Framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <stifinternal/UIEngineContainer.h>
+#include "UIEngineEvent.h"
+#include "Logging.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iUIEngine->iLogger
+
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: CUIEngineEvent
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineEvent::CUIEngineEvent( CUIEngine* aUIEngine) :
+    CActive( CActive::EPriorityStandard ),
+    iState( EEventIdle ),
+    iUIEngine( aUIEngine ),
+    iEventPckg( iEvent )
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineEvent::CUIEngineEvent") ) );
+    __ASSERT_ALWAYS( aUIEngine, User::Panic( _L("Null pointer"), KErrGeneral ) );
+
+    CActiveScheduler::Add( this );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineEvent::ConstructL()
+    {
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+    
+    Parameters: CUIEngineContainer* CUIEngineContainer: in: Pointer to CUIEngineContainer Interface
+                TTestInfo& aTestInfo: in: Test info
+
+    Return Values: CUIEngineEvent* : Pointer to created runner object
+
+    Errors/Exceptions: Leaves if memory allocation for CUIEngineEvent fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineEvent* CUIEngineEvent::NewL( CUIEngine* aUIEngine )
+    {
+    CUIEngineEvent* self =  
+        new ( ELeave ) CUIEngineEvent( aUIEngine );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: ~CUIEngineEvent
+
+    Description: Destructor
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineEvent::~CUIEngineEvent()
+    {
+    
+    __TRACE( KPrint, ( _L( "CUIEngineEvent::~CUIEngineEvent()") ) );
+    Cancel();
+    
+    if( iState == EEventWaitCompleted )
+        {
+        // Release event
+        Release();
+        }
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: Request
+
+    Description: Request event.
+
+    Parameters: RTestCase& aTestCase: in: Handle to test case
+                TFullTestResultPckg& aFullTestResultPckg: in: Handle to TFullTestResultPckg
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngineEvent::Request( TDesC& aEventName, 
+                               TUint32 aMaster, 
+                               TUint32 aSlave )
+    {
+    
+    __TRACE( KPrint, ( _L( "CUIEngineEvent::Request %S"), &aEventName ) );
+    
+    iState = EEventRequested;
+    
+    iMaster = aMaster;
+    iSlave = aSlave; 
+    iEvent.SetType( TEventIf::EReqEvent );
+    iEvent.SetName( aEventName );
+    
+    TRequestStatus status;
+    iUIEngine->iTestEngine.Event( iEventPckg, status ); 
+    User::WaitForRequest( status );
+    
+    if( status.Int() == KErrNone )
+        {
+        // Enable event waiting
+        iState = EEventWait;            
+        iEvent.SetType( TEventIf::EWaitEvent );
+        SetActive();
+        iUIEngine->iTestEngine.Event( iEventPckg, iStatus ); 
+        }
+    return status.Int();
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: Release
+
+    Description: Release event.
+
+    Parameters: RTestCase& aTestCase: in: Handle to test case
+                TFullTestResultPckg& aFullTestResultPckg: in: Handle to TFullTestResultPckg
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngineEvent::Release()
+    {
+    
+    __TRACE( KPrint, ( _L( "CUIEngineEvent::Release %S"), &iEvent.Name() ) );
+    Cancel();
+   
+    TRequestStatus status;
+    // Release event
+    iState = EEventReleased;
+    iEvent.SetType( TEventIf::ERelEvent );
+    iUIEngine->iTestEngine.Event( iEventPckg, status ); 
+    User::WaitForRequest( status ); 
+    
+    return status.Int();
+    
+    }
+    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone, error is handled in
+                       RunError called by CActiveObject
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineEvent::RunL()
+    {
+    
+    __TRACE( KPrint, ( _L( "CUIEngineEvent::RunL") ) );
+
+    // Error handled in RunError
+    User::LeaveIfError ( iStatus.Int() );
+    
+    switch( iState )
+        {
+        case EEventWait:
+            {
+            // Create response 
+            CStifTFwIfProt* resp = CStifTFwIfProt::NewL();
+            CleanupStack::PushL( resp );    
+            
+            resp->CreateL();
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgResponse );
+            resp->AppendId( iSlave );
+            resp->AppendId( iMaster );
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+            resp->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRequest );
+            resp->Append( CStifTFwIfProt::EventStatus, 
+                         CStifTFwIfProt::EEventSet );
+            resp->Append( iEvent.Name() );
+            if( iEvent.EventType() == TEventIf::EState )
+                {
+                resp->Append( CStifTFwIfProt::EventStatusParams, 
+                             CStifTFwIfProt::EEventType,
+                             CStifTFwIfProt::EventType, 
+                             TEventIf::EState );
+                } 
+            // Send response
+            iUIEngine->RemoteMsg( NULL, resp->Message() );
+            CleanupStack::PopAndDestroy( resp );    
+            
+            if( iEvent.EventType() == TEventIf::EIndication )
+                {            
+                // Enable indication event waiting again
+                iEvent.SetType( TEventIf::EWaitEvent );
+                SetActive();
+                iUIEngine->iTestEngine.Event( iEventPckg, iStatus ); 
+                }
+            else  // state event, set only once for one request
+                {                
+                iState = EEventWaitCompleted;
+                }
+            }
+            break;
+        case EEventWaitCompleted:
+        case EEventRequested:
+        case EEventReleased:
+        default:
+            __TRACE( KError, ( _L( "CUIEngineEvent::RunL: Illegal state %d"), iState ) );
+            User::Leave( KErrGeneral );
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: DoCancel
+
+    Description: Cancel active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineEvent::DoCancel()
+    {
+    
+    __TRACE( KPrint, ( _L( "CUIEngineEvent::DoCancel") ) );
+    TRequestStatus status;
+
+    switch( iState )
+        {
+        case EEventWait:
+            // First cancel waiting
+            iEvent.SetType( TEventIf::ECancelWait );
+            iUIEngine->iTestEngine.Event( iEventPckg, status );
+            User::WaitForRequest( status ); 
+            iState = EEventWaitCompleted;
+            break;
+        default:
+            iUIEngine->iTestEngine.CancelAsyncRequest( ETestEngineEvent ); 
+            iState = EEventIdle;
+            break;
+        }
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineEvent
+
+    Method: RunError
+
+    Description: Handle errors from STIF TestFramework
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+    
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIEngineEvent::RunError( TInt aError )
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineEvent::RunError") ) );
+
+    switch( iState )
+        {
+        case EEventRequested:
+        case EEventWait:
+        case EEventWaitCompleted:
+        case EEventReleased:
+            {
+            // Create response
+            CStifTFwIfProt* resp = NULL; 
+            TRAPD( err, resp = CStifTFwIfProt::NewL(); );
+            if( err != KErrNone )
+                {
+                return KErrNone;
+                }
+
+            resp->CreateL();
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgResponse );
+            resp->AppendId( iSlave );
+            resp->AppendId( iMaster );
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+            resp->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRequest );
+            resp->Append( CStifTFwIfProt::EventStatus, 
+                         CStifTFwIfProt::EEventError );
+            resp->Append( iEvent.Name() );
+            resp->Append( CStifTFwIfProt::EventStatusParams, 
+                             CStifTFwIfProt::EEventResult,
+                             aError );
+            
+            // Send response
+            iUIEngine->RemoteMsg( NULL, resp->Message() ); 
+            delete resp;
+            }
+            break;
+        default:
+            __TRACE( KError, ( _L( "CUIEngineEvent::RunError: Illegal state %d"), iState ) );
+            return aError;
+        }
+    
+    return KErrNone;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    CActiveTimer: This object prints running seconds to console screen.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIEnginePrinter.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,290 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CUIEnginePrinter handles prints from test cases.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <stifinternal/UIEngineContainer.h>
+#include "UIEnginePrinter.h"
+#include "Logging.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iUIEngineContainer->iUIEngine->iLogger
+
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEnginePrinter
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CUIEngineContainer* CUIEngineContainer: in: Pointer to CUIEngineContainer Interface
+                TTestInfo& aTestInfo: in: Test info
+
+    Return Values: CUIEnginePrinter* : Pointer to created runner object
+
+    Errors/Exceptions: Leaves if memory allocation for CUIEnginePrinter fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CUIEnginePrinter* CUIEnginePrinter::NewL( 
+    CUIEngineContainer* aUIEngineContainer )
+    {
+    CUIEnginePrinter* self =
+        new ( ELeave ) CUIEnginePrinter( aUIEngineContainer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEnginePrinter
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEnginePrinter::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEnginePrinter
+
+    Method: CUIEnginePrinter
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEnginePrinter::CUIEnginePrinter( 
+    CUIEngineContainer* aUIEngineContainer ) :
+        CActive( CActive::EPriorityStandard ),
+        iUIEngineContainer( aUIEngineContainer ),
+        iProgressPckg( iProgress ),
+        iRunning( EFalse )
+    {
+    __TRACE( KPrint, ( _L( "CUIEnginePrinter::CUIEnginePrinter") ) );
+    __ASSERT_ALWAYS( aUIEngineContainer, User::Panic( _L("Null pointer"), KErrGeneral ) );
+
+    CActiveScheduler::Add( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEnginePrinter
+
+    Method: ~CUIEnginePrinter
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEnginePrinter::~CUIEnginePrinter()
+    {
+    __TRACE( KPrint, ( _L( "CUIEnginePrinter::~CUIEnginePrinter") ) );
+
+    Cancel();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEnginePrinter
+
+    Method: StartProgressL
+
+    Description: Starts testing
+
+    Parameters: RTestCase& aTestCase: in: Handle to test case
+                TTestProgressPckg& aProgressPckg: in: Handle to TTestProgressPckg
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEnginePrinter::StartL( RTestCase& aTestCase )
+    {
+    __TRACE( KPrint, ( _L( "CUIEnginePrinter::StartProgressL.") ) );
+
+    iTestCase = aTestCase;
+
+    if ( IsActive() )
+        User::Leave( KErrInUse );
+
+    iRunning = ETrue;
+
+    SetActive();
+    iTestCase.NotifyProgress( iProgressPckg, iStatus );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEnginePrinter
+
+    Method: RunL
+
+    Description: RunL handles completed requests
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone, error is handled in
+                       RunError called by CActiveObject
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEnginePrinter::RunL()
+    {
+    
+    if( iStatus != KErrNone )
+        {
+        // KErrEof and other errors
+        iRunning = EFalse;
+        // Signal to container
+        iUIEngineContainer->PrintsDone();
+        return;
+        }
+        
+    iUIEngineContainer->PrintProgress( iProgress );
+    
+    // Start a new request
+    SetActive();
+    iTestCase.NotifyProgress( iProgressPckg, iStatus );    
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEnginePrinter
+
+    Method: DoCancel
+
+    Description: Cancel active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEnginePrinter::DoCancel()
+    {
+    __TRACE( KPrint, ( _L( "CUIEnginePrinter::DoCancel") ) );
+    
+    iRunning = EFalse;
+
+    iTestCase.CancelAsyncRequest( ETestCaseNotifyProgress );
+    
+    }
+
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIEngineRemote.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,418 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CUIEngineRemote: This object executes test cases 
+* from STIF Test Framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <stifinternal/UIEngineContainer.h>
+#include "UIEngineRemote.h"
+#include "Logging.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iUIEngineContainer->iUIEngine->iLogger
+
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: CUIEngineRemote
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineRemote::CUIEngineRemote( CUIEngineContainer* aUIEngineContainer) :
+    CActive( CActive::EPriorityStandard ),
+    iUIEngineContainer( aUIEngineContainer ),
+    iRemoteTypePckg ( iRemoteType ),
+    iMsgLenPckg ( iMsgLen ),
+    iState( EIdle )
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRemote::CUIEngineRemote") ) );
+    __ASSERT_ALWAYS( aUIEngineContainer, User::Panic( _L("Null pointer"), KErrGeneral ) );
+
+    CActiveScheduler::Add( this );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRemote::ConstructL()
+    {
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+    
+    Parameters: CUIEngineContainer* CUIEngineContainer: in: Pointer to CUIEngineContainer Interface
+                TTestInfo& aTestInfo: in: Test info
+
+    Return Values: CUIEngineRemote* : Pointer to created runner object
+
+    Errors/Exceptions: Leaves if memory allocation for CUIEngineRemote fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineRemote* CUIEngineRemote::NewL( CUIEngineContainer* aUIEngineContainer )
+    {
+    
+    CUIEngineRemote* self =  
+        new ( ELeave ) CUIEngineRemote( aUIEngineContainer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: ~CUIEngineRemote
+
+    Description: Destructor
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineRemote::~CUIEngineRemote()
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRemote::~CUIEngineRemote()") ) );
+    Cancel();
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: StartTestL
+
+    Description: Starts testing
+
+    Parameters: RTestCase& aTestCase: in: Handle to test case
+                TFullTestResultPckg& aFullTestResultPckg: in: Handle to TFullTestResultPckg
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRemote::StartL( RTestCase& aTestCase )
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRemote::StartL") ) );
+
+    iTestCase = aTestCase;
+
+    if ( IsActive() )
+        User::Leave( KErrInUse );
+
+    Start();
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: Start
+
+    Description: Start request
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRemote::Start()
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRemote::Start") ) );
+
+    iState = EPending;
+    SetActive();
+    iTestCase.NotifyRemoteType( iRemoteTypePckg, iMsgLenPckg, iStatus );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone, error is handled in
+                       RunError called by CActiveObject
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRemote::RunL()
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRemote::RunL") ) );
+    
+    switch( iState )
+        {
+        case EPending:
+            iState = EIdle;
+            
+            switch( iRemoteType )
+                {
+                case EStifCmdSend: // Sending message
+                    {
+                    if( iMsgLen <= 0 ) 
+                        {
+                        User::Leave( KErrGeneral );
+                        }
+                    HBufC8* buf = HBufC8::NewLC( iMsgLen );
+                    TPtr8 tmp = buf->Des(); 
+                    if( iTestCase.NotifyRemoteMsg( tmp, iRemoteType ) == KErrNone )
+                        {
+                        HBufC* buf2 = HBufC::NewLC( iMsgLen );
+                        TPtr tmp2 = buf2->Des();
+                        tmp2.Copy( tmp );
+                        
+                        // Forward message
+                        iUIEngineContainer->RemoteSend( tmp2, iStatus.Int() );
+                        CleanupStack::PopAndDestroy( buf2 );
+                        }
+                    CleanupStack::PopAndDestroy( buf );
+                    }        
+                    break;
+                case EStifCmdStoreState: // Got indication that reboot will follow
+                    {
+                    // System will reboot, inform UI
+                    // Forward message
+                    SetActive();
+                    TInt ret = iUIEngineContainer->GoingToReboot( iStatus );
+                    if( ret != KErrNone )
+                        {
+                        User::Leave( ret );
+                        }
+                    iState = EUIMsgPending;
+                    return;
+                    }
+                // The rest should never come here
+                case EStifCmdReboot:
+                case EStifCmdReceive:
+                case EStifCmdGetStoredState:
+                default:
+                    {
+                    if( iStatus.Int() != KErrServerTerminated )
+                        {   
+                        RDebug::Print( _L("CUIEngineRemote::RunL() -- Leaved with [%d] "), iStatus.Int() );  
+                        User::Leave( KErrNotFound );  
+                        }
+                    break;
+                    }
+                }
+            break;
+        case EUIMsgPending:
+            {
+            TInt result = iStatus.Int();
+            if( result == KErrCancel )
+                {
+                result = KErrNone;
+                }
+            // Let the system to reboot..
+            TPckg<TInt> tmp(  result );
+            iTestCase.NotifyRemoteMsg( tmp, EStifCmdRebootProceed );
+            Start();
+            return;
+            }
+        default:
+            User::Leave( KErrGeneral );
+        }
+        
+    if( iStatus.Int() == KErrNone )
+        {   
+        Start();    
+        }
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: DoCancel
+
+    Description: Cancel active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRemote::DoCancel()
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRemote::DoCancel") ) );
+    iTestCase.CancelAsyncRequest( ETestCaseNotifyRemoteType );
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRemote
+
+    Method: RunError
+
+    Description: None
+
+    Parameters: TInt aError: in: Symbian error code
+
+    Return Values: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/    
+TInt CUIEngineRemote::RunError(TInt aError)
+    {
+    return aError;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    CActiveTimer: This object prints running seconds to console screen.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIEngineRunner.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,288 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CUIEngineRunner: This object executes test cases 
+* from STIF Test Framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <stifinternal/UIEngineContainer.h>
+#include "UIEngineRunner.h"
+#include "Logging.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iUIEngineContainer->iUIEngine->iLogger
+
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRunner
+
+    Method: CUIEngineRunner
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineRunner::CUIEngineRunner( CUIEngineContainer* aUIEngineContainer) :
+    CActive( CActive::EPriorityStandard ),
+    iUIEngineContainer( aUIEngineContainer ),
+    iFullTestResultPckg( iFullTestResult )
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRunner::CUIEngineRunner") ) );
+    __ASSERT_ALWAYS( aUIEngineContainer, User::Panic( _L("Null pointer"), KErrGeneral ) );
+
+    CActiveScheduler::Add( this );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRunner
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRunner::ConstructL()
+    {
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRunner
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+    
+    Parameters: CUIEngineContainer* CUIEngineContainer: in: Pointer to CUIEngineContainer Interface
+                TTestInfo& aTestInfo: in: Test info
+
+    Return Values: CUIEngineRunner* : Pointer to created runner object
+
+    Errors/Exceptions: Leaves if memory allocation for CUIEngineRunner fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineRunner* CUIEngineRunner::NewL( CUIEngineContainer* aUIEngineContainer )
+    {
+    CUIEngineRunner* self =  
+        new ( ELeave ) CUIEngineRunner( aUIEngineContainer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRunner
+
+    Method: ~CUIEngineRunner
+
+    Description: Destructor
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIEngineRunner::~CUIEngineRunner()
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRunner::~CUIEngineRunner()") ) );
+    Cancel();
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRunner
+
+    Method: StartTestL
+
+    Description: Starts testing
+
+    Parameters: RTestCase& aTestCase: in: Handle to test case
+                TFullTestResultPckg& aFullTestResultPckg: in: Handle to TFullTestResultPckg
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRunner::StartL( RTestCase& aTestCase )
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRunner::StartTestL") ) );
+
+    iTestCase = aTestCase;
+
+    if ( IsActive() )
+        User::Leave( KErrInUse );
+
+    SetActive();
+    iTestCase.RunTestCase( iFullTestResultPckg, iStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRunner
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone, error is handled in
+                       RunError called by CActiveObject
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRunner::RunL()
+    {
+    __TRACE( KPrint, ( _L( "CUIEngineRunner::RunL") ) );
+
+    // Complete with the result of the test case
+    iUIEngineContainer->TestCaseExecuted( iFullTestResult, iStatus.Int() );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIEngineRunner
+
+    Method: DoCancel
+
+    Description: Cancel active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIEngineRunner::DoCancel()
+    {
+
+    __TRACE( KPrint, ( _L( "CUIEngineRunner::DoCancel") ) );
+    iTestCase.CancelAsyncRequest( ETestCaseRunTestCase );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    CActiveTimer: This object prints running seconds to console screen.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIStore.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4842 @@
+/* 
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CUIStore 
+* and CModule class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <f32file.h>
+#include <e32uid.h>
+#include <collate.h>
+
+#include <StifLogger.h>
+
+#include "Logging.h"
+#include <stifinternal/UIStore.h>
+#include <stifinternal/UIEngine.h>
+#include <stifinternal/UIStoreContainer.h>
+#include "UIStorePopup.h"
+#include <stifinternal/UIEngineContainer.h>
+
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+//@spe _LIT(KNameTxt,"TEST FRAMEWORK");
+//@spe _LIT(KNameBase,"BASE");
+_LIT( KUIStore, "CUiStore" );
+_LIT( KUIStoreIf, "CUiStoreIf" );
+//_LIT( KUIStoreDefaultDir, "C:\\TestFramework\\" );
+
+_LIT( KUIStoreSetStart, "[TestSetStart]" );
+_LIT( KUIStoreSetEnd, "[TestSetEnd]" );
+_LIT( KUIStoreSetCaseStart, "[TestSetCaseStart]" );
+_LIT( KUIStoreSetCaseEnd, "[TestSetCaseEnd]" );
+_LIT( KUIStoreCaseModuleName, "ModuleName=" );
+_LIT( KUIStoreTestCaseTitle, "Title=" );
+_LIT( KUIStoreTestCaseFile, "TestCaseFile="); 
+_LIT( KUIStoreTestCaseNum, "TestCaseNum=");
+_LIT( KUIStoreCaseExpectedResult, "ExpectedResult=");
+_LIT( KUIStoreCasePriority, "Priority="); 
+_LIT( KUIStoreCaseTimeout, "Timeout=");
+_LIT( KUIStoreLastStartedCaseIndex, "LastStartedCaseIndex=");
+
+
+_LIT( KUIStoreDefaultRebootFile, "TestFrameworkUIReboot.txt" );
+_LIT( KUIStoreStartTest, "[StartTestCase]" );
+_LIT( KUIStoreStartTestEnd, "[StartTestCaseEnd]" );
+
+_LIT( KUIStoreCaseStatus, "TestCaseStatus=");
+_LIT( KUIStoreCaseExecutionResult, "TestCaseExecutionResult=");
+_LIT( KUIStoreCaseResult, "TestCaseResult=");
+_LIT( KUIStoreCaseStartTime, "TestCaseStartTime=");
+_LIT( KUIStoreCaseEndTime, "TestCaseEndTime=");
+
+const TInt KRcpHeaderLen = 16;        
+const TInt KFixedStartedCaseIndex = 10;
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iLogger
+
+// LOCAL CONSTANTS AND MACROS
+static const TUid KUidTestModule = { 0x101FB3E7 };
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: NewL
+
+    Description: Construct the CUIStore class
+
+    Parameters: None
+
+    Return Values: CUIStore*                    New object
+
+    Errors/Exceptions: Leaves if memory allocation fails or
+                       ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIStore* CUIStore::NewL( CUIStoreIf* aUIStoreIf )
+    {
+    
+    CUIStore* self = new ( ELeave ) CUIStore( aUIStoreIf );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Construct the console
+    Construct module and case containers
+    Retrieve command line parameters
+    Connect to test engine
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation fails or fileserver or
+                       test engine can't be connected.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::ConstructL( )
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: CUIStore
+
+    Description: Constructor.
+    Initialize non-zero member variables.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIStore::CUIStore( CUIStoreIf* aUIStoreIf ):
+    iUIStoreIf( aUIStoreIf ),
+    iUpdateNeeded( ETrue ),
+    iActivePopupPriority( EPopupPriorityLow )
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: ~CUIStore
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIStore::~CUIStore( )
+    {	
+
+    iFileList.ResetAndDestroy();
+    iFileList.Close(); 
+    iStartedTestSets.ResetAndDestroy();
+    iStartedTestSets.Close();  
+
+    iStartedTestCases.ResetAndDestroy();
+    iStartedTestCases.Close();
+    
+    iTestSets.ResetAndDestroy();
+    iTestSets.Close();  
+
+    iTestCases.ResetAndDestroy();
+    iTestCases.Close();
+    
+    iPopups.ResetAndDestroy();
+    iPopups.Close();
+        
+    delete iUIEngine;    
+    iUIEngine = 0;
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIf
+
+    Method: Open
+
+    Description: Open test engine.
+
+    Parameters: TDesC& aTestFrameworkIni: in: Initialization file to Test Framework
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C  TInt CUIStore::Open( const TDesC& aTestFrameworkIni )
+    {
+    
+    if( aTestFrameworkIni.Length() > KMaxFileName )
+        {
+        return KErrArgument;
+        }
+    
+    TRAPD( err, 
+        iUIEngine = CUIEngine::NewL( this );
+        );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+    
+    TFileName ini( aTestFrameworkIni );
+    // Check given ini file
+    TRAP( err, CheckIniL( ini ) );
+    
+    // Store folder of initialization file to open it again when looking for filters
+    RDebug::Print(_L("CUIStore stores name of ini file [%S]"), &ini);
+    iTestFrameworkIni.Copy(ini);
+    
+    return iUIEngine->Open( ini );
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: Close
+
+    Description: Close test engine.
+
+    Parameters: None
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::Close()
+    {
+    
+    TInt ret = KErrNone;
+    if( iUIEngine != NULL )
+        {
+        ret = iUIEngine->Close();
+    
+        delete iUIEngine;    
+        iUIEngine = 0;
+        }
+        
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: AddTestModule
+
+    Description: Add test module to module list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which is added to module list
+                TDesC& aIniFile: in: Initialization file to the test module
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::AddTestModule( const TDesC& aModuleName, 
+                                       const TDesC& aIniFile )
+    {
+
+    TInt ret = iUIEngine->AddTestModule( aModuleName, aIniFile );
+         
+    RefreshAllCases();
+    
+    return ret;
+         
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: RemoveTestModule
+
+    Description: Add test module to module list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which is removed of module list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::RemoveTestModule( const TDesC& aModuleName )
+    {
+
+    TInt ret = iUIEngine->RemoveTestModule( aModuleName );
+     
+    RefreshAllCases();
+    
+    return ret;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: AddTestCaseFile
+
+    Description: Add test case file to test case file list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which own test cases of test case list.
+                TDesC& aCaseFile: in: Test case list, which is added to test case list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::AddTestCaseFile( const TDesC& aModuleName, 
+                                         const TDesC& aCaseFile )
+    {
+
+    TInt ret = iUIEngine->AddTestCaseFile( aModuleName, aCaseFile );
+     
+    RefreshAllCases();
+    
+    return ret;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: RemoveTestCaseFile
+
+    Description: Remove test case file of test case file list of test engine
+
+    Parameters: TDesC& aModuleName: in: Testmodule, which own test cases of test case list
+                TDesC& aCaseFile: in: Test case list, which is removed of test case list
+
+    Return Values: Symbian OS error: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::RemoveTestCaseFile( const TDesC& aModuleName, 
+                                            const TDesC& aCaseFile )
+    {   
+    
+    TInt ret = iUIEngine->RemoveTestCaseFile( aModuleName, aCaseFile );
+         
+    RefreshAllCases();
+    
+    return ret;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: StartTestCase
+
+    Description: Start selected test case identified with CTestInfo.
+                anIndex contains index in StartedTestCase array, 
+                which is valid only during execution of calling 
+                function.
+
+    Parameters: const CTestInfo& aTestInfo: in: Test case info
+                TInt& anIndex: out: Index to StartedTestCaseArray returned 
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::StartTestCase( const CTestInfo& aTestInfo, 
+                                       TInt& anIndex )
+    {
+    
+    CUIEngineContainer* container = NULL;
+    TInt ret = iUIEngine->StartTestCase( container, aTestInfo );
+    
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    CStartedTestCase* testCase = NULL;
+    TRAP( ret,
+        testCase = CStartedTestCase::NewL( aTestInfo, *container );
+       );
+    if( ret != KErrNone )
+        {
+        iUIEngine->AbortStartedTestCase( container );
+        return ret;
+        }
+        
+    ret = iStartedTestCases.Append( testCase );
+    if( ret != KErrNone )
+        {
+        iUIEngine->AbortStartedTestCase( container );
+        delete testCase;
+        return ret;
+        }
+    
+    anIndex =  iStartedTestCases.Find( testCase );
+    
+    if( anIndex < 0 )
+        {
+        User::Panic( KUIStore, KErrNotFound );
+        }
+    
+    iUIStoreIf->Update( testCase, testCase->Status() ); 
+                
+    return KErrNone;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: TestCases
+
+    Description: Return array of existing test cases.
+
+    Parameters: RRefArray<CTestInfo>& aTestCases: out: Array of test cases
+                TDesC& aTestModule: in: Test module name (optional)
+                TDesC& aTestCaseFile: in: Test case file name (optional) 
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::TestCases( RRefArray<CTestInfo>& aTestCases, 
+                                   const TDesC& aTestModule,
+                                   const TDesC& aTestCaseFile ) 
+    {
+    
+    TInt ret = UpdateCases();
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    TInt count = iTestCases.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( ( aTestModule.Length() > 0 ) &&
+            ( iTestCases[i]->ModuleName() != aTestModule ) )
+            {
+            continue;
+            }
+        else if( ( aTestCaseFile.Length() > 0 ) &&
+                 ( iTestCases[i]->TestCaseFile() != aTestCaseFile ) )
+            {
+            continue;
+            }
+        aTestCases.Append( *iTestCases[i] );
+        }
+    
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: StartedTestCaseL
+
+    Description: Return started (running/runned) test case
+
+    Parameters: CStartedTestCase& aTestCase: out: Test case information
+                TInt anIndex: in: test case index in StartedTestCaseArray
+
+    Return Values: Reference to CStartedTestCase object
+
+    Errors/Exceptions: Leaves if anIndex out of range
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C CStartedTestCase& CUIStore::StartedTestCaseL( TInt anIndex )
+    {
+    
+    TInt count = iStartedTestCases.Count();
+    if( ( anIndex >= count ) ||
+        ( anIndex < 0 ) )
+        {
+        User::Leave( KErrNotFound );
+        }
+        
+    return *iStartedTestCases[anIndex];
+         
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: StartedTestCases
+
+    Description: Return started (running/runned) test cases
+
+    Parameters: RRefArray<CStartedTestCase>& aTestCases: out: array of test cases
+                TExecutionStatus aStatus: in: test case status (optional)
+                TDesC& aTestModule: in: test module name (optional)
+                TDesC& aTestCaseFile: in: test case file name (optional)
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/            
+EXPORT_C TInt CUIStore::StartedTestCases( RRefArray<CStartedTestCase>& aTestCases,
+                                          TInt aStatus,
+                                          const TDesC& aTestModule,
+                                          const TDesC& aTestCaseFile )
+    {
+    
+    TInt count = iStartedTestCases.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( ( aTestModule.Length() > 0 ) &&
+            ( iStartedTestCases[i]->TestInfo().ModuleName() != aTestModule ) )
+            {
+            continue;
+            }
+        else if( ( aTestCaseFile.Length() > 0 ) &&
+                 ( iStartedTestCases[i]->TestInfo().TestCaseFile() != aTestCaseFile ) )
+            {
+            continue;
+            }
+        else if( ( aStatus != CUIStoreIf::EStatusAll) &&
+                 !( iStartedTestCases[i]->Status() & aStatus ) )
+            {
+            continue;
+            }
+        if( aTestCases.Append( *iStartedTestCases[i] ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    
+    return KErrNone;
+    
+    }
+            
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: Modules
+
+    Description: Return modules array
+
+    Parameters: RRefArray<CModule>& aTestModules: out: modules array
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/     
+EXPORT_C TInt CUIStore::Modules( RRefArray<TDesC>& aTestModules )
+    {
+
+    TInt ret = UpdateCases();
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+
+    // Go through test cases and search if there are new modules 
+    // and add them to aTestModules array 
+    TInt caseCount = iTestCases.Count();
+    TInt moduleCount = 0;
+    TInt caseIndex = 0;
+    TInt moduleIndex = 0;
+    for ( caseIndex = 0; caseIndex < caseCount; caseIndex++ )
+        {
+        // First check modules
+        moduleCount = aTestModules.Count();
+        for ( moduleIndex = 0; moduleIndex < moduleCount; moduleIndex++ )
+            {
+            if( iTestCases[caseIndex]->ModuleName() == 
+                aTestModules[moduleIndex] )
+                {
+                break;
+                }
+            }
+        if ( moduleIndex == moduleCount )
+            {
+            // New module found
+            if( aTestModules.Append( iTestCases[caseIndex]->ModuleName() ) !=
+                KErrNone )
+                {
+                return KErrNoMemory;
+                } 
+            }
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: TestCaseFiles
+
+    Description: Return test case files
+
+    Parameters: RRefArray<TDesC>& aTestCaseFiles: out: Array of test case files
+                TDesC& aTestModule: in: test module name (optional)
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/     
+EXPORT_C TInt CUIStore::TestCaseFiles( RRefArray<TDesC>& aTestCaseFiles,
+                                       const TDesC& aTestModule  )
+    {
+    
+    TInt ret = UpdateCases();
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+
+    // Go through test cases and search if there are new test case files 
+    // for specified test module and add them to aTestCaseFiles array 
+    TInt caseCount = iTestCases.Count();
+    TInt fileCount = 0;
+    TInt caseIndex = 0;
+    TInt fileIndex = 0;
+    for ( caseIndex = 0; caseIndex < caseCount; caseIndex++ )
+        {
+        if( ( aTestModule.Length() > 0 ) &&
+            ( aTestModule != iTestCases[caseIndex]->ModuleName() ) )
+            {
+            // Test case file is not for specified module
+            continue;
+            }
+            
+        // First check modules
+        fileCount = aTestCaseFiles.Count();
+        for ( fileIndex = 0; fileIndex < fileCount; fileIndex++ )
+            {
+            if( iTestCases[caseIndex]->TestCaseFile() == 
+                aTestCaseFiles[fileIndex] )
+                {
+                break;
+                }
+            }
+        if ( fileIndex == fileCount )
+            {
+            // New test case file found
+            if( aTestCaseFiles.Append( iTestCases[caseIndex]->TestCaseFile() ) !=
+                KErrNone )
+                {
+                return KErrNoMemory;
+                } 
+            }
+        }
+
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: LoadAllModules
+
+    Description: Loads all TestFramework test modules from \system\libs\ directories 
+                of all drives. In Secure Platform from \sys\bin directories.
+
+    Parameters: None
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CUIStore::LoadAllModules()
+    {
+    
+    RPointerArray<TDesC> testModules;
+    
+    TInt ret = ListAllModules( testModules );
+    if( ret == KErrNone )
+        {
+        for (TInt i= 0; i < testModules.Count(); i++)
+            {
+            iLogger->Log( _L("Add test module: %S"), testModules[i] );
+            ret = iUIEngine->AddTestModule( *testModules[i], KNullDesC );
+            if( ret != KErrNone )
+                {
+                iLogger->Log( _L("Add test module %S failed %d"), 
+                    testModules[i], ret );
+                break;
+                }
+            }
+        }
+    RefreshAllCases();
+    
+    testModules.ResetAndDestroy();
+    testModules.Close();
+    
+    return ret;
+
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: ListAllModules
+
+    Description: Lists all TestFramework test modules from \system\libs\ directories 
+                of all drives. In Secure Platform from \sys\bin directories.
+
+    Parameters: None
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CUIStore::ListAllModules( RPointerArray<TDesC>& aModuleNames )
+    {
+    
+    TRAPD( err, ListAllModulesL( aModuleNames ); );
+    return err;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: ListAllModulesL
+
+    Description: Lists all TestFramework test modules from \system\libs\ directories 
+                of all drives. In Secure Platform from \sys\bin directories.
+
+    Parameters: None
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+void CUIStore::ListAllModulesL( RPointerArray<TDesC>& aModuleNames )
+    {
+
+    TFileName libDirectory;
+    RFs fsSession;
+    TFileName fullName;
+
+    // Connect to file server
+	User::LeaveIfError( fsSession.Connect() ); // Start session
+	CleanupClosePushL( fsSession );
+
+    TDriveList drivelist; 
+	User::LeaveIfError( fsSession.DriveList(drivelist) );
+	// A TDriveList (the list of available drives), is an array of 
+	// 26 bytes. Each byte with a non zero value signifies that the 
+	// corresponding drive is available.
+
+    // 0x10000079, 0x1000008d, 0x101FB3E7
+    TUidType anEntryUid( KDynamicLibraryUid, 
+                         KSharedLibraryUid, 
+                         KUidTestModule ); 
+    TInt driveNumber; 
+	TChar driveLetter;
+
+    CDir* testModules = NULL;
+    
+	for( driveNumber=EDriveA; driveNumber<=EDriveZ; driveNumber++ )
+		{
+		if( !drivelist[driveNumber] ) 
+			{
+			// If drive-list entry is zero, drive is not available
+			continue;
+			}
+        User::LeaveIfError(fsSession.DriveToChar(driveNumber,driveLetter));
+
+        libDirectory.Zero();
+        libDirectory.Append( driveLetter );
+        libDirectory.Append( _L(":\\sys\\bin\\*") );
+        
+        iLogger->Log( _L("Searching modules from %S"), &libDirectory );
+
+        fsSession.GetDir( libDirectory, anEntryUid, ESortNone, testModules );
+
+        if( !testModules )
+            {
+            // Continue if no test modules found
+            continue;
+            }
+        TInt count = testModules->Count();
+        for (TInt i= 0; i < count; i++)
+            {           
+            fullName = (*testModules)[i].iName;
+            
+            fullName.LowerCase();
+            // Remove optional '.DLL' from file name
+            TParse parse;
+            parse.Set( fullName, NULL, NULL );
+    
+            if ( parse.Ext() == _L(".dll") )
+                {
+                const TInt len = parse.Ext().Length();
+                fullName.Delete( fullName.Length()-len, len );
+                }
+                        
+            // Exclude internal test modules (testcombiner, testscripter, suevent)
+            _LIT(KTestCombiner, "testcombiner");
+            _LIT(KTestScripter, "testscripter");
+            _LIT(KSUEvent, "suevent");
+            if(fullName != KTestCombiner && fullName != KSUEvent && fullName != KTestScripter)
+                { 
+                HBufC* name = fullName.AllocLC();
+                iLogger->Log( _L("Found: %S"), name );
+                User::LeaveIfError( aModuleNames.Append( name ) );
+                CleanupStack::Pop( name );
+                }
+            }
+        delete testModules;
+        testModules = NULL;
+		}
+    
+    CleanupStack::PopAndDestroy(); // fsSession 
+    
+    } 
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: CreateTestSet
+
+    Description: Create new test set.
+
+    Parameters: TDesC& aSetName: in: test set name (Max length is KMaxName)
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CUIStore::CreateTestSet( const TDesC& aSetName )
+    {
+    
+    TPtrC setName;
+    TFileName tmp;
+    TInt ret = ParseTestSetName( aSetName, setName, tmp );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+        
+    CTestSetInfo* setInfo = NULL;
+    if( FindSetByName( setName, setInfo ) == KErrNone )
+        {
+        return KErrAlreadyExists;
+        }
+    TRAPD( err, 
+        setInfo = CTestSetInfo::NewL( setName );
+        );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+    if( iTestSets.Append( setInfo ) != KErrNone )
+        {
+        delete setInfo;
+        return KErrNoMemory;
+        }
+            
+    return KErrNone;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: RemoveTestSet
+
+    Description: Remove active test set.
+
+    Parameters: TDesC& aSetName: in: test set name (Max length is KMaxName)
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CUIStore::RemoveTestSet( const TDesC& aSetName )
+    {
+    TInt err = UnloadTestSet( aSetName );
+    if ( err != KErrNone )
+        {
+        return err;
+        }
+    
+    TFileName setfile;
+    setfile.Append(KUIStoreDefaultDir);
+    setfile.Append(aSetName);
+    RFs fs;
+    err = fs.Connect();
+    if( err != KErrNone )
+        {
+        fs.Close();
+        return err;
+        }
+    err = fs.Delete( setfile );
+    if ( err != KErrNone )
+        {
+        fs.Close();
+        return err;    
+        }
+    
+    return KErrNone;   
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: UnloadTestSet
+
+    Description: Unloads active test set.
+
+    Parameters: TDesC& aSetName: in: test set name (Max length is KMaxName)
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CUIStore::UnloadTestSet( const TDesC& aSetName )
+    {    
+    TPtrC setName;
+    TFileName tmp;
+    TInt ret = ParseTestSetName( aSetName, setName, tmp );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    TInt count = iTestSets.Count();
+    TInt index = 0;
+    for( ; index < count; index++ )
+        {
+        if( iTestSets[index]->Name() == setName )
+            {
+            break;
+            }
+        }
+    if( index == count ) 
+        { 
+        return KErrNotFound;
+        }
+
+    CTestSetInfo* setInfo = iTestSets[index];
+    iTestSets.Remove( index );
+    
+    // If started test set keeps info about currently removed test set
+    // then remove also this info
+    CStartedTestSet *stset;
+    for(index = 0; index < iStartedTestSets.Count(); index++)
+        {
+        stset = iStartedTestSets[index];
+        if(stset->GetOriginalTestSet() == setInfo)
+            {
+            stset->NullOriginalTestSet();
+            }
+        }
+    
+    delete setInfo;
+    
+    return KErrNone;    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: TestSets
+
+    Description: Query test sets.
+
+    Parameters:RRefArray<CTestSetInfo>& aSetInfos: out: list of test sets
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CUIStore::TestSets( RRefArray<CTestSetInfo>& aSetInfos )
+    {
+    
+    TInt count = iTestSets.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aSetInfos.Append( *iTestSets[i] ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    return KErrNone;
+    
+    }       
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: TestSets
+
+    Description: Query test sets.
+
+    Parameters:RRefArray<CTestSetInfo>& aSetInfos: out: list of test sets
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C const CTestSetInfo& CUIStore::TestSetL( const TDesC& aSetName  )
+    {
+    
+    TPtrC setName;
+    TFileName tmp;
+    User::LeaveIfError( ParseTestSetName( aSetName, setName, tmp ) );
+        
+    CTestSetInfo* setInfo = NULL;
+    User::LeaveIfError( FindSetByName( setName, setInfo ) );
+    return *setInfo;
+    
+    }                
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: AddToTestSet
+
+    Description: Add test case to test set.
+
+    Parameters: TDesC& aSetName: out: test set name
+                CTestInfo& aTestInfo: in: test case to add
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CUIStore::AddToTestSet( const TDesC& aSetName, 
+                                      const CTestInfo& aTestInfo )
+    {
+    
+    TPtrC setName;
+    TFileName tmp;
+    TInt ret = ParseTestSetName( aSetName, setName, tmp );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+        
+    CTestSetInfo* setInfo = NULL;
+    ret = FindSetByName( setName, setInfo );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    return setInfo->AddTestCase( aTestInfo );
+        
+    }       
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: InsertToTestSet
+
+    Description: Insert test case to test set.
+
+    Parameters: TDesC& aSetName: out: test set name
+                CTestInfo& aTestInfo: in: test case to add
+                TInt aPos: in: position to add
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CUIStore::InsertToTestSet( const TDesC& aSetName, 
+                                         const CTestInfo& aTestInfo,
+                                         TInt aPos  )
+    {
+    
+    TPtrC setName;
+    TFileName tmp;
+    TInt ret = ParseTestSetName( aSetName, setName, tmp );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+        
+    CTestSetInfo* setInfo = NULL;
+    ret = FindSetByName( setName, setInfo );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    return setInfo->InsertTestCase( aTestInfo, aPos );
+        
+    }       
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: RemoveFromTestSet
+
+    Description: Remove test case from test set.
+
+    Parameters: TDesC& aSetName: out: test set name
+                CTestInfo& aTestInfo: in: test case to remove
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::RemoveFromTestSet( const TDesC& aSetName, 
+                                           const CTestInfo& aTestInfo )
+    {
+    
+    TPtrC setName;
+    TFileName tmp;
+    TInt ret = ParseTestSetName( aSetName, setName, tmp );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+        
+    CTestSetInfo* setInfo = NULL;
+    ret = FindSetByName( setName, setInfo );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    return setInfo->RemoveTestCase( aTestInfo );
+    
+    }       
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: SaveTestSet
+
+    Description: Save test set. Deprecated, SaveTestSet2 to be used instead 
+
+    Parameters: TDesC&:  out: test set name
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::SaveTestSet( const TDesC& /* aSetName */ )
+    {  
+        
+    return KErrNotSupported;
+    
+    }  
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: SaveTestSet2
+
+    Description: Save test set.
+
+    Parameters: TDes& aSetName: out: test set name
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::SaveTestSet2( TDes& aSetName )
+    {
+    
+    RRefArray<TDesC> testsets;
+    
+    GetTestSetsList(testsets);
+    TBool isexist(EFalse);
+    for(TInt i=0;i<testsets.Count();i++)
+    {
+       if(testsets[i]==aSetName)
+           {
+           isexist=ETrue;
+           break;
+           }
+    
+    }
+    testsets.Reset();
+    if(!isexist)
+    {
+        TTime current;
+        TDateTime date_rep;
+        current.HomeTime();
+        date_rep = current.DateTime();
+        TBuf<32> currSetName;
+        _LIT(f_ext,".set");
+        
+        //create "test set name" string
+        currSetName.AppendNum(date_rep.Year());
+        currSetName.Append('_');
+        currSetName.AppendNum(date_rep.Month()+1); // Incrimination necessary, because Day and Month fields of TDateTime class are 0 based
+        currSetName.Append('_');
+        currSetName.AppendNum(date_rep.Day()+1);
+        currSetName.Append('_');
+        currSetName.AppendNum(date_rep.Hour());
+        currSetName.Append('_');
+        currSetName.AppendNum(date_rep.Minute());
+        currSetName.Append('_');
+        currSetName.AppendNum(date_rep.Second());
+        currSetName.Append(f_ext);
+        
+        for(TInt i=0;i<iTestSets.Count();i++)
+        {
+            if(iTestSets[i]->Name()==aSetName)
+                {
+                iTestSets[i]->RenameTestSet(currSetName);
+                
+                }
+        
+        }
+        
+        
+        
+        aSetName.Zero();
+        aSetName.Copy(currSetName);
+       
+        
+    
+    }
+    TPtrC setName;
+    TFileName tmp;
+
+    
+
+    TInt ret = ParseTestSetName( aSetName, setName, tmp );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+        
+    CTestSetInfo* setInfo = NULL;
+    ret = FindSetByName( setName, setInfo );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+     
+    TRAPD( err,
+        SaveTestSetL( *setInfo, aSetName );
+        );
+    
+   
+    
+    return err;
+    
+    }  
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: LoadTestSet
+
+    Description: Load test set.
+
+    Parameters: TDesC& aSetName: out: test set name
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::LoadTestSet( const TDesC& aSetName )
+    {
+    TPtrC setName;
+    TFileName tmp;
+    TInt ret = ParseTestSetName( aSetName, setName, tmp );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    CTestSetInfo* setInfo= NULL;
+    
+    FindSetByName( setName, setInfo );
+    if(setInfo != NULL)
+        {
+        return KErrNone;
+        }
+    
+    TRAPD( err, 
+        setInfo = CTestSetInfo::NewL( aSetName );
+        );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+    if( iTestSets.Append( setInfo ) != KErrNone )
+        {
+        delete setInfo;
+        return KErrNoMemory;
+        }
+
+    TRAP( err,
+        LoadTestSetL( setName, aSetName );
+        );
+    
+     if( err != KErrNone && err != KErrAlreadyExists )
+        {
+        RemoveTestSet( setName );
+        }
+            
+    return err;
+    
+    }       
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: UpdateTestSet
+
+    Description: Updates (on storage) earlier saved test set.
+
+    Parameters: CTestSetInfo& aSetInfo: in: test set
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::UpdateTestSet(CTestSetInfo& aSetInfo)
+    {
+    TRAPD(err,
+          UpdateTestSetL(aSetInfo, aSetInfo.Name());
+         );
+         
+    return err;
+    }  
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: StartTestSet
+
+    Description: Start selected test set identified with CTestSetInfo.
+
+    Parameters: const CTestSetInfo& aTestSetInfo: in: Started test set
+                TInt& anIndex: out index in StartedTestSet array, 
+                    which is valid only during execution of calling 
+                    function.
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TInt CUIStore::StartTestSet( const CTestSetInfo& aTestSetInfo,
+                                      TInt& anIndex,
+                                      CStartedTestSet::TSetType aType )
+    {
+    return StartTestSet(aTestSetInfo, anIndex, aType, EFalse);    
+    }       
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: StartTestSet
+
+    Description: Start selected test set identified with CTestSetInfo.
+
+    Parameters: const CTestSetInfo& aTestSetInfo: in: Started test set
+                TInt& anIndex: out index in StartedTestSet array, 
+                    which is valid only during execution of calling 
+                    function.
+                TSetType aType: sequential or paraller
+                TBool aNotExecutedCasesMode: only test case which haven't been
+                    executed yet
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TInt CUIStore::StartTestSet( const CTestSetInfo& aTestSetInfo,
+                                      TInt& anIndex,
+                                      CStartedTestSet::TSetType aType,
+                                      TBool aNotStartedCasesMode )
+    {
+    
+    TInt ret = KErrNone;
+    
+    CStartedTestSet* set = NULL;
+    TRAPD( err, 
+        set = CStartedTestSet::NewL( this, aTestSetInfo, aType );
+        );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+
+    if( iStartedTestSets.Append( set ) != KErrNone )
+        {
+        delete set;
+        return KErrNoMemory;
+        } 
+
+    // Set mode in which only still not executed test cases will be run.
+    // It applies only to sequential execution.
+    set->SetNotStartedCasesMode(aNotStartedCasesMode);
+    
+    ret = set->StartNext();
+        
+    anIndex = iStartedTestSets.Find( set );
+    if( anIndex < 0 )
+        {
+        User::Panic( KUIStore, KErrNotFound );
+        }
+    // Check that testset starting was successful
+    if( ret != KErrNone )
+        {
+        iStartedTestSets.Remove( anIndex );
+        anIndex = KErrNotFound; // safety
+        delete set;
+        return ret;
+        }
+    
+    return KErrNone;
+    
+    }       
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: AbortTestSet
+
+    Description: Abort running test set.
+
+    Parameters: None
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::AbortTestSet( CStartedTestSet& aSetInfo )
+    {
+        
+    return aSetInfo.Abort();
+    
+    } 
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: StartedTestSetL
+
+    Description: Return started (running/runned) test set.
+
+    Parameters: TInt anIndex: out index in StartedTestSet array 
+                        
+    Return Values: CStartedTestSet&: reference to test set
+
+    Errors/Exceptions: Leaves on error.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/  
+EXPORT_C CStartedTestSet& CUIStore::StartedTestSetL( TInt anIndex)
+    {
+    
+    if( anIndex < 0 ||
+        anIndex >= iStartedTestSets.Count() )
+        {
+        User::Leave( KErrNotFound );
+        }
+    
+    return *iStartedTestSets[ anIndex ];
+    
+    }       
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: StartedTestSets
+
+    Description: Return started (running/runned) test cases
+
+    Parameters: RRefArray<CStartedTestSet>& aTestCases: out: list of test sets
+                TInt aStatus: in: status of queried sets
+                        
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::StartedTestSets( RRefArray<CStartedTestSet>& aTestSets,
+                                         TInt aStatus )
+    {    
+    
+    TInt count = iStartedTestSets.Count();
+    
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( ( aStatus != CUIStoreIf::ESetAll) &&
+            !( iStartedTestSets[i]->Status() & aStatus ) )
+            {
+            continue;
+            }
+        if( aTestSets.Append( *iStartedTestSets[i] ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }        
+        
+    return KErrNone;
+    
+    }           
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: LoadSavedTestCases
+
+    Description: Load saved testcases.
+
+    Parameters: None
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::LoadSavedTestCases()
+    {
+    
+    TRAPD( err,
+        LoadExecutedTestCasesL();
+        );
+    
+    return err;
+    
+    }       
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: GetTestSetsList
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CUIStore::GetTestSetsList( RRefArray<TDesC>& aArray )
+    {
+    RFs fileReader;
+    CDir* dirContents = NULL;
+    _LIT(KSetPattern,".set");
+    TInt entNum = 0;
+    TInt ret = 0;
+    HBufC* fName = NULL;
+
+    
+    ret = fileReader.Connect();
+
+    if (ret != KErrNone)
+    	return ret;
+    
+    
+    ret = fileReader.GetDir(KUIStoreDefaultDir,
+    						KEntryAttNormal | KEntryAttHidden | KEntryAttSystem,
+    						ESortByName | EDirsFirst | EAscending,
+    						dirContents);
+    fileReader.Close();	
+    if (ret != KErrNone)
+    	{    		
+	    delete dirContents;
+	    return ret;
+	    }
+    entNum = dirContents->Count();
+    for (int i = 0;i<entNum;i++)
+    	{
+    	if ((!dirContents->operator[](i).IsDir())&&
+    		 dirContents->operator[](i).iName.Find(KSetPattern)!=KErrNotFound)
+    			{
+    			  TRAPD( err, fName = HBufC::NewL(64) );		       			             
+    			  if( err != KErrNone )
+    			    {
+    			      delete dirContents;
+    			      return err;
+    			    }    		 	
+    		    *fName =  dirContents->operator[](i).iName;
+    		 	ret = iFileList.Append(fName);
+    		 	if (ret != KErrNone)
+    		 		{
+    					delete fName;
+    					delete dirContents;
+    					return ret;	
+    		 		}
+    		 	ret = aArray.Append(*fName);
+			 	if (ret != KErrNone)
+    		 		{
+    					delete fName;
+    					delete dirContents;
+    					return ret;	
+    		 		}
+
+    			}    
+    	}
+    delete dirContents;
+    return KErrNone; 
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: FindSetByName
+
+    Description: Finds test set by name.
+
+    Parameters: const TDesC& aSetName: in: set name 
+                CTestSetInfo*& aSetInfo: out: pointer to test set
+                        
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::FindSetByName( const TDesC& aSetName, 
+                              CTestSetInfo*& aSetInfo )
+    {
+    
+    TInt count = iTestSets.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( iTestSets[i]->Name() == aSetName )
+            {
+            aSetInfo = iTestSets[i];
+            return KErrNone;
+            }
+        }
+    
+    return KErrNotFound;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: FindSetByCase
+
+    Description: Finds test set by name.
+
+    Parameters:  const CStartedTestCase* aTestCase: in: running test case 
+                 CStartedTestSet*& aSet: out: set running test case
+                        
+    Return Values: KErrNotFound: test case is not runned by any test set
+                   KErrNone: test case was runned by aSet
+                   
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::FindStartedSetByCase( const CStartedTestCase* aTestCase, 
+                                     CStartedTestSet*& aSet  )
+    {
+    
+    TInt count = iStartedTestSets.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( iStartedTestSets[i]->IsRunning( aTestCase ) )
+            {
+            aSet = iStartedTestSets[i];
+            return KErrNone;
+            }
+        }
+    
+    return KErrNotFound;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: LoadTestSetL
+
+    Description: Load test set.
+
+    Parameters: TDesC& aSetName: out: test set name
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::LoadTestSetL( const TDesC& aSetName, const TDesC& /*aSetFileName*/ )
+    {
+    
+    TPtrC tmp;
+    TInt num;
+    TInt high;
+    TInt64 interval;
+    
+    CStifParser* parser = CStifParser::NewL( KUIStoreDefaultDir, aSetName );
+
+        
+    CleanupStack::PushL( parser );
+    
+    CStifSectionParser* section = 
+        parser->SectionL( KUIStoreSetStart, KUIStoreSetEnd );
+    CleanupStack::PushL( section );
+    
+    CStifItemParser* item;
+
+    // Get started test case (if possible)
+    TUint lastStartedCaseIndex = 0;
+    item = section->GetItemLineL(KUIStoreLastStartedCaseIndex);
+    if(item)
+        {
+        CleanupStack::PushL(item);
+        TInt r = item->GetInt(KUIStoreLastStartedCaseIndex, lastStartedCaseIndex);
+        CleanupStack::PopAndDestroy(item);
+        if(r != KErrNone)
+            {
+            __TRACE(KInit, (_L("Could not read [%S] from test set file. Result [%d]."), &KUIStoreLastStartedCaseIndex, r));
+            }
+        }
+    else
+        {
+        __TRACE(KInit, (_L("Could not find [%S] from test set file."), &KUIStoreLastStartedCaseIndex));
+        }
+
+    
+    CTestSetInfo* setInfo = NULL;
+    User::LeaveIfError( FindSetByName( aSetName, setInfo ) );
+    
+    // Update started case
+    setInfo->SetLastStartedCaseIndex(lastStartedCaseIndex);
+    
+    CTestInfo* testInfo = CTestInfo::NewL();
+    CleanupStack::PushL( testInfo );    
+
+    CStifSectionParser* subSection = 
+        section->SubSectionL( KUIStoreSetCaseStart, KUIStoreSetCaseEnd );
+    
+    while( subSection )
+        {
+        CleanupStack::PushL( subSection );    
+        
+        // Get module name
+        // Mandatory, leave if not found
+        User::LeaveIfError( 
+            subSection->GetLine( KUIStoreCaseModuleName, tmp, ENoTag ) );
+        testInfo->SetModuleName( tmp );
+    
+        // Get test case title
+        // Mandatory, leave if not found
+        User::LeaveIfError( 
+            subSection->GetLine( KUIStoreTestCaseTitle, tmp, ENoTag ) );
+        testInfo->SetTestCaseTitle( tmp );
+        
+        // Get test case file
+        num = subSection->GetLine( KUIStoreTestCaseFile, tmp, ENoTag );
+        if( ( num == KErrNone ) &&
+            ( tmp.Length() > 0 ) )
+            {
+            // Optional
+            testInfo->SetTestCaseFile( tmp );
+            }
+        
+        // Get test case number
+        item = subSection->GetItemLineL( KUIStoreTestCaseNum );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreTestCaseNum, num ));
+        testInfo->SetTestCaseNumber( num );
+        CleanupStack::PopAndDestroy( item );    
+        
+        // Get test case priority
+        item = subSection->GetItemLineL( KUIStoreCasePriority );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreCasePriority, num ));
+        testInfo->SetPriority( num );
+        CleanupStack::PopAndDestroy( item ); 
+        
+        // Get test case timeout
+        item = subSection->GetItemLineL( KUIStoreCaseTimeout );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreCaseTimeout, num ));
+        User::LeaveIfError( item->GetNextInt( high ));
+        //@js<--remove--> interval.Set( high, num );
+        interval = MAKE_TINT64( high, num );
+        TTimeIntervalMicroSeconds timeout( interval );
+        testInfo->SetTimeout( timeout );
+        CleanupStack::PopAndDestroy( item ); 
+        
+        User::LeaveIfError( setInfo->AddTestCase( *testInfo ) );
+        
+        CleanupStack::PopAndDestroy( subSection );    
+        subSection = 
+            section->NextSubSectionL( KUIStoreSetCaseStart, KUIStoreSetCaseEnd );
+        } 
+        
+    CleanupStack::PopAndDestroy( testInfo );    
+    CleanupStack::PopAndDestroy( section );
+    CleanupStack::PopAndDestroy( parser );
+    
+    const RRefArray<const CTestInfo>& testCases = setInfo->TestCases();
+    LoadTestModulesAndTestCaseFilesL( testCases );
+     
+    }     
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: SaveTestSetL
+
+    Description: Save test set.
+
+    Parameters: CTestSetInfo& aSetInfo: in: test set
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::SaveTestSetL( CTestSetInfo& aSetInfo, const TDesC& aSetFileName )
+    {
+    //Extract path
+    TParse p;
+    p.Set(aSetFileName, NULL, NULL);
+    TPtrC path =  p.DriveAndPath(); // gives path for test set
+    TPtrC fn = p.NameAndExt(); // gives filename with extension
+    if(path.Length() == 0)
+        {
+        path.Set(KUIStoreDefaultDir);
+        }
+
+    //Create file server
+    RFs fs;
+    User::LeaveIfError(fs.Connect());
+    CleanupClosePushL(fs);
+
+    //Create or open file
+    RFile file;
+    TFileName filename = path;
+    filename.Append(fn);
+    
+    TInt r = file.Replace(fs, filename, EFileWrite);
+    if(r != KErrNone)
+        {
+        User::Leave(r);
+        }
+    else
+        {
+        CleanupClosePushL(file);
+        
+        RBuf buffer;
+        buffer.Create(256);
+        CleanupClosePushL(buffer);
+        
+        // Saving
+        buffer.Format(_L("%S"), &KUIStoreSetStart);
+        WriteLineL(file, buffer);
+
+        // Saving test set causes reset of index
+        aSetInfo.SetLastStartedCaseIndex(0);
+        buffer.Format(_L("%S "), &KUIStoreLastStartedCaseIndex);
+        buffer.AppendNumFixedWidth(aSetInfo.GetLastStartedCaseIndex(), EDecimal, KFixedStartedCaseIndex);
+        WriteLineL(file, buffer);
+
+        // Saving test cases
+        TInt count = aSetInfo.TestCases().Count();
+        for(TInt i = 0; i < count; i++)
+            {
+            WriteLineL(file, KNullDesC);
+            buffer.Format(_L("%S"), &KUIStoreSetCaseStart);
+            WriteLineL(file, buffer);
+            
+            buffer.Format(_L("%S %S"), &KUIStoreCaseModuleName, &aSetInfo.TestCases()[i].ModuleName());
+            WriteLineL(file, buffer);
+            buffer.Format(_L("%S %S"), &KUIStoreTestCaseTitle, &aSetInfo.TestCases()[i].TestCaseTitle());
+            WriteLineL(file, buffer);
+            if(aSetInfo.TestCases()[i].TestCaseFile().Length() > 0)
+                {
+                buffer.Format(_L("%S %S"), &KUIStoreTestCaseFile, &aSetInfo.TestCases()[i].TestCaseFile());
+            WriteLineL(file, buffer);
+                }
+            buffer.Format(_L("%S %d"), &KUIStoreTestCaseNum, aSetInfo.TestCases()[i].TestCaseNum());
+            WriteLineL(file, buffer);
+            buffer.Format(_L("%S %d"), &KUIStoreCasePriority, aSetInfo.TestCases()[i].Priority());
+            WriteLineL(file, buffer);
+            buffer.Format(_L("%S %d %d"), &KUIStoreCaseTimeout, I64LOW(aSetInfo.TestCases()[i].Timeout().Int64()), 
+                                                                I64HIGH(aSetInfo.TestCases()[i].Timeout().Int64()));
+            WriteLineL(file, buffer);
+            buffer.Format(_L("%S %d"), &KUIStoreCaseExpectedResult, aSetInfo.TestCases()[i].ExpectedResult());
+            WriteLineL(file, buffer);
+            buffer.Format(_L("%S"), &KUIStoreSetCaseEnd);    
+            WriteLineL(file, buffer);
+            }
+
+        WriteLineL(file, KNullDesC);
+        buffer.Format(_L("%S"), &KUIStoreSetEnd);
+        WriteLineL(file, buffer);
+
+        CleanupStack::PopAndDestroy(&buffer);
+        CleanupStack::PopAndDestroy(&file);
+        }
+    CleanupStack::PopAndDestroy(&fs);        
+    }           
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: UpdateTestSetL
+
+    Description: Updates information in test set file.
+
+    Parameters: CTestSetInfo& aSetInfo: in: test set
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: Leaves when writing to file fails
+                       Leaves when file.seek fails
+                       Leaves when can't connect to file server
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::UpdateTestSetL(CTestSetInfo& aSetInfo, const TDesC& aSetFileName)
+    {
+    // Get path
+    TParse p;
+    p.Set(aSetFileName, NULL, NULL);
+    TPtrC path = p.DriveAndPath(); // gives path for test set
+    TPtrC fn = p.NameAndExt(); // gives filename with extension
+    if(path.Length() == 0)
+        {
+        path.Set(KUIStoreDefaultDir);
+        }
+
+    //Create file server
+    RFs fs;
+    User::LeaveIfError(fs.Connect());
+    CleanupClosePushL(fs);
+
+    //Create or open file
+    RFile file;
+    TFileName filename = path;
+    filename.Append(fn);
+    TInt foundpos = KErrNotFound;
+    
+    TInt r = file.Open(fs, filename, EFileWrite);
+    if(r != KErrNone)
+        {
+        User::Leave(r);
+        }
+    else
+        {
+        CleanupClosePushL(file);
+
+        //Search for line
+        RBuf buffer;
+        buffer.Create(256);
+        CleanupClosePushL(buffer);
+
+        //Prepare file
+        TInt pos = 0;
+        User::LeaveIfError(file.Seek(ESeekStart, pos));
+        
+        //Read file
+        ReadLineL(file, buffer);
+        while(buffer.Length() > 0)
+            {
+            // Keep remembering current position
+            if(buffer.Find(KUIStoreLastStartedCaseIndex) == 0)
+                {
+                foundpos = pos;
+                break;
+                }
+            // What is current position
+            pos = 0;
+            User::LeaveIfError(file.Seek(ESeekCurrent, pos));
+            // Read next line from file
+            ReadLineL(file, buffer);
+            }
+
+        if(foundpos != KErrNotFound)
+            {
+            // Position was found. Just update that line (save index of last 
+            // started test case)
+            RBuf8 b;
+            b.Create(40);
+            CleanupClosePushL(b);
+
+            b.Copy(KUIStoreLastStartedCaseIndex);
+            b.Append(_L8(" "));
+            b.AppendNumFixedWidth(aSetInfo.GetLastStartedCaseIndex(), EDecimal, KFixedStartedCaseIndex);
+            User::LeaveIfError(file.Seek(ESeekStart, foundpos));
+            User::LeaveIfError(file.Write(b));
+            CleanupStack::PopAndDestroy(&b);
+            }
+
+        CleanupStack::PopAndDestroy(&buffer);
+        CleanupStack::PopAndDestroy(&file);
+        }
+    CleanupStack::PopAndDestroy(&fs);        
+    
+    if(foundpos == KErrNotFound)
+        {
+        // Position of KUIStoreLastStartedCaseIndex could not be found.
+        // Store the whole file.
+        SaveTestSetL(aSetInfo, aSetFileName);
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: ReadLineL
+
+    Description: Read the whole line from the file. If there is enough space,
+                 the whole content of line will be returned in buffer.
+
+    Parameters: RFile& file: in: file to be read
+                TDes8& buffer: out: buffer to be returned
+    
+    Return Values: None
+
+    Errors/Exceptions: Leaves if RFile::Read method fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::ReadLineL(RFile &file, TDes& buffer)
+    {
+    TBuf8<1> c;
+    TBuf<1> c16;
+    buffer.Copy(KNullDesC);
+    
+    User::LeaveIfError(file.Read(c));
+    while(c.Length() > 0)
+        {
+        // There is still place to write to the dest buffer
+        if(buffer.Length() < buffer.MaxLength())
+            {
+            c16.Copy(c);
+            buffer.Append(c16);
+            }
+        // Stop reading if end of line
+        if(c[0] == 0x0A)
+            {
+            break;
+            }
+        User::LeaveIfError(file.Read(c));
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: WriteLineL
+
+    Description: Write given line to the file and adds end of line.
+
+    Parameters: RFile& file: in: file to be written
+                TDesC& buffer: in: buffer to be written
+    
+    Return Values: None
+
+    Errors/Exceptions: Leaves if RFile::Write method fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::WriteLineL(RFile &file, const TDesC& buffer)
+    {
+    if(buffer.Length() > 0)
+        {
+        // Create 8-bit buffer
+        RBuf8 buf;
+        buf.Create(buffer.Length());
+        CleanupClosePushL(buf);
+    
+        buf.Copy(buffer);
+    
+        // Write buffer to file + end of line
+        User::LeaveIfError(file.Write(buf));
+
+        // Delete 8-bit buffer
+        CleanupStack::PopAndDestroy(&buf);
+        }
+
+    // Write end of line
+    TBuf8<2> eoline;
+    eoline.Copy(_L("\r\n"));
+    User::LeaveIfError(file.Write(eoline));
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: LoadTestModulesL
+
+    Description: Load test modules. 
+
+    Parameters: CTestSetInfo& aSetInfo: in: test set
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::LoadTestModulesAndTestCaseFilesL( 
+    const RRefArray<const CTestInfo>& aTestCases )
+    {
+    
+    RRefArray<TDesC> testCaseFiles;
+    RRefArray<TDesC> testModules;
+    CleanupClosePushL( testCaseFiles );
+    CleanupClosePushL( testModules );
+    
+    User::LeaveIfError( Modules( testModules ) );
+    
+    TInt cCount = aTestCases.Count();
+    TInt mCount = 0;
+    TInt mInd=0;
+    TInt fCount = 0;
+    TInt fInd=0;
+    for( TInt cInd=0; cInd<cCount; cInd++ )
+        {
+        mCount = testModules.Count();
+        for( mInd=0; mInd<mCount; mInd++ )
+            {
+            if( aTestCases[cInd].ModuleName() == testModules[mInd] )
+                {
+                // Test module already loaded
+                break;
+                }
+            }
+        if( mInd == mCount )
+            {
+            // Not found, load test module
+            if( AddTestModule( aTestCases[cInd].ModuleName() ) == KErrNone )
+                {
+                User::LeaveIfError( 
+                    testModules.Append( aTestCases[cInd].ModuleName() ) );
+                }
+            }                
+        if( aTestCases[cInd].TestCaseFile().Length() == 0 )
+            {
+            // Test case file is not used, continue
+            continue;
+            }    
+        testCaseFiles.Reset();
+        User::LeaveIfError( 
+            TestCaseFiles( testCaseFiles, aTestCases[cInd].ModuleName() ));
+        fCount = testCaseFiles.Count();
+        for( fInd=0; fInd<fCount; fInd++ )
+            {
+            if( aTestCases[cInd].TestCaseFile() == testCaseFiles[fInd] )
+                {
+                // Testcasefile already loaded
+                break;
+                }
+            }  
+        if( fInd == fCount )
+            {  
+            // Load test module
+            if( AddTestCaseFile( aTestCases[cInd].ModuleName(),
+                                 aTestCases[cInd].TestCaseFile() ) == KErrNone )
+                {
+                User::LeaveIfError( 
+                    testCaseFiles.Append( aTestCases[cInd].TestCaseFile() ) );
+                }
+            }
+        }   
+
+    CleanupStack::PopAndDestroy(); // testModules
+    CleanupStack::PopAndDestroy(); // testCaseFiles
+        
+    }
+                               
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: TestExecuted
+
+    Description: Test case executed callback from UI engine.
+    
+    Parameters:  CUIEngineContainer* const aContainer: in: Execution container
+                 TFullTestResult& aFullTestResult: in: test result
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/    
+void CUIStore::TestExecuted ( CUIEngineContainer* aContainer,
+                              TFullTestResult& aFullTestResult )
+    {
+    
+    CStartedTestCase* testCase = NULL;
+    
+    if( FindByContainer( aContainer, testCase ) != KErrNone )
+        {
+        __TRACE( KError, ( CStifLogger::EError, _L("CUIStore::TestExecuted: Not found")));
+        return;
+        }
+    CStartedTestSet* set = NULL;
+    TInt setStatus = 0;
+    if( FindStartedSetByCase( testCase, set ) == KErrNone )
+        {
+        setStatus = set->Status();
+        set->TestCompleted( testCase, aFullTestResult );        
+        setStatus |= set->Status();
+        }
+        
+    // Check and delete all pending popup windows for test case
+    TInt count = iPopups.Count();
+    for( TInt i = 0; i<count; i++ )
+        {
+        if( iPopups[i]->Container() == aContainer )
+            {
+            delete iPopups[i];
+            iPopups.Remove( i );
+            }
+        }
+        
+    // Get old status 
+    TInt status = testCase->Status();
+    // Set result
+    testCase->SetResult( aFullTestResult );
+    // Get new status 
+    status |= testCase->Status();
+    // Add set status flags
+    status |= setStatus;
+    
+    iUIStoreIf->Update( testCase, status ); 
+    
+    return;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: PrintProg
+
+    Description: Progress information from test case execution, 
+            callback from UI engine.
+    
+    Parameters:  CUIEngineContainer* const aContainer: in: Execution container
+                 TTestProgress& aProgress: in: print info
+    
+    Return Values: Symbian OS error code
+
+    
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+TInt CUIStore::PrintProg ( CUIEngineContainer* aContainer,
+                           TTestProgress& aProgress )
+    {
+    if( aContainer == NULL )
+        {
+        return KErrArgument;
+        }
+    if( ( aProgress.iDescription.Length() == 0 ) &&
+        ( aProgress.iText.Length() == 0 ) )
+    
+        {
+        return KErrArgument;
+        }
+        
+    CStartedTestCase* testCase = NULL;
+    
+    if( FindByContainer( aContainer, testCase ) != KErrNone )
+        {
+        __TRACE( KError, ( CStifLogger::EError, _L("CUIStore::TestExecuted: Not found")));
+        return KErrNotFound;
+        }
+
+    TInt position = KErrNotFound;
+    TInt smallPos = KErrNotFound;
+
+    // Search the array to find the position
+    const TInt count = testCase->PrintArray().Count();
+    for (TInt i = 0; i < count; i++)
+        {
+
+        // Check if that item is already on list
+        if ( testCase->PrintArray()[i]->iDescription == aProgress.iDescription &&
+             testCase->PrintArray()[i]->iPosition    == aProgress.iPosition )
+            {
+            // Set it to be updated
+            position = i;
+            break;
+            }
+
+        // Found a smaller priority item from list
+        if ( aProgress.iPosition <  testCase->PrintArray()[i]->iPosition )
+            {              
+            smallPos = i;
+            break;
+            }
+        }
+
+    // Either update item in array or add new item to array
+    if ( position != KErrNotFound )
+        {
+        // Replace existing text
+        testCase->PrintArray()[position]->ReplaceTextL( aProgress );
+        }
+    else 
+        {
+        CTestProgress* prog = NULL;
+        TRAPD( err,
+            // Allocate new
+            prog = CTestProgress::NewL( aProgress );
+            );
+        if( err != KErrNone )
+            {
+            return err;
+            }
+        if ( smallPos != KErrNotFound )
+            {
+            if( testCase->PrintArray().Insert( prog, smallPos ) != KErrNone )
+                {
+                delete prog;
+                return KErrNoMemory;
+                }
+            }
+        else 
+            {
+            if( testCase->PrintArray().Append( prog ) != KErrNone )
+                {
+                delete prog;
+                return KErrNoMemory;
+                }
+            }
+        }
+        
+    iUIStoreIf->Update( testCase, CUIStoreIf::EPrintUpdate ); 
+    
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: PrintProg
+
+    Description: Error information from Test framework, 
+            callback from UI engine.
+    
+    Parameters:  CUIEngineContainer* const aContainer: in: Execution container
+                 TErrorNotification& aError: in: error info
+    
+    Return Values: Symbian OS error code
+    
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/    
+TInt CUIStore::ErrorPrint( TErrorNotification& aError )
+    {
+
+    if( aError.iText.Length() == 0 )
+        {
+        return KErrArgument;
+        }
+    
+    iUIStoreIf->Error( aError );
+        
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: RemoteMsg
+
+    Description: Remote protocol control messages handling.
+
+    Parameters: const TDesC& aMessage: in: Remote message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::RemoteMsg( CUIEngineContainer* aContainer,
+                          const TDesC& aMessage)
+    {
+
+    if( ( aMessage.Length() == 0 ) ||
+        ( aContainer == NULL ) )
+        {
+        return KErrArgument;
+        }
+    
+    TInt ret = KErrNone;
+
+    TInt error = KErrNone;
+    CStifTFwIfProt* msg = NULL;
+    CStifTFwIfProt* resp = NULL;
+    TRAPD( err, msg = CStifTFwIfProt::NewL(); );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+    TRAP( err, resp = CStifTFwIfProt::NewL(); );
+    if( err != KErrNone )
+        {
+        delete msg;
+        return err;
+        }
+    
+    // Parse received message
+    TRAP( err, 
+        error = msg->SetL( aMessage ) 
+    );
+    if( err != KErrNone )
+        {
+        __TRACE( KError, ( _L( "CUIStore::RemoteMsg: message header parsing failed [%d]"), err ) );
+        delete msg;
+        delete resp;
+        return err;
+        }
+
+    // Create response 
+    TRAP( err, resp->CreateL(); );
+    if( err != KErrNone )
+        {
+        delete msg;
+        delete resp;
+        return err;
+        }                
+
+    resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgResponse );
+    
+    if( error != KErrNone )
+        {
+        __TRACE( KError, ( _L( "CUIStore::RemoteMsg: message parsing failed [%d]"), error ) );
+        resp->AppendId( SETID( (TInt32)DevId(), 0 ) );
+        resp->AppendId( msg->SrcId() );
+        resp->Append( CStifTFwIfProt::MsgType, msg->iMsgType );
+        resp->Append( CStifTFwIfProt::RespParam, CStifTFwIfProt::ERespResult, error );
+        
+        aContainer->RemoteReceive( resp->Message() );
+        
+        // Error reported with protocol message, return success
+        delete msg;
+        delete resp;
+        return KErrNone;
+        }                    
+    
+    TBool sendResp = ETrue;
+                        
+    switch( msg->iMsgType )
+        {
+        case CStifTFwIfProt::EMsgReserve:
+            {
+            // Check IDs
+            if( ( msg->SrcDevId() == 0 ) ||
+                ( msg->SrcTestId() == 0 ) )
+                {
+                __TRACE( KError, ( _L( "CUIStore::RemoteMsg: reserve for illegal srcid received") ) );
+                error = KErrGeneral;
+                }
+            if( msg->DstId() != 0 ) 
+                {
+                // Not a broadcast 
+                if( ( msg->DstDevId() != DevId() ) ||
+                    ( msg->DstTestId() != 0 ) )  
+                    {
+                    __TRACE( KError, ( _L( "CUIStore::RemoteMsg: reserve for illegal dstid received") ) );
+                    error = KErrGeneral;
+                    }
+                }                
+                
+            resp->AppendId( SETID( (TInt32)DevId(), 0 ) );
+            resp->AppendId( msg->SrcId() );
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgReserve );
+            if( error != KErrNone )
+                {
+                resp->Append( CStifTFwIfProt::RespParam, CStifTFwIfProt::ERespResult, error );
+                }
+            }
+            break;
+        case CStifTFwIfProt::EMsgRelease:
+            {
+            // Check protocol ids
+            if( ( msg->SrcDevId() == 0 ) ||
+                ( msg->SrcTestId() == 0 ) ||
+                ( msg->DstTestId() != 0 ) )
+                {
+                __TRACE( KError, ( _L( "CUIStore::RemoteMsg: release for illegal srcid or dstid received") ) );
+                error = KErrGeneral;
+                }   
+            else if( msg->DstDevId() != DevId() ) 
+                {
+                __TRACE( KError, ( _L( "CUIStore::RemoteMsg: release for illegal dstid received") ) );
+                error = KErrNotFound;
+                }   
+
+            resp->AppendId( msg->DstId() );
+            resp->AppendId( msg->SrcId() );
+            resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRelease );
+            
+            if( error != KErrNone )
+                {
+                resp->Append( CStifTFwIfProt::RespParam, CStifTFwIfProt::ERespResult, error );
+                }            
+            }
+            break;
+        case CStifTFwIfProt::EMsgRemote:
+            {
+            // Check protocol ids
+            if( ( msg->SrcDevId() == 0 ) ||
+                ( msg->SrcTestId() == 0 ) ||
+                ( msg->DstDevId() == 0 ) )
+                {
+                __TRACE( KError, ( _L( "CUIStore::RemoteMsg: remote for illegal srcid or dstid received") ) );
+                error = KErrGeneral;
+                }
+            else
+                {               
+                __TRACE( KError, ( _L( "CUIStore::RemoteMsg: received remote call") ) );
+                
+                error = MsgRemote( aContainer, *msg, *resp );
+                }
+                
+            if( error != KErrNone )
+                {
+                resp->AppendId( msg->DstId() );
+                resp->AppendId( msg->SrcId() );
+                resp->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+                resp->Append( msg->iCmdDes );
+                resp->Append( CStifTFwIfProt::RespParam,     
+                             CStifTFwIfProt::ERespResult, 
+                             error );
+                }
+            else
+                {
+                sendResp = EFalse;
+                }
+                                
+            }
+            break;
+        case CStifTFwIfProt::EMsgResponse:            
+        default:
+            __TRACE( KError, ( _L( "CUIStore::RemoteMsg: invalid message")) );
+            ret = KErrNotSupported;
+        }
+
+    if( ( ret == KErrNone ) && sendResp ) 
+         {
+        aContainer->RemoteReceive( resp->Message() );
+        }
+        
+    delete msg;
+    delete resp;
+    
+    return ret;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: MsgRemote
+
+    Description: Remote command
+    
+    Parameters: const TDesC& aMessage: in:
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::MsgRemote( CUIEngineContainer* aContainer, 
+                          CStifTFwIfProt& aReq, 
+                          CStifTFwIfProt& aResp )
+    {
+    
+    TInt ret = KErrNone;    
+        
+    switch( aReq.iCmdType )
+        {
+        case CStifTFwIfProt::ECmdRun:
+            ret = MsgRemoteRun( aContainer, aReq, aResp );
+            break;
+        case CStifTFwIfProt::ECmdPause:
+        case CStifTFwIfProt::ECmdResume:
+        case CStifTFwIfProt::ECmdCancel:
+            ret = MsgRemoteTestCtl( aContainer, aReq, aResp );
+            break;
+        case CStifTFwIfProt::ECmdRequest:
+        case CStifTFwIfProt::ECmdRelease:
+            ret = MsgRemoteEventCtl( aContainer, aReq, aResp );            
+            break;
+        case CStifTFwIfProt::ECmdSendReceive:
+            {
+            ret = MsgRemoteSendReceive( aContainer, aReq, aResp );
+            break;
+            }
+        default:
+            {
+            CStifTFwIfProt* resp = NULL;
+            TRAPD( err, 
+                resp = CStifTFwIfProt::NewL(); 
+                resp->CreateL();
+                );
+            if( err != KErrNone )
+                {
+                delete resp;
+                return err;
+                }
+            resp->SetMsgType( CStifTFwIfProt::EMsgResponse );
+            resp->SetSrcId( aReq.DstId() );
+            resp->SetDstId( aReq.SrcId() );
+            resp->SetRespType( CStifTFwIfProt::EMsgRemote );
+            // Command type must be set separately, 
+            // because it is unspecified in this case
+            resp->iCmdType = aReq.iCmdType;
+            resp->Append( aReq.iCmdDes );
+                
+            ret = RemotePopup( aContainer, aReq.Message(), resp );
+
+            if( ret != KErrNone )
+                {
+                delete resp;
+                }
+            }
+            break;
+        }
+    
+    return ret;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: AtsRemoteRun
+
+    Description: Remote run message
+    
+    Parameters: const TDesC& aMessage: in:
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+TInt CUIStore::MsgRemoteRun( CUIEngineContainer* aContainer,
+                             CStifTFwIfProt& aReq, 
+                             CStifTFwIfProt& /* aResp */)
+    {
+    
+    TInt ret = KErrNone;    
+    TUint16 testid = 0;
+    
+    if( ( aReq.DstDevId() == 0 ) ||
+        ( aReq.DstTestId() != 0 ) ) 
+        {
+        // Protocol violation
+        __TRACE( KError, ( _L( "AtsReceive: remote run for illegal dstid received") ) );
+        return KErrGeneral;
+        }
+
+    if ( aReq.DstDevId() != DevId() ) 
+        {
+        // Not our protocol message
+        __TRACE( KError, ( _L( "AtsReceive: remote run for illegal dstdevid received") ) );
+        return KErrNotFound;
+        }
+
+    
+    if( aReq.iModule.Length() == 0 )
+        {
+        __TRACE( KError, ( _L("No mandatory test module name given as run parameter") ) );        
+        ret = KErrNotFound;
+        }    
+    else if( aReq.iTestCaseNumber < 0 )
+        {
+        __TRACE( KError, ( _L("No mandatory test case number given as run parameter") ) );        
+        ret = KErrNotFound;
+        }    
+    
+    testid = 1;
+    CStifTFwIfProt* resp = NULL;
+    TRAPD( err, 
+        resp = CStifTFwIfProt::NewL(); 
+        resp->CreateL();
+        );
+    if( err != KErrNone )
+        {
+        delete resp;
+        return err;
+        }
+
+    CStifTFwIfProt* resp2 = NULL;
+    TRAP( err, 
+        resp2 = CStifTFwIfProt::NewL(); 
+        resp2->CreateL();
+        );
+    if( err != KErrNone )
+        {
+        delete resp2;
+        return err;
+        }              
+
+    resp->SetMsgType( CStifTFwIfProt::EMsgResponse );
+    resp->SetSrcId( SETID( (TInt32)DevId(), testid ) );
+    resp->SetDstId( aReq.SrcId() );
+    resp->SetRespType( CStifTFwIfProt::EMsgRemote );
+    resp->SetCmdType( CStifTFwIfProt::ECmdRun );        
+
+    resp2->SetMsgType( CStifTFwIfProt::EMsgResponse );
+    resp2->SetSrcId( SETID( (TInt32)DevId(), testid ) );
+    resp2->SetDstId( aReq.SrcId() );
+    resp2->SetRespType( CStifTFwIfProt::EMsgRemote );
+    resp2->SetCmdType( CStifTFwIfProt::ECmdRun );        
+   
+    // Remote run started popup call
+    ret = RemotePopup( aContainer, aReq.Message(), resp, EPopupPriorityHighest );
+    if( ret != KErrNone )
+        {
+        delete resp;
+        }
+    
+    // Remote run result popup call
+    ret = RemotePopup( aContainer, aReq.Message(), resp2 );
+    if( ret != KErrNone )
+        {
+        delete resp2;
+        }
+    
+    return ret;            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: MsgRemoteTestCtl
+
+    Description: Remote test control message
+    
+    Parameters: const TDesC& aMessage: in:
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+TInt CUIStore::MsgRemoteTestCtl( CUIEngineContainer* aContainer,
+                                 CStifTFwIfProt& aReq, 
+                                 CStifTFwIfProt& /*aResp*/ )
+    {
+    
+    TInt ret = KErrNone;    
+   
+    if( ( aReq.DstDevId() == 0 ) ||
+        ( aReq.DstTestId() == 0 ) ) 
+        {
+        // Protocol violation
+        __TRACE( KError, ( _L( "AtsReceive: remote test control for illegal dstid received") ) );
+        return KErrGeneral;
+        }
+
+    if ( aReq.DstDevId() != DevId() ) 
+        {
+        // Not our protocol message
+        __TRACE( KError, ( _L( "AtsReceive: remote test control for illegal dstdevid received") ) );
+        return KErrNotFound;
+        }
+    
+    CStifTFwIfProt* resp = NULL;
+    TRAPD( err, 
+        resp = CStifTFwIfProt::NewL(); 
+        resp->CreateL();
+        );
+    if( err != KErrNone )
+        {
+        delete resp;
+        return err;
+        }
+        
+    resp->SetMsgType( CStifTFwIfProt::EMsgResponse );
+    resp->SetSrcId( aReq.DstId() );
+    resp->SetDstId( aReq.SrcId() );
+    resp->SetRespType( CStifTFwIfProt::EMsgRemote );
+    resp->SetCmdType( aReq.iCmdType );
+    
+    ret = RemotePopup( aContainer, aReq.Message(), resp );
+
+    if( ret != KErrNone )
+        {
+        delete resp;
+        }
+
+    return ret;
+    
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: MsgRemoteEventCtl
+
+    Description: Remote run message
+    
+    Parameters: const TDesC& aMessage: in:
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+TInt CUIStore::MsgRemoteEventCtl( CUIEngineContainer* aContainer,
+                                  CStifTFwIfProt& aReq, 
+                                  CStifTFwIfProt& aResp )
+    {
+    
+    if( ( aReq.DstDevId() == 0 ) ||
+        ( aReq.DstTestId() != 0 ) ) 
+        {
+        // Protocol violation
+        __TRACE( KError, ( _L( "AtsReceive: remote event control for illegal dstid received") ) );
+        return KErrGeneral;
+        }
+
+    if ( aReq.DstDevId() != DevId() ) 
+        {
+        // Not our protocol message
+        __TRACE( KError, ( _L( "AtsReceive: remote event control for illegal dstdevid received") ) );
+        return KErrNotFound;
+        }
+        
+    if( aReq.iEventName.Length() == 0 )
+        {
+        __TRACE( KError, ( _L("No event name given") ) );        
+        return KErrNotFound;
+    }
+    
+    TInt ret = KErrNone;
+                    
+    switch( aReq.iCmdType )
+        {
+        case CStifTFwIfProt::ECmdRequest:
+            {
+            // Send event active information
+            CStifTFwIfProt* resp = NULL;
+            TRAP( ret, 
+                resp = CStifTFwIfProt::NewL(); 
+                resp->CreateL(); );
+            if( ret != KErrNone )
+                {
+                delete resp;
+                return ret;
+                }
+                
+            resp->SetMsgType( CStifTFwIfProt::EMsgResponse );
+            resp->SetSrcId( aReq.DstId() );
+            resp->SetDstId( aReq.SrcId() );
+            resp->SetRespType( CStifTFwIfProt::EMsgRemote );
+            resp->SetCmdType( CStifTFwIfProt::ECmdRequest );
+            resp->Append( CStifTFwIfProt::EventStatus, 
+                          CStifTFwIfProt::EEventSet );
+            resp->Append( aReq.iEventName );
+            ret = RemotePopup( aContainer, aReq.Message(), resp, EPopupPriorityNormal );                
+
+            if( ret != KErrNone )
+                {
+                delete resp;
+                }
+                    
+            aResp.AppendId( aReq.DstId() );
+            aResp.AppendId( aReq.SrcId() );
+            aResp.Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+            aResp.Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRequest );
+            if( ret == KErrNone )
+                {
+                aResp.Append( CStifTFwIfProt::EventStatus, 
+                              CStifTFwIfProt::EEventActive );
+                aResp.Append( aReq.iEventName );
+                }
+            else 
+                {
+                aResp.Append( CStifTFwIfProt::EventStatus, 
+                              CStifTFwIfProt::EEventError );
+                aResp.Append( aReq.iEventName );                              
+                aResp.Append( CStifTFwIfProt::EventStatusParams, 
+                             CStifTFwIfProt::EEventResult,
+                             ret );
+                }
+
+            ret = aContainer->RemoteReceive( aResp.Message() );    
+            ret = KErrNone;          
+            }
+            break;
+        case CStifTFwIfProt::ECmdRelease:
+            {
+            // Check and delete all pending event popup windows for test case
+            TInt count = iPopups.Count();
+            for( TInt i = 0; i<count; i++ )
+                {
+                if( ( iPopups[i]->Container() == aContainer ) &&
+                    iPopups[i]->IsEventPopup() )
+                    {
+                    delete iPopups[i];
+                    iPopups.Remove( i );
+                    }
+                }
+                
+            aResp.AppendId( aReq.DstId() );
+            aResp.AppendId( aReq.SrcId() );
+            aResp.Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+            aResp.Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRelease );
+            aResp.Append( aReq.iEventName );
+
+            ret = aContainer->RemoteReceive( aResp.Message() );    
+            ret = KErrNone;          
+            
+            }
+            break;
+        default:
+            return KErrNotSupported;
+        }
+        
+    return ret;
+    
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: MsgRemoteSendReceive
+
+    Description: Asynchronous remote sendreceive message
+    
+    Parameters: CUIEngineContainer* aContainer: in:
+                CStifTFwIfProt& aReq: in
+                CStifTFwIfProt& aResp: in
+
+    Return Values: KErrNotSupported
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+TInt CUIStore::MsgRemoteSendReceive( CUIEngineContainer* aContainer,
+                             CStifTFwIfProt& aReq, 
+                             CStifTFwIfProt& aResp )
+    {
+    
+    TInt ret = KErrNone;    
+    // TUint16 testid = 0;
+    
+    if( ( aReq.DstDevId() == 0 ) ||
+        ( aReq.DstTestId() != 0 ) ) 
+        {
+        // Protocol violation
+        __TRACE( KError, ( _L( "AtsReceive: remote run for illegal dstid received") ) );
+        return KErrGeneral;
+        }
+
+    if ( aReq.DstDevId() != DevId() ) 
+        {
+        // Not our protocol message
+        __TRACE( KError, ( _L( "AtsReceive: remote run for illegal dstdevid received") ) );
+        return KErrNotFound;
+        }
+
+    // testid = 1;
+    CStifTFwIfProt* resp = NULL;
+    TRAPD( err, 
+        resp = CStifTFwIfProt::NewL(); 
+        resp->CreateL();
+        );
+    if( err != KErrNone )
+        {
+        delete resp;
+        return err;
+        }
+        
+    resp->SetMsgType( CStifTFwIfProt::EMsgResponse );
+    //resp->SetSrcId( SETID( DevId(), testid ) );
+    resp->SetSrcId( aReq.DstId() );
+    resp->SetDstId( aReq.SrcId() );
+    resp->SetRespType( CStifTFwIfProt::EMsgRemote );
+    resp->SetCmdType( CStifTFwIfProt::ECmdSendReceive );        
+   
+    ret = RemotePopup( aContainer, aReq.Message(), resp );
+    if( ret != KErrNone )
+        {
+        delete resp;
+        }
+        
+    aResp.AppendId( aReq.DstId() );
+    aResp.AppendId( aReq.SrcId() );
+    aResp.Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote );
+    aResp.Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdSendReceive );
+    if( ret != KErrNone )
+        {
+        aResp.Append( CStifTFwIfProt::RunStatus, 
+                      CStifTFwIfProt::ERunError );
+        aResp.Append( CStifTFwIfProt::RunStatusParams, 
+                      CStifTFwIfProt::ERunResult, ret );
+        }
+    else
+        {
+        aResp.Append( CStifTFwIfProt::RunStatus, 
+                      CStifTFwIfProt::ERunStarted );
+        }
+
+    // Send response
+    aContainer->RemoteReceive( aResp.Message() );
+    
+    // Response is created, return success
+    ret = KErrNone;        
+    
+    return ret;
+            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: GoingToReboot
+
+    Description: Reboot indication handling.
+
+    Parameters: CUIEngineContainer* aContainer: in: Container
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::GoingToReboot( CUIEngineContainer* /* aContainer */,
+                              TRequestStatus& aStatus )
+    {
+    
+    _LIT( KDateString,"%H%T%S.%C" ); 
+       
+    const TInt KTimeFieldLength = 30;
+    TBuf<KTimeFieldLength> time;
+    
+    // Store info 
+    CStifLogger* logger = CStifLogger::NewL( KUIStoreDefaultDir,
+                                             KUIStoreDefaultRebootFile,
+                                             CStifLogger::EData,
+                                             CStifLogger::EFile,
+                                             ETrue,
+                                             EFalse,
+                                             EFalse,
+                                             EFalse,
+                                             EFalse,
+                                             ETrue );
+    
+    CleanupStack::PushL( logger );
+    TInt count = iStartedTestCases.Count();
+    for( TInt index=0; index<count; index++ )
+        {
+        logger->Log( _L("%S\r\n"), &KUIStoreStartTest );
+        
+        // First test case info
+        logger->Log( _L("%S %S\r\n"), &KUIStoreCaseModuleName, 
+            &iStartedTestCases[index]->TestInfo().ModuleName() );
+        logger->Log( _L("%S %S\r\n"), &KUIStoreTestCaseTitle, 
+            &iStartedTestCases[index]->TestInfo().TestCaseTitle() );
+        if( iStartedTestCases[index]->TestInfo().TestCaseFile().Length() > 0 )
+            {
+            logger->Log( _L("%S %S\r\n"), &KUIStoreTestCaseFile, 
+                &iStartedTestCases[index]->TestInfo().TestCaseFile() );
+            }
+        logger->Log( _L("%S %d\r\n"), &KUIStoreTestCaseNum, 
+            iStartedTestCases[index]->TestInfo().TestCaseNum() );
+        logger->Log( _L("%S %d\r\n"), &KUIStoreCasePriority, 
+            iStartedTestCases[index]->TestInfo().Priority() );
+         //@js<--remove--> logger->Log( _L("%S %d %d\r\n"), &KUIStoreCaseTimeout,            
+         //@js<--remove--> iStartedTestCases[index]->TestInfo().Timeout().Int64().Low(),
+         //@js<--remove--> iStartedTestCases[index]->TestInfo().Timeout().Int64().High() );
+        logger->Log( _L("%S %d %d\r\n"), &KUIStoreCaseTimeout,            
+            I64LOW(iStartedTestCases[index]->TestInfo().Timeout().Int64()),
+            I64HIGH(iStartedTestCases[index]->TestInfo().Timeout().Int64()));     
+            
+        logger->Log( _L("%S %d\r\n"), &KUIStoreCaseExpectedResult, 
+            iStartedTestCases[index]->TestInfo().ExpectedResult() );    
+        
+        logger->Log( _L("%S %d\r\n"), &KUIStoreCaseStatus, 
+            iStartedTestCases[index]->Status() );    
+
+        logger->Log( _L("%S %d %d\r\n"), &KUIStoreCaseExecutionResult, 
+            iStartedTestCases[index]->Result().iCaseExecutionResultType,
+            iStartedTestCases[index]->Result().iCaseExecutionResultCode );    
+        logger->Log( _L("%S %d %S\r\n"), &KUIStoreCaseResult, 
+            iStartedTestCases[index]->Result().iTestResult.iResult,
+            &iStartedTestCases[index]->Result().iTestResult.iResultDes );    
+        
+        // Start time
+        iStartedTestCases[index]->Result().iStartTime.FormatL(
+                    time, KDateString );
+        logger->Log( _L("%S %S\r\n"), &KUIStoreCaseStartTime, &time );
+
+        // Start time
+        iStartedTestCases[index]->Result().iEndTime.FormatL(
+                    time, KDateString );
+        logger->Log( _L("%S %S\r\n"), &KUIStoreCaseEndTime, &time );
+
+        logger->Log( _L("%S\r\n\r\n"), &KUIStoreStartTestEnd );
+        }
+    
+    CleanupStack::PopAndDestroy( logger );
+    
+    // Show popup
+    TKeyCode key;
+    iUIStoreIf->PopupMsg( _L("GoingToReboot"), 
+                          _L("Press any key to continue"), 
+                          KRebootPopupTimeout, key, aStatus );
+    
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: LoadExecutedTestCasesL
+
+    Description: Load all executed testcases saved before reboot.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves on error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::LoadExecutedTestCasesL()
+    {
+    TPtrC tmp;
+    TInt num = 0;
+    TInt high = 0;
+    TInt64 interval;
+    TFullTestResult result;
+    TInt status = 0;
+    CStifItemParser* item = NULL;
+    TInt ret = KErrNone;
+
+    CStifParser* parser = NULL;
+    TRAP( ret,
+        parser = CStifParser::NewL( KUIStoreDefaultDir,
+                                    KUIStoreDefaultRebootFile );
+        );
+    if( ret != KErrNone )
+        {
+        // reboot file not found
+        return; 
+        }
+    CleanupStack::PushL( parser );
+   
+    __TRACE( KInit, ( _L( "Reboot file is found(%S%S). Reboot testing ongoing..." ), &KUIStoreDefaultDir, &KUIStoreDefaultRebootFile ) );
+
+    CTestInfo* testInfo = NULL;    
+     
+    CStifSectionParser* section = 
+        parser->SectionL( KUIStoreStartTest, KUIStoreStartTestEnd );
+   
+    while( section )
+        {
+        CleanupStack::PushL( section );    
+        
+        testInfo = CTestInfo::NewL();
+        CleanupStack::PushL( testInfo ); 
+    
+        // Get module name
+        // Mandatory, leave if not found
+        User::LeaveIfError( 
+            section->GetLine( KUIStoreCaseModuleName, tmp, ENoTag ) );
+        testInfo->SetModuleName( tmp );
+    
+        // Get test case title
+        // Mandatory, leave if not found
+        User::LeaveIfError( 
+            section->GetLine( KUIStoreTestCaseTitle, tmp, ENoTag ) );
+        testInfo->SetTestCaseTitle( tmp );
+        
+        // Get test case file
+        num = section->GetLine( KUIStoreTestCaseFile, tmp, ENoTag );
+        if( ( num == KErrNone ) &&
+            ( tmp.Length() > 0 ) )
+            {
+            // Optional
+            testInfo->SetTestCaseFile( tmp );
+            }
+        else
+            {
+            testInfo->SetTestCaseFile( KNullDesC );
+            }
+        
+        // Get test case number
+        item = section->GetItemLineL( KUIStoreTestCaseNum );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreTestCaseNum, num ));
+        testInfo->SetTestCaseNumber( num );
+        CleanupStack::PopAndDestroy( item );    
+        
+        // Get test case priority
+        item = section->GetItemLineL( KUIStoreCasePriority );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreCasePriority, num ));
+        testInfo->SetPriority( num );
+        CleanupStack::PopAndDestroy( item ); 
+        
+        // Get test case timeout
+        item = section->GetItemLineL( KUIStoreCaseTimeout );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreCaseTimeout, num ));
+        User::LeaveIfError( item->GetNextInt( high ));
+        //interval.Set( high, num );
+        interval = MAKE_TINT64( high, num );      
+        TTimeIntervalMicroSeconds timeout( interval );
+        testInfo->SetTimeout( timeout );
+        CleanupStack::PopAndDestroy( item ); 
+        
+        // Get test case status
+        item = section->GetItemLineL( KUIStoreCaseStatus );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreCaseStatus, status ));
+        CleanupStack::PopAndDestroy( item ); 
+
+        // Get test case execution result
+        item = section->GetItemLineL( KUIStoreCaseExecutionResult );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreCaseExecutionResult, num ));
+        result.iCaseExecutionResultType = ( TFullTestResult::TCaseExecutionResult) num;
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetNextInt( result.iCaseExecutionResultCode ));
+        CleanupStack::PopAndDestroy( item );
+        
+        // Get test case result
+        item = section->GetItemLineL( KUIStoreCaseResult );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetInt( KUIStoreCaseResult, 
+                                          result.iTestResult.iResult ));
+        // Not mandatory
+        TBool first = ETrue;
+        result.iTestResult.iResultDes.Zero();
+        ret = item->GetNextString( tmp );
+        while( ret == KErrNone )
+            {
+            if( result.iTestResult.iResultDes.Length() + tmp.Length() + 1 > result.iTestResult.iResultDes.MaxLength() )
+                {
+                User::Leave( KErrGeneral );
+                }
+            if(!first)
+                result.iTestResult.iResultDes.Append(_L(" "));
+            result.iTestResult.iResultDes.Append( tmp );
+            first = EFalse;
+            ret = item->GetNextString( tmp );
+            }
+        /*
+        ret = item->GetNextString( tmp );
+        if( ret == KErrNone )
+            {
+            if( tmp.Length() > result.iTestResult.iResultDes.MaxLength() )
+                {
+                User::Leave( KErrGeneral );
+                }
+            result.iTestResult.iResultDes.Copy( tmp );
+            }
+        */
+        CleanupStack::PopAndDestroy( item ); 
+
+        // Get test start time
+        item = section->GetItemLineL( KUIStoreCaseStartTime );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetString( KUIStoreCaseStartTime, tmp ));
+        result.iStartTime.Set( tmp );
+        CleanupStack::PopAndDestroy( item ); 
+
+        // Get test end time
+        item = section->GetItemLineL( KUIStoreCaseEndTime );
+        CleanupStack::PushL( item );
+        // Mandatory, leave if not found
+        User::LeaveIfError( item->GetString( KUIStoreCaseEndTime, tmp ));
+        result.iEndTime.Set( tmp );
+        CleanupStack::PopAndDestroy( item ); 
+             
+        if( status != CUIStoreIf::EStatusRunning )
+            {
+            // Add executed test cases to list
+            CStartedTestCase* startedCase = 
+                new( ELeave )CStartedTestCase( testInfo, result, status );
+            User::LeaveIfError( iStartedTestCases.Append( startedCase ) );            
+            CleanupStack::Pop( testInfo );            
+
+            // Fill data with test case info and send to test engine
+            TTestInfo *info = new (ELeave) TTestInfo;
+            CleanupStack::PushL(info);
+            info->iModuleName.Copy(testInfo->ModuleName());
+            info->iConfig.Copy(testInfo->TestCaseFile());
+            info->iTestCaseInfo.iCaseNumber = testInfo->TestCaseNum();
+            info->iTestCaseInfo.iTitle.Copy(testInfo->TestCaseTitle());
+            info->iTestCaseInfo.iTimeout = testInfo->Timeout();
+            info->iTestCaseInfo.iPriority = testInfo->Priority();
+            
+            iUIEngine->TestEngine().AddTestCaseResultToTestReport(*info, result, KErrNone);
+            CleanupStack::PopAndDestroy(info);
+            } 
+        else
+            {
+            // Restart testcase that was running when reset was done
+            CUIEngineContainer* container = NULL;
+            User::LeaveIfError(  
+                iUIEngine->StartTestCase( container, *testInfo ) );
+            
+            CStartedTestCase* testCase = NULL;
+            TRAPD( retVal,
+                testCase = CStartedTestCase::NewL( *testInfo, *container );
+               );
+            if( retVal != KErrNone )
+                {
+                iUIEngine->AbortStartedTestCase( container );
+                User::Leave( retVal );
+                }
+                
+            retVal = iStartedTestCases.Append( testCase );
+            if( retVal != KErrNone )
+                {
+                iUIEngine->AbortStartedTestCase( container );
+                delete testCase;
+                User::Leave( retVal );
+                }
+
+            CleanupStack::PopAndDestroy( testInfo );
+
+            }
+        
+        CleanupStack::PopAndDestroy( section );    
+        section = 
+            parser->NextSectionL( KUIStoreStartTest, KUIStoreStartTestEnd );
+        } 
+    
+    CleanupStack::PopAndDestroy( parser );
+    
+    // Delete file
+    RFs rf;
+    TInt retVal = rf.Connect();
+	if( retVal != KErrNone )
+		{
+		User::Leave( retVal );
+		}
+		
+    TFileName file( KUIStoreDefaultDir );
+    file.Append( KUIStoreDefaultRebootFile );
+    rf.Delete( file );
+    rf.Close();
+    
+    return;
+    }    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: FindByContainer
+
+    Description: Find test case with UIEngine Container pointer.
+    
+    Parameters:  CUIEngineContainer* const aContainer: in: Execution container
+                 CStartedTestCase*& aTestCase: out: Testcase info
+    
+    Return Values: Symbian OS error code
+    
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/ 
+TInt CUIStore::FindByContainer( CUIEngineContainer* const aContainer,
+                                CStartedTestCase*& aTestCase )
+    {
+    
+    TInt count = iStartedTestCases.Count();
+    TInt index = 0;
+    for( ; index < count; index++ )
+        {
+        if( ( iStartedTestCases[index]->Status() & 
+              CUIStoreIf::EStatusRunning ) &&
+            ( &iStartedTestCases[index]->UIEngineContainer() ==
+              aContainer ) )
+            {
+            aTestCase = iStartedTestCases[index];
+            return KErrNone;
+            }
+        }
+    
+    return KErrNotFound;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: UpdateCases
+
+    Description: Refreshs iTestCases array ie. fetches test cases from 
+                test framework
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::UpdateCases()
+    {
+    
+    if( iUpdateNeeded )
+        {
+        TInt handle = iUIStoreIf->PopupMsg( 
+            _L("Updating"), _L("Test cases"), 60 );
+        iTestCases.ResetAndDestroy();
+        TRAPD( ret, 
+            ret = iUIEngine->GetTestCasesL( iTestCases );
+            );
+        iUpdateNeeded = EFalse;
+        // Close popup
+        iUIStoreIf->Close( handle );
+        if( iTestCases.Count() == 0 )
+            {
+            iUIStoreIf->PopupMsg( _L("No test cases found"), 
+                                  _L("e.g. check TestEngine log"), 
+                                  3 );
+            }
+        return ret;
+        }
+    
+    return KErrNone;
+            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: CheckIniL
+
+    Description: Check ini file
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::CheckIniL( TFileName& aIni )
+    {
+    
+    RFs fs;
+    User::LeaveIfError( fs.Connect() );
+    RFile file;
+    TInt err = KErrNone;
+    TErrorNotification error;
+    error.iModule.Copy( KUIStore );
+
+    TStifUtil::CorrectFilePathL( aIni );
+    
+    if ( aIni.Length() != 0 )
+        {
+        err = file.Open ( fs, aIni, EFileRead );
+
+        if ( err == KErrNone )
+            {
+            // Use the file given as command line parameter
+            iUIStoreIf->PopupMsg( _L("Using given ini-file"), 
+                                  KNullDesC, 0 );
+            file.Close();
+            fs.Close(); 
+            return;
+            }
+        else
+            { 
+            error.iText.Copy( _L("Can't open given ini-file") );
+            iUIStoreIf->Error( error );  
+            aIni.Zero();       
+            }
+        }
+        
+    // Try to locate default ini file from every drive
+    TDriveList drivelist; 
+	User::LeaveIfError( fs.DriveList(drivelist) );
+	// A TDriveList (the list of available drives), is an array of 
+	// 26 bytes. Each byte with a non zero value signifies that the 
+	// corresponding drive is available.
+
+    TInt driveNumber; 
+	TChar driveLetter;
+
+	for( driveNumber=EDriveA; driveNumber<=EDriveZ; driveNumber++ )
+		{
+		if( !drivelist[driveNumber] ) 
+			{
+			// If drive-list entry is zero, drive is not available
+			continue;
+			}
+        User::LeaveIfError(
+            fs.DriveToChar( driveNumber, driveLetter ));
+        
+        aIni.Zero();
+        aIni.Append( driveLetter );
+        aIni.Append( _L(":") );
+        aIni.Append( KDefaultIni );
+
+        // Try to open
+        err = file.Open ( fs, aIni, EFileRead );
+
+        if ( err == KErrNone )
+            {
+            // Use default file
+            file.Close();
+            TFileName info( _L("Using default ini-file ") );
+            if( info.MaxLength()-info.Length() >  aIni.Length() )
+                {
+                // Show also filename if fits to descriptor
+                info.Append( aIni );
+                }
+            iUIStoreIf->PopupMsg( info, KNullDesC, 0 );
+            break;
+            }
+        }
+    if( err != KErrNone )
+        {
+        iUIStoreIf->PopupMsg( _L("Starting without ini-file"), 
+                              KNullDesC,  0);
+        aIni.Zero();            
+        }
+
+    fs.Close();    
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: ParseTestSetName
+
+    Description: Parses test set name from test set filename.
+
+    Parameters: const TDesC& aSetFileName: in: Test set filename
+                TPtrC& aSetName: out: testset name
+                TFileName& aFileName: in: filenamebuffer
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::ParseTestSetName( const TDesC& aSetFileName, 
+                                 TPtrC& aSetName,
+                                 TFileName& aFileName )
+    {
+    if( aSetFileName.Length() > KMaxFileName )
+        {
+        return KErrArgument;
+        }
+    
+    aFileName.Copy( aSetFileName );
+    TParsePtr p( aFileName );
+    aSetName.Set( p.NameAndExt() ); // gives test set name without path
+    
+    if( aSetName.Length() > KMaxName )
+        {
+        return KErrArgument;
+        }
+    
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: RemotePopup
+
+    Description: Do remote message popup 
+
+    Parameters: const TDesC& aReq: in: request
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::RemotePopup( CUIEngineContainer* aContainer,
+                            const TDesC& aMsg, 
+                            CStifTFwIfProt* aResp,
+                            TPopupPriority aPopupPriority )
+    {
+    TInt ret = KErrNone;
+    
+    CUIStorePopup* popup = NULL;
+    TRAP( ret, popup = CUIStorePopup::NewL( this, aContainer, aResp, aPopupPriority, aMsg ); );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    ret = iPopups.Append( popup );
+    if( ret != KErrNone )
+        {
+        delete popup;
+        return ret;
+        }
+                
+    // We'll put new popup to the top if there are no popups active or if
+    // currently active popup has lower priority than the new one               
+    if( !iPopupActive || iActivePopupPriority > popup->GetPriority() ) 
+        {       
+        SetRemotePopupFromQueue();
+        }
+
+    return ret;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: SetRemotePopupFromQueue
+
+    Description: Prints the highest priority popup to the UI from the popup 
+    queue
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft @js
+
+-------------------------------------------------------------------------------
+*/
+
+void CUIStore::SetRemotePopupFromQueue()
+    {
+    CUIStorePopup* popup = NULL;
+    
+    if(iPopups.Count() > 0 )
+        {        
+        TInt highest = 0;
+        
+        // Let's get the highest priority popup and print it to the UI
+        for( TInt x=0; x<iPopups.Count(); x++)
+            {            
+            if( iPopups[x]->GetPriority() < iPopups[highest]->GetPriority() )    
+                {
+                highest = x;
+                }
+            }
+        
+        popup = iPopups[highest];
+        
+        if( popup == NULL )
+            {
+            // Some weird error
+            iPopupActive = EFalse;
+            return;        
+            }
+        
+        // Change the active popup priority        
+        iActivePopupPriority = popup->GetPriority();             
+                
+        // Create proper popup        
+        if( popup->GetPriority() == EPopupPriorityHighest )
+            {                                 
+            popup->Start( popup->GetMessage().Right( popup->GetMessage().Length() - KRcpHeaderLen ),
+                _L("Press any key to send 'remote run started' message"));                                  
+            }
+        else if( popup->GetPriority() == EPopupPriorityNormal )
+            {
+            popup->Start( popup->GetMessage().Right( popup->GetMessage().Length() - KRcpHeaderLen ),
+                _L("Press any key to set event") );        
+            }
+        else if( popup->GetPriority() == EPopupPriorityLow )
+            {           
+            popup->Start( popup->GetMessage().Right( popup->GetMessage().Length() - KRcpHeaderLen ),
+                _L("Press 1-9 to return negative error value, a to switch to another remote run result popup, or any other key to return 0") );                                    
+            }
+            
+        iPopupActive = ETrue;                                
+        }
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: ShuffleRemoteRunResultPopups
+
+    Description: Shuffle remote run result popups 
+
+    Parameters: CUIStorePopup* aPopup (currently active popup)
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft @js
+
+-------------------------------------------------------------------------------
+*/
+void CUIStore::ShuffleRemoteRunResultPopups( CUIStorePopup* aPopup )
+    {    
+    TInt nextPopupId = -1;
+    
+    for( TInt x=0; x<iPopups.Count(); x++)
+        {            
+        // Lets find the next remote run result priority popup
+        if( iPopups[x]->GetPriority() == EPopupPriorityLow && iPopups[x] != aPopup )    
+            {
+            nextPopupId = x;
+            break;
+            }
+        }
+    
+    if( nextPopupId == -1 )            
+        {
+        // We'll print error message popup, because there weren't any other remote run 
+        // result popups active
+
+        iUIStoreIf->PopupMsg( 
+            _L("Error! There weren't any other remote run result popups active."), 
+            _L(""), 
+            5 );        
+        User::After( 5000000 );
+        iPopups.Append( aPopup );
+        SetRemotePopupFromQueue();
+        return;
+        }
+
+    // We'll add the popup to the end of the array    
+    TInt ret = iPopups.Append( aPopup );
+        
+    if( ret != KErrNone )
+        {
+        delete aPopup;
+        return;
+        }
+        
+    // Print the next popup from queue
+    SetRemotePopupFromQueue();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: RemotePopup
+
+    Description: Do remote message popup 
+
+    Parameters: const TDesC& aReq: in: request
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStore::RemotePopupComplete( CUIStorePopup* aPopup, 
+                                    TInt aError,
+                                    CUIEngineContainer* aContainer,
+                                    CStifTFwIfProt* aResp,
+                                    TKeyCode aKeyCode )
+    {
+    
+    TInt ret = KErrNone;
+    TInt index = iPopups.Find( aPopup );
+    if( index < 0 )
+        {
+        User::Panic( KUIStore, KErrGeneral );
+        }
+    iPopups.Remove( index );   
+
+    iPopupActive = EFalse;
+    iActivePopupPriority = EPopupPriorityLow;
+
+    if( aError != KErrNone )
+        {
+        ret = aError;
+        }
+    else
+        {
+        TChar c( aKeyCode );
+        if( c.IsDigit() )
+            {
+            // Solve return value
+            ret = -( aKeyCode - '0' );
+            }
+        else
+            {
+            ret = KErrNone;
+            }
+        }
+    // If aResp is given, send it
+    if( aResp )
+        {     
+        switch( aResp->iCmdType )
+            {
+            case CStifTFwIfProt::ECmdRun:
+                {
+                TChar response( aKeyCode );  
+                RDebug::Print(_L("CUIStore::RemotePopupComplete: user pressed key %c"), (char)response);
+                  
+                if( aPopup->GetPriority() == EPopupPriorityHighest )
+                    {                                        
+                    // User has given response to remote run started- popup
+                    aResp->Append( CStifTFwIfProt::RunStatus, 
+                      CStifTFwIfProt::ERunStarted );                      
+                    }                
+                else if( aPopup->GetPriority() == EPopupPriorityLow &&  response=='a' )
+                    {                                        
+                    // User wants to change current remote run result popup to other
+                    // remote run result popup. 
+                    
+                    ShuffleRemoteRunResultPopups( aPopup );                             
+                    return KErrNone;
+                    }
+                else 
+                    {                                    
+                    // The test case result was given
+                    aResp->Append( CStifTFwIfProt::RunStatus, 
+                               CStifTFwIfProt::ERunReady );
+                    if( ret != KErrNone )
+                        {
+                        aResp->Append( CStifTFwIfProt::RunStatusParams, 
+                                       CStifTFwIfProt::ERunResult, ret );
+                        }                   
+                    }
+                break;
+                }
+            case CStifTFwIfProt::ECmdSendReceive:
+                {
+                aResp->Append( CStifTFwIfProt::RunStatus, 
+                               CStifTFwIfProt::ERunReady );
+                if( ret != KErrNone )
+                    {
+                    aResp->Append( CStifTFwIfProt::RunStatusParams, 
+                                   CStifTFwIfProt::ERunResult, ret );
+                    }
+                break;
+                }
+            case CStifTFwIfProt::ECmdPause:
+            case CStifTFwIfProt::ECmdResume:
+            case CStifTFwIfProt::ECmdCancel:
+            case CStifTFwIfProt::ECmdRequest:
+            case CStifTFwIfProt::ECmdRelease:
+            default:
+                if( ret != KErrNone )
+                    {
+                    aResp->Append( CStifTFwIfProt::RespParam, 
+                                   CStifTFwIfProt::ERespResult, 
+                                   ret );
+                    }
+                break;
+            }
+        
+        ret = aContainer->RemoteReceive( aResp->Message() ); 
+        }
+                
+    delete aPopup;      
+    
+    SetRemotePopupFromQueue();
+    
+    return ret;
+              
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStore
+
+    Method: ReadFiltersL
+
+    Description: Reads filters from test framework initialization file.
+        
+    Parameters: RPointerArray<TDesC>& aFilters: array to be filled
+
+    Return Values: None
+
+    Errors/Exceptions: 
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CUIStore::ReadFiltersL(RPointerArray<TDesC>& aFilters)
+    {
+    // Clean array
+    aFilters.ResetAndDestroy();
+    
+    // Locate file
+    _LIT(KFilterSectionStart, "[Filters]");
+    _LIT(KFilterSectionEnd, "[End_Filters]");
+    _LIT(KFilterDefinition, "filter=");
+
+    // Parse initialization file
+    TInt err = KErrNone;
+    CStifParser* parser;
+    
+    RDebug::Print(_L("STIF: Try to read filters from [%S]"), &iTestFrameworkIni);
+    parser = CStifParser::NewL(KNullDesC, iTestFrameworkIni);
+    CleanupStack::PushL(parser);
+
+    // Parser created (file exists), create section parser
+    CStifSectionParser* section;
+    section = parser->SectionL(KFilterSectionStart, KFilterSectionEnd);
+    if(section)
+        {
+        CleanupStack::PushL(section);
+            
+        // Get item lines
+        CStifItemParser* item = section->GetItemLineL(KFilterDefinition, ENoTag);
+            
+        TPtrC ptr;
+            
+        while(item)
+            {
+            CleanupStack::PushL(item);
+                
+            // Read filter value
+            err = item->GetString(KNullDesC, ptr);
+            if(err == KErrNone)
+                {
+                HBufC* filter = ptr.AllocLC();
+                User::LeaveIfError(aFilters.Append(filter));
+                CleanupStack::Pop();
+                }
+                
+            CleanupStack::PopAndDestroy(item);
+            item = NULL;
+            item = section->GetNextItemLineL(KFilterDefinition, ENoTag);
+            }
+            
+        CleanupStack::PopAndDestroy(section);
+        }
+        
+    // Clean
+    CleanupStack::PopAndDestroy(parser);
+
+    // If there are some filters added, first filter has to be "No filter"
+    if(aFilters.Count() > 0)
+        {
+        RDebug::Print(_L("STIF: Filters loaded"));
+        _LIT(KNoFilter, "No filter");
+        HBufC* name = KNoFilter().AllocLC();
+        User::LeaveIfError(aFilters.Insert(name, 0));
+        CleanupStack::Pop(name);    
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CUIStoreIf class member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStoreIf
+
+    Method: ConstructL
+
+    Description: Second phase constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if..
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CUIStoreIf::ConstructL( )
+    {
+    
+    iUIStore = CUIStore::NewL( this );
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStoreIf
+
+    Method: CUIStoreIf
+
+    Description: Constructor.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CUIStoreIf::CUIStoreIf( )
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStoreIf
+
+    Method: ~CUIStoreIf
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CUIStoreIf::~CUIStoreIf()
+    {	
+    
+    delete iUIStore;
+    iUIStore = NULL;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStoreIf
+
+    Method: UIStore
+
+    Description: Returns reference to CUIStore object, which handles test 
+                 cases and test modules.
+        
+    Parameters: None
+
+    Return Values: CUIStore reference
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CUIStore& CUIStoreIf::UIStore()
+    {
+    
+    __ASSERT_ALWAYS( iUIStore, User::Panic( KUIStoreIf, KErrNotFound ) );
+        
+    return *iUIStore;
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestSetInfo class member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: NewL
+
+    Description: Construct the CTestSetInfo class
+
+    Parameters: None
+
+    Return Values: CTestSetInfo*                    New object
+
+    Errors/Exceptions: Leaves if memory allocation fails or
+                       ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetInfo* CTestSetInfo::NewL( const TDesC& aName )
+    {
+    
+    CTestSetInfo* self = new ( ELeave ) CTestSetInfo();
+    CleanupStack::PushL( self );
+    self->ConstructL( aName );
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+            
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: ConstructL
+
+    Description: Second phase constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if..
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetInfo::ConstructL( const TDesC& aName )
+    {
+    
+    iName = aName.AllocL();
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: CTestSetInfo
+
+    Description: Constructor.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetInfo::CTestSetInfo()
+    {
+    iLastStartedCaseIndex = 0;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: ~CTestSetInfo
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetInfo::~CTestSetInfo()
+    {	
+    
+    iTestCases.ResetAndDestroy();
+    iTestCaseRefs.Reset();
+    iTestCases.Close();
+    iTestCaseRefs.Close();
+    
+    delete iName;
+    iName = NULL;
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: AddTestCase
+
+    Description: Add test case to test set.
+        
+    Parameters: const CTestInfo& aTestInfo: in: test info
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetInfo::AddTestCase( const CTestInfo& aTestInfo )
+    {
+    
+    CTestInfo* testInfo = NULL;
+    
+    TRAPD( err, 
+        testInfo = CTestInfo::NewL();
+        testInfo->CopyL( aTestInfo );
+        );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+
+    if( iTestCaseRefs.Append( *testInfo ) != KErrNone )
+        {
+        delete testInfo;
+        return KErrNoMemory;        
+        }
+    if( iTestCases.Append( testInfo ) != KErrNone ) 
+        {
+        iTestCaseRefs.Remove( iTestCaseRefs.Count()-1 );
+        delete testInfo;
+        return KErrNoMemory;
+        }
+
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: InsertTestCase
+
+    Description: Insert test case to test set.
+        
+    Parameters: const CTestInfo& aTestInfo: in: test info
+                TInt aPos: in: position to add
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetInfo::InsertTestCase( const CTestInfo& aTestInfo, TInt aPos )
+    {
+    
+    if( ( aPos < 0 ) ||
+        ( aPos >= iTestCases.Count() ) )
+        {
+        return KErrArgument;
+        }
+    
+    CTestInfo* testInfo = NULL;
+    
+    TRAPD( err, 
+        testInfo = CTestInfo::NewL();
+        testInfo->CopyL( aTestInfo );
+        );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+     
+    if( iTestCaseRefs.Insert( *testInfo, aPos ) != KErrNone )
+        {
+        delete testInfo;
+        return KErrNoMemory;        
+        }
+    if( iTestCases.Insert( testInfo, aPos ) != KErrNone )
+        {
+        iTestCaseRefs.Remove( aPos );
+        delete testInfo;
+        return KErrNoMemory;
+        }
+    
+    return err;
+        
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: RemoveTestCase
+
+    Description: Remove test case from test set.
+        
+    Parameters: const CTestInfo& aTestInfo: in: test info
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetInfo::RemoveTestCase( const CTestInfo& aTestInfo )
+    {
+    
+    TInt count = iTestCases.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aTestInfo == *iTestCases[i] )
+            {
+            CTestInfo* testInfo = iTestCases[i];
+            iTestCases.Remove( i );
+            iTestCaseRefs.Remove( i );
+            delete testInfo;
+            return KErrNone;
+            }
+        }
+
+    return KErrNotFound;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: CopyL
+
+    Description: Remove test case from test set.
+        
+    Parameters: const CTestInfo& aTestInfo: in: test info
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetInfo::CopyL( const CTestSetInfo& aTestSetInfo )
+    {
+    
+    iTestCaseRefs.Reset();
+    iTestCases.ResetAndDestroy();
+    
+    TInt count = aTestSetInfo.TestCases().Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        User::LeaveIfError( AddTestCase( aTestSetInfo.TestCases()[i] ) );
+        }
+    
+    delete iName;
+    iName = 0;    
+    iName = aTestSetInfo.Name().AllocL(); 
+    
+    iLastStartedCaseIndex = aTestSetInfo.iLastStartedCaseIndex;
+         
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: SetLastStartedCaseIndex
+
+    Description: Sets the info which test case has been started lately.
+        
+    Parameters: TInt aCaseStarted: index of started test case
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetInfo::SetLastStartedCaseIndex(TUint aLastStartedCaseIndex)
+    {
+    iLastStartedCaseIndex = aLastStartedCaseIndex;
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: GetLastStartedCaseIndex
+
+    Description: Gets the info which test case has been started lately.
+        
+    Parameters: None
+
+    Return Values: TInt: index of lately started test case
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TUint CTestSetInfo::GetLastStartedCaseIndex(void)
+    {
+    return iLastStartedCaseIndex;
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetInfo
+
+    Method: RenameTestSet
+
+    Description:  rename test set
+        
+    Parameters: aTestSetName : new TestSetName
+
+    Return Values: TInt: KErrNone if success.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetInfo::RenameTestSet(const TDesC& aTestSetName)
+    {
+    delete iName;
+    iName=NULL;
+    iName=aTestSetName.AllocL();
+    }
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIStoreContainer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,906 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CStartedTestCase class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+
+#include <stifinternal/UIEngine.h>
+#include <stifinternal/UIEngineContainer.h>
+#include <stifinternal/UIStoreContainer.h>
+#include <stifinternal/UIStore.h>
+
+#include "Logging.h"
+
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+_LIT( KStartedTestCase, "CStartedTestCase" );
+_LIT( KStartedTestSet, "CStartedTestSet" );
+
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestCase
+
+    Method: NewL
+
+    Description: Create a testcase container.
+
+    Parameters: CTestInfo* aTestInfo: in: Test case info
+                CUIEngineContainer* aContainer: in: container
+
+    Return Values: CStartedTestCase* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestCase* CStartedTestCase::NewL( const CTestInfo& aTestInfo, 
+                                          CUIEngineContainer& aContainer )
+    {
+
+    CStartedTestCase* self = new ( ELeave ) CStartedTestCase( aContainer );
+    CleanupStack::PushL( self );
+    self->ConstructL( aTestInfo );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestCase
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CTestInfo* aTestInfo: Test case info
+    
+    Return Values: None
+
+    Errors/Exceptions: Leaves if CTestInfo copying fails
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CStartedTestCase::ConstructL( const CTestInfo& aTestInfo )
+    {
+
+    iTestInfo = CTestInfo::NewL();
+    iTestInfo->CopyL( aTestInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestCase
+
+    Method: CStartedTestCase
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestCase::CStartedTestCase( CUIEngineContainer& aContainer ):
+    iContainer( &aContainer ),
+    iStatus( CUIStoreIf::EStatusRunning )
+    {
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestCase
+
+    Method: CStartedTestCase
+
+    Description: Private Constructor for internal use
+
+    Parameters: CTestInfo* aTestInfo: in: new testinfo
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestCase::CStartedTestCase( CTestInfo* aTestInfo, 
+                                    TFullTestResult aResult, 
+                                    TInt aStatus ):
+    iContainer( 0 ),
+    iTestInfo( aTestInfo ),
+    iResult( aResult ),
+    iStatus( aStatus )
+    {
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestCase
+
+    Method: ~CStartedTestCase
+
+    Description: Destructor.
+
+    Cancels the asynchronous request, deallocate memory and closes the testcase.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestCase::~CStartedTestCase()
+    {
+    
+    delete iTestInfo;
+    iPrints.ResetAndDestroy();
+    iPrints.Close();
+    
+    }
+ 
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestCase
+
+    Method: SetResult
+
+    Description: Set the result
+
+    Parameters: const TFullTestResult&     :in:      Result
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CStartedTestCase::SetResult(const TFullTestResult& aResult)
+    {
+
+    iResult = aResult;
+
+    iStatus = CUIStoreIf::EStatusExecuted;
+
+    switch( aResult.iCaseExecutionResultType )
+        {
+        case TFullTestResult::ECaseExecuted:
+            if( aResult.iTestResult.iResult == KErrNone )
+                {
+                iStatus |= CUIStoreIf::EStatusPassed;
+                }
+            else
+                {
+                iStatus |= CUIStoreIf::EStatusFailed;
+                }
+            break;
+        case TFullTestResult::ECaseCancelled:
+        case TFullTestResult::ECaseTimeout:
+        case TFullTestResult::ECaseSuicided:
+            iStatus |= CUIStoreIf::EStatusAborted;
+            break;
+        default:
+            iStatus |= CUIStoreIf::EStatusCrashed;
+            break;
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestCase
+
+    Method: UIEngineContainer
+
+    Description: Returns the UIEngineContainer
+
+    Parameters: None
+
+    Return Values: CUIEngineContainer& 
+
+    Errors/Exceptions: Panics if called for testcase that is not running
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CUIEngineContainer& CStartedTestCase::UIEngineContainer() const
+    { 
+    
+    if( !( iStatus & CUIStoreIf::EStatusRunning ) ) 
+        {
+        __RDEBUG( _L("CStartedTestCase::UIEngineContainer for test case that is not running"));
+        User::Panic( KStartedTestCase, KErrNotFound );
+        }
+    
+    return *iContainer;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CStartedTestSet class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: NewL
+
+    Description: Create a testcase container.
+
+    Parameters: const CTestSetInfo& aTestSetInfo: in: test set info
+                CUIStore::TSetType aType: in: set type
+
+    Return Values: CStartedTestSet* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestSet* CStartedTestSet::NewL( CUIStore* aUIStore, 
+                                        const CTestSetInfo& aTestSetInfo,
+                                        TSetType aType )
+    {
+
+    CStartedTestSet* self = new ( ELeave ) CStartedTestSet( aUIStore, aType );
+    CleanupStack::PushL( self );
+    self->ConstructL( aTestSetInfo );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: const CTestSetInfo& aTestSetInfo: in: Test set info
+    
+    Return Values: None
+
+    Errors/Exceptions: Leaves if CTestSetInfo copying fails
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CStartedTestSet::ConstructL( const CTestSetInfo& aTestSetInfo )
+    {
+
+    iTestSetInfo = CTestSetInfo::NewL( aTestSetInfo.Name() );
+    iTestSetInfo->CopyL( aTestSetInfo );
+
+    iOriginalTestSet = const_cast<CTestSetInfo*>(&aTestSetInfo);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: CStartedTestSet
+
+    Description: Constructor
+
+    Parameters: CUIStore::TSetType aType: in: set type
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestSet::CStartedTestSet( CUIStore* aUIStore, 
+                                  TSetType aType ):
+    iUIStore( aUIStore ),
+    iResultSet( EFalse ),
+    iType( aType ),
+    iStatus( CUIStoreIf::ESetRunning ),
+    iNext( 0 ),
+    iRunningCases( 0 ),
+    iOriginalTestSet ( NULL )
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: ~CStartedTestSet
+
+    Description: Destructor.
+
+    Cancels the asynchronous request, deallocate memory and closes the testcase.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestSet::~CStartedTestSet()
+    {
+    
+    delete iTestSetInfo;
+    iTestSetInfo = 0;
+    iTestCases.Reset();
+    iTestCases.Close();
+    
+    }
+ 
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: StartNext
+
+    Description: Start next testcase. 
+    
+    Parameters: None
+
+    Return Values: KErrNone: test case started
+                   KErrNotFound: no test cases found.
+                   Other Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStartedTestSet::StartNext()
+    {
+    TInt ret = KErrNone;
+    
+    TInt count = iTestSetInfo->TestCases().Count();
+    if( iNext >= count )
+        {
+        // All test cases running or completed, no more cases to start
+        return KErrNotFound;
+        }
+    
+    TInt index = 0;
+    if( iType == ESetSequential )
+        {
+        // Get test case index to be executed (when in NotExecutedCasesMode)
+        if(iNotStartedCasesMode)
+            {
+            iNext = iTestSetInfo->GetLastStartedCaseIndex();
+
+            if(iNext >= count)
+                {
+                // All test cases running or completed, no more cases to start
+                return KErrNotFound;
+                }
+
+            iTestSetInfo->SetLastStartedCaseIndex(iNext + 1);
+            if(iOriginalTestSet)
+                {
+                iOriginalTestSet->SetLastStartedCaseIndex(iNext + 1);
+                // Update only if original test set exists
+                iUIStore->UpdateTestSet(*iOriginalTestSet);
+                }
+            }
+
+        // Start next one and return
+        ret = iUIStore->StartTestCase( iTestSetInfo->TestCases()[iNext],
+                                       index );
+        if( ret != KErrNone )
+            {
+            return ret;
+            }
+        iNext++;
+        TRAPD( err,
+            CStartedTestCase& testCase = iUIStore->StartedTestCaseL( index );
+            ret = iTestCases.Append( testCase );
+            );
+        if( err != KErrNone )
+            {
+            User::Panic( KStartedTestSet, err );
+            }
+        }
+    else
+        {
+        // Start all cases
+        for( ; iNext<count; iNext++ )
+            {
+            ret = iUIStore->StartTestCase( iTestSetInfo->TestCases()[iNext],
+                                           index );
+            if( ret != KErrNone )
+                {
+                break;
+                }
+            TRAPD( err,
+                CStartedTestCase& testCase = iUIStore->StartedTestCaseL( index );
+                ret = iTestCases.Append( testCase );
+                iRunningCases++;
+                );
+            if( err != KErrNone )
+                {
+                User::Panic( KStartedTestSet, err );
+                }
+            if( ret != KErrNone )
+                {
+                break;
+                }
+            } 
+        }
+    
+    return ret;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: Abort
+
+    Description: Start next testcase. 
+    
+    Parameters: None
+
+    Return Values: KErrNone: test case started
+                   KErrNotFound: no test cases found.
+                   Other Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStartedTestSet::Abort()
+    {
+    
+    TInt ret = KErrNotFound;
+    TInt count = iTestCases.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( iTestCases[i].Status() & 
+            CUIStoreIf::EStatusRunning )
+            {
+            ret = iTestCases[i].UIEngineContainer().CancelTest();
+            if( ret != KErrNone )
+                {
+                break;
+                }
+            }
+        }
+    
+    // Prevent execution of remaining cases
+    count = iTestSetInfo->TestCases().Count();
+    iNext = count;
+    
+    return ret;  
+     
+    }
+    
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: IsRunning
+
+    Description: Check if test case running in this test set.
+    
+    Parameters: const CStartedTestCase* aTestCase: in: test case info
+
+    Return Values: ETrue: This test set is running specified test case
+                   EFalse: Not running
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TBool CStartedTestSet::IsRunning( const CStartedTestCase* aTestCase )
+    {
+    
+    TInt count = iTestCases.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aTestCase == &iTestCases[i] )
+            {
+            return ETrue;
+            }
+        }
+        
+    return EFalse;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: TestCompleted
+
+    Description: Test from this set completed. Start next or 
+                set result for set.
+    
+    Parameters: const CStartedTestCase* aTestCase: in: test case info
+                TFullTestResult aResult: in: test result
+
+    Return Values:  Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStartedTestSet::TestCompleted( const CStartedTestCase* aTestCase, 
+                                     TFullTestResult aResult )  
+    {
+    
+    TInt count = iTestCases.Count();
+    TInt index = 0;
+    for( ; index<count; index++ )
+        {
+        if( aTestCase == &iTestCases[index] )
+            {
+            break;
+            }
+        }
+    if( index == count )
+        {
+        return KErrNotFound;
+        }
+    
+    // Remove from running test cases
+    iRunningCases--;
+    
+    if( iResultSet == EFalse )
+        {
+        // Check test results
+        if( ( aResult.iCaseExecutionResultType != 
+              TFullTestResult::ECaseExecuted ) ||
+            ( aResult.iTestResult.iResult != KErrNone ) )
+            {
+            iResult = aResult; 
+            iResultSet = ETrue;
+            }
+        }
+        
+    // Start next test case
+    if( StartNext() == KErrNone )
+        {
+        // Test case was started
+        return KErrNone;
+        }
+    
+    if( iRunningCases > 0 )
+        {
+        // Test cases still running in test set
+        return KErrNone;
+        }
+    
+    iStatus = CUIStoreIf::ESetExecuted;
+    if( iResultSet == EFalse )
+        {  
+        // Use the result of last test case all 
+        // test cases where succesfull
+        iResult = aResult;
+        }
+        
+    // Set test case completed 
+    if( ( iResult.iCaseExecutionResultType != 
+          TFullTestResult::ECaseExecuted ) ||
+        ( iResult.iTestResult.iResult != KErrNone ) )
+        {
+        iStatus = CUIStoreIf::ESetFailed;               
+        }   
+    else
+        {
+        iStatus = CUIStoreIf::ESetPassed;
+        }
+        
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: SetNotExecutedCasesMode
+
+    Description: Sets mode in which only not executed tests will be run.
+    
+    Parameters: TBool aNotExecutedCasesMode: desired mode
+
+    Return Values:  None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CStartedTestSet::SetNotStartedCasesMode(TBool aNotStartedCasesMode)
+    {
+    iNotStartedCasesMode = aNotStartedCasesMode;
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: GetOriginalTestSet
+
+    Description: Returns pointer to original test set.
+    
+    Parameters: None
+
+    Return Values:  Pointer to original test set.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestSetInfo* CStartedTestSet::GetOriginalTestSet()
+    {
+    return iOriginalTestSet;
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSet
+
+    Method: NullOriginalTestSet
+
+    Description: Sets pointer to original test set to NULL.
+    
+    Parameters: None
+
+    Return Values:  None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CStartedTestSet::NullOriginalTestSet()
+    {
+    iOriginalTestSet = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestProgress class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgress
+
+    Method: NewL
+
+    Description: Create CTestProgress.
+
+    Parameters: TTestProgress& aProgress: in: info from test module
+
+    Return Values: CTestProgress* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestProgress* CTestProgress::NewL( const TTestProgress& aProgress )
+    {
+
+    CTestProgress* self = new ( ELeave ) CTestProgress();
+    CleanupStack::PushL( self );
+    self->ConstructL( aProgress );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgress
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: TTestProgress& aProgress: in: print info
+    
+    Return Values: None
+
+    Errors/Exceptions: Leaves if TTestProgress copying fails
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestProgress::ConstructL( const TTestProgress& aProgress  )
+    {
+    
+    iPosition = aProgress.iPosition;
+    iDescriptionBuf = aProgress.iDescription.AllocL();
+    iTextBuf = aProgress.iText.AllocL();
+    iDescription.Set( iDescriptionBuf->Des() );
+    iText.Set( iTextBuf->Des() );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgress
+
+    Method: ~CTestProgress
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestProgress::~CTestProgress()
+    {
+    
+    delete iTextBuf;
+    delete iDescriptionBuf;
+    
+    }
+ 
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgress
+
+    Method: ReplaceTextL
+
+    Description: Replace text with ne one.
+
+    Parameters: const TTestProgress& aProgress: in: new info
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestProgress::ReplaceTextL( const TTestProgress& aProgress )
+    {
+    
+    HBufC* tmp = iTextBuf;
+    iTextBuf = 0;
+    CleanupStack::PushL( tmp );
+    iTextBuf = aProgress.iText.AllocL();
+    iText.Set( iTextBuf->Des() );
+    CleanupStack::PopAndDestroy( tmp );
+    
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/StifTFwIf/src/UIStorePopup.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,310 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: CUIStorePopup: This object executes test cases 
+* from STIF Test Framework.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <stifinternal/UIStore.h>
+#include "UIStorePopup.h"
+#include "Logging.h"
+
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iUIStore->iLogger
+
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ==================== LOCAL FUNCTIONS ======================================= 
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStorePopup
+
+    Method: CUIStorePopup
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIStorePopup::CUIStorePopup( CUIStore* aUIStore,
+                              CUIEngineContainer* aContainer,
+                              CStifTFwIfProt* aRemoteMsg,                             
+                              CUIStore::TPopupPriority aPopupPriority) :
+    CActive( CActive::EPriorityStandard ),
+    iUIStore( aUIStore ),
+    iRemoteMsg( aRemoteMsg ),
+    iContainer( aContainer ),
+    iPopupPriority( aPopupPriority )
+    {
+    __TRACE( KPrint, ( _L( "CUIStorePopup::CUIStorePopup") ) );
+    __ASSERT_ALWAYS( aUIStore, User::Panic( _L("Null pointer"), KErrGeneral ) );
+
+    CActiveScheduler::Add( this );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStorePopup
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called Open method returns error
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CUIStorePopup::ConstructL( const TDesC& aMsg )
+    {    
+    iMsg = aMsg.AllocL();
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStorePopup
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+    
+    Parameters: CUIStore* CUIStore: in: Pointer to CUIStore Interface
+                TTestInfo& aTestInfo: in: Test info
+
+    Return Values: CUIStorePopup* : Pointer to created runner object
+
+    Errors/Exceptions: Leaves if memory allocation for CUIStorePopup fails
+                       Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIStorePopup* CUIStorePopup::NewL( CUIStore* aUIStore,
+                                    CUIEngineContainer* aContainer,
+                                    CStifTFwIfProt* aRemoteMsg,
+                                    CUIStore::TPopupPriority aPopupPriority,
+                                    const TDesC& aMsg )
+    {
+    
+    CUIStorePopup* self =  
+        new ( ELeave ) CUIStorePopup( aUIStore, aContainer, aRemoteMsg, aPopupPriority );
+    CleanupStack::PushL( self );
+    self->ConstructL( aMsg );
+    CleanupStack::Pop();
+    return self;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStorePopup
+
+    Method: ~CUIStorePopup
+
+    Description: Destructor
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CUIStorePopup::~CUIStorePopup()
+    {
+    __TRACE( KPrint, ( _L( "CUIStorePopup::~CUIStorePopup()") ) );
+    Cancel();
+    
+    delete iMsg;
+    delete iRemoteMsg;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStorePopup
+
+    Method: Start
+
+    Description: Call SETActive and return TRequestStatus member.
+
+    Parameters: None
+
+    Return Values: Symbian OS error code
+    
+    Errors/Exceptions: None
+    
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CUIStorePopup::Start( const TDesC& aLine1, 
+                           const TDesC& aLine2 )
+    {
+    __TRACE( KPrint, ( _L( "CUIStorePopup::Start") ) );
+    
+    if(IsActive())
+    { 
+        __TRACE( KPrint, ( _L( "CUIStorePopup already started") ) );
+       return KErrNone;  
+    }
+          
+    iPopupWindow = iUIStore->iUIStoreIf->PopupMsg( 
+        aLine1, aLine2, KDefaultPopupTimeout, iKey, iStatus );
+    
+    if( iPopupWindow < 0 )
+        {
+        return iPopupWindow;
+        }
+
+    SetActive();
+    return KErrNone;
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStorePopup
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone, error is handled in
+                       RunError called by CActiveObject
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIStorePopup::RunL()
+    {
+   
+    __TRACE( KPrint, ( _L( "CUIStorePopup::RunL") ) );
+    
+    iUIStore->RemotePopupComplete( this, iStatus.Int(), 
+                                   iContainer, iRemoteMsg, iKey );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUIStorePopup
+
+    Method: DoCancel
+
+    Description: Cancel active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CUIStorePopup::DoCancel()
+    {
+    __TRACE( KPrint, ( _L( "CUIStorePopup::DoCancel") ) );
+    
+    iUIStore->iUIStoreIf->Close( iPopupWindow );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    CActiveTimer: This object prints running seconds to console screen.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+
+
+// ================= OTHER EXPORTED FUNCTIONS ================================= 
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/Bmarm/testcombineru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__Fv @ 1 NONAME R3UNUSED ; LibEntryL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/Bwins/testcombineru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCTestCombiner@@XZ @ 1 NONAME ; class CTestCombiner * __cdecl LibEntryL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/eabi/testcombineru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLv @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/group/TestCombiner.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestCombiner.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET      	testcombiner.dll
+TARGETTYPE  	dll
+
+CAPABILITY	ALL -TCB
+VENDORID 	0x101FB657
+SECUREID        0x102073DF
+
+DEFFILE     	testcombiner.def
+
+LIBRARY     	euser.lib
+LIBRARY		stiftestinterface.lib
+LIBRARY		stiftestserver.lib
+LIBRARY         efsrv.lib 
+LIBRARY         stiftestengine.lib
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          TestCombiner.cpp 
+SOURCE          TestCombinerUtils.cpp 
+SOURCE          TestCase.cpp 
+SOURCE          TestCaseNotify.cpp 
+SOURCE          TestKeywords.cpp
+//--PYTHON-- begin
+SOURCE          StifPythonFunComb.cpp
+//--PYTHON-- end
+
+// First UID is DLL UID, Second UID is STIF Test Framework UID
+UID             0x1000008D 0x101FB3E7// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/group/TestCombinerExample.cfg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,94 @@
+[Test]
+title complete
+run demomodule Demo.cfg 1 testid=demo ini=ini.txt expect=0
+pause demo
+resume demo
+complete demo
+[Endtest]
+
+[Test]
+title complete and rerun
+run demomodule Demo.cfg 1 testid=demo expect=0
+pause demo
+resume demo
+complete demo
+run demomodule Demo.cfg 1
+[Endtest]
+
+[Test]
+title cancel
+run demomodule Demo.cfg 1 testid=demo ini=ini.txt expect=-3
+pause demo time=2000
+cancel demo
+[Endtest]
+
+[Test]
+title double
+run demomodule Demo.cfg 1 testid=demo10 ini=ini.txt expect=-3
+run demomodule Demo.cfg 1 testid=demo20 ini=ini.txt
+pause demo10
+pause demo20
+resume demo10
+cancel demo10
+resume demo20
+[Endtest]
+
+[Test]
+title timer2
+run timermodule Demo.cfg 0 testid=t1 expect=-2
+run timermodule Demo.cfg 1 testid=t2
+pause t1
+complete t2
+resume t1
+[Endtest]
+
+[Test]
+title pause t1 5 sec
+run timermodule Demo.cfg 0 testid=t1 expect=-2
+run timermodule Demo.cfg 1 testid=t2
+pause t1 time=5000
+[Endtest]
+
+[Test]  
+title test TestCombiner state events
+request demo
+set demo state=1
+wait demo
+release demo 
+unset demo
+[Endtest]
+
+[Test]  
+title test TestCombiner indication event set
+set demo
+[Endtest]
+
+[Test]  
+title test TestCombiner indication event req-wait-rel
+request demo
+wait demo
+release demo 
+[Endtest]
+
+[Test]  
+title wait TestModuleState1 event (testmodule/TestCombiner combined)
+request TestModuleState1
+run testmodule ex.cfg 18
+wait TestModuleState1
+release TestModuleState1
+[Endtest]
+
+[Test]  
+title multiple wait TestModuleIndication1 event (testmodule/TestCombiner combined)
+request TestModuleIndication1
+run testmodule ex.cfg 20
+wait TestModuleIndication1
+wait TestModuleIndication1
+wait TestModuleIndication1
+wait TestModuleIndication1
+wait TestModuleIndication1
+wait TestModuleIndication1
+release TestModuleIndication1
+[Endtest]
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	Build information for STIF Test Framework's TestCombiner.
+*/
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+	
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	TestCombiner.mmp
+
+PRJ_TESTMMPFILES
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/inc/Logging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,76 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains Logging macros for test combiner
+*
+*/
+
+#ifndef LOGGINGDEFS_H
+#define LOGGINGDEFS_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+
+// CONSTANTS
+const TUint KError              = 0x1;
+const TUint KInit               = 0x2;
+const TUint KPrint              = 0x4;
+const TUint KMessage            = 0x10;
+const TUint KFunction           = 0x20;
+const TUint KVerbose            = 0x40;
+const TUint KAlways             = 0xFFFFFFFF;
+const TUint KDebugLevel         = ( KPrint | KError | KMessage );
+
+// MACROS
+#define __TRACING_ENABLED
+
+#ifdef __TRACING_ENABLED
+
+     // Disable conditional expression is constant -warning
+    #pragma warning( disable : 4127 )
+
+    // General tracing function
+    #define __TRACE(level,p) if ( ( (level) & KDebugLevel ) && LOGGER )\
+                                          {LOGGER->Log p;}
+              
+    // Direct RDebug::Print                            
+    #define __RDEBUG(p) if( KVerbose & KDebugLevel ){ RDebug::Print p ; } 
+
+
+     // Log function name
+    #define __TRACEFUNC() if( ( KFunction & KDebugLevel ) && LOGGER ){\
+                                const char* f = __FUNCTION__;\
+                                 TPtrC8 F((const unsigned char*)f);\
+                                 LOGGER->Log(F);}
+
+#else // __TRACING_ENABLED
+     // No tracing
+    #define __TRACE(level,p)
+    #define __RDEBUG(p)
+    #define __TRACEFUNC()
+#endif // __TRACING_ENABLED
+
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+#endif // LOGGINGDEFS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/inc/StifPythonFunComb.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header of additional functions 
+* needed for Python support and used in PythonScripter, TestEngine 
+* and TestCombiner.
+*
+*/
+
+#ifndef STIFPYTHONFUNCOMB_H
+#define STIFPYTHONFUNCOMB_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+TInt GetNewIndexForThreadL(void);
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+// None
+
+#endif        // STIFPYTHONFUNCOMB_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/inc/TestCase.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,601 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CTCTestCase 
+* and TTCTestModule.
+*
+*/
+
+#ifndef TESTCASE_H
+#define TESTCASE_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <stifinternal/TestServerClient.h>
+#include <StifTestModule.h>
+#include "TestCaseNotify.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CTestCombiner;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestCase is a parent class for the test case runner in TestCombiner.
+NONSHARABLE_CLASS(CTestCase)
+    :public CActive
+    {
+    public: // Enumerations
+        enum TTestCaseStatus
+            {
+            ETestCaseIdle,
+            ETestCaseRunning,
+            ETestCaseCompleted
+            };
+        
+        enum TCaseType
+            {
+            ECaseLocal,
+            ECaseRemote,
+            };
+
+    private: // Enumerations
+
+    public: // Destructor
+        /**
+        * Destructor.
+        */
+        virtual ~CTestCase();
+
+    public: // New functions
+        /**
+        * Calls SetActive() from CActive.
+        */
+        virtual void StartL();
+        
+        /**
+        * Get state of the test case.
+        */
+        TTestCaseStatus State(){ return iState; }
+                
+        /**
+        * Get reference to TestId.
+        */
+        const TDesC& TestId(){ return *iTestId; }
+
+        /**
+        * Get expected result.
+        */
+        TInt ExpectedResult(){ return iExpectedResult; }
+
+        /**
+        * Get expected result category.
+        */
+        TFullTestResult::TCaseExecutionResult
+            ExpectedResultCategory(){ return iExpectedResultCategory; }
+
+        /**
+        * Get test case type.
+        */
+        TCaseType Type(){ return iType; }
+
+        //--PYTHON-- begin
+        /**
+        * Get TestModule.
+        */
+        CTCTestModule* TestModule(void){ return iTestModule; }
+        //--PYTHON-- end
+
+        /**
+        * Checks state and additional conditions
+        */
+        virtual TBool IsCompletelyFinished(void);
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+    protected: // New functions
+
+        /**
+        * Completes testcase.
+        */
+        virtual void Complete( TInt aError );
+
+    protected: // Constructors
+        /**
+        * C++ default constructor.
+        */
+        CTestCase( CTestCombiner* testCombiner,
+                   TInt aExpectedResult,
+                   TFullTestResult::TCaseExecutionResult aCategory,
+                   TCaseType aType,
+                   CTCTestModule* aModule ); //--PYTHON--
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TDesC& aTestId );
+
+    private:
+
+    public:  // Data
+
+        // Test case result
+        TFullTestResult         iResult;
+
+    protected: // Data
+        // Test case type
+        TCaseType               iType;
+
+        // Backpointer
+        CTestCombiner*          iTestCombiner;
+
+        // Internal state
+        TTestCaseStatus         iState;
+
+        // Unique test id
+        HBufC*                  iTestId;
+
+        // Expected result for the test case
+        TInt                    iExpectedResult;
+
+        // Expected result category
+        TFullTestResult::TCaseExecutionResult iExpectedResultCategory;
+
+    private: // Data
+        //--PYTHON-- begin
+        CTCTestModule*			iTestModule;
+        //--PYTHON-- end
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+        friend class CTestRunner;
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTCTestCase handles the running of a single testcase in TestCombiner.
+
+NONSHARABLE_CLASS(CTCTestCase)
+    :public CTestCase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CTCTestCase* NewL( CTestCombiner* testCombiner,
+                                  TDesC& aModuleName,
+                                  TDesC& aTestId,
+                                  TInt aExpectedResult,
+                                  TFullTestResult::TCaseExecutionResult aCategory,
+                                  const TDesC& aTestCaseArguments,
+                                  CTCTestModule* aModule ); //--PYTHON--
+
+        /**
+        * Destructor.
+        */
+        ~CTCTestCase();
+
+    public: // New functions
+        /**
+        * Calls SetActive() from CActive.
+        */
+        void StartL();
+
+        /**
+        * Get reference to ModuleName.
+        */
+        const TDesC& ModuleName(){ return *iModuleName; }
+
+        /**
+         * Get test case arguments
+         */
+        const TDesC& TestCaseArguments() const;
+        
+        /**
+        * Get reference to RTestExecution.
+        */
+        RTestExecution& TestExecution(){ return iTestExecution; }
+
+        /**
+        * Get reference to event array.
+        */
+        RPointerArray<CTestEventNotify>& EventArray(){ return iEventArray; }
+
+        /**
+        * Get reference to state event array.
+        */
+        RPointerArray<TEventIf>& StateEventArray(){ return iStateEventArray; }
+
+         /**
+        * Final complete of the testcase.
+        */
+        void Complete2();
+
+        /**
+        * Checks state and progress notifier
+        */
+        TBool IsCompletelyFinished(void);
+
+    public: // Functions from base classes
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CTCTestCase( CTestCombiner* testCombiner,
+                     TInt aExpectedResult,
+                     TFullTestResult::TCaseExecutionResult aCategory,
+                     CTCTestModule* aModule ); //--PYTHON--
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TDesC& aModuleName, TDesC& aTestId, const TDesC& aTestCaseArguments );
+
+        /**
+        * Start complete the testcase(Complete2 make the final complete).
+        */
+        void Complete( TInt aError );
+
+    public:  // Data
+        // Test case result package
+        TFullTestResultPckg iResultPckg;
+
+    protected: // Data
+
+    private: // Data
+
+        // Progress notifier
+        CTestProgressNotifier*  iProgress;
+
+        // Event notifier
+        CTestEventNotifier*     iEvent;
+
+        // Module name
+        HBufC*                  iModuleName;
+
+        // Test case arguments
+        HBufC*                  iTestCaseArguments;
+        
+        // Handle to test case execution
+        RTestExecution          iTestExecution;
+
+        // Event array for events requested by test case
+        RPointerArray<CTestEventNotify> iEventArray;
+
+        // Event array for state events set by test case
+        RPointerArray<TEventIf>         iStateEventArray;
+        
+        // Command notifier
+        CTestCommandNotifier*    iCommand;
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+
+    };
+
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Testcase starting information
+NONSHARABLE_CLASS(CRemoteTestCase)
+    :public CTestCase
+    {
+
+    public: // Enumerations
+        enum TRemoteState
+            {
+            ECaseIdle,
+            ECaseRunSent,
+            ECaseRunning,
+            ECasePauseSent,
+            ECasePaused,
+            ECaseResumeSent,
+            ECaseCancelSent,
+            ECaseCancelled,
+            ECaseCompleted,
+            };
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CRemoteTestCase* NewL( CTestCombiner* testCombiner,
+                                      TDesC& aTestId,
+                                      TInt aExpectedResult,
+                                      TFullTestResult::TCaseExecutionResult
+                                            aCategory );
+
+        /**
+        * Destructor.
+        */
+        ~CRemoteTestCase();
+
+    public: // New functions
+
+    public: // Functions from base classes
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CRemoteTestCase( CTestCombiner* testCombiner,
+                         TInt aExpectedResult,
+                         TFullTestResult::TCaseExecutionResult aCategory );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TDesC& aTestId );
+
+    public:  // Data
+        // Remote slave state
+        TRemoteState    iRemoteState;
+
+        // Slave identifier
+        TUint32         iSlaveId;
+
+        // Free slave after completed
+        TBool           iFreeSlave;
+
+    protected: // Data
+
+    private: // Data
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CRemoteSendReceive handles the running of an asynchronous 'sendreveive'
+// in TestCombiner.
+// Note: If want to improve sendreceive for allowing use like 'run'
+// then this must inherit from CActive
+NONSHARABLE_CLASS(CRemoteSendReceive) :public CBase
+    {
+    public: // Enumerations
+
+    public: // Enumerations
+        enum TRemoteState
+            {
+            ECaseSend,
+            ECaseCompleted,
+            };
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CRemoteSendReceive* NewL( CTestCombiner* aTestCombiner );
+
+        /**
+        * Destructor.
+        */
+        ~CRemoteSendReceive();
+
+    public: // Constructors and destructor
+
+    public: // New functions
+
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    protected: // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CRemoteSendReceive( CTestCombiner* aTestCombiner );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:  // Data
+
+       // Remote slave state
+        TRemoteState    iRemoteState;
+
+        // Slave identifier
+        TUint32         iSlaveId;
+
+    protected: // Data
+
+    private: // Data
+
+        // Backpointer
+        CTestCombiner*      iTestCombiner;
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+
+    };
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+// TTCTestModule encapsulates information about loaded test module.
+
+NONSHARABLE_CLASS(CTCTestModule)
+    :public CBase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CTCTestModule* NewL( CTestCombiner* testCombiner,
+                                    TDesC& aModule,
+                                    TDesC& aIni,
+                                    const TDesC& aConfigFile );
+
+        /**
+        * Destructor.
+        */
+        ~CTCTestModule();
+
+    public: // Constructors and destructor
+
+    public: // New functions
+         /**
+         * Get module name.
+         */
+         const TDesC& ModuleName(){ return *iModuleName; }
+
+         /**
+         * Get module inifile name.
+         */
+         const TDesC& IniFile(){ return *iIniFile; }
+
+         /**
+        * Get reference to RTestServer.
+        */
+        RTestServer& TestServer(){ return iTestServer; }
+
+        /**
+        * Get reference to RTestModule.
+        */
+        RTestModule& TestModule(){ return iTestModule; }
+
+        /**
+        * Get test cases from module.
+        */
+        void GetTestCasesForCombiner(const TDesC& aConfigFile);
+
+        /**
+        * Get index of given test case.
+        */
+        TInt GetCaseNumByTitle(TDesC& aTitle, TInt& aCaseNum);
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    protected: // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CTCTestModule( CTestCombiner* testCombiner );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TDesC& aModule,
+                         TDesC& aIni,
+                         const TDesC& aConfigFile );
+
+    public:  // Data
+
+    protected: // Data
+
+    private: // Data
+        // Backpointer
+        CTestCombiner*      iTestCombiner;
+        
+        // Module name
+        HBufC*              iModuleName;
+        // Module initialization file
+        HBufC*              iIniFile;
+
+        // Handle to test server
+        RTestServer         iTestServer;
+        // Handle to module 
+        RTestModule         iTestModule;
+        
+        // Error notifier
+        CTestErrorNotifier* iErrorPrinter;
+
+        // Array of test cases used to find test case number by title
+        CFixedFlatArray<TTestCaseInfo>* iTestCases;
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+
+    };
+    
+#endif        // TESTCASE_H  
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/inc/TestCaseNotify.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,530 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of
+* the CTestProgressNotifier and the CTestEventNotifier.
+*
+*/
+
+#ifndef TEST_CASE_NOTIFY_H
+#define TEST_CASE_NOTIFY_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <stifinternal/TestServerClient.h>
+#include "TestCombiner.h"
+#include "StifCommand.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestProgressNotifier is an active object used for notifications called from
+// Test Module using the RTestExecution API.
+NONSHARABLE_CLASS(CTestProgressNotifier)
+    :public CActive
+    {
+    public: // Enumerations
+        
+    private: // Enumerations
+        // TTestProgressStatus defines the status of notification
+        enum TTestProgressStatus
+            {
+            ETestProgressIdle,
+            ETestProgressPending,
+            ETestProgressCompleted
+            };
+
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CTestProgressNotifier* NewL( CTestCombiner* aTestCombiner, 
+                                            CTCTestCase* aTestCase );
+          
+        /**
+        * Destructor.
+        */
+        ~CTestProgressNotifier();
+        
+        /**
+        * Checks is UI print progress finished.
+        */
+        TBool IsPrintProgressFinished();
+          
+    public: // New functions
+          
+    public: // Functions from base classes
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+          
+    protected: // New functions
+        
+    protected: // Functions from base classes
+        
+    private:
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestProgressNotifier( CTestCombiner* aTestCombiner, 
+                               CTCTestCase* aTestCase );
+
+        /**
+        * Start progress notifier.
+        */
+         void StartL();
+
+    public: // Data
+     
+    protected: // Data
+    
+    private: // Data
+        // Pointer to CTestCombiner
+        CTestCombiner*      iTestCombiner;
+          
+        // Pointer to CTCTestCase 
+        CTCTestCase*         iTestCase;
+
+        // Internal state
+        TTestProgressStatus iState;
+
+        // Test Progress
+        TTestProgress       iProgress;
+        TTestProgressPckg   iProgressPckg;
+
+        // Indication for UI print process
+        TBool               iIsPrintProcessFinished;
+
+    public: // Friend classes
+    
+    protected: // Friend classes
+    
+    private: // Friend classes
+    
+    };     
+    
+// DESCRIPTION
+// CTestErrorNotifier is an active object used for notifications called from
+// Test Module using the RTestExecution API.
+NONSHARABLE_CLASS(CTestErrorNotifier)
+    :public CActive
+    {
+    public: // Enumerations
+        
+    private: // Enumerations
+        // TTestProgressStatus defines the status of notification
+        enum TTestErrorStatus
+            {
+            ETestErrorIdle,
+            ETestErrorPending,
+            ETestErrorCompleted
+            };
+
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CTestErrorNotifier* NewL( CTestCombiner* aTestCombiner, 
+                                         CTCTestModule* aTestModule );
+          
+        /**
+        * Destructor.
+        */
+        ~CTestErrorNotifier();
+          
+    public: // New functions
+          
+    public: // Functions from base classes
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+          
+    protected: // New functions
+        
+    protected: // Functions from base classes
+        
+    private:
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestErrorNotifier( CTestCombiner* aTestCombiner, 
+                            CTCTestModule* aTestModule );
+
+        /**
+        * Start progress notifier.
+        */
+         void StartL();
+
+    public: // Data
+     
+    protected: // Data
+    
+    private: // Data
+        // Pointer to CTestCombiner
+        CTestCombiner*      iTestCombiner;
+          
+        //Pointer to CTCTestCase 
+        CTCTestModule*         iTestModule;
+
+        // Internal state
+        TTestErrorStatus iState;
+
+        // Test Progress
+        TErrorNotification       iError;
+        TErrorNotificationPckg   iErrorPckg;
+
+    public: // Friend classes
+    
+    protected: // Friend classes
+    
+    private: // Friend classes
+    
+    };     
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestEventNotify is an active object used to get event notify from
+// Test Server.
+NONSHARABLE_CLASS(CTestEventNotify)
+    :public CActive
+    {
+    public: // Enumerations
+    
+    private: // Enumerations
+        // TTestEventStatus defines the status of notification
+        enum TTestEventNotifyStatus
+            {
+            ETestEventNotifyIdle,
+            ETestEventNotifyPending,
+            ETestEventNotifyCompleted
+            };
+
+    public:  // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CTestEventNotify* NewL( CTestCombiner* aTestCombiner,
+                                       CTCTestCase* aTestCase,
+                                       TEventIf& aEvent );
+          
+        /**
+        * Destructor.
+        */
+        ~CTestEventNotify();
+          
+    public: // New functions     
+          
+        TEventIf& Event(){ return iEvent; };
+        
+    public: // Functions from base classes
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+          
+    protected:  // New functions
+    
+    protected:  // Functions from base classes
+    
+    private:
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TEventIf& aEvent );
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestEventNotify( CTestCombiner* aTestCombiner, 
+                          CTCTestCase* aTestCase );
+        
+
+    public:    //Data
+     
+    protected:  // Data
+ 
+    private:     // Data
+        // Pointer to CTestCombiner
+        CTestCombiner* iTestCombiner;
+        
+        // Pointer CTestCase
+        CTCTestCase* iTestCase;
+
+        // Internal state
+        TTestEventNotifyStatus iState;
+
+        // Event interface
+        TEventIf iEvent;
+        TEventIfPckg iEventPckg;
+
+    public:      // Friend classes
+
+    protected:  // Friend classes
+
+    private:     // Friend classes
+
+    };
+    
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestEventNotifier is an active object used for event notify from
+// Test Module using the RTestExecution API.
+NONSHARABLE_CLASS(CTestEventNotifier)
+    :public CActive
+    {
+    public: // Enumerations
+    
+    private: // Enumerations
+        // TTestEventStatus defines the status of notification
+        enum TTestEventStatus
+            {
+            ETestEventIdle,
+            ETestEventPending,
+            ETestEventCompleted,
+            ETestEventWaitUnset
+            };
+
+    public:  // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CTestEventNotifier* NewL( CTestCombiner* aTestCombiner, 
+                                         CTCTestCase* aTestCase  );
+          
+        /**
+        * Destructor.
+        */
+        ~CTestEventNotifier();
+          
+    public: // New functions     
+          
+    public: // Functions from base classes
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+          
+    protected:  // New functions
+    
+    protected:  // Functions from base classes
+    
+    private:
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestEventNotifier( CTestCombiner* aTestCombiner, 
+                            CTCTestCase* aTestCase );
+
+        /**
+        * StartL starts the CTestEventNotifier active object.
+        */
+        void StartL();
+
+    public:    //Data
+     
+    protected:  // Data
+ 
+    private:     // Data
+        // Pointer to CTestCombiner
+        CTestCombiner* iTestCombiner;
+
+        // Pointer CTestCase
+        CTCTestCase* iTestCase;
+
+        // Internal state
+        TTestEventStatus iState;
+
+        // Event interface
+        TEventIf iEvent;
+        TEventIfPckg iEventPckg;
+
+    public:      // Friend classes
+
+    protected:  // Friend classes
+
+    private:     // Friend classes
+
+    };
+
+// DESCRIPTION
+// CTestCommandNotifier is an active object used for command notify from
+// Test Module using the RTestExecution API.
+NONSHARABLE_CLASS(CTestCommandNotifier): public CActive
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+        // None
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestCommandNotifier* NewL(CTestCombiner* aTestCombiner, CTCTestCase* aTestCase);
+
+        /**
+        * Destructor.
+        */
+        ~CTestCommandNotifier();
+
+    public:     // New functions
+
+        /**
+        * StartL starts the CTestCommandNotifier active object.
+        */
+        void Start();
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError(TInt aError);
+
+    protected:      // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestCommandNotifier(CTestCombiner* aTestCombiner, CTCTestCase* aTestCase);
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to CTestCombiner
+        CTestCombiner*     iTestCombiner;
+
+        // Pointer to CTCTestCase
+        CTCTestCase*       iTestCase;
+
+        // Command to be sent
+        TCommand                        iCommand;
+        TCommandPckg                    iCommandPckg;
+        TBuf8<KMaxCommandParamsLength2> iParamsPckg;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+    };
+
+#endif // TEST_CASE_NOTIFY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/inc/TestCombiner.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,883 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* TestCombiner module of STIF Test Framework.
+*
+*/
+
+#ifndef TESTCOMBINER_H
+#define TESTCOMBINER_H
+
+//  INCLUDES
+#include <e32std.h>
+
+#include <StifParser.h>
+#include <StifLogger.h>
+#include <StifTestEventInterface.h>
+#include <StifTestModule.h>
+#include <stifinternal/TestServerClient.h>
+#include "TestKeywords.h"
+#include "TestCombinerEvent.h" 
+#include "TestCombinerUtils.h" 
+#include "STIFMeasurement.h"
+
+// CONSTANTS
+// Printing priorities
+const TInt KPrintPriExec = 400;
+const TInt KPrintPriLow  = 300;
+const TInt KPrintPriNorm = 200;
+const TInt KPrintPriHigh = 100;
+// Log dir and file
+_LIT( KTestCombinerLogDir, "\\Logs\\TestFramework\\TestCombiner\\" );
+_LIT( KTestCombinerLogFile, "TestCombiner.txt" );
+_LIT( KTestCombinerLogFileWithTitle, "TestCombiner_[%S].txt" );
+// Configuration file tags
+_LIT( KTestStartTag, "[Test]" );
+_LIT( KTestEndTag, "[Endtest]" );
+// Define tags
+_LIT( KDefineStartTag, "[Define]" );
+_LIT( KDefineEndTag, "[Enddefine]" );
+// Initialization tags
+_LIT( KInitStartTag, "[Init]" );
+_LIT( KInitEndTag, "[Endinit]" );
+_LIT( KInitRcpTimeout, "rcptimeout" );
+
+// Remote protocol timeout 
+const TInt KRemoteProtocolTimeout = 30000000;
+// Remote protocol Master id
+const TUint32 KRemoteProtocolMasterId = 0xdeadbeef;
+
+// Loop counter macro
+_LIT( KLoopCounter, "LOOP_COUNTER" );
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CTestRunner;
+class CTestCase;
+class CTCTestCase;
+class CRemoteTestCase;
+class CTCTestModule;
+class CRemoteTimer;
+class CRemoteReceiver;
+class CRemoteSendReceive;
+class TTestMeasurement;
+    
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestCombiner contains the Test Module interface of TestCombiner 
+// for STIF Test Framework
+
+NONSHARABLE_CLASS(CTestCombiner) 
+    :public CTestModuleBase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CTestCombiner* NewL();
+
+        /**
+        * Destructor.
+        */
+        ~CTestCombiner();
+
+    public: // New functions
+        /**
+        * Test Case completion from CTCTestCase.
+        */
+        void Complete( CTestCase* aTestCase, TInt aError=KErrNone );
+
+        /**
+        * Set event request pending.
+        */
+         void SetEventPendingL( TEventIf aEvent );
+
+        /**
+        * Handles timeouts.
+        */
+        void RemoteTimeout();
+
+        /**
+        * Handles responce received from slave
+        */
+        void ReceiveResponse( TDesC& aMsg );
+
+    public: // Functions from base classes
+        /**
+        * Test module initialization.
+        */ 
+        TInt InitL( TFileName& aIniFile, TBool aFirstTime );
+
+        /**
+        * GetTestCasesL is used to inquire testcases. 
+        */
+        TInt GetTestCasesL( const TFileName& aConfigFile, 
+                            RPointerArray<TTestCaseInfo>& aTestCases );
+        /**
+        * RunTestCase is used to run an individual test case specified 
+        * by aTestCase. 
+        */
+        TInt RunTestCaseL( const TInt aCaseNumber, 
+                           const TFileName& aConfig, 
+                           TTestResult& aResult );
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CTestCombiner();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * GetTestCaseL gets the specified test case section 
+        * from the configfile.
+        */
+        CStifSectionParser* GetTestCaseL( TInt aCaseNumber, 
+                                            const TFileName& aConfig );
+
+        /**
+        * RunTestL runs the testcase specified in section.
+        */
+        void RunTestL();
+      
+        /**
+        * StartTestL starts a specified testcase from another test module.
+        */
+        TInt StartTestL( CStartInfo& aStartInfo );
+
+        /**
+        * GetTestModuleL returns a specified test module description.
+        */
+        CTCTestModule* GetTestModuleL( TDesC& aModule,
+                                       TDesC& aIniFile,
+                                       const TDesC& aConfigFile  );
+
+        /**
+        * Gets a testcase identified with testid from test case array.
+        */
+        CTestCase* GetTest( TDesC& aTestId );
+     
+        /**
+        * Gets a running testcase identified with testid from test case array.
+        */
+        CTestCase* GetRunningTest( TDesC& aTestId );
+        
+        /**
+        * Gets a testcase identified with testid from test case array.
+        */
+        CTCTestCase* GetLocalTest( TDesC& aTestId );
+     
+        /**
+        * Gets a running testcase identified with testid from test case array.
+        */
+        CTCTestCase* GetLocalRunningTest( TDesC& aTestId );
+
+        /**
+        * Gets a testcase identified with aSlaveId from slave array.
+        */
+        CRemoteTestCase* GetRemoteTest( TDesC& aTestId );
+
+        /**
+        * Gets a testcase identified with aSlaveId from slave array.
+        */
+        CRemoteTestCase* GetRemoteTest( TUint32 aSlaveId );
+        
+        CRemoteTestCase* GetRemoteTestRunSent( TUint32 aSlaveId );
+        /**
+        * Gets a running testcase identified with aSlaveId from slave array.
+        */
+        CRemoteTestCase* GetRunningRemoteTest( TUint32 aSlaveId );
+
+        /**
+        * Gets a testcase running on slave with aSlaveDevId.
+        */
+        CRemoteTestCase* GetRemoteRunningTestOnSlave( TUint32 aSlaveDevId );
+
+        /**
+        * Gets a correct CRemoteSendReceive object on slave with aSlaveId.
+        */
+        CRemoteSendReceive* GetRemoteSendReceive( TUint32 aSlaveId );        
+
+        /**
+        * Get running slave.
+        */
+        CSlaveInfo* CTestCombiner::GetSlave( TUint32 aSlaveId );
+        CSlaveInfo* CTestCombiner::GetSlave( TDesC& aSlaveName );
+
+        /**
+        * Check requested events and send unset to first requested.
+        */
+        TBool UnsetEvent( TEventIf& aEvent, TRequestStatus& aStatus );
+
+        /**
+        * Read initialization from file.
+        */
+        void ReadInitializationL( const TDesC& aIniFile );
+
+        /**
+        * Executes measurement script line.
+        */
+        void ExecuteMeasurementL( CStifItemParser* aItem );
+
+        /**
+        * Starts measurement.
+        */
+        void StartMeasurementL( const TDesC& aType, CStifItemParser* aItem );
+
+        /**
+        * Stops measurementplugin's measurement.
+        */
+        void StopMeasurementL( const TDesC& aType );
+        
+        /**
+        * Returns new index for test module controller.
+        * This number is appended to module controller name.
+        * This method is used when option to run every test case in separate
+        * process is set to on.                        
+        */
+        TInt GetIndexForNewTestModuleController(void);
+       
+        /**
+        * Append to TC's result description (if possible due to length)
+        * limitation provided text in [] brackets.
+        */
+        void AppendTestResultToResultDes(TDes& aResultDescr, const TDesC& aTestCaseResultDescr);
+
+
+    public:     // Data
+        // Logger 
+        CStifLogger*                    iLog;
+
+    protected:  // Data
+          
+    private:    // Data
+        // Test case array of running/runned test cases 
+        RPointerArray<CTestCase>        iTestCases;
+
+        // SendReceive array(asynchronous sendreveive)
+        RPointerArray<CRemoteSendReceive> iSendReceive;
+
+        // Array of test modules
+        RPointerArray<CTCTestModule>    iTestModules;
+
+        // TestId of the waited (by complete keyword) test case 
+        TName                           iWaitTestCase;
+
+        // Flag to indicate that activescheduler is started    
+        TBool                           iSchedulerActive;
+
+        // Number of currently running test cases
+        TInt                            iRunningTests;
+
+        // Test case result of the TestCombiner
+        TInt                            iResult;
+
+        // Error code in case when execution of script fails
+        TInt                            iScriptFailed;
+        
+        // Error description in case when execution of script fails
+        TName                           iScriptFailedDescription;
+        
+        // Sectionparser for the current testcase
+        CStifSectionParser*             iSectionParser;
+
+        // Pointer to used testrunner
+        CTestRunner*                    iTestRunner;
+
+        // Pointer to used testrunner
+        CRemoteReceiver*                iRemoteReceiver;
+
+        // Event for async NotifyEvent
+        TEventIf                        iEvent;
+        TEventIfPckg                    iEventPckg;
+
+        RPointerArray<TEventTc>         iEventArray;
+
+         // Predefined values are listed here
+        RPointerArray<CDefinedValue>    iDefined;
+
+        // CSlaveInfo 
+        RPointerArray<CSlaveInfo>       iSlaveArray;
+
+        // Remote protocol timeout
+        TInt                            iRemoteTimeout;
+
+        // Variable for abortimmediately keyword @js
+        TBool                           iCancelIfError;
+
+        // Number of the failed test case, needed when using 
+        // abortimmediately keyword @js
+        TInt                            iFailedTestCase;
+
+        // CStifTestMeasurement object
+        RPointerArray<TTestMeasurement> iTestMeasurementArray;
+
+        // Indicate that loop is used in test case file.
+        // This is used for reseting and allowing allocated id's etc.
+        // (E.g. testid values can be same in loop).
+        TBool                           iLoopIsUsed;
+        RArray<TAny*>                   iLoopAllocationArray;
+
+        // Standard Logger 
+        CStifLogger*                    iStdLog;
+
+        // Test case Logger 
+        CStifLogger*                    iTCLog;
+
+        // Flag which says if test case title should be appended to the
+        // log file name. This is read from SettingServer
+        TBool                               iAddTestCaseTitleToLogName;
+        
+        // Counter for created TCModuleControllers
+        TInt                            iIndexTestModuleControllers;
+
+        // Is this UI testing?
+        // If yes, then Test Engine works in a specific way.
+        // It creates new process for every test scripter's test case
+        // and deletes it after test case has finished.
+        TBool                           iUITestingSupport;
+        
+        // Should every test case be executed in separate process?
+        // This option is similar to iUITestingSupport, however
+        // it does not delete the process after test case is finished.
+        TBool                           iSeparateProcesses;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+        friend class CTestRunner;
+        friend class CTestEventNotifier;
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestRunner parses the TestCombiner configuration file and 
+// runs a testcase. CTestRunner is the friend of CTestCombiner
+// and uses its private member variables directly.
+
+NONSHARABLE_CLASS(CTestRunner) 
+    :public CActive
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+        enum TRunnerState{
+            ERunnerIdle,
+            ERunnerRunning,
+            ERunnerWaitTestCase,
+            ERunnerWaitEvent,
+            ERunnerWaitUnset,
+            ERunnerWaitTimeout,
+            ERunnerCancel,
+            ERunnerError,
+            ERunnerAllocate,
+            ERunnerFree,
+            ERunnerRemote,
+            ERunnerReady,
+            };
+
+    public:  // Constructors and destructor  
+        /**
+        * Two-phased constructor.
+        */
+        static CTestRunner* NewL( CTestCombiner* aTestCombiner );
+
+        /**
+        * Destructor.
+        */
+        ~CTestRunner();
+
+    public: // New functions
+        /**
+        * Calls SetActive() from CActive.
+        */
+        void SetRunnerActive();
+
+        /**
+        * Handles received response from slave.
+        */
+        TBool ReceiveResponseL( TDesC& aMsg );
+
+        /**
+        * Cancel testcases.
+        */
+        void CancelTestCases();
+
+    public: // Functions from base classes     
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CTestRunner( CTestCombiner* aTestCombiner );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Executes one script line.
+        */
+        TBool ExecuteLineL( CStifItemParser* aItem );
+
+        /**
+        * Executes run script line.
+        */
+        TBool ExecuteRunL( CStifItemParser* aItem );
+
+        /**
+        * Parses run parameters.
+        */
+        void ParseRunParamsL( CStifItemParser* aItem, CStartInfo& aStartInfo );
+
+        /**
+        * Executes test control script line.
+        */
+        TBool ExecuteTestCtlL( CStifItemParser* aItem, 
+                               TTCKeywords::TKeywords aKeyword );
+                               
+        /**
+        * Executes pause in combiner
+        */
+        TBool ExecuteCombinerPauseL( CStifItemParser* aItem );
+
+        /**
+        * Executes pause script line.
+        */
+        TBool ExecutePauseL( CStifItemParser* aItem, CTestCase* aTestCase );
+
+        /**
+        * Executes complete script line.
+        */
+        TBool ExecuteCompleteL( CStifItemParser* aItem, CTestCase* aTestCase );
+
+        /**
+        * Executes event set script line.
+        */
+        TBool ExecuteEventSetL( CStifItemParser* aItem );
+
+        /**
+        * Executes event unset script line.
+        */
+        TBool ExecuteEventUnsetL( CStifItemParser* aItem );
+
+        /**
+        * Executes event control command.
+        */
+        TBool ExecuteEventCtlL( CStifItemParser* aItem, 
+                                TTCKeywords::TKeywords aKeyword );
+
+        /**
+        * Executes allocate script line.
+        */
+        TBool ExecuteAllocateL( CStifItemParser* aItem );
+
+        /**
+        * Executes free script line.
+        */
+        TBool ExecuteFreeL( CStifItemParser* aItem );
+
+        /**
+        * Frees slave.
+        */
+        void ExecuteFreeL( CSlaveInfo* aSlave );
+
+        /**
+        * Executes remote script line.
+        */
+        TBool ExecuteRemoteL( CStifItemParser* aItem );
+
+        /**
+        * Executes remote run script line.
+        */
+        TBool ExecuteRemoteRunL( CStifItemParser* aItem, CSlaveInfo* aSlave,
+                                 HBufC *aSetUnsetEvent = NULL,
+                                 TInt aCaseNumber = 0 );
+
+        /**
+        * Executes remote test control script line.
+        */
+        TBool ExecuteRemoteTestCtlL( CStifItemParser* aItem, 
+                                     CTestCase* aTestCase, 
+                                     TInt aCmd  );
+
+        /**
+        * Executes remote event control script line.
+        */
+        TBool ExecuteRemoteEventCtlL( CStifItemParser* aItem, 
+                                      CSlaveInfo* aSlave, 
+                                      TInt aCmd  );
+                                      
+        /**
+        * Executes remote event set unset line
+        */
+        TBool ExecuteRemoteSetUnsetEventL( CStifItemParser* aItem,
+                                      CSlaveInfo* aSlave,
+                                      TInt aCmd  );
+
+        /**
+        * Executes asynchronous remote sendreceive control script line.
+        */
+        TBool ExecuteRemoteSendReceiveL( CStifItemParser* aItem, 
+                                      CSlaveInfo* aSlave );
+
+        /**
+        * Executes remote unknown control script line.
+        */
+        TBool ExecuteRemoteUnknownL( CStifItemParser* aItem, 
+                                     CSlaveInfo* aSlave,
+                                     TDesC& aCommand );
+        /**
+        * Handles received run responses from slave.
+        */
+        TBool ReceiveResponseRunL( CStifTFwIfProt& aMsg );
+
+        /**
+        * Handles received test control responses from slave.
+        */
+        TBool ReceiveResponseTestCtlL( CStifTFwIfProt& aMsg );
+
+        /**
+        * Handles received Event system control responses from slave.
+        */
+        TBool ReceiveResponseEventCtlL( CStifTFwIfProt& aMsg );
+
+        /**
+        * Handles received asynchronous sendreceive responses from slave.
+        */
+        TBool ReceiveResponseSendReceiveL( CStifTFwIfProt& aMsg );
+
+        /**
+        * Handles received responses for unspecified commands from slave.
+        */
+        TBool ReceiveResponseUnknownL( CStifTFwIfProt& aMsg );
+
+        /**
+        * Check unset event we are waiting.
+        */
+        TBool CheckUnsetEvent();
+
+        /**
+        * Parses optional argument.
+        */
+        void ParseOptArgL( const TDesC& aOptArg, TPtrC& aArg, TPtrC& aVal);
+
+        /**
+        * Preprocess hardcoded values in test case.
+        */                    
+        CStifItemParser* PreprocessLineL( TDesC& line );
+
+        /**
+        * Checks if aWord is defined value.
+        */                    
+        TInt CheckDefined( TPtrC& aWord );
+
+        /**
+        * Handle the loop keyword operations.
+        */                    
+        void ExecuteLoopL( CStifItemParser* aItem );
+
+        /**
+        * Handle the endloop keyword operations.
+        */                    
+        TBool ExecuteEndLoopL();
+
+    public:     //Data
+
+    protected:  // Data
+
+    private:    // Data
+        // Runner state
+        TRunnerState                iState;
+
+        // Backpointer to CTestCombiner
+        CTestCombiner*              iTestCombiner;
+
+        // Event system control
+        TEventIf                    iEvent;
+
+        // Pause timer
+        RTimer                      iPauseTimer;
+        TName                       iPausedTestCase;
+        TInt                        iPauseTime;
+        
+        // Pause combiner timer
+        RTimer                      iPauseCombTimer;
+        TInt                        iPauseCombRemainingTime;
+
+        // Temporary line buffer 
+        HBufC*                      iLine;
+
+        // Remote control protocol timer
+        CRemoteTimer*               iRemoteTimer;
+
+        // Loop times, counter and start position
+        TInt                    iLoopTimes;
+        TInt                    iLoopCounter;
+        TInt                    iLoopStartPos;
+        TBuf<10>                iLoopCounterDes;
+        TInt                    iEndLoopStartPos;
+
+        // Loop passlimit (endurance) feature
+        TInt                    iPasslimit;
+        TBool                   iPasslimitEnabled;
+        TInt                    iPassedIterationCnt;
+        
+        // Loop (timed loop option)
+        TBool                   iTimedLoop;
+        TTime                   iStartTime;
+        TTimeIntervalMicroSeconds iExpectedLoopTime;
+
+		// Message displayed when leave occurs during script parsing
+		TBuf<256> iRunErrorMessage;
+    public:      // Friend classes
+
+    protected:  // Friend classes
+
+    private:     // Friend classes
+        friend class CTestCombiner;
+
+    };
+
+// CLASS DECLARATION
+typedef TBuf<0x200> TRemoteProtMsg;
+
+// DESCRIPTION
+// CTestRemoteReceiver handles remote protocol receiving
+NONSHARABLE_CLASS(CRemoteReceiver) 
+    :public CActive
+    {
+    public: // Enumerations
+         
+    private: // Enumerations
+        enum TReceiverState
+            {
+            EReceiverIdle,
+            EReceiverPending,
+            };
+
+    public:  // Constructors and destructor  
+        /**
+        * Two-phased constructor.
+        */
+        static CRemoteReceiver* NewL( CTestCombiner* aTestCombiner );
+
+        /**
+        * Destructor.
+        */
+        ~CRemoteReceiver();
+
+    public: // New functions
+        /**
+        * Calls SetActive() from CActive.
+        */
+        void Start();
+
+    public: // Functions from base classes     
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CRemoteReceiver( CTestCombiner* aTestCombiner );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:     //Data
+
+    protected:  // Data
+
+    private:    // Data
+        // Runner state
+        TReceiverState              iState;
+
+        // Backpointer to CTestCombiner
+        CTestCombiner*              iTestCombiner;
+
+        // Remote protocol message
+        TRemoteProtMsg              iRemoteMsg;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CRemoteTimer handles remote protocol timeouts
+NONSHARABLE_CLASS(CRemoteTimer) 
+    :public CActive
+    {
+    public: // Enumerations
+         
+    private: // Enumerations
+        enum TTimerState
+            {
+            ETimerIdle,
+            ETimerPending,
+            };
+
+    public:  // Constructors and destructor  
+        /**
+        * Two-phased constructor.
+        */
+        static CRemoteTimer* NewL( CTestCombiner* aTestCombiner );
+
+        /**
+        * Destructor.
+        */
+        ~CRemoteTimer();
+
+    public: // New functions
+        /**
+        * Starts timer.
+        */
+        void SetTimerActive( TTimeIntervalMicroSeconds32 anInterval );
+
+    public: // Functions from base classes     
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+    protected:  // New functions
+          
+    protected:  // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CRemoteTimer( CTestCombiner* aTestCombiner );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:     //Data
+     
+    protected:  // Data
+
+    private:    // Data
+        // Runner state
+        TTimerState     iState;
+
+        // Backpointer to CTestCombiner
+        CTestCombiner*  iTestCombiner;
+
+        // Pause timer
+        RTimer          iTimer;
+
+    public:      // Friend classes
+
+    protected:  // Friend classes
+
+    private:     // Friend classes
+
+    };
+
+
+// DESCRIPTION
+// TTestMeasurement contains test measurement module information
+class TTestMeasurement
+    {
+    public: 
+        TTestMeasurement(){ iMeasurement = NULL; };
+        ~TTestMeasurement(){ delete iMeasurement; };
+
+    public:
+
+    public:
+        // "object" name given in test case file.
+        TName                   iName;
+        // MSTIFTestInterference object.
+        CSTIFTestMeasurement*  iMeasurement;
+
+    private:
+
+    };
+
+#endif        // TESTCOMBINER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/inc/TestCombinerEvent.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the event 
+* interface.
+*
+*/
+
+#ifndef TESTCOMBINEREVENT_H
+#define TESTCOMBINEREVENT_H
+
+//  INCLUDES
+#include <StifTestEventInterface.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+class CLogger;
+class CStifLogger;
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+// Interface class for the test system.
+class TEventTc
+    :public TEventIf
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        /**
+        * C++ default constructor.
+        */
+        TEventTc( CStifLogger* aLogger );
+        
+        /**
+        * C++ parametric constructor.
+        */
+        TEventTc( TName& aEventName, CStifLogger* aLogger );
+  
+        /**
+        * C++ destructor.
+        */
+        ~TEventTc();
+
+    public: // New functions
+        
+        /**
+        * Set request status member.
+        */
+        void SetRequestStatus( TRequestStatus* aStatus );
+        
+        /**
+        * Complete request status member.
+        */
+        void Complete( TInt aError );
+
+        /**
+        * Set event pending.
+        */
+        void SetEvent( TEventType aEventType );
+        
+        /**
+        * Wait event.
+        */
+        void WaitEvent( TRequestStatus& aStatus );
+        
+    public: // Functions from base classes
+        // None
+        
+    protected:  // New functions
+        // None
+        
+    protected:  // Functions from base classes
+        // None
+        
+    private:
+        // None
+        
+    public:   //Data
+        // None
+        
+    protected:  // Data
+        // None
+        
+    private:    // Data
+        /**
+        * Request status.
+        */
+        TRequestStatus* iReq; 
+        
+        /**
+        * Logger.
+        */ 
+        CStifLogger*  iLogger;
+                        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+    };
+
+#endif      // TESTCOMBINEREVENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/inc/TestCombinerUtils.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,249 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* TestCombinerUtils.
+*
+*/
+
+#ifndef TESTCOMBINERUTILS_H
+#define TESTCOMBINERUTILS_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+#include <StifTestInterface.h>
+
+#include "TestCombinerEvent.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+    
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Testcase starting information
+NONSHARABLE_CLASS(CStartInfo)
+    :public CBase
+    {
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CStartInfo* NewL();
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CStartInfo();
+            
+    public: // New functions
+        /**
+        * Set module name.
+        */
+        void SetModuleNameL( TDesC& aModule, TInt aExtLength=0 );
+            
+        /**
+        * Set initialization file name.
+        */
+        void SetIniFileL( TDesC& aIni );
+            
+        /**
+        * Set configuration file name.
+        */
+        void SetConfigL( TDesC& aConfig );
+            
+        /**
+        * Set test identifier.
+        */
+        void SetTestIdL( TDesC& aTestId );
+
+        /**
+        * Delete module name buffer for creating new module name.
+        */
+        void DeleteModuleName();
+        
+        /**
+        * Set test case title.
+        */
+        void SetTitleL(TDesC& aTitle);
+
+        /**
+         * Sets test case arguments.
+         */
+        void SetTestCaseArgumentsL( const TDesC& aTestCaseArguments );
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CStartInfo();
+                    
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+                
+    public:
+        TPtr    iModule;
+        TPtrC   iIniFile;
+        TPtrC   iConfig;
+        TPtrC   iTestId;
+        TInt    iCaseNum;
+        TInt    iExpectedResult;
+        TFullTestResult::TCaseExecutionResult iCategory;
+        TInt    iTimeout;
+        TPtrC   iTitle;
+		TPtrC   iTestCaseArguments;
+        
+    private:
+        HBufC*  iModuleBuf;
+        HBufC*  iIniFileBuf;
+        HBufC*  iConfigBuf;
+        HBufC*  iTestIdBuf;
+        HBufC*  iTitleBuf;
+        HBufC*  iTestCaseArgumentsBuf;
+    };
+    
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Slave information structure
+NONSHARABLE_CLASS(CSlaveInfo)
+    :public CBase
+    {
+    public:
+        enum TSlaveState
+            {
+            ESlaveIdle,
+            ESlaveReserveSent,
+            ESlaveReserved,
+            ESlaveReleaseSent,
+            ESlaveReleased,
+            };        
+            
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CSlaveInfo* NewL( TDesC& aName, TUint32 aMaster );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CSlaveInfo();
+            
+    public:            
+        
+        /**
+        * Get event name requested from slave.
+        */    
+        TEventTc* GetEvent( TDesC& aEventName );
+        
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CSlaveInfo( TUint32 aMaster );
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TDesC& aName );
+        
+    public:
+        TInt    iState;
+
+        TPtrC   iName;
+        TUint32 iMasterId;
+        TUint32 iSlaveDevId;
+        
+        RPointerArray<TEventTc>         iEvents;
+        
+    private:
+        HBufC*  iNameBuf;
+        
+    };     
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Predefined value entry
+NONSHARABLE_CLASS(CDefinedValue)
+    :public CBase
+    {
+    public: // Constructors and destructor
+        /**
+        * Two-phased constructor.
+        */
+        static CDefinedValue* NewL( TDesC& aName, TDesC& aValue );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CDefinedValue();
+
+    public: // New functions
+        /**
+        * Returns define name.
+        */
+        TDesC& Name();
+        
+        /**
+        * Returns define value.
+        */
+        TDesC& Value();
+        
+        /**
+        * Returns new define value.
+        */
+        void SetValueL( TDesC& aValue );
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CDefinedValue();
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TDesC& aName, TDesC& aValue );
+        
+    private: // Data
+        // Define name
+        HBufC* iNameBuf;
+        TPtrC  iName;
+
+        // Define value
+        HBufC* iValueBuf;
+        TPtrC  iValue;
+
+    };
+    
+#endif        // TESTCOMBINERUTILS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/inc/TestKeywords.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,186 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the keywords for the TestCombiner 
+* module.
+*
+*/
+
+#ifndef TESTKEYWORDS_H
+#define TESTKEYWORDS_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <StifTestInterface.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+typedef TPtrC (*KeywordFunc)( TInt aKeyword );
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Test Combiner Keyword class
+class TTCKeywords 
+    {
+    public: // Enumerations
+        // Keyword enum
+        enum TKeywords
+            {
+            ETitle,
+            ERun,
+            ECancel,
+            EPause,
+            EResume,
+            EComplete,
+            ERequest,
+            EWait,
+            ERelease,
+            ESet,
+            EUnset,
+            ETimeout,
+            EPriority,
+            EPrint,
+            EAllocate,
+            EFree,
+            ERemote,
+            ESendReceive,
+            ECancelIfError,
+            EMeasurement,
+            ELoop,
+            EEndLoop,
+            EPauseCombiner,  
+            };
+
+        // run keyword optional arguments
+        enum TRunOptArgs
+            {
+            EExpect,
+            ETestid,
+            EIni,
+            ECategory,
+            ECaseTimeout,
+            ECaseTitle,
+            EArgs,			
+            };
+
+        // pause keyword optional arguments
+        enum TPauseOptArgs
+            {
+            ETime,
+            };
+
+        // event keywords optional arguments
+        enum TEventOptArgs
+            {
+            EState,
+            };
+
+        // priorities
+        enum TPriority
+            {
+            EPriHigh,
+            EPriNormal,
+            EPriLow,
+            };
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+    public: // Constructors and destructor
+
+    public: // New functions
+
+        /**
+        * Returns a string desrciptor corresponding to keyword number. 
+        */
+        static TPtrC Keyword( TInt aKeyword );
+
+        /**
+        * Returns a string desrciptor corresponding to run keyword 
+        * optional argument number. 
+        */
+        static TPtrC RunOptArg( TInt aArg );
+
+        /**
+        * Returns a string desrciptor corresponding to pause keyword 
+        * optional argument number. 
+        */
+        static TPtrC PauseOptArg( TInt aArg );
+
+        /**
+        * Returns a string desrciptor corresponding to event keywords 
+        * optional argument number. 
+        */
+        static TPtrC EventOptArg( TInt aArg );
+
+        /**
+        * Returns a string desrciptor corresponding to priority 
+        * enum value. 
+        */
+        static TPtrC Priority( TInt aArg );
+
+        /**
+        * Returns a keyword enum corresponding to keyword 
+        * string descriptor. 
+        */
+        static TInt Parse( TDesC& aKeyword, KeywordFunc aFunc );
+
+        /**
+        * Returns result category description. 
+        */
+        static TPtrC ResultCategory( TInt aArg );
+
+        /**
+        * Returns result category type. 
+        */
+        static TFullTestResult::TCaseExecutionResult 
+            GetResultCategory( TDesC& aCategory );
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+    public:     // Data
+     
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif        // TESTKEYWORDS_H  
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/src/StifPythonFunComb.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains StifPythonFunComb implementation.
+*
+*/
+
+
+// INCLUDE FILES
+#include "StifPythonFunComb.h"
+#include <e32svr.h>
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// GetNewIndexForThreadL
+// Function countss all threads named like pythonscripter* and returns index for
+// the new thread for pythonscripter.
+// -----------------------------------------------------------------------------
+TInt GetNewIndexForThreadL(void)
+	{
+	TInt max_index = 0;
+	// * as a wildcard for the name search
+	_LIT(KFindAll, "pythonscripter*");
+
+	// default RThread object, has a handle of the current thread
+	RThread thread;
+	TFullName fullName;
+	TFindThread finder(KFindAll);
+
+	while(finder.Next(fullName) == KErrNone)
+		{
+		max_index++;
+		}
+	return max_index;
+	}
+//
+// ============================ MEMBER FUNCTIONS ===============================
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/src/TestCase.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1207 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* CTestCase class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include "TestCombiner.h"
+#include "TestCase.h"
+#include "TestCaseNotify.h"
+#include "Logging.h"
+#include "StifPython.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iTestCombiner->iLog
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCase
+
+     Method: CTestCase
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+
+     Parameters: CTestCombiner* testCombiner: in: Backpointer to CTestCombiner
+                 TDesC& aModuleName: in: name of the used test module
+                 TDesC& aTestId: in: TestId for testcase
+                 TInt aExpectedResult: in: expected result for the testcase
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+
+CTestCase::CTestCase( CTestCombiner* testCombiner,
+                      TInt aExpectedResult,
+                      TFullTestResult::TCaseExecutionResult aCategory,
+                      TCaseType aType,
+                      CTCTestModule* aModule ): //--PYTHON
+    CActive(  CActive::EPriorityStandard ),
+    iType( aType ),
+    iTestCombiner( testCombiner ),
+    iState( ETestCaseIdle ),
+    iExpectedResult( aExpectedResult ),
+    iExpectedResultCategory( aCategory ),
+    iTestModule( aModule ) //--PYTHON
+    {
+    
+    CActiveScheduler::Add( this );   
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCase
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.     
+
+     Parameters: TDesC& aTestId: in: Test identifier
+
+     Return Values: None.
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CTestCase::ConstructL( TDesC& aTestId )
+    {
+    __ASSERT_ALWAYS( aTestId.Length() < KMaxFileName, User::Leave( KErrArgument ) );
+    iTestId = aTestId.AllocL();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCase
+
+     Method: ~CTestCase
+
+     Description: Destructor
+     
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+     
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/     
+
+CTestCase::~CTestCase()
+    {    
+
+    Cancel();    
+    delete iTestId;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCase
+
+     Method: RunL
+
+     Description: Derived from CActive. Handles the completed testcase.
+
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if completed with error. 
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CTestCase::RunL()
+    {
+    __TRACE( KMessage, ( _L("CTestCase::RunL: [%d] "), iStatus.Int() ));
+    
+    Complete( iStatus.Int() );
+
+    __TRACE( KMessage, ( _L( "CTestCase::RunL: Testcase completed" )));
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCase
+
+     Method: DoCancel
+
+     Description: Derived from CActive, handles the Cancel.
+
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCase::DoCancel()
+    {
+    __TRACE( KMessage, ( _L("CTestCase::DoCancel")));
+    
+    TRequestStatus* rs = &iStatus;
+    User::RequestComplete( rs, KErrCancel );
+    Complete( KErrCancel );
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCase
+
+     Method: Start
+
+     Description: Start progress and event notifiers and set CTestCase active.
+  
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCase::StartL()
+    {
+
+    iState = ETestCaseRunning;
+    iStatus = KRequestPending;
+    SetActive();
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCase
+
+     Method: Complete
+
+     Description: Completes testcase to CTestCombiner.
+  
+     Parameters: TInt aError: in: Completion error
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCase::Complete( TInt aError )
+    {
+
+    __TRACE( KMessage, ( _L("CTestCase::Complete: %d "), aError ));
+    iState = ETestCaseCompleted;
+    
+    iTestCombiner->Complete( this, aError );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCase
+
+     Method: IsCompletelyFinished
+
+     Description: Checks state.
+
+     Parameters: None
+
+     Return Values: TBool.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestCase::IsCompletelyFinished(void)
+    {
+    TBool result = (iState == CTestCase::ETestCaseCompleted);
+    return result;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CTCTestCase class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: CTCTestCase
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+
+     Parameters: CTestCombiner* testCombiner: in: Backpointer to CTestCombiner
+                 TDesC& aModuleName: in: name of the used test module
+                 TDesC& aTestId: in: TestId for testcase
+                 TInt aExpectedResult: in: expected result for the testcase
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+CTCTestCase::CTCTestCase( CTestCombiner* testCombiner,
+                          TInt aExpectedResult,
+                          TFullTestResult::TCaseExecutionResult aCategory,
+                          CTCTestModule* aModule ): //--PYTHON
+    CTestCase( testCombiner, aExpectedResult, aCategory, ECaseLocal, aModule ), //--PYTHON
+    iResultPckg( iResult )
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.     
+
+     Parameters: None. 
+
+     Return Values: None.
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CTCTestCase::ConstructL( TDesC& aModuleName,
+                              TDesC& aTestId,
+                              const TDesC& aTestCaseArguments )
+    {
+    __ASSERT_ALWAYS( aModuleName.Length() < KMaxFileName, User::Leave( KErrArgument ) );
+    CTestCase::ConstructL( aTestId );
+    iModuleName = aModuleName.AllocL();
+    iTestCaseArguments = aTestCaseArguments.AllocL();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+
+     Parameters: CTestCombiner* testCombiner: in: Backpointer to CTestCombiner
+
+     Return Values: CTCTestCase*: pointer to new CTCTestCase object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+CTCTestCase* CTCTestCase::NewL( CTestCombiner* testCombiner,
+                                TDesC& aModuleName,
+                                TDesC& aTestId,
+                                TInt aExpectedResult,
+                                TFullTestResult::TCaseExecutionResult aCategory,
+                                const TDesC& aTestCaseArguments,
+                                CTCTestModule* aModule ) //--PYTHON
+    {
+    CTCTestCase* self = new (ELeave) CTCTestCase( testCombiner,
+                                                   aExpectedResult,
+                                                   aCategory,
+                                                   aModule ); //--PYTHON
+     
+    CleanupStack::PushL( self );
+    self->ConstructL( aModuleName, aTestId, aTestCaseArguments );
+    CleanupStack::Pop();
+    return self;
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: ~CTCTestCase
+
+     Description: Destructor
+     
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+     
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/     
+
+CTCTestCase::~CTCTestCase()
+    {    
+    Cancel();
+    
+    delete iEvent;
+    
+    // Unset all set events
+    TInt count = iStateEventArray.Count();
+    TInt i = 0;
+    for( i = 0; i < count; i++ )
+        {
+		if( iStateEventArray[i] != NULL )
+			{
+			iStateEventArray[i]->SetType( TEventIf::EUnsetEvent );
+			}
+		if( iTestCombiner != NULL )
+			{
+			iTestCombiner->TestModuleIf().Event( *iStateEventArray[i] );
+			}
+        }
+    iStateEventArray.ResetAndDestroy();
+    iStateEventArray.Close();
+    
+    // to be sure..
+    count = iEventArray.Count();
+    TEventIf event;
+    for( i = 0; i < count; i++ )
+        {
+        event.Copy( iEventArray[i]->Event() );
+        event.SetType( TEventIf::ERelEvent );
+		if( iTestCombiner != NULL )
+			{
+			iTestCombiner->TestModuleIf().Event( event );
+			}
+        }
+
+
+    iEventArray.ResetAndDestroy();
+    iEventArray.Close();
+    
+    delete iProgress;
+    delete iModuleName;
+    delete iTestCaseArguments;
+    
+    delete iCommand;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: TestCaseArguments
+
+     Description: Get test case arguments
+
+     Parameters: None.
+
+     Return Values: Test case arguments.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTCTestCase::TestCaseArguments() const 
+    {
+    if ( iTestCaseArguments !=NULL ) 
+        {
+        return *iTestCaseArguments; 
+        }
+    return KNullDesC;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: DoCancel
+
+     Description: Derived from CActive, handles the Cancel.
+
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTCTestCase::DoCancel()
+    {
+    __TRACE( KMessage, ( _L("CTCTestCase::DoCancel")));
+    iTestExecution.CancelAsyncRequest( ETestExecutionRunTestCase );
+    Complete( KErrCancel );
+     
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: Start
+
+     Description: Start progress and event notifiers and set CTCTestCase active.
+  
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTCTestCase::StartL()
+    {
+    iProgress = CTestProgressNotifier::NewL( iTestCombiner, this );
+    iEvent = CTestEventNotifier::NewL( iTestCombiner, this );
+    iCommand = CTestCommandNotifier::NewL(iTestCombiner, this);
+    iState = ETestCaseRunning;
+    SetActive();
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: Complete
+
+     Description: Start complete the testcase to CTestCombiner (Complete2 make
+                  the final complete).
+  
+     Parameters: TInt aError: in: Completion error
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTCTestCase::Complete( TInt aError )
+    {
+    if( iState == ETestCaseRunning )
+        {
+        // Testcase is in running state, complete and delete notifiers
+        if( aError != KErrNone )
+            {
+            iResult.iTestResult.iResult = aError;
+            }
+            
+        iState = ETestCaseCompleted;
+        __TRACE( KMessage, ( _L("CTCTestCase::Complete: %d "), aError ));
+        
+        }
+
+	if( iProgress->IsPrintProgressFinished() )
+        {
+        // Print process is finished to UI => make final complete of
+        // the test case
+		Complete2();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: Complete2
+
+     Description: Testcase final complete to CTestCombiner.
+  
+     Parameters: None
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTCTestCase::Complete2()
+    {
+ 	// to be sure..
+    TInt count = iEventArray.Count();
+    TEventIf event;
+    for( TInt i = 0; i < count; i++ )
+        {
+        event.Copy( iEventArray[0]->Event() );
+        event.SetType( TEventIf::ERelEvent );
+        CTestEventNotify* eventEntry = iEventArray[0];
+        iEventArray.Remove( 0 );
+        delete eventEntry;
+        iTestCombiner->TestModuleIf().Event( event );
+        }
+      
+    iEventArray.ResetAndDestroy();
+    iEventArray.Close();
+    
+    delete iEvent;
+    iEvent = NULL;
+    delete iProgress;
+    iProgress = NULL;
+    delete iCommand;
+    iCommand = NULL;
+
+    iTestCombiner->Complete( this );
+
+    // Close execution handle
+    iTestExecution.Close();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestCase
+
+     Method: IsCompletelyFinished
+
+     Description: Checks state and progress notifier.
+
+     Parameters: None
+
+     Return Values: TBool.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CTCTestCase::IsCompletelyFinished(void)
+    {
+    TBool result = (iState == CTCTestCase::ETestCaseCompleted);
+	if(iProgress)
+	    {
+		result = result && (iProgress->IsPrintProgressFinished());
+		}
+    return result;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CRemoteTestCase class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTestCase
+
+     Method: CRemoteTestCase
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+
+     Parameters: CTestCombiner* testCombiner: in: Backpointer to CTestCombiner
+                 TInt aExpectedResult: in: expected result for the testcase
+                 TFullTestResult::TCaseExecutionResult aCategory: in: 
+                    result category
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+CRemoteTestCase::CRemoteTestCase( CTestCombiner* testCombiner,
+                          TInt aExpectedResult,
+                          TFullTestResult::TCaseExecutionResult aCategory ):
+    CTestCase( testCombiner, aExpectedResult, aCategory, ECaseRemote, NULL ), //--PYTHON
+    iRemoteState( ECaseIdle ),
+    iFreeSlave( EFalse ) 
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTestCase
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.     
+
+     Parameters: None. 
+
+     Return Values: None.
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CRemoteTestCase::ConstructL( TDesC& aTestId )
+    {
+    CTestCase::ConstructL( aTestId );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTestCase
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+
+     Parameters: CTestCombiner* testCombiner: in: Backpointer to CTestCombiner
+
+     Return Values: CRemoteTestCase*: pointer to new CRemoteTestCase object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+CRemoteTestCase* CRemoteTestCase::NewL( CTestCombiner* testCombiner,
+                                TDesC& aTestId, 
+                                TInt aExpectedResult,
+                                TFullTestResult::TCaseExecutionResult 
+                                    aCategory )
+    {
+    CRemoteTestCase* self = new (ELeave) CRemoteTestCase( testCombiner, 
+                                                   aExpectedResult,
+                                                   aCategory );
+     
+    CleanupStack::PushL( self );
+    self->ConstructL( aTestId );
+    CleanupStack::Pop();
+    return self;
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTestCase
+
+     Method: ~CRemoteTestCase
+
+     Description: Destructor
+     
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+     
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/     
+
+CRemoteTestCase::~CRemoteTestCase()
+    {        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CTCTestModule class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestModule
+
+     Method: CTCTestModule
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+
+     Parameters: TDesC& aModule: in: module name
+                 TDesC& aIni: in: inifile name
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTCTestModule::CTCTestModule( CTestCombiner* testCombiner ):
+    iTestCombiner( testCombiner )
+    {
+    iTestCases = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestModule
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.     
+
+     Parameters: TDesC& aModule: in: Module name.
+                 TDesC& aIni: in: Inifile name.
+                 const TDesC& aConfigFile: in: Test case(config) file name. 
+
+     Return Values: None.
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CTCTestModule::ConstructL( TDesC& aModule,
+                                TDesC& aIni,
+                                const TDesC& aConfigFile )
+    {
+    __TRACE( KMessage, ( _L("CTCTestModule::ConstructL [%S]"), &aModule));
+    
+    __ASSERT_ALWAYS( aModule.Length() < KMaxFileName, User::Leave( KErrArgument ) );
+    __ASSERT_ALWAYS( aIni.Length() < KMaxFileName, User::Leave( KErrArgument ) );
+    iModuleName = aModule.AllocL();
+    iIniFile = aIni.AllocL();
+    
+    TFileName ini = *iIniFile;
+    // Open handles
+    __TRACE( KMessage, ( _L("CTCTestModule: Server connect")));    
+    User::LeaveIfError( iTestServer.Connect( ModuleName(), aConfigFile ) ); 
+    __TRACE( KMessage, ( _L("CTCTestModule: Module open")));
+    User::LeaveIfError( iTestModule.Open( iTestServer, ini ) );
+    
+    iErrorPrinter = CTestErrorNotifier::NewL( iTestCombiner, this );
+  
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestModule
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+
+     Parameters: None
+     
+     Return Values: TDesC& aModule: in: Module name.
+                    TDesC& aIni: in: Inifile name.
+                    const TDesC& aConfigFile: in: Test case(config) file name.
+     
+     Errors/Exceptions: Leaves if ConstructL leaves
+                        Leaves if memory allocation fails
+                        Leaves if illegal arguments are given
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+CTCTestModule* CTCTestModule::NewL( CTestCombiner* testCombiner,
+                                    TDesC& aModule, 
+                                    TDesC& aIni,
+                                    const TDesC& aConfigFile )
+    {
+    CTCTestModule* self = new (ELeave) CTCTestModule( testCombiner );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aModule, aIni, aConfigFile );
+    CleanupStack::Pop();
+
+    return self;
+     
+    }
+
+/*
+
+-------------------------------------------------------------------------------
+
+     Class: CTCTestModule
+
+     Method: ~CTCTestModule
+
+     Description: Destructor
+     
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+     
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/     
+
+CTCTestModule::~CTCTestModule()
+    {
+    __TRACE( KMessage, ( _L("CTCTestModule::~CTCTestModule [%S]"), iModuleName));
+    
+    // delete error printer
+    delete iErrorPrinter;
+    // Close handles
+    if( iTestServer.Handle() != 0 )
+        {
+        iTestModule.Close();
+        iTestServer.Close();
+        }
+    delete iModuleName;
+    delete iIniFile;
+    delete iTestCases;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestModule
+
+     Method: GetTestCasesForCombiner
+
+     Description: Get array of test cases (used to find test case number by title)
+     
+     Parameters:    const TDesC& aConfigFile: in: config file name.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+     
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTCTestModule::GetTestCasesForCombiner(const TDesC& aConfigFile)
+    {
+    __TRACE(KMessage, (_L("Going to enumerate test cases for TestCombiner")));
+    TName configFile(aConfigFile);
+
+    // Enumerate test cases
+    TCaseCount caseCount;
+    TRequestStatus status;
+    iTestModule.EnumerateTestCases(configFile, caseCount, status);
+    User::WaitForRequest(status);
+
+    // Check that enumerate succeeded
+    if(status != KErrNone)
+        {
+        __TRACE(KMessage, (_L("Enumerating test cases from module returned error. Status %d."), status.Int()));
+        return;
+    	}
+    __TRACE(KMessage, (_L("Enumeration for TestCombiner returned %d cases"), caseCount()));
+
+    // Get test cases to buffer
+    iTestCases = CFixedFlatArray<TTestCaseInfo>::NewL(caseCount());
+
+    TInt ret = iTestModule.GetTestCases(*iTestCases);
+    if(ret != KErrNone)
+        {
+        __TRACE(KMessage, (_L("Getting test cases from module returned error %d."), ret));
+        return;
+        }
+
+    __TRACE(KMessage, (_L("Test cases for TestCombiner have been enumerated")));
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTCTestModule
+
+     Method: GetCaseNumByTitle
+
+     Description: Finds test case index by title
+
+     Parameters:    TDesC& aTitle: in: test case title.
+                    TInt& aCaseNum: in out: test case index
+
+     Return Values: KErrNone if everything is ok
+                    KErrNotFound if there is no such test case
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTCTestModule::GetCaseNumByTitle(TDesC& aTitle, TInt& aCaseNum)
+    {
+    for(TInt i = 0; i < iTestCases->Count(); i++)
+        {
+        if((*iTestCases)[i].iTitle == aTitle)
+            {
+            aCaseNum = i;
+            //TestScripter relies on 1-based indexing
+            if((iModuleName->Find(KTestScripterName) != KErrNotFound) || (iModuleName->Find(KPythonScripter) != KErrNotFound) || (iModuleName->Find(KTestCombinerName) != KErrNotFound))
+                aCaseNum++;
+            return KErrNone;
+            }
+        }
+    
+    return KErrNotFound;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CRemoteSendReceive class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteSendReceive
+
+     Method: CRemoteSendReceive
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+
+     Parameters: 
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteSendReceive::CRemoteSendReceive( CTestCombiner* aTestCombiner  ) :
+    iTestCombiner( aTestCombiner )
+    {
+    // None
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteSendReceive
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.     
+
+     Parameters: None. 
+
+     Return Values: None.
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteSendReceive::ConstructL()
+    {
+    // None
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteSendReceive
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+
+     Parameters: 
+
+     Return Values: CRemoteTestCase*: pointer to new CRemoteTestCase object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteSendReceive* CRemoteSendReceive::NewL( CTestCombiner* aTestCombiner )
+    {
+    CRemoteSendReceive* self = new (ELeave) CRemoteSendReceive( aTestCombiner );
+     
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteSendReceive
+
+     Method: ~CRemoteSendReceive
+
+     Description: Destructor
+     
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+     
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/     
+CRemoteSendReceive::~CRemoteSendReceive()
+    {
+    // None
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/src/TestCaseNotify.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1617 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestProgressNotifier class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include "TestCombiner.h"
+#include "TestCase.h"
+#include "TestCaseNotify.h"
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iTestCombiner->iLog
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: CTestProgressNotifier
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+CTestProgressNotifier::CTestProgressNotifier( CTestCombiner* aTestCombiner, 
+                                              CTCTestCase* aTestCase ) : 
+    CActive( CActive::EPriorityStandard ),
+    iTestCombiner( aTestCombiner ),
+    iTestCase( aTestCase ),
+    iState( ETestProgressIdle ),
+    iProgressPckg( iProgress ),
+    iIsPrintProcessFinished( EFalse )
+    {
+    CActiveScheduler::Add( this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: Leaves if StartL leaves
+     
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestProgressNotifier::ConstructL()
+    {
+    StartL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+     
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to TestCombiner
+                 CTCTestCase* aTestCase: in: Pointer to used CTCTestCase
+     
+     Return Values: CTestProgressNotifier* : pointer to created object
+
+     Errors/Exceptions: Leaves if ConstructL leaves or memory allocation fails
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+CTestProgressNotifier* CTestProgressNotifier::NewL( CTestCombiner* aTestCombiner, 
+                                                    CTCTestCase* aTestCase )
+    {
+    CTestProgressNotifier* self = 
+        new ( ELeave ) CTestProgressNotifier( aTestCombiner, aTestCase );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: ~CTestProgressNotifier
+
+     Description: Destructor
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/     
+CTestProgressNotifier::~CTestProgressNotifier()
+    {
+    __TRACE( KMessage, ( _L("~CTestProgressNotifier") ));
+    Cancel();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: StartL
+
+     Description: Start ProgressNotifier
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: Leaves if allready pending
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestProgressNotifier::StartL()
+    {
+    // Check that this request is not pending!!
+    if( iState == ETestProgressPending )
+        {
+        User::Leave( KErrGeneral );
+        }
+        
+    iState = ETestProgressPending;
+    iTestCase->TestExecution().NotifyProgress( iProgressPckg, iStatus );
+    SetActive();
+
+    } 
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: RunL
+
+     Description: RunL handles completed requests.
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestProgressNotifier::RunL()
+    {
+
+    iState = ETestProgressCompleted;
+
+    // Check that request was successful or completed with acceptable error
+    // KErrEof is acceptable error and it means that the test case will not
+    // send progresses anymore (because it is closed)
+    if ( KErrNone == iStatus.Int() )
+        {
+        TStifInfoName desc( iProgress.iDescription );
+
+        // Append testid if possible
+        if( ( iTestCase->TestId().Length() > 0 ) &&
+            ( desc.MaxLength() > 
+            ( desc.Length() + iTestCase->TestId().Length() + 1 ) ) )
+            {
+            desc.Append( _L("_") );
+            desc.Append( iTestCase->TestId() );
+            }
+          // Append module name if possible
+        else if( desc.MaxLength() > 
+            ( desc.Length() + iTestCase->ModuleName().Length() + 1 ) )
+            {
+            desc.Append( _L("_") );
+            desc.Append( iTestCase->ModuleName() );
+            }
+
+        // Forward printing to engine
+        iTestCombiner->TestModuleIf().Printf( iProgress.iPosition, 
+                                                desc, 
+                                                iProgress.iText );
+          
+        // Set request pending again
+        StartL();
+        }
+    else if ( KErrEof != iStatus.Int() )
+        {
+        // Leave, error will be handled in RunError
+        User::Leave( iStatus.Int() );
+        }
+	
+	if( KErrEof == iStatus.Int()  )
+		{
+        // KErrEof indicates that all print process to UI is completed.
+        iIsPrintProcessFinished = ETrue;
+		if(iTestCase->State() == CTestCase::ETestCaseCompleted )
+			{
+            // Test case is completed so do final complete.
+			iTestCase->Complete2();	
+			}
+		
+		}
+        
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: DoCancel
+
+     Description: Cancel active request
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestProgressNotifier::DoCancel()
+    {
+    switch ( iState )
+        {
+        case ETestProgressPending:
+            iTestCase->TestExecution().CancelAsyncRequest( ETestExecutionNotifyProgress );
+            break;
+        case ETestProgressIdle:
+        case ETestProgressCompleted:
+        default:
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestProgressNotifier, "CTestProgressNotifier" );
+            User::Panic( KTestProgressNotifier, KErrGeneral );
+            break;
+        }
+    iState = ETestProgressIdle;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: RunError
+
+     Description: Handle errors. Should newer come here so we return error.
+
+     Parameters: TInt aError: in: Symbian OS error: Error code
+     
+     Return Values: Symbian OS error value
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+TInt CTestProgressNotifier::RunError( TInt aError )
+    {
+    return aError;
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestProgressNotifier
+
+     Method: IsPrintProgressFinished
+
+     Description: Indicates is print process to UI finished
+
+     Parameters: None
+     
+     Return Values: TBool: ETrue indicates that print process is finished,
+     					   EFalse indicates that print process is not finished
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+TBool CTestProgressNotifier::IsPrintProgressFinished()
+    {
+    return iIsPrintProcessFinished;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     DESCRIPTION
+
+     This module contains implementation of CTestErrorNotifier class member
+     functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestErrorNotifier
+
+     Method: CTestErrorNotifier
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+CTestErrorNotifier::CTestErrorNotifier( CTestCombiner* aTestCombiner, 
+                                        CTCTestModule* aTestModule ) : 
+    CActive( CActive::EPriorityStandard ),
+    iTestCombiner( aTestCombiner ),
+    iTestModule( aTestModule ),
+    iState( ETestErrorIdle ),
+    iErrorPckg( iError )
+    {
+    CActiveScheduler::Add( this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestErrorNotifier
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: Leaves if StartL leaves
+     
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestErrorNotifier::ConstructL()
+    {
+    StartL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestErrorNotifier
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+     
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to TestCombiner
+                 CTCTestModule* aTestModule: in: Pointer to used CTCTestModule
+     
+     Return Values: CTestErrorNotifier* : pointer to created object
+
+     Errors/Exceptions: Leaves if ConstructL leaves or memory allocation fails
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+CTestErrorNotifier* CTestErrorNotifier::NewL( CTestCombiner* aTestCombiner, 
+                                              CTCTestModule* aTestModule )
+    {
+    CTestErrorNotifier* self = 
+        new ( ELeave ) CTestErrorNotifier( aTestCombiner, aTestModule );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestErrorNotifier
+
+     Method: ~CTestErrorNotifier
+
+     Description: Destructor
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/     
+CTestErrorNotifier::~CTestErrorNotifier()
+    {
+    __TRACE( KMessage, ( _L("~CTestErrorNotifier") ));
+    Cancel();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestErrorNotifier
+
+     Method: StartL
+
+     Description: Start ProgressNotifier
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: Leaves if allready pending
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestErrorNotifier::StartL()
+    {
+    // Check that this request is not pending!!
+    if( iState == ETestErrorPending )
+        {
+        User::Leave( KErrGeneral );
+        }
+        
+    iState = ETestErrorPending;
+    iTestModule->TestModule().ErrorNotification( iErrorPckg, iStatus );
+    SetActive();
+
+    } 
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestErrorNotifier
+
+     Method: RunL
+
+     Description: RunL handles completed requests.
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestErrorNotifier::RunL()
+    {
+
+    iState = ETestErrorCompleted;
+
+    // Check that request was successful or completed with acceptable error
+    // KErrEof is acceptable error and it means that the test case will not
+    // send progresses anymore (because it is closed)
+    if ( KErrNone == iStatus.Int() )
+        {
+              
+        // Forward printing to engine
+        iTestCombiner->TestModuleIf().Printf( iError.iPriority, 
+                                              iError.iModule, 
+                                              iError.iText );
+          
+        // Set request pending again
+        StartL();
+        }
+    else if ( KErrEof != iStatus.Int() )
+        {
+        // Leave, error will be handled in RunError
+        User::Leave( iStatus.Int() );
+        }
+          
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestErrorNotifier
+
+     Method: DoCancel
+
+     Description: Cancel active request
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestErrorNotifier::DoCancel()
+    {
+    switch ( iState )
+        {
+        case ETestErrorPending:
+            iTestModule->TestModule().CancelAsyncRequest( ETestModuleErrorNotification );
+            break;
+        case ETestErrorIdle:
+        case ETestErrorCompleted:
+        default:
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestErrorNotifier, "CTestErrorNotifier" );
+            User::Panic( KTestErrorNotifier, KErrGeneral );
+            break;
+        }
+    iState = ETestErrorIdle;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestErrorNotifier
+
+     Method: RunError
+
+     Description: Handle errors. Should newer come here so we return error.
+
+     Parameters: TInt aError: in: Symbian OS error: Error code
+     
+     Return Values: Symbian OS error value
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+TInt CTestErrorNotifier::RunError( TInt /*aError*/ )
+    {
+    
+    // Ignore error, stop error note forwarding
+    return KErrNone;
+     
+    }
+     
+     
+/*
+-------------------------------------------------------------------------------
+
+     DESCRIPTION
+
+     This module contains implementation of CTestEventNotify class member
+     functions. Handles requested events from test modules below.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotify
+
+     Method: CTestEventNotify
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to TestCombiner
+                 CTCTestCase* aTestCase: in: Pointer to used CTCTestCase
+                 
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+CTestEventNotify::CTestEventNotify( CTestCombiner* aTestCombiner, 
+                                    CTCTestCase* aTestCase ) : 
+    CActive( CActive::EPriorityStandard ),
+    iTestCombiner( aTestCombiner ),
+    iTestCase( aTestCase ),
+    iState( ETestEventNotifyIdle ),
+    iEventPckg( iEvent )
+    {
+    CActiveScheduler::Add( this );
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotify
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+     
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+void CTestEventNotify::ConstructL( TEventIf& aEvent )
+    {
+    iEvent.Copy( aEvent );
+    
+    iEvent.SetType( TEventIf::EWaitEvent );
+    iState = ETestEventNotifyPending;
+    iTestCombiner->TestModuleIf().Event( iEvent, iStatus );
+    SetActive();
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotify
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+     
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to TestCombiner
+                 CTCTestCase* aTestCase: in: Pointer to used CTCTestCase
+     
+     Return Values: CTestEventNotify* : pointer to created object
+
+     Errors/Exceptions: Leaves if ConstructL leaves or memory allocation fails
+     
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+CTestEventNotify* CTestEventNotify::NewL( CTestCombiner* aTestCombiner, 
+                                          CTCTestCase* aTestCase,
+                                          TEventIf& aEvent )
+    {
+    CTestEventNotify* self = 
+        new ( ELeave ) CTestEventNotify( aTestCombiner, aTestCase );
+    CleanupStack::PushL( self );
+    self->ConstructL( aEvent );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotify
+
+     Method: ~CTestEventNotify
+
+     Description: Destructor
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/     
+CTestEventNotify::~CTestEventNotify()
+    {
+    __TRACE( KMessage, ( _L("~CTestEventNotify") ));
+     
+    Cancel();
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotify
+
+     Method: RunL
+
+     Description: Handles completed event wait
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: Leaves on error.
+
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+
+void CTestEventNotify::RunL()
+    {
+    __TRACE( KMessage, ( _L("CTestEventNotify::RunL(%d): %d, %d"), 
+        this, iStatus.Int(), iState ) );
+    User::LeaveIfError( iStatus.Int() );
+
+    switch( iState )
+        {
+        case ETestEventNotifyPending:
+            {     
+            // Forward event set/unset
+            iEvent.SetType( TEventIf::ESetEvent );
+            iState = ETestEventNotifyCompleted;
+            User::LeaveIfError(
+                iTestCase->TestExecution().NotifyEvent( iEventPckg, iStatus ) );
+            SetActive();
+            }
+            break;
+        case ETestEventNotifyCompleted:
+            // Enable wait again
+            iEvent.SetType( TEventIf::ESetWaitPending );
+            iState = ETestEventNotifyPending;
+            iTestCombiner->TestModuleIf().Event( iEvent, iStatus );
+            SetActive();
+            break;
+        default:          
+            User::LeaveIfError( KErrGeneral );
+            break;
+        }
+    __TRACE( KMessage, ( _L("CTestEventNotify::RunL(%d) done: %d"), 
+        this, iState ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotify
+
+     Method: DoCancel
+
+     Description: Handle Cancel
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+     
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+
+void CTestEventNotify::DoCancel()
+    {
+    __TRACE( KMessage, ( _L("CTestEventNotify::DoCancel")));
+ 
+    _LIT( KTestEventNotify, "CTestEventNotify" );
+    switch ( iState )
+        {
+        case ETestEventNotifyPending:
+            {
+            TInt ret = 
+                iTestCombiner->TestModuleIf().CancelEvent( iEvent, &iStatus );
+            if( ret != KErrNone )
+                {
+                __TRACE( KMessage, ( _L("CTestEventNotify::DoCancel(%d) not pending: %d"), 
+                    this, ret ) );
+                }
+            }
+            break;
+        case ETestEventNotifyCompleted:            
+            iTestCase->TestExecution().
+                CancelAsyncRequest( ETestExecutionNotifyEvent );
+            break;
+        case ETestEventNotifyIdle:
+        default:
+            // DoCancel called in wrong state => Panic
+            User::Panic( KTestEventNotify, KErrGeneral );
+            break;
+        }
+     
+    iState = ETestEventNotifyIdle;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotify
+
+     Method: RunError
+
+     Description: Handle error. Should newer come here so we return error.
+
+     Parameters: TInt aError: in: error from CActive
+     
+     Return Values: Symbian OS error value
+     
+     Errors/Exceptions: None
+     
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+
+TInt CTestEventNotify::RunError( TInt aError )
+    {
+    __TRACE( KMessage, ( _L("CTestEventNotify::RunError")));
+ 
+    return aError;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     DESCRIPTION
+
+     This module contains implementation of CTestEventNotifier class member
+     functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotifier
+
+     Method: CTestEventNotifier
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to TestCombiner
+                 CTCTestCase* aTestCase: in: Pointer to used CTCTestCase
+                 
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+CTestEventNotifier::CTestEventNotifier( CTestCombiner* aTestCombiner, 
+                                        CTCTestCase* aTestCase ) : 
+    CActive( CActive::EPriorityStandard ),
+    iTestCombiner( aTestCombiner ),
+    iTestCase( aTestCase ),
+    iState( ETestEventIdle ),
+    iEventPckg( iEvent )
+    {
+    CActiveScheduler::Add( this );
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotifier
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+     
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+void CTestEventNotifier::ConstructL( )
+    {
+    StartL();
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotifier
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+     
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to TestCombiner
+                 CTCTestCase* aTestCase: in: Pointer to used CTCTestCase
+     
+     Return Values: CTestEventNotifier* : pointer to created object
+
+     Errors/Exceptions: Leaves if ConstructL leaves or memory allocation fails
+     
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+CTestEventNotifier* CTestEventNotifier::NewL( CTestCombiner* aTestCombiner, 
+                                              CTCTestCase* aTestCase  )
+    {
+    CTestEventNotifier* self = 
+        new ( ELeave ) CTestEventNotifier( aTestCombiner, aTestCase );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotifier
+
+     Method: ~CTestEventNotifier
+
+     Description: Destructor
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/     
+CTestEventNotifier::~CTestEventNotifier()
+    {
+    __TRACE( KMessage, ( _L("~CTestEventNotifier") ));
+     
+    
+     
+    Cancel();
+     
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotifier
+
+     Method: StartL
+
+     Description: Start active object
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: Leave if already pending
+
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+void CTestEventNotifier::StartL()
+    {
+    // Check that this request is not pending!!
+    if( iState == ETestEventPending )
+        {
+        User::Leave( KErrGeneral );
+        }
+        
+    iEvent.SetType( TEventIf::EEnable );
+    iState = ETestEventPending;
+    __TRACE( KMessage, ( _L("Set event pending %d"), this ) );
+    iTestCase->TestExecution().NotifyEvent( iEventPckg, iStatus );
+    SetActive();
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotifier
+
+     Method: RunL
+
+     Description: Handles completed event request
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: Leaves on error.
+
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+
+void CTestEventNotifier::RunL()
+    {
+    __TRACE( KMessage, ( _L("CTestEventNotifier::RunL(%d): %d, %d"), 
+        this, iStatus.Int(), iState ) );
+
+    User::LeaveIfError( iStatus.Int() );
+    
+    switch( iState )
+        {
+        case ETestEventPending:
+        case ETestEventWaitUnset:
+            {  
+            iState = ETestEventCompleted;
+            
+            switch( iEvent.Type() )
+                {
+                case TEventIf::ERelEvent:
+                    {
+                    // Remove from requested events list
+                    TInt count = iTestCase->EventArray().Count();
+                    TInt ind = 0;
+                    for( ; ind < count; ind++)
+                        { 
+                          if( iTestCase->EventArray()[ind]->Event().Name() == iEvent.Name() )
+                              {
+                              __RDEBUG( ( _L("TC CTestEventNotifier(RelEvent) %S"), 
+                                  &iEvent.Name() ));
+                              CTestEventNotify* event = iTestCase->EventArray()[ind];
+                              iTestCase->EventArray().Remove( ind );
+                              delete event;
+                              break;
+                              }
+                          }
+                    if( ind == count )
+                        {
+                        User::Leave( KErrNotFound );
+                        }
+                    }
+                    break; 
+                case TEventIf::EUnsetEvent:
+                    {
+                    __RDEBUG( ( _L("TC CTestEventNotifier(UnsetEvent) %S"), 
+                                  &iEvent.Name() ));
+                    TInt count = iTestCase->StateEventArray().Count();
+                    for( TInt i=0; i<count; i++ )
+                        {
+                        if( iTestCase->StateEventArray()[i]->Name() == iEvent.Name() )
+                            {
+                            TEventIf* event = iTestCase->StateEventArray()[i];
+                            iTestCase->StateEventArray().Remove(i);
+                            delete event;
+                            break;
+                            }
+                        }
+                                  
+                    if( iTestCombiner->UnsetEvent( iEvent, iStatus ) )
+                        {
+                         // Event request is pending from modules below test 
+                         // combiner, stay waiting
+                        iState = ETestEventWaitUnset;
+                        // Wait for unset to complete 
+                        SetActive();
+                        return;
+                        }
+                    }
+                    break;
+                case TEventIf::EReqEvent:
+                    // Do nothing
+                    __RDEBUG( ( _L("TC CTestEventNotifier(ReqEvent) %S"), 
+                                  &iEvent.Name() ));
+                    break;
+                case TEventIf::ESetEvent: 
+                    // Do nothing
+                    __RDEBUG( ( _L("TC CTestEventNotifier(SetEvent) %S"), 
+                                  &iEvent.Name() ));
+                    break;
+                default:
+                    User::Leave( KErrArgument );
+                    break;
+                }   
+                            
+            // Forward event request
+            iTestCombiner->TestModuleIf().Event( iEvent, iStatus );
+            SetActive();
+            
+            }
+            break;
+        case ETestEventCompleted:
+            __RDEBUG( ( _L("TC CTestEventNotifier(Complete)")));
+            switch( iEvent.Type() )
+                {
+                case TEventIf::EReqEvent:
+                    {
+                    // Store requested events
+                    CTestEventNotify* event = 
+                        CTestEventNotify::NewL( iTestCombiner, iTestCase, iEvent );
+                    CleanupStack::PushL( event ); 
+                    User::LeaveIfError( iTestCase->EventArray().Append( event ) );
+                    CleanupStack::Pop( event ); 
+                    }
+                    break;
+                case TEventIf::ESetEvent: 
+                    if( iEvent.EventType() == TEventIf::EState )
+                        {
+                        TEventIf* event = new( ELeave )TEventIf;
+                        CleanupStack::PushL( event );
+                        event->Copy( iEvent );
+                        User::LeaveIfError( iTestCase->StateEventArray().Append( event ) ); 
+                        CleanupStack::Pop( event );
+                        }
+                    break;
+                case TEventIf::ERelEvent: 
+                case TEventIf::EUnsetEvent:
+                    // Do nothing
+                    break;
+                default:
+                    User::Leave( KErrArgument );
+                    break;
+                }
+       
+            // Enable request again
+            StartL();
+            break;
+        default:          
+            User::LeaveIfError( KErrGeneral );
+            break;
+        }
+    __TRACE( KMessage, ( _L("CTestEventNotifier::RunL(%d) done: %d"), 
+        this, iState ) );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotifier
+
+     Method: DoCancel
+
+     Description: Handle Cancel
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+     
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+
+void CTestEventNotifier::DoCancel()
+    {
+    __TRACE( KMessage, ( _L("CTestEventNotifier::DoCancel")));
+    _LIT( KTestEventNotifier, "CTestEventNotifier" );
+    
+    switch ( iState )
+        {
+        case ETestEventPending:
+            iTestCase->TestExecution().
+                CancelAsyncRequest( ETestExecutionNotifyEvent );
+            break;
+        case ETestEventCompleted:            
+            {
+            TInt ret = iTestCombiner->TestModuleIf().CancelEvent( iEvent, &iStatus );
+            if( ret != KErrNone )
+                {
+                __TRACE( KMessage, ( _L("CTestEventNotifier::DoCancel(%d) not pending: %d"), 
+                    this, ret ) );
+                }
+            }
+			User::WaitForRequest( iStatus );
+            break;
+        case ETestEventIdle:
+        default:
+            // DoCancel called in wrong state => Panic
+            User::Panic( KTestEventNotifier, KErrGeneral );
+            break;
+        }
+     
+    iState = ETestEventIdle;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestEventNotifier
+
+     Method: RunError
+
+     Description: Handle error. Should newer come here so we return error.
+
+     Parameters: TInt aError: in: error from CActive
+     
+     Return Values: Symbian OS error value
+     
+     Errors/Exceptions: None
+     
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+
+TInt CTestEventNotifier::RunError( TInt aError )
+    {
+    __TRACE( KMessage, ( _L("CTestEventNotifier::RunError")));
+    
+     switch( iState )
+        {
+        case ETestEventPending:
+        case ETestEventWaitUnset:
+            // Either the event request is cancelled or some 
+            // unknown error occurred. We go idle state.
+            iState = ETestEventIdle;
+            break;
+        
+        case ETestEventCompleted:
+            // Error in event command, forward it to the test module
+            iEvent.SetType( TEventIf::EEnable );
+            iState = ETestEventPending;
+            __TRACE( KMessage, ( _L("Cmd error %d"), this ) );
+            iTestCase->TestExecution().NotifyEvent( iEventPckg, iStatus, aError );
+            SetActive();
+            break;
+        default:          
+            __TRACE( KMessage, ( _L("Illegal state %d"), this ) );
+            return aError;
+        }
+     
+    return KErrNone;
+    
+    }
+    
+// ================= MEMBER FUNCTIONS =========================================
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: CTestCommandNotifier
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: CTestCombiner* aTestCombiner: in: Pointer to TestCombiner
+                CTCTestCase* aTestCase: in: Pointer to test case
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCommandNotifier::CTestCommandNotifier(CTestCombiner* aTestCombiner, 
+                                           CTCTestCase* aTestCase):
+    CActive(CActive::EPriorityStandard),
+    iTestCombiner(aTestCombiner),
+    iTestCase(aTestCase),
+    iCommandPckg(iCommand)
+    {
+    CActiveScheduler::Add(this);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCommandNotifier::ConstructL( )
+    {
+    __TRACE(KMessage, (_L("CTestCommandNotifier::ConstructL (combiner)")));
+    Start();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestCombiner* aTestCombiner: in: Pointer to TestCombiner
+                CTCTestCase* aTestCase: in: Pointer to test case
+
+    Return Values: CTestCommandNotifier* : pointer to created object
+
+    Errors/Exceptions: Leaves if construction of CTestCommandNotifier fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCommandNotifier* CTestCommandNotifier::NewL(CTestCombiner* aTestCombiner, 
+                                                 CTCTestCase* aTestCase)
+    {
+    CTestCommandNotifier* self = new (ELeave) CTestCommandNotifier(aTestCombiner, aTestCase);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: ~CTestCommandNotifier
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCommandNotifier::~CTestCommandNotifier()
+    {
+    __TRACE(KMessage, (_L("CTestEventNotifier::~CTestEventNotifier (combiner)")));
+    Cancel();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: StartL
+
+    Description: Start active object
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCommandNotifier::Start()
+    {
+    __TRACE(KMessage, (_L("CTestEventNotifier::StartL (combiner)")));
+
+    iTestCase->TestExecution().NotifyCommand2(iCommandPckg, iParamsPckg, iStatus, KErrNone);
+    SetActive();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone
+                       Leaves if iState is not ETestEventPending
+                       Leaves if some leaving method called here leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCommandNotifier::RunL()
+    {
+    __TRACE(KMessage, (_L("CTestCommandNotifier::RunL (combiner): iStatus=[%d]"), iStatus.Int()));
+
+    User::LeaveIfError(iStatus.Int());
+
+    switch(iCommand)
+        {
+        case EStopExecution:
+            {
+            __TRACE(KMessage, (_L("CTestCommandNotifier::RunL (combiner): StopExecution command received")));
+            TStopExecutionCommandParams par;
+            TStopExecutionCommandParamsPckg parPack(par);
+            parPack.Copy(iParamsPckg);
+            __TRACE(KMessage, (_L("CTestCommandNotifier::RunL(combiner): propagating stop execution [%d][%d]"), par.iType, par.iCode));
+            iTestCombiner->TestModuleIf().StopExecution(par.iType, par.iCode);
+            }
+            break;
+
+        case ESendTestModuleVersion:
+            {
+            __TRACE(KMessage, (_L("CTestCommandNotifier::RunL (combiner): SendTestModuleVersion command received")));
+            TSendTestModuleVesionCommandParams params;
+            TSendTestModuleVesionCommandParamsPckg paramsPack(params);
+            paramsPack.Copy(iParamsPckg);
+
+            __TRACE(KMessage, (_L("CTestCommandNotifier::RunL(combiner): propagating module version [%d][%d][%d][%S]"), params.iMajor, params.iMinor, params.iBuild, &params.iTestModuleName));
+            TVersion moduleVersion(params.iMajor, params.iMinor, params.iBuild);
+            
+            TBool newVersionOfMethod = ETrue;
+            iTestCombiner->TestModuleIf().SendTestModuleVersion(moduleVersion, params.iTestModuleName, newVersionOfMethod);
+            }
+            break;
+
+        default:
+            __TRACE(KError, (_L("CTestCommandNotifier::RunL (combiner): Unknown command [%d]."), iCommand));
+        }
+
+    // Set request again
+    Start();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCommandNotifier::DoCancel()
+    {
+    __TRACE(KMessage, (_L( "CTestEventNotifier::DoCancel (combiner)")));
+
+    iTestCase->TestExecution().CancelAsyncRequest(ETestExecutionNotifyCommand);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: RunError
+
+    Description: Handle errors.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCommandNotifier::RunError(TInt aError)
+    {
+    __TRACE(KError, (CStifLogger::ERed, _L("CTestCommandNotifier::RunError %d (combiner)"), aError));
+    return KErrNone;
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/src/TestCombiner.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,6619 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* CTestCombiner class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestEventInterface.h>
+#include <StifLogger.h>
+#include "TestCombiner.h"
+#include "TestKeywords.h"
+#include "TestCase.h"
+#include "TestCombinerEvent.h"
+#include "Logging.h"
+//--PYTHON-- begin
+#include "StifPython.h"
+#include "StifPythonFunComb.h"
+//--PYTHON-- end
+#include "SettingServerClient.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+_LIT( KTestRunner, "CTestRunner" );
+_LIT( KRemoteTimer, "CRemoteTimer" );
+_LIT( KRemoteReceiver, "CRemoteReceiver" );
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iLog
+
+// LOCAL CONSTANTS AND MACROS
+_LIT(KTitle, "title");
+_LIT(KTimeout, "timeout");
+_LIT(KPriority, "priority");
+
+//printing macros
+ _LIT( KExecute, "Execute");
+ 
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: CTestCombiner
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTestCombiner::CTestCombiner(): 
+    iSchedulerActive( EFalse ),
+    iRunningTests( 0 ), 
+    iResult( KErrNone ),
+    iEventPckg( iEvent ),
+    iRemoteTimeout( KRemoteProtocolTimeout ),
+    iCancelIfError( EFalse ),
+    iFailedTestCase( 0 ),
+    iLoopIsUsed( EFalse )
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::ConstructL()
+    {
+    // TRAPed to avoid crashing if logfile creation fails,
+    // so we can run test without logging to file
+    TRAPD( err, iStdLog = CStifLogger::NewL( KTestCombinerLogDir, 
+                                      KTestCombinerLogFile );
+        );
+    if( err != KErrNone )
+        {
+        iStdLog = NULL;
+        __RDEBUG( (_L("Creating logfile failed") ) );
+        }  
+    iLog = iStdLog;
+
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+
+    // Get engine settings
+    TEngineSettings engineSettings;
+    ret = settingServer.GetEngineSettings(engineSettings);
+    if(ret != KErrNone)
+        {
+        __TRACE(KError, (_L("Could not retrieve engine settings from SettingServer [%d]"), ret));
+        iUITestingSupport = EFalse;
+        iSeparateProcesses = EFalse;
+        }
+        else
+        {
+        iUITestingSupport = engineSettings.iUITestingSupport;
+        iSeparateProcesses = engineSettings.iSeparateProcesses;
+        __TRACE(KMessage, (_L("Engine settings retrieved from SettingServer. UITestingSupport [%d] SeparateProcesses [%d]"), iUITestingSupport, iSeparateProcesses));
+        }
+
+    // Close Setting server session
+    settingServer.Close();
+    iAddTestCaseTitleToLogName = loggerSettings.iAddTestCaseTitle;
+
+    iIndexTestModuleControllers = 1;
+    
+    __TRACE( KPrint, ( _L("New TestCombiner") ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters:    None
+
+     Return Values: CTestCombiner*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTestCombiner* CTestCombiner::NewL()
+    {
+     
+    CTestCombiner* self = new (ELeave) CTestCombiner();
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: ~CTestCombiner
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTestCombiner::~CTestCombiner()
+    {
+    iLoopAllocationArray.Reset();
+    iLoopAllocationArray.Close();
+    iLoopIsUsed = EFalse;
+
+    iTestCases.ResetAndDestroy();
+    iTestModules.ResetAndDestroy();
+    iEventArray.ResetAndDestroy();
+    iSlaveArray.ResetAndDestroy();
+    iSendReceive.ResetAndDestroy();
+
+    iTestCases.Close();
+    iTestModules.Close();
+    iEventArray.Close();
+    iSlaveArray.Close();
+    iSendReceive.Close();
+
+    // Stop all remaining measurement modules
+    const TInt count_meas = iTestMeasurementArray.Count();
+    for( TInt b = 0; b < count_meas; b++ )
+        {
+        iTestMeasurementArray[b]->iMeasurement->Stop();
+        }
+    iTestMeasurementArray.ResetAndDestroy();
+    iTestMeasurementArray.Close();
+
+    delete iSectionParser;
+    delete iRemoteReceiver;
+    delete iTestRunner;
+
+    iLog = NULL;
+    delete iStdLog;
+    iStdLog = NULL;
+    delete iTCLog;
+    iTCLog = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: InitL
+
+     Description: InitL is used to initialize the Test Module.
+
+     Parameters: const TFileName& aIniFile: in: Initialization file
+                 TBool aFirstTime: in: First time flag 
+
+     Return Values: Symbian OS error code
+
+     Errors/Exceptions: Leaves if ReadInitializationL leaves
+
+     Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCombiner::InitL( TFileName& aIniFile, 
+                           TBool /*aFirstTime*/ )
+    {
+
+    __TRACEFUNC();
+
+    if( aIniFile.Length() > 0 )
+        {
+        // Read initialization from test case file
+        ReadInitializationL( aIniFile );
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetTestCases
+
+     Description: GetTestCases is used to inquired test cases
+
+     Parameters:    const TFileName& aConfigFile: in: Config file name
+                    RPointerArray<RTestEngine::TTestCaseInfo>& aTestCases: out: 
+                          Array of TestCases 
+
+     Return Values: KErrNone: Success
+                    KErrNotFound: Testcases not found
+
+     Errors/Exceptions: Leaves if CStifParser::NewL leaves
+                        Leaves if CStifParser::SectionL leaves
+                        Leaves if CStifParser::NextSectionL leaves
+                        Leaves if memory allocation fails
+
+     Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCombiner::GetTestCasesL( const TFileName& aConfigFile, 
+                                   RPointerArray<TTestCaseInfo>& aTestCases )
+    {
+    __TRACEFUNC();
+
+    if( aConfigFile.Length() == 0 )
+        {
+        __TRACE( KError, (_L("No test case script file given") ) );
+        __RDEBUG( (_L("No test case script file given") ) );
+        return KErrNotFound;
+        }
+
+    CStifParser* parser = NULL;
+    TRAPD( err, parser = 
+        CStifParser::NewL( _L(""), aConfigFile, CStifParser::ECStyleComments ) );
+    if( err != KErrNone )
+        {
+        __TRACE( KError, (_L("Test case script file not found") ) );
+        __RDEBUG( (_L("Test case script file not found") ) );
+        return KErrNotFound;
+        }
+    CleanupStack::PushL( parser );
+    CStifSectionParser* section;
+    TPtrC tmp;
+    TInt index = 0;
+    TInt ret = KErrNone;
+
+    section = parser->SectionL( KTestStartTag, KTestEndTag );
+    if( section == NULL )
+        {
+        ret = KErrNotFound;
+        }
+    else
+        {    
+        while( section )
+            {
+            CleanupStack::PushL( section );
+             
+            if( section->GetLine( KTitle,  tmp, ENoTag ) == KErrNone )
+                 {
+                 if( tmp.Length() > KMaxName )
+                    {
+                    tmp.Set( tmp.Left( KMaxName ) );
+                    }                    
+                 TTestCaseInfo* tc = new ( ELeave ) TTestCaseInfo();
+                 CleanupStack::PushL( tc );
+                 __TRACE( KVerbose, (_L("TestCase: %S"), &tmp));
+                 tc->iTitle.Copy( tmp );
+                 tc->iCaseNumber = ++index;
+                 CStifItemParser* item = section->GetItemLineL( KTimeout );
+                 if( item )
+                    {
+                    TInt timeout; // In milliseconds
+                    ret = item->GetInt( KTimeout, timeout ); 
+                    if( ret != KErrNone )
+                        {
+                        __TRACE( KError, (_L("Illegal timeout")));
+                        User::Leave( ret ); 
+                        }
+                    tc->iTimeout = (TInt64)timeout*1000;
+                    __TRACE( KMessage, (_L("Timeout: %i"), tc->iTimeout.Int64() ));
+                    }
+                 item = section->GetItemLineL( KPriority );
+                 if( item )
+                    {
+                    ret = item->GetInt( KPriority, tc->iPriority ); 
+                    if( ret != KErrNone )
+                        {
+                        TPtrC priority;
+                        ret = item->GetString( KPriority, priority );
+                        if( ret != KErrNone )
+                            {
+                            __TRACE( KError, (_L("Illegal priority")));
+                            User::Leave( ret ); 
+                            }
+                        switch( TTCKeywords::Parse( priority, 
+                                                    TTCKeywords::Priority ) )
+                            {
+                            case TTCKeywords::EPriHigh:
+                                tc->iPriority = TTestCaseInfo::EPriorityHigh;
+                                break;
+                            case TTCKeywords::EPriNormal:
+                                tc->iPriority = TTestCaseInfo::EPriorityNormal;
+                                break;
+                            case TTCKeywords::EPriLow:
+                                tc->iPriority = TTestCaseInfo::EPriorityLow;
+                                break;
+                            default:
+                                __TRACE( KError, (_L("Illegal priority")));
+                                User::Leave( KErrArgument ); 
+                            }
+                        }
+                    __TRACE( KMessage, (_L("Priority: %i"), tc->iPriority ));
+                    }
+
+                 aTestCases.Append(tc);
+                 CleanupStack::Pop( tc );
+                 }
+            CleanupStack::PopAndDestroy( section );
+            section = parser->NextSectionL( KTestStartTag, KTestEndTag );
+            }
+        }
+
+    CleanupStack::PopAndDestroy( parser );
+
+    __TRACE( KPrint, (  _L( "Configfile '%S', testcases %d" ),
+        &aConfigFile, index ));
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: RunTestCaseL
+
+     Description: Run a specified testcase.
+
+     RunTestCaseL is used to run an individual test case specified 
+     by aTestCase. 
+
+     Parameters:    const TInt aCaseNumber: in: Testcase number 
+                    const TFileName& aConfig: in: Configuration file name
+                    TTestResult& aResult: out; test case result
+
+     Return Values: KErrNone: Test case started succesfully.
+                    KErrNotFound: Testcase not found
+                    KErrUnknown: Unknown TestCombiner error
+                    Any other SymbianOS error
+
+     Errors/Exceptions: Leaves if GetTestCaseL leaves
+                        Leaves if RunTestL leaves
+                        Leaves if memory allocation fails
+
+     Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCombiner::RunTestCaseL( const TInt aCaseNumber, 
+                                  const TFileName& aConfig, 
+                                  TTestResult& aResult )
+    {
+    __TRACEFUNC();
+
+    __TRACE( KMessage, (_L("***Testcase started***")));
+
+    //Open new log file with test case title in file name
+    if(iAddTestCaseTitleToLogName)
+        {
+        //Close test case log if exists
+        if(iTCLog)
+            {
+            delete iTCLog;
+            iTCLog = NULL;
+            }
+        TFileName logFileName;
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        
+        logFileName.Format(KTestCombinerLogFileWithTitle, &title);
+        iTCLog = CStifLogger::NewL(KTestCombinerLogDir, logFileName);
+        iLog = iTCLog;
+        }
+
+    /* 
+    * Allow memory leaks, because Defines are leaved untouched 
+    * after test case execution. Real memory leaks are detected with 
+    * UHEAP macros.
+    */
+    TestModuleIf().SetBehavior( CTestModuleIf::ETestLeaksMem );
+
+    // Read initialization from test case file
+    ReadInitializationL( aConfig );
+
+    __UHEAP_MARK;
+        
+    iSectionParser = GetTestCaseL( aCaseNumber, aConfig );
+
+    // Check parsing result
+    if( iSectionParser == NULL )
+        {
+        __TRACE( KError, (_L("***Parsing testcase failed***")));
+        __UHEAP_MARKEND;
+        return KErrNotFound;
+        }
+
+    CActiveScheduler* activeScheduler = 
+        new ( ELeave ) CActiveScheduler();
+    CleanupStack::PushL( activeScheduler );
+    CActiveScheduler::Install( activeScheduler );
+
+    // Resetting these variables to normal state @js             
+    iFailedTestCase = 0;    
+    iCancelIfError = EFalse;
+    iScriptFailed = KErrNone;
+    iScriptFailedDescription.Copy(KNullDesC);
+
+    // Run the given testcase described in iSectionParser section
+    RunTestL();
+
+    CleanupStack::PopAndDestroy( activeScheduler );
+
+    delete iSectionParser;
+    iSectionParser = NULL;
+
+    TInt ret = KErrNone;
+    // Check if test case starting failed
+    if( iResult != KErrNone )
+        {
+        TestModuleIf().Printf( KPrintPriHigh, _L("Result"), _L("Starting FAILED"));
+         __TRACE( KError, (_L("***Starting testcase FAILED***")));
+        ret = iResult;
+        aResult.iResult = -2;
+        aResult.iResultDes = _L("Testcase script execution failed");
+        }
+    else if(iScriptFailed != KErrNone)
+        {
+        TestModuleIf().Printf( KPrintPriHigh, _L("Result"), _L("Script execution FAILED"));
+        __TRACE( KError, (_L("***Sscript execution FAILED***")));
+        aResult.iResult = iScriptFailed;
+        if(iScriptFailedDescription != KNullDesC)
+            {
+            aResult.iResultDes.Copy(iScriptFailedDescription);
+            }
+        else
+            {
+            aResult.iResultDes = _L("Testcase script execution failed");
+            }
+        }
+    else
+        {
+        __TRACE( KPrint, (_L("***Testcase completed***")));
+              
+        // Testcombiner succeeded to start all testcases, 
+        // check individual testcase results
+        TInt count = iTestCases.Count();
+        TInt i = iFailedTestCase;
+        // iFailedTestCase is either 0 or the number of failed test case if 
+        // canceliferror was given and a test case has failed
+
+        for(; i < count; i++ )
+            {
+            // All cases should be completed now
+            if( iTestCases[i]->State() != CTCTestCase::ETestCaseCompleted )
+                {
+                // This is some unknown internal TestCombiner error
+                // Should not happen
+                __TRACE( KError, (_L("TestCase (%S) not completed"), 
+                    &iTestCases[i]->TestId() ));
+                ret = KErrUnknown;
+                break;
+                }
+
+            // Interpret execution result type from returned result
+            TInt executionResult = TFullTestResult::ECaseExecuted; // Ok
+            if( iTestCases[i]->iResult.iCaseExecutionResultType >= 
+                TFullTestResult::ECaseLeave )
+                {
+                // Some abnormal execution result type
+                executionResult = iTestCases[i]->iResult.iCaseExecutionResultType;
+                }
+
+            // Check expected execution result type
+            if( executionResult != iTestCases[i]->ExpectedResultCategory() ) 
+                {
+                // expected and returned result types differ
+                aResult.iResult = KErrGeneral;
+                aResult.iResultDes.Copy( _L("Test case completed with ") );
+                aResult.iResultDes.Append( 
+                    TTCKeywords::ResultCategory( 
+                    iTestCases[i]->iResult.iCaseExecutionResultType ));
+                aResult.iResultDes.Append( _L(" and expected was ") );
+                aResult.iResultDes.Append( 
+                    TTCKeywords::ResultCategory( 
+                    iTestCases[i]->ExpectedResultCategory() ));
+                AppendTestResultToResultDes(aResult.iResultDes, iTestCases[i]->iResult.iTestResult.iResultDes);
+                __TRACE( KPrint, ( _L( "%S"), &aResult.iResultDes ) );
+                break;
+                }
+
+            // Check normal test result
+            if( iTestCases[i]->ExpectedResultCategory() == 
+                TFullTestResult:: ECaseExecuted )
+                {
+                // Normal completion, check result
+                if( iTestCases[i]->iResult.iTestResult.iResult != 
+                      iTestCases[i]->ExpectedResult() )
+                    {
+                     __TRACE( KPrint, ( _L( "Test failed, expect(%d) != result(%d)"), 
+                         iTestCases[i]->ExpectedResult(),
+                         iTestCases[i]->iResult.iTestResult.iResult ));
+                    // We return the first error result as aResult
+                    if( iTestCases[i]->iResult.iTestResult.iResult != KErrNone )
+                        {
+                        aResult = iTestCases[i]->iResult.iTestResult;
+                        }
+                    else
+                        {
+                        aResult.iResult = KErrGeneral;
+                        aResult.iResultDes.Copy( _L("Test case completed with KErrNone and expected "));
+                        aResult.iResultDes.AppendNum( iTestCases[i]->ExpectedResult() );
+                        AppendTestResultToResultDes(aResult.iResultDes, iTestCases[i]->iResult.iTestResult.iResultDes);
+                        }
+                    break;
+                    }
+                }
+            else 
+                {
+                // Abnormal completion, i.e. panic, leave, exception or timeout
+                if( iTestCases[i]->iResult.iCaseExecutionResultCode != 
+                      iTestCases[i]->ExpectedResult() )
+                    {
+                    __TRACE( KPrint, ( _L( "Test failed, expect errorcode(%d) != result(%d)"), 
+                         iTestCases[i]->ExpectedResult(),
+                         iTestCases[i]->iResult.iCaseExecutionResultCode ) );
+                    // We return the first error result as aResult
+                    aResult = iTestCases[i]->iResult.iTestResult;
+                    // override result with real error code
+                    aResult.iResult = iTestCases[i]->iResult.iCaseExecutionResultCode;
+                    break;
+                    }
+                }
+            }
+        if( i == count )
+            {
+            TestModuleIf().Printf( KPrintPriHigh, _L("Result"), _L("PASSED"));
+            __TRACE( KPrint, (_L("***Test case result: PASSED***")));
+            aResult.iResult = KErrNone;
+            aResult.iResultDes.Copy( _L("Test case succeeded") );
+            }
+        else
+            {
+            TestModuleIf().Printf( KPrintPriHigh, _L("Result"), _L("FAILED"));        
+            __TRACE( KPrint, (_L("***Test case result: FAILED***")));
+            }
+        }
+
+    // Release all pending event requests
+    TEventIf event( TEventIf::ERelEvent );
+    TInt eventCount = iEventArray.Count();
+    for( TInt ind=0; ind < eventCount; ind++ )
+        {
+        event.SetName( iEventArray[ind]->Name() );
+        TestModuleIf().Event( event );
+        }
+
+    iLoopAllocationArray.Reset();
+    iLoopAllocationArray.Close();
+    iLoopIsUsed = EFalse;
+
+    // Delete all completed and checked testcases
+    // Do not change the deletion order of events and test cases!!!
+    iEventArray.ResetAndDestroy();
+    iTestCases.ResetAndDestroy();
+    iTestModules.ResetAndDestroy();
+    iSlaveArray.ResetAndDestroy();
+
+    iSendReceive.ResetAndDestroy();
+
+    // Stop all remaining measurement modules
+    const TInt count_meas = iTestMeasurementArray.Count();
+    for( TInt b = 0; b < count_meas; b++ )
+        {
+        iTestMeasurementArray[b]->iMeasurement->Stop();
+        }
+    iTestMeasurementArray.ResetAndDestroy();
+    iTestMeasurementArray.Close();
+
+    __UHEAP_MARKEND;
+
+    //If log was replaced then restore it
+    if(iAddTestCaseTitleToLogName)
+        {
+        iLog = iStdLog;
+        delete iTCLog;
+        iTCLog = NULL;
+        }
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetTestCaseL
+
+     Description: Get specified test case section from configfile.
+
+     Parameters:    const TInt aCaseNumber: in: Test case number
+                    const TFileName& aConfig: in: Configfile name 
+
+     Return Values: CSectionParser*: pointer to test case section
+
+     Errors/Exceptions: Leaves if CStifParser::NewL leaves
+                        Leaves if CStifParser::SectionL leaves
+                        Leaves if memory allocation fails
+
+     Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifSectionParser* CTestCombiner::GetTestCaseL( const TInt aCaseNumber, 
+                                             const TFileName& aConfig )
+    {
+    __TRACEFUNC();
+    CStifParser* parser = 
+        CStifParser::NewL( _L(""), aConfig, CStifParser::ECStyleComments );
+    CleanupStack::PushL( parser );
+
+    CStifSectionParser* section = 
+        parser->SectionL( KTestStartTag, KTestEndTag, aCaseNumber );
+
+    CleanupStack::PopAndDestroy( parser );
+    return section;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: ReadInitializationL
+
+     Description: Read initialization from file.
+
+     Parameters:    const TDesC& aIniFile: in: File that contains initialization
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::ReadInitializationL( const TDesC& aIniFile )
+    {
+    CStifParser* parser = NULL; 
+
+    // Open file
+    TRAPD( err, parser = 
+        CStifParser::NewL( _L(""), aIniFile, CStifParser::ECStyleComments ) );
+    if( ( err == KErrNone ) && parser )
+        {
+        CleanupStack::PushL( parser );
+        __TRACE( KMessage, (_L("Read initialization from [%S]"),
+            &aIniFile ) );
+        
+        // Read initialization parameters 
+        CStifSectionParser* section = parser->SectionL( KInitStartTag,
+                                                        KInitEndTag );
+        if( section  )
+            {
+            CleanupStack::PushL( section );
+            __TRACE( KMessage, (_L("Read initializations")) );
+
+            // Read RCP timeout            
+            CStifItemParser* item = section->GetItemLineL( KInitRcpTimeout );
+            if( item != NULL )
+                {
+                __TRACE( KMessage, (_L("Got RCP timeout definition")) );
+                CleanupStack::PushL( item );
+                
+                TInt value;
+                if( item->GetInt( KInitRcpTimeout, value ) 
+                        != KErrNone )
+                    {
+                    __TRACE( KError, (_L("No RCP timeout value given")) );
+                    User::Leave( KErrGeneral );                    
+                    } 
+                // Change from seconds to milliseconds
+                iRemoteTimeout = value*1000*1000;
+                CleanupStack::PopAndDestroy( item );
+                }
+
+            CleanupStack::PopAndDestroy( section );
+            }
+           
+        // Read defines
+        section = parser->SectionL( KDefineStartTag, KDefineEndTag );
+        while(section)
+            {
+            CleanupStack::PushL( section );
+            __TRACE( KMessage, (_L("Read defines")) );
+
+            TPtrC name;
+            TPtrC value;
+            CStifItemParser* item = section->GetItemLineL( _L("") );
+            while( item )
+                {
+                CleanupStack::PushL( item );
+                
+                if( item->GetString( _L(""), name ) != KErrNone )
+                    {
+                    __TRACE( KError, (_L("No define name given")) );
+                    User::Leave( KErrGeneral );
+                    } 
+                if( item->Remainder( value ) != KErrNone )
+                    {
+                    __TRACE( KError, (_L("No define value given")) );
+                    User::Leave( KErrGeneral );
+                    } 
+                TInt count = iDefined.Count();
+                TInt i = 0;
+                for( ; i < count; i++ )
+                    {
+                    if( iDefined[i]->Name() == name )
+                        {
+                        __TRACE( KMessage, (_L("Update define %S:%S"), &name, &value ) );
+                        // Update existing
+                        iDefined[i]->SetValueL( value );
+                        break;
+                        }
+                    }
+                if( i == count) 
+                    {
+                    // New define, store it
+                    CDefinedValue* define = CDefinedValue::NewL( name, value );
+                    CleanupStack::PushL( define );
+                    User::LeaveIfError( iDefined.Append( define ) );
+                    CleanupStack::Pop( define );
+                    }
+
+                CleanupStack::PopAndDestroy( item );
+                item = section->GetNextItemLineL();
+                }
+            CleanupStack::PopAndDestroy( section );
+            section = parser->NextSectionL(KDefineStartTag, KDefineEndTag);
+            }
+        CleanupStack::PopAndDestroy( parser );
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: RunTestL
+
+     Description: Run a testcase specified by iSectionParser.
+
+     Parameters:    None
+     
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if CSectionParser::GetItemLineL leaves
+                        Leaves if CTestRunner::NewL leaves
+                        Leaves if memory allocation fails                                
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::RunTestL()
+    {
+    __TRACEFUNC();
+    iResult = KErrNone;
+
+    TPtrC line;
+    // "title" keyword must be in the first line
+    User::LeaveIfError( iSectionParser->GetLine( KTitle, line, ENoTag ) );
+     
+    iTestRunner = CTestRunner::NewL( this ); 
+    iRemoteReceiver = CRemoteReceiver::NewL( this );
+    iRemoteReceiver->Start();
+
+    __TRACE( KMessage, (_L("Run: %S"), &line));
+    
+    TestModuleIf().Printf( KPrintPriNorm, _L("Run"), _L("%S"), &line);
+    // Rest of the job is done by test runner
+    iTestRunner->SetRunnerActive();
+
+    // Start activeScheduler looping testcase lines
+    iSchedulerActive = ETrue;
+    __TRACE( KMessage, (_L("Start CActiveScheduler")));
+    CActiveScheduler::Current()->Start();
+
+    TestModuleIf().Printf( KPrintPriNorm, _L("Executed"), _L("%S"), &line);
+    __TRACE( KMessage, (_L("Executed: %S"), &line));
+        
+    delete iRemoteReceiver;
+    iRemoteReceiver = NULL;
+    delete iTestRunner;
+    iTestRunner = NULL;
+
+    }     
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetTestModuleL
+
+     Description: Load testmodule if not already loaded, otherwise return
+                  description of the loaded testmodule.
+
+     Parameters:    TDesC& aModule: in: Module name.
+                    TDesC& aIniFile: in: Ini file name.
+                    const TDesC& aConfigFile: in: Test case(config) file name.
+     
+     Return Values: CTCTestModule*: pointer to testmodules description
+     
+     Errors/Exceptions: Leaves if CTCTestModule::NewL leaves
+                        Leaves if RPointerArray::Append fails  
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CTCTestModule* CTestCombiner::GetTestModuleL( TDesC& aModule,
+                                              TDesC& aIniFile,
+                                              const TDesC& aConfigFile )
+    {
+    __TRACEFUNC();
+    TInt count = iTestModules.Count();
+    TInt i, j;
+    TInt counttc;
+    TInt running;
+    TBool newWay = EFalse;
+    
+    __TRACE(KMessage, (_L("Find test module for [%S]"), &aModule));
+
+    //Name for new module controller
+    TName newModuleName = aModule;
+
+    //Check if it is python case or UITestingSupport or SeparateProcesses mode
+    newWay = (aModule.Find(KPythonScripter) == 0)
+             || (iUITestingSupport && aModule.Find(KTestScripterName) == 0)
+             || (iSeparateProcesses); 
+
+    if(newWay)
+        {
+        __TRACE(KMessage, (_L("TCTestModule operating mode: exclusive")));
+
+        //Find module of given name
+        __TRACE(KMessage, (_L("Looking for module [%S]"), &aModule));
+        if(iUITestingSupport && aModule.Find(KTestScripterName) == 0)
+            {
+            __TRACE(KMessage, (_L("UITestingSupport option is on. New module controller will be created always")));
+            }
+        else
+            {
+            for(i = 0; i < count; i++)
+                {
+                TPtrC modName = iTestModules[i]->ModuleName();
+                if(modName.Find(aModule) == 0)
+                    {
+                    //Check if there is running test case
+                    counttc = iTestCases.Count();
+                    running = 0;
+                    for(j = 0; j < counttc; j++)
+                        {
+                        if(iTestCases[j]->TestModule() == iTestModules[i] && iTestCases[j]->State() != CTestCase::ETestCaseCompleted)
+                            {
+                            //We have found at least one running test case. There is no reason to find any more,
+                            //because there shouldn't be because test module may run only one python scripter test case.
+                            running++;
+                            __TRACE(KMessage, (_L("Module controller found [%S], but it has running test cases"), &modName));
+                            break;
+                            }
+                        }
+                    if(running == 0)
+                        {
+                        __TRACE(KMessage, (_L("Free module controller has been found [%S]"), &modName));
+                        return iTestModules[i];
+                        }
+                    }
+                }
+            }
+        //Update name of new module to be created
+        newModuleName.AppendFormat(_L("@%d_"), GetIndexForNewTestModuleController());
+        newModuleName.LowerCase();
+        }
+    else
+        {
+        __TRACE(KMessage, (_L("TCTestModule operating mode: normal")));
+        for(i = 0; i < count; i++)
+            {
+            if(iTestModules[i]->ModuleName() == aModule)
+                {
+                // Found test module, return description
+                __TRACE(KMessage, (_L("Module controller [%S] found"), &aModule));
+                return iTestModules[i];
+                }
+            }
+        }
+
+    __TRACE(KMessage, (_L("Creating new test module controller [%S] with ini [%S]"), &newModuleName, &aIniFile));
+    CTCTestModule* module = CTCTestModule::NewL(this, newModuleName, aIniFile, aConfigFile);
+    CleanupStack::PushL(module);
+
+    //Enumerate test cases
+    module->GetTestCasesForCombiner(aConfigFile);
+
+    //Append new module to list
+    User::LeaveIfError(iTestModules.Append(module));
+    CleanupStack::Pop(module);
+
+    //Log some info
+    if(newWay)
+        {    
+        __TRACE(KMessage, (_L("Module [%S] added to list. Currently there are following controllers of [%S] type:"), &newModuleName, &aModule));
+        j = 1;
+        for(i = 0; i < iTestModules.Count(); i++)
+            {
+            if(iTestModules[i]->ModuleName().Find(aModule) == 0)
+                {
+                __TRACE(KMessage, (_L("    %d. [%S]"), j, &iTestModules[i]->ModuleName()));
+                j++;
+                }
+            }
+        }
+
+    if( iLoopIsUsed )
+        {
+        User::LeaveIfError( iLoopAllocationArray.Append( module ) );
+        }
+
+    return module;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetTest
+
+     Description: Get test case from testcase array.
+
+     Parameters:    TDesC& aTestId: in: TestId for testcase
+     
+     Return Values: CTCTestCase*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTestCase* CTestCombiner::GetTest( TDesC& aTestId )
+    {
+    __TRACEFUNC();
+    // TestId is not mandatory, so length may be zero
+    if( aTestId.Length() == 0 )
+        {
+        return NULL;
+        }
+
+    TInt count = iTestCases.Count();
+    for( TInt i=0; i < count; i++ )
+        {
+        if( iTestCases[i]->TestId() == aTestId )
+            {
+            // Found testcase with specified TestId
+            return iTestCases[i];
+            }
+        }
+    // Test case with aTestId not found
+    return NULL;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetRunningTest
+
+     Description: Get running test case.
+
+     Parameters: TDesC& aTestId: in: TestId for testcase
+     
+     Return Values: CTCTestCase*: running testcase
+                    NULL: Testcase with aTestId not running 
+
+     Errors/Exceptions: None
+
+     Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCase* CTestCombiner::GetRunningTest( TDesC& aTestId )
+    {
+    __TRACEFUNC();
+     
+    CTestCase* test = GetTest( aTestId );
+    if( test ) 
+        {
+        if( test->State() == CTestCase::ETestCaseRunning )
+            {
+            return test;
+            }
+        else
+            {
+             __TRACE( KMessage, (_L("GetTest: Searched task (%S) not running (%i)"), 
+                &aTestId, test->State() ));
+            }
+        }
+
+    return NULL;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetLocalTest
+
+     Description: Get local test case from testcase array.
+
+     Parameters:    TDesC& aTestId: in: TestId for testcase
+     
+     Return Values: CTCTestCase*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned 
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CTCTestCase* CTestCombiner::GetLocalTest( TDesC& aTestId )
+    {
+    __TRACEFUNC();
+    CTestCase* testCase = GetTest( aTestId );
+    if( testCase )
+        {    
+        if( testCase->Type() != CTestCase::ECaseLocal )
+            {
+            __TRACE( KMessage, (_L("GetLocalTest: Searched task (%S) not local"), 
+                      &aTestId ));
+            return NULL;
+            }
+        }
+    return ( CTCTestCase* ) testCase;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetLocalRunningTest
+
+     Description:  Get local running test case.
+
+     Parameters:    TDesC& aTestId: in: TestId for testcase
+     
+     Return Values: CTCTestCase*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned 
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CTCTestCase* CTestCombiner::GetLocalRunningTest( TDesC& aTestId )
+    {
+    __TRACEFUNC();
+    CTestCase* testCase = GetRunningTest( aTestId );
+    if( testCase )
+        {    
+        if( testCase->Type() != CTestCase::ECaseLocal )
+            {
+            __TRACE( KMessage, (_L("GetLocalRunningTest: Searched task (%S) not local"), 
+                      &aTestId ));
+            return NULL;
+            }
+        }
+        
+    return ( CTCTestCase* ) testCase;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetRemoteTest
+
+     Description: Get local test case from testcase array.
+
+     Parameters:    TDesC& aTestId: in: TestId for testcase
+     
+     Return Values: CTCTestCase*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned 
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteTestCase* CTestCombiner::GetRemoteTest( TDesC& aTestId )
+    {
+    __TRACEFUNC();
+    CTestCase* testCase = GetTest( aTestId );
+    if( testCase )
+        {    
+        if( testCase->Type() != CTestCase::ECaseRemote )
+            {
+            __TRACE( KMessage, (_L("GetRemoteTest: Searched task (%S) not remote"), 
+                      &aTestId ));
+            return NULL;
+            }
+        }
+        
+    return ( CRemoteTestCase* ) testCase;
+    
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetRemoteTest
+
+     Description: Get remote test case from slave array.
+
+     Parameters:    TUint32 aSlaveId: in: Slave id for testcase
+     
+     Return Values: TCaseInfo*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned 
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteTestCase* CTestCombiner::GetRemoteTest( TUint32 aSlaveId )
+    {
+    
+    __TRACEFUNC();
+    
+    // Check all remote testcases
+    TInt caseCount = iTestCases.Count(); 
+    CRemoteTestCase* testCase = NULL;
+    for( TInt caseInd = 0; caseInd < caseCount; caseInd++ )
+        {
+        if( iTestCases[caseInd]->Type() == CTestCase::ECaseRemote )
+            {
+            testCase = ( CRemoteTestCase* )iTestCases[caseInd];
+            if( testCase->iSlaveId == aSlaveId )
+                {
+                return testCase;
+                }
+            }
+        }
+    
+    return NULL;
+        
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetRemoteTestRunSent
+
+     Description: Get remote test case from slave array
+
+     Parameters:    TUint32 aSlaveId: in: Slave id for testcase
+
+     Return Values: TCaseInfo*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned 
+
+     Errors/Exceptions: None
+
+     Status: Draft @js
+    
+-------------------------------------------------------------------------------
+*/
+    
+CRemoteTestCase* CTestCombiner::GetRemoteTestRunSent( TUint32 aSlaveId )
+    {
+    
+    __TRACEFUNC();
+    
+    // Check all remote testcases
+    TInt caseCount = iTestCases.Count(); 
+    CRemoteTestCase* testCase = NULL;
+    for( TInt caseInd = 0; caseInd < caseCount; caseInd++ )
+        {
+        if( iTestCases[caseInd]->Type() == CTestCase::ECaseRemote )
+            {
+            testCase = ( CRemoteTestCase* )iTestCases[caseInd];
+            
+            if( testCase->iRemoteState != CRemoteTestCase::ECaseRunSent )
+                {
+                continue;
+                }
+            if( testCase->iSlaveId == aSlaveId )
+                {
+                return testCase;
+                }
+            }
+        }
+    
+    return NULL;
+        
+    }       
+  
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetRemoteTest
+
+     Description: Get remote test case from slave array.
+
+     Parameters:    TUint32 aSlaveId: in: Slave id for testcase
+     
+     Return Values: TCaseInfo*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned 
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteTestCase* CTestCombiner::GetRunningRemoteTest( TUint32 aSlaveId )
+    {
+    
+    __TRACEFUNC();
+    
+    // Check all remote testcases
+    TInt caseCount = iTestCases.Count(); 
+    CRemoteTestCase* testCase = NULL;
+    for( TInt caseInd = 0; caseInd < caseCount; caseInd++ )
+        {
+        if( ( iTestCases[caseInd]->Type() == CTestCase::ECaseRemote ) &&
+            ( iTestCases[caseInd]->State() == CTestCase::ETestCaseRunning ) )
+            {
+            testCase = ( CRemoteTestCase* )iTestCases[caseInd];
+            
+            if( ( testCase->iRemoteState != CRemoteTestCase::ECaseRunSent ) &&
+                ( testCase->iRemoteState != CRemoteTestCase::ECaseRunning ) && 
+                ( testCase->iRemoteState != CRemoteTestCase::ECaseCancelled ))
+                {
+                //User::Leave( KErrGeneral ); 
+                continue;                       
+                }
+                
+            if( testCase->iSlaveId == aSlaveId )
+                {
+                return testCase;
+                }
+            }
+        }
+    
+    return NULL;
+        
+    }   
+
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetRemoteTestSlave
+
+     Description: Get remote test case running on slave
+
+     Parameters:    TUint32 aSlaveDevId: in: Slave id for testcase
+     
+     Return Values: CRemoteTestCase*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned 
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteTestCase* CTestCombiner::GetRemoteRunningTestOnSlave( 
+                                                    TUint32 aSlaveDevId )
+    {
+    
+    __TRACEFUNC();
+    
+    // Check all remote testcases
+    TInt caseCount = iTestCases.Count(); 
+    CRemoteTestCase* testCase = NULL;
+    for( TInt caseInd = 0; caseInd < caseCount; caseInd++ )
+        {
+        if( ( iTestCases[caseInd]->Type() == CTestCase::ECaseRemote ) &&
+            ( iTestCases[caseInd]->State() == CTestCase::ETestCaseRunning ) )
+            {
+            testCase = ( CRemoteTestCase* )iTestCases[caseInd];
+            if( DEVID( testCase->iSlaveId ) == DEVID( aSlaveDevId ) )
+                {
+                return testCase;
+                }
+            }
+        }
+    
+    return NULL;
+        
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetRemoteTestSlave
+
+     Description: Gets a correct CRemoteSendReceive object on slave with
+                  aSlaveId.
+
+     Parameters:    TUint32 aSlaveId: in: Slave id CRemoteSendReceive object
+     
+     Return Values: CRemoteSendReceive*: Current CRemoteSendReceive object.
+                    NULL: CRemoteSendReceive object do not exist or found.
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteSendReceive* CTestCombiner::GetRemoteSendReceive( TUint32 aSlaveId )
+    {
+    __TRACEFUNC();
+    
+    for( TInt sr = 0; sr < iSendReceive.Count(); sr++ )
+        {
+        if( iSendReceive[sr]->iSlaveId == aSlaveId )
+            {
+            return iSendReceive[sr];
+            }
+        }
+
+    return NULL;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetSlave
+
+     Description: Get remote slave.
+
+     Parameters:    TUint32 aSlaveId: in: Slave id 
+     
+     Return Values: CSlaveInfo*: reserved slave
+                    NULL: slave with aSlaveId not reserved 
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CSlaveInfo* CTestCombiner::GetSlave( TUint32 aSlaveId )
+    {
+    
+    __TRACEFUNC();
+    
+    TInt count = iSlaveArray.Count();
+    for( TInt index = 0; index < count; index++ )
+        {
+        if( DEVID( iSlaveArray[index]->iSlaveDevId ) == DEVID( aSlaveId) )
+            {
+            return iSlaveArray[index];
+            }
+        }
+    
+    return NULL;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: GetSlave
+
+     Description: Get remote slave.
+
+     Parameters:    TDesC& aSlaveName: in: Slave name 
+     
+     Return Values: CSlaveInfo*: reserved slave
+                    NULL: slave with aSlaveId not reserved 
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CSlaveInfo* CTestCombiner::GetSlave( TDesC& aSlaveName )
+    {
+    
+    __TRACEFUNC();
+
+    TInt count = iSlaveArray.Count();
+    for( TInt index = 0; index < count; index++ )
+        {
+        if( iSlaveArray[index]->iName == aSlaveName )
+            {
+            return iSlaveArray[index];
+            }
+        }
+    
+    return NULL;
+    
+    }        
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: StartTestL
+
+     Description: Start specified test case from testmodule.
+
+     Parameters:    CStartInfo& aStartInfo: in: Test case information
+     
+     Return Values: KErrNone: Testcase started
+                    KErrAlreadyExists: testcase with same aTestId is already 
+                                       running
+                    Any other SymbianOS errorcode
+
+     Errors/Exceptions: Leaves if CTCTestCase::NewL leaves
+                        Leaves if arguments are illegal
+                        Leaves if GetTestModuleL leaves
+                        Leaves if CTestExecution::Open fails
+                        Leaves if CTCTestCase::StartL leaves
+                        Leaves if RPointerArray::Append fails
+
+     Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCombiner::StartTestL(  CStartInfo& aStartInfo )
+    {
+    __TRACEFUNC();
+    // Check that TestId is unique.
+    if( GetTest( aStartInfo.iTestId ) != NULL )
+        {
+        // If loop testing is ongoing, allow already defined testid.
+        if( iLoopIsUsed )
+            {
+            __TRACE( KVerbose, ( _L("StartTestL: TestId (%S) already in use. Loop allows already defined TestId"), 
+             &aStartInfo.iTestId ));
+            }
+        else
+            {
+            __TRACE( KError, ( _L("StartTestL: TestId (%S) already in use"), 
+                 &aStartInfo.iTestId ));
+            return KErrAlreadyExists;
+            }
+        }
+
+    __ASSERT_ALWAYS( aStartInfo.iModule.Length() < KMaxFileName, 
+        User::Leave( KErrArgument ) );
+    __ASSERT_ALWAYS( aStartInfo.iIniFile.Length() < KMaxFileName, 
+        User::Leave( KErrArgument ) );
+    __ASSERT_ALWAYS( aStartInfo.iConfig.Length() < KMaxFileName, 
+        User::Leave( KErrArgument ) );
+    __ASSERT_ALWAYS( aStartInfo.iTestId.Length() < KMaxName, 
+        User::Leave( KErrArgument ) );
+
+    __TRACE( KMessage, ( _L("Call GetTestModuleL") ));
+
+    // Load Test Module
+    CTCTestModule* module = NULL;
+    if( (aStartInfo.iModule.Find( KTestScripterName ) != KErrNotFound) 
+        || (aStartInfo.iModule.Find( KPythonScripter ) != KErrNotFound)
+        || (aStartInfo.iModule.Find( KTestCombinerName ) != KErrNotFound) 
+        )
+        {
+        // TestScripter in use. Give config file for parsing STIF Settings.
+        module = GetTestModuleL( aStartInfo.iModule,
+                                 aStartInfo.iIniFile,
+                                 aStartInfo.iConfig );
+        }
+    else
+        {
+        module = GetTestModuleL( aStartInfo.iModule,
+                                 aStartInfo.iIniFile,
+                                 KNullDesC );
+        }
+
+    __TRACE( KMessage, ( _L("Create CTCTestCase") ));
+
+    CTCTestCase* tc = 
+        CTCTestCase::NewL( this, 
+                           aStartInfo.iModule, 
+                           aStartInfo.iTestId, 
+                           aStartInfo.iExpectedResult, 
+                           aStartInfo.iCategory,
+                           aStartInfo.iTestCaseArguments,
+                           module ); //--PYTHON--
+
+    CleanupStack::PushL( tc );
+    
+    //If name of testcase was given, find testcase number
+    if(aStartInfo.iTitle != KNullDesC)
+        {
+        __TRACE(KMessage, (_L("Trying to find test case entitled \"%S\""), &aStartInfo.iTitle));
+        aStartInfo.iCaseNum = -1;
+        TInt ret = module->GetCaseNumByTitle(aStartInfo.iTitle, aStartInfo.iCaseNum);
+        if(ret != KErrNone)
+            {
+            __TRACE(KError, (_L("Couldn't find test case entitled \"%S\". Error %d"), &aStartInfo.iTitle, ret));
+            }
+        else
+            {
+            __TRACE(KMessage, (_L("Found test case entitled \"%S\". Case num %d"), &aStartInfo.iTitle, aStartInfo.iCaseNum));
+            }
+        }
+
+    __TRACE( KMessage, ( _L("Open TestExecution") ));
+    
+    User::LeaveIfError( tc->TestExecution().Open( module->TestServer(), 
+                                                  aStartInfo.iCaseNum, 
+                                                  aStartInfo.iConfig ) );
+
+    __TRACE( KMessage, ( _L("Start testcase runner") ));
+
+      // Enable testcase control before calling RunTestCase
+    tc->StartL();
+
+    __TRACE( KMessage, 
+        ( _L("Start: testid(%S), module(%S), ini(%S), config(%S), case(%d), expect(%d/%d), timeout(%d)"), 
+        &aStartInfo.iTestId, &aStartInfo.iModule, &aStartInfo.iIniFile, 
+        &aStartInfo.iConfig, aStartInfo.iCaseNum, aStartInfo.iExpectedResult, 
+        aStartInfo.iCategory, aStartInfo.iTimeout ));
+
+    TestModuleIf().Printf( KPrintPriLow, _L("Start"),
+        _L("testid(%S), module(%S), ini(%S), config(%S), case(%d), expect(%d)"), 
+         &aStartInfo.iTestId, &aStartInfo.iModule, &aStartInfo.iIniFile, 
+         &aStartInfo.iConfig, aStartInfo.iCaseNum, aStartInfo.iExpectedResult );
+
+    if ( tc->TestCaseArguments().Length() > 0 )
+        {
+        tc->TestExecution().RunTestCase( tc->iResultPckg, tc->TestCaseArguments(), tc->iStatus );
+        }
+    else
+        {
+        tc->TestExecution().RunTestCase( tc->iResultPckg, tc->iStatus );
+        }
+
+    iRunningTests++;
+
+    User::LeaveIfError( iTestCases.Append( tc ) );
+    if( iLoopIsUsed )
+        {
+        User::LeaveIfError( iLoopAllocationArray.Append( tc ) );
+        }
+    CleanupStack::Pop( tc );
+
+    return KErrNone;
+
+}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: Complete
+
+     Description: Handle completed test case.
+
+     Parameters:    CTCTestCase* aTestCase: in: Test case to complete
+
+     Return Values: None.
+
+     Errors/Exceptions: None
+
+     Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::Complete( CTestCase* aTestCase, TInt aError )
+    {
+    __TRACEFUNC();
+    
+    if( aError != KErrNone )
+        {
+        iResult = aError;
+        }
+
+    TInt count = iTestCases.Count();
+    TInt i = 0;
+    for(; i < count; i++ )
+        {
+        if( iTestCases[i] == aTestCase )
+            {
+            // Test Case completed
+            __TRACE( KPrint, (  _L( "Complete: %S result: %d, execution result: %d, expected: %d"), 
+                 &aTestCase->TestId(), aTestCase->iResult.iTestResult.iResult, 
+                 aTestCase->iResult.iCaseExecutionResultCode, aTestCase->ExpectedResult()  ));
+            TestModuleIf().Printf( KPrintPriLow, _L("Complete"),
+                _L( "%S results: test(%d) exe(%d) expect(%d)"), 
+                 &aTestCase->TestId(), aTestCase->iResult.iTestResult.iResult,
+                 aTestCase->iResult.iCaseExecutionResultCode, aTestCase->ExpectedResult() );
+            iRunningTests--;
+            break;
+            }
+        }
+    if( i == count )
+        {
+        __TRACE( KError, (_L("CTestCombiner::Complete: Test case not found!!")));
+        }
+
+    // Check if we were waiting this case to complete
+    if( ( iWaitTestCase.Length() > 0 ) && 
+        ( iWaitTestCase == aTestCase->TestId() ) )
+        {
+        // We were waiting this case to complete 
+        // Now we can proceed executing the testcase
+        __TRACE( KMessage, (_L("TestCase was waiting, set runner active")));
+        iTestRunner->SetRunnerActive();
+        iWaitTestCase.Zero();
+        
+     //return; - return removed due to STIF-509 CancelIfError won't work when used together with complete command
+     
+        }
+    else if( aTestCase->Type() == CTestCase::ECaseRemote )
+        {
+        __TRACE( KMessage, (_L("CTestCombiner::Complete: Remote case complete")));
+        // Completed testcase was remote case,
+        // check if slave should be freed
+        CRemoteTestCase* remote = ( CRemoteTestCase* )aTestCase;
+        if( remote->iFreeSlave )
+            {
+            CSlaveInfo* slave = GetSlave( remote->iSlaveId );
+            if( slave )
+                {
+                // Free slave now
+                TRAPD( err, iTestRunner->ExecuteFreeL( slave ) );
+                // Continue if freeing fails
+                if( err == KErrNone )
+                    {
+                    __TRACE( KMessage, (_L("Complete: Freeing slave")));
+                    return;
+                    }
+                else
+                    {
+                    __TRACE( KError, (_L("Complete: Freeing slave failed")));
+                    }
+                }
+            else 
+                {
+                __TRACE( KError, (_L("Complete: Slave not found")));
+                }
+            }
+        }
+
+    // If running test is 0, active scheduler is active and CTestRunner is
+    // ready then stop active scheduler.(Operations continue from 
+    // CTestCombiner::RunTestL() after active scheduler start).
+    if( ( iRunningTests == 0 ) &&
+          iSchedulerActive &&
+        ( iTestRunner->iState == CTestRunner::ERunnerReady ) )
+        {
+        // This was last running testcase, so we can stop 
+        // activescheduler
+        __TRACE( KMessage, (_L("All TestCases completed, stop CActiveScheduler")));
+        CActiveScheduler::Current()->Stop();
+        iSchedulerActive = EFalse;
+        }
+    else 
+        {
+        __TRACE( KMessage, 
+            (_L("CTestCombiner::Complete: %d test cases running"), iRunningTests ));
+        __TRACE( KMessage, 
+            (_L("CTestCombiner::Complete: active %d"), iSchedulerActive ));
+        if(iSchedulerActive)    
+            {             
+            __TRACE( KMessage, 
+                (_L("CTestCombiner::Complete: state %d"), iTestRunner->iState ));
+            }
+        }
+
+    // Checking if user wants to skip the rest of the execution in case of error @js
+    if(iCancelIfError && iSchedulerActive)    
+        {
+        // Cancel event if it was waiting event
+        if(iTestRunner->iEvent.Name() != KNullDesC && iTestRunner->iEvent.Type() == TEventIf::EWaitEvent)
+            {
+            TestModuleIf().CancelEvent(iTestRunner->iEvent, &iTestRunner->iStatus);
+            }
+
+        // Interpret execution result type from returned result
+        TInt executionResult = TFullTestResult::ECaseExecuted; // Ok
+        if( (aTestCase->iResult.iCaseExecutionResultType >= 
+            TFullTestResult::ECaseLeave ))
+            {
+            __TRACE( KMessage, (_L("The test case ended with error!")));
+
+            // Some abnormal execution result type
+            executionResult = iTestCases[i]->iResult.iCaseExecutionResultType;
+            }
+
+         // Check expected execution result type
+        if( executionResult != aTestCase->ExpectedResultCategory() ) 
+            {
+            // expected and returned result types differ
+            __TRACE( KMessage, (_L("The test case has wrong result category!")));
+            // There was an error and we must stop test case execution
+            iFailedTestCase = i;
+            iRunningTests--;
+            __TRACE( KMessage, (_L("Stopping the CActiveScheduler.")));
+            CActiveScheduler::Current()->Stop();
+            iSchedulerActive = EFalse;
+            }
+
+        // Check normal test result if activescheduler is still up & running
+        if( iSchedulerActive )
+            {
+            if( aTestCase->ExpectedResultCategory() == 
+            TFullTestResult:: ECaseExecuted)
+                {
+                // Normal completion, check result
+                if( iTestCases[i]->iResult.iTestResult.iResult != 
+                    iTestCases[i]->ExpectedResult() )
+                    { 
+                    __TRACE( KMessage, (_L("Result category is not what was expected!")));
+                    // There was an error and we must stop test case execution
+                    iFailedTestCase = i;
+                    iRunningTests = 0; //The whole test is stopped. Reset value of running tests.
+                    //This line caused that variable value to be -1. Test could not finish. //iRunningTests--;
+                    __TRACE( KMessage, (_L("Stopping the CActiveScheduler.")));
+                    CActiveScheduler::Current()->Stop();
+                    iSchedulerActive = EFalse;
+                    }
+                }
+            else 
+                {
+                // Abnormal completion, i.e. panic, leave, exception or timeout
+                if( aTestCase->iResult.iCaseExecutionResultCode != 
+                    aTestCase->ExpectedResult())
+                    {
+                    __TRACE( KMessage, (_L("The test case has abnormal completion!")));
+                    // There was an error and we must stop test case execution
+                    iFailedTestCase = i;
+                    iRunningTests--;
+                    __TRACE( KMessage, (_L("Stopping the CActiveScheduler.")));
+                    CActiveScheduler::Current()->Stop();
+                    iSchedulerActive = EFalse;
+                    }
+                }
+            }
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: NotifyEvent
+
+     Description: Asynchronous event command interface
+     
+     Check requested events and send unset to first requested
+     
+     Parameters: TEventIf& aEvent: in: Event command 
+                TRequestStatus& aStatus: in: TRequestStatus used in 
+                                                          asynchronous command 
+     
+     Return Values: ETrue: asynchronous command given
+                          EFalse: asyncronous command not given
+
+     Errors/Exceptions: None
+     
+     Status: Proposal
+     
+-------------------------------------------------------------------------------
+*/
+TBool CTestCombiner::UnsetEvent( TEventIf& aEvent, 
+                                 TRequestStatus& aStatus )
+    {
+    
+    __TRACE( KMessage, ( _L("CTestCombiner::NotifyEvent")));    
+    
+    // First check TestCombiner events
+    TInt eventCount = iEventArray.Count();
+    for( TInt i = 0; i < eventCount; i++ )
+        {
+        if( aEvent.Name() == iEventArray[i]->Name() )
+            {
+            __TRACE( KMessage, (  
+                _L( "Set unset pending for testcombiner's %S event"),  
+                    &aEvent.Name()  ));
+            iEventArray[i]->SetRequestStatus( &aStatus );
+            return ETrue;
+            }
+        }
+    
+    // Check all local testcases
+    TInt caseCount = iTestCases.Count(); 
+    TInt eventInd;
+    CTCTestCase* testCase = NULL;
+    for( TInt caseInd = 0; caseInd < caseCount; caseInd++ )
+        {
+        if( iTestCases[caseInd]->Type() == CTestCase::ECaseLocal )
+            {
+            testCase = ( CTCTestCase* )iTestCases[caseInd];
+            eventCount = testCase->EventArray().Count();
+             
+             // Check all requested events
+            for( eventInd = 0; eventInd < eventCount; eventInd++)
+                {
+                const TName& eventName = 
+                    testCase->EventArray()[eventInd]->Event().Name();
+                if( eventName == aEvent.Name() )
+                    {
+                      // Event request is pending, send control command
+                    iEvent.Copy( aEvent );
+                    __TRACE( KMessage, (  
+                        _L( "Set unset pending for client's %S event"),  
+                        &aEvent.Name()  ));
+                    testCase->TestExecution().NotifyEvent( iEventPckg, 
+                                                             aStatus );
+                    return ETrue;
+                    }
+                }
+            }
+        }
+     
+    return EFalse;
+     
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: ReceiveResponse
+
+     Description: Handles responce received from slave
+  
+     Parameters:    None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::ReceiveResponse( TDesC& aMsg )
+    {
+    
+    __TRACEFUNC();
+    
+    TBool continueTask = ETrue;
+    TRAPD( err, continueTask = iTestRunner->ReceiveResponseL( aMsg ) );
+        
+    // We start receiver again, even in error situation
+    iRemoteReceiver->Start();
+
+    if( err != KErrNone )
+        {
+        __TRACE( KError, ( _L("CTestCombiner::ReceiveResponse ERROR")));
+        iResult = err;
+        if( iTestRunner->IsActive() )
+            {
+            iTestRunner->Cancel();
+            }
+        else
+            {
+            iTestRunner->CancelTestCases();
+            }
+        return;
+        }
+        
+    if( continueTask && !iTestRunner->IsActive() )
+        {
+        iTestRunner->SetRunnerActive();
+        }
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: RemoteTimeout
+
+     Description: Handles timeouts.
+  
+     Parameters:    None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::RemoteTimeout()
+    {
+    
+    __TRACEFUNC();
+    
+    iResult = KErrTimedOut;
+    if( iTestRunner->IsActive() )
+        {
+        __TRACE( KError, (_L("Remote timeout, Cancel runner")));
+        iTestRunner->Cancel();
+        }
+    else
+        {
+        __TRACE( KError, (_L("Remote timeout, Cancel test cases")));
+        iTestRunner->CancelTestCases();
+        }
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: ExecuteMeasurementL
+
+     Description: Executes measurement script line.
+  
+     Parameters: CStifItemParser* aItem: in: parsed line
+     
+     Return Values: TBool: in no error ETrue returned
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::ExecuteMeasurementL( CStifItemParser* aItem )
+    {
+    __TRACEFUNC();
+    
+     __TRACEFUNC();
+    TPtrC type;
+    TPtrC command;
+
+    // Get command
+    if( aItem->GetNextString( command ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'measurement' command" ) ) );
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+    // Get name
+    if( aItem->GetNextString( type ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'measurement' type" ) ) );
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+
+    // Verify measurement type
+    if( !( type == KParamMeasurement01 ||
+                type == KParamMeasurement02 ||
+                type == KParamMeasurement03 ||
+                type == KParamMeasurement04 ||
+                type == KParamMeasurement05 ||
+                type == KParamMeasurementBappea ) )
+
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown measurement type:[%S]" ), &type ) );
+        User::Leave( KErrArgument ); // Error in types => Leave
+        }
+
+    // Verify command
+   if( command == _L( "start" ) )
+        {
+        // START measurement's process
+        __TRACE( KMessage, ( _L( "Start 'measurement' with '%S'"), &type ) );
+        StartMeasurementL( type, aItem );
+        }
+    else if( command == _L( "stop" ) )
+        {
+        // STOP measurement's process
+        __TRACE( KMessage, ( _L( "'Stop 'measurement' with '%S'"), &type ) );
+        StopMeasurementL( type );
+        }
+    else
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown command for 'measurement' command:[%S] or type:[%S]" ), &command, &type ) );
+        User::Leave( KErrArgument ); // Error in commands => Leave
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: StartMeasurementL
+
+     Description: 
+  
+     Parameters: const TDesC& aType: in: Plugin type.
+                 CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves is bappea start or timed operation fails.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::StartMeasurementL( const TDesC& aType,
+                                           CStifItemParser* aItem )
+    {
+    __TRACEFUNC();
+
+    CSTIFTestMeasurement* testMeasurement = NULL;
+
+    // Get Measurement configuration info
+    TPtrC configurationInfo( KNullDesC() );
+    if( aItem->Remainder( configurationInfo ) != KErrNone )
+        {
+        __TRACE( KInit, ( 
+            _L( "Using default path and file name for measurement configure" ) ) );
+        } 
+
+    if( aType == KParamMeasurement01 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    this, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin01,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurement02 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    this, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin02,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurement03 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    this, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin03,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurement04 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    this, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin04,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurement05 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    this, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin05,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurementBappea )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    this, 
+                    CSTIFTestMeasurement::KStifMeasurementBappeaProfiler,
+                    configurationInfo );
+        }
+    else
+        {
+        __TRACE( KError, ( _L( "Unknown plugin[%S] for 'measurement'" ), &aType ) );
+        User::Leave( KErrArgument );
+        }
+
+   // Start test measurement
+    TInt start_ret( KErrNone );
+    start_ret = testMeasurement->Start();
+    if( start_ret != KErrNone )
+        {
+        delete testMeasurement;
+        __TRACE( KError, ( 
+            _L( "CTestCombiner::StartMeasurementL(): Measurement Start() fails:[%d]" ), start_ret ) );
+        User::Leave( start_ret );
+        }
+
+    TTestMeasurement* object = new (ELeave) TTestMeasurement();
+    object->iName = aType;
+    object->iMeasurement = testMeasurement;
+
+    // Array for handling test measurement between different objects
+    TInt ret = iTestMeasurementArray.Append( object );
+    if( ret != KErrNone )
+        {
+        delete object;
+        __TRACE( KError, ( 
+            _L( "CTestCombiner::StartMeasurementL(): iTestMeasurementArray.Append fails:[%d]" ), ret ) );
+        User::Leave( ret );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: StopMeasurementL
+
+     Description: Stops test measurement.
+  
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::StopMeasurementL( const TDesC& aType )
+    {
+    __TRACEFUNC();
+
+    TInt count = iTestMeasurementArray.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( iTestMeasurementArray[i]->iName == aType )
+            {
+            // Found measurement module, stop
+            iTestMeasurementArray[i]->iMeasurement->Stop();
+            // Delete data
+            delete iTestMeasurementArray[i];
+            // Remove pointer to deleted data(Append())
+            iTestMeasurementArray.Remove( i );
+            // iTestMeasurementArray can contain only one type of measurement
+            // so we can break when type is removed.
+            break;
+            }
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestCombiner
+
+     Method: AppendTestResultToResultDes
+
+     Description: Append to TC's result description (if possible due to length) 
+                  limitation provided text in [] brackets.
+  
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestCombiner::AppendTestResultToResultDes(TDes& aResultDescr, const TDesC& aTestCaseResultDescr)
+    {
+    if(aTestCaseResultDescr != KNullDesC)
+        {
+        _LIT(KAdditionalInfo, " [%S]");
+        TInt len = aResultDescr.Length() + KAdditionalInfo().Length() + aTestCaseResultDescr.Length();
+
+        if(len > KStifMaxResultDes)
+            {
+            len = KStifMaxResultDes - aResultDescr.Length() - KAdditionalInfo().Length();
+            if(len > 0)
+                {
+                TPtrC descr = aTestCaseResultDescr.Mid(0, len); 
+                aResultDescr.AppendFormat(KAdditionalInfo, &descr);
+                }
+            }
+        else
+            {
+            aResultDescr.AppendFormat(KAdditionalInfo, &aTestCaseResultDescr);
+            }
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCombiner
+
+    Method: GetIndexForNewTestModuleController
+
+    Description: Returns new index for test module controller.
+                 This number is appended to module controller name.
+                 This method is used when option to run every test case in 
+                 separate process is set to on.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCombiner::GetIndexForNewTestModuleController(void)
+    {
+    return iIndexTestModuleControllers++;
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CTestRunner class 
+    member functions. CTestRunner is used to execute TestCombiner testcase by 
+    CTestCombiner.
+
+-------------------------------------------------------------------------------
+*/
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iTestCombiner->iLog
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: CTestRunner
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to CTestCombiner
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTestRunner::CTestRunner( CTestCombiner* aTestCombiner ): 
+    CActive(  CActive::EPriorityLow ), // Executed with lowest priority 
+    iState( ERunnerIdle ),
+    iTestCombiner( aTestCombiner )
+    {
+    CActiveScheduler::Add( this );
+    __TRACEFUNC();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::ConstructL()
+    {
+    TInt ret;
+    
+    ret = iPauseTimer.CreateLocal();
+    if(ret != KErrNone)
+        {
+        __TRACE( KError, (_L("Unable to create RTimer: iPauseTimer [%d] "), ret));
+        User::Leave(ret);
+        }
+        
+    ret = iPauseCombTimer.CreateLocal();
+    if(ret != KErrNone)
+        {
+        __TRACE( KError, (_L("Unable to create RTimer: iPauseCombTimer [%d] "), ret));
+        User::Leave(ret);
+        }
+    
+    iRemoteTimer = CRemoteTimer::NewL( iTestCombiner );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to CTestCombiner
+
+     Return Values: CTestRunner*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+
+CTestRunner* CTestRunner::NewL( CTestCombiner* aTestCombiner )
+    {
+    CTestRunner* self = new (ELeave) CTestRunner( aTestCombiner );
+     
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ~CTestRunner
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/     
+
+CTestRunner::~CTestRunner()
+    {
+    __TRACEFUNC();
+    Cancel();
+    
+    delete iRemoteTimer;
+    iRemoteTimer = 0;
+    
+    delete iLine;
+    iLine = 0;
+    
+    iPauseTimer.Close();
+    
+    iPauseCombTimer.Close();
+         
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: RunL
+
+     Description: Derived from CActive, handles testcase execution.
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::RunL()
+    {
+    __TRACEFUNC();
+    __TRACE( KMessage, (_L("CTestRunner::RunL: [%d] "), iStatus.Int() ));
+     
+    User::LeaveIfError( iStatus.Int() );
+
+    if( ( iTestCombiner == NULL ) || 
+        ( iTestCombiner->iSectionParser == NULL ) )
+        {
+        User::Leave( KErrGeneral );
+        }
+        
+    TBool continueTask = EFalse;
+    
+    // Check if there is still some time for combiner pause and we need to 
+    // continue pausing
+    if(iPauseCombRemainingTime > 0)
+        {           
+        // Maximum time for one RTimer::After request                   
+        TInt maximumTime = KMaxTInt / 1000;                       
+        
+        __TRACE( KMessage, (_L("CTestRunner::RunL: Going to reissue PauseCombiner request ") ) );           
+        __TRACE( KMessage, (_L("CTestRunner::RunL: iRemainingTimeValue = %d"), iPauseCombRemainingTime ) );        
+        
+        if( iPauseCombRemainingTime < maximumTime )
+            {                           
+            iPauseCombTimer.After(iStatus, (iPauseCombRemainingTime * 1000));
+            iPauseCombRemainingTime = 0;
+            }
+        else
+            {            
+            iPauseCombRemainingTime -= maximumTime;
+            iPauseCombTimer.After(iStatus, (maximumTime * 1000));        
+            }     
+            
+        SetActive();
+        return;
+        }     
+ 
+    // Handling runner states
+    switch( iState )
+        {
+        case ERunnerWaitTimeout:
+            {
+            __TRACE( KMessage, (_L("Resume %S"), &iPausedTestCase));
+            iTestCombiner->TestModuleIf().Printf( KPrintPriExec, 
+                KExecute, _L("Resume %S"), &iPausedTestCase);
+             // Get running testcase identified with testid
+            CTestCase* testCase = iTestCombiner->GetRunningTest( iPausedTestCase ); 
+            if( testCase == NULL ) User::Leave( KErrNotFound );
+            iPausedTestCase.Zero();
+            if( testCase->Type() == CTestCase::ECaseLocal )
+                {
+                CTCTestCase* localTestCase = ( CTCTestCase* )testCase;
+                // Resume execution
+                User::LeaveIfError( localTestCase->TestExecution().Resume() );
+                continueTask = ETrue;
+                }
+            else // ECaseRemote
+                {
+                CRemoteTestCase* remoteTestCase = ( CRemoteTestCase* )testCase;
+                // Resume execution
+                if( ExecuteRemoteTestCtlL( NULL, 
+                                           remoteTestCase, 
+                                           TTCKeywords::EResume ) )
+                    {
+                    continueTask = ETrue;
+                    }
+                }               
+            }
+            break;
+        case ERunnerWaitUnset:
+            iState = ERunnerIdle;
+
+            // Check Unset event 
+            if( !CheckUnsetEvent() )
+                {
+                // Got event and unset has not completed 
+                // Should never come here
+                User::Panic( KTestRunner, KErrGeneral );
+                 }
+            break;
+                         
+        case ERunnerRunning:
+            {
+            iState = ERunnerIdle;
+            
+            // Get next execution line from configuration section
+            iEndLoopStartPos = iTestCombiner->iSectionParser->GetPosition();
+            TPtrC line;
+            if( iTestCombiner->iSectionParser->GetNextLine( line ) == KErrNone )
+                {
+                // Got new execution line 
+                __TRACE( KMessage, (_L("CTestRunner got line")));
+        
+                CStifItemParser* item = PreprocessLineL( line );
+            
+                if( item )
+                    {     
+                     // Got new execution line 
+                    CleanupStack::PushL( item ); 
+                      
+                    // Execute script line 
+                    if( ExecuteLineL( item ) )
+                        {
+                          __TRACE( KMessage, (_L("RunL: continueTask")));
+                         // Set CTestRunner active again to perform 
+                         // next execution line
+                         // from testcase section 
+                        continueTask = ETrue;
+                        }
+                    CleanupStack::PopAndDestroy( item );
+                    }
+                }
+            else 
+                {
+                // No more execution lines in testcase section
+                __TRACE( KMessage, 
+                    (_L("CTestRunner::RunL: Testcase script done (%d running)"), 
+                        iTestCombiner->iRunningTests));
+ 
+                if( ( iTestCombiner->iRunningTests == 0 ) &&
+                    iTestCombiner->iSchedulerActive )
+                    {
+                    __TRACE( KMessage, 
+                        (_L("RunL: All TestCases done, stop CActiveScheduler")));                     
+                    CActiveScheduler::Current()->Stop();
+                    iTestCombiner->iSchedulerActive = EFalse;
+                    }
+                // Now testcase section is executed, 
+                // so CTestRunner has done its job and stops
+                iState = ERunnerReady;
+
+                //If we're inside loop, then we have error
+                if(iTestCombiner->iLoopIsUsed)
+                    {
+                    __TRACE(KError, (_L("Endloop keyword not found. Cannot finish test case properly.")));
+                    iTestCombiner->iResult = KErrGeneral;
+                    }
+                }
+            }
+            break;
+        case ERunnerAllocate:
+        case ERunnerFree:
+        case ERunnerRemote:
+        default:
+            __TRACE( KError, 
+                (_L("CTestRunner::RunL: Entered in illegal state(%d)"), iState ));
+            User::Panic( KTestRunner, KErrGeneral );  
+            break;
+        }   
+    if( continueTask )
+        {
+        SetRunnerActive();
+        }
+           
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: DoCancel
+
+     Description: Derived from CActive handles the Cancel
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::DoCancel()
+    {
+    __TRACEFUNC();
+    __TRACE( KMessage, (_L("CTestRunner::DoCancel")));
+    iTestCombiner->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), _L("DoCancel"));
+    
+    iPauseCombTimer.Cancel();
+    
+    switch( iState )
+        {
+        case ERunnerWaitTimeout:
+            iPauseTimer.Cancel();
+            break;
+        case ERunnerWaitUnset:
+            break;             
+        case ERunnerRunning:
+            break;
+        case ERunnerAllocate:
+        case ERunnerFree:
+        case ERunnerRemote:
+            // Cancel remote test cases
+            break;
+        default:
+            __TRACE( KError, 
+                (_L("CTestRunner::DoCancel: Entered in illegal state(%d)"), iState ));
+            User::Panic( KTestRunner, KErrGeneral );  
+            break;
+        }                  
+    
+    // Cancel all testcases
+    CancelTestCases();
+         
+    iState = ERunnerCancel;
+      
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: RunError
+
+     Description: Derived from CActive handles errors from active handler.
+  
+     Parameters:    TInt aError: in: error from CActive
+     
+     Return Values: KErrNone: success
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestRunner::RunError( TInt aError )
+    {
+    __TRACEFUNC();
+    __TRACE( KMessage, (_L("CTestRunner::RunError %d"), aError));
+        
+    if ( iRunErrorMessage.Length() != 0 )
+    	{
+    	iTestCombiner->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), 
+	            _L("RunError : %S"), &iRunErrorMessage );  
+	    iRunErrorMessage = KNullDesC;
+    	}
+    else
+    	{
+    	iTestCombiner->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), 
+	            _L("RunError"));        	
+    	}    
+    
+    iState = ERunnerError;
+        
+    // Return error from here
+    iTestCombiner->iResult = aError;
+
+    CancelTestCases();
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: PreprocessLineL
+
+     Description: Preprocesses script line
+  
+     Parameters:  TPtrC& line: in: script line
+                  CStifItemParser*& aItem: out: New CStifItemParser for script
+                  line.
+                    
+     Return Values: HBufC* pointer if new memory that has been allocated
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/        
+CStifItemParser* CTestRunner::PreprocessLineL( TDesC& line )
+    {
+    
+    CStifItemParser* item = NULL;
+    TPtrC tmp;
+    TInt len = 0;
+        
+    // Decide how long buffer should be allocated
+    if( line.Length() < KMaxName/2 )
+        {
+        len = KMaxName;
+        }
+    else 
+        {
+        len = line.Length() + KMaxName;
+        }
+    delete iLine;
+    iLine = 0;
+    iLine = HBufC::NewL( len );
+    TPtr parsedLine( iLine->Des() );
+    len = 0;
+    
+    item = CStifItemParser::NewL( line, 0, line.Length() );
+    CleanupStack::PushL( item);
+    
+    TInt ret = item->GetString( _L(""), tmp );
+    while( ret == KErrNone )
+        {
+        len += CheckDefined( tmp );
+        if( ( parsedLine.Length() + tmp.Length() + 1 ) > parsedLine.MaxLength() )
+            {
+            // Allocate bigger buffer
+            HBufC* tmpBuf = HBufC::NewL( parsedLine.MaxLength() + KMaxName );
+            CleanupStack::PushL( tmpBuf );
+            TPtrC ptr( iLine->Des() );
+            parsedLine.Set( tmpBuf->Des() );
+            parsedLine.Copy( ptr );
+            delete iLine;
+            iLine = tmpBuf;
+            CleanupStack::Pop( tmpBuf );
+            } 
+        parsedLine.Append( tmp );        
+        parsedLine.Append( _L(" ") );        
+        ret = item->GetNextString( tmp );
+        }
+        
+    CleanupStack::PopAndDestroy( item );
+    
+    item = CStifItemParser::NewL( parsedLine, 0, parsedLine.Length() );
+    
+    return item;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: CheckDefined
+
+     Description: Check if aWord is some defined word
+  
+     Parameters:  TPtrC& aWord: inout: Parsed word, defined or original returned
+
+     Return Values: TInt: Length difference between new and old word
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestRunner::CheckDefined( TPtrC& aWord )
+    {
+    TInt len = 0;
+
+    // KLoopCounter word changing to current loop count value.
+    if( aWord == KLoopCounter )
+        {
+        iLoopCounterDes.Zero();
+        iLoopCounterDes.AppendNum( iLoopCounter );
+        len = iLoopCounterDes.Length() - aWord.Length();
+        aWord.Set( iLoopCounterDes );
+        return len;
+        }
+
+    TInt count = iTestCombiner->iDefined.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( iTestCombiner->iDefined[i]->Name() == aWord )
+            { 
+            len = iTestCombiner->iDefined[i]->Value().Length() - aWord.Length();
+            aWord.Set( iTestCombiner->iDefined[i]->Value() );
+            break;
+            }
+        }
+    return len;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteLineL
+
+     Description: Executes script line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    TTCKeywords::TKeywords aKeyword: in: keyword index
+
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteLineL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgUnknownKeyword, "Unknown or illegal keyword %S" );
+    _LIT( KErrMsgMeasurementInvalidArgument, "Measurement : Invalid argument" );
+    TBool continueTask = ETrue;
+    TPtrC tmp;
+
+    TPtrC keywordItem;
+    // Get first word from line, i.e. keyword
+    User::LeaveIfError( aItem->GetString( _L(""), keywordItem ) );
+    // Parse keyword
+    TInt keyword = TTCKeywords::Parse( keywordItem, TTCKeywords::Keyword );
+        
+    switch( keyword )
+        {
+        // Test case execution control cases
+        case TTCKeywords::EPauseCombiner:
+        	continueTask = ExecuteCombinerPauseL( aItem );
+        	break;
+        case TTCKeywords::ERun:
+            continueTask = ExecuteRunL( aItem );
+            break;
+        case TTCKeywords::EPause:
+        case TTCKeywords::EComplete:
+        case TTCKeywords::ECancel:
+        case TTCKeywords::EResume:
+            continueTask = ExecuteTestCtlL( aItem, (TTCKeywords::TKeywords)keyword );
+            break;
+
+        // Event control cases
+        case TTCKeywords::ESet:
+              continueTask = ExecuteEventSetL( aItem );
+            break;
+        case TTCKeywords::EUnset:
+              continueTask = ExecuteEventUnsetL( aItem );
+            break;
+        case TTCKeywords::ERequest:
+        case TTCKeywords::EWait:
+        case TTCKeywords::ERelease:
+            continueTask = ExecuteEventCtlL( aItem, (TTCKeywords::TKeywords)keyword );
+            break;
+        case TTCKeywords::EPrint:
+            {
+            TName buf;
+            while( aItem->GetNextString( tmp ) == KErrNone )
+                {
+                if( buf.Length() + tmp.Length() >= buf.MaxLength() )
+                    {
+                    break;
+                    }
+                buf.Append( tmp );
+                buf.Append( _L(" ") );
+                }
+
+            __TRACE( KMessage, (_L("Test: %S"), &buf ));
+            iTestCombiner->TestModuleIf().Printf( KPrintPriHigh, 
+                _L("Test"), 
+                _L("%S"), &buf);
+           }
+           break;
+        case TTCKeywords::EAllocate:
+            continueTask = ExecuteAllocateL( aItem );
+            break;
+        case TTCKeywords::EFree:
+            continueTask = ExecuteFreeL( aItem );
+            break;
+        case TTCKeywords::ERemote:
+            continueTask = ExecuteRemoteL( aItem );
+            break;
+        case TTCKeywords::ETimeout:
+        case TTCKeywords::EPriority:
+            // not used here
+            break;
+        case TTCKeywords::ECancelIfError:
+            // @js
+            iTestCombiner->iCancelIfError = ETrue;
+            break;
+        case TTCKeywords::EMeasurement:
+            TRAPD( retErr, iTestCombiner->ExecuteMeasurementL( aItem ) );
+        	if ( retErr == KErrArgument )
+        		{
+        		iRunErrorMessage = KErrMsgMeasurementInvalidArgument;
+        		}
+        	if ( retErr != KErrNone )
+        		{
+        		User::Leave( retErr );
+        		}
+            break;
+        case TTCKeywords::ELoop:
+            ExecuteLoopL( aItem );
+            iTestCombiner->iLoopIsUsed = ETrue;
+            break;
+        case TTCKeywords::EEndLoop:
+            continueTask = ExecuteEndLoopL();
+            break;
+        case TTCKeywords::ETitle:
+            // title has been handled already, this is duplicate
+        default:
+            {
+              __TRACE( KError, (_L("Unknown or illegal keyword") ) );
+            // Unknown or illegal keyword
+            iRunErrorMessage.Format( KErrMsgUnknownKeyword, &keywordItem );
+            User::Leave( KErrGeneral );
+            }
+            break;
+        }
+
+    __TRACE( KMessage, (_L("RunL: TestCase line executed")));
+
+    return continueTask;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteRunL
+
+     Description: Executes run line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteRunL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgCaseRunError, "Run : %S[case=%d] run error" );
+    __TRACE( KMessage, (_L("Run")));
+    iTestCombiner->TestModuleIf().Printf( KPrintPriExec, KExecute, _L("Run"));
+    
+    CStartInfo* startInfo = CStartInfo::NewL();
+    CleanupStack::PushL( startInfo );
+
+    ParseRunParamsL( aItem, *startInfo );
+             
+    // Start new case with configurations parsed above                
+    
+    iRunErrorMessage.Format( KErrMsgCaseRunError, &startInfo->iModule, startInfo->iCaseNum );
+    User::LeaveIfError( 
+        iTestCombiner->StartTestL( *startInfo ) );
+    iRunErrorMessage = KNullDesC;
+    
+    CleanupStack::PopAndDestroy( startInfo );
+        
+    return ETrue;
+    
+}
+
+ 
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ParseRunParamsL
+
+     Description: Parses run parameters
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    CStartInfo& aStartInfo: out: Parsed information
+     
+     Return Values: None
+     
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::ParseRunParamsL( CStifItemParser* aItem,
+                                    CStartInfo& aStartInfo )
+    {
+    _LIT( KErrMsgRunTestmoduleNameNotDefined, "Run : Testmodule name is not defined " );
+    _LIT( KErrMsgRunCfgFileNotDefined, "Run : Testmodule configuration file is not defined" );
+    _LIT( KErrMsgRunTestcaseNumberNotDefined, "Run : Testcase number is not defined or has invalid value" );
+    _LIT( KErrMsgRunCfgFileNameToLong, "Run : TestScripter test case file(config)'s name is too long. Current length[%d], allowed max length[%d]. Cannot continue" );
+    _LIT( KErrMsgRunInvalidExpectValue, "Run : Invalid expected result value" );
+    _LIT( KErrMsgRunUnknownOrIllegalCategory, "Run : Unknown or illegal result category" );
+    _LIT( KErrMsgRunInvalidTimeoutValue, "Run: Invalid testcase timeout value" );
+    _LIT( KErrMsgRunUnknowOrIllegalKeyword, "Run: Unknown or illegal keyword %S" );
+    
+    TPtrC tmp;
+    TInt ret = KErrNone;
+
+    // Get mandatory run arguments
+    // Testmodule name
+    ret = aItem->GetNextString( tmp );
+    if ( ret != KErrNone )
+    	{
+    	iRunErrorMessage = KErrMsgRunTestmoduleNameNotDefined;
+    	User::Leave( ret );
+    	}
+    
+    aStartInfo.SetModuleNameL( tmp );
+    __TRACE( KMessage, (_L("module: %S"), &aStartInfo.iModule ));
+    
+    // Configuration file
+    ret = aItem->GetNextString( tmp );
+    if ( ret != KErrNone )
+    	{
+    	iRunErrorMessage = KErrMsgRunCfgFileNotDefined;
+    	User::Leave( ret );
+    	}
+    
+    TFileName cfgFileName( tmp );
+    TStifUtil::CorrectFilePathL( cfgFileName );    
+    aStartInfo.SetConfigL( cfgFileName );
+    
+    __TRACE( KMessage, (_L("config: %S"), &aStartInfo.iConfig ));
+
+    // Check is TestScripter
+    if( aStartInfo.iModule.Find( KTestScripterName ) != KErrNotFound )
+        {
+        // TestScripter name is format: 'testscripter_testcasefilename'
+
+        TParse parse;
+        parse.Set( aStartInfo.iConfig, NULL, NULL );
+
+        // Maximum length of TestScripter's name(Max limitation from
+        // CTestModuleController creation)
+        TInt maximumLength = KMaxName - ( KTestScripterNameLength + 1 );
+
+        TFileName testScripterAndTestCaseFile; // InitL() takes TFileName
+        testScripterAndTestCaseFile.Copy( KTestScripterName );
+        testScripterAndTestCaseFile.Append( _L( "_" ) );
+        if( parse.Name().Length() < maximumLength )
+            {
+            testScripterAndTestCaseFile.Append( parse.Name() );
+            }
+        else
+            {
+            __TRACE( KInit, ( CStifLogger::ERed,
+                _L( "TestScripter test case file(config)'s name is too long. Current length[%d], allowed max length[%d]. Cannot continue" ),
+                parse.Name().Length(), maximumLength ) );
+            iRunErrorMessage.Format( KErrMsgRunCfgFileNameToLong, parse.Name().Length(), maximumLength );
+            User::Leave( KErrArgument );
+            }
+// ----
+        aStartInfo.DeleteModuleName(); // Delete old name buffer for new one
+        aStartInfo.SetModuleNameL( testScripterAndTestCaseFile );
+        }
+
+    // Testcase number
+    ret = aItem->GetInt( tmp, aStartInfo.iCaseNum );
+    if ( ret != KErrNone )
+    	{
+    	iRunErrorMessage = KErrMsgRunTestcaseNumberNotDefined;
+    	User::Leave( ret );
+    	}
+    
+    __TRACE( KMessage, (_L("testcasenum: %d"), aStartInfo.iCaseNum ) );
+     
+    // Set mode of item parser to be able to read titles with spaces inside
+    aItem->SetParsingType(CStifItemParser::EQuoteStyleParsing);
+
+    // Get optional run arguments
+    while( aItem->GetNextString( tmp ) == KErrNone )
+        {
+        TPtrC val;   
+        TPtrC arg;
+        ParseOptArgL( tmp, arg, val );
+        CheckDefined( val );
+              
+        // Parse optional argument
+        switch( TTCKeywords::Parse( arg, TTCKeywords::RunOptArg ) )
+            {
+            case TTCKeywords::EExpect:
+                {
+                TLex ptr( val );
+                ret = ptr.Val( aStartInfo.iExpectedResult );
+                if ( ret != KErrNone )
+                	{
+                	iRunErrorMessage = KErrMsgRunInvalidExpectValue;
+                    User::Leave( ret );
+                	}
+                __TRACE( KMessage, (_L("expect=%d"), aStartInfo.iExpectedResult));
+                }
+                break;
+            case TTCKeywords::ETestid:
+				{
+                aStartInfo.SetTestIdL( val );
+                __TRACE( KMessage, (_L("TestId=%S"), &val));
+				}
+                break;
+            case TTCKeywords::EIni:
+				{
+                __TRACE( KMessage, (_L("ini=%S"), &val));
+	        	TFileName iniFileName( val );
+	        	TStifUtil::CorrectFilePathL( iniFileName );
+	            aStartInfo.SetIniFileL( iniFileName );
+				}
+                break;
+            case TTCKeywords::ECategory:
+				{
+                __TRACE( KMessage, (_L("category=%S"), &val));
+                aStartInfo.iCategory = TTCKeywords::GetResultCategory( val );
+                if( aStartInfo.iCategory == TFullTestResult::ECaseOngoing )
+                    {
+                    __TRACE( KError, (_L("Unknown or illegal result category")));
+                    //Unknown or illegal category
+                    iRunErrorMessage = KErrMsgRunUnknownOrIllegalCategory;
+                    User::Leave( KErrGeneral );
+                    }
+				}
+                break;
+            case TTCKeywords::ECaseTimeout:
+                {
+                TLex ptr( val );
+                ret = ptr.Val( aStartInfo.iTimeout );
+                if ( ret != KErrNone )
+                	{
+                	iRunErrorMessage = KErrMsgRunInvalidTimeoutValue;
+                    User::Leave( ret );
+                	}
+                __TRACE( KMessage, (_L("timeout=%d"), aStartInfo.iTimeout ) );
+                }
+                break;
+           	case TTCKeywords::ECaseTitle:
+           	    {
+                __TRACE( KMessage, (_L("case title=%S"), &val));
+                aStartInfo.SetTitleL(val);
+                break;
+           	    }
+            case TTCKeywords::EArgs:
+                {
+                __TRACE( KMessage, (_L("case arguments=%S"), &val));
+                aStartInfo.SetTestCaseArgumentsL( val );
+                }
+                break;				
+            default:
+				{
+                __TRACE( KError, (_L("Unknown or illegal keyword")));
+                //Unknown or illegal keyword
+                iRunErrorMessage.Format( KErrMsgRunUnknowOrIllegalKeyword, &arg );
+                User::Leave( KErrGeneral );
+				}
+            }
+        }             
+    } 
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteTestCtlL
+
+     Description: Executes script line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    TTCKeywords::TKeywords aKeyword: in: keyword index
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteTestCtlL( CStifItemParser* aItem, 
+                                    TTCKeywords::TKeywords aKeyword )
+    {
+    _LIT( KErrMsgTestIdNotDefined, "%S : testid is not defined" );
+    _LIT( KErrMsgTestCaseNotFound, "%S : Test case %S not found" );
+    TBool continueTask = ETrue;
+    TPtrC tmp;
+    
+    TInt ret = KErrNone;
+
+	TPtrC keywordStr = TTCKeywords::Keyword( aKeyword );
+
+    // Parse testid
+    ret = aItem->GetNextString( tmp );
+    if( ret != KErrNone )
+    	{
+    	iRunErrorMessage.Format( KErrMsgTestIdNotDefined, &keywordStr );
+        User::Leave( ret );            	
+    	}
+
+    // Get testcase identified with testid
+    CTestCase* testCase = iTestCombiner->GetTest( tmp ); 
+    if( testCase == NULL )
+        {
+        __TRACE( KError, (_L("ExecuteTestCtlL: Test case %S not found"), 
+            &tmp));
+        iRunErrorMessage.Format( KErrMsgTestCaseNotFound, &keywordStr, &tmp );
+        User::Leave( KErrNotFound );
+        }  
+                              
+    switch( aKeyword )
+        {
+        // Test case execution control cases
+        case TTCKeywords::EPause:
+            continueTask = ExecutePauseL( aItem, testCase );
+            break;
+        case TTCKeywords::EComplete:
+            continueTask = ExecuteCompleteL( aItem, testCase );
+            break;
+        case TTCKeywords::ECancel:
+            __TRACE( KMessage, (_L("Cancel %S"), &tmp));
+            iTestCombiner->TestModuleIf().Printf( KPrintPriExec, 
+                KExecute, _L("Cancel %S"), &tmp);
+            if( testCase->Type() == CTestCase::ECaseRemote )
+                {
+                continueTask = 
+                    ExecuteRemoteTestCtlL( aItem, testCase, aKeyword ); 
+                }
+            else 
+                {
+                if( testCase->State() != CTestCase::ETestCaseRunning )
+                    {
+                    __TRACE( KMessage, (_L("Cancelled task (%S) not running (%i)"), 
+                        &tmp, testCase->State() )); 
+                    User::Leave( KErrNotFound );                   
+                    }
+                CTCTestCase* test = ( CTCTestCase* )testCase;
+                // Cancel local testcase
+                test->TestExecution().CancelAsyncRequest( ETestExecutionRunTestCase );
+                }
+            break;
+        case TTCKeywords::EResume:
+            {
+            __TRACE( KMessage, (_L("Resume %S"), &tmp));
+            iTestCombiner->TestModuleIf().Printf( KPrintPriExec, 
+                KExecute, _L("Resume %S"), &tmp);
+            if( testCase->Type() == CTestCase::ECaseRemote )
+                {
+                continueTask = 
+                    ExecuteRemoteTestCtlL( aItem, testCase, aKeyword ); 
+                }
+            else 
+                {
+                if( testCase->State() != CTestCase::ETestCaseRunning )
+                    {
+                    __TRACE( KMessage, (_L("Resumed task (%S) not running (%i)"), 
+                        &tmp, testCase->State() )); 
+                    User::Leave( KErrNotFound );                   
+                    }
+                CTCTestCase* test = ( CTCTestCase* )testCase;
+                // Resume execution
+                User::LeaveIfError( test->TestExecution().Resume() );
+                }
+            }
+            break;
+            
+        default:
+            // Should never come here
+            User::Leave( KErrGeneral );
+            break;
+        }      
+    
+    return continueTask;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteCombinerPauseL
+
+     Description: Executes causes pause in TestCombiner
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                         
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteCombinerPauseL( CStifItemParser* aItem )
+{
+	_LIT( KErrMsgPauseTimeoutNotDefined, "PauseCombiner : No timeout value given or value has invalid format" );
+	_LIT( KErrMsgPauseTimeoutNotPositive, "PauseCombiner : Timeout value can't be <0" );
+
+    TBool continueTask = EFalse;
+    TInt pauseTime;
+    TInt ret = KErrNone;
+    
+    // Parse testid
+    ret = aItem->GetNextInt( pauseTime );
+    if ( ret != KErrNone )
+    	{
+    	iRunErrorMessage = KErrMsgPauseTimeoutNotDefined;
+        User::Leave( ret );    	
+    	}
+
+    if( pauseTime < 0 )
+        {
+        __TRACE( KError, (_L("CTestRunner::ExecuteCombinerPauseL: Given pause value < 0")));
+        iRunErrorMessage = KErrMsgPauseTimeoutNotPositive;
+        User::Leave( KErrArgument );
+        }    
+    
+    
+    // Maximum time for one RTimer::After request
+    TInt maximumTime = KMaxTInt / 1000;
+
+    // Check if pause value is suitable for RTimer::After
+    if(pauseTime < maximumTime)
+        {
+        iPauseCombTimer.After(iStatus, pauseTime * 1000);
+        iPauseCombRemainingTime = 0;
+        }
+    else
+        {
+        // Given pause value after multiplication with 1000 is
+        // larger than KMaxTInt, so we need to split it and 
+        // re-request After with remaining value from RunL
+
+        iPauseCombRemainingTime = pauseTime - maximumTime;
+        iPauseCombTimer.After(iStatus, maximumTime * 1000);
+        }
+
+    SetActive();
+
+    __TRACE(KMessage, (_L("Executing pause, time=[%d]"), pauseTime));
+    
+    iState = ERunnerRunning;
+    
+    return continueTask;
+}
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecutePauseL
+
+     Description: Executes pause line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    CTestCase* aTestcase: in: test case
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecutePauseL( CStifItemParser* aItem,
+                                    CTestCase* aTestcase )
+    {
+    _LIT( KErrMsgPauseUnknownKeyword, "Pause : Unknown or illegal keyword %S" );
+    _LIT( KErrMsgPauseTimeInvalidValue, "Pause : Pause time is not defined or has invalid value" );
+    _LIT( KErrMsgPauseTimeNotPositive, "Pause : Pause time can't be <0" );
+    TBool continueTask = ETrue;
+
+    // Get optional pause arguments
+    TPtrC tmp;
+    iPauseTime = 0;
+    while( aItem->GetNextString( tmp ) == KErrNone )
+        {
+        TPtrC val;   
+        TPtrC arg;
+        ParseOptArgL( tmp, arg, val );
+        CheckDefined( val );
+              
+        // Parse optional argument
+        switch( TTCKeywords::Parse( arg, TTCKeywords::PauseOptArg ) )
+            {
+            case TTCKeywords::ETime:
+                {
+                TLex ptr( val );
+                TInt ret = KErrNone;
+                ret = ptr.Val( iPauseTime );
+                if ( ret != KErrNone )
+                	{
+                	iRunErrorMessage = KErrMsgPauseTimeInvalidValue;
+                	User::Leave( ret );
+                	}                
+                if ( iPauseTime < 0 )
+                	{
+                	iRunErrorMessage = KErrMsgPauseTimeNotPositive;
+                	User::Leave( KErrArgument );                	
+                	}
+                __TRACE( KMessage, (_L("time=%d"), iPauseTime ));
+                }
+                break;
+            default:
+                __TRACE( KError, (_L("Unknown or illegal keyword")));
+                //Unknown or illegal keyword
+                iRunErrorMessage.Format( KErrMsgPauseUnknownKeyword, &arg );
+                User::Leave( KErrGeneral );
+            }
+        }             
+    
+    // Store paused testcase id if timeout was given as pause argument 
+    if( iPauseTime != 0 )
+        {
+        iPausedTestCase.Copy( aTestcase->TestId() );
+        }
+    
+    if( aTestcase->Type() == CTestCase::ECaseRemote )
+        {
+        return ExecuteRemoteTestCtlL( aItem, aTestcase, TTCKeywords::EPause );
+        }
+    if( aTestcase->State() != CTestCase::ETestCaseRunning )
+        {
+        __TRACE( KMessage, (_L("Paused task (%S) not running (%i)"), 
+            &aTestcase->TestId(), aTestcase->State() )); 
+        User::Leave( KErrNotFound );                   
+        }
+    CTCTestCase* test = ( CTCTestCase* )aTestcase;
+    
+    // Pause execution
+    User::LeaveIfError( test->TestExecution().Pause() );
+    
+    // Resume paused case if timeout was given 
+    if( iPauseTime != 0 )
+        {
+        continueTask = EFalse;
+        iState = ERunnerWaitTimeout;
+        iPauseTimer.After( iStatus, iPauseTime*1000 );
+        SetActive();         
+        }
+        
+    return continueTask;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteCompleteL
+
+     Description: Executes complete line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    CTestCase* aTestcase: in: test case
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteCompleteL( CStifItemParser* /* aItem */, 
+                                     CTestCase* aTestcase )
+    {
+    TBool ret = ETrue;
+    
+    if( aTestcase->State() == CTestCase::ETestCaseCompleted )
+         {
+         // Requested testcase is completed already,
+         // proceed testcase execution
+          __TRACE( KMessage, (_L("Already completed")));
+         }
+    else if( aTestcase->State() == CTCTestCase::ETestCaseRunning )
+         {
+         // Wait testcase to complete                    
+         iTestCombiner->iWaitTestCase.Copy( aTestcase->TestId() );
+         // Stop testcase execution until testcase completed 
+         ret = EFalse;
+         iState = ERunnerWaitTestCase;
+         }
+    else
+        {
+        // This should newer happen
+        User::Leave( KErrGeneral );
+        }
+        
+    return ret;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteEventSetL
+
+     Description: Executes event set line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteEventSetL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgSetEventNameNotDefined, "Set : event name is not defined" );
+    _LIT( KErrMsgSetUnknownOrIllegalKeyword, "Set :Unknown or illegal keyword %S" );
+    _LIT( KErrMsgSetStateInvalidValue, "Set : State value is not defined or has invalid format" );
+    TPtrC tmp;
+    TPtrC eventName;
+    TInt ret = KErrNone;
+    
+    // Get event name
+    ret = aItem->GetNextString( eventName );
+    if( ret != KErrNone )
+    	{
+    	iRunErrorMessage = KErrMsgSetEventNameNotDefined;
+        User::Leave( ret );        
+    	}
+    __TRACE( KMessage, (_L("Set %S"), &eventName));
+    iTestCombiner->TestModuleIf().Printf( KPrintPriExec, KExecute, 
+        _L("Set %S"), &eventName);
+    iEvent.SetName( eventName );
+    iEvent.SetType( TEventIf::ESetEvent );
+
+    // Get optional set arguments
+    while( aItem->GetNextString( tmp ) == KErrNone )
+        {
+        TPtrC val;   
+        TPtrC arg;
+        ParseOptArgL( tmp, arg, val );
+        CheckDefined( val );
+              
+        // Parse optional set argument
+        switch( TTCKeywords::Parse( arg, TTCKeywords::EventOptArg ) )
+            {
+            case TTCKeywords::EState:
+                {
+                TLex ptr( val );
+                TInt tmpVal = 0;
+                ret = ptr.Val( tmpVal );
+                if ( ret != KErrNone )
+                	{
+                	iRunErrorMessage = KErrMsgSetStateInvalidValue;
+                	User::Leave( ret );
+                	}
+                
+                // Only value 1 has special meaning, others are ignored
+                if( tmpVal == 1 )
+                    {
+                     __TRACE( KMessage, (_L("State event")));
+                     iEvent.SetEventType( TEventIf::EState );
+                    }
+                }
+                break;
+            default:
+                __TRACE( KError, (_L("Unknown or illegal keyword")));
+                //Unknown or illegal keyword
+                iRunErrorMessage.Format( KErrMsgSetUnknownOrIllegalKeyword, &arg );
+                User::Leave( KErrGeneral );
+            }
+        }      
+
+    // Set event
+    iTestCombiner->TestModuleIf().Event( iEvent, iStatus );
+    iState = ERunnerRunning;
+    SetActive();
+            
+    return EFalse;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteEventUnsetL
+
+     Description: Executes event unset line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteEventUnsetL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgUnsetEventNameNotDefined, "Unset : Event name is not defined" );
+    TPtrC eventName;
+    TInt ret = KErrNone;
+    // Get event name
+    ret = aItem->GetNextString( eventName );
+    if ( ret != KErrNone )
+    	{
+    	iRunErrorMessage = KErrMsgUnsetEventNameNotDefined;
+    	User::Leave( ret );        
+    	}
+    
+    __TRACE( KMessage, (_L("Unset %S"), &eventName));
+    iTestCombiner->TestModuleIf().Printf( KPrintPriExec, KExecute, 
+        _L("Unset %S"), &eventName);
+    iEvent.Set( TEventIf::EUnsetEvent, eventName, TEventIf::EState );
+    
+    // Check if trying to unset an event that is requested 
+    // by testcombiner (otherwise testcombiner would deadlock)
+    TInt count = iTestCombiner->iEventArray.Count();
+    TInt ind = 0;
+    for(; ind < count; ind++ )
+        {
+        if( eventName == iTestCombiner->iEventArray[ind]->Name() )
+            {
+            User::Leave( KErrInUse );
+            }
+        }
+
+    // Check if some testmodule below 
+    // has event request pending
+    if( iTestCombiner->UnsetEvent( iEvent, 
+                                   iStatus ) == EFalse )
+        {
+        // If they haven't requested event,
+        // then check others above
+        iTestCombiner->TestModuleIf().Event( iEvent, iStatus );
+        iState = ERunnerRunning;
+        SetActive();
+            
+        }
+    else
+        {
+        // Some testmodule below has requested the event
+        // Wait unset to complete
+        SetActive();
+        __TRACE( KPrint, ( _L("Unset: Start" ) ) );
+        iState = ERunnerWaitUnset;
+        // Stop execution until unset has completed
+        }
+    return EFalse;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteLineL
+
+     Description: Executes script line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    TTCKeywords::TKeywords aKeyword: in: keyword index
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteEventCtlL( CStifItemParser* aItem, 
+                                     TTCKeywords::TKeywords aKeyword )
+    {
+    _LIT( KErrMsgEventNameNotDefined, "%S : Event name is not defined" );
+    _LIT( KErrMsgEequestEventAlreadyExist, "Request : Requested event %S already exists" );
+    _LIT( KErrMsgWaitEventNotRequested, "Wait :Waited event %S is not requested" );
+    _LIT( KErrMsgReleaseEventNotRequested, "Release : Released event %S is not requested" );
+    
+    TBool continueTask = ETrue;
+    TPtrC eventName;
+    TInt ret = KErrNone;
+	TPtrC keywordStr = TTCKeywords::Keyword( aKeyword );
+    // Get event name
+    ret = aItem->GetNextString( eventName );
+    if ( ret != KErrNone )
+    	{
+    	iRunErrorMessage.Format( KErrMsgEventNameNotDefined, &keywordStr );
+    	User::Leave( ret );
+    	}
+    
+    TInt count = iTestCombiner->iEventArray.Count();
+    TInt ind = 0;
+    for(; ind < count; ind++ )
+        {
+        if( eventName == iTestCombiner->iEventArray[ind]->Name() )
+            {
+            break;
+            }
+        }
+                    
+    switch( aKeyword )
+        {
+        case TTCKeywords::ERequest:
+            {
+            __TRACE( KMessage, (_L("Request %S"), &eventName));
+            iTestCombiner->TestModuleIf().Printf( KPrintPriExec, 
+                KExecute, _L("Request %S"), &eventName);
+                
+            // Check that event is not already requested           
+            if( ind < count )
+                {
+                __TRACE( KError, (_L("Requested event %S already exists"), 
+                    &eventName));
+                iRunErrorMessage.Format( KErrMsgEequestEventAlreadyExist, &eventName );
+                User::Leave( KErrAlreadyExists );
+                }
+                
+            // Add event to event array
+            iEvent.SetName( eventName );
+            iEvent.SetType( TEventIf::EReqEvent );
+            TEventTc* event = new (ELeave) TEventTc( iTestCombiner->iLog );
+            CleanupStack::PushL( event );
+            event->Copy( iEvent );
+            User::LeaveIfError( iTestCombiner->iEventArray.Append( event ));
+            if( iTestCombiner->iLoopIsUsed )
+                {
+                User::LeaveIfError( iTestCombiner->iLoopAllocationArray.Append( event ) );
+                }
+            CleanupStack::Pop( event );
+            
+            // Request event
+            iTestCombiner->TestModuleIf().Event( iEvent, iStatus );
+            iState = ERunnerRunning;
+            SetActive();
+            continueTask = EFalse;
+            }
+            break;
+        case TTCKeywords::EWait:
+              {
+            __TRACE( KMessage, (_L("Wait %S"), &eventName));
+            iTestCombiner->TestModuleIf().Printf( KPrintPriExec, KExecute, 
+                _L("Wait %S"), &eventName);
+
+            // Check that event is requested           
+            if( ind == count )
+                {
+                __TRACE( KError, (_L("Waited event %S is not requested"), 
+                    &eventName));
+                iRunErrorMessage.Format( KErrMsgWaitEventNotRequested, &eventName );
+                User::Leave( KErrNotFound );
+                }            
+            iEvent.SetName( eventName );    
+            iEvent.SetType( TEventIf::EWaitEvent );     
+            // Wait event
+            iTestCombiner->TestModuleIf().Event( iEvent, iStatus );
+            iState = ERunnerRunning;
+            SetActive();
+            continueTask = EFalse;
+            }
+            break;
+        case TTCKeywords::ERelease:
+            {
+            __TRACE( KMessage, (_L("Release %S"), &eventName));
+            iTestCombiner->TestModuleIf().Printf( KPrintPriExec, KExecute, 
+                _L("Release %S"), &eventName);
+            // Check that event is requested           
+            if( ind == count )
+                {
+                __TRACE( KError, (_L("Released event %S is not requested"), 
+                    &eventName));
+                iRunErrorMessage.Format( KErrMsgReleaseEventNotRequested, &eventName );
+                User::Leave( KErrNotFound );
+                }            
+            // Remove event from array
+            TEventTc* event = iTestCombiner->iEventArray[ind];
+            iTestCombiner->iEventArray.Remove( ind );
+            delete event;
+            iEvent.SetName( eventName );
+            iEvent.SetType( TEventIf::ERelEvent );
+            
+            // Release event
+            iTestCombiner->TestModuleIf().Event( iEvent, iStatus );
+            iState = ERunnerRunning;
+            SetActive();
+            continueTask = EFalse;
+            }
+            break;
+        default:
+            {
+              __TRACE( KError, (_L("Illegal keyword") ) );
+            
+            // Unknown or illegal keyword
+            User::Leave( KErrGeneral );
+            }
+            break;
+     
+        }
+    return continueTask;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteAllocateL
+
+     Description: Executes allocate line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteAllocateL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgAllocateSlaveTypeNotDefined, "Allocate : Slave type was not given for allocate" );
+    _LIT( KErrMsgAllocateSlaveNameNotDefined, "Allocate : Slave name is not defined" );
+    _LIT( KErrMsgAllocateSlaveAlreadyAllocated, "Allocate : Slave with name %S already allocated" );
+    __TRACE( KMessage, (_L("Allocate")));
+       
+    TPtrC type;
+    TPtrC name;
+    // Get slave type
+    TInt ret = aItem->GetNextString( type );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, (_L("Slave type was not given for allocate")));
+        iRunErrorMessage = KErrMsgAllocateSlaveTypeNotDefined;
+        User::Leave( KErrArgument );
+        }
+    
+    // Get slave name
+    ret = aItem->GetNextString( name );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, (_L("Slave name was not given for allocate")));
+        iRunErrorMessage = KErrMsgAllocateSlaveNameNotDefined;
+        User::Leave( KErrArgument );
+        }
+
+    iTestCombiner->TestModuleIf().Printf( KPrintPriExec, KExecute, 
+        _L("Allocate %S"), &name );
+        
+    __TRACE( KMessage, (_L("Allocate %S [name: %S]"), &type, &name));
+    
+    if( iTestCombiner->GetSlave( name ) )
+        {
+        __TRACE( KError, (_L("Slave with name %S already allocated"), 
+            &name ) );
+        iRunErrorMessage.Format( KErrMsgAllocateSlaveAlreadyAllocated, &name );
+        User::Leave( KErrAlreadyExists );
+        } 
+        
+    CSlaveInfo* slave = CSlaveInfo::NewL( name, KRemoteProtocolMasterId );
+    CleanupStack::PushL( slave );
+    User::LeaveIfError( iTestCombiner->iSlaveArray.Append( slave ) );
+    if( iTestCombiner->iLoopIsUsed )
+        {
+        User::LeaveIfError( iTestCombiner->iLoopAllocationArray.Append( slave ) );
+        }
+    CleanupStack::Pop( slave );
+
+    CStifTFwIfProt* req = CStifTFwIfProt::NewL();
+    CleanupStack::PushL( req );
+    req->CreateL();
+    
+    // Reserve message
+    User::LeaveIfError(
+        req->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgReserve ) );
+    // Srcid. i.e. master id
+    User::LeaveIfError(
+        req->AppendId( slave->iMasterId ) );
+    // DstId, broacast id
+    User::LeaveIfError(
+        req->AppendId( slave->iSlaveDevId ) );
+    // Slave type
+    User::LeaveIfError( req->Append( type ) );
+
+    User::LeaveIfError( 
+        iTestCombiner->TestModuleIf().RemoteSend( req->Message() ) );
+        
+    iState = ERunnerAllocate;
+    slave->iState = CSlaveInfo::ESlaveReserveSent;
+
+    // Start timer    
+    iRemoteTimer->SetTimerActive( iTestCombiner->iRemoteTimeout );
+
+    CleanupStack::PopAndDestroy( req );
+
+    return EFalse;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteFreeL
+
+     Description: Executes free line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteFreeL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgFreeSlaveNameNotDefined, "Free : Slave name is not defined" );
+    _LIT( KErrMsgFreeSlaveNotFound, "Free : Slave %S not found" );
+    _LIT( KErrMsgFreeSlaveReserved, "Free : Slave %S in illegal state %d, cannot be released" );
+    __TRACE( KMessage, (_L("Free")));
+    
+    TPtrC name;    
+    // Get slave name
+    TInt ret = aItem->GetNextString( name );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, (_L("Slave name was not given for free")));
+        iRunErrorMessage = KErrMsgFreeSlaveNameNotDefined;
+        User::Leave( KErrArgument );
+        }
+
+    iTestCombiner->TestModuleIf().Printf( KPrintPriExec, KExecute, 
+        _L("Free %S"), &name );
+        
+    __TRACE( KMessage, (_L("Free %S"), &name ) );
+    
+    CSlaveInfo* slave = iTestCombiner->GetSlave( name );
+    if( slave == NULL )
+        {
+        __TRACE( KError, (_L("Slave %S not found"), &name ));
+        iRunErrorMessage.Format( KErrMsgFreeSlaveNotFound, &name );
+        User::Leave( KErrNotFound );
+        }
+    if( slave->iState != CSlaveInfo::ESlaveReserved )
+        {
+        __TRACE( KError, (_L("Slave %S in illegal state %d, cannot be released"), 
+            &name, slave->iState ));
+        iRunErrorMessage.Format( KErrMsgFreeSlaveReserved, &name, slave->iState );
+        User::Leave( KErrGeneral );
+        } 
+        
+    ExecuteFreeL( slave );
+    
+    return EFalse;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteFreeL
+
+     Description: Executes free line
+  
+     Parameters:    CSlaveInfo* aSlave: in: slave info
+     
+     Return Values: None
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::ExecuteFreeL( CSlaveInfo* aSlave )
+    {    
+    
+    CRemoteTestCase* testCase = 
+        iTestCombiner->GetRemoteRunningTestOnSlave( aSlave->iSlaveDevId );
+          
+    if( testCase )
+        {
+        __TRACE( KMessage, 
+            (_L("Postpone free until testcases completed")));
+        // Test cases still running on slave,
+        // Free slave after test case has completed
+        testCase->iFreeSlave = ETrue;
+        return;
+        }
+    
+    CStifTFwIfProt* req = CStifTFwIfProt::NewL();
+    CleanupStack::PushL( req );
+    req->CreateL();
+    
+    // Release message
+    User::LeaveIfError( 
+        req->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRelease ) );
+    // Srcid. i.e. master id
+    User::LeaveIfError( 
+        req->AppendId( aSlave->iMasterId ) );
+    // DstId is device broadcast
+    User::LeaveIfError( 
+        req->AppendId( SETID( DEVID( aSlave->iSlaveDevId ), 0 ) ) );
+    
+    User::LeaveIfError( 
+        iTestCombiner->TestModuleIf().RemoteSend( req->Message() ) );
+        
+    iState = ERunnerFree;
+    aSlave->iState = CSlaveInfo::ESlaveReleaseSent;
+
+    // Start timer    
+    iRemoteTimer->SetTimerActive( iTestCombiner->iRemoteTimeout );
+   
+    CleanupStack::PopAndDestroy( req );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteRemoteL
+
+     Description: Executes remote line
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteRemoteL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgRemoteSlaveNameNotDefined, "Remote : Slave name is not defined" );
+    _LIT( KErrMsgRemoteSlaveNotFound, "Remore : Slave %S not found" );
+    _LIT( KErrMsgRemoteIllegalState, "Remote : Slave %S in illegal state %d, cannot send remote call" );
+    _LIT( KErrMsgRemoteCommandNotDefined, "Slave command name was not given for remote" );
+    TPtrC name;    
+    TPtrC command;    
+    // Get slave name
+    TInt ret = aItem->GetNextString( name );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, (_L("Slave name was not given for remote")));
+        iRunErrorMessage = KErrMsgRemoteSlaveNameNotDefined;
+        User::Leave( KErrArgument );
+        }
+        
+    __TRACE( KMessage, (_L("Remote command to %S"), &name));
+    
+    CSlaveInfo* slave = iTestCombiner->GetSlave( name );
+    if( slave == NULL )
+        {
+        __TRACE( KError, (_L("Slave %S not found"), &name ));
+        iRunErrorMessage.Format( KErrMsgRemoteSlaveNotFound, &name );
+        User::Leave( KErrArgument );
+        }
+    if( slave->iState != CSlaveInfo::ESlaveReserved )
+        {
+        __TRACE( KError, (_L("Slave %S in illegal state %d, cannot send remote call"), 
+            &name, slave->iState ));
+        iRunErrorMessage.Format( KErrMsgRemoteIllegalState, &name, slave->iState );
+        User::Leave( KErrNotReady );
+        } 
+        
+    // Get remote command name
+    ret = aItem->GetNextString( command );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, (_L("Slave command name was not given for remote")));
+        iRunErrorMessage = KErrMsgRemoteCommandNotDefined;
+        User::Leave( KErrArgument );
+        }
+
+    iTestCombiner->TestModuleIf().Printf( KPrintPriExec, KExecute, 
+        _L("remote %S %S"), &name, &command );
+
+    __TRACE( KPrint, (_L("remote %S %S"), &name, &command ) );
+
+    // Parse command name
+    TInt key = TTCKeywords::Parse( command, TTCKeywords::Keyword );    
+    TBool continueTask = ETrue;
+    
+    switch( key )
+        {
+        // Test case starting
+        case TTCKeywords::ERun:
+            continueTask = ExecuteRemoteRunL( aItem, slave );
+            break;
+                   
+        // Event control cases
+        case TTCKeywords::ERequest:
+        case TTCKeywords::EWait:
+        case TTCKeywords::ERelease:
+            continueTask = ExecuteRemoteEventCtlL( aItem, slave, key );
+            break;
+
+        case TTCKeywords::ESet:
+        case TTCKeywords::EUnset:
+            continueTask = ExecuteRemoteSetUnsetEventL(aItem, slave, key);
+			break;
+        // asynchronous 'sendreceive'
+        case TTCKeywords::ESendReceive:
+            continueTask = ExecuteRemoteSendReceiveL( aItem, slave );
+            break;
+
+        default:
+            // Some unknown remote command, forward as such 
+            continueTask = ExecuteRemoteUnknownL( aItem, slave, command );
+            break;
+        }
+    
+    return continueTask;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteRemoteRunL
+
+     Description: Handles remote run 
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    CSlaveInfo* aSlave: in: slave info
+                    HBufC *aSetUnsetEvent: in: data needed for startInfo
+                    TInt aCaseNumber: in: data needed for startInfo
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution and wait response
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteRemoteRunL( CStifItemParser* aItem,
+                                        CSlaveInfo* aSlave,
+                                        HBufC *aSetUnsetEvent,
+                                        TInt aCaseNumber )
+    {
+    
+    CStifTFwIfProt* req = CStifTFwIfProt::NewL();
+    CleanupStack::PushL( req );
+    req->CreateL();
+    
+    CStartInfo* startInfo = CStartInfo::NewL();
+    CleanupStack::PushL( startInfo );
+    //if aSetUnsetEvent is given, then get start info from this argument
+    if(aSetUnsetEvent != NULL)
+    	{
+    	TBuf<10> tmpModuleName;
+    	tmpModuleName.Copy(_L("suevent"));
+    	startInfo->SetModuleNameL(tmpModuleName);
+    	startInfo->SetConfigL(*aSetUnsetEvent);
+    	startInfo->iCaseNum = aCaseNumber;
+    	}
+    else
+    	{
+    ParseRunParamsL( aItem, *startInfo );   
+}
+    
+    if( iTestCombiner->GetTest( startInfo->iTestId ) )
+        {
+        /*        
+        __TRACE( KError, (_L("´Slave test running already with testid %S"), 
+            &startInfo->iTestId  ) );
+        */
+        User::Leave( KErrAlreadyExists );
+        }
+        
+    CRemoteTestCase* remote = 
+        CRemoteTestCase::NewL( iTestCombiner, 
+                               startInfo->iTestId,
+                               startInfo->iExpectedResult,
+                               startInfo->iCategory ); 
+    
+    CleanupStack::PushL( remote );
+        
+    // Remote message
+    User::LeaveIfError( 
+        req->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote ) );
+    // Srcid. i.e. master id
+    User::LeaveIfError( req->AppendId( aSlave->iMasterId ) );
+    // DstId is device broadcast
+    User::LeaveIfError( 
+        req->AppendId( SETID( DEVID( aSlave->iSlaveDevId ), 0 ) ) );
+    // Run command
+    User::LeaveIfError( 
+        req->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRun ) );
+    // Run parameters
+    User::LeaveIfError(
+        req->Append( CStifTFwIfProt::RunParams, 
+                CStifTFwIfProt::ERunModule, 
+                startInfo->iModule ) );
+    User::LeaveIfError(
+        req->Append( CStifTFwIfProt::RunParams, 
+                CStifTFwIfProt::ERunTestcasenum, 
+                startInfo->iCaseNum ));
+    if( startInfo->iIniFile.Length() > 0 )
+        {
+        // Initialization file
+        __TRACE( KMessage, (_L("ini: %S"), &startInfo->iIniFile ));     
+        User::LeaveIfError(
+            req->Append( CStifTFwIfProt::RunParams, 
+                    CStifTFwIfProt::ERunInifile, 
+                    startInfo->iIniFile ) );
+        }
+    if( startInfo->iConfig.Length() > 0 )
+        {
+        // Initialization file
+        __TRACE( KMessage, (_L("config: %S"), &startInfo->iConfig ));     
+        User::LeaveIfError(
+            req->Append( CStifTFwIfProt::RunParams, 
+                    CStifTFwIfProt::ERunTestcasefile, 
+                    startInfo->iConfig ));
+        } 
+    //Title (must be given between quotation marks in case of any spaces inside
+    if( startInfo->iTitle.Length() > 0 )
+        {
+        __TRACE(KMessage, (_L("title: %S"), &startInfo->iTitle));
+        TName tit;
+        tit.Format(_L("\"title=%S\""), &startInfo->iTitle);
+        User::LeaveIfError(req->Append(tit));
+        }
+    
+    User::LeaveIfError(
+        iTestCombiner->TestModuleIf().RemoteSend( req->Message() ) );
+        
+    remote->iRemoteState = CRemoteTestCase::ECaseRunSent;
+    remote->iSlaveId = aSlave->iSlaveDevId;
+    remote->StartL();
+    User::LeaveIfError( iTestCombiner->iTestCases.Append( remote ) );
+    if( iTestCombiner->iLoopIsUsed )
+        {
+        User::LeaveIfError( iTestCombiner->iLoopAllocationArray.Append( remote ) );
+        }
+    CleanupStack::Pop( remote );
+    
+    CleanupStack::PopAndDestroy( startInfo );
+    
+    iTestCombiner->iRunningTests++;
+    
+    // Start timer    
+    iRemoteTimer->SetTimerActive( iTestCombiner->iRemoteTimeout );
+
+    iState = ERunnerRemote;
+
+    CleanupStack::PopAndDestroy( req );
+
+    return EFalse;
+         
+    }
+    
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteRemoteTestCtlL
+
+     Description: Handles remote testcase controlling
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    CTestCase* aTestCase: in: test case
+                    TInt aCmd: in: remote command 
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution and wait response
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteRemoteTestCtlL( CStifItemParser* /* aItem */, 
+                                          CTestCase* aTestCase, 
+                                          TInt aCmd )
+    {
+    
+    CRemoteTestCase* caseInfo = ( CRemoteTestCase* ) aTestCase;
+    
+    CStifTFwIfProt* req = CStifTFwIfProt::NewL();
+    CleanupStack::PushL( req );
+    req->CreateL();
+    // Remote message
+    User::LeaveIfError( 
+        req->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote ) );
+    // Srcid. i.e. master id
+    //req->AppendId( ( TUint32 ) this );
+    User::LeaveIfError(
+        req->AppendId( KRemoteProtocolMasterId ));
+    // DstId, i.e.slave id
+    User::LeaveIfError(
+        req->AppendId( caseInfo->iSlaveId ));
+    
+    switch( aCmd )
+        {
+        case TTCKeywords::EPause:
+            if( caseInfo->iRemoteState != CRemoteTestCase::ECaseRunning )
+                {
+                __TRACE( KError, (_L("Test case with testid %S not running"), 
+                    &aTestCase->TestId() ));
+                User::Leave( KErrGeneral );
+                }
+            // Pause command
+            User::LeaveIfError(
+                req->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdPause ) );
+            caseInfo->iRemoteState = CRemoteTestCase::ECasePauseSent;
+            break;
+        case TTCKeywords::EResume:
+            if( caseInfo->iRemoteState != CRemoteTestCase::ECasePaused )
+                {
+                __TRACE( KError, (_L("Test case with testid %S not paused"), 
+                    &aTestCase->TestId() ));
+                User::Leave( KErrGeneral );
+                }
+            // Resume command
+            User::LeaveIfError( 
+                req->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdResume ));
+            caseInfo->iRemoteState = CRemoteTestCase::ECaseResumeSent;
+            break;            
+        case TTCKeywords::ECancel:
+            if( ( caseInfo->iRemoteState != CRemoteTestCase::ECaseRunning ) &&
+                ( caseInfo->iRemoteState != CRemoteTestCase::ECasePaused ) )
+                {
+                __TRACE( KError, (_L("Test case with testid %S not running"),
+                    &aTestCase->TestId() ));
+                User::Leave( KErrGeneral );
+                }
+            // Cancel command
+            User::LeaveIfError( 
+                req->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdCancel ));    
+            caseInfo->iRemoteState = CRemoteTestCase::ECaseCancelSent;
+            break;      
+        case TTCKeywords::EComplete:
+            if( caseInfo->iRemoteState == CRemoteTestCase::ECaseCompleted )
+                {
+                __TRACE( KError, (_L("Test case with testid %S already completed"), 
+                    &aTestCase->TestId() ));
+                CleanupStack::PopAndDestroy( req );
+                return ETrue;
+                }
+            else
+                {
+                iTestCombiner->iWaitTestCase = aTestCase->TestId();
+                CleanupStack::PopAndDestroy( req );
+                return EFalse;
+                }    
+        default:
+            // Should never come here
+            User::Leave( KErrGeneral );            
+        }
+    
+    User::LeaveIfError( 
+        iTestCombiner->TestModuleIf().RemoteSend( req->Message() ) );
+
+    // Start timer    
+    iRemoteTimer->SetTimerActive( iTestCombiner->iRemoteTimeout );
+            
+    iState = ERunnerRemote;
+    
+    CleanupStack::PopAndDestroy( req );
+    
+    return EFalse;
+   
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteRemoteEventCtlL
+
+     Description: Handles remote event controlling
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    CSlaveInfo* aSlave: in: slave info
+                    TInt aCmd: in: remote command 
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution and wait response
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteRemoteEventCtlL( CStifItemParser* aItem, 
+                                           CSlaveInfo* aSlave, 
+                                           TInt aCmd )
+    {
+    
+    TPtrC eventName;
+    // Get event name
+    TInt ret = aItem->GetNextString( eventName );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, (_L("Event name was not given for remote")));
+        User::Leave( KErrArgument );
+        }
+    
+    if( aCmd == TTCKeywords::EWait )
+        {
+        TEventTc* event = aSlave->GetEvent( eventName );
+        if( event == NULL )
+            {
+            __TRACE( KError, (_L("Waited event %S not requested"), 
+                &eventName  ) );
+            User::Leave( KErrNotFound );
+            }
+        iState = ERunnerRunning;
+        SetActive();
+        event->WaitEvent( iStatus );     
+        // Execution continue if waited event is set or after it is set       
+        return EFalse;
+        }
+    
+    CStifTFwIfProt* req = CStifTFwIfProt::NewL();
+    CleanupStack::PushL( req );
+    
+    req->CreateL();
+    // Remote message
+    User::LeaveIfError( 
+        req->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote ));
+    // Srcid. i.e. master id
+    User::LeaveIfError( req->AppendId( aSlave->iMasterId ) );
+    // DstId, i.e.slave device id
+    User::LeaveIfError( req->AppendId( aSlave->iSlaveDevId ) );
+           
+    switch( aCmd )
+        {       
+        // Event control cases
+        case TTCKeywords::ERequest:
+            {
+            TEventTc* event = aSlave->GetEvent( eventName );
+            if( event != NULL )
+                {
+                __TRACE( KError, (_L("Event %S already requested"), 
+                    &eventName  ) );
+                User::Leave( KErrNotFound );
+                }
+            event = new( ELeave ) TEventTc( (TName&)eventName, 
+                                             iTestCombiner->iLog );
+            CleanupStack::PushL( event );
+            User::LeaveIfError( aSlave->iEvents.Append( event ) );
+            CleanupStack::Pop( event );
+            // Request event
+            User::LeaveIfError( 
+                req->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRequest ));  
+            }
+            break;
+                        
+        case TTCKeywords::ERelease:
+            {
+            TEventIf* event = NULL;
+            TInt count = aSlave->iEvents.Count();
+            TInt i = 0;
+            for( ; i < count; i++ )
+                {
+                if( aSlave->iEvents[i]->Name() == eventName )
+                    {
+                    event = aSlave->iEvents[i];
+                    break;
+                    }
+                }
+            if( event == NULL )
+                {
+                __TRACE( KError, (_L("Event not found %S"), 
+                    &eventName  ) );
+                User::Leave( KErrNotFound );
+                }
+                                                  
+            aSlave->iEvents.Remove(i);
+            delete event;
+            // Release event
+            User::LeaveIfError(
+                req->Append( CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdRelease ));  
+            }
+            break;
+        
+        case TTCKeywords::ESet:
+        	{
+        		__TRACE( KPrint, (_L("JIRA51 CTestRunner::ExecuteRemoteEventCtlL case ESet")));
+	            User::LeaveIfError(req->Append(CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdSetEvent));
+        		break;
+        	}
+       	case TTCKeywords::EUnset:
+        	{
+        		__TRACE( KPrint, (_L("JIRA51 CTestRunner::ExecuteRemoteEventCtlL case EUnset")));
+	            User::LeaveIfError(req->Append(CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdUnsetEvent));
+        		break;
+        	}
+        default:
+             // Should never come here
+            User::Leave( KErrGeneral );            
+        }
+        
+    // Event name
+    User::LeaveIfError( req->Append( eventName ) );  
+    
+	if(aCmd == TTCKeywords::ESet)
+		{
+ 		TPtrC stateEvent;
+		TInt ret = aItem->GetNextString(stateEvent);
+		if(ret == KErrNotFound) //indication event - add indicate keyword to message
+			{
+	            User::LeaveIfError(req->Append(CStifTFwIfProt::EventType, TEventIf::EIndication));
+			}
+		else if(ret == KErrNone) //possibly state event
+			{
+			if(stateEvent.Compare(_L("state")) == 0) //state event - add state keyword to message
+				{
+	            User::LeaveIfError(req->Append(CStifTFwIfProt::EventType, TEventIf::EState));
+				}
+			else //syntax error in the line
+				{
+		        __TRACE(KError, (_L("Unknown keyword %S"), &stateEvent));
+				}
+			}
+		else //syntax error in the line
+			{
+	        __TRACE(KError, (_L("Unknown keyword (2) %S"), &stateEvent));
+			}
+		}
+    User::LeaveIfError( 
+        iTestCombiner->TestModuleIf().RemoteSend( req->Message() ) );
+                
+    // Start timer    
+    iRemoteTimer->SetTimerActive( iTestCombiner->iRemoteTimeout );
+
+    iState = ERunnerRemote;
+    
+    CleanupStack::PopAndDestroy( req );
+    
+    return EFalse;
+    
+    }    
+
+TBool CTestRunner::ExecuteRemoteSetUnsetEventL(CStifItemParser* aItem,
+                                               CSlaveInfo* aSlave,
+                                               TInt aCmd)
+	{
+	TPtrC eventName;
+	// Get event name
+	TInt ret = aItem->GetNextString(eventName);
+	if(ret != KErrNone)
+		{
+		__TRACE(KError, (_L("Event name was not given for remote")));
+		User::Leave(KErrArgument);
+		}
+	// Check if this is a state set, indication set, or unset command
+	TInt caseNumber = -1;
+	if(aCmd == TTCKeywords::ESet)
+		{
+ 		TPtrC stateEvent;
+		TInt ret = aItem->GetNextString(stateEvent);
+		if(ret == KErrNotFound) //indication event - add indicate keyword to message
+			{
+			caseNumber = 1;
+			}
+		else if(ret == KErrNone) //possibly state event
+			{
+			if(stateEvent.Compare(_L("state")) == 0) //state event - add state keyword to message
+				{
+				caseNumber = 0;
+				}
+			else //syntax error in the line
+				{
+				__TRACE(KError, (_L("Unknown keyword %S"), &stateEvent));
+				}
+			}
+		else //syntax error in the line
+			{
+			}
+		}
+	else //TTCKeyword::EUnset
+		{
+		caseNumber = 2;
+		}
+
+	if(caseNumber == -1)
+		{
+			__TRACE(KError, _L("Should never occur"));
+		}
+	// Build new descriptor with command to run hardcoded suevent test case on remote phone
+	HBufC* cmd = HBufC::NewL(100);
+	CleanupStack::PushL(cmd);
+	TPtr cmdPtr(cmd->Des());
+	cmdPtr.Copy(eventName);
+	// Run remotely test case
+RDebug::Print(_L("CTestRunner::ExecuteRemoteSetUnsetEventL calling ExecuteRemoteRun"));
+	TBool retval = ExecuteRemoteRunL(aItem, aSlave, cmd, caseNumber);
+	// Clean data
+	CleanupStack::PopAndDestroy(cmd);
+RDebug::Print(_L("CTestRunner::ExecuteRemoteSetUnsetEventL end"));
+	return retval;
+    }
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteRemoteSendReceiveL
+
+     Description: Handles asynchronous remote sendreceive controlling
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    CSlaveInfo* aSlave: in: slave info
+
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution and wait response
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteRemoteSendReceiveL( CStifItemParser* aItem, 
+                                           CSlaveInfo* aSlave )
+    {
+    CStifTFwIfProt* req = CStifTFwIfProt::NewL();
+    CleanupStack::PushL( req );
+    
+    // Create CRemoteSendReceive object for taking sendreceive information to
+    // save for later use.
+    CRemoteSendReceive* remoteSendReceive = 
+        CRemoteSendReceive::NewL( iTestCombiner );
+    
+    CleanupStack::PushL( remoteSendReceive );
+
+    req->CreateL();
+    // Remote message
+    User::LeaveIfError(
+        req->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote ) );
+    // Srcid. i.e. master id
+    User::LeaveIfError( req->AppendId( aSlave->iMasterId ) );
+    // DstId, i.e.slave device id
+    User::LeaveIfError( req->AppendId( aSlave->iSlaveDevId ) );
+    // Run command
+    User::LeaveIfError( req->Append( 
+        CStifTFwIfProt::CmdType, CStifTFwIfProt::ECmdSendReceive ) );
+    // asynchronous sendreceive's parameters    
+    TPtrC tmp;    
+
+    while( aItem->GetNextString( tmp ) == KErrNone )
+        {        
+        // Append parameters
+        User::LeaveIfError( req->Append( tmp ) );  
+        }
+    
+    User::LeaveIfError( 
+        iTestCombiner->TestModuleIf().RemoteSend( req->Message() ) );
+
+    remoteSendReceive->iRemoteState = CRemoteSendReceive::ECaseSend;
+    remoteSendReceive->iSlaveId = aSlave->iSlaveDevId;
+
+    // Take CRemoteSendReceive object to save in array. This can be used in
+    // TestCombiner when handling responses.
+    User::LeaveIfError( 
+            iTestCombiner->iSendReceive.Append( remoteSendReceive ) );
+    if( iTestCombiner->iLoopIsUsed )
+        {
+        User::LeaveIfError( 
+            iTestCombiner->iLoopAllocationArray.Append( remoteSendReceive ) );
+        }
+    CleanupStack::Pop( remoteSendReceive );
+
+    // Start timer    
+    iRemoteTimer->SetTimerActive( iTestCombiner->iRemoteTimeout );
+
+    iState = ERunnerRemote;
+    
+    CleanupStack::PopAndDestroy( req );
+    
+    // Return EFalse=>start waiting response...
+    return EFalse;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteRemoteUnknownL
+
+     Description: Forwards messages as such
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+                    CSlaveInfo* aSlave: in: slave info
+                    TInt aCmd: in: remote command 
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution and wait response
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteRemoteUnknownL( CStifItemParser* aItem, 
+                                          CSlaveInfo* aSlave,
+                                          TDesC& aCommand )
+    {
+    
+    CStifTFwIfProt* req = CStifTFwIfProt::NewL();
+    CleanupStack::PushL( req );
+    
+    req->CreateL();
+    // Remote message
+    User::LeaveIfError(
+        req->Append( CStifTFwIfProt::MsgType, CStifTFwIfProt::EMsgRemote ) );
+    // Srcid. i.e. master id
+    User::LeaveIfError( req->AppendId( aSlave->iMasterId ) );
+    // DstId, i.e.slave device id
+    User::LeaveIfError( req->AppendId( aSlave->iSlaveDevId ) );
+    
+    // Append command name
+    User::LeaveIfError( req->Append( aCommand ) );
+    
+    TPtrC tmp;         
+    while( aItem->GetNextString( tmp ) == KErrNone )
+        {        
+        // Append parameters
+        User::LeaveIfError( req->Append( tmp ) );  
+        }
+    
+    User::LeaveIfError( 
+        iTestCombiner->TestModuleIf().RemoteSend( req->Message() ) );
+                
+    // Start timer    
+    iRemoteTimer->SetTimerActive( iTestCombiner->iRemoteTimeout );
+
+    iState = ERunnerRemote;
+    
+    CleanupStack::PopAndDestroy( req );
+    
+    return EFalse;
+    
+    }    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ReceiveResponseL
+
+     Description: Handles responce received from slave
+  
+     Parameters:    TDesC& aMsg: in: message
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ReceiveResponseL( TDesC& aMsg )
+    {
+    __TRACE( KMessage, (_L("ReceiveResponse")));
+    
+    iRemoteTimer->Cancel();
+    
+    CStifTFwIfProt* msg = CStifTFwIfProt::NewL();
+    CleanupStack::PushL( msg );
+    TRAPD( err, msg->SetL( aMsg ); );
+    if( err != KErrNone )
+        {
+        __TRACE( KError, (_L("Response parsing failed")));
+        User::Leave( err );
+        }
+    
+    // Check protocol identifiers
+    if( ( msg->SrcDevId() == 0 ) ||
+        ( msg->DstDevId() == 0 ) ||
+        ( msg->DstTestId() == 0 ) )
+        {
+        __TRACE( KError, (_L("Illegal deviceid received")));
+        User::Leave( KErrGeneral );
+        }
+    
+    // This is master, cannot receive anything else but responses
+    if( msg->iMsgType != CStifTFwIfProt::EMsgResponse )
+        {
+        __TRACE( KError, (_L("Illegal message received %d"), 
+            msg->iMsgType ));
+        User::Leave( KErrGeneral );        
+        }
+        
+    TBool continueTask = ETrue;
+    switch( msg->iRespType )
+        {
+        case CStifTFwIfProt::EMsgReserve:
+            {
+            __TRACE( KMessage, (_L("ReceiveResponse Reserve")));
+            if( iState != ERunnerAllocate )
+                {
+                __TRACE( KError, (_L("Response reserve received in illegal state %d"), 
+                    iState ));
+                User::Leave( KErrGeneral );    
+                }
+            // Check protocol Src test id
+            if( msg->SrcTestId() != 0 )
+                {
+                __TRACE( KError, (_L("Illegal deviceid received")));
+                User::Leave( KErrGeneral );
+                }
+            if( msg->iResult != KErrNone )
+                {
+                __TRACE( KError, (_L("Response with error %d"), msg->iResult ));
+                User::Leave( msg->iResult );
+                }
+            CSlaveInfo* slave = NULL;
+            TInt count = iTestCombiner->iSlaveArray.Count();
+            for( TInt index = 0; index < count; index++ )
+                {
+                slave = iTestCombiner->iSlaveArray[index];
+                if( ( slave->iSlaveDevId == 0 ) &&
+                    ( slave->iState ==  CSlaveInfo::ESlaveReserveSent ) )
+                    {
+                    break;
+                    }
+                slave = NULL;
+                }
+            if( slave == NULL )
+                {
+                User::Leave( KErrNotFound );
+                }
+            slave->iSlaveDevId = msg->SrcId();
+            slave->iState = CSlaveInfo::ESlaveReserved;
+            __TRACE( KMessage, (_L("Slave allocated succesfully, continue execution")));
+            }
+            break;
+        case CStifTFwIfProt::EMsgRelease:
+            {
+            __TRACE( KMessage, (_L("ReceiveResponse Release")));
+            if( iState != ERunnerFree )
+                {
+                __TRACE( KError, (_L("Response release received in illegal state %d"), 
+                    iState ));
+                User::Leave( KErrGeneral );    
+                }
+            // Check protocol Src test id
+            if( msg->SrcTestId() != 0 )
+                {
+                __TRACE( KError, (_L("Illegal deviceid received")));
+                User::Leave( KErrGeneral );
+                }                
+            if( msg->iResult != KErrNone )
+                {
+                __TRACE( KError, (_L("Response with error %d"), msg->iResult ));
+                User::Leave( msg->iResult );
+                }
+
+            CSlaveInfo* slave = iTestCombiner->GetSlave( msg->SrcId() );
+            if( slave == NULL )
+                {
+                User::Leave( KErrNotFound );
+                }
+            slave->iState = CSlaveInfo::ESlaveReleased;
+            __TRACE( KMessage, (_L("Slave freed succesfully, continue execution")));
+            }            
+            break;
+        case CStifTFwIfProt::EMsgRemote:
+            {         
+            __TRACE( KMessage, (_L("ReceiveResponse Remote")));
+            switch( msg->iCmdType )
+                {
+                case CStifTFwIfProt::ECmdRun:
+                    continueTask = ReceiveResponseRunL( *msg );
+                    break;
+                case CStifTFwIfProt::ECmdPause:
+                case CStifTFwIfProt::ECmdResume:
+                case CStifTFwIfProt::ECmdCancel:
+                    continueTask = ReceiveResponseTestCtlL( *msg );
+                    break;
+                case CStifTFwIfProt::ECmdRequest:
+                case CStifTFwIfProt::ECmdRelease:
+                case CStifTFwIfProt::ECmdSetEvent:
+                case CStifTFwIfProt::ECmdUnsetEvent:
+                    continueTask = ReceiveResponseEventCtlL( *msg );                    
+                    break;
+                case CStifTFwIfProt::ECmdSendReceive:
+                    continueTask = ReceiveResponseSendReceiveL( *msg );                    
+                    break;
+                default:
+                    continueTask = ReceiveResponseUnknownL( *msg );                    
+                    break;
+                }
+            }            
+            break;
+        default:
+            User::Leave( KErrGeneral );
+        } 
+               
+    
+    CleanupStack::PopAndDestroy( msg );    
+    return continueTask;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ReceiveResponseRunL
+
+     Description: Handles response for run received from slave
+  
+     Parameters:    CStifTFwIfProt& aMsg: in: protocol message parser
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/    
+TBool CTestRunner::ReceiveResponseRunL( CStifTFwIfProt& aMsg )
+    {
+
+    TPtrC tmp = CStifTFwIfProt::RunStatus(aMsg.iRunStatus); 
+    __TRACE( KMessage, (_L("ReceiveResponse Remote Run %S"), &tmp ));
+
+    TBool continueTask = ETrue; 
+    switch( aMsg.iRunStatus )
+        {
+        case CStifTFwIfProt::ERunStarted:
+            {
+            // Locate testcase    
+            CRemoteTestCase* tcase = 
+                iTestCombiner->GetRemoteTestRunSent( GETDEVID( aMsg.SrcId() ) );
+            if( tcase == NULL ) 
+                {
+                __TRACE( KError, (_L("Testcase not found")));
+                User::Leave( KErrNotFound );        
+                }
+            tcase->iSlaveId = aMsg.SrcId();
+
+            tcase->iRemoteState = CRemoteTestCase::ECaseRunning;
+            }
+            break;
+        case CStifTFwIfProt::ERunError:
+        case CStifTFwIfProt::ERunReady:
+            {
+            // Locate testcase    
+            CRemoteTestCase* tcase = 
+                iTestCombiner->GetRunningRemoteTest( aMsg.SrcId() );
+            if( tcase == NULL ) 
+                {
+                __TRACE( KError, (_L("Testcase not found")));
+                User::Leave( KErrNotFound );        
+                }
+
+            switch( aMsg.iResultCategory )
+                {
+                case CStifTFwIfProt::EResultNormal:
+                    tcase->iResult.iCaseExecutionResultType = 
+                        TFullTestResult::ECaseExecuted;
+                    tcase->iResult.iTestResult.iResult = aMsg.iResult;
+                    tcase->iResult.iCaseExecutionResultCode = 0;
+                    break;
+                case CStifTFwIfProt::EResultPanic:
+                    tcase->iResult.iCaseExecutionResultType = 
+                        TFullTestResult::ECasePanic;
+                    tcase->iResult.iTestResult.iResult = KErrGeneral;
+                    tcase->iResult.iCaseExecutionResultCode = aMsg.iResult;
+                    break;
+                case CStifTFwIfProt::EResultException:
+                    tcase->iResult.iCaseExecutionResultType = 
+                        TFullTestResult::ECaseException;
+                    tcase->iResult.iTestResult.iResult = KErrGeneral;
+                    tcase->iResult.iCaseExecutionResultCode = aMsg.iResult;
+                    break;
+                case CStifTFwIfProt::EResultTimeout:
+                    tcase->iResult.iCaseExecutionResultType = 
+                        TFullTestResult::ECaseTimeout;                
+                    tcase->iResult.iTestResult.iResult = KErrGeneral;
+                    tcase->iResult.iCaseExecutionResultCode = aMsg.iResult;
+                    break;
+                case CStifTFwIfProt::EResultLeave:
+                    tcase->iResult.iCaseExecutionResultType = 
+                        TFullTestResult::ECaseLeave;                
+                    tcase->iResult.iTestResult.iResult = KErrGeneral;
+                    tcase->iResult.iCaseExecutionResultCode = aMsg.iResult;
+                    break;
+                default:
+                    User::Leave( KErrGeneral );
+                }
+                    
+            if( ( tcase->iRemoteState == CRemoteTestCase::ECaseCancelled ) ||
+                ( tcase->iRemoteState == CRemoteTestCase::ECaseRunSent ) )
+                {
+                // Complete for cancelled testcase or error for run request, 
+                // set runner active again
+                continueTask = ETrue; 
+                }
+            else
+                {
+                // Continued from Complete in state ECaseRunning
+                continueTask = EFalse; 
+                }
+                
+            tcase->iRemoteState = CRemoteTestCase::ECaseCompleted;
+
+        __TRACE( KMessage, (_L("ReceiveResponse Remote Run rq comp")));
+            
+            TRequestStatus* rs = &tcase->iStatus;
+            // Complete testcase
+            User::RequestComplete( rs, KErrNone );
+            
+            }
+            break;
+        default:
+            // Should never come here
+            User::Leave( KErrGeneral );    
+        }        
+    
+    return continueTask;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ReceiveResponseTestCtlL
+
+     Description: Handles responses for test control commands 
+        received from slave
+  
+     Parameters:    CStifTFwIfProt& aMsg: in: protocol message parser
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/    
+TBool CTestRunner::ReceiveResponseTestCtlL( CStifTFwIfProt& aMsg )
+    {
+
+    if( aMsg.iResult != KErrNone )
+        {
+        __TRACE( KError, (_L("Response with error %d"), aMsg.iResult ));
+        User::Leave( aMsg.iResult );
+        }
+    
+    // Locate testcase    
+    CRemoteTestCase* tcase = iTestCombiner->GetRemoteTest( aMsg.SrcId() );
+    if( tcase == NULL ) 
+        {
+        __TRACE( KError, (_L("Testcase not found")));
+        User::Leave( KErrNotFound );        
+        }
+    
+    TBool continueTask = ETrue;
+    
+    switch( aMsg.iCmdType )
+        {
+        case CStifTFwIfProt::ECmdPause:
+            __TRACE( KMessage, (_L("ReceiveResponse Remote Pause")));
+
+            if( tcase->iRemoteState != CRemoteTestCase::ECasePauseSent )
+                {
+                __TRACE( KError, (_L("Pause response received in illegal state")));
+                User::Leave( KErrGeneral );                        
+                }
+            tcase->iRemoteState = CRemoteTestCase::ECasePaused;
+            
+            // Start pause timer if timeout was given 
+            if( ( iPausedTestCase.Length() > 0 ) &&
+                ( iPauseTime != 0 ) )
+                {
+                continueTask = EFalse;
+                iState = ERunnerWaitTimeout;
+                iPauseTimer.After( iStatus, iPauseTime*1000 );
+                SetActive();         
+                }
+            break;
+        case CStifTFwIfProt::ECmdResume:
+            __TRACE( KMessage, (_L("ReceiveResponse Remote Resume")));
+
+            if( tcase->iRemoteState != CRemoteTestCase::ECaseResumeSent )
+                {
+                __TRACE( KError, (_L("Resume response received in illegal state")));
+                User::Leave( KErrGeneral );                        
+                }
+            tcase->iRemoteState = CRemoteTestCase::ECaseRunning;
+            break;
+        case CStifTFwIfProt::ECmdCancel:
+            __TRACE( KMessage, (_L("ReceiveResponse Remote Cancel")));
+
+            if( tcase->iRemoteState != CRemoteTestCase::ECaseCancelSent )
+                {
+                __TRACE( KError, (_L("Cancel response received in illegal state")));
+                User::Leave( KErrGeneral );                        
+                }
+            tcase->iRemoteState = CRemoteTestCase::ECaseCancelled;
+            // Need to wait Run response with KErrCancel
+            continueTask = EFalse;
+            // Start timer    
+            iRemoteTimer->SetTimerActive( iTestCombiner->iRemoteTimeout );
+            break;
+        default:
+            // Should never come here
+            User::Leave( KErrGeneral );
+        }
+    
+    return continueTask;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ReceiveResponseEventCtlL
+
+     Description: Handles responses for event system control commands 
+        received from slave
+  
+     Parameters:    CStifTFwIfProt& aMsg: in: protocol message parser
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution 
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ReceiveResponseEventCtlL( CStifTFwIfProt& aMsg )
+    {
+        
+    CSlaveInfo* slave = iTestCombiner->GetSlave( aMsg.SrcId() );
+    if( slave == NULL )
+        {
+        User::Leave( KErrNotFound );
+        }
+    
+    TBool continueTask = ETrue;
+    switch( aMsg.iCmdType )
+        {
+        case CStifTFwIfProt::ECmdRequest:
+            {
+            __TRACE( KMessage, (_L("ReceiveResponse Request")));
+ 
+            TEventTc* event = slave->GetEvent( aMsg.iEventName );
+            if( event == NULL )
+                {
+                User::Leave( KErrNotFound );
+                }
+            switch( aMsg.iEventStatus )
+                {
+                case CStifTFwIfProt::EEventActive:
+                    __TRACE( KMessage, (_L("Event %S active"), &aMsg.iEventName ));
+                    break;
+                case CStifTFwIfProt::EEventSet:
+                    __TRACE( KMessage, (_L("Event %S set"), &aMsg.iEventName ));
+                    // Set event
+                    event->SetEvent( aMsg.iEventType );
+                    continueTask = EFalse;
+                    break;
+                case CStifTFwIfProt::EEventError:
+                    __TRACE( KMessage, (_L("Event %S error %d"), 
+                        &aMsg.iEventName, aMsg.iResult ));
+                    User::Leave( aMsg.iResult );
+                default:
+                    User::Leave( KErrGeneral );
+                }
+            }
+            break;
+        case CStifTFwIfProt::ECmdRelease:
+            __TRACE( KMessage, (_L("ReceiveResponse Release")));
+            if( aMsg.iResult != KErrNone )
+                {
+                __TRACE( KError, (_L("Response with error %d"), aMsg.iResult ));
+                User::Leave( aMsg.iResult );
+                }
+
+            // Everything ok, no need to do anything
+            break;
+        case CStifTFwIfProt::ECmdSetEvent:
+            __TRACE( KMessage, (_L("ReceiveResponse SetEvent")));
+            if( aMsg.iResult != KErrNone )
+                {
+                __TRACE( KError, (_L("Response with error %d"), aMsg.iResult ));
+                User::Leave( aMsg.iResult );
+                }
+
+            // Everything ok, no need to do anything
+            break;
+        case CStifTFwIfProt::ECmdUnsetEvent:
+            __TRACE( KMessage, (_L("ReceiveResponse Unset")));
+            if( aMsg.iResult != KErrNone )
+                {
+                __TRACE( KError, (_L("Response with error %d"), aMsg.iResult ));
+                User::Leave( aMsg.iResult );
+                }
+            // Everything ok, no need to do anything
+            break;
+        default:
+            // Should never come here
+            User::Leave( KErrGeneral );
+        }
+
+    return continueTask;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ReceiveResponseSendReceiveL
+
+     Description: Handles responses for asynchronous sendreceive commands 
+                  received from slave
+  
+     Parameters: CStifTFwIfProt& aMsg: in: protocol message parser
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution 
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ReceiveResponseSendReceiveL( CStifTFwIfProt& aMsg )
+    {
+        
+    TPtrC tmp = CStifTFwIfProt::RunStatus(aMsg.iRunStatus); 
+    __TRACE( KMessage, (
+        _L("ReceiveResponseSendReceiveL asynchronous Remote SendReceive %S"),
+        &tmp ) );
+
+    TBool continueTask = EFalse; 
+    switch( aMsg.iRunStatus )
+        {
+        case CStifTFwIfProt::ERunStarted:
+            {
+            // Locate CRemoteSendReceive object
+            CRemoteSendReceive* sendreceive = 
+                            iTestCombiner->GetRemoteSendReceive( GETDEVID(
+                            aMsg.SrcId() ) );
+            if( sendreceive == NULL ) 
+                {
+                __TRACE( KError, (_L("CRemoteSendReceive object not found")));
+                User::Leave( KErrNotFound );        
+                }
+            sendreceive->iRemoteState = CRemoteSendReceive::ECaseSend;
+
+            // continueTask is EFalse=>stop script file execution
+            break;
+            }
+        case CStifTFwIfProt::ERunError:
+        case CStifTFwIfProt::ERunReady:
+            {
+            if( aMsg.iResult != KErrNone )
+                    {
+                    __TRACE( KError, (_L("sendreceive response with error %d"), aMsg.iResult ));
+                    User::Leave( aMsg.iResult );
+                    }
+
+            // Locate CRemoteSendReceive object
+            CRemoteSendReceive* sendreceive = 
+                iTestCombiner->GetRemoteSendReceive( aMsg.SrcId() );
+            if( sendreceive == NULL ) 
+                {
+                __TRACE( KError, (_L("CRemoteSendReceive object not found")));
+                User::Leave( KErrNotFound );        
+                }
+
+            // continueTask is ETrue=>continue script file execution
+            continueTask = ETrue;
+              
+            sendreceive->iRemoteState = CRemoteSendReceive::ECaseCompleted;
+
+            __TRACE( KMessage, (
+                _L( "ReceiveResponseSendReceiveL asynchronous Remote SendReceive rq comp" ) ) );
+            break;
+            }
+        default:
+            {
+            // Should never come here
+            User::Leave( KErrGeneral );    
+            }
+        }
+    return continueTask;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ReceiveResponseUnknownL
+
+     Description: Handles responses for unspecified commands
+  
+     Parameters:    CStifTFwIfProt& aMsg: in: protocol message parser
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution 
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ReceiveResponseUnknownL( CStifTFwIfProt& aMsg )
+    {
+        
+    CSlaveInfo* slave = iTestCombiner->GetSlave( aMsg.SrcId() );
+    if( slave == NULL )
+        {
+        User::Leave( KErrNotFound );
+        }
+    if( aMsg.iResult != KErrNone )
+        {
+        __TRACE( KError, (_L("Response with error %d"), aMsg.iResult ));
+        User::Leave( aMsg.iResult );
+        }
+    
+    return ETrue;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ParseOptArgL
+
+     Description: Parses optional argument 
+  
+     Parameters: const TDesC& aOptArg: in: 
+                    argument-value pair (format arg=value)
+                 TPtrC& aArg: out: parsed argument  
+                 TPtrC& aVal: out: parsed value
+     
+     Return Values: None
+
+     Errors/Exceptions: Leaves if parsing fails.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::ParseOptArgL( const TDesC& aOptArg, TPtrC& aArg, TPtrC& aVal)
+    { 
+    _LIT( KErrMsgUnknownOrIllegalKeyword, "Unknown or illegal argument %S" );
+    _LIT( KErrMsgValueNotDefined, "Value of optional argument %S is not defined" );
+    TInt length = aOptArg.Length();
+    for( TInt i=0; i < length; i++) 
+        {
+        // find the '=' sign 
+        if( aOptArg[i] == '=' )
+            {
+            if( i+1 >= length )
+                {
+                __TRACE( KError, 
+                    (_L("Illegal optional argument(%S), no value"), 
+                    &aOptArg ));    
+				TPtrC tmp = aOptArg.Left( i );
+                iRunErrorMessage.Format( KErrMsgValueNotDefined, &tmp );
+                User::Leave( KErrArgument );
+                }
+            aArg.Set( aOptArg.Left( i ) );
+            aVal.Set( aOptArg.Mid( i+1 ) );
+            __TRACE( KMessage, (  _L( "arg '%S', val '%S'" ),
+                &aArg, &aVal ));        
+            return;
+            }
+        }
+    __TRACE( KError, (_L("Illegal optional argument(%S)"), &aOptArg ));    
+    iRunErrorMessage.Format( KErrMsgUnknownOrIllegalKeyword, &aOptArg );
+    User::Leave( KErrArgument );
+    
+    }     
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: CancelTestCases
+
+     Description: Cancels all running testcases
+  
+     Parameters:    None
+     
+     Return Values: None
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::CancelTestCases()
+    {
+    __TRACEFUNC();
+
+    TInt count = iTestCombiner->iTestCases.Count();
+    for( TInt i=0; i < count; i++ )
+        {
+        if( iTestCombiner->iTestCases[i]->State() == 
+            CTCTestCase::ETestCaseRunning )
+            {
+            iTestCombiner->iTestCases[i]->Cancel();
+            }
+        }
+        
+    if( ( iTestCombiner->iRunningTests == 0 ) &&
+        iTestCombiner->iSchedulerActive ) 
+        {
+        // Stop execution
+        CActiveScheduler::Current()->Stop();
+        iTestCombiner->iSchedulerActive = EFalse;
+        return;
+        }
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: SetRunnerActive
+
+     Description: Set CTestRunner active and complete.
+  
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::SetRunnerActive()
+     {
+     __TRACEFUNC();
+     
+     if( IsActive() )
+        {
+        __TRACE( KError, ( _L("Runner already active %d"), iState ));
+        User::Panic( KTestRunner, KErrInUse );
+        }
+ 
+     // Update state
+     iState = ERunnerRunning;
+ 
+     iStatus = KRequestPending;
+     TRequestStatus* rs = &iStatus;
+     SetActive();
+     User::RequestComplete( rs, KErrNone );
+     
+     }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: CheckUnsetEvent
+
+     Description: Check unset event.
+     
+     Parameters: None
+         
+     Return Values: ETrue: Unset event completed
+                    EFalse: No unset event pending
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::CheckUnsetEvent()
+    {
+    if( iEvent.Name().Length() == 0 )
+        {
+        return EFalse;
+        }
+        
+    __TRACE( KMessage, (_L("Unset event completed") ));
+    // Check if some testmodule below has still event request pending
+    if( iTestCombiner->UnsetEvent( iEvent, iStatus ) == EFalse )
+        {
+         // No event request pending
+        // then check other testmodules (may block)
+        TInt res = iTestCombiner->TestModuleIf().Event( iEvent );
+        if( res != KErrNone )
+            {
+            iTestCombiner->iResult = res;
+            }
+            
+        __TRACE( KPrint, (_L("Unset: Complete") ) );
+        iEvent.SetName( _L("") );
+        // Proceed testcase section execution
+        SetRunnerActive();
+        }    
+    else
+        {
+        iState = ERunnerWaitUnset;
+        // Wait for unset to complete 
+        SetActive();
+        }
+         
+    return ETrue;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteLoopL
+
+     Description: Handle the loop keyword operations.
+
+     Parameters: CStifItemParser* aItem: in: Pointer to parsed item object.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::ExecuteLoopL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgLoopNestedLoop, "Loop: Nested loops are not supported " );
+    _LIT( KErrMsgLoopInvalidLoopCountParam, "Loop: No loop count value given for loop or value has invalid format" );
+    _LIT( KErrMsgLoopUnknownUnexpectedOption, "Loop: Unknown or unexpected loop option");
+    _LIT( KErrMsgLoopPasslimitInvalidValue, "Loop: No passlimit value given for loop or value has invalid format" );
+    _LIT( KErrMsgLoopPasslimitNotInRange, "Loop: Passlimit value is lower than 0 or higher than loop count" );
+    __TRACEFUNC();
+
+    if( iLoopTimes != 0 )
+        {
+        __TRACE( KError, (_L("ExecuteLoopL: Nested loop are not supported")));
+        iRunErrorMessage = KErrMsgLoopNestedLoop;
+        User::Leave( KErrNotSupported );
+        }
+
+    iLoopTimes = 0;
+    iLoopCounter = 0;
+    iPasslimitEnabled = EFalse;
+    iTimedLoop = EFalse;
+    
+    if( aItem->GetNextInt( iLoopTimes ) != KErrNone )
+        {
+        __TRACE( KError, (_L("ExecuteLoopL: No loop count value given for loop")));
+        iRunErrorMessage = KErrMsgLoopInvalidLoopCountParam;
+        User::Leave( KErrArgument );
+        }
+    __TRACE( KMessage, (_L("ExecuteLoopL: Loop for %d times" ), iLoopTimes ) );
+
+    //Check loop options
+    TPtrC option;
+    TInt ret = aItem->GetNextString(option); 
+    if(ret == KErrNone)
+        {
+        if(option.Compare(_L("msec")) == 0) //time loop option
+            {
+            iTimedLoop = ETrue;
+            iStartTime.HomeTime();
+            iExpectedLoopTime = TInt64(iLoopTimes) * TInt64(1000); //convert to micro seconds
+            __TRACE(KMessage, (_L("ExecuteLoopL: Timed loop for %d msec" ), iLoopTimes));
+            
+            ret = aItem->GetNextString(option); //Get next option
+            }
+        }
+        
+    if(ret == KErrNone)
+        {
+        if(option.Compare(_L("passlimit")) == 0) //passlimit option
+            {
+            iPasslimit = 0;
+            if( aItem->GetNextInt( iPasslimit ) != KErrNone )
+                {
+                __TRACE( KError, ( _L( "ExecuteLoopL: No passlimit value given for loop." ) ) );
+                iRunErrorMessage = KErrMsgLoopPasslimitInvalidValue;
+                User::Leave( KErrArgument );
+                }
+            __TRACE( KMessage, ( _L( "ExecuteLoopL: Passlimit set on %d" ), iPasslimit ) );
+            //Check if passlimit has valid value
+            if(iPasslimit < 0 || (iPasslimit > iLoopTimes && !iTimedLoop))
+                {
+                __TRACE( KError, ( _L( "ExecuteLoopL: Passlimit value is lower than 0 or higher than loop count." ) ) );
+                iRunErrorMessage = KErrMsgLoopPasslimitNotInRange;
+                User::Leave( KErrArgument );
+                }
+            iPasslimitEnabled = ETrue;
+
+            ret = aItem->GetNextString(option); //Get next option
+            }
+        }
+        
+    if(ret == KErrNone)
+        {
+        __TRACE( KError, ( _L( "ExecuteLoopL: Unknown or unexpected loop option [%S]" ), &option ) );
+        iRunErrorMessage = KErrMsgLoopUnknownUnexpectedOption;
+        User::Leave( KErrNotSupported );
+        }
+
+	iPassedIterationCnt = 0;
+
+    iLoopStartPos = iTestCombiner->iSectionParser->GetPosition();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteEndLoopL
+
+     Description: Handle the endloop keyword operations.
+
+     Parameters: None.
+
+     Return Values: TBool: Boolean value for indicate can testing continue.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteEndLoopL()
+    {
+    __TRACEFUNC();
+
+    // Fail test case if there was no loop started
+    if(iTestCombiner->iLoopIsUsed == EFalse)
+        {
+        __TRACE(KError, (_L("Encountered \'endloop\' without \'loop\'. Aborting test case.")));
+        iTestCombiner->iResult = KErrGeneral;
+        iState = ERunnerError;
+        CancelTestCases();
+        return ETrue; // Test case file parsing can be continue
+        }
+
+	TBool iterationFailed = EFalse; //Has last iteration failed (at least one of test cases has failed)
+
+    // First we check is all test cases that is set to run inside the loop
+    // completed. If not completed we wait until test case completes.
+    // Is some loop executions fails that is not allowed then loop execution
+    // will be stopped and error result is given to TestCombiner
+
+    for( TInt s = 0; s < iTestCombiner->iTestCases.Count(); s++ )
+        {
+        CTestCase* testCase = (CTestCase*)iTestCombiner->iTestCases[s]; 
+        if( testCase == NULL )
+            {
+            __TRACE( KError, (_L("ExecuteEndLoopL: CTestCase object not found") ) );
+            return ETrue;
+            }
+        // Check that testCase object is allocated inside the loop
+        TBool isLoopTestCase( EFalse );
+        for( TInt p = 0; p < iTestCombiner->iLoopAllocationArray.Count(); p++ )
+            {
+            if( iTestCombiner->iLoopAllocationArray[p] == testCase )
+                {
+                isLoopTestCase = ETrue;
+                break;
+                }
+            }
+        // testCase object is allocated inside loop
+        if( isLoopTestCase )
+            {
+            // Test case is completed
+            //if( testCase->State() == CTCTestCase::ETestCaseCompleted )
+            if(testCase->IsCompletelyFinished())
+                {
+                // Check normal test result
+                if( testCase->iExpectedResultCategory == TFullTestResult:: ECaseExecuted )
+                    {
+                    // Normal completion, check result
+                    if( testCase->iResult.iTestResult.iResult != testCase->iExpectedResult )
+                        {
+                        __TRACE( KPrint, ( _L( "Test failed, expect(%d) != result(%d)"), 
+                             testCase->iExpectedResult,
+                             testCase->iResult.iTestResult.iResult ));
+                        //If no passlimit is provided behave in old way
+                        if( !iPasslimitEnabled )
+                             {
+                            // We return the first error result as aResult
+                            if( testCase->iResult.iTestResult.iResult != KErrNone )
+                                {
+                                iTestCombiner->iScriptFailed = testCase->iResult.iCaseExecutionResultCode;
+                                iTestCombiner->iScriptFailedDescription.Copy(testCase->iResult.iTestResult.iResultDes);
+                                }
+                            else
+                                {
+                                iTestCombiner->iScriptFailed = testCase->iResult.iCaseExecutionResultCode;
+                                iTestCombiner->iScriptFailedDescription.Copy(_L("Test case has not finished with expected result (in loop)."));
+                                }
+
+                            iState = ERunnerError;
+                            CancelTestCases();
+                            return ETrue; // Test case file parsing can be continue
+                            }
+                        else
+                            {
+                            // Set flag that one of test cases has failed, so whole iteration is failed
+                            iterationFailed = ETrue;
+                            }
+                        }
+                    }
+                // Abnormal completion, i.e. panic, leave, exception or timeout
+                else 
+                    {
+                    if( testCase->iResult.iCaseExecutionResultCode != testCase->iExpectedResult )
+                        {
+                        __TRACE( KPrint, ( _L( "Test failed, expect errorcode(%d) != result(%d)"), 
+                             testCase->iExpectedResult,
+                             testCase->iResult.iCaseExecutionResultCode ) );
+                        //If no passlimit is provided behave in old way
+                        if( !iPasslimitEnabled )
+                            {
+                            // We return the first error result as aResult
+                            iTestCombiner->iScriptFailed = testCase->iResult.iCaseExecutionResultCode;
+                            iTestCombiner->iScriptFailedDescription.Copy(_L("Test case has not finished with expected execution error (in loop)."));
+
+                            iState = ERunnerError;
+                            // Return error from here
+                            CancelTestCases();
+                            return ETrue; // Test case file parsing can be continue
+                            }
+                        else
+                            {
+                            // Set flag that one of test cases has failed, so whole iteration is failed
+                            iterationFailed = ETrue;
+                            }
+                        }
+
+                    // Requested testcase is completed already,
+                    // proceed testcase execution
+                    __TRACE( KMessage, (_L("Already completed")));
+                    }
+                } // End "Test case is completed"
+            // Test case is running state, set to wait the test case complete
+            else if( testCase->State() == CTCTestCase::ETestCaseRunning )
+                 {
+                 // Wait testcase to complete. If no id there should generate
+                 // id that test case complete will be handled correctly
+                 if( testCase->TestId().Length() == 0 )
+                    {
+                    TPtrC generatedTestId( _L( "stif" ) );
+                    delete testCase->iTestId;
+                    testCase->iTestId = generatedTestId.Alloc();
+                    }
+                iTestCombiner->iWaitTestCase.Copy( testCase->TestId() );
+                 // Stop testcase execution until testcase completed 
+                 iState = ERunnerWaitTestCase;
+                // Go to beginning of the endloop
+                User::LeaveIfError(
+                    iTestCombiner->iSectionParser->SetPosition( iEndLoopStartPos ));
+
+                // Testing is ongoing, test case file parsing cannot
+                // be continue. Next line will be run when some AO
+                // will be complete and allow parsing to continue
+                return EFalse; 
+                }
+            else if(testCase->State() == CTCTestCase::ETestCaseCompleted)
+                {
+                // Go to beginning of the endloop
+                User::LeaveIfError(iTestCombiner->iSectionParser->SetPosition(iEndLoopStartPos));
+
+                // Testing is ongoing, test case file parsing cannot
+                // be continue. Next line will be run when some AO
+                // will be complete and allow parsing to continue
+                return ETrue;
+                }
+            else
+                {
+                // This should newer happen
+                __TRACE( KError, (_L("ExecuteEndLoopL: Illegal branch") ) );
+                }
+            }
+        } // end for-loop
+
+    iLoopCounter++;
+    __TRACE( KMessage, (_L("ExecuteLineL: Loop executed for %d times" ), 
+            iLoopCounter ) );
+
+    //If passlimit (endurance) is enabled, we must check if any of test case in this iteration has failed
+    if( iPasslimitEnabled && !iterationFailed )
+    	{
+    	iPassedIterationCnt++;
+    	}
+
+    TTime currTime;
+    currTime.HomeTime();
+    //if( iLoopCounter < iLoopTimes )
+    if(((!iTimedLoop) && (iLoopCounter < iLoopTimes)) //Normal loop
+       ||
+       iTimedLoop && (currTime.MicroSecondsFrom(iStartTime) < iExpectedLoopTime)) //Timed loop
+        {
+        // Go to beginning of the loop
+        User::LeaveIfError(
+            iTestCombiner->iSectionParser->SetPosition( iLoopStartPos ));
+        }
+    else
+        {
+        // End looping
+        if( iPasslimitEnabled )
+        	{
+	        __TRACE(KMessage, (_L("ExecuteLoopL: Loop executed. Iterations: %d, passed: %d, expected: %d"), iLoopCounter, iPassedIterationCnt, iPasslimit));
+        	}
+
+        iLoopCounter = 0;
+        iLoopTimes = 0;
+        iLoopStartPos = 0;
+        // Loop related initializations
+        iTestCombiner->iLoopIsUsed = EFalse;
+        //--LOOPBUG-- Do not zero counter because there could be some test cases run before the loop (Stif-83)
+        //--LOOPBUG-- iTestCombiner->iRunningTests = 0;
+
+        //If passlimit was given and number of passed test is less then expected, stop execution of combiner's test case
+        if( iPasslimitEnabled && iPassedIterationCnt < iPasslimit )
+        	{
+	        __TRACE( KMessage, ( _L( "ExecuteLoopL: Loop has failed (passlimit). Finishing with KErrCompletion." ) ) );
+            iTestCombiner->iScriptFailed = KErrCompletion;
+            iTestCombiner->iScriptFailedDescription = _L("Loop has not reached passlimit requirement.");
+            iState = ERunnerError;
+            CancelTestCases();
+            return ETrue; // Test case file parsing can be continue
+        	}
+        else if( iPasslimitEnabled && iPassedIterationCnt >= iPasslimit )
+        	{
+	        __TRACE( KMessage, ( _L( "ExecuteLoopL: Loop has passed (passlimit)" ) ) );
+        	}
+        iPassedIterationCnt = 0;
+        iPasslimit = 0;
+        iPasslimitEnabled = EFalse;
+        }
+
+    // Loop time is executed, free allocations that is allocated during loop
+    TInt a( 0 );
+    TInt b( 0 );
+
+    for( b = 0; b < iTestCombiner->iLoopAllocationArray.Count(); b++ )
+        {
+        //for( a = 0; a < iTestCombiner->iLoopAllocationArray.Count(); a++ )
+        for( a = 0; a < iTestCombiner->iTestCases.Count(); a++ )
+            {
+            if( a < iTestCombiner->iTestCases.Count() && iTestCombiner->iTestCases[a] == iTestCombiner->iLoopAllocationArray[b] )
+                {
+                delete iTestCombiner->iTestCases[a];
+                iTestCombiner->iTestCases.Remove( a );
+                }
+            }
+        }
+
+    for( b = 0; b < iTestCombiner->iLoopAllocationArray.Count(); b++ )
+        {
+        //for( a = 0; a < iTestCombiner->iLoopAllocationArray.Count(); a++ )
+        for( a = 0; a < iTestCombiner->iTestModules.Count(); a++ )
+            {
+            if( a < iTestCombiner->iTestModules.Count() && iTestCombiner->iTestModules[a] == iTestCombiner->iLoopAllocationArray[b] )
+                {
+                delete iTestCombiner->iTestModules[a];
+                iTestCombiner->iTestModules.Remove( a );
+                }
+            }
+        }
+
+    for( b = 0; b < iTestCombiner->iLoopAllocationArray.Count(); b++ )
+        {
+        //for( a = 0; a < iTestCombiner->iLoopAllocationArray.Count(); a++ )
+        for( a = 0; a < iTestCombiner->iEventArray.Count(); a++ )
+            {
+            if( a < iTestCombiner->iEventArray.Count() && iTestCombiner->iEventArray[a] == iTestCombiner->iLoopAllocationArray[b] )
+                {
+                delete iTestCombiner->iEventArray[a];
+                iTestCombiner->iEventArray.Remove( a );
+                }
+            }
+        }
+    for( b = 0; b < iTestCombiner->iLoopAllocationArray.Count(); b++ )
+        {
+        //for( a = 0; a < iTestCombiner->iLoopAllocationArray.Count(); a++ )
+        for( a = 0; a < iTestCombiner->iSlaveArray.Count(); a++ )
+            {
+            if( a < iTestCombiner->iSlaveArray.Count() && iTestCombiner->iSlaveArray[a] == iTestCombiner->iLoopAllocationArray[b] )
+                {
+                delete iTestCombiner->iSlaveArray[a];
+                iTestCombiner->iSlaveArray.Remove( a );
+                }
+            }
+        }
+    for( b = 0; b < iTestCombiner->iLoopAllocationArray.Count(); b++ )
+        {
+        //for( a = 0; a < iTestCombiner->iLoopAllocationArray.Count(); a++ )
+        for( a = 0; a < iTestCombiner->iSendReceive.Count(); a++ )
+            {
+            if( a < iTestCombiner->iSendReceive.Count() && iTestCombiner->iSendReceive[a] == iTestCombiner->iLoopAllocationArray[b] )
+                {
+                delete iTestCombiner->iSendReceive[a];
+                iTestCombiner->iSendReceive.Remove( a );
+                }
+            }
+        }
+
+    // Test operation can be continued
+    return ETrue; // Test case file parsing can be continue
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CRemoteTimer class 
+    member functions. 
+
+-------------------------------------------------------------------------------
+*/
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iTestRunner->iTestCombiner->iLog
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTimer
+
+     Method: CRemoteTimer
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: CTestRunner* aTestRunner: in: Backpointer to CTestRunner
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteTimer::CRemoteTimer( CTestCombiner* aTestCombiner ): 
+    CActive(  CActive::EPriorityLow ), // Executed with lowest priority 
+    iState( ETimerIdle ),
+    iTestCombiner( aTestCombiner )
+    {
+    CActiveScheduler::Add( this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTimer
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteTimer::ConstructL()
+    {
+    
+    iTimer.CreateLocal();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTimer
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to CTestCombiner
+
+     Return Values: CRemoteTimer*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+CRemoteTimer* CRemoteTimer::NewL(  CTestCombiner* aTestCombiner )
+    {
+    
+    CRemoteTimer* self = new (ELeave) CRemoteTimer( aTestCombiner );
+     
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTimer
+
+     Method: ~CRemoteTimer
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/     
+
+CRemoteTimer::~CRemoteTimer()
+    {
+    
+    Cancel();
+    
+    iTimer.Close();
+         
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTimer
+
+     Method: RunL
+
+     Description: Derived from CActive, handles testcase execution.
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteTimer::RunL()
+    {
+        
+    if( iState != ETimerPending )
+        {
+        User::Panic( KRemoteTimer, KErrGeneral );
+        }
+    
+    if( iStatus.Int() != KErrNone )
+        {
+        User::Panic( KRemoteTimer, KErrDied );
+        }
+    
+    iState = ETimerIdle;
+    
+    iTestCombiner->RemoteTimeout();
+    
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTimer
+
+     Method: DoCancel
+
+     Description: Derived from CActive handles the Cancel
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteTimer::DoCancel()
+    {
+    iTimer.Cancel();
+    iState = ETimerIdle;
+      
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteTimer
+
+     Method: SetTimerActive
+
+     Description: Starts timer
+
+     Parameters:   TTimeIntervalMicroSeconds32 anInterval: in: Timeout
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteTimer::SetTimerActive( TTimeIntervalMicroSeconds32 anInterval )
+    {
+    if( iState != ETimerIdle )
+        {
+        User::Panic( KRemoteTimer, KErrGeneral );
+        }
+        
+    iState = ETimerPending;
+    
+    iTimer.After( iStatus, anInterval );
+    SetActive();         
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CRemoteReceiver class 
+    member functions. 
+
+-------------------------------------------------------------------------------
+*/
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iTestCombiner->iLog
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteReceiver
+
+     Method: CRemoteReceiver
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to CTestCombiner
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRemoteReceiver::CRemoteReceiver( CTestCombiner* aTestCombiner ): 
+    CActive(  CActive::EPriorityStandard ), 
+    iState( EReceiverIdle ),
+    iTestCombiner( aTestCombiner )
+    {
+    CActiveScheduler::Add( this );
+    __TRACEFUNC();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteReceiver
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteReceiver::ConstructL()
+    {
+    
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteReceiver
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters: CTestCombiner* aTestCombiner: in: Backpointer to CTestCombiner
+
+     Return Values: CRemoteReceiver*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+CRemoteReceiver* CRemoteReceiver::NewL( CTestCombiner* aTestCombiner )
+    {
+    CRemoteReceiver* self = new (ELeave) CRemoteReceiver( aTestCombiner );
+     
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteReceiver
+
+     Method: ~CRemoteReceiver
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/     
+
+CRemoteReceiver::~CRemoteReceiver()
+    {
+    __TRACEFUNC();
+    Cancel();
+
+         
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteReceiver
+
+     Method: StartL
+
+     Description: Activates receiving.
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteReceiver::Start()
+    {
+    __TRACEFUNC();
+    __ASSERT_ALWAYS( iState == EReceiverIdle, 
+        User::Panic( KRemoteReceiver, KErrGeneral ) );
+    iState = EReceiverPending;
+    
+    iTestCombiner->TestModuleIf().RemoteReceive( iRemoteMsg, iStatus );        
+    SetActive();
+                 
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteReceiver
+
+     Method: RunL
+
+     Description: Derived from CActive, handles testcase execution.
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteReceiver::RunL()
+    {
+    __TRACEFUNC();
+    
+    __ASSERT_ALWAYS( iState == EReceiverPending, 
+        User::Panic( KRemoteReceiver, KErrGeneral ) );
+    iState = EReceiverIdle;
+    
+    iTestCombiner->ReceiveResponse( iRemoteMsg );
+                 
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CRemoteReceiver
+
+     Method: DoCancel
+
+     Description: Derived from CActive handles the Cancel
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CRemoteReceiver::DoCancel()
+    {
+    __TRACEFUNC();
+    
+    iTestCombiner->TestModuleIf().RemoteReceiveCancel();
+ 
+    }
+    
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+    
+     Function: LibEntryL
+
+     Description: Polymorphic Dll Entry Point
+
+     Parameters:    None.
+
+     Return Values: CTestCombiner*: pointer to new CTestCombiner
+
+     Errors/Exceptions: Leaves if NewL leaves.
+
+     Status: Approved
+     
+-------------------------------------------------------------------------------
+*/
+
+EXPORT_C CTestCombiner* LibEntryL()
+    {
+    return CTestCombiner::NewL();
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/src/TestCombinerUtils.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,995 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* CStartInfo class member functions.
+*
+*/
+
+
+// INCLUDE FILES
+#include <f32file.h>
+#include <StifLogger.h>
+#include "TestCombinerUtils.h"
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iLog
+
+// LOCAL CONSTANTS AND MACROS
+// None
+ 
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: CStartInfo
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CStartInfo::CStartInfo():
+    iModule(0,0),
+    iCaseNum(0),
+    iExpectedResult(0),
+    iTimeout(0),
+    iModuleBuf(0),
+    iIniFileBuf(0),
+    iConfigBuf(0),
+    iTestIdBuf(0),
+    iTitleBuf(0),
+	iTestCaseArgumentsBuf(0)
+    {
+
+    iCategory = TFullTestResult::ECaseExecuted; 
+
+    };
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CStartInfo::ConstructL()
+    {    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters:    None
+     
+     Return Values: CStartInfo*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CStartInfo* CStartInfo::NewL()
+    {
+
+    CStartInfo* self = new (ELeave) CStartInfo();
+     
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+
+    }    
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: ~CStartInfo
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/     
+CStartInfo::~CStartInfo()
+    {
+
+    delete iModuleBuf;
+    delete iIniFileBuf;
+    delete iConfigBuf;
+    delete iTestIdBuf;
+    delete iTitleBuf;
+	delete iTestCaseArgumentsBuf;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: SetModuleNameL
+
+     Description: Set module name.
+     
+     Parameters: TDesC& aModule: in: Module name 
+                 TInt aExtLength: in: Extra length reserved for buffer
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+ void CStartInfo::SetModuleNameL( TDesC& aModule, TInt aExtLength )
+    {
+
+    iModuleBuf = HBufC::NewL( aModule.Length() + aExtLength );
+    iModule.Set( iModuleBuf->Des() );
+    iModule.Append( aModule );
+    
+    // Remove optional '.DLL' from file name
+    iModule.LowerCase();
+    TParse parse;
+    parse.Set( iModule, NULL, NULL );
+    
+    if ( parse.Ext() == _L(".dll") )
+        {
+        const TInt len = parse.Ext().Length();
+        iModule.Delete ( iModule.Length()-len, len );
+        }
+
+
+    };
+            
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: SetIniFileL
+
+     Description: Set initialization file name name.
+     
+     Parameters: TDesC& aIni: in: Initialization file name
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/        
+void CStartInfo::SetIniFileL( TDesC& aIni )
+    {
+
+    iIniFileBuf = aIni.AllocL();
+    iIniFile.Set( iIniFileBuf->Des() );
+
+    };
+            
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: SetConfigL
+
+     Description: Set configuration file name name.
+     
+     Parameters: TDesC& aConfig: in: Configuration file name
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/        
+void CStartInfo::SetConfigL( TDesC& aConfig )
+    {
+
+    iConfigBuf = aConfig.AllocL();
+    iConfig.Set( iConfigBuf->Des() );
+
+    };
+            
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: SetTestIdL
+
+     Description: Set test identifier.
+     
+     Parameters: TDesC& aTestId: in: test identifier
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/        
+void CStartInfo::SetTestIdL( TDesC& aTestId )
+    {
+
+    iTestIdBuf = aTestId.AllocL();
+    iTestId.Set( iTestIdBuf->Des() );
+
+    };
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: DeleteModuleName
+
+     Description: Delete module name buffer for creating new module name.
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/        
+void CStartInfo::DeleteModuleName()
+    {
+    delete iModuleBuf;
+	iModuleBuf = NULL;
+    };
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: SetTitleL
+
+     Description: Set title.
+     
+     Parameters: TDesC& aTitle: in: Test case title
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/        
+void CStartInfo::SetTitleL(TDesC& aTitle)
+    {
+
+    iTitleBuf = aTitle.AllocL();
+    iTitle.Set(iTitleBuf->Des());
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStartInfo
+
+     Method: SetTestCaseArguments
+
+     Description: Sets test case arguments
+     
+     Parameters:  const TDesC& aTestCaseArguments: in: test case arguments.
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/        
+void CStartInfo::SetTestCaseArgumentsL( const TDesC& aTestCaseArguments )
+    {
+    delete iTestCaseArgumentsBuf;
+	iTestCaseArgumentsBuf = NULL;
+    iTestCaseArgumentsBuf = aTestCaseArguments.AllocL();
+	iTestCaseArguments.Set( iTestCaseArgumentsBuf->Des() );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CSlaveInfo class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CSlaveInfo
+
+     Method: CSlaveInfo
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: TUint32 aMaster: in: Master id
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CSlaveInfo::CSlaveInfo( TUint32 aMaster ):
+    iState(ESlaveIdle),
+    iMasterId(aMaster),
+    iSlaveDevId(0)
+    {
+    
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CSlaveInfo
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    TDesC& aName: in: Slave name
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CSlaveInfo::ConstructL( TDesC& aName )
+    {    
+
+    iNameBuf = aName.AllocL();
+    iName.Set( iNameBuf->Des() );
+            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CSlaveInfo
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters:    TDesC& aName: in: Slave name
+                    TUint32 aMaster: in: Master id
+
+     Return Values: CSlaveInfo*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CSlaveInfo* CSlaveInfo::NewL( TDesC& aName, TUint32 aMaster )
+    {
+
+    CSlaveInfo* self = new (ELeave) CSlaveInfo( aMaster);
+     
+    CleanupStack::PushL( self );
+    self->ConstructL( aName );
+    CleanupStack::Pop();
+
+    return self;
+
+    }    
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CSlaveInfo
+
+     Method: ~CSlaveInfo
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/     
+CSlaveInfo::~CSlaveInfo()
+    {
+    
+    iEvents.ResetAndDestroy();
+    iEvents.Close();
+    delete iNameBuf;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CSlaveInfo
+
+     Method: GetEvent
+
+     Description: Returns event with given name.
+
+     Parameters:  TDesC& aEventName: in; Event name
+
+     Return Values: TEventTc: Event structure
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TEventTc* CSlaveInfo::GetEvent( TDesC& aEventName )
+    {
+    
+    TInt count = iEvents.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( iEvents[i]->Name() == aEventName )
+            {
+            return iEvents[i];
+            }
+        }
+    return NULL;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CDefinedValue class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: CDefinedValue
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CDefinedValue::CDefinedValue()
+    {
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    TDesC& aName: in: Define name
+                    TDesC& aValue: in: Define value
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CDefinedValue::ConstructL( TDesC& aName, TDesC& aValue )
+    {    
+
+    iNameBuf = aName.AllocLC();
+    iName.Set( iNameBuf->Des() );
+    iValueBuf = aValue.AllocLC();
+    iValue.Set( iValueBuf->Des() );
+    CleanupStack::Pop( iValueBuf );
+    CleanupStack::Pop( iNameBuf );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters:    TDesC& aName: in: Define name
+                    TDesC& aValue: in: Define value
+
+     Return Values: CDefinedValue*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CDefinedValue* CDefinedValue::NewL( TDesC& aName, TDesC& aValue )
+    {
+
+    CDefinedValue* self = new (ELeave) CDefinedValue();
+     
+    CleanupStack::PushL( self );
+    self->ConstructL( aName, aValue );
+    CleanupStack::Pop();
+
+    return self;
+
+    }    
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: ~CDefinedValue
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/     
+CDefinedValue::~CDefinedValue()
+    {
+    
+    delete iValueBuf;
+    delete iNameBuf;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: SetValueL
+
+     Description: Set new define value
+
+     Parameters:    TDesC& aValue: in: Define value
+
+     Return Values: None
+
+     Errors/Exceptions: Leaves on error.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CDefinedValue::SetValueL( TDesC& aValue )
+    {
+    delete iValueBuf;
+    iValueBuf = 0;
+    iValueBuf = aValue.AllocLC();
+    iValue.Set( iValueBuf->Des() );
+    CleanupStack::Pop( iValueBuf );
+    
+    }
+
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: Name
+
+     Description: Returns define name.
+
+     Parameters:  None
+
+     Return Values: TDesC: Define name
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TDesC& CDefinedValue::Name()
+    { 
+    return iName; 
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: Value
+
+     Description: Returns define value.
+
+     Parameters:  None
+
+     Return Values: TDesC: Define value
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TDesC& CDefinedValue::Value()
+    { 
+    return iValue; 
+    }    
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TEventTc class 
+    member functions. 
+
+-------------------------------------------------------------------------------
+*/
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iLogger
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TEventTc
+
+     Method: TEventTc
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TEventTc::TEventTc( CStifLogger* aLogger ):
+    iReq(NULL),
+    iLogger( aLogger )
+    {
+    __TRACE( KMessage, (_L("TEventTc::TEventTc") ) );
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+     Class: TEventTc
+
+     Method: TEventTc
+
+     Description: Parametric constructor
+
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/ 
+TEventTc::TEventTc( TName& aEventName, CStifLogger* aLogger ):
+    iReq(NULL),
+    iLogger( aLogger )
+    {
+    SetName( aEventName );
+    SetType( EReqEvent );
+    __TRACE( KMessage, (_L("TEventTc::TEventTc %S"), &aEventName ) );
+    __TRACE( KMessage, (_L("TEvent::SetType Req") ) );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TEventTc
+
+     Method: ~TEventTc
+
+     Description: Destructor
+
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/ 
+TEventTc::~TEventTc()
+    { 
+    __TRACE( KMessage, (_L("TEventTc::~TEventTc %S"), &Name() ) );
+    Complete( KErrNone ); 
+    }
+/*
+-------------------------------------------------------------------------------
+
+     Class: TEventTc
+
+     Method: SetRequestStatus
+
+     Description: Set request status member.
+
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/ 
+void TEventTc::SetRequestStatus( TRequestStatus* aStatus )
+    { 
+    iReq = aStatus; 
+    *iReq = KRequestPending;
+    __TRACE( KMessage, (_L("TEventTc::SetRequestStatus %S"), &Name() ) );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TEventTc
+
+     Method: Complete
+
+     Description: Complete request status member.
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/ 
+void TEventTc::Complete( TInt aError )
+    { 
+    if( iReq )
+        { 
+        __TRACE( KMessage, (_L("TEventTc::Complete %S"), &Name() ) );
+        User::RequestComplete(iReq, aError ); 
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TEventTc
+
+     Method: SetEvent
+
+     Description: Set event pending.
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/ 
+void TEventTc::SetEvent( TEventType aEventType )
+    {
+    __TRACE( KMessage, (_L("TEventTc::SetEvent %S, type %d"),   
+        &Name(), aEventType ) );
+
+    SetEventType( aEventType );
+    if( iReq )
+        {
+        Complete( KErrNone );
+        if( EventType() == EState )
+            {
+            __TRACE( KMessage, (_L("TEvent::SetType Set") ) );
+            SetType( ESetEvent ) ;
+            }
+        }
+    else 
+        {
+        __TRACE( KMessage, (_L("TEvent::SetType Set") ) );
+        SetType( ESetEvent ) ;
+        }
+    }
+   
+/*
+-------------------------------------------------------------------------------
+
+     Class: TEventTc
+
+     Method: WaitEvent
+
+     Description: Wait event.
+     
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void TEventTc::WaitEvent( TRequestStatus& aStatus )
+    {
+    __TRACE( KMessage, (_L("TEventTc::WaitEvent %S"), &Name() ) );
+    SetRequestStatus( &aStatus );
+    if( Type() == ESetEvent )
+        {
+        Complete( KErrNone );
+        if( EventType() == EIndication )
+            {
+            __TRACE( KMessage, (_L("TEvent::SetType Req") ) );
+            SetType( EReqEvent );
+            }
+        }
+    }
+    
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestCombiner/src/TestKeywords.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,400 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* TTCKeywords class member functions.
+*
+*/
+
+
+// INCLUDE FILES
+#include "TestKeywords.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTCKeywords
+
+     Method: Keyword
+
+     Description: Returns a string desrciptor corresponding to keyword number. 
+
+     Parameters:    TKeywords aKeyword: in: keyword index.
+     
+     Return Values: TPtrC8: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Approved 
+    
+-------------------------------------------------------------------------------
+*/      
+TPtrC TTCKeywords::Keyword( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"title",
+        (TText*)L"run",
+        (TText*)L"cancel",
+        (TText*)L"pause",
+        (TText*)L"resume",
+        (TText*)L"complete",
+        (TText*)L"request",
+        (TText*)L"wait",
+        (TText*)L"release",
+        (TText*)L"set",
+        (TText*)L"unset",
+        (TText*)L"timeout",
+        (TText*)L"priority",
+        (TText*)L"print",
+        (TText*)L"allocate",
+        (TText*)L"free",
+        (TText*)L"remote",
+        (TText*)L"sendreceive",
+        (TText*)L"canceliferror",
+        (TText*)L"measurement",
+        (TText*)L"loop",
+        (TText*)L"endloop",
+        (TText*)L"pausecombiner",        
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTCKeywords
+
+     Method: RunOptArg
+
+     Description: Returns a string desrciptor corresponding to run keyword 
+                  optional argument number. 
+
+     Parameters:    TRunOptArgs aArg: in: run keyword optional argument index
+     
+     Return Values: TPtrC8: argument descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Approved 
+    
+-------------------------------------------------------------------------------
+*/
+TPtrC TTCKeywords::RunOptArg( TInt aArg )
+    {
+    static TText* const runOptArgs[] =
+        {
+        (TText*)L"expect",
+        (TText*)L"testid",
+        (TText*)L"ini",
+        (TText*)L"category",
+        (TText*)L"timeout",
+        (TText*)L"title",
+        (TText*)L"args",
+        };
+
+    if( aArg >= (TInt)(sizeof( runOptArgs )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          }
+
+    TPtrC arg( runOptArgs[ aArg ] );
+    return arg;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTCKeywords
+
+     Method: PauseOptArg
+
+     Description: Returns a string desrciptor corresponding to pause keyword 
+                      optional argument number. 
+
+     Parameters:    TPauseOptArgs aArg: in: argument index.
+     
+     Return Values: TPtrC8: argument descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Approved 
+    
+-------------------------------------------------------------------------------
+*/
+TPtrC TTCKeywords::PauseOptArg( TInt aArg )
+    {
+    static TText* const pauseOptArgs[] =
+        {
+        (TText*)L"time",
+        };
+    
+    if( aArg >= (TInt)(sizeof( pauseOptArgs )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC arg( pauseOptArgs[ aArg ] ); 
+    return arg;
+    
+    }
+      
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTCKeywords
+
+     Method: EventOptArg
+
+     Description: Returns a string desrciptor corresponding to event keywords 
+                      optional argument number. 
+
+     Parameters:    TEventOptArgs aArg: in: argument index.
+     
+     Return Values: TPtrC8: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Approved 
+    
+-------------------------------------------------------------------------------
+*/              
+TPtrC TTCKeywords::EventOptArg( TInt aArg )
+    {
+    static TText* const optArgs[] =
+        {
+        (TText*)L"state",
+        };
+    
+    if( aArg >= (TInt)(sizeof( optArgs )/sizeof(TText*)) )
+        {
+        TPtrC null;
+          return null;
+          } 
+    
+    TPtrC arg( optArgs[ aArg ] ); 
+    return arg;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTCKeywords
+
+     Method: ResultCategory
+
+     Description: Returns a string desrciptor corresponding to event keywords 
+                      optional argument number. 
+
+     Parameters:    TEventOptArgs aArg: in: argument index.
+     
+     Return Values: TPtrC8: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Approved 
+    
+-------------------------------------------------------------------------------
+*/              
+TPtrC TTCKeywords::Priority( TInt aArg )
+    {
+    static TText* const priority[] =
+        {
+        (TText*)L"high",
+        (TText*)L"normal",
+        (TText*)L"low",
+        };
+        
+    if( aArg >= (TInt)(sizeof( priority )/sizeof(TText*)) )
+        {
+        TPtrC null;
+        return null;
+        } 
+    
+    TPtrC arg( priority[ aArg ] ); 
+    return arg;
+    
+    }
+   
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTCKeywords
+
+     Method: Parse
+
+     Description: Returns a keyword enum corresponding to keyword 
+                      string descriptor.
+
+     Parameters:    TPtrC aKeyword: in: keyword descriptor.
+                    KeywordFunc aFunc: in: Function pointer to keyword parser 
+     
+     Return Values: TInt: keyword index
+                    KErrNotFound: keyword not found
+
+     Errors/Exceptions: None
+     
+     Status: Proposal 
+    
+-------------------------------------------------------------------------------
+*/
+TInt TTCKeywords::Parse( TDesC& aKeyword, KeywordFunc aFunc )
+    {
+    TInt ind;
+    for( ind = 0; aFunc( ind ).Length() > 0; ind++ )
+        {
+        if( aFunc( ind ) == aKeyword )
+            {
+            return ind;
+            }
+        }
+    return KErrNotFound;
+    };
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTCKeywords
+
+     Method: ResultCategory
+
+     Description: Returns a string desrciptor corresponding to result 
+        category number. 
+
+     Parameters:    TInt aArg: in: argument index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/              
+TPtrC TTCKeywords::ResultCategory( TInt aArg )
+    {
+    static TText* const category[] =
+        {
+        (TText*)L"ongoing",
+        (TText*)L"normal",
+        (TText*)L"cancelled",
+        (TText*)L"errorfrommodule",
+        (TText*)L"leave",
+        (TText*)L"panic",
+        (TText*)L"exception",
+        (TText*)L"timeout",
+        };
+        
+    if( aArg >= (TInt)(sizeof( category )/sizeof(TText*)) )
+        {
+        TPtrC null;
+        return null;
+        } 
+    
+    TPtrC arg( category[ aArg ] ); 
+    return arg;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTCKeywords
+
+     Method: ResultCategory
+
+     Description: Returns a string desrciptor corresponding to event keywords 
+                      optional argument number. 
+
+     Parameters:    TEventOptArgs aArg: in: argument index.
+     
+     Return Values: TPtrC8: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Proposal 
+    
+-------------------------------------------------------------------------------
+*/              
+TFullTestResult::TCaseExecutionResult 
+    TTCKeywords::GetResultCategory( TDesC& aCategory )
+    {
+    
+    TInt ind;
+    for( ind = 0; ResultCategory( ind ).Length() > 0; ind++ )
+        {
+        if( ResultCategory( ind ) == aCategory )
+            {
+            switch( ind )
+                {
+                case TFullTestResult::ECaseExecuted:
+                case TFullTestResult::ECaseLeave:
+                case TFullTestResult::ECasePanic:
+                case TFullTestResult::ECaseException:
+                case TFullTestResult::ECaseTimeout:
+                    return (TFullTestResult::TCaseExecutionResult)ind;
+                default:
+                    break;
+                }        
+            }
+        }      
+    return TFullTestResult::ECaseOngoing;    
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/BMARM/StifTestEngineu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,45 @@
+EXPORTS
+	__14RSettingServer @ 1 NONAME R3UNUSED ; RSettingServer::RSettingServer(void)
+	AddTestModule__11RTestEngineRCt4TBuf1i128RCt4TBuf1i256 @ 2 NONAME R3UNUSED ; RTestEngine::AddTestModule(TBuf<128> const &, TBuf<256> const &)
+	CancelAsyncRequest__11RTestEnginei @ 3 NONAME R3UNUSED ; RTestEngine::CancelAsyncRequest(int)
+	CancelAsyncRequest__9RTestCasei @ 4 NONAME R3UNUSED ; RTestCase::CancelAsyncRequest(int)
+	Close__11RTestEngine @ 5 NONAME R3UNUSED ; RTestEngine::Close(void)
+	Close__14RSettingServer @ 6 NONAME R3UNUSED ; RSettingServer::Close(void)
+	Close__17RTestEngineServer @ 7 NONAME R3UNUSED ; RTestEngineServer::Close(void)
+	Close__9RTestCase @ 8 NONAME R3UNUSED ; RTestCase::Close(void)
+	Connect__14RSettingServer @ 9 NONAME R3UNUSED ; RSettingServer::Connect(void)
+	Connect__17RTestEngineServer @ 10 NONAME R3UNUSED ; RTestEngineServer::Connect(void)
+	EnumerateTestCases__11RTestEngineRt8TPckgBuf1ZiR14TRequestStatus @ 11 NONAME R3UNUSED ; RTestEngine::EnumerateTestCases(TPckgBuf<int> &, TRequestStatus &)
+	ErrorNotification__11RTestEngineRt5TPckg1Z18TErrorNotificationR14TRequestStatus @ 12 NONAME R3UNUSED ; RTestEngine::ErrorNotification(TPckg<TErrorNotification> &, TRequestStatus &)
+	Event__11RTestEngineRt5TPckg1Z8TEventIfR14TRequestStatus @ 13 NONAME R3UNUSED ; RTestEngine::Event(TPckg<TEventIf> &, TRequestStatus &)
+	GetBooleanSettingsL__26CSTIFTestFrameworkSettingsP18CStifSectionParserG7TPtrC16Ri @ 14 NONAME ; CSTIFTestFrameworkSettings::GetBooleanSettingsL(CStifSectionParser *, TPtrC16, int &)
+	GetFileSetting__26CSTIFTestFrameworkSettingsP18CStifSectionParserG7TPtrC16R7TPtrC16 @ 15 NONAME ; CSTIFTestFrameworkSettings::GetFileSetting(CStifSectionParser *, TPtrC16, TPtrC16 &)
+	GetFormatL__26CSTIFTestFrameworkSettingsP18CStifSectionParserG7TPtrC16RQ211CStifLogger11TLoggerType @ 16 NONAME ; CSTIFTestFrameworkSettings::GetFormatL(CStifSectionParser *, TPtrC16, CStifLogger::TLoggerType &)
+	GetLoggerSettings__14RSettingServerR15TLoggerSettings @ 17 NONAME R3UNUSED ; RSettingServer::GetLoggerSettings(TLoggerSettings &)
+	GetOutputL__26CSTIFTestFrameworkSettingsP18CStifSectionParserG7TPtrC16RQ211CStifLogger7TOutput @ 18 NONAME ; CSTIFTestFrameworkSettings::GetOutputL(CStifSectionParser *, TPtrC16, CStifLogger::TOutput &)
+	GetOverwriteL__26CSTIFTestFrameworkSettingsP18CStifSectionParserG7TPtrC16Ri @ 19 NONAME ; CSTIFTestFrameworkSettings::GetOverwriteL(CStifSectionParser *, TPtrC16, int &)
+	GetReportModeL__26CSTIFTestFrameworkSettingsP18CStifSectionParserG7TPtrC16RUi @ 20 NONAME ; CSTIFTestFrameworkSettings::GetReportModeL(CStifSectionParser *, TPtrC16, unsigned int &)
+	GetTestCases__11RTestEngineRt15CFixedFlatArray1Z9TTestInfo @ 21 NONAME R3UNUSED ; RTestEngine::GetTestCases(CFixedFlatArray<TTestInfo> &)
+	NewL__26CSTIFTestFrameworkSettings @ 22 NONAME R3UNUSED ; CSTIFTestFrameworkSettings::NewL(void)
+	NotifyProgress__9RTestCaseRt5TPckg1Z13TTestProgressR14TRequestStatus @ 23 NONAME R3UNUSED ; RTestCase::NotifyProgress(TPckg<TTestProgress> &, TRequestStatus &)
+	NotifyRemoteMsg__9RTestCaseR5TDes812TStifCommand @ 24 NONAME R3UNUSED ; RTestCase::NotifyRemoteMsg(TDes8 &, TStifCommand)
+	NotifyRemoteType__9RTestCaseRt5TPckg1Z12TStifCommandRt5TPckg1ZiR14TRequestStatus @ 25 NONAME ; RTestCase::NotifyRemoteType(TPckg<TStifCommand> &, TPckg<int> &, TRequestStatus &)
+	OpenLoggerSession__11RTestEngineR17RTestEngineServerR15TLoggerSettings @ 26 NONAME R3UNUSED ; RTestEngine::OpenLoggerSession(RTestEngineServer &, TLoggerSettings &)
+	Open__11RTestEngineR17RTestEngineServerRCt4TBuf1i256 @ 27 NONAME R3UNUSED ; RTestEngine::Open(RTestEngineServer &, TBuf<256> const &)
+	Open__9RTestCaseR17RTestEngineServerRCt5TPckg1Z9TTestInfo @ 28 NONAME R3UNUSED ; RTestCase::Open(RTestEngineServer &, TPckg<TTestInfo> const &)
+	Pause__9RTestCase @ 29 NONAME R3UNUSED ; RTestCase::Pause(void)
+	ReadLoggerSettingsFromIniFile__14RSettingServerR15TLoggerSettings @ 30 NONAME R3UNUSED ; RSettingServer::ReadLoggerSettingsFromIniFile(TLoggerSettings &)
+	RemoveConfigFile__11RTestEngineRCt4TBuf1i128RCt4TBuf1i256 @ 31 NONAME R3UNUSED ; RTestEngine::RemoveConfigFile(TBuf<128> const &, TBuf<256> const &)
+	RemoveTestModule__11RTestEngineRCt4TBuf1i128 @ 32 NONAME R3UNUSED ; RTestEngine::RemoveTestModule(TBuf<128> const &)
+	Resume__9RTestCase @ 33 NONAME R3UNUSED ; RTestCase::Resume(void)
+	RunTestCase__9RTestCaseRt5TPckg1Z15TFullTestResultR14TRequestStatus @ 34 NONAME R3UNUSED ; RTestCase::RunTestCase(TPckg<TFullTestResult> &, TRequestStatus &)
+	SetAttribute__11RTestEngine10TAttributeRC7TDesC16 @ 35 NONAME R3UNUSED ; RTestEngine::SetAttribute(TAttribute, TDesC16 const &)
+	SetIniFileInformation__14RSettingServerRCt4TBuf1i256 @ 36 NONAME R3UNUSED ; RSettingServer::SetIniFileInformation(TBuf<256> const &)
+	SetNewIniFileSetting__14RSettingServerRt4TBuf1i128 @ 37 NONAME R3UNUSED ; RSettingServer::SetNewIniFileSetting(TBuf<128> &)
+	StartEngine__Fv @ 38 NONAME R3UNUSED ; StartEngine(void)
+	StartNewServer__FRt4TBuf1i128 @ 39 NONAME R3UNUSED ; StartNewServer(TBuf<128> &)
+	Version__C14RSettingServer @ 40 NONAME R3UNUSED ; RSettingServer::Version(void) const
+	Version__C17RTestEngineServer @ 41 NONAME R3UNUSED ; RTestEngineServer::Version(void) const
+	"_._26CSTIFTestFrameworkSettings" @ 42 NONAME R3UNUSED ; CSTIFTestFrameworkSettings::~CSTIFTestFrameworkSettings(void)
+	AddConfigFile__11RTestEngineRCt4TBuf1i128RCt4TBuf1i256 @ 43 NONAME R3UNUSED ; RTestEngine::AddConfigFile(TBuf<128> const &, TBuf<256> const &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/BWINS/StifTestEngineu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,65 @@
+EXPORTS
+	??0RSettingServer@@QAE@XZ @ 1 NONAME ; public: __thiscall RSettingServer::RSettingServer(void)
+	??1CSTIFTestFrameworkSettings@@UAE@XZ @ 2 NONAME ; public: virtual __thiscall CSTIFTestFrameworkSettings::~CSTIFTestFrameworkSettings(void)
+	?AddConfigFile@RTestEngine@@QAEHABV?$TBuf@$0IA@@@ABV?$TBuf@$0BAA@@@@Z @ 3 NONAME ; public: int __thiscall RTestEngine::AddConfigFile(class TBuf<128> const &,class TBuf<256> const &)
+	?AddTestModule@RTestEngine@@QAEHABV?$TBuf@$0IA@@@ABV?$TBuf@$0BAA@@@@Z @ 4 NONAME ; public: int __thiscall RTestEngine::AddTestModule(class TBuf<128> const &,class TBuf<256> const &)
+	?CancelAsyncRequest@RTestCase@@QAEHH@Z @ 5 NONAME ; public: int __thiscall RTestCase::CancelAsyncRequest(int)
+	?CancelAsyncRequest@RTestEngine@@QAEHH@Z @ 6 NONAME ; public: int __thiscall RTestEngine::CancelAsyncRequest(int)
+	?Close@RSettingServer@@QAEXXZ @ 7 NONAME ; public: void __thiscall RSettingServer::Close(void)
+	?Close@RTestCase@@QAEXXZ @ 8 NONAME ; public: void __thiscall RTestCase::Close(void)
+	?Close@RTestEngine@@QAEXXZ @ 9 NONAME ; public: void __thiscall RTestEngine::Close(void)
+	?Close@RTestEngineServer@@QAEXXZ @ 10 NONAME ; public: void __thiscall RTestEngineServer::Close(void)
+	?Connect@RSettingServer@@QAEHXZ @ 11 NONAME ; public: int __thiscall RSettingServer::Connect(void)
+	?Connect@RTestEngineServer@@QAEHXZ @ 12 NONAME ; public: int __thiscall RTestEngineServer::Connect(void)
+	?EnumerateTestCases@RTestEngine@@QAEXAAV?$TPckgBuf@H@@AAVTRequestStatus@@@Z @ 13 NONAME ; public: void __thiscall RTestEngine::EnumerateTestCases(class TPckgBuf<int> &,class TRequestStatus &)
+	?ErrorNotification@RTestEngine@@QAEXAAV?$TPckg@VTErrorNotification@@@@AAVTRequestStatus@@@Z @ 14 NONAME ; public: void __thiscall RTestEngine::ErrorNotification(class TPckg<class TErrorNotification> &,class TRequestStatus &)
+	?Event@RTestEngine@@QAEXAAV?$TPckg@VTEventIf@@@@AAVTRequestStatus@@@Z @ 15 NONAME ; public: void __thiscall RTestEngine::Event(class TPckg<class TEventIf> &,class TRequestStatus &)
+	?GetBooleanSettingsL@CSTIFTestFrameworkSettings@@QAEHPAVCStifSectionParser@@VTPtrC16@@AAH@Z @ 16 NONAME ; public: int __thiscall CSTIFTestFrameworkSettings::GetBooleanSettingsL(class CStifSectionParser *,class TPtrC16,int &)
+	?GetFileSetting@CSTIFTestFrameworkSettings@@QAEHPAVCStifSectionParser@@VTPtrC16@@AAV3@@Z @ 17 NONAME ; public: int __thiscall CSTIFTestFrameworkSettings::GetFileSetting(class CStifSectionParser *,class TPtrC16,class TPtrC16 &)
+	?GetFormatL@CSTIFTestFrameworkSettings@@QAEHPAVCStifSectionParser@@VTPtrC16@@AAW4TLoggerType@CStifLogger@@@Z @ 18 NONAME ; public: int __thiscall CSTIFTestFrameworkSettings::GetFormatL(class CStifSectionParser *,class TPtrC16,enum CStifLogger::TLoggerType &)
+	?GetLoggerSettings@RSettingServer@@QAEHAAUTLoggerSettings@@@Z @ 19 NONAME ; public: int __thiscall RSettingServer::GetLoggerSettings(struct TLoggerSettings &)
+	?GetOutputL@CSTIFTestFrameworkSettings@@QAEHPAVCStifSectionParser@@VTPtrC16@@AAW4TOutput@CStifLogger@@@Z @ 20 NONAME ; public: int __thiscall CSTIFTestFrameworkSettings::GetOutputL(class CStifSectionParser *,class TPtrC16,enum CStifLogger::TOutput &)
+	?GetOverwriteL@CSTIFTestFrameworkSettings@@QAEHPAVCStifSectionParser@@VTPtrC16@@AAH@Z @ 21 NONAME ; public: int __thiscall CSTIFTestFrameworkSettings::GetOverwriteL(class CStifSectionParser *,class TPtrC16,int &)
+	?GetReportModeL@CSTIFTestFrameworkSettings@@QAEHPAVCStifSectionParser@@VTPtrC16@@AAI@Z @ 22 NONAME ; public: int __thiscall CSTIFTestFrameworkSettings::GetReportModeL(class CStifSectionParser *,class TPtrC16,unsigned int &)
+	?GetTestCases@RTestEngine@@QAEHAAV?$CFixedFlatArray@VTTestInfo@@@@@Z @ 23 NONAME ; public: int __thiscall RTestEngine::GetTestCases(class CFixedFlatArray<class TTestInfo> &)
+	?NewL@CSTIFTestFrameworkSettings@@SAPAV1@XZ @ 24 NONAME ; public: static class CSTIFTestFrameworkSettings * __cdecl CSTIFTestFrameworkSettings::NewL(void)
+	?NotifyProgress@RTestCase@@QAEXAAV?$TPckg@VTTestProgress@@@@AAVTRequestStatus@@@Z @ 25 NONAME ; public: void __thiscall RTestCase::NotifyProgress(class TPckg<class TTestProgress> &,class TRequestStatus &)
+	?NotifyRemoteMsg@RTestCase@@QAEHAAVTDes8@@W4TStifCommand@@@Z @ 26 NONAME ; public: int __thiscall RTestCase::NotifyRemoteMsg(class TDes8 &,enum TStifCommand)
+	?NotifyRemoteType@RTestCase@@QAEXAAV?$TPckg@W4TStifCommand@@@@AAV?$TPckg@H@@AAVTRequestStatus@@@Z @ 27 NONAME ; public: void __thiscall RTestCase::NotifyRemoteType(class TPckg<enum TStifCommand> &,class TPckg<int> &,class TRequestStatus &)
+	?Open@RTestCase@@QAEHAAVRTestEngineServer@@ABV?$TPckg@VTTestInfo@@@@@Z @ 28 NONAME ; public: int __thiscall RTestCase::Open(class RTestEngineServer &,class TPckg<class TTestInfo> const &)
+	?Open@RTestEngine@@QAEHAAVRTestEngineServer@@ABV?$TBuf@$0BAA@@@@Z @ 29 NONAME ; public: int __thiscall RTestEngine::Open(class RTestEngineServer &,class TBuf<256> const &)
+	?OpenLoggerSession@RTestEngine@@QAEHAAVRTestEngineServer@@AAUTLoggerSettings@@@Z @ 30 NONAME ; public: int __thiscall RTestEngine::OpenLoggerSession(class RTestEngineServer &,struct TLoggerSettings &)
+	?Pause@RTestCase@@QAEHXZ @ 31 NONAME ; public: int __thiscall RTestCase::Pause(void)
+	?ReadLoggerSettingsFromIniFile@RSettingServer@@QAEHAAUTLoggerSettings@@@Z @ 32 NONAME ; public: int __thiscall RSettingServer::ReadLoggerSettingsFromIniFile(struct TLoggerSettings &)
+	?RemoveConfigFile@RTestEngine@@QAEHABV?$TBuf@$0IA@@@ABV?$TBuf@$0BAA@@@@Z @ 33 NONAME ; public: int __thiscall RTestEngine::RemoveConfigFile(class TBuf<128> const &,class TBuf<256> const &)
+	?RemoveTestModule@RTestEngine@@QAEHABV?$TBuf@$0IA@@@@Z @ 34 NONAME ; public: int __thiscall RTestEngine::RemoveTestModule(class TBuf<128> const &)
+	?Resume@RTestCase@@QAEHXZ @ 35 NONAME ; public: int __thiscall RTestCase::Resume(void)
+	?RunTestCase@RTestCase@@QAEXAAV?$TPckg@VTFullTestResult@@@@AAVTRequestStatus@@@Z @ 36 NONAME ; public: void __thiscall RTestCase::RunTestCase(class TPckg<class TFullTestResult> &,class TRequestStatus &)
+	?SetAttribute@RTestEngine@@QAEHW4TAttribute@@ABVTDesC16@@@Z @ 37 NONAME ; public: int __thiscall RTestEngine::SetAttribute(enum TAttribute,class TDesC16 const &)
+	?SetIniFileInformation@RSettingServer@@QAEHABV?$TBuf@$0BAA@@@@Z @ 38 NONAME ; public: int __thiscall RSettingServer::SetIniFileInformation(class TBuf<256> const &)
+	?SetNewIniFileSetting@RSettingServer@@QAEHAAV?$TBuf@$0IA@@@@Z @ 39 NONAME ; public: int __thiscall RSettingServer::SetNewIniFileSetting(class TBuf<128> &)
+	?StartEngine@@YAHXZ @ 40 NONAME ; int __cdecl StartEngine(void)
+	?StartNewServer@@YAHAAV?$TBuf@$0IA@@@@Z @ 41 NONAME ; int __cdecl StartNewServer(class TBuf<128> &)
+	?Version@RSettingServer@@QBE?AVTVersion@@XZ @ 42 NONAME ; public: class TVersion __thiscall RSettingServer::Version(void)const 
+	?Version@RTestEngineServer@@QBE?AVTVersion@@XZ @ 43 NONAME ; public: class TVersion __thiscall RTestEngineServer::Version(void)const 
+	??1CTestModuleList@@UAE@XZ @ 44 NONAME ; CTestModuleList::~CTestModuleList(void)
+	?AddCfgFile@CTestModuleInfo@@QAEHAAVTDesC16@@@Z @ 45 NONAME ; int CTestModuleInfo::AddCfgFile(class TDesC16 &)
+	?AddTestModule@CTestModuleList@@QAEHAAVTDesC16@@@Z @ 46 NONAME ; int CTestModuleList::AddTestModule(class TDesC16 &)
+	?Count@CTestModuleList@@QAEHXZ @ 47 NONAME ; int CTestModuleList::Count(void)
+	?CountCfgFiles@CTestModuleInfo@@QAEHXZ @ 48 NONAME ; int CTestModuleInfo::CountCfgFiles(void)
+	?GetCfgFileName@CTestModuleInfo@@QAEHHAAVTDes16@@@Z @ 49 NONAME ; int CTestModuleInfo::GetCfgFileName(int, class TDes16 &)
+	?GetIniFileName@CTestModuleInfo@@QAEHAAVTDes16@@@Z @ 50 NONAME ; int CTestModuleInfo::GetIniFileName(class TDes16 &)
+	?GetModule@CTestModuleList@@QAEPAVCTestModuleInfo@@AAVTDesC16@@@Z @ 51 NONAME ; class CTestModuleInfo * CTestModuleList::GetModule(class TDesC16 &)
+	?GetModule@CTestModuleList@@QAEPAVCTestModuleInfo@@H@Z @ 52 NONAME ; class CTestModuleInfo * CTestModuleList::GetModule(int)
+	?GetModuleName@CTestModuleInfo@@QAEHAAVTDes16@@@Z @ 53 NONAME ; int CTestModuleInfo::GetModuleName(class TDes16 &)
+	?GetUncheckedCfgFile@CTestModuleList@@QAEPAVCTestCaseFileInfo@@XZ @ 54 NONAME ; class CTestCaseFileInfo * CTestModuleList::GetUncheckedCfgFile(void)
+	?NewL@CTestModuleList@@SAPAV1@PAVCStifLogger@@@Z @ 55 NONAME ; class CTestModuleList * CTestModuleList::NewL(class CStifLogger *)
+	?SetIniFile@CTestModuleInfo@@QAEHAAVTDesC16@@@Z @ 56 NONAME ; int CTestModuleInfo::SetIniFile(class TDesC16 &)
+	?GetCfgFileName@CTestCaseFileInfo@@QAEHAAVTDes16@@@Z @ 57 NONAME ; int CTestCaseFileInfo::GetCfgFileName(class TDes16 &)
+	?SetChecked@CTestCaseFileInfo@@QAEXXZ @ 58 NONAME ; void CTestCaseFileInfo::SetChecked(void)
+	?GetEngineSettings@RSettingServer@@QAEHAAUTEngineSettings@@@Z @ 59 NONAME ; int RSettingServer::GetEngineSettings(struct TEngineSettings &)
+	?StoreEngineSettings@RSettingServer@@QAEHAAUTEngineSettings@@@Z @ 60 NONAME ; int RSettingServer::StoreEngineSettings(struct TEngineSettings &)
+	?GetFormatL@CSTIFTestFrameworkSettings@@QAEHPAVCStifSectionParser@@VTPtrC16@@AAW4TLoggerType@CStifLogger@@AAH@Z @ 61 NONAME ; int CSTIFTestFrameworkSettings::GetFormatL(class CStifSectionParser *, class TPtrC16, enum CStifLogger::TLoggerType &, int &)
+	?AddTestCaseResultToTestReport@RTestEngine@@QAEHABVTTestInfo@@ABVTFullTestResult@@H@Z @ 62 NONAME ; int RTestEngine::AddTestCaseResultToTestReport(class TTestInfo const &, class TFullTestResult const &, int)
+	?RunTestCase@RTestCase@@QAEXAAV?$TPckg@VTFullTestResult@@@@ABVTDesC16@@AAVTRequestStatus@@@Z @ 63 NONAME ; void RTestCase::RunTestCase(class TPckg<class TFullTestResult> &, class TDesC16 const &, class TRequestStatus &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/eabi/StifTestEngineu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,114 @@
+EXPORTS
+	_Z11StartEnginev @ 1 NONAME
+	_Z14StartNewServerR4TBufILi128EE @ 2 NONAME
+	_ZN11RTestEngine12GetTestCasesER15CFixedFlatArrayI9TTestInfoE @ 3 NONAME
+	_ZN11RTestEngine12SetAttributeE10TAttributeRK7TDesC16 @ 4 NONAME
+	_ZN11RTestEngine13AddConfigFileERK4TBufILi128EERKS0_ILi256EE @ 5 NONAME
+	_ZN11RTestEngine13AddTestModuleERK4TBufILi128EERKS0_ILi256EE @ 6 NONAME
+	_ZN11RTestEngine16RemoveConfigFileERK4TBufILi128EERKS0_ILi256EE @ 7 NONAME
+	_ZN11RTestEngine16RemoveTestModuleERK4TBufILi128EE @ 8 NONAME
+	_ZN11RTestEngine17ErrorNotificationER5TPckgI18TErrorNotificationER14TRequestStatus @ 9 NONAME
+	_ZN11RTestEngine17OpenLoggerSessionER17RTestEngineServerR15TLoggerSettings @ 10 NONAME
+	_ZN11RTestEngine18CancelAsyncRequestEi @ 11 NONAME
+	_ZN11RTestEngine18EnumerateTestCasesER8TPckgBufIiER14TRequestStatus @ 12 NONAME
+	_ZN11RTestEngine4OpenER17RTestEngineServerRK4TBufILi256EE @ 13 NONAME
+	_ZN11RTestEngine5CloseEv @ 14 NONAME
+	_ZN11RTestEngine5EventER5TPckgI8TEventIfER14TRequestStatus @ 15 NONAME
+	_ZN14RSettingServer17GetLoggerSettingsER15TLoggerSettings @ 16 NONAME
+	_ZN14RSettingServer20SetNewIniFileSettingER4TBufILi128EE @ 17 NONAME
+	_ZN14RSettingServer21SetIniFileInformationERK4TBufILi256EE @ 18 NONAME
+	_ZN14RSettingServer29ReadLoggerSettingsFromIniFileER15TLoggerSettings @ 19 NONAME
+	_ZN14RSettingServer5CloseEv @ 20 NONAME
+	_ZN14RSettingServer7ConnectEv @ 21 NONAME
+	_ZN14RSettingServerC1Ev @ 22 NONAME
+	_ZN14RSettingServerC2Ev @ 23 NONAME
+	_ZN17RTestEngineServer5CloseEv @ 24 NONAME
+	_ZN17RTestEngineServer7ConnectEv @ 25 NONAME
+	_ZN26CSTIFTestFrameworkSettings10GetFormatLEP18CStifSectionParser7TPtrC16RN11CStifLogger11TLoggerTypeE @ 26 NONAME
+	_ZN26CSTIFTestFrameworkSettings10GetOutputLEP18CStifSectionParser7TPtrC16RN11CStifLogger7TOutputE @ 27 NONAME
+	_ZN26CSTIFTestFrameworkSettings13GetOverwriteLEP18CStifSectionParser7TPtrC16Ri @ 28 NONAME
+	_ZN26CSTIFTestFrameworkSettings14GetFileSettingEP18CStifSectionParser7TPtrC16RS2_ @ 29 NONAME
+	_ZN26CSTIFTestFrameworkSettings14GetReportModeLEP18CStifSectionParser7TPtrC16Rj @ 30 NONAME
+	_ZN26CSTIFTestFrameworkSettings19GetBooleanSettingsLEP18CStifSectionParser7TPtrC16Ri @ 31 NONAME
+	_ZN26CSTIFTestFrameworkSettings4NewLEv @ 32 NONAME
+	_ZN26CSTIFTestFrameworkSettingsD0Ev @ 33 NONAME
+	_ZN26CSTIFTestFrameworkSettingsD1Ev @ 34 NONAME
+	_ZN26CSTIFTestFrameworkSettingsD2Ev @ 35 NONAME
+	_ZN9RTestCase11RunTestCaseER5TPckgI15TFullTestResultER14TRequestStatus @ 36 NONAME
+	_ZN9RTestCase14NotifyProgressER5TPckgI13TTestProgressER14TRequestStatus @ 37 NONAME
+	_ZN9RTestCase15NotifyRemoteMsgER5TDes812TStifCommand @ 38 NONAME
+	_ZN9RTestCase16NotifyRemoteTypeER5TPckgI12TStifCommandERS0_IiER14TRequestStatus @ 39 NONAME
+	_ZN9RTestCase18CancelAsyncRequestEi @ 40 NONAME
+	_ZN9RTestCase4OpenER17RTestEngineServerRK5TPckgI9TTestInfoE @ 41 NONAME
+	_ZN9RTestCase5CloseEv @ 42 NONAME
+	_ZN9RTestCase5PauseEv @ 43 NONAME
+	_ZN9RTestCase6ResumeEv @ 44 NONAME
+	_ZNK14RSettingServer7VersionEv @ 45 NONAME
+	_ZNK17RTestEngineServer7VersionEv @ 46 NONAME
+	_ZTI11CTestEngine @ 47 NONAME ; #<TI>#
+	_ZTI11CTestReport @ 48 NONAME ; #<TI>#
+	_ZTI13CErrorPrinter @ 49 NONAME ; #<TI>#
+	_ZTI13CRebootParams @ 50 NONAME ; #<TI>#
+	_ZTI14CLoggerSetting @ 51 NONAME ; #<TI>#
+	_ZTI14CSettingServer @ 52 NONAME ; #<TI>#
+	_ZTI16CTestCaseTimeout @ 53 NONAME ; #<TI>#
+	_ZTI17CTestEngineServer @ 54 NONAME ; #<TI>#
+	_ZTI18CTestEventNotifier @ 55 NONAME ; #<TI>#
+	_ZTI19CTestCaseController @ 56 NONAME ; #<TI>#
+	_ZTI20CTestEventController @ 57 NONAME ; #<TI>#
+	_ZTI21CTestModuleController @ 58 NONAME ; #<TI>#
+	_ZTI21CTestProgressNotifier @ 59 NONAME ; #<TI>#
+	_ZTI22CTestRemoteCmdNotifier @ 60 NONAME ; #<TI>#
+	_ZTI23CTestScripterController @ 61 NONAME ; #<TI>#
+	_ZTI26CSTIFTestFrameworkSettings @ 62 NONAME ; #<TI>#
+	_ZTI9CTestCase @ 63 NONAME ; #<TI>#
+	_ZTV11CTestEngine @ 64 NONAME ; #<VT>#
+	_ZTV11CTestReport @ 65 NONAME ; #<VT>#
+	_ZTV13CErrorPrinter @ 66 NONAME ; #<VT>#
+	_ZTV13CRebootParams @ 67 NONAME ; #<VT>#
+	_ZTV14CLoggerSetting @ 68 NONAME ; #<VT>#
+	_ZTV14CSettingServer @ 69 NONAME ; #<VT>#
+	_ZTV16CTestCaseTimeout @ 70 NONAME ; #<VT>#
+	_ZTV17CTestEngineServer @ 71 NONAME ; #<VT>#
+	_ZTV18CTestEventNotifier @ 72 NONAME ; #<VT>#
+	_ZTV19CTestCaseController @ 73 NONAME ; #<VT>#
+	_ZTV20CTestEventController @ 74 NONAME ; #<VT>#
+	_ZTV21CTestModuleController @ 75 NONAME ; #<VT>#
+	_ZTV21CTestProgressNotifier @ 76 NONAME ; #<VT>#
+	_ZTV22CTestRemoteCmdNotifier @ 77 NONAME ; #<VT>#
+	_ZTV23CTestScripterController @ 78 NONAME ; #<VT>#
+	_ZTV26CSTIFTestFrameworkSettings @ 79 NONAME ; #<VT>#
+	_ZTV9CTestCase @ 80 NONAME ; #<VT>#
+	_ZN15CTestModuleInfo10AddCfgFileER7TDesC16 @ 81 NONAME
+	_ZN15CTestModuleInfo10SetIniFileER7TDesC16 @ 82 NONAME
+	_ZN15CTestModuleInfo13CountCfgFilesEv @ 83 NONAME
+	_ZN15CTestModuleInfo13GetModuleNameER6TDes16 @ 84 NONAME
+	_ZN15CTestModuleInfo14GetCfgFileNameEiR6TDes16 @ 85 NONAME
+	_ZN15CTestModuleInfo14GetIniFileNameER6TDes16 @ 86 NONAME
+	_ZN15CTestModuleList13AddTestModuleER7TDesC16 @ 87 NONAME
+	_ZN15CTestModuleList19GetUncheckedCfgFileEv @ 88 NONAME
+	_ZN15CTestModuleList4NewLEP11CStifLogger @ 89 NONAME
+	_ZN15CTestModuleList5CountEv @ 90 NONAME
+	_ZN15CTestModuleList9GetModuleER7TDesC16 @ 91 NONAME
+	_ZN15CTestModuleList9GetModuleEi @ 92 NONAME
+	_ZN15CTestModuleListD0Ev @ 93 NONAME
+	_ZN15CTestModuleListD1Ev @ 94 NONAME
+	_ZN15CTestModuleListD2Ev @ 95 NONAME
+	_ZN17CTestCaseFileInfo10SetCheckedEv @ 96 NONAME
+	_ZN17CTestCaseFileInfo14GetCfgFileNameER6TDes16 @ 97 NONAME
+	_ZTI15CTestModuleInfo @ 98 NONAME ; #<TI>#
+	_ZTI15CTestModuleList @ 99 NONAME ; #<TI>#
+	_ZTI17CTestCaseFileInfo @ 100 NONAME ; #<TI>#
+	_ZTV15CTestModuleInfo @ 101 NONAME ; #<VT>#
+	_ZTV15CTestModuleList @ 102 NONAME ; #<VT>#
+	_ZTV17CTestCaseFileInfo @ 103 NONAME ; #<VT>#
+	_ZTI20CTestCommandNotifier @ 104 NONAME ; #<TI>#
+	_ZTV20CTestCommandNotifier @ 105 NONAME ; #<VT>#
+	_ZN14RSettingServer17GetEngineSettingsER15TEngineSettings @ 106 NONAME
+	_ZN14RSettingServer19StoreEngineSettingsER15TEngineSettings @ 107 NONAME
+	_ZTI21CTestEngineSubSession @ 108 NONAME ; #<TI>#
+	_ZTV21CTestEngineSubSession @ 109 NONAME ; #<VT>#
+	_ZN26CSTIFTestFrameworkSettings10GetFormatLEP18CStifSectionParser7TPtrC16RN11CStifLogger11TLoggerTypeERi @ 110 NONAME
+	_ZN11RTestEngine29AddTestCaseResultToTestReportERK9TTestInfoRK15TFullTestResulti @ 111 NONAME
+	_ZN9RTestCase11RunTestCaseER5TPckgI15TFullTestResultERK7TDesC16R14TRequestStatus @ 112 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/group/TestEngine.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,63 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestEngine module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+#include        "../../inc/STIFConfiguration.mmh"
+
+TARGET          StifTestEngine.dll
+TARGETTYPE      dll
+
+UID             0x1000008D 0x101FB3DF
+
+CAPABILITY      ALL -TCB
+VENDORID        0x101FB657
+SECUREID        0x102073E0
+
+DEFFILE         StifTestEngine.def
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+
+SOURCE          TestEngineClient.cpp
+SOURCE          TestEngine.cpp
+SOURCE          TestCaseController.cpp
+SOURCE          TestModuleController.cpp
+SOURCE          TestReport.cpp
+SOURCE          Testcasetimeout.cpp
+SOURCE          STIFTestFrameworkSettings.cpp
+SOURCE          SettingServerClient.cpp
+SOURCE          SettingServer.cpp
+SOURCE          SettingServerSession.cpp
+SOURCE          StifPythonFunEng.cpp
+SOURCE          TestModuleInfo.cpp
+
+LIBRARY         euser.lib
+LIBRARY         hal.lib                 // For logging (HAL)
+LIBRARY         stiftestserver.lib
+LIBRARY         efsrv.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         atslogger.lib
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for STIF TestEngine.
+*/
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	TestEngine.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/Logging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,70 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains logging macros for test engine.
+*
+*/
+
+#ifndef LOGGINGDEFS_H
+#define LOGGINGDEFS_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+// CONSTANTS
+const TUint KError           = 0x1;
+const TUint KInit            = 0x2;
+const TUint KVerbose         = 0x4;
+const TUint KAlways          = 0xFFFFFFFF;
+const TUint KDebugLevel      = ( KInit | KError );
+
+// MACROS
+#define __TRACING_ENABLED
+
+// Define USE_LOGGER to use logger for logging
+#define USE_LOGGER
+
+#ifdef __TRACING_ENABLED
+
+    // Disable conditional expression is constant -warning
+    #pragma warning( disable : 4127 )
+
+    // Using logger
+    #if defined (USE_LOGGER)
+    #define __TRACE(level,p) if ( (level) & KDebugLevel) { LOGGER->Log p; }
+    #else
+    #define __TRACE(level,p);
+    #endif
+
+    #define __RDEBUG(x) if( KVerbose & KDebugLevel){ RDebug::Print x ; }
+
+#else
+    // No tracing
+    #define __TRACE(level,p);
+    
+    #define __RDEBUG(x)
+
+#endif
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+#endif // LOGGINGDEFS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/STIFTestFrameworkSettings.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CSTIFTestFrameworkSettings.
+*
+*/
+
+#ifndef STIFTESTFRAMEWORKSETTINGS_H
+#define STIFTESTFRAMEWORKSETTINGS_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <StifLogger.h>
+#include <StifParser.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CSTIFTestFrameworkSettings is a STIF Test Framework Test Engine class.
+// Class contains different operations of settings parsing from Test Framework
+// initíalization file.
+
+class CSTIFTestFrameworkSettings 
+        :public CBase
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CSTIFTestFrameworkSettings* NewL();
+
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~CSTIFTestFrameworkSettings();
+
+    public:     // New functions
+
+        /**
+        * Get report mode settings from STIF TestFramework's ini file.
+        */
+        IMPORT_C TInt GetReportModeL( CStifSectionParser* aSectionParser,
+                                                TPtrC aTag,
+                                                TUint& aSetting );
+
+        /**
+        * Get file settings from STIF TestFramework's ini file.
+        */
+        IMPORT_C TInt GetFileSetting( CStifSectionParser* aSectionParser,
+                                                TPtrC aTag,
+                                                TPtrC& aSetting );
+
+        /**
+        * Get format setting from STIF TestFramework's ini file.
+        */
+        IMPORT_C TInt GetFormatL( CStifSectionParser* aSectionParser,
+                                        TPtrC aTag,
+                                        CStifLogger::TLoggerType& aLoggerType );
+
+        /**
+        * Get output setting from STIF TestFramework's ini file.
+        */
+        IMPORT_C TInt GetOutputL( CStifSectionParser* aSectionParser,
+                                        TPtrC aTag,
+                                        CStifLogger::TOutput& aOutput );
+
+        /**
+        * Get boolean type of settings from STIF TestFramework's ini file.
+        */
+        IMPORT_C TInt GetBooleanSettingsL( CStifSectionParser* aSectionParser,
+                                            TPtrC aTag,
+                                            TBool& aOverwrite );
+
+        /**
+        * Get file creation mode setting from STIF TestFramework's ini file.
+        */
+        IMPORT_C TInt GetOverwriteL( CStifSectionParser* aSectionParser,
+                                                TPtrC aTag,
+                                                TBool& aOverwrite );
+
+        /**
+        * Get format setting from STIF TestFramework's ini file.
+        */
+        IMPORT_C TInt GetFormatL( CStifSectionParser* aSectionParser,
+                                        TPtrC aTag,
+                                        CStifLogger::TLoggerType& aLoggerType,
+                                        TBool &aXML );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CSTIFTestFrameworkSettings();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // STIFTESTFRAMEWORKSETTINGS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/SettingServer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,305 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CSettingServer.
+*
+*/
+
+#ifndef SETTING_SERVER_H
+#define SETTING_SERVER_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifLogger.h>
+#include "Logging.h"
+#include "TestEngineClient.h"
+
+// CONSTANTS
+
+// Server heap size
+const TUint KDefaultHeapSize = 0x10000;     // 64 K
+const TUint KMaxHeapSize     = 0x20000;     // 128 K 
+
+// MACROS
+
+// DATA TYPES
+
+// Panic reasons
+enum TSettingServerPanic
+    {
+    EBadRequest,
+    EBadDescriptor,
+    EMainSchedulerError,
+    ESvrCreateServer,
+    ECreateTrapCleanup,
+    ENoStartupInformation,
+    ETooManyCloseSessions,
+    EPopFromEmptyStack
+    };
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CSettingServer is a server class.
+class CSettingServer
+    :public CServer2 // Inter Process Communication version 2 is used(EKA2)
+    {
+    public: // Enumerations
+        enum { ESettingServerSchedulerPriority = CActive::EPriorityHigh };
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CSettingServer* NewL( const TName& aName );
+
+        /**
+        * Destructor of CSettingServer.
+        */
+        ~CSettingServer();
+
+    public: // New functions
+
+        /**
+        * ThreadFunction is used to create new thread.
+        */
+        static TInt ThreadFunction( TAny* aStarted );       
+
+        /**
+        * PanicServer panics the CSettingServer
+        */
+        static void PanicServer( const TSettingServerPanic aPanic );
+
+        /**
+        * Return pointer to the Logger(iSettingServerLogger)
+        */
+        CStifLogger* CSettingServer::Logger();
+
+    public: // Functions from base classes
+
+        /**
+        * NewSessionL creates new CSettingServer session.
+        */
+        CSession2* NewSessionL( const TVersion &aVersion,
+                                    const RMessage2& aMessage ) const;
+        /**
+        * Open session
+        */
+        void OpenSession();
+
+        /**
+        * Close session
+        */
+        void CloseSession();
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CSettingServer();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+
+        // NOTE:
+        // There is one CSettingServer and may be many CLoggerSetting sessions
+        // so variables are defined here and are available to all sessions.
+
+        // Logger overwrite settings
+        TLoggerSettings         iLoggerSettings;
+
+        // Includes inifile name and path information
+        TFileName               iIniFile;
+        
+        // Engine settings
+        TEngineSettings         iEngineSettings;
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Session counter
+        TInt                    iSessions;
+
+        // Logger instance
+        CStifLogger*            iSettingServerLogger;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// CLoggerSetting is a session class.
+// Session for the CSettingServer server, to a single client-side session
+// a session may own any number of CCounter objects
+
+class CLoggerSetting
+    :public CSession2
+    {    
+    public:
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+
+        /**
+        * Construct a clean-up server session
+        */
+        static CLoggerSetting* NewL( CSettingServer* aServer );
+
+        /**
+        * Destructor
+        */
+        virtual ~CLoggerSetting();
+
+    public: // New functions
+
+        /**
+        * Dispatch message
+        */
+        TInt DispatchMessageL( const RMessage2& aMessage,
+                                TBool& aIsMessageSync );
+
+        /**
+        * Close the session to CSettingpServer.
+        */
+        TInt CloseSession( /*const RMessage& aMessage*/ );
+
+        /**
+        * Read Logger setting from initialization file. Mainly use from
+        * TestEngine side.
+        */
+        TInt ReadLoggerSettingsFromIniFile( const RMessage2& aMessage );
+
+        /**
+        * Set initialization filename and path settings to Setting server.
+        */
+        TInt SetIniFileSettings( const RMessage2& aMessage );
+
+        /**
+        * Get Logger settings. Mainly use from Logger side.
+        */
+        TInt GetLoggerSettings( const RMessage2& aMessage );
+
+        /**
+        * 
+        */
+        TInt SetNewIniFileSetting( const RMessage2& aMessage );
+
+        /**
+        * PanicClient panics the user of CLoggerSetting
+        */
+        void PanicClient( TInt aPanic, const RMessage2& aMessage ) const;
+        
+        /**
+        * Get test engine settings
+        */
+        TInt GetEngineSettings(const RMessage2& aMessage);
+
+        /**
+        * Set (store) test engine settings
+        */
+        TInt StoreEngineSettings(const RMessage2& aMessage);
+
+    public: // Functions from base classes
+
+        /**
+        * ServiceL handles the messages to CSettingServer
+        */
+        virtual void ServiceL( const RMessage2& aMessage );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CLoggerSetting();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CSettingServer* aServer );
+
+        /**
+        * Real resource reservation routine
+        */
+        TInt ReserveInternalL( const RMessage2& aMessage );
+
+        /**
+        * Read Logger default parameters for initialization file.
+        */
+        TInt ReadLoggerDefaults();
+
+    public:     // Data
+        // None
+   
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to "parent"
+        CSettingServer*         iSettingServer;
+
+        // Indication for reading logger defaults from initialization file.
+        TBool                   iReadOrUpdateLoggerDefaults;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif // SETTING_SERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/StifPythonFunEng.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header of additional 
+* functions needed for Python support and used in PythonScripter, 
+* TestEngine and TestCombiner.
+*
+*/
+
+#ifndef STIFPYTHONFUNENG_H
+#define STIFPYTHONFUNENG_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+TInt GetNewIndexForThreadL(void);
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+// None
+
+#endif        // STIFPYTHONFUNENG_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/TestCallBack.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CTestCallBack class.
+*
+*/
+
+#ifndef TESTCALLBACK_H
+#define TESTCALLBACK_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Simple class for callbacks.
+
+class CCallBack 
+    :public CAsyncCallBack
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * C++ constructor.
+        */
+        //CCallBack( TInt aPriority ):CAsyncCallBack( aPriority ) {}
+
+        /**
+        * C++ constructor.
+        */
+        CCallBack( TCallBack& aCallBack, TInt aPriority ):
+            CAsyncCallBack( aCallBack, aPriority ) {}
+
+        /**
+        * C++ destructor.
+        */
+        ~CCallBack(){ Cancel(); }
+
+    public: // New functions
+        /**
+        * Return reference to TRequestStatus member.
+        */
+        TRequestStatus& Status(){ return iStatus; }
+
+        /**
+        * Set CCallBack active.
+        */
+        void SetActive()
+            { 
+            iStatus = KRequestPending; 
+            CActive::SetActive(); 
+            };
+
+    public: // Functions from base classes
+
+        /**
+        * Handle completion.
+        */
+        void RunL(){ iCallBack.CallBack(); }
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // TESTCALLBACK_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/TestCaseController.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,910 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CTestCaseController, the CTestProgressNotifier and the 
+* CTestEventNotifier.
+*
+*/
+
+#ifndef TEST_CASE_CONTROLLER_H
+#define TEST_CASE_CONTROLLER_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <stifinternal/TestServerClient.h>
+#include <atslogger.h>
+#include "TestEngine.h"
+#include "TestCallBack.h"
+
+#include "StifHWReset.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+typedef CStifHWReset*( *CTestInterfaceFactory )();
+
+// FORWARD DECLARATIONS
+class CTestModuleController;
+class CTestReport;
+class CTestCaseTimeout;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestCaseController is an active object used for running the test case
+// using the RTestExecution API.
+class CTestCaseController
+        : public CActive
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+
+        // TTestCaseStatus defines the status of test case
+        enum TTestCaseStatus
+            {
+            ETestCaseIdle,
+            ETestCaseRunning,
+            ETestCaseCompleted,
+            ETestCaseTimeout,
+            ETestCaseSuicided, //test case has killed itself
+            };
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestCaseController* NewL( CTestEngine* aEngine,
+            CTestReport* aTestReport,
+            CAtsLogger& aAtsLogger,
+            RTestExecution aTestExecution, 
+            const TTestInfo& aTestInfo );
+
+        /**
+        * Destructor.
+        */
+        ~CTestCaseController();
+
+    public:     // New functions
+
+        /**
+        * StartL starts the CTestCaseController active object.
+        */
+        void StartL( const RMessage2& aMessage );
+
+        /**
+        * Timeouts a testcase
+        */
+        void Timeout();
+
+        /**
+        * Kills a testcase
+        */
+        void Suicide(TStopExecutionType aType, TInt aCode);
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+        
+        /**
+        * Get testcase info(test module, config file, test case, etc).
+        */
+        void GetTestCaseInfo( TTestInfo& aTestInfo );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestCaseController( CTestEngine* aEngine, 
+                             CTestReport* aTestReport,
+                             CAtsLogger& aAtsLogger,
+                             RTestExecution aTestExecution,
+                             const TTestInfo& aTestInfo );
+        
+        /**
+        * Generates XML log about the test case.
+        */
+        void GenerateXmlLogL();
+
+    public:     // Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to CTestEngine
+        CTestEngine*        iEngine;
+
+        // Pointer to Test Report
+        CTestReport*        iTestReport;
+
+        // Handle to RTestExecution
+        RTestExecution      iTestExecution;
+
+        // Pointer to timeout handler
+        CTestCaseTimeout*    iTimeout;
+
+        // Test Info
+        TTestInfo           iTestInfo;
+
+        // Test case arguments
+		HBufC*              iTestCaseArguments;
+        
+        // Internal state
+        TTestCaseStatus     iState;
+
+        // Test Result
+        TFullTestResult     iResult;
+        TFullTestResultPckg iResultPckg;
+
+        // Message to be completed when case is finished
+        RMessage2            iMessage;
+
+        // AtsLogger
+        CAtsLogger&         iAtsLogger;
+
+        // RDebug logging for testcase status
+        CStifLogger*        iRDebugLogger;
+
+        // Stop execution type
+        TStopExecutionType  iStopExecutionType;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+
+        friend class CTestRemoteCmdNotifier;
+
+    };
+
+// DESCRIPTION
+// CTestProgressNotifier is an active object used for notifications called from
+// Test Module using the RTestExecution API.
+class CTestProgressNotifier
+        : public CActive
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+
+        // TTestProgressStatus defines the status of notification
+        enum TTestProgressStatus
+            {
+            ETestProgressIdle,
+            ETestProgressPending,
+            ETestProgressCompleted
+            };
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestProgressNotifier* NewL( CTestEngine* aEngine, 
+                             RTestExecution aTestExecution );
+
+        /**
+        * Destructor.
+        */
+        ~CTestProgressNotifier();
+
+    public:     // New functions
+
+        /**
+        * StartL starts the CTestProgressNotifier active object.
+        */
+        void StartL( const RMessage2& aMessage );
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestProgressNotifier( CTestEngine* aEngine, 
+                               RTestExecution aTestExecution );
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to CTestEngine
+        CTestEngine*        iEngine;
+
+        // Handle to RTestExecution
+        RTestExecution      iTestExecution;
+
+        // Internal state
+        TTestProgressStatus iState;
+
+        // Test Progress
+        TTestProgress       iProgress;
+        TTestProgressPckg   iProgressPckg;
+
+        // Message to be completed when notification is completed
+        RMessage2           iMessage;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// CTestEventNotifier is an active object used for event notify from
+// Test Module using the RTestExecution API.
+class CTestEventNotifier
+        : public CActive
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+
+        // TTestEventStatus defines the status of notification
+        enum TTestEventStatus
+            {
+            ETestEventIdle,
+            ETestEventPending,
+            ETestEventCompleted
+            };
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestEventNotifier* NewL( CTestEngine* aEngine,  
+            RTestExecution aTestExecution );
+
+        /**
+        * Destructor.
+        */
+        ~CTestEventNotifier();
+        
+    public:     // New functions
+
+        /**
+        * StartL starts the CTestEventNotifier active object.
+        */
+        void Start();
+
+        /**
+        * For event control.
+        */
+        void CtlEvent( const TEventIf& aEvent, TRequestStatus& aStatus );
+
+		/**
+		* Check if CtlEvent should be called
+		*/
+        TBool CheckCtlEvent( const TEventIf& aEvent );
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:      // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestEventNotifier( CTestEngine* aEngine,
+             RTestExecution aTestExecution);
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to CTestEngine
+        CTestEngine* iEngine;
+
+        // Handle to RTestExecution
+        RTestExecution iTestExecution;
+
+        // Internal state
+        TTestEventStatus iState;
+
+        // Event interface
+        TEventIf iEvent;
+        TEventIfPckg iEventPckg;
+        TEventIf iEventNotify;
+        TEventIfPckg iEventNotifyPckg;
+
+        // Event array
+        RPointerArray<HBufC> iEventArray;
+
+        // Associated event controller
+        CTestEventController* iController;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// CTestEventController is used for event controlling from
+// TestEngine.
+class CTestEventController
+        : public CBase
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestEventController* NewL( CTestEngine* aEngine,
+                                           const TEventIf& aEvent,
+                                           TRequestStatus* aStatus );
+  
+        static CTestEventController* NewL( CTestEngine* aEngine,
+                                           const TEventIf& aEvent,
+                                           RMessage2& aMessage );
+
+        /**
+        * Destructor.
+        */
+        ~CTestEventController();
+
+    public:     // New functions
+        /**
+        * Event complete.
+        */ 
+        void EventComplete();
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TRequestStatus* aStatus );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( RMessage2& aMessage );
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestEventController( CTestEngine* aEngine, const TEventIf& aEvent );
+
+        /**
+        * Check all events.
+        */ 
+        TBool CheckEventsL();
+
+        /**
+        * Check client events.
+        */ 
+        TBool CheckClientEventsL();
+
+        /**
+        * Check testcase events.
+        */ 
+        TBool CheckTestcaseEventsL(); 
+
+        /**
+        * Callback for event controller.
+        */ 
+        static TInt EventCallBack( TAny* aTestEventController );
+
+    public:     // Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to CTestEngine
+        CTestEngine*    iEngine;
+
+        // Either of these is completed when ready
+        // If aRequestStatus exists, it is completed,
+        // otherwise aMessage is completed.
+        TRequestStatus* iRequestStatus;
+        RMessage2        iMessage;
+
+        // Event interface
+        TEventIf iEvent;
+        TEventIfPckg iEventPckg;
+
+        // Number of active event commands
+        TInt iActiveEventCmds;
+        
+        RPointerArray<CCallBack> iEventCallBacks;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// CTestCaseTimeout is used for time controlling
+class CTestCaseTimeout
+        : public CActive
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+        // None
+         
+    public:     // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CTestCaseTimeout* NewL( CTestCaseController* aCase,
+                     TTimeIntervalMicroSeconds aTimeout );
+
+        /**
+        * Destructor.
+        */
+        ~CTestCaseTimeout();
+        
+    public:     // New functions
+        
+        /**
+        * Starts timeout counting
+        */
+        void Start();
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL(CTestCaseController* aCase,
+               TTimeIntervalMicroSeconds aTimeout );
+
+        /**
+        * C++ constructor.
+        */
+        CTestCaseTimeout();
+
+    public:     // Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CTestCaseController* iCase;
+        TTimeIntervalMicroSeconds iTimeout;
+        RTimer iTimer;
+        
+        // Storage for testcase timeout.
+        TTime iTestCaseTimeout;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+    
+// DESCRIPTION
+// CTestProgressNotifier is an active object used for notifications called from
+// Test Module using the RTestExecution API.
+class CTestRemoteCmdNotifier
+        : public CActive
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+
+        // TTestProgressStatus defines the status of notification
+        enum TTestProgressStatus
+            {
+            ETestProgressIdle,
+            ETestProgressPending,
+            ETestProgressCompleted
+            };
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestRemoteCmdNotifier* NewL( CTestEngine* aEngine, 
+                             RTestExecution aTestExecution ,
+                             CTestCaseController* aTestCaseController,
+                             CAtsLogger& aAtsLogger );
+
+        /**
+        * Destructor.
+        */
+        ~CTestRemoteCmdNotifier();
+
+    public:     // New functions
+
+        /**
+        * StartL starts the CTestRemoteCmdNotifier active object.
+        */
+        //void StartL( const RMessage& aMessage );
+
+        /**
+        * EnableReceive prepares to start active object
+        */
+        void EnableReceive( const RMessage2& aMessage );
+
+        /**
+        * GetReceivedMsg get received message.
+        */
+        void GetReceivedMsg( const RMessage2& aMessage );
+
+        /**
+        * Start starts the CTestCaseController active object.
+        */
+        void Start( const RMessage2& aMessage );
+
+        /**
+        * CancelReq cancels the request.
+        */
+        void CancelReq();
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestRemoteCmdNotifier( CTestEngine* aEngine, 
+                               RTestExecution aTestExecution,
+                               CTestCaseController* aTestCaseController,
+                               CAtsLogger& aAtsLogger );
+
+        /**
+        * Loads dynamically reset module.
+        */
+        TInt DynamicResetModule( CTestModuleIf::TRebootType aResetType );
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to CTestEngine
+        CTestEngine*        iEngine;
+
+        // Handle to RTestExecution
+        RTestExecution      iTestExecution;
+
+        // Internal state
+        TTestProgressStatus iState;
+
+        // Remote command's definition
+        TStifCommand          iRemoteType;
+        TStifCommandPckg      iRemoteTypePckg;
+                
+        TInt                    iMsgSize;              
+        TPckg<TInt>             iMsgSizePckg;              
+
+        // Message to be completed when notification is completed
+        RMessage2           iMessage;
+        
+        HBufC8*             iReceivedMsg;
+
+        TInt                iRebootCode;
+        TName               iRebootName;
+
+        // Pointer to CTestCaseController
+        CTestCaseController* iTestCaseController;
+
+        TBool               iMessageAvail;
+        
+        CAtsLogger&         iAtsLogger;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// CTestCommandNotifier is an active object used for command notify from
+// Test Module using the RTestExecution API.
+// It was created to allow test case to kill itself.
+class CTestCommandNotifier: public CActive
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+        // None
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestCommandNotifier* NewL(CTestEngine* aEngine, RTestExecution aTestExecution);
+
+        /**
+        * Destructor.
+        */
+        ~CTestCommandNotifier();
+
+    public:     // New functions
+
+        /**
+        * StartL starts the CTestCommandNotifier active object.
+        */
+        void Start();
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError(TInt aError);
+
+    protected:      // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Parametric C++ constructor.
+        */
+        CTestCommandNotifier(CTestEngine* aEngine, RTestExecution aTestExecution);
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to CTestEngine
+        CTestEngine*     iEngine;
+
+        // Handle to RTestExecution
+        RTestExecution   iTestExecution;
+
+        // Command to be sent
+        TCommand                        iCommand;
+        TCommandPckg                    iCommandPckg;
+        TBuf8<KMaxCommandParamsLength2>  iParamsPckg;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+#endif // TEST_CASE_CONTROLLER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/TestEngine.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,988 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CTestEngine.
+*
+*/
+
+#ifndef TEST_ENGINE_H
+#define TEST_ENGINE_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifLogger.h>
+#include <StifParser.h>
+#include <stifinternal/TestServerClient.h>
+#include "TestEngineClient.h"
+#include "TestEngineEvent.h"
+#include "STIFTestFrameworkSettings.h"
+#include "SettingServerClient.h"
+#include "STIFMeasurement.h"
+#include "TestModuleInfo.h"
+
+// CONSTANTS
+// Heap sizes needed for creating server thread.
+const TUint KTestEngineMinHeapSize = 0x10000;
+const TUint KTestEngineMaxHeapSize = 0x100000;
+
+// MACROS
+// None
+
+// DATA TYPES
+
+// Panic reasons
+enum TTestEnginePanic
+    {
+    EBadRequest,
+    EBadDescriptor,
+    EMainSchedulerError,
+    ESvrCreateServer,
+    ECreateTrapCleanup,
+    EBadSubsessionHandle,
+    ENoStartupInformation,
+    EInvalidModuleName,
+    EReqPending,
+    EDoCancelDisorder,
+    ECancelAsyncIPCError,
+    EEventPanic
+    };
+
+// Struct to Test report settings
+NONSHARABLE_CLASS(CTestReportSettings)
+	:public CBase
+    {
+    public:
+    
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CTestReportSettings* NewL();
+
+
+       ~CTestReportSettings();
+       
+    private:
+       CTestReportSettings();
+       /**
+       * By default Symbian OS constructor is private.
+       */
+       void ConstructL();
+
+    public:
+
+        TBool                   iCreateTestReport; // Test report creation mode
+        HBufC*                  iPath;             // Test report path
+        HBufC*                  iName;             // Test report name
+        CStifLogger::TLoggerType iFormat;          // Test report file type
+        CStifLogger::TOutput    iOutput;           // Test report output
+        TBool                   iOverwrite;        // Test report overwrite
+        TBool                   iXML;              // Test report in xml format
+
+    };
+
+class CRebootParams
+    :public CBase
+    {
+    public:     // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CRebootParams* NewL();
+
+        /**
+        * Destructor of CTestEngineServer.
+        */
+        ~CRebootParams();
+        
+        // Setters
+        void SetTestModuleNameL( const TDesC& aName ); 
+        void SetTestCaseFileNameL( const TDesC& aName ); 
+        void SetTestCaseTitleL( const TDesC& aName ); 
+        void SetTestCaseStateL( const TDesC& aName ); 
+
+     
+     private:    // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CRebootParams();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+        
+      public: // Data
+        TInt iCaseNumber;
+        TInt iStateCode;
+
+        TPtrC iTestModule;
+        TPtrC iTestCaseFile;
+        TPtrC iTestCaseTitle;
+        TPtrC iStateName;
+              
+      private: // Data   
+        HBufC* iTestModuleBuf;
+        HBufC* iTestCaseFileBuf;
+        HBufC* iTestCaseTitleBuf;
+        HBufC* iStateNameBuf;
+        
+    };
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CTestModuleController;
+class CTestReport;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestEngineServer is a server class.
+// Contains an object container index which provides subsessions with object
+// containers.
+
+class CTestEngineServer
+        : public CServer2
+    {
+    public:     // Enumerations
+        enum { ETestEngineServerPriority = CActive::EPriorityHigh };
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CTestEngineServer* NewL();
+
+        /**
+        * Destructor of CTestEngineServer.
+        */
+        ~CTestEngineServer();
+
+    public:     // New functions
+
+        /**
+        * ThreadFunction is used to create new thread.
+        */
+        static TInt ThreadFunction( TAny* aStarted );
+
+        /**
+        * Return object container, guaranteed to produce object containers with
+        * unique ids within the server.
+        */
+        CObjectCon* NewContainerL();
+
+        /**
+        * Delete container.
+        */
+        void DeleteContainer( CObjectCon* aContainer );
+
+        /**
+        * Inform Server that session is closed.
+        */
+        void SessionClosed();
+
+        /**
+        * PanicServer panics the CTestEngineServer
+        */
+        static void PanicServer( TTestEnginePanic aPanic );
+
+        /**
+        * Return the pointer to iLogger
+        */
+        CStifLogger* Logger();
+
+    public:     // Functions from base classes
+
+        /**
+        * NewSessionL creates new CTestEngineServer session.
+        */
+        CSession2* NewSessionL( const TVersion &aVersion,
+                                const RMessage2& aMessage ) const;
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CTestEngineServer();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+
+    public:     // Data
+        // Test report settings
+        CTestReportSettings*     iTestReportSettings;
+
+        // Logger overwrite settings
+        TLoggerSettings         iLoggerSettings;
+
+    protected:  // Data
+
+    private:    // Data
+        // The server has an object container index which
+        // creates an object container for each session
+        CObjectConIx*           iContainerIndex; 
+
+        // Logger instance
+        CStifLogger*            iLogger;
+
+        // Container count
+        TInt                    iSessionCount;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// DESCRIPTION
+// Class used to store version information of test module.
+// iTestModuleName field keeps name of test module dll
+// iVersion keeps version of test module dll
+        
+    struct TTestModuleVersionInfo
+    {
+    	TFileName iTestModuleName;
+    	TInt iMajor;
+    	TInt iMinor;
+    	TInt iBuild;
+    };
+
+// DESCRIPTION
+// CTestEngine is a session class.
+// Session for the CTestEngineServer server, to a single client-side session
+// a session may own any number of CCounter objects
+
+class CTestCase;
+class CTestEventController;
+class CTestEngine
+        : public CSession2
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CTestEngine* NewL( CTestEngineServer* aServer );
+
+        /**
+        * Leave with notify
+        */
+        void LeaveWithNotifyL( TInt aCode, const TDesC& aText );
+
+        /**
+        * If error leave with notify
+        */
+        void LeaveIfErrorWithNotify( TInt aCode, const TDesC& aText );
+
+        /**
+        * Leave with notify
+        */
+        void LeaveWithNotifyL( TInt aCode );
+
+        /**
+        * If error leave with notify
+        */
+        void LeaveIfErrorWithNotify( TInt aCode );
+
+        /**
+        * Close the session to CTestEngineServer.
+        */
+        void CloseSession();
+
+    public:     // New functions
+
+        /**
+        * PanicClient panics the user of CTestEngine ( RTestEngine user )
+        */
+        void PanicClient( TTestEnginePanic aPanic, const RMessage2& aMessage ) const;
+
+        /**
+        * NumResources is used to provide reserver resources to client.
+        */
+        void NumResources( const RMessage2& aMessage );
+
+        /**
+        * Return the number of resources owned by the session. 
+        * Required by CSession if derived class implements resource
+        * mark-start and mark-end protocol.
+        */
+        TInt CountResources();
+
+        /**
+        * Callback to inform that enumeration of test cases is completed
+        */
+        void EnumerationCompleted( TInt aCount, TInt aError = KErrNone );
+
+
+        /**
+        * Callback to check state event status.
+        */
+        TBool IsStateEventAndSet( const TName& aEventName );
+
+        /**
+        * Callback to control events.
+        */
+        CTestEventController* CtlEventL( const TEventIf& aEvent, 
+                                         TRequestStatus& aStatus );
+
+        /**
+        * Return the pointer to CStifLogger owned by CTestEngineServer
+        */
+        CStifLogger* Logger();
+
+        /**
+        * Return testcases.
+        */
+        RPointerArray<CTestCase>& TestCaseArray(){ return iTestCaseArray; }
+
+        /**
+        * Return client events.
+        */
+        RPointerArray<TEventMsg>& ClientEvents(){ return iClientEvents; }
+
+        /**
+        * ErrorPrint print errors. This version is used to print engine own
+        * errors.
+        */
+        void ErrorPrint( const TInt aPriority, 
+                         TPtrC aError );
+
+        /**
+        * ErrorPrint print errors. This version is used to forward errors.
+        */
+        void ErrorPrint( TErrorNotificationPckg aError );
+
+        /**
+        * Write the Reboot related information to file.
+        */
+        TInt WriteRebootParams( TTestInfo& aTestInfo,
+                                TInt& aCode, TDesC& aName );
+
+        /**
+        * Read the Reboot related information from the file.
+        */
+        TInt ReadRebootParams( TTestInfo& aTestInfo, 
+                               TDes& aStateDes,
+                               TInt& aState );
+
+        /**
+        * Pause all test case(s) which are/is running.
+        */
+        void PauseAllTestCases();
+        
+        /**
+        * Flush ATS logger buffers.
+        */ 
+        void FlushAtsLogger();
+        
+        /**
+        * Get device reset module's DLL name.
+        */
+        TPtrC GetDeviceResetDllName();
+
+        /**
+        * Get measurements related information. Returns is measurement disable.
+        */
+        TInt StifMeasurement();
+        
+        /**
+        * For Recovering from serious testmodulecrash situations (KErrserverTerminated (-15))
+        * Clones TestModuleController
+        */
+        void TestModuleCrash( CTestModuleController* aTestModuleController );
+
+        /**
+        * Executes command received from test case.
+        * It was created to allow test case to kill itself.
+        */
+        void ExecuteCommandL(TCommand aCommand, TDesC8& aParamsPckg);
+
+        /**
+        * Returns new index for test module controller.
+        * This number is appended to module controller name.
+        * This method is used when option to run every test case in separate
+        * process is set to on.                        
+        */
+        TInt GetIndexForNewTestModuleController(void);
+
+        /**
+        * Return free module controller specified by given parameter.
+        * If it can't be found, new one will be created.                        
+        */
+        CTestModuleController* GetFreeOrCreateModuleControllerL(TTestInfo& aTestInfo,
+                                                                CTestModuleController** aRealModuleController);
+
+    public:     // Functions from base classes
+
+        /**
+        * ServiceL handles the messages to CTestEngineServer
+        */
+        virtual void ServiceL( const RMessage2& aMessage );
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CTestEngine();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CTestEngineServer* aServer );
+
+        /**
+        * DispatchMessageL handles the messages to CTestEngineServer
+        */
+        void DispatchMessageL( const RMessage2& aMessage );
+
+        /**
+        * Get module controller by name
+        */
+        CTestModuleController* ModuleControllerByName(
+                                                const TName& aModuleName );
+
+        /**
+        * Initialize test report and logger's overwrite variables
+        */
+        void InitTestReportAndLoggerVarL();
+
+        /**
+        * Initialize the Test Engine.
+        */
+        void InitEngineL( const RMessage2& aMessage );
+
+        /**
+        * Parse Test Engine defaults from STIF initialization
+        * file.
+        */
+        void ReadEngineDefaultsL( CStifParser* aParser,
+                                    CSTIFTestFrameworkSettings* aSettings );
+
+        /**
+        * Set parsed logger's settings to TestEngine side.
+        */
+        void SetLoggerSettings( TLoggerSettings& aLoggerSettings );
+
+        /**
+        * Parse Test modules and module information from STIFTestFramework
+        * initialization file.
+        */
+        void ReadTestModulesL( CStifParser* aParser );
+
+        /**
+        * 
+        */
+        void TestModuleConfigFileL( CTestModuleController* aModule,
+                                        CStifSectionParser* aSectionParser,
+                                        TDesC& aTag );
+
+        /**
+        * Sets attributes to Test Framework
+        */
+        void SetAttributeL( const RMessage2& aMessage );
+
+        /**
+        * Adds new Test Module
+        */
+        void AddTestModuleL( const RMessage2& aMessage );
+
+        /**
+        * Removes Test Module
+        */
+        TInt RemoveTestModuleL( const RMessage2& aMessage );
+        
+        /**
+        * Close Test Engine
+        */
+        void CloseTestEngineL( TUint aHandle );
+
+        /**
+        * Adds new config file to Test Module
+        */
+        void AddConfigFileL( const RMessage2& aMessage );
+
+        /**
+        * Removes config file from test module
+        */
+        void RemoveConfigFileL( const RMessage2& aMessage );
+        
+        /**
+        * Enumerates test cases
+        */
+        void EnumerateTestCasesL( const RMessage2& aMessage );
+
+        /**
+        * Get test cases
+        */
+        void GetTestCasesL( const RMessage2& aMessage );
+
+        /**
+        * Cancel outstanding asynchronous request
+        */
+        void CancelAsyncRequest( const RMessage2& aMessage );
+
+        /**
+        * Event system control.
+        */
+        void EventControlL( const RMessage2& aMessage );
+
+        /**
+        * Update state event list.
+        */ 
+        void UpdateEventL( const TEventIf& aEvent );
+
+        /**
+        * Handles error notifications
+        */
+        void HandleErrorNotificationL( const RMessage2& iMessage );
+
+        /**
+        * Get Logger's overwrite parameters
+        */
+        void LoggerSettings( const RMessage2& iMessage );
+
+        /**
+        * Close logger settings
+        */
+        void CloseLoggerSettings();
+
+        /**
+        * Process error queue.
+        */
+        void ProcessErrorQueue();
+
+        /**
+        * Resolve the correct CTestCase object
+        */
+        CTestCase* TestCaseByHandle( TUint aHandle, const RMessage2& aMessage );
+
+        /**
+        * Create CTestCase subsession.
+        */
+        void NewTestCaseL( const RMessage2& aMessage );
+
+        /**
+        * Destroy the created CTestCase subsession.
+        * Cannot fail - can panic client.
+        */
+        void DeleteTestCase( TUint aHandle );
+     
+        /**
+        * Parse the Reboot related information from the file.
+        */
+        TInt ParseRebootParamsL();
+
+        /**
+        * Set measurements related information, enable measurement.
+        */
+        TInt EnableStifMeasurement( const TDesC& aInfoType );
+
+        /**
+        * Set measurements related information, disable measurement.
+        */
+        TInt DisableStifMeasurement( const TDesC& aInfoType );
+
+        /**
+        * Parse and search for module info and fill list of modules.
+        */
+        void ParseTestModulesL(CStifParser* aParser, CTestModuleList* aModuleList, const TDesC& aSectionStart, const TDesC& aSectionEnd);
+
+        /**
+        * Add test case info to test report.
+        */
+        TInt AddTestCaseToTestReport(const RMessage2& aMessage);
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+        // Test module array
+        RPointerArray<CTestModuleController> iModules;
+
+        // Object container for this session
+        CObjectCon*                 iContainer;
+
+        // Object index which stores objects (CTestCase instances)
+        // for this session
+        CObjectIx*                  iTestCases;
+        
+        // Object index which stores objects (CTestEngineSubSession instances)
+        // for this session
+        CObjectIx*                  iTestEngineSubSessions;
+        
+        // Array of CTestCase instances
+        RPointerArray<CTestCase>    iTestCaseArray;
+
+        // Pointer to owning server
+        CTestEngineServer*          iTestEngineServer;
+
+        // Test Report
+        CTestReport*                iTestReport;
+        // Test Report Mode
+        TUint                       iReportMode;
+        // Test Report Output Type
+        TUint                       iReportOutput;
+
+        // Device reset module's DLL name(Reboot)
+        HBufC*                      iDeviceResetDllName;
+
+        // Total number of resources allocated
+        TInt                        iResourceCount;
+
+        // Test Engine's initialization file
+        HBufC*                      iIniFile;
+
+        // RMessage for ongoing operation
+        RMessage2                   iEnumerationMessage;
+
+        // Test case count used in EnumerateTestCases
+        TInt                        iCaseCount;
+        // Error code used in EnumerateTestCases
+        TInt                        iEnumError;
+
+        // Tell if message can be completed
+        TBool                       iComplete;
+
+        // Error code for complete of message
+        TInt                        iReturn;
+
+        // State event Array
+        RPointerArray<HBufC>        iStateEvents;
+        
+        // Client event Array
+        RPointerArray<TEventMsg>    iClientEvents;
+
+        // Number of enumerated test modules currently
+        TInt                        iEnumerateModuleCount;
+
+        // RMessage for error notifications
+        TBool                       iErrorMessageAvailable;
+        RMessage2                   iErrorMessage;
+        RArray<TErrorNotification>    iErrorQueue;
+
+        // Reboot path definition
+        HBufC*                      iRebootPath;
+        // Reboot file name definition
+        HBufC*                      iRebootFilename;
+        // Reboot default path definition
+        TPtrC                       iRebootDefaultPath;
+        // Reboot default file name definition
+        TPtrC                       iRebootDefaultFilename;
+
+        // Handle to Setting server.
+        RSettingServer              iSettingServer;
+        
+        CRebootParams*              iRebootParams;
+        TBool                       iIsTestReportGenerated;
+
+        // For indication is measurement disable
+        TInt                        iDisableMeasurement;
+        
+        // Default timeout value. 0 - no timeout value
+        TInt64                      iDefaultTimeout;
+
+        // Counter for created TestModuleControllers
+        TInt                        iIndexTestModuleControllers;
+        
+        // Is this UI testing?
+        // If yes, then Test Engine works in a specific way.
+        // It creates new process for every test scripter's test case
+        // and deletes it after test case has finished.
+        TBool                       iUITestingSupport;
+
+        // Should every test case be executed in separate process?
+        // This option is similar to iUITestingSupport, however
+        // it does not delete the process after test case is finished.
+        TBool                       iSeparateProcesses;
+        
+        //RPointerArray of versions of test modules
+        RPointerArray<TTestModuleVersionInfo> iTestModulesVersionInfo;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// DESCRIPTION
+// CTestEngineSubSession represents a subsession object in the CTestEngineServer.
+// A session may own any number of CTestEngineSubSession objects
+
+class CTestEngineSubSession
+        : public CObject
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CTestEngineSubSession* NewL( CTestEngine* aEngine );
+
+        /**
+        * Destructor of CTestCase.
+        */
+        ~CTestEngineSubSession();
+
+    public:     // New functions
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+    	CTestEngineSubSession( CTestEngine* aEngine);
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+    public:     // Data
+    
+    protected:  // Data
+
+        // Session owning us
+        CTestEngine*            iTestEngine;
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+    };
+
+    
+// DESCRIPTION
+// CTestCase represents a subsession object in the CTestEngineServer.
+// A session may own any number of CTestCase objects
+
+class CTestProgressNotifier;
+class CTestCaseController;
+class CTestEventNotifier;
+class CTestRemoteCmdNotifier;
+class CTestCommandNotifier;
+class CTestCase
+        : public CObject
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CTestCase* NewL( CTestEngine* aEngine,
+            CTestModuleController* aModuleController,
+            CTestReport* aTestReport,
+            TTestInfo& aTestInfo,
+            CTestModuleController* aRealModuleController);
+
+        /**
+        * Destructor of CTestCase.
+        */
+        ~CTestCase();
+
+        /**
+        * Close Test Case.
+        */
+        void CloseTestCase();
+
+    public:     // New functions
+
+        /**
+        * Run test case.
+        */
+        void RunTestCaseL( const RMessage2& aMessage );
+
+        /**
+        * Suspend the test case execution.
+        */
+        TInt Pause();
+
+        /**
+        * Resume the suspended test case execution.
+        */
+        TInt Resume();
+
+        /**
+        * Notify progress from Test Module.
+        */
+        void NotifyProgressL( const RMessage2& aMessage );
+
+        /**
+        * Notify remote commands from Test Module.
+        */
+        void NotifyRemoteTypeL( const RMessage2& aMessage );
+
+        /**
+        * Notify remote commands from Test Module.
+        */
+        void NotifyRemoteMsgL( const RMessage2& aMessage );
+        
+        /**
+        * Cancel outstanding asynchronous request.
+        */
+        void CancelAsyncRequest( const RMessage2& aMessage );
+
+        /**
+        * Return the name of Test Module.
+        */
+        const TDesC& ModuleName();
+
+        /**
+        * For event control.
+        */
+        void CtlEvent( const TEventIf& aEvent, TRequestStatus& aStatus );
+
+		/**
+		* Check if CtlEvent should be called
+		*/
+        TBool CheckCtlEvent( const TEventIf& aEvent );
+
+        /**
+        * Executes command received from test case.
+        */
+        void ExecuteCommandL(TCommand aCommand, TDesC8& aParamsPckg);
+        
+        /**
+        * Return module controller and real module controller.
+        */
+        CTestModuleController* GetModuleControllers(CTestModuleController** aRealModuleController);
+        
+        /**
+        * Set new module controller for test case (only in case when original controller crashed).
+        */
+        void ResetModuleController(CTestModuleController* aModuleController);
+
+        /**
+        * Set new real module controller for test case (only in case when original controller crashed).
+        */
+        void ResetRealModuleController(CTestModuleController* aRealModuleController);
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+        /** 
+        * C++ default constructor.
+        */
+        CTestCase( CTestEngine* aEngine,
+            CTestModuleController* aModuleController,
+            TTestInfo& aTestInfo,
+            CTestModuleController* aRealModuleController);
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CTestReport* aTestReport, TTestInfo& aTestInfo );
+
+        /**
+        * Return the pointer to CStifLogger owned by CTestEngineServer
+        */
+        CStifLogger* Logger();
+
+    public:     // Data
+    
+    protected:  // Data
+
+        // Session owning us
+        CTestEngine*            iTestEngine;
+
+    private:    // Data
+
+        // Test Module
+        CTestModuleController*  iTestModule;
+
+        // Test case controller
+        CTestCaseController*    iTestCaseController;
+
+        // Notifier for print
+        CTestProgressNotifier*  iTestCasePrint;
+
+        // Notifier for event
+        CTestEventNotifier*     iTestCaseEvent;
+
+        // Notifier for remote commands
+        CTestRemoteCmdNotifier* iTestCaseRemoteCmd;
+
+        // Handle to RTestServer
+        RTestServer             iTestServer;
+
+        // Handle to RTestExecution
+        RTestExecution          iTestExecution;
+
+        // Notifier for commands
+        CTestCommandNotifier*   iTestCaseCommand;
+        
+        // Real Test Module (when test module controller is testscripter)
+        CTestModuleController*  iRealModuleController;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif // TEST_ENGINE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/TestEngineCommon.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains common data for Test Engine.
+*
+*/
+
+#ifndef TEST_ENGINE_COMMON_H
+#define TEST_ENGINE_COMMON_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+// None
+
+// DESCRIPTION
+
+// Server name
+_LIT(KTestEngineName,"TestFrameworkEngine");
+
+// The server version.
+// A version must be specified when creating a session with the server.
+const TUint KTestEngineMajorVersionNumber = 0;
+const TUint KTestEngineMinorVersionNumber = 2;
+const TUint KTestEngineBuildVersionNumber = 1;
+
+// Function for starting the TestEngineServer
+IMPORT_C TInt StartEngine();
+
+#endif // TEST_ENGINE_COMMON_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/TestEngineEvent.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,145 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the event 
+* interface.
+*
+*/
+
+#ifndef TESTENGINEEVENT_H
+#define TESTENGINEEVENT_H
+
+//  INCLUDES
+#include <StifTestEventInterface.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+// None
+
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Interface class for the test system.
+class TEventMsg
+    :public TEventIf
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+        // None
+
+    public:     // Constructors and destructor
+        /**
+        * C++ default constructor.
+        */
+        TEventMsg();
+
+        /**
+        * C++ destructor.
+        */
+        ~TEventMsg();
+
+    public:     // New functions
+        
+        /**
+        * Set event.
+        */
+        void Set( TEventType aEventType );
+
+        /**
+        * Wait event.
+        */
+        void Wait( const RMessage2& aMessage );
+            
+        /**
+        * Cancel pending Wait.
+        */
+        void CancelWait();
+             
+        /**
+        * Release event. Unset released.
+        */
+        void Release();
+        
+        /**
+        * Unset event. Blocks until Release is called.
+        */
+        void Unset( TRequestStatus& aStatus );
+        
+    public:     // Functions from base classes
+        // None
+        
+    protected:  // New functions
+        // None
+        
+    protected:  // Functions from base classes
+        // None
+        
+    private:
+        // None
+        
+    public:     //Data
+        // None
+        
+    protected:  // Data
+        // None
+        
+    private:    // Data
+        /**
+        * Wait RMessage
+        */
+        RMessage2 iWaitMsg;
+        
+        /**
+        * Wait pending
+        */
+        TBool iWaitPending;
+        
+        /**
+        * StateEventPending.
+        */ 
+        TBool iStateEventPending;
+        
+        /**
+        * Unset status.
+        */ 
+        TRequestStatus* iStatus;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+    };
+
+#endif      // TESTENGINEEVENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/TestModuleController.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,686 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CTestModuleController.
+*
+*/
+
+#ifndef TEST_MODULE_CONTROLLER_H
+#define TEST_MODULE_CONTROLLER_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <atslogger.h>
+#include <StifTestInterface.h>
+#include <stifinternal/TestServerClient.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CTestEngine;
+class CBufferArray;
+class CTestScripterController;
+class CTestModuleController;
+
+// CLASS DECLARATION
+// None
+
+// CErrorPrinter is an active object which handles the execute test case
+// asynchronous request.
+class CErrorPrinter : public CActive
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CErrorPrinter* NewL( CTestEngine* aTestEngine );
+
+        /**
+        * Destructor of CErrorPrinter.
+        */
+        virtual ~CErrorPrinter();
+
+        /**
+        * Start
+        */
+        TInt StartL( RTestModule& aEngine );
+
+    public:     // New functions
+        // None
+
+    protected:  // New functions
+        // None
+
+    private:
+        /** 
+        * C++ default constructor.
+        */
+        CErrorPrinter();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CTestEngine* aEngine );
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:    // Functions from base classes
+       // None
+
+    public:     // Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestEngine*           iEngine;     // Pointer to main console
+
+         TErrorNotification     iError;      // Error notification
+         TErrorNotificationPckg iErrorPckg;  // Error package
+         RTestModule            iServer;     // Handle to TestModule
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CServerStateHandler class is an active object that handles server state
+// e.g. KErrServerTerminated
+NONSHARABLE_CLASS( CServerStateHandler )
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CServerStateHandler* NewL( CTestEngine* aTestEngine, CTestModuleController* aTestModuleController );
+
+        /**
+        * Destructor of CServerStateHandler.
+        */
+        virtual ~CServerStateHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        TInt StartL( RTestServer& aServer );
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CServerStateHandler( CTestEngine* aTestEngine, CTestModuleController* aTestModuleController );
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CTestEngine*           iEngine;          // Pointer to TestEngine
+        RThread                iServerThread;   // Handle to TestServer thread
+        CTestModuleController*  iTestModuleController;  //Pointer to TestModuleController
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// CTestModuleController is an active object used for controlling the test
+// module using the RTestModule API.
+
+class CTestModuleController
+        : public CActive 
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+
+    protected:    // Enumerations
+
+        // TTestModuleStatus defines the status of test module
+        enum TTestModuleStatus
+            {
+            ETestModuleIdle,
+            ETestModuleEnumerateCases,
+            ETestModuleEnumerateCasesCompleted,
+            };
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestModuleController* NewL( CTestEngine* aEngine,
+                                            const TName& aName,
+                                            TBool aAfterReboot,
+                                            TBool aCreateTestScripterCont = EFalse,
+                                            CTestScripterController* aTestScripterController = NULL );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CTestModuleController();
+
+    public:     // New functions
+
+        /**
+        * StartEnumerateL starts the CTestModuleController active object.
+        */
+        virtual void StartEnumerateL();
+
+        /**
+        * Init the test module
+        */
+        virtual void InitL( TFileName& aIniFile, const TDesC& aConfigFile );
+
+        /**
+        * Add config file
+        */
+        virtual void AddConfigFileL( TFileName& aConfigFile );
+
+        /**
+        * Remove config file
+        */
+        virtual void RemoveConfigFileL( TFileName& aConfigFile );
+
+        /**
+        * Get Test Cases
+        */
+        virtual CFixedFlatArray<TTestInfo>* TestCasesL();
+
+        /**
+        * Free used memory for test cases
+        */
+        virtual void FreeTestCases();
+
+        /**
+        * Return handle to Test Server
+        */
+        virtual RTestServer& Server( TTestInfo& aTestInfo );
+
+        /**
+        * Return the name of Test Module.
+        */
+        virtual const TDesC& ModuleName( const TDesC& aModuleName );
+
+        /**
+        * Return reference to AtsLogger
+        */
+        virtual CAtsLogger& AtsLogger(){ return *iAtsLogger; };
+        
+        /**
+        * Is enumeration complete?
+        */
+        virtual TBool EnumerationComplete();
+        
+        /**
+        * Returns pointer to the created clone of the TestModuleController
+        */		
+		virtual CTestModuleController* CloneL( CTestModuleController* aTestModuleController, TBool aAfterReset, CTestScripterController* aTestScripterController );  		
+		
+		/**
+        * Increases the value of iTestCaseCounter
+        */
+		virtual void CaseCreated();
+
+		/**
+        * Decreases the value of iTestCaseCounter and checks
+        * can old testmodulecontroller deleted or not.
+        */		
+		virtual void CaseFinished();
+		
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        virtual void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the cancellation
+        */
+        virtual void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        virtual TInt RunError( TInt aError );
+
+        /**
+        * Finds free test module controller, if not possible, creates new one.
+        */
+        virtual CTestModuleController* GetFreeOrCreateModuleControllerL(TTestInfo& aTestInfo, TBool aUITestingSupport);
+        
+        /**
+        * Deletes given module controller (used only in CTestScripterController).
+        */
+        virtual void DeleteModuleController(CTestModuleController* aRealModuleController);
+
+        /**
+        * Removes given module controller from child list (used only in CTestScripterController).
+        */
+        virtual void RemoveModuleController(CTestModuleController* aRealModuleController);
+
+        /**
+        * Enumerates test module controller synchronously.
+        * This is used when new test module controller is created when stif
+        * is about to run test case.                
+        */        
+        virtual void EnumerateSynchronously(void);
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TName& aName,
+                            TBool aAfterReboot,
+                            CTestScripterController* aTestScripterController );
+
+        /**
+        * Generate error report to xml result file and leave with notify.
+        */
+        void LeaveWithNotifyL( TInt aCode, const TDesC& aText );
+
+        /**
+        * Construct ATS logger. Added this function due to compiler error with
+        * CW 3.0 when there are multiple TRAPDs 
+        */        
+        TInt ConstructASTLoggerL( TDesC& atsName, TBool & aAfterReboot);
+
+    protected:
+        /**
+        * Parametric constructor.
+        */
+        CTestModuleController( CTestEngine* aEngine );
+
+    public:     // Data
+        // None
+
+        // Config file array
+        RPointerArray<HBufC>            iConfigFiles;
+        
+        // Tells is TestModuleController cloned or not in -15 (KErrServerTerminated) cases.
+        TBool iTestModuleCrashDetected;
+
+    private:    // Data
+    
+    protected:  // Data
+
+        // Test Engine owning us
+        CTestEngine*                    iEngine;
+
+        // Test case array
+        typedef CFixedFlatArray<TTestCaseInfo> TTestCaseArray;
+        RPointerArray<TTestCaseArray>   iTestCaseArray;
+
+        // Handle to Test Server
+        RTestServer                     iServer;
+
+        // Handle to Test Module
+        RTestModule                     iModule;
+
+        // Module name
+        HBufC*                          iName;
+
+        // Internal state
+        TTestModuleStatus               iState;
+
+        // Enumeration result
+        TCaseSize                       iEnumResultPackage;
+
+        // Count of test cases
+        TInt                            iTestCaseCount;
+
+        // Count of enumerated config files
+        TInt                            iEnumerateCount;
+
+        // Count of failed enumerated config files(This is used to decrease
+        // iEnumerateCount)
+        TInt                            iFailedEnumerateCount;
+        // For removing faulty config (test case) file(s)
+        RPointerArray<HBufC>            iFailedEnumerateConfig;
+
+        // Is enumeration complete
+        TBool                           iEnumerateComplete;
+
+        // Temporary config file for each Enumerate call
+        TPtrC                           iEnumConfigFile;
+
+        // Pointer to CErrorPrinter
+        CErrorPrinter*                  iErrorPrinter;
+        // Server state handler
+        CServerStateHandler*    iServerStateHandler;
+
+        // ATS Logger
+        CAtsLogger*                     iAtsLogger;
+
+        // Pointer to CTestScripterController
+        CTestScripterController*        iTestScripterController;
+        // Indication is CTestScripterController's services needed. Services
+        // that is implemented in CTestScripterController class.
+        TInt                            iTestScripterIndicator;
+
+        // Initialization file of Test Module
+        TFileName                       iInifile;
+        
+        // Number of running test cases
+        TInt iTestCaseCounter;
+        
+        // Reboot indication (moved here from ScripterControlle)
+        TBool                           iAfterReboot;
+        
+        // List of additional module controllers "owned" by current controller
+        // Used only with UITestingSupport and in case when every test case
+        // has to be run in separate process
+        RPointerArray<CTestModuleController> iChildrenControllers;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+        friend class CTestScripterController;
+        //friend class CTestModuleController;
+        friend class CTestEngine; //iTestScripterController used from CTestEngine::TestModuleCrash 
+
+    };
+
+// DESCRIPTION
+// CTestScripterController is for handling TestScripter's server session
+// creations and handling operations that concern to TestScripter.
+
+class CTestScripterController
+        : public CTestModuleController
+    {
+    public:     // Enumerations
+        // None
+
+    private:    // Enumerations
+        // None
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestScripterController* NewL( CTestEngine* aEngine,
+                                            const TName& aName,
+                                            TBool aAfterReboot );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CTestScripterController();
+
+    public:     // New functions
+
+        /**
+        * StartEnumerateL starts the CTestModuleController active object.
+        */
+        void StartEnumerateL();
+
+        /**
+        * Init the test module
+        */
+        void InitL( TFileName& aIniFile, const TDesC& aConfigFile );
+
+        /**
+        * Add config file
+        */
+        void AddConfigFileL( TFileName& aConfigFile );
+
+        /**
+        * Remove config file
+        */
+        void RemoveConfigFileL( TFileName& aConfigFile );
+
+        /**
+        * Get Test Cases
+        */
+        CFixedFlatArray<TTestInfo>* TestCasesL();
+
+        /**
+        * Free used memory for test cases
+        */
+        void FreeTestCases();
+
+        /**
+        * Return handle to Test Server
+        */
+        RTestServer& Server( TTestInfo& aTestInfo );
+
+        /**
+        * Return the name of Test Module.
+        */
+        const TDesC& ModuleName( const TDesC& aModuleName );
+
+        /**
+        * Return reference to AtsLogger
+        */
+        CAtsLogger& AtsLogger(){ return *iTestScripter[0]->iAtsLogger; };
+
+        /**
+        * Is enumeration complete?
+        */
+        TBool EnumerationComplete();
+
+        /**
+        * Handles completed requests (Emulates RunL() ).
+        */
+        void RunLEmulator( CTestModuleController* aTestModuleController );
+
+        /**
+        * Handle errors(Emulates RunError()).
+        */
+        TInt RunErrorEmulator( TInt aError,
+                                CTestModuleController* aTestModuleController );
+
+        /**
+        * Cancel active request(Emulates DoCancel()).
+        */
+        void DoCancelEmulator( CTestModuleController* aTestModuleController );
+
+        /**
+        * Get current CTestScripterController.
+        */
+        TInt GetCurrentIndex( CTestModuleController* aTestModuleController );
+
+        /**
+        * Finds free test module controller, if not possible, creates new one.
+        */
+        CTestModuleController* GetFreeOrCreateModuleControllerL(TTestInfo& aTestInfo, TBool aUITestingSupport);
+
+        /**
+        * Deletes given module controller.
+        */
+        void DeleteModuleController(CTestModuleController *aRealModuleController);
+
+        /**
+        * Removes given module controller from children list.
+        */
+        void RemoveModuleController(CTestModuleController *aRealModuleController);
+
+    public:     // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the cancellation
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TName& aName, TBool aAfterReboot );
+
+        /**
+        * Parametric constructor.
+        */
+        CTestScripterController( CTestEngine* aEngine );
+
+        /**
+        * Create name according to TestScripter and Test case file.
+        */
+        HBufC* CreateTestScripterNameL( TFileName& aTestCaseFile, HBufC* aCreatedName );
+
+    public:     // Data
+
+        // Array for created CTestScripterController
+        RPointerArray<CTestModuleController> iTestScripter;
+
+    protected:  // Data
+
+    private:    // Data
+        // None
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+/**
+* Check is module TestScripter. Does parsing and returns new module name and
+* error codes(Needed operations when creating server sessions to TestScripter).
+*/
+TInt GenerateModuleName(const TDesC& aModuleName, TDes& aNewModuleName);
+
+#endif // TEST_MODULE_CONTROLLER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/inc/TestReport.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,280 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CTestReport.
+*
+*/
+
+#ifndef TEST_REPORT_H
+#define TEST_REPORT_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include "TestEngineClient.h"
+#include "TestEngine.h"
+
+// CONSTANTS
+// Maximum length for date or time definitions 'Thursday 06th November 2003'
+const TInt KMaxDateAndTimeStamp = 30;
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CStifLogger;
+
+// CLASS DECLARATION
+// None
+
+// DESCRIPTION
+// CTestReport is a class that can generate different test reports.
+class CTestReport
+        : public CBase
+    {
+    public:     // Enumerations
+
+        // TTestReportMode defines the mode of test report
+        enum TTestReportMode
+            {
+            ETestReportBlank = 0x00000000,
+            ETestReportSummary = 0x00000001,
+            ETestReportEnvironment = 0x00000002,
+            ETestReportCases = 0x00000004,
+            ETestReportFull = ETestReportSummary | ETestReportEnvironment | ETestReportCases
+            };
+
+        // TTestReportOutput defines the type of test report output
+        enum TTestReportOutput
+            {
+            ETestReportNone = 0x00000000,
+            ETestReportDebug = 0x00000001,
+            ETestReportPlainText = 0x00000002,
+            ETestReportHtml = 0x00000004,
+            ETestReportAll = ETestReportDebug | ETestReportPlainText | ETestReportHtml
+            };
+
+    public:     // Structured classes
+
+        /**
+        *  TTestReportHeader includes header information for test report.
+        *
+        */
+        struct THwInfo
+            {
+            TInt iManufacturer;
+            TInt iMachineUid;
+            TInt iModel;
+            TInt iHwRev;
+            TInt iCpu;
+            TInt iCpuSpeed;
+            TInt iLanguage;
+            };
+
+        struct TSwInfo
+            {
+            TInt iSwRev;
+            TInt iSwBuild;
+            };
+
+        struct TMemoryInfo
+            {
+            TInt iRAM;
+            TInt iRAMFree;
+            };
+
+        class TTestHWInfo
+            {
+            public: // New functions
+                TTestHWInfo();
+
+            public: // Data
+                // HW Info
+                THwInfo         iHwInfo;
+                // SW Info
+                TSwInfo         iSwInfo;
+                // Memory Info
+                TMemoryInfo     iMemoryInfo;
+            };
+
+        /**
+        *  TTestCaseSummary includes information for summary of test cases.
+        */
+        class TTestCaseSummary
+            {
+            public:     // New functions
+                TTestCaseSummary();
+
+            public:     // Data
+                // Test Info
+                TTestInfo           iTestInfo;
+                // Test Result
+                TFullTestResult     iFullTestResult;
+            };
+
+        /**
+        *  TTestSummary includes information for test report summary.
+        */
+        class TTestSummary
+            {
+            public:     // New functions
+                TTestSummary( const TName& aName );
+
+            public:     // Data
+                // Name (e.g. test module name )
+                const TName     iName;
+                // Count of passed test cases
+                TInt            iPassedCases;
+                // Count of failed test cases
+                TInt            iFailedCases;
+                // Count of crashed cases
+                TInt            iCrashedCases;
+                // Count of timed out cases
+                TInt            iTimeoutCases;
+            };
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        static CTestReport* NewL( CTestReportSettings& aTestReportSettings,
+                                  const TTestReportMode aReportMode );
+        
+        /**
+        * Destructor.
+        */
+        ~CTestReport();
+        
+    public:     // New functions
+        
+        /**
+        * Add test case result.
+        */
+        void AddTestCaseResultL( const TTestInfo& aTestInfo,
+                                 const TFullTestResult& aTestResult,
+                                 const TInt aError );
+
+        /**
+        * Generate result reports.
+        */
+        void GenerateReportL();
+        
+        /**
+        * Update result reports.
+        */
+        void UpdateReportSummaryL();
+        
+        /**
+         * Adds version of test module to RPointerArray
+         */
+        void AddTestModuleVersion(TTestModuleVersionInfo& aVersion);
+
+    public:     // Functions from base classes
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL(  CTestReportSettings& aTestReportSettings );
+
+        /**
+        * Default C++ constructor.
+        */
+        CTestReport( const TTestReportMode aReportMode );
+        
+        /**
+        * Write result file header.
+        */
+        void WriteHeaderL();
+        
+        /**
+        * Write result file trailer.
+        */
+        void WriteTrailerL();
+        
+        /**
+        * Write data to file.
+        */
+        void WriteLineL( TRefByValue<const TDesC> aStr,... );
+        
+        /**
+        * Write delimiter line.
+        */
+        void WriteDelimiterL( const TDesC& aDelimiter, TInt aCount );
+        
+        /**
+        * Adds needed tags to get valid xml file.
+        */
+        void CloseXMLTagsInUnfinishedFileL(void);
+
+    public:     // Data
+    
+    protected:  // Data
+
+    private:    // Data
+
+        // Report file handles
+        RFs                             iFs;
+        RFile                           iFile;
+        CStifLogger::TLoggerType        iFormat;
+        CStifLogger::TOutput            iOutput;
+    
+        // Report Mode
+        TTestReportMode                 iReportMode;
+
+        // Report HW info
+        TTestHWInfo                     iReportHWInfo;
+
+        // Total summary
+        TTestSummary*                   iTotalSummary;
+
+        // Test summary array
+        RPointerArray<TTestSummary>     iTestSummaries;
+        
+        // Summary start position
+        TInt                            iSummaryPos;
+        
+        // Versions of test modules position
+        TInt							iModulesVersionsPos;
+        
+        // Test modules versions
+        RPointerArray<TTestModuleVersionInfo> iTestModulesVersionsInfo;
+
+        // Will report be written in xml format 
+        TBool                           iXML;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif // TEST_REPORT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/STIFTestFrameworkSettings.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,672 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CSTIFTestFrameworkSettings class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include "STIFTestFrameworkSettings.h"
+#include "TestReport.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: CSTIFTestFrameworkSettings
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFTestFrameworkSettings::CSTIFTestFrameworkSettings()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CSTIFTestFrameworkSettings::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: None
+
+    Return Values: CSTIFTestFrameworkSettings*: pointer to 
+                                                CSTIFTestFrameworkSettings
+                                                object
+
+    Errors/Exceptions: None 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CSTIFTestFrameworkSettings* CSTIFTestFrameworkSettings::NewL()
+    {
+    CSTIFTestFrameworkSettings* self = 
+                        new ( ELeave ) CSTIFTestFrameworkSettings();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: ~CSTIFTestFrameworkSettings
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CSTIFTestFrameworkSettings::~CSTIFTestFrameworkSettings()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: GetReportModeL
+
+    Description: Get report mode settings
+
+    Parameters: CStifSectionParser* aSectionParser: in: CStifSectionParser
+                object.
+                TPtrC aTag: in: Tag to setting to be found.
+                TUint& aSetting: inout: Parsed setting.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: Leaves is memory allocation fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestFrameworkSettings::GetReportModeL( 
+                                        CStifSectionParser* aSectionParser,
+                                        TPtrC aTag,
+                                        TUint& aSetting )
+    {
+    TPtrC string;
+
+    CStifItemParser* item = NULL;
+    TRAPD( ret, item = aSectionParser->GetItemLineL( aTag, ENoTag ) );
+    if( ret != KErrNone )
+        {
+        delete item;
+        return ret;
+        }
+    if( !item )
+        {
+        delete item;
+        return KErrNotFound;
+        }
+    else
+        {
+        ret = item->GetString( _L( "" ), string );
+        while( ret == KErrNone )
+            {
+            HBufC* stringHbuf = string.AllocL();
+            TPtr modifiableString = stringHbuf->Des();
+            modifiableString.UpperCase();
+
+            if( modifiableString == _L( "EMPTY" ) )
+                {
+                // No test report
+                aSetting = CTestReport::ETestReportBlank;
+                }
+            else if( modifiableString == _L( "SUMMARY" ) )
+                {
+                // Increment aSetting
+                aSetting += CTestReport::ETestReportSummary;
+                }
+            else if( modifiableString == _L( "ENVIRONMENT" ) )
+                {
+                // Increment aSetting
+                aSetting += CTestReport::ETestReportEnvironment;
+                }
+            else if( modifiableString == _L( "TESTCASES" ) )
+                {
+                // Increment aSetting
+                aSetting += CTestReport::ETestReportCases;
+                }
+            else if( modifiableString == _L( "FULLREPORT" ) )
+                {
+                // Set aSettings to max value and break
+                aSetting = CTestReport::ETestReportFull;
+                delete stringHbuf;
+                break;
+                }
+            else if( modifiableString == _L( "#" ) )
+                {
+                delete stringHbuf;
+                break;
+                }
+            else
+                {
+                delete stringHbuf;
+                delete item;
+                return KErrArgument;
+                }
+            delete stringHbuf;
+            ret = item->GetNextString( string );
+            }
+        }
+
+    delete item;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: GetFileSetting
+
+    Description: Get file settings
+
+    Parameters: CStifSectionParser* aSectionParser: in: CStifSectionParser
+                object.
+                TPtrC aTag: in: Tag to setting to be found.
+                TPtrC& aFilePath: inout: Test file setting.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestFrameworkSettings::GetFileSetting( 
+                                        CStifSectionParser* aSectionParser,
+                                        TPtrC aTag,
+                                        TPtrC& aSetting )
+    {
+    CStifItemParser* item = NULL;
+    TRAPD( ret, item = aSectionParser->GetItemLineL( 
+                                            aTag,
+                                            ENoTag ) );
+    if( ret != KErrNone )
+        {
+        delete item;
+        return ret;
+        }
+    if( !item )
+        {
+        delete item;
+        return KErrNotFound;
+        }
+    else
+        {
+        ret = item->GetString( _L( "" ), aSetting );
+        }
+
+    delete item;
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: GetFormatL
+
+    Description: Get Test report format settings
+
+    Parameters: CStifSectionParser* aSectionParser: in: CStifSectionParser
+                object.
+                TPtrC aTag: in: Tag to setting to be found.
+                CStifLogger::TLoggerType& aLoggerType: inout: Test report type
+                setting.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: Leaves is memory allocation fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestFrameworkSettings::GetFormatL( 
+                                        CStifSectionParser* aSectionParser,
+                                        TPtrC aTag, 
+                                        CStifLogger::TLoggerType& aLoggerType )
+    {
+    TBool xml;
+    return GetFormatL(aSectionParser, aTag, aLoggerType, xml);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: GetFormatL
+
+    Description: Get Test report format settings
+
+    Parameters: CStifSectionParser* aSectionParser: in: CStifSectionParser
+                object.
+                TPtrC aTag: in: Tag to setting to be found.
+                CStifLogger::TLoggerType& aLoggerType: inout: Test report type setting.
+                TBool& aXML: inout: true if xml format is set
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: Leaves is memory allocation fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestFrameworkSettings::GetFormatL( 
+                                        CStifSectionParser* aSectionParser,
+                                        TPtrC aTag, 
+                                        CStifLogger::TLoggerType& aLoggerType,
+                                        TBool& aXML )
+    {
+    aXML = EFalse;
+    CStifItemParser* item = NULL;
+    TRAPD( ret, item = aSectionParser->GetItemLineL( aTag, ENoTag ) );
+
+    TPtrC string;
+
+    if( ret != KErrNone )
+        {
+        delete item;
+        return ret;
+        }
+    if( !item )
+        {
+        delete item;
+        return KErrNotFound;
+        }
+    else
+        {
+        ret = item->GetString( _L( "" ), string );
+        if ( ret != KErrNone )
+            {
+            delete item;
+            return ret;
+            }
+        }
+
+    HBufC* stringHbuf = string.AllocL();
+    TPtr modifiableString = stringHbuf->Des();
+    modifiableString.UpperCase();
+
+    if( modifiableString == _L( "TXT" ) )
+        {
+        aLoggerType = CStifLogger::ETxt;
+        }
+    else if( modifiableString == _L( "HTML" ) )
+        {
+        aLoggerType = CStifLogger::EHtml;
+        }
+    else if( modifiableString == _L( "DATA" ) )
+        {
+        aLoggerType = CStifLogger::EData;
+        }
+    else if( modifiableString == _L( "XML" ) )
+        {
+        aLoggerType = CStifLogger::ETxt;
+        aXML = ETrue;
+        }
+    else
+        {
+        delete stringHbuf;
+        delete item;
+        return KErrArgument;
+        }
+
+    delete stringHbuf;
+    delete item;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: GetOutputL
+
+    Description: Get Test report output settings
+
+    Parameters: CStifSectionParser* aSectionParser: in: CStifSectionParser
+                object.
+                TPtrC aTag: in: Tag to setting to be found.
+                CStifLogger::TOutput& aOutput: inout: Test report output setting.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: Leaves is memory allocation fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestFrameworkSettings::GetOutputL( 
+                                        CStifSectionParser* aSectionParser,
+                                        TPtrC aTag,
+                                        CStifLogger::TOutput& aOutput )
+    {
+    CStifItemParser* item = NULL;
+    TRAPD( ret, item = aSectionParser->GetItemLineL( aTag, ENoTag ) );
+
+    TPtrC string;
+
+    if( ret != KErrNone )
+        {
+        delete item;
+        return ret;
+        }
+    if( !item )
+        {
+        delete item;
+        return KErrNotFound;
+        }
+    else
+        {
+        ret = item->GetString( _L( "" ), string );
+        if ( ret != KErrNone )
+            {
+            delete item;
+            return ret;
+            }
+        }
+
+    HBufC* stringHbuf = string.AllocL();
+    TPtr modifiableString = stringHbuf->Des();
+    modifiableString.UpperCase();
+
+    if( modifiableString == _L( "FILE" ) )
+        {
+        aOutput = CStifLogger::EFile;
+        }
+    else if( modifiableString == _L( "RDEBUG" ) )
+        {
+        aOutput = CStifLogger::ERDebug;
+        }
+    else
+        {
+        delete stringHbuf;
+        delete item;
+        return KErrArgument;
+        }
+
+    delete stringHbuf;
+    delete item;
+
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: GetBooleanSettingsL
+
+    Description: Get boolean type of settings
+
+    Parameters: CStifSectionParser* aSectionParser: in: CStifSectionParser
+                object.
+                TPtrC aTag: in: Tag to setting to be found.
+                TBool& aSetting: inout: Parsed setting.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: Leaves is memory allocation fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestFrameworkSettings::GetBooleanSettingsL( 
+                                        CStifSectionParser* aSectionParser,
+                                        TPtrC aTag,
+                                        TBool& aSetting )
+    {
+    TPtrC string;
+
+    CStifItemParser* item = NULL;
+    TRAPD( ret, item = aSectionParser->GetItemLineL( aTag, ENoTag ) );
+    if( ret != KErrNone )
+        {
+        delete item;
+        return ret;
+        }
+    if( !item )
+        {
+        delete item;
+        return KErrNotFound;
+        }
+    else
+        {
+        ret = item->GetString( _L( "" ), string );
+        if( ret != KErrNone )
+            {
+            delete item;
+            return ret;
+            }
+
+        HBufC* stringHbuf = string.AllocL();
+        TPtr modifiableString = stringHbuf->Des();
+        modifiableString.UpperCase();
+
+        // Parsed parameter is false
+        if( modifiableString == _L( "NO" ) )
+            {
+            aSetting = EFalse;
+            }
+        // Parsed parameter is true
+        else if( modifiableString == _L( "YES" ) )
+            {
+            aSetting = ETrue;
+            }
+        else
+            {
+            delete stringHbuf;
+            delete item;
+            return KErrArgument;
+            }
+        delete stringHbuf;
+        }
+
+    delete item;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestFrameworkSettings
+
+    Method: GetOverwriteL
+
+    Description: Get Test report file creation mode settings
+                 (overwrite settings)
+
+    Parameters: CStifSectionParser* aSectionParser: in: CStifSectionParser
+                object.
+                TPtrC aTag: in: Tag to setting to be found.
+                TBool& aOverwrite: inout: Overwrite setting.
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: Leaves is memory allocation fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestFrameworkSettings::GetOverwriteL( 
+                                        CStifSectionParser* aSectionParser,
+                                        TPtrC aTag,
+                                        TBool& aOverwrite )
+    {
+    CStifItemParser* item = NULL;
+    TRAPD( ret, item = aSectionParser->GetItemLineL( aTag, ENoTag ) );
+    if( ret != KErrNone )
+        {
+        delete item;
+        return ret;
+        }
+    if( !item )
+        {
+        delete item;
+        return KErrNotFound;
+        }
+    else
+        {
+        TPtrC string;
+        ret = item->GetString( _L( "" ), string );
+        if( ret != KErrNone )
+            {
+            delete item;
+            return ret;
+            }
+
+        HBufC* stringHbuf = string.AllocL();
+        TPtr modifiableString = stringHbuf->Des();
+        modifiableString.UpperCase();
+
+        if( modifiableString == _L( "APPEND" ) )
+            {
+            aOverwrite = EFalse;
+            }
+        else if( modifiableString == _L( "OVERWRITE") )
+            {
+            aOverwrite = ETrue;
+            }
+        else
+            {
+            delete stringHbuf;
+            delete item;
+            return KErrArgument;
+            }
+        delete stringHbuf;
+        }
+
+    delete item;
+
+    return KErrNone;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/SettingServer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,571 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CSettingServer 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+
+#include "SettingServerClient.h"
+#include "SettingServer.h"
+
+#include <StifLogger.h>
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// Struct to pass parameters to server thread
+struct TThreadStartSetting
+    {
+    TFileName  iName;         // Server name
+    RThread    iServerThread; // The server thread
+    RSemaphore iStarted;      // Startup syncronisation semaphore   
+    TInt       iStartupResult;// Start-up result
+    };
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+#undef LOGGER
+#define LOGGER iSettingServerLogger
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: PanicServer
+
+    Description: Panics the server. 
+
+    Parameters: const TSettingServerPanic aPanic :in:  Panic code
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CSettingServer::PanicServer( const TSettingServerPanic aPanic )
+    {
+
+/*#ifdef USE_LOGGER
+    // Check if logger is available, if so, use it.
+    CStifLogger* log = (CStifLogger*) Dll::Tls();
+    if (log)
+        {
+        log->Log(_L("SettingServer.DLL Panic %d"), aPanic);
+        }
+#endif
+*/
+    RDebug::Print( _L( "CSettingServer::PanicServer" ) );
+    _LIT( KTxtServer,"CSettingServer" );
+    User::Panic( KTxtServer,aPanic );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: NewL
+
+    Description: Returns new CSettingServer object
+
+    Parameters: const TName& aName: in: Server name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation, ConstructL or StartL
+                       leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CSettingServer* CSettingServer::NewL( const TName& aName )
+
+    {
+    CSettingServer* self = new( ELeave ) CSettingServer();
+    CleanupStack::PushL( self );
+
+    // Construct the server
+    self->ConstructL();
+
+    // Start the server
+    self->StartL( aName );
+
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+ 
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CSettingServer::ConstructL()
+    {
+    // Create logger, in Wins use HTML in HW default logger
+    TLoggerSettings loggerSettings;
+    // Directory must create by hand if test engine log wanted
+    loggerSettings.iCreateLogDirectories = EFalse;
+    loggerSettings.iOverwrite = ETrue;
+    loggerSettings.iTimeStamp = ETrue;
+    loggerSettings.iLineBreak = ETrue;
+    loggerSettings.iEventRanking = EFalse;
+    loggerSettings.iThreadId = EFalse;
+    loggerSettings.iHardwareFormat = CStifLogger::ETxt;
+#ifndef FORCE_STIF_INTERNAL_LOGGING_TO_RDEBUG
+    loggerSettings.iEmulatorFormat = CStifLogger::EHtml;
+    loggerSettings.iHardwareOutput = CStifLogger::EFile;
+    loggerSettings.iEmulatorOutput = CStifLogger::EFile;
+#else
+    RDebug::Print( _L( "STIF SettingServer logging forced to RDebug" ) );
+    loggerSettings.iEmulatorFormat = CStifLogger::ETxt;
+    loggerSettings.iHardwareOutput = CStifLogger::ERDebug;
+    loggerSettings.iEmulatorOutput = CStifLogger::ERDebug;
+#endif
+    loggerSettings.iUnicode = EFalse;
+    loggerSettings.iAddTestCaseTitle = EFalse;
+    iSettingServerLogger = CStifLogger::NewL( 
+                        _L( "C:\\logs\\testframework\\testengine\\"),
+                        _L( "SettingServer" ),
+                        loggerSettings );
+
+    // iLoggerSettings initializations to indicate is setting in use
+    iLoggerSettings.iIsDefined.iCreateLogDir = EFalse;
+    iLoggerSettings.iEmulatorPath.Copy( _L( "" ) );
+    iLoggerSettings.iEmulatorFormat = CStifLogger::ETxt;
+    iLoggerSettings.iEmulatorOutput = CStifLogger::EFile;
+    iLoggerSettings.iHardwarePath.Copy( _L( "" ) );
+    iLoggerSettings.iHardwareFormat = CStifLogger::ETxt;
+    iLoggerSettings.iHardwareOutput = CStifLogger::EFile;
+    iLoggerSettings.iOverwrite = ETrue;
+    iLoggerSettings.iTimeStamp = ETrue;
+    iLoggerSettings.iLineBreak = ETrue;
+    iLoggerSettings.iEventRanking = EFalse;
+    iLoggerSettings.iThreadId = EFalse;
+    iLoggerSettings.iUnicode = EFalse;
+    iLoggerSettings.iAddTestCaseTitle = EFalse;
+
+    iLoggerSettings.iIsDefined.iPath = EFalse;
+    iLoggerSettings.iIsDefined.iHwPath = EFalse;
+    iLoggerSettings.iIsDefined.iFormat = EFalse;
+    iLoggerSettings.iIsDefined.iHwFormat = EFalse;
+    iLoggerSettings.iIsDefined.iOutput = EFalse;
+    iLoggerSettings.iIsDefined.iHwOutput = EFalse;
+    iLoggerSettings.iIsDefined.iOverwrite = EFalse;
+    iLoggerSettings.iIsDefined.iLineBreak = EFalse;
+    iLoggerSettings.iIsDefined.iTimeStamp = EFalse;
+    iLoggerSettings.iIsDefined.iEventRanking = EFalse;
+    iLoggerSettings.iIsDefined.iThreadId = EFalse;
+    iLoggerSettings.iIsDefined.iUnicode = EFalse;
+    iLoggerSettings.iIsDefined.iAddTestCaseTitle = EFalse;
+
+    __TRACE( KInit,( _L( "-.-.-.-.-.-.-.-.-.- SettingServer log starts -.-.-.-.-.-.-.-.-.-" ) ) );
+    __TRACE( KInit,( _L( "CSettingServer::ConstructL()" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: CSettingServer
+
+    Description: Constructor.
+
+    Initialises non-zero member variables and base class with correct
+    priority.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CSettingServer::CSettingServer() :
+        CServer2( CSettingServer::ESettingServerSchedulerPriority )
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: ~CSettingServer
+
+    Description: Destructor.
+   
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CSettingServer::~CSettingServer()
+    {
+    delete iSettingServerLogger;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: NewSessionL
+
+    Description: Returns new session.
+    
+    Parameters: const TVersion &aVersion:in :Version required
+
+    Return Values: CSharableSession* New session
+
+    Errors/Exceptions: Leaves if invalid version
+                       Leaves if CSettingServer construction leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CSession2* CSettingServer::NewSessionL( const TVersion& aVersion,
+                                        const RMessage2& /*aMessage*/ ) const
+
+    {
+    // check version is ok
+    TVersion v( KSettingServerMajorVersionNumber,
+                KSettingServerMinorVersionNumber,
+                KSettingServerVersionNumber
+               );
+
+    if( !User::QueryVersionSupported( v, aVersion ) )
+        {
+        User::Leave( KErrNotSupported );
+        }
+
+    return CLoggerSetting::NewL( ( CSettingServer* ) this );
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: OpenSession
+
+    Description: Opens session. Session calls calls this when session is
+    properly constructed.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CSettingServer::OpenSession()
+    {
+    iSessions++;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: Logger
+
+    Description: Return pointer to the Logger(iSettingServerLogger)
+
+    Parameters: None
+
+    Return Values: CStifLogger*: Pointer to Logger
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CStifLogger* CSettingServer::Logger()
+    {
+    return iSettingServerLogger;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: CloseSession
+
+    Description: Closes session. CLoggerSetting::CloseSession calls this
+    to inform server class. 
+
+    If there are not any active sessions, then stop active scheduler and
+    close whole server.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Function panics if OpenSessions() and CloseSessions()
+                       does not match.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CSettingServer::CloseSession()
+    {
+    __ASSERT_ALWAYS ( iSessions > 0, CSettingServer::PanicServer(ETooManyCloseSessions));
+    iSessions--;  
+
+    if ( iSessions == 0 )
+        {
+        // Stop the active scheduler if no-one is using server anymore
+        CActiveScheduler::Stop();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: ThreadFunction
+
+    Description: The thread function, where Setting Server lives in
+    
+    Parameters: TAny* aStartInfo aName: in: Start-up information
+    
+    Return Values: TInt: Result from server start
+
+    Errors/Exceptions: Panics current thread if:
+                       Invalid start-up information
+                       Clean-up stack can't be created
+                       Setting Server can't be started
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CSettingServer::ThreadFunction( TAny* aStarted )
+    {
+    __UHEAP_MARK;
+
+    // Get start-up information
+    TThreadStartSetting* startInfo = ( TThreadStartSetting* ) aStarted;
+    __ASSERT_ALWAYS( startInfo,PanicServer( ENoStartupInformation ) );
+
+    // Create clean-up stack
+    CTrapCleanup* tc = CTrapCleanup::New();
+    __ASSERT_ALWAYS( tc, PanicServer(ECreateTrapCleanup));
+
+    // Construct and install active scheduler
+    CActiveScheduler* scheduler = new CActiveScheduler;
+    __ASSERT_ALWAYS( scheduler, PanicServer( EMainSchedulerError ) );
+    CActiveScheduler::Install( scheduler );
+
+    // Construct server
+    CSettingServer* server = NULL;
+    RDebug::Print( startInfo->iName );
+    TRAPD( err, server = CSettingServer::NewL( startInfo->iName ) );
+    __ASSERT_ALWAYS( !err, PanicServer( ESvrCreateServer ) );
+
+    // Inform that we are up and running
+    startInfo->iStartupResult = KErrNone;
+    startInfo->iStarted.Signal();
+
+    // Start handling requests
+    CActiveScheduler::Start();
+
+   // Execution continues from here after CActiveScheduler::Stop
+
+    // Delete the server. This should be deleted before scheduler,
+    // if server still has any active objects
+    delete server;
+    server = NULL;
+    
+    // Delete scheduler. 
+    delete scheduler;
+    scheduler = NULL;
+
+    // Delete clean-up stack
+    delete tc;
+    tc = NULL;
+
+    __UHEAP_MARKEND;
+
+    return KErrNone;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: StartNewServer
+
+    Description: Starts a new server. Server will be running its own
+    thread and this functions returns when server is up and running or
+    server start-up fails.
+
+    Parameters:  TName& aServerName: inout: The name of the server
+    
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt StartNewServer( TName& aServerName )
+    {
+    __UHEAP_MARK;
+
+    _LIT(KServerName, "SettingServer");
+
+    //Ccheck server not already started
+    TFindServer findServer( KServerName );
+    TFullName name;
+    if( findServer.Next( name ) == KErrNone )
+        {   
+        // Server already started, nothing to do
+        aServerName = KServerName;
+        __UHEAP_MARKEND;
+        return KErrAlreadyExists;
+        }
+
+    // Construct start-up information object
+    TThreadStartSetting* startInfo = new TThreadStartSetting();
+    if( startInfo == NULL )
+        {
+        __UHEAP_MARKEND;
+        return KErrNoMemory;
+        }
+
+    // Fill the start-up information
+    startInfo->iName = KServerName;
+    startInfo->iStartupResult = KErrNone;
+    startInfo->iStarted.CreateLocal( 0 );
+
+    // Create thread    
+    TInt res = startInfo->iServerThread.Create( 
+        startInfo->iName ,                       // Name of thread
+        CSettingServer::ThreadFunction,          // Thread function
+        KDefaultStackSize,                       // Stack size
+        KDefaultHeapSize,                        // Heap initial size
+        KMaxHeapSize,                            // Heap start max size
+        startInfo                                // Parameter to thread function
+        );
+
+    // If thread creation failed
+    if( res != KErrNone )        
+        {
+        startInfo->iStarted.Close();             // Close semaphore
+        delete startInfo;
+        startInfo = NULL;
+        __UHEAP_MARKEND;
+        return res;
+        }
+
+    // Now start thread
+    startInfo->iServerThread.SetPriority( EPriorityMuchMore ); 
+    startInfo->iServerThread.Resume();
+    
+    // Wait until the thread is started
+    startInfo->iStarted.Wait();
+
+    // Server is started( or it has returned error )
+    
+
+    // Set server name
+    aServerName = KServerName;
+
+    // Free memory
+    TInt r = startInfo->iStartupResult;
+    startInfo->iServerThread.Close();
+    startInfo->iStarted.Close();
+    delete startInfo;
+    startInfo = NULL;
+
+    __UHEAP_MARKEND;
+
+    // Return start-up result.
+    return r;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/SettingServerClient.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,360 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contain implementation of RSettingServer 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include "SettingServerClient.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// Function for starting the Setting server
+IMPORT_C TInt StartNewServer( TName& aServerName );
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: RSettingServer
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C RSettingServer::RSettingServer()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: Connect
+
+    Description: Connect method creates new RSettingServer session.
+    First the server is tried to start. If start is successfull or server is
+    already started, then a new session is created.  
+
+    Parameters: None
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RSettingServer::Connect()
+    {
+    TName serverName;
+    TInt ret = StartNewServer( serverName );
+
+    if( ret == KErrNone || ret == KErrAlreadyExists )
+        {
+        ret = CreateSession( serverName, Version() );
+        }
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: Version
+
+    Description: Return client side version.
+
+    Parameters: None
+
+    Return Values: TVersion: Version number
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TVersion RSettingServer::Version() const
+    {
+    return( TVersion( KSettingServerMajorVersionNumber,
+                      KSettingServerMinorVersionNumber, 
+                      KSettingServerVersionNumber 
+                     ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: Close
+
+    Description: Closes the RSettingServer session.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RSettingServer::Close()
+    {
+    // Check that server is connected and send close message to it if possible.
+    if( Handle() != 0 )
+        {
+        TIpcArgs args( TIpcArgs::ENothing, TIpcArgs::ENothing, TIpcArgs::ENothing );
+        // Goes to CSettingServer's DispatchMessageL() method
+        SendReceive( ESettingServerCloseSession, args );
+        }
+
+    RSessionBase::Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: SetIniFileInformation
+
+    Description: Set initialization filename and path settings to Setting
+                 server.
+
+    Parameters: const TFileName& aIniFile: in: Filename and path information.
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RSettingServer::SetIniFileInformation( const TFileName& aIniFile )
+    {
+    TIpcArgs args( &aIniFile, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    // Goes to CSettingServer's DispatchMessageL() method
+    SendReceive( ESetIniFileInformation, args );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: ReadLoggerSettingsFromIniFile
+
+    Description: Read Logger setting from initialization file. Mainly use from
+                 TestEngine side.
+
+    Parameters: TLoggerSettings& aLoggerSettings: inout: Logger's overwrite
+                struct
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RSettingServer::ReadLoggerSettingsFromIniFile( 
+                                            TLoggerSettings& aLoggerSettings )
+    {
+    // Package
+    TPckg<TLoggerSettings> loggerSettingsPckg( aLoggerSettings );
+
+	TIpcArgs args( &loggerSettingsPckg, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    // Goes to CSettingServer's DispatchMessageL() method
+    SendReceive( EReadLoggerSettingsFromIniFile, args );
+   
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: GetLoggerSettings
+
+    Description: Get Logger settings. Mainly use from Logger side.
+
+    Parameters: TLoggerSettings& aLoggerSettings: in: Logger's overwrite struct
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RSettingServer::GetLoggerSettings( 
+                                            TLoggerSettings& aLoggerSettings )
+    {
+    // Package
+    TPckg<TLoggerSettings> loggerSettingsPckg( aLoggerSettings );
+
+	TIpcArgs args( &loggerSettingsPckg, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    // Goes to CSettingServer's DispatchMessageL() method
+    SendReceive( EGetLoggerSettings, args );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: SetIniFileSetting
+
+    Description: Set new initialization file setting(e.g. SetAttribute).
+
+    Parameters: TName& aNewIniFileSetting: in: New setting
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RSettingServer::SetNewIniFileSetting( TName& aNewIniFileSetting )
+    {
+	TIpcArgs args( &aNewIniFileSetting, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    // Goes to CSettingServer's DispatchMessageL() method
+    SendReceive( ESetNewIniFileSetting, args );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: GetEngineSettings
+
+    Description: Get Engine settings.
+
+    Parameters: TEngineSettings& aEngineSettings: in: Engine settings struct
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RSettingServer::GetEngineSettings(TEngineSettings& aEngineSettings)
+    {
+    // Package
+    TPckg<TEngineSettings> engineSettingsPckg(aEngineSettings);
+
+    TIpcArgs args(&engineSettingsPckg, TIpcArgs::ENothing, TIpcArgs::ENothing);
+    // Goes to CSettingServer's DispatchMessageL() method
+    SendReceive(EGetEngineSettings, args);
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RSettingServer
+
+    Method: StoreEngineSettings
+
+    Description: Store Engine settings.
+
+    Parameters: TEngineSettings& aEngineSettings: in: Engine settings struct
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RSettingServer::StoreEngineSettings(TEngineSettings& aEngineSettings)
+    {
+    // Package
+    TPckg<TEngineSettings> engineSettingsPckg(aEngineSettings);
+
+    TIpcArgs args(&engineSettingsPckg, TIpcArgs::ENothing, TIpcArgs::ENothing);
+    // Goes to CSettingServer's DispatchMessageL() method
+    SendReceive(EStoreEngineSettings, args);
+
+    return KErrNone;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/SettingServerSession.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,950 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CSettingServer 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+
+#include "SettingServerClient.h"
+#include "SettingServer.h"
+
+#include <StifParser.h>
+#include "STIFTestFrameworkSettings.h"
+
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+#undef LOGGER
+#define LOGGER iSettingServer->Logger()
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: NewL
+
+    Description: Create new CLoggerSetting (Setting server session)
+
+    Parameters: RThread& aClient: in: Handle to thread client
+                CSettingServer* aServer: in: Pointer to CSettingServer
+
+    Return Values: CLoggerSetting* Pointer to new CLoggerSetting
+
+    Errors/Exceptions: Leaves if memory allocation fails or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CLoggerSetting* CLoggerSetting::NewL( CSettingServer* aServer )
+    {
+    CLoggerSetting* self=new( ELeave ) CLoggerSetting();
+    CleanupStack::PushL( self );
+    self->ConstructL( aServer );
+    CleanupStack::Pop();
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: CLoggerSetting
+
+    Description: Constructor. Initialise base class.
+
+    Parameters: RThread& aClient: in: Handle to client
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CLoggerSetting::CLoggerSetting() :
+        CSession2()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: ~CLoggerSetting
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CLoggerSetting::~CLoggerSetting()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+    
+    Parameters: CSettingServer* aServer: in: Server
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if base class CreateL leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CLoggerSetting::ConstructL( CSettingServer* aServer )
+    {
+    // @spe __TRACE( KInit,( _L( "CLoggerSetting::ConstructL - constructing server session" ) ) );
+    iSettingServer = aServer;
+
+    // second-phase construct base class
+    //CSession2::CreateL();
+
+//    iSettingServer = aServer;
+
+     // Inform server class that session is opening. 
+    iSettingServer->OpenSession();    
+
+    __TRACE( KInit,( _L( "CLoggerSetting::ConstructL - constructing server session done" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: PanicClient
+
+    Description: Panic clients.
+
+    Parameters: TInt aPanic: in: Panic code
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CLoggerSetting::PanicClient( const TInt aPanic, const RMessage2& aMessage ) const
+    {
+    __TRACE( KError,( _L( "CLoggerSetting::PanicClient code = %d" ), aPanic ) );
+
+    _LIT( KTxtModule,"CLoggerSetting" );
+
+    aMessage.Panic( KTxtModule,aPanic );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: CloseSession
+
+    Description: Close session
+
+    Parameters: const RMessage&: out: Message to be completed.
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::CloseSession( /*const RMessage& aMessage*/ )
+    {
+    __TRACE( KVerbose,( _L( "CLoggerSetting::CloseSession in" ) ) );
+             
+    // Close session from server (and stop it if required)
+    iSettingServer->CloseSession();
+
+    // NOTE: This complete will make after DispatchMessageL in ServiceL method.
+    // Complete message. This must be done after possible closing
+    // of the server to make sure that server is first closed before
+    // client can send new messages.
+    // aMessage.Complete( KErrNone );
+
+    __TRACE( KVerbose,( _L( "CLoggerSetting::CloseSession out" ) ) );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: ServiceL
+
+    Description: Trap harness for dispatcher
+
+    Parameters: const RMessage& aMessage: inout: Message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CLoggerSetting::ServiceL( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose,( _L( "CLoggerSetting::ServiceL in" ) ) );
+
+    TInt r( KErrNone );
+    TBool isMessageSync( EFalse );
+    
+    TRAPD( ret, r = DispatchMessageL( aMessage, isMessageSync ) );
+
+    if( ret != KErrNone )
+        {
+        // Complete message on leaving cases with leave code allways.
+        __TRACE( KError,( _L( "CLoggerSetting::DispatchMessageL leaved" ) ) );
+        aMessage.Complete( ret );
+        }
+    else if( isMessageSync )
+        {
+        // Message is syncronous, Complete message with error code 
+        // originating from message handling
+         __TRACE( KVerbose,( _L( "CLoggerSetting::DispatchMessageL completed with: %d" ), r ) );
+        aMessage.Complete( r );
+        }
+    __TRACE( KVerbose,( _L( "CLoggerSetting::ServiceL out" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: DispatchMessageL
+
+    Description: Dispatch message, calls corresponding function to do it.
+
+    Parameters: const RMessage& aMessage: inout: Message to be handled
+                TBool& aIsMessageSync: inout: Indication of the message type
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: Leaves if operation handling function leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::DispatchMessageL( const RMessage2& aMessage,
+                                        TBool& aIsMessageSync )
+    {
+    __TRACE( KInit ,( _L( "CLoggerSetting::DispatchMessageL in" ) ) );
+    switch( aMessage.Function() )
+        {
+        case ESettingServerCloseSession: 
+            {
+            __TRACE( KInit ,( _L( "Closing Setting server session" ) ) );
+            aIsMessageSync = ETrue;
+            return CloseSession( /*aMessage*/ );
+            }
+        case ESetIniFileInformation:
+            {
+            __TRACE( KInit ,( _L( "Set initialization file setting" ) ) );
+            aIsMessageSync = ETrue;
+            return SetIniFileSettings( aMessage );
+            }
+        case EReadLoggerSettingsFromIniFile:
+            {
+            __TRACE( KInit ,( _L( "Read Logger setting(s) from initialization file" ) ) );
+            aIsMessageSync = ETrue;
+            return ReadLoggerSettingsFromIniFile( aMessage );
+            }
+        case EGetLoggerSettings:
+            {
+            __TRACE( KInit ,( _L( "Get Logger setting(s)" ) ) );
+            aIsMessageSync = ETrue;
+            return GetLoggerSettings( aMessage );
+            }
+        case ESetNewIniFileSetting:
+            {
+            __TRACE( KInit ,( _L( "Set new initialization file setting" ) ) );
+            aIsMessageSync = ETrue;
+            return SetNewIniFileSetting( aMessage );
+            }
+        case EGetEngineSettings:
+            {
+            __TRACE(KInit, (_L("Get Engine settings")));
+            aIsMessageSync = ETrue;
+            return GetEngineSettings(aMessage);
+            }
+        case EStoreEngineSettings:
+            {
+            __TRACE(KInit, (_L("Store Engine settings")));
+            aIsMessageSync = ETrue;
+            return StoreEngineSettings(aMessage);
+            }
+         // Invalid request
+        default:
+            {
+            PanicClient( EBadRequest, aMessage );
+            return KErrNotSupported;
+            }
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: SetIniFileSettings
+
+    Description: Set initialization filename and path settings to Setting
+                 server.
+
+    Parameters: const RMessage& aMessage: inout: Message to be handled
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::SetIniFileSettings( const RMessage2& aMessage )
+    {
+    __TRACE( KInit, ( _L( "CLoggerSetting::SetIniFileSettings" ) ) );
+
+    // Get data from message
+    TFileName iniFile;
+    
+    // Get length from message param 1
+    // Read data from client descriptor (param 0)
+    TRAPD( ret, aMessage.ReadL( 0, iniFile ) );
+
+    if ( ret != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        return KErrBadDescriptor;
+        }
+
+    // Inifile name and path information
+    iSettingServer->iIniFile = iniFile;
+
+    __TRACE( KInit, ( _L( "New initialization file: [%S]" ), &iSettingServer->iIniFile ) );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: ReadLoggerSettingsFromIniFile
+
+    Description: Read Logger setting from initialization file. Mainly use from
+                 TestEngine side.
+
+    Parameters: const RMessage& aMessage: inout: Message to be handled
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::ReadLoggerSettingsFromIniFile( const RMessage2& aMessage )
+    {
+    __TRACE( KInit, ( _L( "CLoggerSetting::ReadLoggerSettingsFromIniFile" ) ) );
+
+    TInt ret = ReadLoggerDefaults();
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+
+    // Copies logger settings to the package
+    TPckg<TLoggerSettings> loggerSettingsPckg( iSettingServer->iLoggerSettings );
+
+    // Writes a packege that includes the logger overwrite settings to aMessage
+    TRAPD( err, aMessage.WriteL( 0, loggerSettingsPckg ) );
+
+    if ( err != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CLoggerSetting
+
+    Method: ReadLoggerDefaults
+
+    Description: Parse Logger defaults from STIF initialization
+                 file.
+
+    Parameters: None
+
+    Return Values: TInt: Return Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::ReadLoggerDefaults()
+    {
+    __TRACE( KInit,( _L( "" ) ) );
+    __TRACE( KInit,( _L( "CLoggerSetting::ReadLoggerDefaults" ) ) );
+    __TRACE( KInit,( _L( "Start reading and parsing Logger defaults" ) ) );
+
+    TInt ret = KErrNone;
+    
+    // Create parser for parsing ini file
+    CStifParser* parser = NULL;
+    TRAPD( r, parser = CStifParser::NewL( _L(""), iSettingServer->iIniFile ) );
+    if ( r != KErrNone )
+        {
+        __TRACE( KError,( CStifLogger::ERed, _L( "Can't open ini-file [%S], code %d" ), &iSettingServer->iIniFile, r ) );
+        return r;
+        }
+
+    CSTIFTestFrameworkSettings* settings = NULL;
+    TRAPD( settings_ret, settings = CSTIFTestFrameworkSettings::NewL() );
+    if ( settings_ret != KErrNone )
+        {
+        __TRACE( KError,( CStifLogger::ERed, _L( "CSTIFTestFrameworkSettings class object creation fails") ) );
+        return settings_ret;
+        }
+
+    TInt get_ret( KErrNone );
+
+    CStifSectionParser* sectionParser = NULL;
+    // Parse Logger's overwrite values
+    _LIT( KDefaultsStart, "[Logger_Defaults]" );
+    _LIT( KDefaultsEnd, "[End_Logger_Defaults]" );
+    __TRACE( KInit,( _L( "Starting to search sections" ) ) );
+    
+    TRAP( r,
+        sectionParser = parser->SectionL( KDefaultsStart, KDefaultsEnd );
+        );
+    // Get directory settings
+    if ( ( r == KErrNone ) && sectionParser )
+        {
+        __TRACE( KInit,( _L( "Found '%S' and '%S' sections" ), &KDefaultsStart, &KDefaultsEnd ) );
+
+        __TRACE( KInit,( _L( "Parsing Logger directory indicator" ) ) );
+        TBool createDir( EFalse );
+        TRAP( get_ret,
+            get_ret = settings->GetBooleanSettingsL( sectionParser,
+                                _L( "CreateLogDirectories=" ), createDir );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Logger directory indicator: %d"), createDir ) );
+            iSettingServer->iLoggerSettings.iCreateLogDirectories = createDir;
+            iSettingServer->iLoggerSettings.iIsDefined.iCreateLogDir = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Indicator not found or not given" ) ) );
+            }
+
+        // Get Logger path settings
+        __TRACE( KInit,( _L( "Parsing Logger path setting (Emulator)" ) ) );
+        TPtrC emulatorPath;
+        get_ret = settings->GetFileSetting( sectionParser,
+                                               _L( "EmulatorBasePath=" ),
+                                               emulatorPath );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Logger base path setting: %S"), &emulatorPath ) );
+            iSettingServer->iLoggerSettings.iEmulatorPath = emulatorPath;
+            iSettingServer->iLoggerSettings.iIsDefined.iPath = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Path not found or not given (Emulator)" ) ) );
+            }
+
+        // Get Logger format settings
+        __TRACE( KInit,( _L( "Parsing Logger file type setting (Emulator)" ) ) );
+        CStifLogger::TLoggerType emulatorType = CStifLogger::ETxt;
+        TRAP( get_ret, 
+            get_ret = settings->GetFormatL( sectionParser,
+                                    _L( "EmulatorFormat=" ), emulatorType );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "File type setting: %d"), emulatorType ) );
+            iSettingServer->iLoggerSettings.iEmulatorFormat = emulatorType;
+            iSettingServer->iLoggerSettings.iIsDefined.iFormat = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "File type not found or not given (Emulator)" ) ) );
+            }
+
+        // Get Logger output settings
+        __TRACE( KInit,( _L( "Parsing Logger output setting (Emulator)" ) ) );
+        CStifLogger::TOutput emulatorOutput = CStifLogger::EFile;
+        TRAP( get_ret,
+            get_ret = settings->GetOutputL( sectionParser,
+                                    _L( "EmulatorOutput=" ), emulatorOutput );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Output setting: %d"), emulatorOutput ) );
+            iSettingServer->iLoggerSettings.iEmulatorOutput = emulatorOutput;
+            iSettingServer->iLoggerSettings.iIsDefined.iOutput = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Output not found or not given (Emulator)" ) ) );
+            }
+
+        // Get Logger HW path settings
+        __TRACE( KInit,( _L( "Parsing Logger path setting (Hardware)" ) ) );
+        TPtrC hwPath;
+        get_ret = settings->GetFileSetting( sectionParser,
+                                               _L( "HardwareBasePath=" ),
+                                               hwPath );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Base path setting: %S"), &hwPath ) );
+            iSettingServer->iLoggerSettings.iHardwarePath = hwPath;
+            iSettingServer->iLoggerSettings.iIsDefined.iHwPath = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Path not found or not given (Hardware)" ) ) );
+            }
+
+        // Get Logger HW format settings
+        __TRACE( KInit,( _L( "Parsing Logger file type setting (Hardware)" ) ) );
+        CStifLogger::TLoggerType hwType = CStifLogger::ETxt;
+        TRAP( get_ret,
+            get_ret = settings->GetFormatL( sectionParser,
+                                        _L( "HardwareFormat=" ), hwType );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "File type setting: %d"), hwType ) );
+            iSettingServer->iLoggerSettings.iHardwareFormat = hwType;
+            iSettingServer->iLoggerSettings.iIsDefined.iHwFormat = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "File type not found or not given (Hardware)" ) ) );
+            }
+
+        // Get Logger HW output settings
+        __TRACE( KInit,( _L( "Parsing Logger output setting (Hardware)" ) ) );
+        CStifLogger::TOutput hwOutput = CStifLogger::EFile;
+        TRAP( get_ret, 
+        get_ret = settings->GetOutputL( sectionParser,
+                                    _L( "HardwareOutput=" ), hwOutput );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Output setting: %d"), hwOutput ) );
+            iSettingServer->iLoggerSettings.iHardwareOutput = hwOutput;
+            iSettingServer->iLoggerSettings.iIsDefined.iHwOutput = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Output not found or not given (Hardware)" ) ) );
+            }
+
+        // Get Logger file creation mode (overwrite settings)
+        __TRACE( KInit,( _L( "Parsing file creation setting" ) ) );
+        TBool overwrite( ETrue );
+        TRAP( get_ret,
+            get_ret = settings->GetOverwriteL( sectionParser,
+                                _L( "FileCreationMode=" ), overwrite );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "File creation mode setting: %d"), overwrite ) );
+            iSettingServer->iLoggerSettings.iOverwrite = overwrite;
+            iSettingServer->iLoggerSettings.iIsDefined.iOverwrite = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "File creation not found or not given" ) ) );
+            }
+
+        // Get Time stamp settings
+        __TRACE( KInit,( _L( "Parsing time stamp setting" ) ) );
+        TBool timeStamp( ETrue );
+        TRAP( get_ret,
+            get_ret = settings->GetBooleanSettingsL( sectionParser,
+                                _L( "WithTimeStamp=" ), timeStamp );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Time stamp setting: %d"), timeStamp ) );
+            iSettingServer->iLoggerSettings.iTimeStamp = timeStamp;
+            iSettingServer->iLoggerSettings.iIsDefined.iTimeStamp = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Time stamp not found or not given" ) ) );
+            }
+
+        // Get Test report line break settings
+        __TRACE( KInit,( _L( "Parsing line break setting" ) ) );
+        TBool lineBreak( ETrue );
+        TRAP( get_ret,
+            get_ret = settings->GetBooleanSettingsL( sectionParser,
+                                _L( "WithLineBreak=" ), lineBreak );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Line break setting: %d"), lineBreak ) );
+            iSettingServer->iLoggerSettings.iLineBreak = lineBreak;
+            iSettingServer->iLoggerSettings.iIsDefined.iLineBreak = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Line break not found or not given" ) ) );
+            }
+
+        // Get Test report event ranking settings
+        __TRACE( KInit,( _L( "Parsing event ranking setting" ) ) );
+        TBool eventRanking( EFalse );
+        TRAP( get_ret,
+            get_ret = settings->GetBooleanSettingsL( sectionParser,
+                            _L( "WithEventRanking=" ), eventRanking );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Event ranking setting: %d"), eventRanking ) );
+            iSettingServer->iLoggerSettings.iEventRanking = eventRanking;
+            iSettingServer->iLoggerSettings.iIsDefined.iEventRanking = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Event ranking not found or not given" ) ) );
+            }
+
+        // Get Test report thread id settings
+        __TRACE( KInit,( _L( "Parsing thread id setting" ) ) );
+        TBool threadId( EFalse );
+        TRAP( get_ret,
+            get_ret = settings->GetBooleanSettingsL( sectionParser,
+                                    _L( "ThreadIdToLogFile=" ), threadId );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Thread id setting: %d"), threadId ) );
+            iSettingServer->iLoggerSettings.iThreadId = threadId;
+            iSettingServer->iLoggerSettings.iIsDefined.iThreadId = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Thread id not found or not given" ) ) );
+            }
+        // Get unicode setting
+        __TRACE( KInit,( _L( "Parsing unicode setting" ) ) );
+        TBool unicode(EFalse);
+        TRAP( get_ret,
+            get_ret = settings->GetBooleanSettingsL( sectionParser,
+                                    _L( "FileUnicode=" ), unicode );
+            );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Unicode setting: %d"), unicode ) );
+            iSettingServer->iLoggerSettings.iUnicode = unicode;
+            iSettingServer->iLoggerSettings.iIsDefined.iUnicode = ETrue;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Unicode setting not found or not given" ) ) );
+            }
+
+        // Check if test case title should be added to log file name
+        __TRACE( KInit,( _L( "Parsing AddTestCaseTitle setting" ) ) );
+        TBool addTestCaseTitle(EFalse);
+        TRAP(get_ret,
+            get_ret = settings->GetBooleanSettingsL(sectionParser,
+                                    _L( "AddTestCaseTitle=" ), addTestCaseTitle);
+            );
+        if(get_ret == KErrNone)
+            {
+            __TRACE( KInit,( _L( "AddTestCaseTitle setting: %d"), addTestCaseTitle));
+            iSettingServer->iLoggerSettings.iAddTestCaseTitle = addTestCaseTitle;
+            iSettingServer->iLoggerSettings.iIsDefined.iAddTestCaseTitle = ETrue;
+            }
+        else
+            {
+            __TRACE(KInit, (_L("AddTestCaseTitle setting not found or not given")));
+            }
+        }
+    else
+        {
+        __TRACE( KInit,( _L( "Not found '%S' and '%S' sections" ), &KDefaultsStart, &KDefaultsEnd ) );
+        ret = KErrNotFound;
+        }
+    __TRACE( KInit,( _L( "End reading and parsing Logger defaults" ) ) );
+    __TRACE( KInit,( _L( "" ) ) );
+    delete sectionParser;
+    delete settings;
+    delete parser;
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: GetLoggerSettings
+
+    Description: Get Logger settings. Mainly use from Logger side.
+
+    If there are not any active sessions, then stop active scheduler and
+    close whole server.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::GetLoggerSettings( const RMessage2& aMessage )
+    {
+    __TRACE( KInit, ( _L( "CLoggerSetting::GetLoggerSettings in" ) ) );
+    
+    // Copies logger settings to the package
+    TPckg<TLoggerSettings> loggerSettingsPckg( iSettingServer->iLoggerSettings );
+
+    // Writes a packege that includes the logger overwrite settings to aMessage
+    TRAPD( err, aMessage.WriteL( 0, loggerSettingsPckg ) );
+
+    if ( err != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        }
+
+    __TRACE( KInit, ( _L( "CLoggerSetting::GetLoggerSettings out" ) ) );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: SetNewIniFileSetting
+
+    Description: Set new initialization file settings to WINS and HW platforms.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::SetNewIniFileSetting( const RMessage2& aMessage )
+    {
+    __TRACE( KInit, ( _L( "CLoggerSetting::SetNewIniFileSetting" ) ) );
+    
+    TInt ret( 0 );
+
+    TName newIniFileSetting;
+    // Get data from message
+    // NOTE! If message length is over TName, ReadL will cut the message
+    // to allowed size and won't return any error code or leave code.
+    TRAP( ret, aMessage.ReadL( 0, newIniFileSetting ) );
+
+    if ( ret != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        return KErrBadDescriptor;
+        }
+
+    iSettingServer->iLoggerSettings.iEmulatorPath = newIniFileSetting;
+    iSettingServer->iLoggerSettings.iIsDefined.iPath = ETrue;
+    iSettingServer->iLoggerSettings.iHardwarePath = newIniFileSetting;
+    iSettingServer->iLoggerSettings.iIsDefined.iHwPath = ETrue;
+
+    __TRACE( KInit, ( _L( "New emulator and hardware path: [%S]" ), &newIniFileSetting ) );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: GetEngineSettings
+
+    Description: Get TestEngine settings.
+
+    If there are not any active sessions, then stop active scheduler and
+    close whole server.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::GetEngineSettings(const RMessage2& aMessage)
+    {
+    __TRACE(KInit, (_L("CLoggerSetting::GetEngineSettings in")));
+    
+    // Copies logger settings to the package
+    TPckg<TEngineSettings> engineSettingsPckg(iSettingServer->iEngineSettings);
+
+    // Writes a packege that includes the logger overwrite settings to aMessage
+    TRAPD(err, aMessage.WriteL(0, engineSettingsPckg));
+
+    if(err != KErrNone)
+        {
+        PanicClient(EBadDescriptor, aMessage);
+        }
+
+    __TRACE(KInit, (_L("CLoggerSetting::GetEngineSettings out")));
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSettingServer
+
+    Method: StoreEngineSettings
+
+    Description: Store TestEngine settings.
+
+    If there are not any active sessions, then stop active scheduler and
+    close whole server.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CLoggerSetting::StoreEngineSettings(const RMessage2& aMessage)
+    {
+    __TRACE(KInit, (_L("CLoggerSetting::StoreEngineSettings in")));
+    
+    // Copies logger settings to the package
+    TPckg<TEngineSettings> engineSettingsPckg(iSettingServer->iEngineSettings);
+
+    // Reads a packege that includes the engine settings
+    TRAPD(err, aMessage.ReadL(0, engineSettingsPckg));
+
+    if(err != KErrNone)
+        {
+        PanicClient(EBadDescriptor, aMessage);
+        }
+
+    __TRACE(KInit, (_L("CLoggerSetting::StoreEngineSettings out")));
+
+    return KErrNone;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/StifPythonFunEng.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains StifPythonFunEng implementation.
+*
+*/
+
+// INCLUDE FILES
+#include "StifPythonFunEng.h"
+#include <e32svr.h>
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// GetNewIndexForThreadL
+// Function countss all threads named like pythonscripter* and returns index for
+// the new thread for pythonscripter.
+// -----------------------------------------------------------------------------
+TInt GetNewIndexForThreadL(void)
+	{
+	TInt max_index = 0;
+	// * as a wildcard for the name search
+	_LIT(KFindAll, "pythonscripter*");
+
+	// default RThread object, has a handle of the current thread
+	RThread thread;
+	TFullName fullName;
+	TFindThread finder(KFindAll);
+
+	while(finder.Next(fullName) == KErrNone)
+		{
+		max_index++;
+		}
+	return max_index;
+	}
+//
+// ============================ MEMBER FUNCTIONS ===============================
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/TestCaseController.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2880 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestCaseController class member functions.
+*
+*/
+
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include <e32uid.h>
+#include <StifLogger.h>
+#include "StifTFwIfProt.h"
+#include "TestCaseController.h"
+#include "TestModuleController.h"
+#include "TestReport.h"
+#include "Logging.h"
+#include "StifHWReset.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+
+#define LOGGER iEngine->Logger()
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: CTestCaseController
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+                CAtsLogger& aAtsLogger: in: Reference to CAtsLogger
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+                const TTestInfo& aTestInfo: in: Test Info
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseController::CTestCaseController( CTestEngine* aEngine,
+                                          CTestReport* aTestReport,
+                                          CAtsLogger& aAtsLogger,
+                                          RTestExecution aTestExecution,
+                                          const TTestInfo& aTestInfo ) :
+    CActive( CActive::EPriorityStandard ),
+    iEngine( aEngine ),
+    iTestReport( aTestReport ),
+    iTestExecution( aTestExecution ),
+    iTestInfo( aTestInfo ),
+    iState( ETestCaseIdle ),
+    iResultPckg( iResult ),
+    iAtsLogger( aAtsLogger )
+    {
+    CActiveScheduler::Add( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseController::ConstructL()
+    {
+    __TRACE( KVerbose, ( _L( "CTestCaseController::ConstructL, [%S]" ), &iTestInfo.iTestCaseInfo.iTitle ) );
+
+    // Logger settings
+    TLoggerSettings loggerSettings;
+    loggerSettings.iCreateLogDirectories = EFalse;
+    loggerSettings.iOverwrite = ETrue;
+    loggerSettings.iTimeStamp = EFalse;
+    loggerSettings.iLineBreak = EFalse;
+    loggerSettings.iEventRanking = EFalse;
+    loggerSettings.iThreadId = EFalse;
+    loggerSettings.iHardwareFormat = CStifLogger::ETxt;
+    loggerSettings.iHardwareOutput = CStifLogger::ERDebug;
+    loggerSettings.iEmulatorFormat = CStifLogger::ETxt;
+    loggerSettings.iEmulatorOutput = CStifLogger::ERDebug;
+    loggerSettings.iUnicode = EFalse;
+    loggerSettings.iAddTestCaseTitle = EFalse;
+
+    iRDebugLogger = CStifLogger::NewL( _L( "" ), _L( "" ), loggerSettings );
+
+    // If timeout is specified, then create timeout handler.
+    if ( iTestInfo.iTestCaseInfo.iTimeout > TTimeIntervalMicroSeconds(0) )
+        {
+        iTimeout = CTestCaseTimeout::NewL ( this,
+                                            iTestInfo.iTestCaseInfo.iTimeout );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                CTestReport* aTestReport: in: Pointer to CTestReport
+                CAtsLogger& aAtsLogger: in: Reference to CAtsLogger
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+                const TTestInfo& aTestInfo: in: Test Info
+
+    Return Values: CTestCaseController* : pointer to created object
+
+    Errors/Exceptions: Leaves if construction of CTestCaseController fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseController* CTestCaseController::NewL( CTestEngine* aEngine,
+                                               CTestReport* aTestReport,
+                                               CAtsLogger& aAtsLogger,
+                                               RTestExecution aTestExecution,
+                                               const TTestInfo& aTestInfo )
+    {
+    CTestCaseController* self = new ( ELeave ) CTestCaseController( aEngine,
+        aTestReport, aAtsLogger, aTestExecution, aTestInfo );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: ~CTestCaseController
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseController::~CTestCaseController()
+    {
+    __TRACE( KVerbose, ( _L( "CTestCaseController::~CTestCaseController" ) ) );
+    Cancel();
+
+    delete iRDebugLogger;
+    delete iTimeout;
+    delete iTestCaseArguments;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: StartL
+
+    Description: Start active object
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseController::StartL( const RMessage2& aMessage )
+    {
+    iRDebugLogger->Log( _L( "Starting testcase [%S]" ), &iTestInfo.iTestCaseInfo.iTitle );
+    __TRACE( KInit, ( _L(" Starting testcase [%S]"), &iTestInfo.iTestCaseInfo.iTitle ) );
+
+    // Check that this request is not pending!!
+    __ASSERT_ALWAYS( iState != ETestCaseRunning,
+                            iEngine->PanicClient( EReqPending, aMessage ) );
+    iMessage = aMessage;
+
+    iState = ETestCaseRunning;
+    
+    delete iTestCaseArguments;
+    iTestCaseArguments = NULL;
+    
+    TInt testCaseArgumentsLength = iMessage.GetDesLength( 1 );
+    if ( ( testCaseArgumentsLength != KErrArgument ) && ( testCaseArgumentsLength != KErrBadDescriptor ) )
+        {
+        iTestCaseArguments = HBufC::NewL( testCaseArgumentsLength );
+        TPtr testCaseArgumentsPtr( iTestCaseArguments->Des() );
+        User::LeaveIfError( iMessage.Read( 1, testCaseArgumentsPtr ) );
+        iTestExecution.RunTestCase( iResultPckg, *iTestCaseArguments, iStatus );        
+        }
+    else
+        {    
+        iTestExecution.RunTestCase( iResultPckg, iStatus );
+        }
+    SetActive();
+
+    // If testcase has timeout (handler), then start it
+    if ( iTimeout )
+        {
+        iTimeout->Start();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: Timeout
+
+    Description: Timeouts active request.
+    - Cancel request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseController::Timeout()
+    {
+    if ( iState == ETestCaseRunning )
+        {
+        iState = ETestCaseTimeout;
+        Cancel();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: RunL
+
+    Description: RunL handles completed requests. Leaves are handled in
+                 RunError method
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if AddTestCaseResultL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseController::RunL()
+    {
+    iState = ETestCaseCompleted;
+
+
+    // "iStatus.Int()" error code is received from system's framework not from
+    // test case execution.
+    if ( iStatus.Int() != KErrNone )
+        {
+            if ( iStatus.Int() == KErrServerTerminated )
+            {
+            // something went badly wrong!
+            __TRACE( KInit, ( CStifLogger::ERed, 
+                _L( "TestCase [%S] cannot be executed, STIF panics with[%d]" ),
+                &iTestInfo.iTestCaseInfo.iTitle,
+                iStatus.Int() ) );       
+                
+            __TRACE( KInit, ( CStifLogger::ERed, 
+                _L( "Possible reason: Test case has paniced seriously" ) ) );
+
+            // We don't leave here but we write information to 
+            // forward(testreport etc.)
+            _LIT( KLeaveInfo, "Test case execution fails" );
+            // Sets test case to crash category
+            iResult.iCaseExecutionResultCode = iStatus.Int();
+            // Test case result
+            iResult.iTestResult.iResult = iStatus.Int();
+            iResult.iTestResult.iResultDes = KLeaveInfo;
+
+            } 
+        
+            else
+            {   
+        // For example testmodule's NewL or testmodule's constructor has
+        // leaved and STIF cannot connect to test module
+        __TRACE( KInit, ( CStifLogger::ERed, 
+            _L( "TestCase [%S] cannot execute, TestModule loading operations fails with[%d]" ),
+            &iTestInfo.iTestCaseInfo.iTitle,
+            iStatus.Int() ) );
+        __TRACE( KInit, ( CStifLogger::ERed, 
+            _L( "Possible reason: TestModule's NewL or Constructor has leaved and STIF cannot connect to test module" ) ) );
+
+        // We don't leave here but we write information to 
+        // forward(testreport etc.)
+        _LIT( KLeaveInfo, "TestModule loading fails, cannot connect to the TestModule" );
+        // Sets test case to crash category
+        iResult.iCaseExecutionResultCode = iStatus.Int();
+        // Test case result
+        iResult.iTestResult.iResult = iStatus.Int();
+        iResult.iTestResult.iResultDes = KLeaveInfo;
+            }
+        }
+        
+	else
+	{
+			
+    // Cancel event request, because the testcase is completed
+    iTestExecution.CancelAsyncRequest( ETestExecutionNotifyEvent );        
+	}
+
+    // Test case is executed
+    if( iTestInfo.iTestCaseInfo.iTitle.Length() > 0 )
+        {
+        iRDebugLogger->Log( _L( "TestCase [%S] finished with verdict[%d]" ),
+                            &iTestInfo.iTestCaseInfo.iTitle,
+                            iResult.iTestResult.iResult );
+
+        __TRACE( KInit, ( _L( " TestCase [%S] finished with verdict[%d]" ),
+                            &iTestInfo.iTestCaseInfo.iTitle,
+                            iResult.iTestResult.iResult ) );
+        }
+    else
+        {
+        iRDebugLogger->Log( _L( "TestCase [%d] finished with verdict[%d]" ),
+                            iTestInfo.iTestCaseInfo.iCaseNumber,
+                            iResult.iTestResult.iResult );
+
+        __TRACE( KInit, ( _L( " TestCase [%d] finished with verdict[%d]" ),
+                            iTestInfo.iTestCaseInfo.iCaseNumber,
+                            iResult.iTestResult.iResult ) );
+        }
+    __TRACE( KVerbose, ( 
+            _L( "CTestCaseController::RunL: iStatus=[%d]" ), iStatus.Int() ));
+
+    GenerateXmlLogL();
+
+    // Report test case result
+    if( iTestReport )
+        {
+        iTestReport->AddTestCaseResultL( iTestInfo, iResult, iStatus.Int() );
+        iTestReport->UpdateReportSummaryL();
+        }
+
+    TRAPD( ret, iMessage.WriteL( 0, iResultPckg ) );
+
+    // Case done
+    iMessage.Complete( ret );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseController::DoCancel()
+    {
+
+    switch ( iState )
+        {
+        case ETestCaseRunning:
+            iTestExecution.CancelAsyncRequest( ETestExecutionRunTestCase );
+            if( iTestInfo.iTestCaseInfo.iTitle.Length() > 0 )
+                {
+                iRDebugLogger->Log( _L( "TestCase [%S] execution aborted" ),
+                                    &iTestInfo.iTestCaseInfo.iTitle );
+
+                __TRACE( KInit, ( _L( "TestCase [%S] execution aborted" ),
+                                    &iTestInfo.iTestCaseInfo.iTitle ) );
+                }
+            else
+                {
+                iRDebugLogger->Log( _L( "TestCase [%S] execution aborted" ),
+                                    iTestInfo.iTestCaseInfo.iCaseNumber );
+
+                __TRACE( KInit, ( _L( "TestCase [%S] execution aborted" ),
+                                    iTestInfo.iTestCaseInfo.iCaseNumber ) );
+                }
+            break;
+        case ETestCaseTimeout:
+            iTestExecution.CancelAsyncRequest( ETestExecutionRunTestCase );
+            // Update result to timeout
+            iResult.iCaseExecutionResultType = TFullTestResult::ECaseTimeout;
+            iResult.iTestResult.iResultDes = _L("Test case was timeouted and cancelled");
+
+            if( iTestReport )
+                {
+                iTestReport->AddTestCaseResultL( iTestInfo, iResult, KErrTimedOut );
+                }
+
+            if( iTestInfo.iTestCaseInfo.iTitle.Length() > 0 )
+                {
+                iRDebugLogger->Log( _L( "TestCase [%S] finished with verdict[%d]" ),
+                                    &iTestInfo.iTestCaseInfo.iTitle,
+                                    iResult.iTestResult.iResult );
+
+                __TRACE( KInit, ( _L( " TestCase [%S] finished with verdict[%d]" ),
+                                    &iTestInfo.iTestCaseInfo.iTitle,
+                                    iResult.iTestResult.iResult ) );
+                }
+            else
+                {
+                iRDebugLogger->Log( _L( "TestCase [%d] finished with verdict[%d]" ),
+                                    iTestInfo.iTestCaseInfo.iCaseNumber,
+                                    iResult.iTestResult.iResult );
+
+                __TRACE( KInit, ( _L( " TestCase [%d] finished with verdict[%d]" ),
+                                    iTestInfo.iTestCaseInfo.iCaseNumber,
+                                    iResult.iTestResult.iResult ) );
+                }            
+            
+            break;
+        case ETestCaseSuicided:
+            {
+            //Store current results because cancel operation overwrites it
+            TInt currentTestResult = iResult.iTestResult.iResult;
+            TInt currentExecutionResult = iResult.iCaseExecutionResultCode;
+            iTestExecution.CancelAsyncRequest(ETestExecutionRunTestCase);
+            // Update result to suicide
+            switch(iStopExecutionType)
+                {
+                case EOk:
+                    iResult.iCaseExecutionResultType = TFullTestResult::ECaseExecuted;
+                    iResult.iTestResult.iResultDes = _L("Test case passed (StopExecution())");
+                    break;
+                case EFail:
+                    iResult.iCaseExecutionResultType = TFullTestResult::ECaseExecuted;
+                    iResult.iTestResult.iResultDes = _L("Test case failed (StopExecution())");
+                    break;
+                default: //EAbort
+                    iResult.iCaseExecutionResultType = TFullTestResult::ECaseSuicided;
+                    iResult.iTestResult.iResultDes = _L("Test case killed (StopExecution())");
+                }
+            iResult.iTestResult.iResult = currentTestResult;
+            iResult.iCaseExecutionResultCode = currentExecutionResult;
+            }
+            if(iTestReport)
+                {
+                iTestReport->AddTestCaseResultL(iTestInfo, iResult, KErrNone);
+                }
+
+            // Log some message
+            if(iTestInfo.iTestCaseInfo.iTitle.Length() > 0)
+                {
+                _LIT(KTestCaseDesc, "TestCase [%S] finished with verdict [%d]");
+                switch(iStopExecutionType)
+                    {
+                    case EOk:
+                        {
+                        _LIT(KTestCaseResult, "***Testcase PASSED***");
+
+                        iRDebugLogger->Log(KTestCaseResult);
+                        __TRACE(KInit, (KTestCaseResult));
+                        iRDebugLogger->Log(KTestCaseDesc, &iTestInfo.iTestCaseInfo.iTitle, iResult.iTestResult.iResult);
+                        __TRACE(KInit, (KTestCaseDesc, &iTestInfo.iTestCaseInfo.iTitle, iResult.iTestResult.iResult));
+                        break;
+                        }
+                    case EFail:
+                        {
+                        _LIT(KTestCaseResult, "***Testcase FAILED***");
+
+                        iRDebugLogger->Log(KTestCaseResult);
+                        __TRACE(KInit, (KTestCaseResult));
+                        iRDebugLogger->Log(KTestCaseDesc, &iTestInfo.iTestCaseInfo.iTitle, iResult.iTestResult.iResult);
+                        __TRACE(KInit, (KTestCaseDesc, &iTestInfo.iTestCaseInfo.iTitle, iResult.iTestResult.iResult));
+                        break;
+                        }
+                    default: //EAbort
+                        {
+                        _LIT(KTestCaseResult, "***Testcase KILLED***");
+
+                        iRDebugLogger->Log(KTestCaseResult);
+                        __TRACE(KInit, (KTestCaseResult));
+                        iRDebugLogger->Log(KTestCaseDesc, &iTestInfo.iTestCaseInfo.iTitle, iResult.iTestResult.iResult);
+                        __TRACE(KInit, (KTestCaseDesc, &iTestInfo.iTestCaseInfo.iTitle, iResult.iTestResult.iResult));
+                        }
+                    }
+                }
+            else
+                {
+                _LIT(KTestCaseDesc, "TestCase [%d] finished with verdict [%d]");
+                switch(iStopExecutionType)
+                    {
+                    case EOk:
+                        {
+                        _LIT(KTestCaseResult, "***Testcase PASSED***");
+
+                        iRDebugLogger->Log(KTestCaseResult);
+                        __TRACE(KInit, (KTestCaseResult));
+                        iRDebugLogger->Log(KTestCaseDesc, iTestInfo.iTestCaseInfo.iCaseNumber, iResult.iTestResult.iResult);
+                        __TRACE(KInit, (KTestCaseDesc, iTestInfo.iTestCaseInfo.iCaseNumber, iResult.iTestResult.iResult));
+                        break;
+                        }
+                    case EFail:
+                        {
+                        _LIT(KTestCaseResult, "***Testcase FAILED***");
+
+                        iRDebugLogger->Log(KTestCaseResult);
+                        __TRACE(KInit, (KTestCaseResult));
+                        iRDebugLogger->Log(KTestCaseDesc, iTestInfo.iTestCaseInfo.iCaseNumber, iResult.iTestResult.iResult);
+                        __TRACE(KInit, (KTestCaseDesc, iTestInfo.iTestCaseInfo.iCaseNumber, iResult.iTestResult.iResult));
+                        break;
+                        }
+                    default: //EAbort
+                        {
+                        _LIT(KTestCaseResult, "***Testcase KILLED***");
+
+                        iRDebugLogger->Log(KTestCaseResult);
+                        __TRACE(KInit, (KTestCaseResult));
+                        iRDebugLogger->Log(KTestCaseDesc, iTestInfo.iTestCaseInfo.iCaseNumber, iResult.iTestResult.iResult);
+                        __TRACE(KInit, (KTestCaseDesc, iTestInfo.iTestCaseInfo.iCaseNumber, iResult.iTestResult.iResult));
+                        }
+                    }
+                }
+            break;
+        case ETestCaseIdle:
+        case ETestCaseCompleted:
+        default:
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestCaseController, "CTestCaseController" );
+            User::Panic( KTestCaseController, EDoCancelDisorder );
+            break;
+        }
+
+    // Write result and complete 
+    TRAPD( ret, iMessage.WriteL( 0, iResultPckg ) );
+
+    iMessage.Complete( ret );  
+        
+    iState = ETestCaseCompleted;
+    
+    // Generate xml result log
+    GenerateXmlLogL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: RunError
+
+    Description: Handle errors.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCaseController::RunError( TInt aError )
+    {
+    __TRACE( KError, ( CStifLogger::ERed, 
+        _L( "CTestCaseController::RunError: Test case execution has failed! aError=[%d]" ), aError ) );
+    TInt completionError = aError;
+
+    // Write result, because it could include descriptive result for
+    // failed case
+    TRAPD( err, iMessage.WriteL( 0, iResultPckg ); );
+
+    if ( err != KErrNone )
+        {
+        completionError = err;
+        }
+
+    // Complete message with error
+    iMessage.Complete( completionError );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: GenerateXmlLogL
+
+    Description: Generate XML log.
+
+    Parameters: None
+
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseController::GenerateXmlLogL()
+    {
+    
+    // Report result with AtsLogger
+    iAtsLogger.BeginTestCaseReportL( iTestInfo.iTestCaseInfo.iTitle, 
+                                     KErrNone,  // Expected result not supported
+                                     iResult.iStartTime );
+    
+    if( iResult.iCaseExecutionResultCode != KErrNone )
+        {
+        iAtsLogger.SetTestCaseResultL( iResult.iCaseExecutionResultCode );
+        iAtsLogger.TestCaseFailed();  
+        if( iResult.iTestResult.iResultDes.Length() > 0 )
+            {
+            iAtsLogger.ErrorL( iResult.iTestResult.iResultDes );   
+            } 
+        }
+     else
+        {
+        iAtsLogger.SetTestCaseResultL( iResult.iTestResult.iResult ); 
+        if( iResult.iTestResult.iResult == KErrNone )
+            {
+            iAtsLogger.TestCasePassed();  
+            }
+        else
+            {
+            iAtsLogger.TestCaseFailed();  
+            if( iResult.iTestResult.iResultDes.Length() > 0 )
+                {
+                iAtsLogger.ErrorL( iResult.iTestResult.iResultDes );    
+                }
+            }
+        }
+    // Set test case result to ATS Logger
+    iAtsLogger.EndTestCaseL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: GetTestCaseInfo
+
+    Description: Get testcase info(test module, config file, test case, etc).
+
+    Parameters: TTestInfo& aTestInfo: inout: Test information
+
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseController::GetTestCaseInfo( TTestInfo& aTestInfo )
+    {
+    aTestInfo = iTestInfo;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseController
+
+    Method: Suicide
+
+    Description: Cancels active request.
+
+    Parameters: aCode: the reason of suicide
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseController::Suicide(TStopExecutionType aType, TInt aCode)
+    {
+    if(iState == ETestCaseRunning)
+        {
+        iStopExecutionType = aType;
+        switch(iStopExecutionType)
+            {
+            case EOk:
+                iResult.iTestResult.iResult = KErrNone;
+                iResult.iCaseExecutionResultCode = KErrNone;
+                break;
+            case EFail:
+                iResult.iTestResult.iResult = aCode;
+                iResult.iCaseExecutionResultCode = KErrNone;
+                break;
+            default: //EAbort
+                iResult.iTestResult.iResult = aCode;
+                iResult.iCaseExecutionResultCode = aCode;
+            }
+        iState = ETestCaseSuicided;
+        Cancel();
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestProgressNotifier class member
+    functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: CTestProgressNotifier
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestProgressNotifier::CTestProgressNotifier( CTestEngine* aEngine,
+                             RTestExecution aTestExecution ) :
+    CActive( CActive::EPriorityStandard ),
+    iEngine( aEngine ),
+    iTestExecution( aTestExecution ),
+    iState( ETestProgressIdle ),
+    iProgressPckg( iProgress )
+    {
+    CActiveScheduler::Add( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestProgressNotifier::ConstructL()
+    {
+    __TRACE( KVerbose, ( _L( "CTestProgressNotifier::ConstructL" ) ) );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+
+    Return Values: CTestProgressNotifier* : pointer to created object
+
+    Errors/Exceptions: Leaves if construction of CTestProgressNotifier fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestProgressNotifier* CTestProgressNotifier::NewL( CTestEngine* aEngine,
+                             RTestExecution aTestExecution )
+    {
+    CTestProgressNotifier* self = new ( ELeave ) CTestProgressNotifier(
+        aEngine, aTestExecution );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: ~CTestProgressNotifier
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestProgressNotifier::~CTestProgressNotifier()
+    {
+    __TRACE( KVerbose, ( _L( "CTestProgressNotifier::~CTestProgressNotifier" ) ) );
+    Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: StartL
+
+    Description: Start active object
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestProgressNotifier::StartL( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestProgressNotifier::StartL" ) ) );
+    // Check that this request is not pending!!
+    __ASSERT_ALWAYS( iState != ETestProgressPending,
+                        iEngine->PanicClient( EReqPending, aMessage ) );
+    iMessage = aMessage;
+
+    iState = ETestProgressPending;
+    SetActive();
+
+    iTestExecution.NotifyProgress( iProgressPckg, iStatus );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if WriteL leaves
+                       Leaves if iStatus is not KErrNone or KErrEof
+                       Leaves are handled in RunError method
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestProgressNotifier::RunL()
+    {
+    __TRACE( KVerbose, (_L("CTestProgressNotifier::RunL: iStatus=[%d]" ), iStatus.Int() ));
+
+    iState = ETestProgressCompleted;
+
+    // Check that request was successful or completed with acceptable error
+    // KErrEof is acceptable error and it means that the test case will not
+    // send progresses anymore (because it is closed)
+    if ( KErrNone == iStatus.Int() )
+        {
+        iMessage.WriteL( 0, iProgressPckg );
+        }
+    else if ( KErrEof != iStatus.Int() )
+        {
+        // Leave, error will be handled in RunError
+        User::Leave( iStatus.Int() );
+        }
+
+    // Complete message
+    iMessage.Complete( iStatus.Int() );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestProgressNotifier::DoCancel()
+    {
+    switch ( iState )
+        {
+        case ETestProgressPending:
+            iTestExecution.CancelAsyncRequest( ETestExecutionNotifyProgress );
+            iMessage.Complete( KErrCancel );
+            break;
+        case ETestProgressIdle:
+        case ETestProgressCompleted:
+        default:
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestProgressNotifier, "CTestProgressNotifier" );
+            User::Panic( KTestProgressNotifier, EDoCancelDisorder );
+            break;
+        }
+    iState = ETestProgressIdle;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: RunError
+
+    Description: Handle errors.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestProgressNotifier::RunError( TInt aError )
+    {
+    // Complete message with error
+    iMessage.Complete( aError );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestEventNotifier class member
+    functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: CTestEventNotifier
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEventNotifier::CTestEventNotifier( CTestEngine* aEngine, 
+                                        RTestExecution aTestExecution ) :
+    CActive( CActive::EPriorityStandard ),
+    iEngine( aEngine ),
+    iTestExecution( aTestExecution ),
+    iState( ETestEventIdle ),
+    iEventPckg( iEvent ),
+    iEventNotifyPckg( iEventNotify ),
+    iController( NULL )
+    {
+    CActiveScheduler::Add( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEventNotifier::ConstructL( )
+    {
+    __TRACE( KVerbose, ( _L( "CTestEventNotifier::ConstructL" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+
+    Return Values: CTestEventNotifier* : pointer to created object
+
+    Errors/Exceptions: Leaves if construction of CTestEventNotifier fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEventNotifier* CTestEventNotifier::NewL( CTestEngine* aEngine,
+                                              RTestExecution aTestExecution )
+    {
+    CTestEventNotifier* self = new ( ELeave ) CTestEventNotifier(
+        aEngine, aTestExecution );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: ~CTestEventNotifier
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEventNotifier::~CTestEventNotifier()
+    {
+    __TRACE( KVerbose, ( _L( "CTestEventNotifier::~CTestEventNotifier" ) ) );
+    Cancel();
+    iEventArray.ResetAndDestroy();
+    iEventArray.Close();
+    delete iController;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: StartL
+
+    Description: Start active object
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEventNotifier::Start()
+    {
+    __TRACE( KVerbose, ( _L( "CTestEventNotifier::StartL" ) ) );
+    // Check that this request is not pending!!
+    __ASSERT_ALWAYS( iState != ETestEventPending,
+        User::Leave( KErrAlreadyExists ) );
+
+    iEvent.SetType( TEventIf::EEnable );
+    iState = ETestEventPending;
+    iTestExecution.NotifyEvent( iEventPckg, iStatus );
+    SetActive();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone
+                       Leaves if iState is not ETestEventPending
+                       Leaves if some leaving method called here leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEventNotifier::RunL()
+    {
+    __TRACE( KVerbose, ( _L( "CTestEventNotifier::RunL: iStatus=[%d]" ), iStatus.Int() ) );
+
+    User::LeaveIfError( iStatus.Int() );
+
+    switch( iState )
+        {
+        case ETestEventPending:
+            {
+            iState = ETestEventCompleted;
+            
+            switch( iEvent.Type() )
+                {
+                case TEventIf::EReqEvent:
+                    {
+                    __RDEBUG( ( _L("CTestEventNotifier(ReqEvent) %S"), 
+                        &iEvent.Name() ));
+                    if( iEngine->IsStateEventAndSet( iEvent.Name() ) )
+                        {
+                        __TRACE( KVerbose, ( _L( "CTestEventNotifier::RunL: Requested Global event already set" ) ) );
+                        TEventIf event( TEventIf::ESetEvent, iEvent.Name(),
+                                        TEventIf::EState );
+                        TEventIfPckg eventPckg( event );
+                        TRequestStatus status;
+                        iTestExecution.NotifyEvent( eventPckg, status );
+                        User::WaitForRequest( status );
+                        }
+                    //add to iEventArray
+                    HBufC* name = iEvent.Name().AllocLC();
+                    if( iEventArray.Append( name ) != KErrNone )
+                        {
+                        User::Leave( KErrNoMemory );
+                        }
+                    CleanupStack::Pop( name );
+                    }
+                    break;                    
+                case TEventIf::ERelEvent:
+                    {
+                    __TRACE( KVerbose, ( _L( "CTestEventNotifier(RelEvent) %S" ), &iEvent.Name() ) );
+                    //remove from iEventArray
+                    TInt count = iEventArray.Count();
+                    const TDesC& eventName = iEvent.Name();
+                    TInt i;
+                    for( i = 0; i < count; i++ )
+                        {
+                        TPtrC name = iEventArray[i]->Des();
+                        if( name == eventName )
+                            {
+                            HBufC* tmp = iEventArray[i];
+                            iEventArray.Remove( i );
+                            delete tmp;
+                            break;
+                            }
+                        }
+                    // Check that event was found
+                    if( i == count )
+                        {
+                        User::Leave( KErrGeneral );
+                        }         
+                    }
+                    break;                    
+                case TEventIf::ESetEvent:
+                    {
+                    __RDEBUG( ( _L("CTestEventNotifier(SetEvent) %S"), 
+                        &iEvent.Name() ));
+                    iController = iEngine->CtlEventL( iEvent, iStatus );
+                    SetActive();
+                    return;
+                    }
+                case TEventIf::EUnsetEvent:
+                    {
+                    __RDEBUG( ( _L("CTestEventNotifier(UnsetEvent) %S"), 
+                        &iEvent.Name() ));
+                    iController = iEngine->CtlEventL( iEvent, iStatus );
+                    SetActive();
+                    return;
+                    }
+                default:
+                    {
+                    User::Leave( KErrGeneral );
+                    }
+                }
+            // Set request again
+            Start();                
+            // Otherwise request is enabled again later
+            }
+            break;
+        case ETestEventCompleted:
+            __RDEBUG( ( _L("CTestEventNotifier(Complete)")));
+            Start();
+            break;
+        default:
+            User::Leave( KErrGeneral );
+            break;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEventNotifier::DoCancel()
+    {
+    __TRACE( KVerbose, ( _L( "CTestEventNotifier::DoCancel" ) ) );
+
+    switch ( iState )
+        {
+        case ETestEventPending:
+            iTestExecution.CancelAsyncRequest( ETestExecutionNotifyEvent );
+            break;
+        case ETestEventCompleted:
+            delete iController;
+            iController = NULL;
+            break;
+        default:
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestEventNotifier, "CTestEventNotifier" );
+            User::Panic( KTestEventNotifier, EDoCancelDisorder );
+            break;
+        }
+
+    iState = ETestEventIdle;
+    iEventArray.ResetAndDestroy();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: RunError
+
+    Description: Handle errors.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEventNotifier::RunError( TInt aError )
+    {
+    switch ( iState )
+        {
+        case ETestEventPending:
+            if( aError != KErrCancel )
+                {
+                __TRACE( KError, ( CStifLogger::ERed, _L( "CTestEventNotifier::RunError %d"), aError) );
+                }
+            else
+                {
+                __TRACE( KVerbose, ( _L( "CTestEventNotifier stopped")) );
+                }
+
+            // We stop event notifier if we get error here
+            // Clear requested event list
+            iEventArray.ResetAndDestroy();
+            break;
+        case ETestEventCompleted:
+            // Do not close here
+            __TRACE( KError, ( CStifLogger::ERed, _L( "CTestEventNotifier::RunError %d"), aError) );
+            delete iController;
+            iController = NULL;
+            // forward error to testcase
+            iEvent.SetType( TEventIf::EEnable );
+            iState = ETestEventPending;
+            iTestExecution.NotifyEvent( iEventPckg, iStatus, aError );
+            SetActive();
+            break;
+        default:
+            __TRACE( KError, ( CStifLogger::ERed, _L( "CTestEventNotifier::RunError %d"), aError) );
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestEventNotifier, "CTestEventNotifier" );
+            User::Panic( KTestEventNotifier, EDoCancelDisorder );
+            break;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: CtlEventL
+
+    Description: Controls events
+
+    Parameters: const TEventIf& aEvent: in: Event
+                TRequestStatus& aStatus: in: Request status
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEventNotifier::CtlEvent( const TEventIf& aEvent, 
+                                    TRequestStatus& aStatus )
+    {
+    __TRACE( KVerbose, ( _L( "CTestEventNotifier::CtlEventL" ) ) );
+    const TDesC& eventName = aEvent.Name();
+    TInt count = iEventArray.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        TPtrC name = iEventArray[i]->Des();
+        if( name == eventName )
+            {
+            iEventNotify.Copy( aEvent );
+            iTestExecution.NotifyEvent( iEventNotifyPckg, aStatus );
+            return;
+            }
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: CheckCtlEventL
+
+    Description: Checks if CtlEvent should be called
+
+    Parameters: const TEventIf& aEvent: in: Event
+
+    Return Values: ETrue: If CtlEvent sould be called.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestEventNotifier::CheckCtlEvent( const TEventIf& aEvent )
+    {
+    const TDesC& eventName = aEvent.Name();
+    TInt count = iEventArray.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        TPtrC name = iEventArray[i]->Des();
+        if( name == eventName )
+            {
+            return ETrue;
+            }
+        }
+
+    return EFalse;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestEventController class member
+    functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: CTestEventController
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                const TEventIf& aEvent: in: Event
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEventController::CTestEventController( CTestEngine* aEngine, 
+                                            const TEventIf& aEvent ) :
+    iEngine( aEngine ),
+    iRequestStatus( NULL ),
+    iEventPckg( iEvent ),
+    iActiveEventCmds( 0 )
+    {
+    iEvent.Copy( aEvent );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: TRequestStatus* aStatus: in: Request status
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEventController::ConstructL( TRequestStatus* aStatus )
+    {
+    iEngine->Logger()->Log( _L( "CTestEventController::ConstructL" ) );
+
+    if( CheckEventsL() == 0 )
+        {
+        // No request was pending, complete immediately
+        User::RequestComplete( aStatus, KErrNone );
+        }
+    else
+        {
+        iRequestStatus = aStatus;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: RMessage& aMessage: inout: Message to be handled
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEventController::ConstructL( RMessage2& aMessage )
+    {
+    iEngine->Logger()->Log( _L( "CTestEventController::ConstructL" ) );
+
+    if( CheckEventsL() == 0 )
+        {
+        // No request was pending, complete immediately
+        aMessage.Complete( KErrNone );
+        }
+    else
+        {
+        iMessage = aMessage;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                const TEventIf& aEvent: in: Event
+                TRequestStatus* aStatus: in: Request status
+
+    Return Values: CTestEventController* : pointer to created object
+
+    Errors/Exceptions: Leaves if construction of CTestEventController fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+
+CTestEventController* CTestEventController::NewL( CTestEngine* aEngine,
+                                                  const TEventIf& aEvent,
+                                                  TRequestStatus* aStatus )
+    {
+    CTestEventController* self = 
+        new ( ELeave )CTestEventController( aEngine, aEvent );
+    CleanupStack::PushL( self );
+    self->ConstructL( aStatus );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventNotifier
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                const TEventIf& aEvent: in: Event
+                RMessage& aMessage: inout: Message to be handled
+
+    Return Values: CTestEventController* : pointer to created object
+
+    Errors/Exceptions: Leaves if construction of CTestEventController fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEventController* CTestEventController::NewL( CTestEngine* aEngine,
+                                                  const TEventIf& aEvent,
+                                                  RMessage2& aMessage )
+    {
+    CTestEventController* self = 
+        new ( ELeave )CTestEventController( aEngine, aEvent );
+    CleanupStack::PushL( self );
+    self->ConstructL( aMessage );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: ~CTestEventController
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+
+CTestEventController::~CTestEventController()
+    {
+	if( iEngine != NULL )
+		{
+		if( iEngine->Logger() != NULL )
+			{
+			iEngine->Logger()->Log( _L( "CTestEventController::~CTestEventController" ) );
+			}
+		}
+    
+    if( iRequestStatus )
+        {
+        // Must be completed if pending, otherwise  
+        // CTestEventNotifier::DoCancel blocks
+        User::RequestComplete( iRequestStatus, KErrCancel );
+        }
+            
+    iEventCallBacks.ResetAndDestroy();
+    iEventCallBacks.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: CheckEventsL
+
+    Description: Check all events.
+
+    Parameters: None
+
+    Return Values: TInt: Active event commands
+
+    Errors/Exceptions: Leaves if CtlEventL leaves
+                       Leaves if memory allocation fails
+                       Leaves if unset event not found from pending 
+                            state event list 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/  
+TInt CTestEventController::CheckEventsL()
+    {
+    iEngine->Logger()->Log( _L( "CTestEventController::CheckEventsL" ) );
+
+    iActiveEventCmds += CheckClientEventsL();
+    iActiveEventCmds += CheckTestcaseEventsL();
+
+    return iActiveEventCmds;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: CheckClientEventsL
+
+    Description: Check client events.
+
+    Parameters: None
+
+    Return Values: TInt: Request of pending
+
+    Errors/Exceptions: Leaves if CtlEventL leaves
+                       Leaves if memory allocation fails
+                       Leaves if unset event not found from pending 
+                            state event list 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/  
+TInt CTestEventController::CheckClientEventsL()
+    {
+    iEngine->Logger()->Log( _L( "CTestEventController::CheckClientEventsL" ) );
+    TInt reqPending = 0;
+
+    // Check client event requests
+    TInt count = iEngine->ClientEvents().Count();
+    for( TInt index = 0; index < count; index++ )
+        {
+        if( iEngine->ClientEvents()[index]->Name() == iEvent.Name() )
+            {
+            TEventMsg* event = iEngine->ClientEvents()[index]; 
+            if( iEvent.Type() == TEventIf::ESetEvent )
+                {
+                // Set found event 
+                event->Set( iEvent.EventType() );
+                }
+            else if( iEvent.Type() == TEventIf::EUnsetEvent )
+                {
+                // Unset found event
+                // Create callback for change notifier
+                TCallBack callBack( EventCallBack, this );
+                CCallBack* eventCallBack = new (ELeave)CCallBack( callBack,
+                                                    CActive::EPriorityHigh );
+                CleanupStack::PushL( eventCallBack );
+                
+                event->Unset( eventCallBack->Status() ); 
+                reqPending++;
+                eventCallBack->SetActive();
+                User::LeaveIfError( iEventCallBacks.Append( eventCallBack ) );
+                CleanupStack::Pop( eventCallBack );
+                }       
+            break;
+            }
+        }
+
+    return reqPending;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: CheckTestcaseEventsL
+
+    Description: Check testcase events.
+
+    Parameters: None
+
+    Return Values: TInt: Request of pending
+
+    Errors/Exceptions: Leaves if CtlEventL leaves
+                       Leaves if memory allocation fails
+                       Leaves if unset event not found from pending 
+                            state event list 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEventController::CheckTestcaseEventsL()
+    {
+    TInt reqPending = 0;
+    TCallBack callBack( EventCallBack, this );
+    CCallBack* eventCallBack = NULL;
+
+    // Then check testcase event requests
+    TInt count = iEngine->TestCaseArray().Count();
+    eventCallBack = new (ELeave)CCallBack( callBack, 
+                                           CActive::EPriorityHigh );
+    CleanupStack::PushL( eventCallBack );
+    for ( TInt index = 0; index < count; index++ )
+        {
+
+        if( iEngine->TestCaseArray()[index]->CheckCtlEvent( iEvent ))
+            {
+            reqPending++;
+            eventCallBack->SetActive();
+            iEngine->TestCaseArray()[index]->CtlEvent( iEvent, 
+                                                          eventCallBack->Status() );                                                          
+            User::LeaveIfError( iEventCallBacks.Append( eventCallBack ) );
+            CleanupStack::Pop( eventCallBack );
+            eventCallBack = new (ELeave)CCallBack( callBack, 
+                                                   CActive::EPriorityHigh );
+            CleanupStack::PushL( eventCallBack );    
+            }
+        }
+    CleanupStack::PopAndDestroy( eventCallBack );
+    return reqPending;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: EventComplete
+
+    Description: EventComplete handles completed event requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEventController::EventComplete()
+    {
+    iEngine->Logger()->Log( _L( "CTestEventController::EventComplete" ));
+
+    iActiveEventCmds--;
+    
+    if( iActiveEventCmds == 0 )
+        {
+        TInt error = KErrNone;
+        TInt count = iEventCallBacks.Count();
+        for( TInt i=0; i<count; i++ )
+            {
+            if( iEventCallBacks[i]->iStatus.Int() != KErrNone )
+                {
+                error = iEventCallBacks[i]->iStatus.Int();
+                break;
+                }
+            }
+        iEventCallBacks.ResetAndDestroy();
+            
+        // All event commands are completed
+        if( iRequestStatus )
+            {
+            User::RequestComplete( iRequestStatus, error );
+            }
+        else
+            {
+            // No request was pending, complete immediately
+            iMessage.Complete( error );
+            }
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEventController
+
+    Method: EventCallBack
+
+    Description: static EventCallBack handles completed event requests.
+
+    Parameters: TAny* aTestEventController: in: Test event controller
+
+    Return Values: TInt: returns KErrNone
+
+    Errors/Exceptions:None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEventController::EventCallBack( TAny* aTestEventController )
+    {
+    CTestEventController* controller =
+                                (CTestEventController*) aTestEventController;
+    controller->EventComplete();
+    return KErrNone;
+
+    }
+    
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestRemoteCmdNotifier class member
+    functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestProgressNotifier
+
+    Method: CTestRemoteCmdNotifier
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestRemoteCmdNotifier::CTestRemoteCmdNotifier( CTestEngine* aEngine,
+                             RTestExecution aTestExecution,
+                             CTestCaseController* aTestCaseController,
+                             CAtsLogger& aAtsLogger ) :
+    CActive( CActive::EPriorityStandard ),
+    iEngine( aEngine ),
+    iTestExecution( aTestExecution ),
+    iState( ETestProgressIdle ),
+    iRemoteTypePckg( iRemoteType ),
+    iMsgSizePckg( iMsgSize ),
+    iTestCaseController( aTestCaseController ),
+    iAtsLogger( aAtsLogger )
+    {
+    CActiveScheduler::Add( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestRemoteCmdNotifier::ConstructL( )
+    {
+    __TRACE( KVerbose, ( _L( "CTestRemoteCmdNotifier::ConstructL" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+
+    Return Values: CTestRemoteCmdNotifier* : pointer to created object
+
+    Errors/Exceptions: Leaves if construction of CTestRemoteCmdNotifier fails
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestRemoteCmdNotifier* CTestRemoteCmdNotifier::NewL( CTestEngine* aEngine,
+                             RTestExecution aTestExecution,
+                             CTestCaseController* aTestCaseController,
+                             CAtsLogger& aAtsLogger )
+    {
+    CTestRemoteCmdNotifier* self = new ( ELeave ) CTestRemoteCmdNotifier(
+        aEngine, aTestExecution, aTestCaseController, aAtsLogger );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: ~CTestRemoteCmdNotifier
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestRemoteCmdNotifier::~CTestRemoteCmdNotifier()
+    {
+    __TRACE( KVerbose, ( _L( "CTestRemoteCmdNotifier::~CTestRemoteCmdNotifier" ) ) );
+    Cancel();
+
+    delete iReceivedMsg;
+    iReceivedMsg = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: EnableReceive
+
+    Description: Prepare to start active object
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestRemoteCmdNotifier::EnableReceive( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestRemoteCmdNotifier::EnableReceive" ) ) );
+    
+    iMessage = aMessage;
+    iMessageAvail = ETrue;
+    
+    Start( aMessage );
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: GetReceivedMsg
+
+    Description: Read received message
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestRemoteCmdNotifier::GetReceivedMsg( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestRemoteCmdNotifier::GetReceivedMsg" ) ) );
+    
+    TInt ret = KErrNone;
+    if( iReceivedMsg )
+        {
+        TRAP( ret, aMessage.WriteL( 0, iReceivedMsg->Des() ) );
+        delete iReceivedMsg;
+        iReceivedMsg = 0;
+        }
+    else
+        {
+        ret = KErrNotFound;
+        }
+        
+    // Complete message
+    aMessage.Complete( ret );
+                
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: StartL
+
+    Description: Start active object
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestRemoteCmdNotifier::Start( const RMessage2& aMessage )
+    {
+    // Check that this request is not pending!!
+    __ASSERT_ALWAYS( iState != ETestProgressPending,
+                    iEngine->PanicClient( EReqPending, aMessage ) );
+    iState = ETestProgressPending;
+    SetActive();
+    // Start first phase of the remote command's operations
+    iTestExecution.NotifyRemoteCmd( iRemoteTypePckg, 
+                                    iMsgSizePckg, 
+                                    iStatus );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: CancelReq
+
+    Description: Cancel the request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestRemoteCmdNotifier::CancelReq()
+    {
+    if(iMessageAvail)
+        {
+        iMessageAvail = EFalse;
+        iMessage.Complete( KErrCancel );
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if WriteL leaves
+                       Leaves if iStatus is not KErrNone or KErrEof
+                       Leaves are handled in RunError method
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestRemoteCmdNotifier::RunL()
+    {
+    __TRACE( KVerbose, ( _L( "CTestRemoteCmdNotifier::StartL: iStatus=[%d]" ), iStatus.Int() ) );
+
+    User::LeaveIfError( iStatus.Int() );
+    
+    iState = ETestProgressCompleted;
+
+    TInt ret( 0 );
+    switch( iRemoteType )
+        {
+        case EStifCmdSend:             // "Sending"
+            {
+            if( ( iMessageAvail == EFalse ) ||
+                ( iMsgSize <= 0 ) )
+                { 
+                User::Leave( KErrGeneral );
+                }
+            // Delete previous if exists
+            delete iReceivedMsg;
+            iReceivedMsg = 0;
+            // Create new buffer 
+            iReceivedMsg = HBufC8::NewL( iMsgSize );
+
+            // Start second phase of the remote command's operations,
+            // buffer is read with GetReceivedMsg
+            TPtr8 tmp = iReceivedMsg->Des();
+            ret = iTestExecution.ReadRemoteCmdInfo( tmp, iRemoteType );
+
+            // Writing received info to UI
+            iMessage.WriteL( 0, iRemoteTypePckg );
+            iMessage.WriteL( 1, iMsgSizePckg );
+            
+            // Complete message
+            iMessage.Complete( ret );
+            iMessageAvail = EFalse;
+
+            break;
+            }
+        case EStifCmdReboot:           // "Sending"
+            {
+            TRebootParams remoteType;
+            TRebootParamsPckg remoteTypePckg( remoteType );
+            // Start second phase of the remote command's operations
+            ret = iTestExecution.ReadRemoteCmdInfo( remoteTypePckg, iRemoteType );
+            __TRACE( KInit, ( CStifLogger::ERed, _L("REBOOT PHONE (type %d)" ), remoteType.aType ) );
+
+            if( remoteType.aType == CTestModuleIf::EKernelReset )
+                {
+                __TRACE( KInit, ( _L("Rebooting with kernel reset" ) ) );
+                __TRACE( KInit, ( _L("Kernel reset implementation is ongoing, trying different reset..." ) ) );
+                }
+
+#ifdef __WINS__
+            __TRACE( KInit, ( _L("Rebooting with Process kill(WINS)" ) ) );
+            RProcess thisProcess;
+            //thisProcess.SetSystem( ETrue );
+            thisProcess.Kill( KErrNone );
+            thisProcess.Close();
+#else // Hardware specific
+            TInt r( KErrNone );
+            __TRACE( KInit, ( _L("Rebooting with reset module(HW)" ) ) );
+            r = DynamicResetModule( remoteType.aType );
+            if( r != KErrNone )
+                {
+                __TRACE( KInit, ( CStifLogger::EError, _L("This reseting type is failed, trying different reset...")) );
+                }
+#endif // Hardware specific
+
+            // if( !remoteType.aType == CTestModuleIf::EDefaultReset )
+            // Note this change needs an error code tranceiver between reboot
+            // module and engine. (If reboot fails return error code, if reboot
+            // is default then kill process else error code returning)
+
+            // Do process kill as a last option
+            __TRACE( KInit, ( _L("Rebooting with Process kill" ) ) );
+           
+            RProcess thisProcess2;         
+            thisProcess2.Kill( KErrNone );
+            thisProcess2.Close();
+
+            // If this text is shown in UI something is wrong and this needs some investigation.
+            iEngine->ErrorPrint( 0, _L( "Reboot phone...E.g. disconnect battery!!!" ) );
+            break;
+            }
+        case EStifCmdStoreState:       // "Sending"
+            {
+            if( iMessageAvail == EFalse )
+                { 
+                User::Leave( KErrGeneral );
+                }
+            TRebootStateParams remoteState;
+            TRebootStateParamsPckg remoteStatePckg( remoteState );
+
+            // Start second phase of the remote command's operations
+            ret = iTestExecution.ReadRemoteCmdInfo( remoteStatePckg,
+                                                    iRemoteType );
+
+            // Get test case information(test module, test case file, etc.)
+            TTestInfo testInfo;
+            iTestCaseController->GetTestCaseInfo( testInfo );
+
+            // Write state informations to the file
+            iEngine->WriteRebootParams( testInfo, remoteState.aCode,
+                                        remoteState.aName );
+                                                        
+            // Write ATS loggers buffers to drive
+            iEngine->FlushAtsLogger();
+
+            // Pause test cases that there cannot make e.g. new store state
+            // calls. iCaseNumber is index type value so increment by one to
+            // get current test case.
+            iEngine->PauseAllTestCases();
+            // Resume current test case
+            iTestCaseController->iTestExecution.Resume();
+
+            // Writing received info to UI
+            iMessage.WriteL( 0, iRemoteTypePckg );
+
+            // Complete message
+            iMessage.Complete( ret );
+            iMessageAvail = EFalse;
+            break;
+            }
+        case EStifCmdGetStoredState:   // "Reading, this must be done with two phase"
+            {
+            // Get test case information(test module, test case file, etc.)
+            TTestInfo testInfo;
+            iTestCaseController->GetTestCaseInfo( testInfo );
+
+            TGetRebootStoredParams remoteStoredState;
+            // Read state informations from the file
+            TInt errorCodeToClient = 
+                iEngine->ReadRebootParams( testInfo, 
+                                           remoteStoredState.aName,
+                                           remoteStoredState.aCode );
+
+            TGetRebootStoredParamsPckg remoteStoredPckg( remoteStoredState );
+
+            // Start second phase of the remote command's operations
+            ret = iTestExecution.ReadRemoteCmdInfo( remoteStoredPckg,
+                                                    iRemoteType,
+                                                    errorCodeToClient );
+            
+            Start( iMessage ); // Starts active object
+
+            break;
+            }
+       case EStifCmdMeasurement:   // "Reading, this must be done with two phase"
+            {
+            TGetMeasurementOptions remoteMeasurementOptions;
+            remoteMeasurementOptions.iOptions = iEngine->StifMeasurement();
+
+            TGetMeasurementOptionsPckg remoteMeasurementPckg( remoteMeasurementOptions );
+
+            // Start second phase of the remote command's operations
+            ret = iTestExecution.ReadRemoteCmdInfo( remoteMeasurementPckg,
+                                                    iRemoteType,
+                                                    KErrNone );
+            
+            Start( iMessage ); // Starts active object
+
+            break;
+            }
+
+        case EStifCmdReceive:          // "Reading"
+        default:
+            User::Leave( KErrNotFound );
+            break;
+        }
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestRemoteCmdNotifier::DoCancel()
+    {
+    switch ( iState )
+        {
+        case ETestProgressPending:
+            iTestExecution.CancelAsyncRequest( ETestExecutionNotifyRemoteCmd );
+            //iMessage.Complete( KErrCancel );
+            break;
+        case ETestProgressIdle:
+        case ETestProgressCompleted:
+        default:
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestRemoteCmdNotifier, "CTestRemoteCmdNotifier" );
+            User::Panic( KTestRemoteCmdNotifier, EDoCancelDisorder );
+            break;
+        }
+    iState = ETestProgressIdle;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: RunError
+
+    Description: Handle errors.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestRemoteCmdNotifier::RunError( TInt aError )
+    {
+    // Complete message with error
+    if(iMessageAvail)
+        {
+        iMessageAvail = EFalse;
+        iMessage.Complete( aError );
+        }
+    
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestRemoteCmdNotifier
+
+    Method: ResetL
+
+    Description: Reset HW/WINS. Loads dynamically reset module by name.
+
+    Parameters: CTestModuleIf::TRebootType aResetType: in: Reset type
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestRemoteCmdNotifier::DynamicResetModule( 
+                                        CTestModuleIf::TRebootType aResetType )
+    {
+    __TRACE( KInit, (  _L( "DynamicResetModule()" ) ) );
+    RLibrary resetModule;
+    // Load the module
+    TPtrC dllName;
+    dllName.Set( iEngine->GetDeviceResetDllName() );
+    // Loading should work with and without '.dll' extension.
+    TInt r = resetModule.Load( dllName );
+    if ( r != KErrNone )
+        {
+        __TRACE( KError, ( CStifLogger::EError, _L("Can't initialize reset module[%S], code = %d"), &dllName, r ) );
+        return KErrNotFound;
+        }
+    else
+        {
+        // Print reset module name
+        __TRACE( KInit, (  _L("Loaded reset module[%S]"), &dllName ) );
+        }
+
+    
+
+    // Get pointer to first exported function
+    CTestInterfaceFactory libEntry;
+    libEntry = (CTestInterfaceFactory) resetModule.Lookup( 1 );
+    if ( libEntry == NULL )
+        {
+        // New instance can't be created
+        __TRACE ( KError, ( CStifLogger::EError, _L("Can't initialize reset module, NULL libEntry" ) ) );
+        return KErrNoMemory;
+        }
+    else
+        {
+        __TRACE ( KInit, ( _L("Pointer to 1st exported received")));
+        }
+
+    CStifHWReset* reset;
+    reset = NULL;
+
+    // initialize test module
+    __TRACE ( KVerbose, (_L("Calling 1st exported at 0x%x"), (TUint32) libEntry ));
+    TRAPD ( err, reset =  (*libEntry)() );
+
+     // Handle leave from test module
+    if ( err != KErrNone )
+        {
+        __TRACE (KError, ( CStifLogger::EError, _L("Leave when calling 1st exported function, code %d"), err));
+        return err;
+        }
+    else if ( reset == NULL )     // Handle NULL from test module init
+        {
+        __TRACE (KError, ( CStifLogger::EError, _L("NULL pointer received when constructing test module")));
+        delete reset;
+
+        // Set error codes
+        return KErrNoMemory;
+        }
+    else
+        {
+        __TRACE (KInit, (_L("Entrypoint successfully called, test module instance at 0x%x"), (TUint32)reset ) );
+        }
+
+    // Calls dynamically loaded reset module's method.
+    TInt ret = reset->DoReset( aResetType );
+    if( ret != KErrNone )
+        {
+        __TRACE (KInit, (_L("DynamicResetModule; DoReset fails with error: %d"), ret ) );
+        return ret;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestCommandNotifier class member
+    functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: CTestCommandNotifier
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCommandNotifier::CTestCommandNotifier(CTestEngine* aEngine,
+                                           RTestExecution aTestExecution):
+    CActive(CActive::EPriorityStandard),
+    iEngine(aEngine),
+    iTestExecution(aTestExecution),
+    iCommandPckg(iCommand)
+    {
+    CActiveScheduler::Add(this);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCommandNotifier::ConstructL( )
+    {
+    __TRACE(KVerbose, (_L("CTestCommandNotifier::ConstructL")));
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+                RTestExecution aTestExecution: in: Handle to RTestExecution
+
+    Return Values: CTestCommandNotifier* : pointer to created object
+
+    Errors/Exceptions: Leaves if construction of CTestCommandNotifier fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCommandNotifier* CTestCommandNotifier::NewL(CTestEngine* aEngine,
+                                                 RTestExecution aTestExecution)
+    {
+    CTestCommandNotifier* self = new (ELeave) CTestCommandNotifier(aEngine, aTestExecution);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: ~CTestCommandNotifier
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCommandNotifier::~CTestCommandNotifier()
+    {
+    __TRACE(KVerbose, (_L("CTestEventNotifier::~CTestEventNotifier")));
+    Cancel();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: StartL
+
+    Description: Start active object
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCommandNotifier::Start()
+    {
+    __TRACE(KVerbose, (_L("CTestEventNotifier::StartL")));
+
+    iTestExecution.NotifyCommand2(iCommandPckg, iParamsPckg, iStatus, KErrNone);
+    SetActive();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone
+                       Leaves if iState is not ETestEventPending
+                       Leaves if some leaving method called here leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCommandNotifier::RunL()
+    {
+    __TRACE(KVerbose, (_L("CTestCommandNotifier::RunL: iStatus=[%d]"), iStatus.Int()));
+
+    User::LeaveIfError(iStatus.Int());
+
+    iEngine->ExecuteCommandL(iCommand, iParamsPckg);
+
+    // Set request again
+    Start();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCommandNotifier::DoCancel()
+    {
+    __TRACE(KVerbose, (_L( "CTestEventNotifier::DoCancel")));
+
+    iTestExecution.CancelAsyncRequest(ETestExecutionNotifyCommand);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCommandNotifier
+
+    Method: RunError
+
+    Description: Handle errors.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCommandNotifier::RunError(TInt aError)
+    {
+    __TRACE(KError, (CStifLogger::ERed, _L("CTestCommandNotifier::RunError %d"), aError));
+    return KErrNone;
+    }
+
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/TestEngine.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,6214 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestEngineServer class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+#include <f32file.h>
+#include "TestEngine.h"
+#include "TestEngineClient.h"
+#include "TestEngineCommon.h"
+#include <stifinternal/TestServerClient.h>
+#include "TestModuleController.h"
+#include "TestCaseController.h"
+#include "TestReport.h"
+#include "Logging.h"
+#include "SettingServerClient.h"
+//--PYTHON-- begin
+#include "StifPython.h"
+#include "StifPythonFunEng.h"
+//--PYTHON-- end
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+_LIT( KTestModule, "TestModule=" );
+_LIT( KTestCaseFile, "TestCaseFile=" );
+_LIT( KTestCaseNumber, "TestCaseNumber=" );
+_LIT( KTestCaseTitle, "TestCaseTitle=" );
+_LIT( KStateCode, "StateCode=" );
+_LIT( KStateName, "StateName=" );
+    
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+struct TThreadStartTestEngine
+    {   
+    RThread    iEngineThread; // The server thread
+    RSemaphore iStarted;      // Startup syncronisation semaphore   
+    };
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+   
+    Function: ErrorPrint
+
+    Description: ErrorPrint
+
+    Parameters: const TInt aPriority: in: Priority of error
+                TPtrC aError: in: Error description
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ErrorPrint( const TInt aPriority, 
+                              TPtrC aError )
+    {
+    TErrorNotification error;
+    TErrorNotificationPckg errorPckg ( error );
+
+    error.iModule = _L("TestEngine");
+    error.iPriority = aPriority;
+    error.iText = aError;
+
+    ErrorPrint( errorPckg );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: ErrorPrint
+
+    Description: Sends error notification
+
+    Parameters: TErrorNotificationPckg aError: in: Error
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ErrorPrint( TErrorNotificationPckg aError )
+    {
+    // Add new item to end of queue
+     if ( iErrorQueue.Append ( aError() ) != KErrNone )
+            {
+            RDebug::Print (_L("Error message lost"));
+            return;
+            }
+
+    ProcessErrorQueue();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: ProcessErrorQueue
+
+    Description: Process error queue
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ProcessErrorQueue()
+    {
+    // If message is available, complete first item from queue
+    if ( iErrorMessageAvailable )
+        {
+        
+        if ( iErrorQueue.Count() > 0 )
+            {
+            TErrorNotification err = iErrorQueue[0];
+            TErrorNotificationPckg errPckg(err);
+            iErrorQueue.Remove(0);
+        
+        	TInt r( KErrNone );
+        
+            TRAP( r, iErrorMessage.WriteL( 0, errPckg ) );
+
+            // Do not handle errors
+
+            iErrorMessageAvailable = EFalse;
+            iErrorMessage.Complete( KErrNone );
+            }
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+   
+    Function: LeaveIfErrorWithNotify
+
+    Description: If error leave with notify
+
+    Parameters: TInt aCode: in: Error code
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::LeaveIfErrorWithNotify( TInt aCode )
+      {
+      LeaveIfErrorWithNotify ( aCode, _L("Check testengine log") );
+
+      }
+
+/*
+-------------------------------------------------------------------------------
+   
+    Function: LeaveIfErrorWithNotify
+
+    Description: If error leave with notify
+
+    Parameters: TInt aCode: in: Error code
+                const TDesC& aText: in: Descriptive text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::LeaveIfErrorWithNotify( TInt aCode,
+                                          const TDesC& aText )
+    {
+    if ( aCode != KErrNone )
+        {
+           LeaveWithNotifyL ( aCode, aText );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Function: LeaveWithNotifyL
+
+    Description: Leave with notify
+
+    Parameters: TInt aCode: in: Error code
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::LeaveWithNotifyL( TInt aCode )
+    {
+    LeaveWithNotifyL ( aCode, _L("Check testengine log") );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Function: LeaveWithNotifyL
+
+    Description: Leave with notify
+
+    Parameters: TInt aCode: in: Error code
+                const TDesC& aText: in: Descriptive text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::LeaveWithNotifyL( TInt aCode,
+                                   const TDesC& aText )
+    {
+    ErrorPrint ( 0, aText );
+    User::Leave ( aCode );
+
+    }
+
+#define LOGGER iLogger
+
+/*
+-------------------------------------------------------------------------------
+
+    Function: ThreadFunction
+
+    Description: The thread function, where Test Engine lives in.
+
+    Parameters: TAny* aStarted: in: Start info
+
+    Return Values: TInt: Returns always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngineServer::ThreadFunction( TAny* aStarted )
+    {
+//    __UHEAP_MARK;
+
+    // Create cleanup stack
+    CTrapCleanup* cleanup = CTrapCleanup::New();
+    __ASSERT_ALWAYS( cleanup, PanicServer( ECreateTrapCleanup ) );
+
+    // Get start-up information
+    TThreadStartTestEngine* startInfo = ( TThreadStartTestEngine* ) aStarted;
+    __ASSERT_ALWAYS( startInfo, PanicServer( ENoStartupInformation ) );
+
+    // Construct and install active scheduler
+    CActiveScheduler* scheduler = new CActiveScheduler;
+    __ASSERT_ALWAYS( scheduler, PanicServer( EMainSchedulerError ) );
+    CActiveScheduler::Install( scheduler );
+
+    // Construct server, an active object
+    CTestEngineServer* server = NULL;
+    TRAPD( err, server = CTestEngineServer::NewL() );
+    __ASSERT_ALWAYS( !err, PanicServer( ESvrCreateServer ) );
+
+    // Inform that we are up and running
+    startInfo->iStarted.Signal();
+
+    // Global mutex(handling according to the name)
+    RMutex startupMutex;
+    // Try to create global mutex, CREATE
+    TInt ret = startupMutex.CreateGlobal( KStifTestServerStartupMutex );
+    if( ret != KErrNone )
+        {
+        // Mutex already create, OPEN
+        ret = startupMutex.OpenGlobal( KStifTestServerStartupMutex );
+        }
+    if( ret != KErrNone )
+        {
+        // Not able to create or open mutex
+        return ret;
+        }
+
+    // Start handling requests
+    CActiveScheduler::Start();
+
+    startupMutex.Close();
+
+    // Should come here after RTestEngineServer is closed
+    delete server;
+    delete scheduler;
+    delete cleanup;
+
+//    __UHEAP_MARKEND;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: CTestEngineServer
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEngineServer::CTestEngineServer() :
+    CServer2( CTestEngineServer::ETestEngineServerPriority ),
+    iSessionCount( 0 )
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if CObjectConIx::NewL leaves
+                       Leaves if CStifLogger::NewL leaves
+                       Leaves if StartL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngineServer::ConstructL()
+    {
+    // Create report setting
+    iTestReportSettings = CTestReportSettings::NewL();
+    // Create container
+    iContainerIndex = CObjectConIx::NewL();
+
+    // Create logger, in Wins use HTML in HW default logger
+    TLoggerSettings loggerSettings;
+
+    // Directory must create by hand if test engine log wanted
+    loggerSettings.iCreateLogDirectories = EFalse;
+
+    loggerSettings.iOverwrite = ETrue;
+    loggerSettings.iTimeStamp = ETrue;
+    loggerSettings.iLineBreak = ETrue;
+    loggerSettings.iEventRanking = EFalse;
+    loggerSettings.iThreadId = EFalse;
+    loggerSettings.iHardwareFormat = CStifLogger::ETxt;
+#ifndef FORCE_STIF_INTERNAL_LOGGING_TO_RDEBUG
+    loggerSettings.iEmulatorFormat = CStifLogger::EHtml;
+    loggerSettings.iEmulatorOutput = CStifLogger::EFile;
+    loggerSettings.iHardwareOutput = CStifLogger::EFile;
+#else
+    RDebug::Print( _L( "STIF Test Engine logging forced to RDebug" ) );
+    loggerSettings.iEmulatorFormat = CStifLogger::ETxt;
+    loggerSettings.iEmulatorOutput = CStifLogger::ERDebug;
+    loggerSettings.iHardwareOutput = CStifLogger::ERDebug;
+#endif
+    loggerSettings.iUnicode = EFalse;
+    loggerSettings.iAddTestCaseTitle = EFalse;
+
+    iLogger = CStifLogger::NewL( _L( "C:\\logs\\testframework\\testengine\\"),
+                                    _L( "testengine" ),
+                                    loggerSettings );
+    // Start Server
+    StartL( KTestEngineName );
+
+    __TRACE(KVerbose, (_L( "CTestEngineServer::ConstructL: Server Created" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: None
+
+    Return Values: CTestEngineServer* : pointer to CTestEngineServer object
+
+    Errors/Exceptions: Leaves if construction of CBufferArray fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEngineServer* CTestEngineServer::NewL()
+    {
+    CTestEngineServer* self = new ( ELeave ) CTestEngineServer();
+    CleanupStack::PushL( self );      
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: ~CTestEngineServer
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEngineServer::~CTestEngineServer()
+    {
+    delete iContainerIndex; 
+
+    __TRACE(KAlways, ( _L( "---------------- Log Ended ----------------" ) ) );
+    delete iLogger;
+
+    delete iTestReportSettings;
+    iTestReportSettings = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: NewContainerL
+
+    Description: Create new container
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called CreateL method leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CObjectCon* CTestEngineServer::NewContainerL()
+    {
+    CObjectCon* container = iContainerIndex->CreateL();
+
+    iSessionCount++;
+
+    return container;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: DeleteContainer
+
+    Description: Deletes a container
+
+    Parameters: CObjectCon* 
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngineServer::DeleteContainer( CObjectCon* aContainer )
+    {
+    iContainerIndex->Remove( aContainer );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: SessionClosed
+
+    Description: Inform Server that session is closed.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngineServer::SessionClosed()
+    {
+    // Decrease session count
+    iSessionCount--;
+
+    // Check if last session is closed
+    if ( iSessionCount <= 0 )
+        {
+        // Stop the active scheduler
+        // Execution will continue in ThreadFunction()
+        CActiveScheduler::Stop();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: NewSessionL
+
+    Description: Create a new client session for this server.
+
+    Parameters: const TVersion& aVersion: in: Client side version number
+
+    Return Values: CSharableSession* : pointer to CSharableSession object
+
+    Errors/Exceptions: Leaves if given version is incorrect
+                       Leaves if CTestEngine::NewL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSession2* CTestEngineServer::NewSessionL( const TVersion &aVersion,
+                                         const RMessage2& /*aMessage*/ ) const
+    {
+    // Check that version is ok
+    TVersion v( KTestEngineMajorVersionNumber,
+                KTestEngineMinorVersionNumber,
+                KTestEngineBuildVersionNumber );
+    if ( !User::QueryVersionSupported( v, aVersion ) )
+        {
+        User::Leave( KErrNotSupported );
+        }
+
+    return CTestEngine::NewL( ( CTestEngineServer* ) this );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: PanicServer
+
+    Description: Panic the server
+
+    Parameters: TTestEnginePanic aPanic: in: Panic number
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngineServer::PanicServer( TTestEnginePanic aPanic )
+    {
+    _LIT( KTestServer, "CTestEngineServer" );
+    User::Panic( KTestServer, aPanic );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineServer
+
+    Method: Logger
+
+    Description: Return the pointer to iLogger.
+
+    Parameters: None
+
+    Return Values: CStifLogger*: Pointer to StifLogger
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifLogger* CTestEngineServer::Logger()
+    {
+    return iLogger;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestEngine class member functions.
+
+-------------------------------------------------------------------------------
+*/
+#undef LOGGER
+#define LOGGER Logger()
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: CTestEngine
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: RThread& aClient: in: Client's thread
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+    CTestEngine::CTestEngine() :
+        CSession2(),
+    iReportMode( CTestReport::ETestReportFull ),
+    iReportOutput( CTestReport::ETestReportNone ),
+    iEnumerateModuleCount( 0 ),
+    iIsTestReportGenerated( EFalse ),
+    iDisableMeasurement( EEnableAll)
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: CTestEngineServer* aServer: in: Pointer to CTestEngineServer
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ConstructL( CTestEngineServer* aServer )
+    {
+    // Log version info
+    TInt majorV;
+    TInt minorV;
+    TInt buildV;
+    TBuf<30> relDate;
+    TStifUtil::STIFVersion(majorV, minorV, buildV, relDate);
+    RDebug::Print(_L( "STIF startup... version %d.%d.%d (%S)"), majorV, minorV, buildV, &relDate);
+
+
+    // Second-phase construct base class
+    //CSession2::CreateL();
+
+    iTestEngineServer = aServer;
+
+    // Create new object index
+    iTestEngineSubSessions = CObjectIx::NewL();
+
+    // Create new object index
+    iTestCases = CObjectIx::NewL();
+    
+    // Initialize the object container from Server
+    iContainer = iTestEngineServer->NewContainerL();
+
+    __TRACE(KInit, (_L( "STIF startup... version %d.%d.%d (%S)"), majorV, minorV, buildV, &relDate));
+    __TRACE( KInit, ( _L( "CTestEngine::ConstructL: Test Engine Created" ) ) );
+
+   
+    RFs iFs;
+    User::LeaveIfError( iFs.Connect() );
+    _LIT(KCSteve,"C:\\Testframework\\");
+    iFs.MkDirAll(KCSteve);
+      
+    iFs.Close();
+    
+    iRebootDefaultPath.Set( _L( "C:\\TestFramework\\" ) );
+    iRebootDefaultFilename.Set( _L( "Reboot.txt" ) );
+
+    TPtrC dllName;
+    dllName.Set( _L( "StifHWResetStub.dll" ) );
+    iDeviceResetDllName = dllName.AllocL();
+
+    iDefaultTimeout = 0;
+    iUITestingSupport = EFalse;
+    iSeparateProcesses = EFalse;
+    
+    iIndexTestModuleControllers = 1;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: RThread& aClient : Client's thread
+                CTestEngineServer* aServer : Pointer to CTestEngineServer
+
+    Return Values: CTestEngine* : pointer to CTestEngine object
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEngine* CTestEngine::NewL( CTestEngineServer* aServer )
+    {
+    CTestEngine* self = new ( ELeave ) CTestEngine();
+    CleanupStack::PushL( self );
+    self->ConstructL( aServer );
+    CleanupStack::Pop();
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: CloseSession
+
+    Description: Close client server session to Test Engine
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::CloseSession() 
+    {
+    __TRACE( KInit, ( _L( "CTestEngine::CloseSession" ) ) );
+
+    iErrorQueue.Close();
+
+    // Delete test report
+    delete iTestReport;
+    iTestReport = NULL;
+
+    // Delete device reset module's DLL name
+    delete iDeviceResetDllName;
+    iDeviceResetDllName = NULL;
+
+    // Delete state events
+    iStateEvents.ResetAndDestroy();
+    iStateEvents.Close();
+
+    //Delete Client events
+    iClientEvents.ResetAndDestroy();
+    iClientEvents.Close();
+
+    // Remove contents of iTestCases
+    if ( iTestCases )
+        {
+        TInt handle;
+        CObject* object = NULL;
+        TInt count = iTestCases->Count();
+
+        for ( TInt i = 0; i < count; i++ )
+            {
+            object = iTestCases->operator[](i);
+            if ( object )
+                {
+                handle = iTestCases->At( object );
+                iTestCases->Remove( handle );       
+                }
+            }
+
+        delete iTestCases;
+        iTestCases = NULL;
+        }
+    
+    iTestCaseArray.Close();    
+    delete iTestEngineSubSessions;
+    iTestEngineSubSessions = NULL;
+
+    // Delete the object container
+    // This provides unique ids for the objects of this session
+    iTestEngineServer->DeleteContainer( iContainer );
+
+    // Inform server that session is closed
+    iTestEngineServer->SessionClosed();
+
+    delete iIniFile;
+    iIniFile = NULL;
+
+    delete iRebootPath;
+    iRebootPath = NULL;
+
+    delete iRebootFilename;
+    iRebootFilename = NULL;
+
+    delete iRebootParams;
+    iRebootParams = 0;
+
+    __TRACE(KVerbose, ( _L( "CTestEngine::CloseSession finished" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: CountResources
+
+    Description: Resource counding
+
+    Parameters: None
+
+    Return Values: TInt Resource count
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::CountResources()
+    {
+    return iResourceCount;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: NumResources
+
+    Description: Get resources, writes to Message()
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::NumResources( const RMessage2& aMessage )
+    {
+
+    TInt ret( 0 );
+
+    TPckgBuf<TInt> countPckg( iResourceCount );
+
+    TRAP( ret, aMessage.WriteL( 0, countPckg ) );
+
+    if ( ret != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        }
+
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: PanicClient
+
+    Description: Panic the client
+
+    Parameters: TTestEnginePanic aPanic: in: Panic number
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::PanicClient( TTestEnginePanic aPanic,
+                                const RMessage2& aMessage ) const
+    {
+    iTestEngineServer->Logger()->Log( CStifLogger::ERed, _L( "CTestEngine::PanicClient [%d]" ), aPanic );
+
+    _LIT( KTestEngine, "CTestEngine" );
+
+    aMessage.Panic( KTestEngine, aPanic );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ServiceL
+
+    Description: Message handling method that calls trapped DispatchMessageL
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Error from DispatchMessageL is trapped and handled
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ServiceL( const RMessage2& aMessage )
+    {
+    TRAPD( ret, DispatchMessageL( aMessage ) );
+    if ( ret != KErrNone )
+        {
+         __TRACE(KError, ( CStifLogger::ERed, _L( "CTestEngine::DispatchMessageL Function=[%d], left with [%d]" ),
+                                                aMessage.Function(), ret ) );
+        if( ret == KErrNoMemory )
+            {
+            __TRACE( KError, ( CStifLogger::ERed, _L( "No memory available. Some possibility to do: 1. Reduce test case count. 2. Increase StifTestEngine's heap size." ) ) );
+            }
+        aMessage.Complete( ret );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: DispatchMessageL
+
+    Description: Actual message handling
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::DispatchMessageL( const RMessage2& aMessage )
+    {
+    iComplete = ETrue;
+    iReturn = KErrNone;
+
+    switch ( aMessage.Function() )
+        {
+        case ETestEngineServerCloseSession:
+            {
+            if ( !iIsTestReportGenerated  && iTestReport )
+                {
+                iTestReport->GenerateReportL();
+                iIsTestReportGenerated = ETrue;
+                }               
+            CloseSession();
+            break;
+            }
+        case ETestEngineCreateSubSession:
+            {
+            InitEngineL( aMessage );
+            break;
+            }
+        case ETestEngineCloseSubSession:
+            {
+            CloseTestEngineL( aMessage.Int3() );
+            break;
+            }
+        case ETestEngineSetAttribute:
+            {
+            SetAttributeL( aMessage );
+            break;
+            }
+
+        case ETestEngineAddTestModule:
+            {
+            AddTestModuleL( aMessage );
+            break;
+            }
+        case ETestEngineRemoveTestModule:
+            {
+            iReturn = RemoveTestModuleL( aMessage );
+            break;
+            }
+        case ETestEngineAddConfigFile:
+            {
+            AddConfigFileL( aMessage );
+            break;
+            }
+        case ETestEngineRemoveConfigFile:
+            {
+            RemoveConfigFileL( aMessage );
+            break;
+            }
+        case ETestEngineEnumerateTestCases:
+            {
+            EnumerateTestCasesL( aMessage );
+            break;
+            }
+        case ETestEngineGetTestCases:
+            {
+            GetTestCasesL( aMessage );
+            break;
+            }
+        case ETestEngineCancelAsyncRequest:
+            {
+            CancelAsyncRequest( aMessage );
+            break;
+            }
+        case ETestEngineEvent:
+            {
+            EventControlL( aMessage );
+            iComplete = EFalse;
+            break;
+            }
+        case ETestEngineErrorNotification:
+            {
+            HandleErrorNotificationL( aMessage );
+            iComplete = EFalse;
+            break;
+            }
+        case ETestEngineLoggerSettings:
+            {
+            LoggerSettings( aMessage );
+            break;
+            }
+        case ETestEngineCloseLoggerSettings:
+            {
+            CloseLoggerSettings();
+            break;
+            }
+        case ETestEngineReportTestCase:
+            {
+            iReturn = AddTestCaseToTestReport(aMessage);
+            break;
+            }
+        // Subsession specific functions
+        case ETestCaseCreateSubSession:
+            {
+            NewTestCaseL( aMessage );
+            break;
+            }
+        case ETestCaseCloseSubSession:
+            {
+            DeleteTestCase( aMessage.Int3() );
+            break;
+            }
+        case ETestCaseRunTestCase:
+            {
+            TestCaseByHandle( aMessage.Int3(), aMessage )->RunTestCaseL( aMessage );
+            iComplete = EFalse;
+            break;
+            }
+        case ETestCasePause:
+            {
+            iReturn = TestCaseByHandle( aMessage.Int3(), aMessage )->Pause();
+            break;
+            }
+        case ETestCaseResume:
+            {
+            iReturn = TestCaseByHandle( aMessage.Int3(), aMessage )->Resume();
+            break;
+            }
+        case ETestCaseNotifyProgress:
+            {
+            TestCaseByHandle( aMessage.Int3(), aMessage )->NotifyProgressL( aMessage );
+            iComplete = EFalse;
+            break;
+            }
+        case ETestCaseNotifyRemoteType:
+            {
+            TestCaseByHandle( aMessage.Int3(), aMessage )->NotifyRemoteTypeL( aMessage );
+            iComplete = EFalse;
+            break;
+            }
+        case ETestCaseNotifyRemoteMsg:
+            {
+            TestCaseByHandle( aMessage.Int3(), aMessage )->NotifyRemoteMsgL( aMessage );
+            iComplete = EFalse;
+            break;
+            }
+        case ETestCaseCancelAsyncRequest:
+            {
+            TestCaseByHandle( 
+                aMessage.Int3(), aMessage )->CancelAsyncRequest( aMessage );
+            break;
+            }
+        default:
+            {
+            User::Leave( KErrNotSupported );
+            break;
+            }
+        }
+    
+    if ( iComplete )
+        {
+        aMessage.Complete( iReturn );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: InitTestReportAndLoggerVarL
+
+    Description: Initialize Test report and Logger's overwrite parameters
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::InitTestReportAndLoggerVarL()
+    {
+    // Test report settings initialization
+    iTestEngineServer->iTestReportSettings->iCreateTestReport = ETrue;
+    _LIT( path, "C:\\LOGS\\TestFramework\\");
+    _LIT( name, "TestReport");
+    delete iTestEngineServer->iTestReportSettings->iPath;
+    iTestEngineServer->iTestReportSettings->iPath = NULL;
+    iTestEngineServer->iTestReportSettings->iPath = path().AllocL();
+    delete iTestEngineServer->iTestReportSettings->iName;
+    iTestEngineServer->iTestReportSettings->iName = NULL;
+    iTestEngineServer->iTestReportSettings->iName = name().AllocL();
+    iTestEngineServer->iTestReportSettings->iFormat = CStifLogger::ETxt;
+    iTestEngineServer->iTestReportSettings->iOutput = CStifLogger::EFile;
+    iTestEngineServer->iTestReportSettings->iOverwrite = ETrue;
+
+    // Initializations to indicator is setting in use
+    iTestEngineServer->iLoggerSettings.iIsDefined.iCreateLogDir = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iPath = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iHwPath = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iFormat = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iHwFormat = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iOutput = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iHwOutput = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iOverwrite = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iLineBreak = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iTimeStamp = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iEventRanking = EFalse;
+    iTestEngineServer->iLoggerSettings.iIsDefined.iThreadId = EFalse;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: InitEngineL
+
+    Description: Init the test engine
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::InitEngineL( const RMessage2& aMessage )
+    {
+  
+    // Parse reboot file 
+    ParseRebootParamsL();
+
+    TName iniFileName;
+
+    // Read ini file name from aMessage
+    aMessage.ReadL( 0, iniFileName );
+    TStifUtil::CorrectFilePathL( iniFileName );
+
+    iIniFile = iniFileName.AllocL();
+
+    // HBufC to TPtrC
+    TPtrC iniFile( iIniFile->Des() );
+
+    __TRACE( KInit, ( CStifLogger::EBold, _L( "CTestEngine::InitEngineL\t iIniFile=[%S]" ), iIniFile ) );
+
+    // Connect to the Setting server and open handle(Handle will close when
+    // closing TestEngine).
+    TInt ret = iSettingServer.Connect();
+    if ( ret != KErrNone )
+        {
+        User::Leave( ret );
+        }
+
+    InitTestReportAndLoggerVarL();
+
+    if ( iniFile.Length() > 0 )
+        {
+        Logger()->WriteDelimiter();
+        __TRACE( KInit,( _L( "Starting to parse initialization file" ) ) );
+
+        // Set initialization file information to Setting server's side.
+        ret = iSettingServer.SetIniFileInformation( iniFileName );
+        if ( ret != KErrNone )
+            {
+            User::Leave( ret );
+            }
+        // Struct to Logger settigs.
+        TLoggerSettings loggerSettings; 
+        // Parse Logger defaults from STIF initialization file.
+        ret = iSettingServer.ReadLoggerSettingsFromIniFile( loggerSettings );
+        if ( ret != KErrNone )
+            {
+            User::Leave( ret );
+            }
+
+        // Create parser for parsing ini file
+        CStifParser* parser = NULL;
+        TRAPD( r, parser = CStifParser::NewL( _L(""), iniFile ) );
+        if ( r != KErrNone )
+            {
+            __TRACE( KError,( CStifLogger::ERed, _L( "Can't open ini-file [%S], code %d" ), &iniFile, r ) );
+            LeaveWithNotifyL(r);
+            }
+
+        CleanupStack::PushL( parser );
+
+        CSTIFTestFrameworkSettings* settings = NULL;
+        TRAPD( settings_ret, settings = CSTIFTestFrameworkSettings::NewL() );
+        CleanupStack::PushL( settings );
+        if ( settings_ret != KErrNone )
+            {
+            __TRACE( KError,( CStifLogger::ERed, _L( "CSTIFTestFrameworkSettings class object creation fails") ) );
+            LeaveWithNotifyL( settings_ret );
+            }
+
+        ReadEngineDefaultsL( parser, settings );
+
+        SetLoggerSettings( loggerSettings ) ;
+
+        TRAP(r, ReadTestModulesL( parser ));
+        if(r != KErrNone)
+            {
+            __TRACE(KError, (CStifLogger::ERed, _L("Reading test modules finished with error [%d]"), r));
+            User::Leave(r);
+            }
+
+        CleanupStack::PopAndDestroy( settings );
+        CleanupStack::PopAndDestroy( parser );
+        __TRACE( KInit, ( _L( "Configuration file reading finished" ) ) );
+        }
+    else
+        {
+        __TRACE( KInit,( CStifLogger::EBold, _L( "Initialisation file not specified." ) ) );
+        }
+
+    Logger()->WriteDelimiter();
+    
+    // Create Test Reporter if allowed
+    if ( iTestEngineServer->iTestReportSettings->iCreateTestReport )
+        {
+        TRAPD(err, iTestReport = 
+            CTestReport::NewL( *(iTestEngineServer->iTestReportSettings), 
+                               ( CTestReport::TTestReportMode ) iReportMode ));
+        if(err!=KErrNone)
+            {
+            iTestReport = NULL;
+            __TRACE( KInit,( CStifLogger::ERed, _L( "Test report creation failed with error: %d, test report not created." ), err ) );
+            __TRACE( KInit,( CStifLogger::ERed, _L( "Check your testreport settings from testframework.ini file (e.g. TestReportFilePath)." ) ) );
+            }
+        }
+    
+    // Create test engine subsession object
+    CTestEngineSubSession* testEngineSubSession =
+    CTestEngineSubSession::NewL( this );
+    CleanupStack::PushL( testEngineSubSession );
+
+    // Add object to object container to generate unique id
+    iContainer->AddL( testEngineSubSession );
+
+    // Add object to object index
+    // This returns a unique handle so we can get it again
+    TInt handle = iTestEngineSubSessions->AddL( testEngineSubSession );
+
+    // Write the handle to client
+    TPckg<TInt> handlePckg( handle );
+
+    TRAPD( res, aMessage.WriteL( 3, handlePckg ) );
+    if ( res != KErrNone )
+        {
+        iTestEngineSubSessions->Remove( handle );
+        PanicClient( EBadDescriptor, aMessage );
+        return;
+        }
+
+    CleanupStack::Pop( testEngineSubSession );
+
+    // Notch up another resource
+    iResourceCount++;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ReadEngineDefaults
+
+    Description: Parse Test Engine defaults from STIF 
+                 initialization file.
+
+    Parameters: CStifParser& parser: in: CStifParser object
+                CSTIFTestFrameworkSettings* aSettings: in:
+                CSTIFTestFrameworkSettings object
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ReadEngineDefaultsL( CStifParser* aParser,
+                                        CSTIFTestFrameworkSettings* aSettings )
+    {
+    __TRACE( KInit,( _L( "" ) ) );
+    __TRACE( KInit,( _L( "Start parsing engine defaults" ) ) );
+    TInt get_ret( KErrNone );
+
+    CStifSectionParser* sectionParser = NULL;
+
+    // Parse Engine's default values
+    _LIT( KDefaultsStart, "[Engine_Defaults]" );
+    _LIT( KDefaultsEnd, "[End_Defaults]" );
+    __TRACE( KInit,( _L( "Starting to search sections" ) ) );
+    sectionParser = aParser->SectionL( KDefaultsStart, KDefaultsEnd );
+    CleanupStack::PushL( sectionParser );
+    if ( sectionParser )
+        {
+        __TRACE( KInit,( _L( "Found '%S' and '%S' sections" ), &KDefaultsStart, &KDefaultsEnd ) );
+
+        // Get Test Report Mode
+        __TRACE( KInit,( _L( "Parsing Test report mode" ) ) );
+        TUint reportMode( 0 );
+        get_ret = aSettings->GetReportModeL( sectionParser,
+                                        _L( "TestReportMode=" ), reportMode );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Report mode: %d"), reportMode ) );
+            iReportMode = reportMode;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Report mode not found or not given" ) ) );
+            }
+
+        // Indicator to test report creation
+        __TRACE( KInit,( _L( "Parsing Test report creation indicator" ) ) );
+        TBool createTestReport( 0 );
+        get_ret = aSettings->GetBooleanSettingsL( sectionParser,
+                                _L( "CreateTestReport=" ), createTestReport );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Test report creation indicator: %d"), createTestReport ) );
+            iTestEngineServer->iTestReportSettings->iCreateTestReport = createTestReport;
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Creation indicator not found or not given" ) ) );
+            }
+
+        // Get Test report path settings
+        if ( iTestEngineServer->iTestReportSettings->iCreateTestReport )
+            {
+            __TRACE( KInit,( _L( "Parsing Test report path" ) ) );
+            TPtrC path;
+            get_ret = aSettings->GetFileSetting( sectionParser,
+                                        _L( "TestReportFilePath=" ), path );
+            if ( get_ret == KErrNone )
+                {
+                __TRACE( KInit,( _L( "Test report path: %S"), &path ) );
+                // Delete old one before setting new one
+                delete iTestEngineServer->iTestReportSettings->iPath;
+				iTestEngineServer->iTestReportSettings->iPath = NULL;
+                iTestEngineServer->iTestReportSettings->iPath = path.AllocL();
+                }
+            else
+                {
+                __TRACE( KInit,( _L( "Path not found or not given" ) ) );
+                }
+            }
+
+        // Get Test report name settings
+        if ( iTestEngineServer->iTestReportSettings->iCreateTestReport )
+            {
+            __TRACE( KInit,( _L( "Parsing Test report filename" ) ) );
+            TPtrC name;
+            get_ret = aSettings->GetFileSetting( sectionParser,
+                                        _L( "TestReportFileName=" ), name );
+            if ( get_ret == KErrNone )
+                {
+                __TRACE( KInit,( _L( "Test report filename: %S"), &name ) );
+                // Delete old one before setting new one
+                delete iTestEngineServer->iTestReportSettings->iName;
+				iTestEngineServer->iTestReportSettings->iName = NULL;
+                iTestEngineServer->iTestReportSettings->iName = name.AllocL();
+                }
+            else
+                {
+                __TRACE( KInit,( _L( "Filename not found or not given" ) ) );
+                }
+            }
+
+        // Get Test report format settings
+        if ( iTestEngineServer->iTestReportSettings->iCreateTestReport )
+            {
+            __TRACE( KInit,( _L( "Parsing Test report format" ) ) );
+            CStifLogger::TLoggerType type;
+            TBool xml;
+            get_ret = aSettings->GetFormatL( sectionParser,
+                                            _L( "TestReportFormat=" ), type, xml );
+            if ( get_ret == KErrNone )
+                {
+                __TRACE( KInit,( _L( "Test report format: %d, xml: %d"), type, xml ) );
+                iTestEngineServer->iTestReportSettings->iFormat = type;
+                iTestEngineServer->iTestReportSettings->iXML = xml;
+                }
+            else
+                {
+                __TRACE( KInit,( _L( "Format not found or not given" ) ) );
+                }
+            }
+
+        // Get Test report output settings
+        if ( iTestEngineServer->iTestReportSettings->iCreateTestReport )
+            {
+            __TRACE( KInit,( _L( "Parsing Test report output" ) ) );
+            CStifLogger::TOutput output;
+            get_ret = aSettings->GetOutputL( sectionParser,
+                                        _L( "TestReportOutput=" ), output );
+            if ( get_ret == KErrNone )
+                {
+                __TRACE( KInit,( _L( "Test report output: %d"), output ) );
+                iTestEngineServer->iTestReportSettings->iOutput = output;
+                }
+            else
+                {
+                __TRACE( KInit,( _L( "Output not found or not given" ) ) );
+                }
+            }
+
+        // Get Test report file creation mode (overwrite settings)
+        if ( iTestEngineServer->iTestReportSettings->iCreateTestReport )
+            {
+            __TRACE( KInit,( _L( "Parsing Test report file writing mode" ) ) );
+            TBool overwrite;
+            get_ret = aSettings->GetOverwriteL( sectionParser,
+                            _L( "TestReportFileCreationMode=" ), overwrite );
+            if ( get_ret == KErrNone )
+                {
+                __TRACE( KInit,( _L( "Test report file creation mode: %d"), overwrite ) );
+                iTestEngineServer->iTestReportSettings->iOverwrite = overwrite;
+                }
+            else
+                {
+                __TRACE( KInit,( _L( "Writing mode not found or not given" ) ) );
+                }
+            }
+        // Get device reset module's DLL name
+        __TRACE( KInit,( _L( "Parsing device reset module's DLL name" ) ) );
+        TPtrC deviceResetName;
+        get_ret = aSettings->GetFileSetting( sectionParser,
+                                        _L( "DeviceResetDllName=" ), deviceResetName );
+        if ( get_ret == KErrNone )
+            {
+            __TRACE( KInit,( _L( "Device reset module's name: %S"), &deviceResetName ) );
+            // Delete old one before setting new one
+            delete iDeviceResetDllName;
+			iDeviceResetDllName = NULL;
+            iDeviceResetDllName = deviceResetName.AllocL();
+            }
+        else
+            {
+            __TRACE( KInit,( _L( "Device reset module's name not found or not given" ) ) );
+            }
+
+        // Get measurement disable option
+        CStifItemParser* item = NULL;
+        TRAPD( ret, item = sectionParser->GetItemLineL( _L( "DisableMeasurement=" ), ENoTag ) );
+        if( ( ret != KErrNone ) || ( item == NULL ) )
+            {
+             __TRACE( KInit,( _L( "Measurement 'DiableMeasurement=' not found or not given" ) ) );
+			delete item; 
+            item = NULL;
+            }
+        else
+            {
+			CleanupStack::PushL( item );			
+            TPtrC string;
+            ret = item->GetString( KNullDesC(), string );
+            while( ret == KErrNone )
+                {
+                HBufC* stringHbuf = string.AllocL();
+                TPtr modifiableString = stringHbuf->Des();
+                modifiableString.LowerCase();
+
+                if( modifiableString == KStifMeasurementDisableNone ||
+                    modifiableString == KStifMeasurementDisableAll ||
+                    modifiableString == KStifMeasurement01 ||
+                    modifiableString == KStifMeasurement02 ||
+                    modifiableString == KStifMeasurement03 ||
+                    modifiableString == KStifMeasurement04 ||
+                    modifiableString == KStifMeasurement05 ||
+                    modifiableString == KStifMeasurementBappea )
+                    {
+                    __TRACE( KInit,( _L( "Measurement disable option: %S"), &modifiableString ) );
+                    DisableStifMeasurement( modifiableString );
+                    }
+                else if( modifiableString == _L( "#" ) )
+                    {
+					delete stringHbuf;
+					stringHbuf = NULL;
+                    break;
+                    }
+                else
+                    {
+                    __TRACE( KInit,( _L( "Measurement disable option not found or not given" ) ) );
+                    delete stringHbuf;                    
+					stringHbuf = NULL;
+                    break;
+                    }
+                delete stringHbuf;
+                ret = item->GetNextString( string );
+                }
+			CleanupStack::PopAndDestroy( item );
+			item = NULL;
+            }
+
+        // Get timeout value option
+        __TRACE(KInit, (_L("Parsing default timeout value")));
+        iDefaultTimeout = 0;
+        item = NULL;
+        TRAP(ret, item = sectionParser->GetItemLineL(_L("Timeout=" ), ENoTag));
+        if( ( ret != KErrNone ) || ( item == NULL ) )
+            {
+            __TRACE(KInit, (_L("'Timeout' option not found or not given")));
+            delete item;
+            item = NULL;
+            }
+        else
+            {
+            CleanupStack::PushL( item );
+            TPtrC string;
+            ret = item->GetString(KNullDesC(), string);
+            if(string.Length() > 0)
+                {
+                TLex lex(string);
+                ret = lex.Val(iDefaultTimeout);
+                if(ret != KErrNone)
+                    {
+                    __TRACE(KError, (_L("Could not convert timeout value '%S' to integer. Error %d. Ignoring this setting."), &string, ret));
+                    }
+                if(iDefaultTimeout < 0)
+                    {
+                    __TRACE(KError, (_L("'Timeout' value cannot be negative. Resetting to 0.")));
+                    iDefaultTimeout = 0;
+                    }
+                }
+            else
+                {
+                __TRACE(KInit, (_L("'Timeout' value not given")));
+                }
+            CleanupStack::PopAndDestroy( item );
+            item = NULL;
+            }
+        __TRACE(KInit, (_L("'Timeout' value set to %d"), iDefaultTimeout));
+        iDefaultTimeout *= 1000;
+        
+        // Get UITestingSupport value option
+        __TRACE(KInit, (_L("Parsing UITestingSupport value")));
+        iUITestingSupport = EFalse;
+        item = NULL;
+        TRAP(ret, item = sectionParser->GetItemLineL(_L("UITestingSupport=" ), ENoTag));
+        if((ret != KErrNone) || (item == NULL))
+            {
+            __TRACE(KInit, (_L("'UITestingSupport' option not found")));
+            delete item;
+            item = NULL;
+            }
+        else
+            {
+            CleanupStack::PushL(item);
+            TPtrC string;
+            ret = item->GetString(KNullDesC(), string);
+            if(string.Length() > 0)
+                {
+                iUITestingSupport = (string == _L("YES"));
+                }
+            else
+                {
+                __TRACE(KInit, (_L("'UITestingSupport' value not given")));
+                }
+            CleanupStack::PopAndDestroy(item);
+            item = NULL;
+            }
+        __TRACE(KInit, (_L("'UITestingSupport' value set to %d"), iUITestingSupport));
+
+        // Get SeparateProcesses value option
+        __TRACE(KInit, (_L("Parsing SeparateProcesses value")));
+        iSeparateProcesses = EFalse;
+        item = NULL;
+        TRAP(ret, item = sectionParser->GetItemLineL(_L("SeparateProcesses=" ), ENoTag));
+        if((ret != KErrNone) || (item == NULL))
+            {
+            __TRACE(KInit, (_L("'SeparateProcesses' option not found")));
+            delete item;
+            item = NULL;
+            }
+        else
+            {
+            CleanupStack::PushL(item);
+            TPtrC string;
+            ret = item->GetString(KNullDesC(), string);
+            if(string.Length() > 0)
+                {
+                iSeparateProcesses = (string == _L("YES"));
+                }
+            else
+                {
+                __TRACE(KInit, (_L("'SeparateProcesses' value not given")));
+                }
+            CleanupStack::PopAndDestroy(item);
+            item = NULL;
+            }
+        __TRACE(KInit, (_L("'SeparateProcesses' value set to %d"), iSeparateProcesses));
+        }
+    else
+        {
+        __TRACE( KInit,( _L( "Not found '%S' and '%S' sections" ), &KDefaultsStart, &KDefaultsEnd ) );
+        }
+    __TRACE( KInit,( _L( "End parsing engine defaults" ) ) );
+    CleanupStack::PopAndDestroy( sectionParser );
+    
+    // Store engine settings to SettingServer
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        __TRACE(KError, (_L("Could not connect to SettingServer [%d] and store engine settings"), ret));
+        }
+    else
+        {
+        TEngineSettings settings;
+        settings.iUITestingSupport = iUITestingSupport;
+        settings.iSeparateProcesses = iSeparateProcesses;
+        ret = settingServer.StoreEngineSettings(settings);
+        if(ret != KErrNone)
+            {
+            __TRACE(KError, (_L("Could not store engine settings to SettingServer [%d]"), ret));
+            }
+            else
+            {
+            __TRACE(KInit, (_L("Engine settings succesfully stored to SettingServer")));
+            }
+        settingServer.Close();
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: SetLoggerSettings
+
+    Description: Set parsed logger's settings to TestEngine side.
+
+    Parameters: TLoggerSettings& aLoggerSettings: in: Parsed logger settings
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::SetLoggerSettings( TLoggerSettings& aLoggerSettings )
+    {
+    iTestEngineServer->iLoggerSettings = aLoggerSettings;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ParseTestModulesL
+
+    Description: Parse and search for module info and fill list of modules.
+
+    Parameters: CStifParser*     aParser:       in: CStifParser object
+                CTestModuleList* aModuleList:   in: list of modules
+                TPtrC&           aSectionStart: in: descriptor with start of section string
+                TPTrC&           aSectionEnd:   in: descriptor with end of section string
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ParseTestModulesL(CStifParser* aParser, CTestModuleList* aModuleList, const TDesC& aSectionStart, const TDesC& aSectionEnd)
+    {
+    //First let's find all modules given in Stif's ini file and store that info in CTestModuleList object
+    CStifSectionParser* sectionParser = NULL;
+    CStifItemParser* item = NULL;
+
+    sectionParser = aParser->SectionL(aSectionStart, aSectionEnd);
+
+    TBool sectionOK;
+
+    while(sectionParser)
+        {
+        sectionOK = ETrue;
+        __TRACE(KInit, (_L("Found '%S' and '%S' sections"), &aSectionStart, &aSectionEnd));
+        CleanupStack::PushL(sectionParser);
+        __TRACE(KInit, (_L("Starting to read module information")));
+
+        // Get name of module
+        _LIT(KModuleName, "ModuleName=");
+        item = sectionParser->GetItemLineL(KModuleName);
+        CleanupStack::PushL(item);
+        if(!item)
+            {
+            __TRACE(KError, (CStifLogger::ERed, _L("'%S' not found from Module section. Skipping whole section."), &KModuleName));
+            sectionOK = EFalse;
+            }
+        else
+            {
+            __TRACE(KInit, (_L("'%S' found"), &KModuleName));
+            }
+
+        TName moduleName;
+        TInt ret(KErrNone);
+
+        if(sectionOK)
+            {
+            TPtrC name;
+            ret = item->GetString(KModuleName, name);
+            if(ret != KErrNone)
+                {
+                __TRACE(KError, (CStifLogger::ERed, _L("Module name parsing ended with error [%d]. Skipping whole section"), ret));
+                sectionOK = EFalse;
+                }
+            else
+                {
+                __TRACE(KInit, (_L("Module '%S' found from ini-file"), &name));
+                moduleName.Copy(name);
+                moduleName.LowerCase();
+                ret = aModuleList->AddTestModule(moduleName);
+                if(ret != KErrNone && ret != KErrAlreadyExists)
+                    {
+                    CleanupStack::PopAndDestroy(item);
+                    __TRACE(KError, (CStifLogger::ERed, _L("Could not add module to list of modules. Error %d"), ret));
+                    LeaveIfErrorWithNotify(ret);
+                    }
+                }
+            }
+        CleanupStack::PopAndDestroy(item);
+
+        //Get pointer to added module
+        if(sectionOK)
+            {
+            CTestModuleInfo* moduleInfo = aModuleList->GetModule(moduleName);
+            if(!moduleInfo)
+                {
+                __TRACE(KError, (CStifLogger::ERed, _L("Could not add get module info from list")));
+                LeaveIfErrorWithNotify(KErrNotFound);
+                }
+    
+            // Get ini file, if it exists
+            __TRACE(KInit, (_L("Start parsing ini file")));
+            _LIT(KIniFile, "IniFile=");
+            item = sectionParser->GetItemLineL(KIniFile);
+            if(item)
+                {
+                __TRACE(KInit, (_L("'%S' found"), &KIniFile));
+                CleanupStack::PushL(item);
+                TPtrC iniFile;
+                ret = item->GetString(KIniFile, iniFile);
+                if(ret == KErrNone)
+                    {
+                    // Module inifile (might be empty) OK
+                    TFileName filename;
+                    filename.Copy(iniFile);
+                    TStifUtil::CorrectFilePathL( filename );
+                    filename.LowerCase();
+                    __TRACE(KInit, (CStifLogger::EBold, _L("Initialization file '%S' found, file can be empty"), &iniFile));
+                    moduleInfo->SetIniFile(filename);
+                    }
+                else
+                    {
+                    __TRACE(KInit, (_L("Initialization file not found")));
+                    }
+                CleanupStack::PopAndDestroy(item);
+                }
+            else
+                {
+                __TRACE(KInit, (_L("'%S' not found"), &KIniFile));
+                }
+    
+            // Get config (testcase) file
+            __TRACE(KInit, (_L("Start parsing cfg files")));
+            TPtrC cfgTag;
+            for(TInt i = 0; i < 2; i++)
+                {
+                //Set tag for config files
+                if(i == 0)
+                    {
+                    cfgTag.Set(_L("ConfigFile="));
+                    }
+                    else
+                    {
+                    cfgTag.Set(_L("TestCaseFile="));
+                    }
+                //Read data
+                item = sectionParser->GetItemLineL(cfgTag);
+                while(item)
+                    {
+                    CleanupStack::PushL(item);
+                    __TRACE(KInit, (_L("Item '%S' found"), &cfgTag));
+                    TPtrC cfgFile;
+                    ret = item->GetString(cfgTag, cfgFile);
+                    if(ret == KErrNone)
+                        {
+                        TFileName ifile;
+                        ifile.Copy(cfgFile);
+                        TStifUtil::CorrectFilePathL( ifile );
+                        ifile.LowerCase();
+                        __TRACE(KInit, (_L("Configuration file '%S' found"), &ifile));
+                        moduleInfo->AddCfgFile(ifile);
+                        }
+                    else
+                        {
+                        __TRACE(KInit, (_L("Configuration file not found")));
+                        }
+                    CleanupStack::PopAndDestroy(item);
+                    item = sectionParser->GetNextItemLineL(cfgTag);
+                    }
+                }
+    
+            __TRACE(KInit, (_L("Module '%S' information read correctly"), &moduleName));
+            }
+        else
+            {
+            __TRACE(KError, (_L("Module '%S' information skipped"), &moduleName));
+            }
+
+        // Get next section...
+        CleanupStack::PopAndDestroy(sectionParser);
+        sectionParser = aParser->NextSectionL(aSectionStart, aSectionEnd);
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ReadTestModules
+
+    Description: Parse Test modules and module information from
+                 STIF initialization file.
+
+    Parameters: CStifParser& parser: in: CStifParser object
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ReadTestModulesL(CStifParser* aParser)
+    {
+    __TRACE( KInit, (_L("")));
+    __TRACE( KInit, (CStifLogger::EBold, _L("Start parsing test modules")));
+
+    //Create CTestModuleList object. It will keep information about all found test modules,
+    //its initialization files and test case (config) files.
+    CTestModuleList* moduleList = CTestModuleList::NewL(Logger());
+    CleanupStack::PushL(moduleList);
+
+    // Parse Test Module information
+    _LIT(KTestModuleStart, "[New_Module]");
+    _LIT(KTestModuleEnd, "[End_Module]");
+
+    __TRACE(KInit, (_L("Starting to search module sections")));
+    TRAPD(err, ParseTestModulesL(aParser, moduleList, KTestModuleStart, KTestModuleEnd));
+    if(err != KErrNone)
+        {
+        __TRACE(KError, (CStifLogger::ERed, _L("Parsing test modules returned error [%d]"), err));
+        User::Leave(err);
+        }
+    __TRACE(KInit, (CStifLogger::EBold, _L("End parsing test modules")));
+    __TRACE(KInit, (_L("")));
+
+    //Now, find included test modules and also add them to CTestModuleList object.
+    _LIT(KIncludeModuleStart, "[New_Include_Module]");
+    _LIT(KIncludeModuleEnd, "[End_Include_Module]");
+
+    __TRACE(KInit, (CStifLogger::EBold, _L("Start parsing included modules")));
+    CTestCaseFileInfo* finfo = moduleList->GetUncheckedCfgFile();
+    while(finfo)
+        {
+        TFileName fname;
+        finfo->GetCfgFileName(fname);
+
+        __TRACE(KInit, (_L("checking file: '%S'"), &fname));
+        finfo->SetChecked();
+
+        CStifParser* parser = NULL;
+
+        TRAPD(err, parser = CStifParser::NewL(_L(""), fname));
+        if(err == KErrNotFound)
+            {
+            __TRACE(KError, (CStifLogger::ERed, _L("Could not open file '%S'"), &fname));
+            }
+        else if(err != KErrNone)
+            {
+            __TRACE(KError, (CStifLogger::ERed, _L("Could not create parser for file '%S'"), &fname));
+            LeaveIfErrorWithNotify(err);
+            }
+        else
+            {
+            CleanupStack::PushL(parser);
+
+            ParseTestModulesL(parser, moduleList, KIncludeModuleStart, KIncludeModuleEnd);
+
+            CleanupStack::PopAndDestroy(parser);
+            }
+
+        finfo = moduleList->GetUncheckedCfgFile();
+        }
+
+    __TRACE(KInit, (CStifLogger::EBold, _L("End parsing included modules")));
+    __TRACE(KInit, (_L("")));
+
+    //Now, when all modules have been found, create them
+    __TRACE(KInit, (CStifLogger::EBold, _L("Start creating modules")));
+    TBool afterReset = EFalse;
+    if(iRebootParams)
+        {
+        afterReset = ETrue;
+        }
+    CTestModuleInfo* moduleInfo = NULL;
+    TInt i;
+    TInt modCnt = moduleList->Count();
+
+    for(i = 0; i < modCnt; i++)
+        {
+        moduleInfo = moduleList->GetModule(i);
+        if(!moduleInfo)
+            {
+            __TRACE(KInit, (CStifLogger::ERed, _L("Could not get module info at index %d"), i));
+            TName error;
+            error.AppendFormat(_L("Could not get module info at index %d"), i);
+            ErrorPrint(1, error);
+            continue;
+            }
+
+        TName moduleName;
+        moduleInfo->GetModuleName(moduleName);
+
+        // Create module controller
+        __TRACE(KInit, (_L("Creating module controller for '%S'"), &moduleName));
+		CTestModuleController* module = NULL;
+		if( moduleName == _L( "testscripter" ) )
+			{
+			module = CTestModuleController::NewL(this, moduleName, afterReset, ETrue);
+			}
+		else
+			{
+			module = CTestModuleController::NewL(this, moduleName, afterReset);
+			}
+        CleanupStack::PushL(module);
+        __TRACE(KInit, (_L("Module controller created")));
+
+        // Get ini file, if exists
+        __TRACE(KInit, (_L("Checking ini file")));
+        TFileName ini;
+        moduleInfo->GetIniFileName(ini);
+        if(ini.Length() == 0)
+            {
+            __TRACE(KInit, (_L("Ini file not found")));
+            }
+
+        TRAPD(err, module->InitL(ini, KNullDesC));
+        if(err != KErrNone)
+            {
+            __TRACE(KInit, (CStifLogger::ERed, _L("Module '%S' loading failed: %d"), &moduleName, err));
+            TName error;
+            error.AppendFormat(_L("Module '%S' loading failed: %d"), &moduleName, err);
+            ErrorPrint(1, error);
+
+            CleanupStack::PopAndDestroy(module);
+            continue;
+            }
+
+        //Add test case files
+        __TRACE(KInit, (_L("Checking cfg files")));
+        TInt cfgCnt = moduleInfo->CountCfgFiles();
+        TInt j;
+        TFileName cfgFile;
+        for(j = 0; j < cfgCnt; j++)
+            {
+            moduleInfo->GetCfgFileName(j, cfgFile);
+            if(cfgFile.Length() > 0)
+                {
+                __TRACE(KInit, (_L("Adding config file '%S'"), &cfgFile));
+                module->AddConfigFileL(cfgFile);
+                }
+            else
+                {
+                __TRACE(KInit, (_L("Got empty config filename")));
+                }
+            }
+        if(cfgCnt == 0)
+            {
+            __TRACE(KInit, (_L("Cfg file not found")));
+            }
+
+        __TRACE(KInit, (_L("Module '%S' created correctly"), &moduleName));
+
+        // Store module for later use
+        User::LeaveIfError(iModules.Append(module));
+        CleanupStack::Pop(module);
+        }
+
+    __TRACE(KInit, (CStifLogger::EBold, _L("End creating test modules")));
+    __TRACE(KInit, (_L("")));
+
+    //Check if there are any modules added to Stif
+    if (iModules.Count() == 0)
+        {
+        __TRACE(KInit, (_L("Not found '%S' and '%S' sections"), &KTestModuleStart, &KTestModuleEnd));
+        __TRACE(KInit, (CStifLogger::EBold, _L("Test module(s) not defined in initialisation file")));
+        // Note is printed from UI, not from here anymore
+        // ErrorPrint( 0 , _L("Test modules not found. Check testengine log"));
+        }
+
+    //Delete CTestModuleList object. It is not needed any more
+    CleanupStack::PopAndDestroy(moduleList);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: TestModuleConfigFileL
+
+    Description: Add config file to test module
+
+    Parameters: CTestModuleController* aModule: in: CTestModuleController
+                                                    object.
+                CStifSectionParser* aSectionParser: in: CStifSectionParser
+                object.
+                TDesC& aTag :in: Founded tag.
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if GetNextItemLineL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::TestModuleConfigFileL( CTestModuleController* aModule,
+                                            CStifSectionParser* aSectionParser,
+                                            TDesC& aTag )
+    {
+    // Add config files to Test Module
+    TPtrC configFile;
+    CStifItemParser* item = NULL;
+    item = aSectionParser->GetItemLineL( aTag );
+
+    TInt cfgFiles = 0;
+    TFileName config;
+
+    TInt ret( 0 );
+
+    while ( item )
+        {
+        __TRACE( KInit,( _L( "Found '%S' section" ), &aTag ) );
+        CleanupStack::PushL( item );
+        ret = item->GetString( aTag, configFile );
+        if ( ret != KErrNone )
+            {
+            CleanupStack::PopAndDestroy( item );
+            __TRACE( KError, ( CStifLogger::ERed, _L( "File parsing left with error [%d]" ), ret ) );
+            }
+        else
+            {
+            config = configFile;
+            aModule->AddConfigFileL( config );
+
+            // Module configfile (might be empty) OK
+            __TRACE( KInit,( _L( "Adding configuration file [%S]" ), &config ) );
+            cfgFiles++;
+            CleanupStack::PopAndDestroy( item );
+            }
+        item = aSectionParser->GetNextItemLineL( aTag );
+        }
+
+    // Print trace
+    if ( cfgFiles == 0)
+        {  
+        __TRACE( KInit,( _L( "Module does not have '%S' files") , &aTag ) );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ModuleControllerByName
+
+    Description: Return the module controller specified by given parameter.
+
+    Parameters: const TName& aModuleName: in: Test module name
+
+    Return Values: CTestModuleController* : pointer to CTestModuleController
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleController* CTestEngine::ModuleControllerByName(
+                                                    const TName& aModuleName )
+    {
+    TInt modules = iModules.Count();
+
+    for ( TInt i = 0; i < modules; i++ )
+        {
+        if ( iModules[i]->ModuleName( aModuleName ) == aModuleName )
+            {
+            return iModules[i];
+            }
+        }
+    return NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: GetFreeOrCreateModuleControllerL
+
+    Description: Return free module controller specified by given parameter.
+                 If it can't be found, new one will be created.
+
+    Parameters: TTestInfo& aTestInfo: test info structure
+                CTestModuleController** aRealModuleController: for test scripter a real module controller will be returned
+
+    Return Values: CTestModuleController* : pointer to CTestModuleController
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleController* CTestEngine::GetFreeOrCreateModuleControllerL(TTestInfo& aTestInfo,
+                                                                     CTestModuleController** aRealModuleController)
+    {
+    TInt i, j;
+    *aRealModuleController = NULL;
+    
+    TInt modules = iModules.Count();
+
+    //Find out which way it should be processed
+    //New way means that Stif is going to find free test module controller
+    //(free means that it does not run any test case)
+    TBool oldWay = ETrue;
+    if((iUITestingSupport && aTestInfo.iModuleName.Find(KTestScripterName) == 0) 
+        || (aTestInfo.iModuleName == KPythonScripter)
+        || (iSeparateProcesses))
+        {
+        __TRACE(KInit, (_L("Module controllers handling mode: exclusive")));
+        //Exclusive mode means that every test case must be run in separate module controller.
+        oldWay = EFalse;
+        }
+    else
+        {
+        __TRACE(KInit, (_L("Module controllers handling mode: normal")));
+        oldWay = ETrue;
+        }
+        
+    //If option is not set and it is not python scripter case
+    //(python scripter always should look for free module controller)
+    //This is the old way
+    if(oldWay) 
+        {
+        __TRACE(KInit, (_L("Find test module controller for [%S]"), &aTestInfo.iModuleName));
+        for(i = 0; i < modules; i++)
+            {
+            if(iModules[i]->ModuleName(aTestInfo.iModuleName) == aTestInfo.iModuleName)
+                {
+                __TRACE(KInit, (_L("Found test module controller for [%S]"), &aTestInfo.iModuleName));
+                return iModules[i];
+                }
+            }
+        __TRACE(KInit, (_L("Test module controller for [%S] NOT FOUND"), &aTestInfo.iModuleName));
+        return NULL;
+        }
+    
+    //This is a new way
+    __TRACE(KInit, (_L("Find free test module controller for [%S]"), &aTestInfo.iModuleName));
+
+    TName moduleName(aTestInfo.iModuleName);
+    CTestModuleController* parentController = NULL;
+
+    //First find original test module controller (parent)
+    for(TInt i = 0; i < modules; i++)
+        {
+        if(iModules[i]->ModuleName(moduleName) ==  moduleName)
+            {
+            parentController = iModules[i];
+            __TRACE(KInit, (_L("Original (parent) module controller found [%S]"), &moduleName));
+            break;
+            }
+        }
+
+    //Search free module controller among parent's children
+    if(parentController)
+        {
+        //TestScripter is handled in other way
+        if(moduleName.Find(KTestScripterName) == 0)
+            {
+            __TRACE(KInit, (_L("This is testscripter case. Searching real module controller.")));
+            *aRealModuleController = parentController->GetFreeOrCreateModuleControllerL(aTestInfo, iUITestingSupport);
+            return parentController;                 
+            }
+
+        //When UITestingSupport always create new module controller!
+        TInt childrenCount = parentController->iChildrenControllers.Count();
+        for(TInt i = 0; i < childrenCount; i++)
+            {
+            if(parentController->iChildrenControllers[i]->iTestCaseCounter == 0)
+                {
+                if(iUITestingSupport && aTestInfo.iModuleName.Find(KTestScripterName) == 0)
+                    {
+                    __TRACE(KInit, (_L("Free module controller found but in UITestingSupport mode always new one will be created")));
+                    }
+                else
+                    {
+                    __TRACE(KInit, (_L("Free module controller found [%S]"), parentController->iChildrenControllers[i]->iName));
+                    return parentController->iChildrenControllers[i];
+                    }
+                }
+            else
+                {
+                __TRACE(KInit, (_L("Module controller [%S] found but it is not free (it runs %d test cases)"), parentController->iChildrenControllers[i]->iName, parentController->iChildrenControllers[i]->iTestCaseCounter));
+                }
+            }
+        }
+    else
+        {
+        __TRACE(KError, (_L("Parent module controller NOT found [%S]"), &moduleName));
+        User::Leave(KErrNotFound);
+        }
+
+    //No free module controller has been found. Create new one.
+    TBuf<10> ind;
+    ind.Format(_L("%d"), GetIndexForNewTestModuleController());
+    moduleName.Append(_L("@"));
+    moduleName.Append(ind);
+    __TRACE(KInit, (_L("Free module controller not found. Creating new one [%S]."), &moduleName));
+            
+    //Create server and active object (This uses CTestModuleController::InitL())
+    CTestModuleController* module = CTestModuleController::NewL(this, moduleName, parentController->iAfterReboot);
+    CleanupStack::PushL(module);
+    
+    TRAPD(err, module->InitL(parentController->iInifile, aTestInfo.iConfig));
+    if(err != KErrNone)
+        {
+        __TRACE(KInit, (_L("InitL fails with error: %d for module [%S]" ), err, &moduleName));
+        User::Leave(err);
+        }
+    __TRACE(KInit, (_L("New module controller created [%S]."), &moduleName));
+
+    // Store module for later use
+    User::LeaveIfError(parentController->iChildrenControllers.Append(module));
+    CleanupStack::Pop(module);
+    __TRACE(KInit, (_L("Child added to [%S] controller. Currently it has %d children:"), parentController->iName, parentController->iChildrenControllers.Count()));
+    for(j = 0; j < parentController->iChildrenControllers.Count(); j++)
+        {
+        __TRACE(KInit, (_L("    %d. [%S]"), j + 1, parentController->iChildrenControllers[j]->iName));
+        }
+
+    return module;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: SetAttributeL
+
+    Description: Sets attributes to Test Framework
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leave if ReadL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::SetAttributeL( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::SetAttributeL" ) ) );
+
+    TAttribute attribute;
+    TName genericTName;
+
+    // Read attribute from aMessage
+    attribute = (TAttribute)aMessage.Int0();
+
+    switch( attribute )
+        {
+        // Path attribute
+        case ELogPath:
+            {
+            // Read path from aMessage. 
+            // NOTE!If message length is over TName, ReadL will cut the message
+            // to allowed size and won't return any error code or leave code.
+            aMessage.ReadL( 1, genericTName );
+
+            // Handle to Setting server.
+            RSettingServer settingServer;
+            // Connect to the Setting server and create session
+            TInt ret = settingServer.Connect();
+            if ( ret != KErrNone )
+                {
+                User::Leave( ret );
+                }
+            settingServer.SetNewIniFileSetting( genericTName );
+            // Close Setting server session
+            settingServer.Close();
+            break;
+            }
+        // Reboot directory
+        case ERebootPath:
+            {
+            // Read reboot path from aMessage. 
+            // NOTE!If message length is over TName, ReadL will cut the message
+            // to allowed size and won't return any error code or leave code.
+            aMessage.ReadL( 1, genericTName );
+            // Allocated dynamically iRebootPath size and copies aMessage path.
+            iRebootPath = genericTName.AllocL();
+            break;
+            }
+        // Reboot path
+        case ERebootFilename:
+            {
+            // Read reboot path from aMessage. 
+            // NOTE!If message length is over TName, ReadL will cut the message
+            // to allowed size and won't return any error code or leave code.
+            aMessage.ReadL( 1, genericTName );
+            // Allocated dynamically iRebootFilename size and copies aMessage
+            // filename.
+            iRebootFilename = genericTName.AllocL();
+            break;
+            }
+        // Measurement configuration info
+        case EStifMeasurementOn:
+            {
+            // Read Measurement configuration info from aMessage. 
+            aMessage.ReadL( 1, genericTName );
+
+            // Set info to test engine
+            User::LeaveIfError( EnableStifMeasurement( genericTName ) );
+            break;
+            }
+        // Measurement configuration info
+        case EStifMeasurementOff:
+            {
+            // Read Measurement configuration info from aMessage. 
+            aMessage.ReadL( 1, genericTName );
+
+            // Set info to test engine
+            User::LeaveIfError( DisableStifMeasurement( genericTName ) );
+            break;
+            }
+        default:
+            {
+            __TRACE( KVerbose, ( _L( "Not valid attribute" ) ) );
+            }
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: AddTestModuleL
+
+    Description: Adds new Test Module
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+                       Leaves if name length is zero
+
+    Status: Approved: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::AddTestModuleL( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::AddTestModuleL" ) ) );
+    TName name;
+    TFileName iniFile;
+
+    // Read test module name from aMessage
+    aMessage.ReadL( 0, name );
+
+    if( name.Length() == 0 )
+        {
+        LeaveWithNotifyL( KErrArgument );
+        }
+    // Read ini file name from aMessage
+    aMessage.ReadL( 1, iniFile );
+    
+    name.LowerCase();
+    // Remove optional '.DLL' from file name
+    TParse parse;
+    parse.Set( name, NULL, NULL );
+    
+    if ( parse.Ext() == _L(".dll") )
+        {
+        const TInt len = parse.Ext().Length();
+        name.Delete ( name.Length()-len, len );
+        }
+
+    __TRACE( KInit, ( 
+        _L( "CTestEngine::AddTestModuleL, Adding Module:[%S]"), &name ) );
+
+    // Check if test module already exists
+    CTestModuleController* testModule = ModuleControllerByName( name );
+    if ( testModule == NULL )
+        {
+        TBool afterReset = EFalse;
+        if( iRebootParams && iRebootParams->iTestModule == name )
+            {
+            afterReset = ETrue;
+            }
+        
+        // Create module controller
+		CTestModuleController* module = NULL;
+		if( name == _L( "testscripter" ) )
+			{
+			module = CTestModuleController::NewL( this, name, afterReset, ETrue );
+			}
+		else
+			{
+			//CTestModuleController* module = 
+			module = CTestModuleController::NewL( this, name, afterReset );
+			}
+        CleanupStack::PushL( module );
+
+        module->InitL( iniFile, KNullDesC );
+
+        // Store module for later use
+        User::LeaveIfError( iModules.Append( module ) );
+        CleanupStack::Pop( module );
+        // Done
+        iReturn = KErrNone;
+
+        __TRACE( KInit, ( 
+        _L( "CTestEngine::AddTestModuleL, module added correctly") ) );
+        }
+    else
+        {
+        iReturn = KErrAlreadyExists;
+        __TRACE( KInit, ( 
+        _L( "CTestEngine::AddTestModuleL, module already added, all ok.") ) );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: RemoveTestModuleL
+
+    Description: Removes Test Module
+
+    Parameters: const RMessage& aMessage: in: Server message
+    
+    Return Values: TInt KErrNone: No errors occurred
+                        KErrNotFound: Test module not found
+                        KErrInUse: Test module is in use, cannot be removed
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+                       Leaves if moduleName length is zero
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::RemoveTestModuleL( const RMessage2& aMessage )
+    {
+    __TRACE( KInit, ( _L( "CTestEngine::RemoveTestModuleL" ) ) );
+    // Read Module name from message
+    TName moduleName;
+    aMessage.ReadL( 0, moduleName );
+    if( moduleName.Length() == 0 )
+        {
+        LeaveWithNotifyL( KErrArgument );
+        }
+
+    moduleName.LowerCase();
+    // Remove optional '.DLL' from file name
+    TParse parse;
+    parse.Set( moduleName, NULL, NULL );
+
+    if ( parse.Ext() == _L(".dll") )
+        {
+        const TInt len = parse.Ext().Length();
+        moduleName.Delete ( moduleName.Length()-len, len );
+        }
+
+    __TRACE(KInit, (_L("Going to remove module controller [%S]"), &moduleName));
+    // Check that the module that will be removed exists
+    TInt moduleCount = iModules.Count();
+    TBool found = EFalse;
+    TInt moduleIndex;
+    for ( moduleIndex = 0; moduleIndex < moduleCount; moduleIndex++ )
+        {
+        if ( iModules[moduleIndex]->ModuleName( moduleName ) == moduleName )
+            {
+            found = ETrue;
+            break;
+            }
+        }
+
+    if ( !found )
+        {
+        // Test Module does not exists
+        __TRACE(KInit, (_L("Module controller [%S] to be removed NOT FOUND"), &moduleName));
+        return KErrNotFound;
+        }
+    // Check module controller and its children
+    if(iModules[moduleIndex]->iTestCaseCounter > 0)
+        {
+        __TRACE(KInit, (_L("Cannot remove module controller [%S], it is running %d test cases"), &moduleName, iModules[moduleIndex]->iTestCaseCounter));
+        return KErrInUse;
+        }
+    TInt j;
+    for(j = 0; j < iModules[moduleIndex]->iChildrenControllers.Count(); j++)
+        {
+        if(iModules[moduleIndex]->iChildrenControllers[j]->iTestCaseCounter > 0)
+            {
+            __TRACE(KInit, (_L("Cannot remove module controller [%S], its child [%S] is running %d test cases"), &moduleName, iModules[moduleIndex]->iChildrenControllers[j]->iName, iModules[moduleIndex]->iChildrenControllers[j]->iTestCaseCounter));
+            return KErrInUse;
+            }
+        }
+    // Test cases not running so we can remove the Test Module
+    __TRACE(KInit, (_L("Removing module controller [%S]"), &moduleName));
+    CTestModuleController* module = iModules[moduleIndex];
+    iModules.Remove(moduleIndex);
+    delete module;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: CloseTestEngineL
+
+    Description: Close test engine
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if GenerateReportL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::CloseTestEngineL( TUint aHandle )
+    {
+    __TRACE( KInit, ( _L( "CTestEngine::CloseTestEngineL" ) ) );
+    // Remove all module controllers
+    iModules.ResetAndDestroy();
+    iModules.Close();
+
+    // If test report is created
+    if( iTestReport )
+        {
+        iTestReport->GenerateReportL();
+        iIsTestReportGenerated = ETrue;
+        }
+
+    // Close Setting server, no handle available anymore
+    iSettingServer.Close();
+
+    // Get test case from container
+    CTestEngineSubSession* testEngineSubSession = ( CTestEngineSubSession* )iTestEngineSubSessions->At( aHandle );
+
+    // Do nothing if invalid handle
+    if ( testEngineSubSession == NULL )
+        {
+        // Handle might be already deleted, so do nothing.
+        return;
+        }
+
+    iTestEngineSubSessions->Remove( aHandle );
+
+    // Decrement resource count
+    iResourceCount--;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: AddConfigFileL
+
+    Description: Adds new config file to Test Module
+
+    Parameters: const RMessage& aMessage: in: Server Message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+                       Leaves if module length is zero
+                       Leaves if configFile length is zero
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::AddConfigFileL( const RMessage2& aMessage )
+    {
+    TName module;
+    TFileName configFile;
+
+    // Read module name from aMessage
+    aMessage.ReadL( 0, module );
+
+    if( module.Length() == 0 )
+        {
+        LeaveWithNotifyL( KErrArgument );
+        }
+    // Read config file name from aMessage
+    aMessage.ReadL( 1, configFile );
+
+    if( configFile.Length() == 0 )
+        {
+        LeaveWithNotifyL( KErrArgument );
+        }
+
+    module.LowerCase();
+    // Remove optional '.DLL' from file name
+    TParse parse;
+    parse.Set( module, NULL, NULL );
+    
+    if ( parse.Ext() == _L(".dll") )
+        {
+        const TInt len = parse.Ext().Length();
+        module.Delete ( module.Length()-len, len );
+        }
+        
+    __TRACE( KInit, ( _L( "Adding config file [%S] to [%S] module"), &configFile, &module ) );
+    
+    // Get correct test module controller
+    CTestModuleController* testModule = ModuleControllerByName( module );
+    if ( testModule == NULL )
+        {        
+        __TRACE( KError, ( CStifLogger::ERed, _L( "Added configure file has an invalid module:[%S]"), &module ) );
+        LeaveWithNotifyL ( KErrNotFound );
+        }
+
+    // Add config file to Module
+    testModule->AddConfigFileL( configFile );
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: RemoveConfigFileL
+
+    Description: Removes a config file from test module
+
+    Parameters: const RMessage& aMessage: in: Server Message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+                       Leaves if module length is zero
+                       Leaves if configFile length is zero
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::RemoveConfigFileL( const RMessage2& aMessage )
+    {
+    TName module;
+    TFileName configFile;
+
+    // Read module name from aMessage
+    aMessage.ReadL( 0, module );
+
+    if( module.Length() == 0 )
+        {
+        LeaveWithNotifyL( KErrArgument );
+        }
+    // Read config file name from aMessage
+    aMessage.ReadL( 1, configFile );
+
+    if( configFile.Length() == 0 )
+        {
+        LeaveWithNotifyL( KErrArgument );
+        }
+
+    module.LowerCase();
+    // Remove optional '.DLL' from file name
+    TParse parse;
+    parse.Set( module, NULL, NULL );
+    
+    if ( parse.Ext() == _L(".dll") )
+        {
+        const TInt len = parse.Ext().Length();
+        module.Delete ( module.Length()-len, len );
+        }
+        
+    __TRACE( KInit, ( _L( "Removing config file [%S] from [%S] module"), &configFile, &module ) );
+    
+    // Get correct test module controller
+    CTestModuleController* testModule = ModuleControllerByName( module );
+    if ( testModule == NULL )
+        {        
+        __TRACE( KError, ( CStifLogger::ERed, _L( "Added configure file has an invalid module:[%S]"), &module ) );
+        LeaveWithNotifyL ( KErrNotFound );
+        }
+
+    // Remove config file from Module
+    testModule->RemoveConfigFileL( configFile );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: EnumerateTestCasesL
+
+    Description: Enumerates test cases
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Panics the client if enumeration is already pending
+                       Leaves if called StartEnumerateL method leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::EnumerateTestCasesL( const RMessage2& aMessage )
+    {
+    __TRACE( KInit, ( _L( "CTestEngine::EnumerateTestCasesL" ) ) );
+    // Check if enumerate is ongoing!!
+    __ASSERT_ALWAYS( iEnumerateModuleCount == 0, PanicClient( EReqPending, aMessage ) );
+
+    iCaseCount = 0;
+    iEnumError = KErrNone;
+
+    TInt count = iModules.Count();
+    if ( count == 0 )
+        {
+
+        __TRACE( KInit, ( CStifLogger::EBold, _L( "Test module(s) not loaded - returning 0 test cases" ) ) );
+        
+        // Note is printed from UI
+        // ErrorPrint(0, _L("No test modules, check testengine log"));
+        // Write test case count to client
+        TCaseCount countPckg( 0 );
+        TRAPD( err, aMessage.WriteL( 0, countPckg ) );
+
+        // Request will be completed in DispatchMessageL
+        iReturn = err;
+        }
+    else
+        {
+        for ( TInt i = 0; i < count; i++ )
+            {
+            // Send enumerate request to each test module.
+            iModules[i]->StartEnumerateL();
+            iEnumerateModuleCount++;
+            }
+    
+        // Message is completed later from EnumerationCompleted function
+        iComplete = EFalse;
+
+        // Store the message
+        iEnumerationMessage = aMessage;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: EnumerationCompleted
+
+    Description: Return the module controller specified by given parameter.
+
+    Parameters: TInt aCount: in: Count of test cases
+                TInt aError: in: Symbian OS Error code: Error from Test Module
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::EnumerationCompleted( TInt aCount, TInt aError )
+    {
+    // Increment test case count by aCount
+    iCaseCount+= aCount;
+
+    if ( aError != KErrNone )
+        {
+        iEnumError = aError;
+        }
+
+    iEnumerateModuleCount--;
+    
+    if ( iEnumerateModuleCount == 0 )
+        {
+       
+        TInt attrib = CStifLogger::ENoStyle;
+        if ( iCaseCount == 0 )
+            {
+            attrib = CStifLogger::EBold;
+            }
+        __TRACE( KInit, ( attrib, _L( "Test case enumeration completed, testcase count %d"), iCaseCount ) );
+
+        // Write test case count to client
+        TCaseCount countPckg( iCaseCount );
+        TRAPD( err, iEnumerationMessage.WriteL( 0, countPckg ) );
+
+        if ( err != KErrNone )
+            {
+            iEnumError = err;
+            __TRACE( KError, ( CStifLogger::ERed,  _L( "CTestEngine::EnumerationCompleted: Failed %d"), iEnumError ) );
+            }
+        
+        // Complete request
+        iEnumerationMessage.Complete( iEnumError );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: GetTestCasesL
+
+    Description: Get test cases
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if enumeration is not yet complete
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::GetTestCasesL( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::GetTestCasesL" ) ) );
+
+    const TInt len = sizeof( TTestInfo );
+
+    // Loop through all test modules
+    TInt moduleCount = iModules.Count();
+    TInt pos = 0;
+    TInt totalCount = 0;
+    for ( TInt i = 0; i < moduleCount; i++ )
+        {
+        CTestModuleController* module = iModules[i];
+
+        // Check that test cases are enumerated first
+        if ( !module->EnumerationComplete() )
+            {
+            __TRACE( KError, ( CStifLogger::ERed, _L( "CTestEngine::GetTestCasesL, Test Cases not yet enumerated!" ) ) );
+            LeaveIfErrorWithNotify( KErrNotFound );
+            }
+
+        CFixedFlatArray<TTestInfo>* testCases = module->TestCasesL();
+        CleanupStack::PushL( testCases );
+        
+        // Loop through all test cases got from test module
+        const TInt caseCount = testCases->Count();
+        totalCount+=caseCount;
+
+        for ( TInt j = 0; j < caseCount; j++ )
+            {
+            if(((*testCases)[j]).iTestCaseInfo.iTimeout == 0 && iDefaultTimeout > 0)
+                {
+                ((*testCases)[j]).iTestCaseInfo.iTimeout = iDefaultTimeout;
+                }
+
+            // Construct package for source data
+            TTestInfoPckg tmpPackage( ( *testCases )[j] );
+
+            // Copy test case package to client's memory
+            aMessage.WriteL( 0, tmpPackage, pos ) ;
+
+            pos = pos + len;
+            }
+        CleanupStack::PopAndDestroy( testCases );
+
+        // Free allocated test cases because not needed anymore
+        module->FreeTestCases();
+
+        }
+
+    __TRACE( KVerbose, ( _L( "CTestEngine::GetTestCasesL, case count %d" ), totalCount ) );
+
+    // Finished
+    iReturn = KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: CancelAsyncRequest
+
+    Description: Asynchronous requests are canceled by this function.
+
+    Parameters: const RMessage aMessage
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::CancelAsyncRequest( const RMessage2& aMessage )
+    {
+    switch ( aMessage.Int0() )
+        {
+        case ETestEngineEnumerateTestCases:
+            {
+            TInt count = iModules.Count();
+            for ( TInt i=0; i < count; i++ )
+                {
+                // Cancel enumerate  
+                iModules[i]->Cancel();
+                }
+            break;
+            }
+
+        case ETestEngineErrorNotification:
+            {
+            if ( iErrorMessageAvailable )
+                {
+                iErrorMessageAvailable = EFalse;
+                iErrorMessage.Complete ( KErrCancel );
+                }
+            }
+            break;
+        case ETestEngineEvent:
+            // Event command cannot be cancelled
+            // Only EWaitEvent can be cancelled with ECancelWait
+        default:
+            PanicClient( EBadRequest, aMessage );
+            break;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: EventControlL
+
+    Description: Controls event system.
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::EventControlL( const RMessage2& aMessage )
+
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::EventControlL" ) ) );
+    TInt ret = KErrNone;
+
+    // Read EventIf from aMessage
+    TEventIf event;
+    TEventIfPckg eventIfPckg( event );
+    aMessage.ReadL( 0, eventIfPckg );
+
+    // EWaitEvent, EReqEvent and ERelEvent need processing here
+    if( ( event.Type() == TEventIf::EWaitEvent ) ||
+        ( event.Type() == TEventIf::EReqEvent ) ||
+        ( event.Type() == TEventIf::ERelEvent ) ||
+        ( event.Type() == TEventIf::ECancelWait ) )
+        {
+        TInt ind = 0; 
+        TInt count = iClientEvents.Count();
+        const TDesC& eventName = event.Name();
+        // Search event from client event list
+        for( ind=0; ind < count; ind++ )
+            {
+            if( iClientEvents[ind]->Name() == eventName )
+                {
+                break;
+                }
+            }
+
+        switch( event.Type() )
+            {
+            // Handle event waiting  
+            case TEventIf::EWaitEvent:
+                {
+                // Check that we found event from client events list
+                if( ind == count )
+                    {
+                    ret = KErrNotFound;
+                    }
+                else
+                    {
+                    TEventMsg* eventEntry = iClientEvents[ind];
+                    
+                    __TRACE( KVerbose, ( _L( "CTestEngine::EventControlL: Waiting %S (count %i)"), 
+                        &event.Name(), count ) );
+
+                    // Waiting is completed either from here in Wait method 
+                    // if event is already pending,
+                    // or from Set method in CtlEvent when event is set.
+                    eventEntry->Wait( aMessage );
+                    return;
+                    }
+                }
+                break;
+            case TEventIf::ECancelWait:
+                {
+                // Check that we found event from client events list
+                if( ind == count )
+                    {
+                    ret = KErrNotFound;
+                    }
+                else
+                    {
+                    TEventMsg* eventEntry = iClientEvents[ind];
+                    
+                    __TRACE( KVerbose, ( _L( "CTestEngine::EventControlL: Cancel waiting %S (count %i)"), 
+                        &event.Name(), count ) );
+
+                    eventEntry->CancelWait();
+                    }
+                }
+                break;
+            // Handle event request
+            case TEventIf::EReqEvent:
+                {
+                // Check that event is not already requested
+                if( ind < count )
+                    {
+                    // Already exists
+                    ret = KErrArgument;
+                    }
+                else
+                    { 
+                    // Requested events are added to iClientEvents
+                    TEventMsg* eventEntry = new TEventMsg;
+                    if( eventEntry == NULL )
+                        {
+                        ret = KErrNoMemory;
+                        }
+                    else
+                        {
+                        CleanupStack::PushL( eventEntry );
+                        eventEntry->Copy( event );
+                        // Check if state event is set already
+                        if( IsStateEventAndSet( event.Name() ) )
+                            { 
+                            // If it was set already, set the event
+                            eventEntry->Set( TEventIf::EState );
+                            }
+                        ret = iClientEvents.Append( eventEntry ); 
+                        if( ret != KErrNone )
+                            {
+                            CleanupStack::PopAndDestroy( eventEntry );
+                            }
+                        else
+                            {   
+                            CleanupStack::Pop( eventEntry );
+                               
+                            __TRACE( KVerbose, ( _L( "CTestEngine::EventControlL: Req added %S (count %i)"),
+                                &event.Name(), iClientEvents.Count() ) );
+                            } 
+                        }
+                    }
+                }
+                break;
+            // Release event 
+            case TEventIf::ERelEvent:
+                {
+                // Released events are deleted from iClientEvents
+                // Check that we found entry from client events list
+                if( ind == count )
+                    {
+                    ret = KErrNotFound;
+                    }
+                else
+                    {
+                    __TRACE( KVerbose, ( _L( "CTestEngine::EventControlL: Release event %S (count %i)"), 
+                        &event.Name(), iClientEvents.Count() ) );
+
+                    TEventMsg* eventEntry = iClientEvents[ind];
+                    iClientEvents.Remove( ind );
+                    eventEntry->Release();
+                    delete eventEntry;
+                    }
+                }
+                break;
+            default: // This should never happen!!!
+                { 
+                _LIT( KEngine, "CTestEngine" );
+                User::Panic( KEngine, KErrGeneral );
+                }
+                break;
+            }
+        }
+    else
+        {
+        // ESetEvent and EUnsetEvent are only forwarded
+        TRequestStatus req;
+        CtlEventL( event, req );
+        User::WaitForRequest( req );
+        }
+        
+    aMessage.Complete( ret );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: HandleErrorNotificationL
+
+    Description: Handle error notifications.
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::HandleErrorNotificationL( const RMessage2& aMessage )
+    {
+    iErrorMessage = aMessage;
+    iErrorMessageAvailable = ETrue;
+
+    ProcessErrorQueue();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: LoggerSettings
+
+    Description: Get Logger's overwrite parameters
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Panics if WriteL fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::LoggerSettings( const RMessage2& aMessage )
+    {
+    __TRACE( KInit, ( _L( "CTestEngine::LoggerSettings" ) ) );
+
+    // Copies logger settings to the package
+    TPckg<TLoggerSettings> loggerSettingsPckg( iTestEngineServer->iLoggerSettings );
+
+    // Writes a packege that includes the logger overwrite settings to aMessage
+    TRAPD( err, aMessage.WriteL( 0, loggerSettingsPckg ) );
+    if ( err != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: CloseLoggerSettings
+
+    Description: Close logger settings
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::CloseLoggerSettings()
+    {
+    __TRACE( KInit, ( _L( "CTestEngine::CloseLoggerSettings" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: TestCaseByHandle
+
+    Description: Return test case specified by aHandle
+
+    Parameters: TUint aHandle : in : TUint : Handle to TestCase subsession
+
+    Return Values: CTestCase* : pointer to CTestCase object
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCase* CTestEngine::TestCaseByHandle( TUint aHandle, const RMessage2& aMessage )
+    {
+    // Try to get test case from test case container
+    CTestCase* testCase =
+        ( CTestCase* )iTestCases->At( aHandle );
+    if ( testCase == NULL )
+        {
+        PanicClient( EBadSubsessionHandle, aMessage ); 
+        }
+
+    return testCase;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: NewTestCaseL
+
+    Description: Create new test execution subsession
+
+    Parameters: const RMessage& aMessage: in: Server Message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving method leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::NewTestCaseL( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::NewTestCaseL start" ) ) );
+
+    // Get data from message
+    TTestInfo testInfo;
+    TTestInfoPckg testInfoPckg = testInfo;
+
+    TRAPD( res, aMessage.ReadL( 0, testInfoPckg ) );
+    if ( res != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        return;
+        }
+
+    testInfo.iModuleName.LowerCase();
+    // Remove optional '.DLL' from file name
+    TParse parse;
+    parse.Set( testInfo.iModuleName, NULL, NULL );
+
+    if ( parse.Ext() == _L(".dll") )
+        {
+        const TInt len = parse.Ext().Length();
+        testInfo.iModuleName.Delete ( testInfo.iModuleName.Length()-len, len );
+        }
+
+    // Get correct test module controller
+    CTestModuleController* scrModule = NULL;
+    CTestModuleController* module = GetFreeOrCreateModuleControllerL(testInfo, &scrModule);
+    if ( module == NULL )
+        {
+        //@spe PanicClient( EInvalidModuleName, aMessage );
+        //@spe return;
+        __TRACE( KError, ( CStifLogger::ERed, _L( "Invalid module:[%S]"), &testInfo.iModuleName ) );
+        LeaveWithNotifyL ( KErrNotFound );
+        }
+
+    // Create test case object
+    CTestCase* testCase =
+        CTestCase::NewL( this, module, iTestReport, testInfo, scrModule);
+    CleanupStack::PushL( testCase );
+
+    // Add object to object container to generate unique id
+    iContainer->AddL( testCase );
+
+    // Add object to object index
+    // This returns a unique handle so we can get it again
+    TInt handle = iTestCases->AddL( testCase );
+
+    // Write the handle to client
+    TPckg<TInt> handlePckg( handle );
+
+    TRAP( res, aMessage.WriteL( 3, handlePckg ) );
+    if ( res != KErrNone )
+        {
+        iTestCases->Remove( handle );
+        PanicClient( EBadDescriptor, aMessage );
+        return;
+        }
+
+    // Add new test case to testcase array
+    User::LeaveIfError( iTestCaseArray.Append( testCase ) );
+    CleanupStack::Pop( testCase );
+
+    // Notch up another resource
+    iResourceCount++;
+
+    iReturn = KErrNone;
+
+    __TRACE( KVerbose, ( _L( "CTestEngine::NewTestCaseL done" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: DeleteTestCase
+
+    Description: Delete test case from container list
+
+    Parameters: TUint aHandle: in: Handle to test case to be removed
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::DeleteTestCase( TUint aHandle ) 
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::DeleteTestCase" ) ) );
+
+    // Get test case from container
+    CTestCase* testCase = ( CTestCase* )iTestCases->At( aHandle );
+
+    // Do nothing if invalid handle
+    if ( testCase == NULL )
+        {
+        // Handle might be already deleted, so do nothing.
+        return;
+        }
+
+    //Get controllers
+    CTestModuleController* moduleController;
+    CTestModuleController* realModuleController;
+    
+    moduleController = testCase->GetModuleControllers(&realModuleController);
+    
+    // Check if module controllers have crashed
+    TBool moduleControllerCrashed = EFalse;
+    TBool realModuleControllerCrashed = EFalse;
+
+    if(moduleController)
+        {
+        moduleControllerCrashed = moduleController->iTestModuleCrashDetected;
+        }
+    if(realModuleController)
+        {
+        realModuleControllerCrashed = realModuleController->iTestModuleCrashDetected;
+        }
+
+    //__TRACE(KInit, (_L("CTestEngine::DeleteTestCase moduleController=[%x] crashed=[%d] realModuleController=[%x] crashed=[%d]"), moduleController, moduleControllerCrashed, realModuleController, realModuleControllerCrashed));
+    // For UITestingSupport, SeparateProcesses and PythonSupport, when module is crashed,
+    // remove it from module lists, because it will be deleted when closing test case.
+    if(moduleController)
+        {
+        if(moduleControllerCrashed && iUITestingSupport && moduleController->iName->Find(KTestScripterName) == 0
+           || moduleControllerCrashed && iSeparateProcesses
+           || moduleControllerCrashed &&  moduleController->iName->Find(KPythonScripter) == 0
+          )
+            {
+            __TRACE(KInit, (_L("Removing module controller from module list because of crash")));
+            //Look for specific module controller and delete it
+            TInt i;
+            TInt j, children;
+            TInt modules = iModules.Count();
+            for(i = 0; i < modules; i++)
+                {
+                if(iModules[i] == moduleController)
+                    {
+                    __TRACE(KInit, (_L("Module controller found - removing")));
+                    iModules.Remove(i);
+                    break;
+                    }
+
+                //Check children of the module and if module to be deleted found there, remove it
+                children = iModules[i]->iChildrenControllers.Count();
+                __TRACE(KInit, (_L("Checking %d children of [%S]"), children, iModules[i]->iName));
+                for(j = 0; j < children; j++)
+                    {
+                    if(iModules[i]->iChildrenControllers[j] == moduleController)
+                        {
+                        __TRACE(KInit, (_L("Module controller found (child) - removing")));
+                        
+                        iModules[i]->iChildrenControllers.Remove(j);
+
+                        __TRACE(KInit, (_L("Child removed from [%S] controller. Currently it has %d children:"), iModules[i]->iName, iModules[i]->iChildrenControllers.Count()));
+                        for(TInt k = 0; k < iModules[i]->iChildrenControllers.Count(); k++)
+                            {
+                            __TRACE(KInit, (_L("    %d. [%S]"), k + 1, iModules[i]->iChildrenControllers[k]->iName));
+                            }                            
+                        break;
+                        }
+                    }
+                }
+            }
+        }
+    if(moduleController && realModuleController)
+        {
+        if(realModuleControllerCrashed && iUITestingSupport && realModuleController->iName->Find(KTestScripterName) == 0
+           || realModuleControllerCrashed && iSeparateProcesses
+           || realModuleControllerCrashed &&  realModuleController->iName->Find(KPythonScripter) == 0
+          )
+            {
+            __TRACE(KInit, (_L("Removing real module controller from module list because of crash")));
+            //Remove module controller from scripter controller
+            moduleController->RemoveModuleController(realModuleController);
+            }
+        }
+
+    // Close test case and remove it from container
+    //testCase->CloseTestCase();
+    iTestCases->Remove( aHandle );
+
+    // Decrement resource count
+    iResourceCount--;
+
+    // Remove from testcase array
+    iTestCaseArray.Remove( iTestCaseArray.Find( testCase ) );
+
+    //If this is UITestingSupport and module is not crashed, delete controller 
+    //(in other words, kill process, because we need somehow reset the test server).
+    if(moduleController && !moduleControllerCrashed)
+        {        
+        if(iUITestingSupport && moduleController->iName->Find(KTestScripterName) == 0)
+            {
+            if(realModuleController)
+                {
+                if(!realModuleControllerCrashed)
+                    {
+                    __TRACE(KInit, (_L("Delete module controller (and kill process in which test case was run).")));
+                    __TRACE(KInit, (_L("Real module controller provided - processing")));
+                    //Remove module controller from scripter controller
+                    moduleController->DeleteModuleController(realModuleController);
+                    }
+                }
+            else
+                {
+                 __TRACE(KInit, (_L("Delete module controller (and kill process in which test case was run).")));
+                 __TRACE(KInit, (_L("Real module controller not provided, checking normal controllers")));
+                //Look for specific module controller and delete it
+                TInt i;
+                TInt j, children;
+                TInt modules = iModules.Count();
+                for(i = 0; i < modules; i++)
+                    {
+                    if(iModules[i] == moduleController)
+                        {
+                        __TRACE(KInit, (_L("Module controller found - deleting")));
+                        delete iModules[i];
+                        iModules.Remove(i);
+                        break;
+                        }
+
+                    //Check children of the module and if module to be deleted found there, remove it
+                    children = iModules[i]->iChildrenControllers.Count();
+                    __TRACE(KInit, (_L("Checking %d children of [%S]"), children, iModules[i]->iName));
+                    for(j = 0; j < children; j++)
+                        {
+                        if(iModules[i]->iChildrenControllers[j] == moduleController)
+                            {
+                            __TRACE(KInit, (_L("Module controller found (child) - deleting")));
+                            
+                            delete iModules[i]->iChildrenControllers[j];
+                            iModules[i]->iChildrenControllers.Remove(j);
+    
+                            __TRACE(KInit, (_L("Child removed from [%S] controller. Currently it has %d children:"), iModules[i]->iName, iModules[i]->iChildrenControllers.Count()));
+                            for(TInt k = 0; k < iModules[i]->iChildrenControllers.Count(); k++)
+                                {
+                                __TRACE(KInit, (_L("    %d. [%S]"), k + 1, iModules[i]->iChildrenControllers[k]->iName));
+                                }                            
+                            break;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: IsStateEventAndSet
+
+    Description: Callback to check state event status.
+
+    Parameters: const TName& aEventName: in: Event name
+
+    Return Values: ETrue: event is set 
+                   EFalse: event is not set
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestEngine::IsStateEventAndSet( const TName& aEventName )
+    {
+    TInt count = iStateEvents.Count();
+    for( TInt i = 0; i < count; i++ ) 
+        {
+        TPtrC name = iStateEvents[i]->Des();
+        if( name == aEventName )
+            {
+            // Requested state event set already
+            return ETrue;
+            }
+        }
+    return EFalse;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: CtlEventL
+
+    Description: Callback to control events.
+
+    Parameters: const TEventIf& aEvent: in: event information
+                TRequestStatus& aStatus: in: Request status
+
+    Return Values: CTestEventController*: CTestEventController object
+
+    Errors/Exceptions: Leaves if CtlEventL leaves
+                       Leaves if memory allocation fails
+                       Leaves if unset event not found from pending 
+                       state event list
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEventController* CTestEngine::CtlEventL( const TEventIf& aEvent, 
+                                              TRequestStatus& aStatus )
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::CtlEventL" ) ) );
+    
+    aStatus = KRequestPending;
+
+    UpdateEventL( aEvent );
+    return CTestEventController::NewL( this, aEvent, &aStatus );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: UpdateEventL
+
+    Description: Update event lists.
+
+    Parameters: const TEventIf& aEvent: in: event information
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if CtlEventL leaves
+                       Leaves if memory allocation fails
+                       Leaves if unset event not found from pending
+                       state event list
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::UpdateEventL( const TEventIf& aEvent )
+    {
+    // Handle ESetEvent and EUnsetEvent for state events here
+    if( aEvent.EventType() == TEventIf::EState )
+        {
+        // Find event from the list
+        TInt count = iStateEvents.Count();
+        TInt index = 0;
+        const TDesC& eventName = aEvent.Name();
+        for( ; index < count; index++ ) 
+            {
+            TPtrC name = iStateEvents[index]->Des();
+            if( name == eventName )
+                {
+                break;
+                }
+            }
+
+        if( aEvent.Type() == TEventIf::ESetEvent )
+            {
+            // Check that event is not already pending
+            if( index < count )
+                {
+                User::Leave( KErrAlreadyExists );
+                }
+
+            // Add set event to pending state event list
+            HBufC* name = aEvent.Name().AllocLC();
+            User::LeaveIfError( iStateEvents.Append( name ) );
+            CleanupStack::Pop( name );
+            }
+        else if( aEvent.Type() == TEventIf::EUnsetEvent )
+            {
+            if( index == count )
+                {
+                // Not found from state event list
+                User::Leave( KErrNotFound );
+                }
+            HBufC* tmp = iStateEvents[index];
+            iStateEvents.Remove( index );
+            delete tmp;
+            }
+        }
+    else if( aEvent.Type() == TEventIf::EUnsetEvent )
+        {
+        // Can not give Unset for indication event
+        User::Leave( KErrNotSupported );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: Logger
+
+    Description: Return the pointer to Logger.
+
+    Parameters: None
+
+    Return Values: CStifLogger*: Pointer to StifLogger
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifLogger* CTestEngine::Logger()
+    {
+    return iTestEngineServer->Logger();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: WriteRebootParams
+
+    Description: Write the Reboot's state parameters.
+
+    Parameters: TTestInfo& aTestInfo: in: Test case information.
+                TInt& aCode: in: Reboot related integer information.
+                TDesC& aName: in: Reboot related string information.
+
+    Return Values: TInt: Symbian OS error
+
+    Errors/Exceptions: Error code returned if Logger creation fails.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::WriteRebootParams( TTestInfo& aTestInfo,
+                                        TInt& aCode,
+                                        TDesC& aName )
+    {
+    __TRACE( KVerbose, ( _L( "WriteRebootParams() starts..." ) ) );
+    
+    // Logger's setting definitions
+    TLoggerSettings loggerSettings;
+
+    loggerSettings.iCreateLogDirectories = ETrue;
+    loggerSettings.iOverwrite = ETrue;
+    loggerSettings.iTimeStamp = EFalse;
+    loggerSettings.iLineBreak = EFalse;
+    loggerSettings.iEventRanking = EFalse;
+    loggerSettings.iThreadId = EFalse;
+    // EData format because now we don't have to check file type when
+    // parsing this.
+    loggerSettings.iHardwareFormat = CStifLogger::EData;
+    loggerSettings.iHardwareOutput = CStifLogger::EFile;
+    loggerSettings.iEmulatorFormat = CStifLogger::EData;
+    loggerSettings.iEmulatorOutput = CStifLogger::EFile;
+    loggerSettings.iUnicode = EFalse;
+    loggerSettings.iAddTestCaseTitle = EFalse;
+
+    // Use default setting if path or filename are not set by SetAttribute()
+    if( iRebootPath == NULL )
+        {
+        iRebootPath= iRebootDefaultPath.Alloc();
+        }
+    if( iRebootFilename == NULL )
+        {
+        iRebootFilename= iRebootDefaultFilename.Alloc();
+        }
+
+    CStifLogger* logger = NULL;
+    TRAPD( ret, logger = CStifLogger::NewL( *iRebootPath,
+                                        *iRebootFilename,
+                                        loggerSettings ) );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, ( _L( "WriteRebootParams() Logger creation fails with error: " ), ret ) );
+        delete logger;
+        return ret;
+        }
+
+    // Write reboot parameters
+    // Because logging format is EData we need add line breaks by hand.
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "This is TestFramework's file which includes Reboot related informations" ) );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "Reboot case's related information:" ) );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "%S %S" ), &KTestModule, &aTestInfo.iModuleName );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "%S %S" ), &KTestCaseFile, &aTestInfo.iConfig );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "%S %d" ), &KTestCaseNumber, aTestInfo.iTestCaseInfo.iCaseNumber );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "%S %S" ), &KTestCaseTitle, &aTestInfo.iTestCaseInfo.iTitle );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "%S %d" ), &KStateCode, aCode );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "%S " ), &KStateName );
+    logger->Log( aName );
+    logger->Log( _L( "\r\n" ) );
+    logger->Log( _L( "\r\n" ) );
+
+    delete logger;
+
+    __TRACE( KVerbose, ( _L( "WriteRebootParams() ends" ) ) );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ReadRebootParams
+
+    Description: Read the Reboot parameters.
+
+    Parameters: TTestInfo& aTestInfo: in: Test case information.
+
+    Return Values: TInt: Symbian OS error
+
+    Errors/Exceptions: Error code returned if Parser creation fails.
+                       Error code returned if section creation fails.
+                       Error code returned if item creation fails.
+                       Error code returned if parsing operation fails.
+                       KErrArgument returned if parsed values and test case
+                       values are different.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::ReadRebootParams( TTestInfo& aTestInfo, 
+                                    TDes& aStateDes, 
+                                    TInt& aState )
+    {
+    __TRACE( KVerbose, ( _L( "ReadRebootParams() starts..." ) ) );
+
+    if( iRebootParams == NULL )
+        {
+        __TRACE( KVerbose, ( _L( "ReadRebootParams(): Reboot not done" )) );
+        return KErrNotFound;
+        }
+        
+    // --.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--
+    // Checks parsed values and test case values
+    // --.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--
+    if( iRebootParams->iTestModule != aTestInfo.iModuleName ||
+        iRebootParams->iTestCaseFile != aTestInfo.iConfig ||
+        iRebootParams->iCaseNumber != aTestInfo.iTestCaseInfo.iCaseNumber )
+        {
+        __TRACE( KVerbose, 
+            ( _L( "ReadRebootParams(): Reboot not done by %S" ), 
+                &aTestInfo.iModuleName) );
+        return KErrArgument;
+        }
+   
+    aStateDes.Copy( iRebootParams->iStateName );
+    aState = iRebootParams->iStateCode;
+   
+    // delete reboot params, to ensure that same test case 
+    // does not get indication about reboot again
+    delete iRebootParams;
+    iRebootParams = 0;
+
+    __TRACE( KVerbose, ( _L("ReadRebootParams() ends" ) ) );
+    
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ParseRebootParamsL
+
+    Description: Parse the Reboot parameters.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian OS error
+
+    Errors/Exceptions: Error code returned if Parser creation fails.
+                       Error code returned if section creation fails.
+                       Error code returned if item creation fails.
+                       Error code returned if parsing operation fails.
+                       KErrArgument returned if parsed values and test case
+                       values are different.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::ParseRebootParamsL()
+    {
+    __TRACE( KVerbose, ( _L( "ParseRebootParamsL() starts..." ) ) );
+
+    TInt ret_parsing( 0 );
+    TPtrC tmp;
+
+    // Use default setting if path or filename are not set by SetAttribute()
+    if( iRebootPath == NULL )
+        {
+        iRebootPath= iRebootDefaultPath.Alloc();
+        }
+    if( iRebootFilename == NULL )
+        {
+        iRebootFilename= iRebootDefaultFilename.Alloc();
+        }
+
+    // Create parser object
+    CStifParser* parser = NULL;
+    TRAPD( ret, parser = CStifParser::NewL( *iRebootPath,
+                                        *iRebootFilename ) );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, ( _L( "ReadRebootParams(): Reboot file not found" )) );
+        return ret;        
+        }
+    CleanupStack::PushL( parser );
+    
+    // Create section object
+    CStifSectionParser* section = parser->SectionL( KNullDesC, KNullDesC );
+    CleanupStack::PushL( section );
+    
+    // Delete old reboot params
+    delete iRebootParams;
+    iRebootParams = 0;
+    iRebootParams = CRebootParams::NewL();
+    
+    // ----------------------Test module parsing
+    CStifItemParser* item = section->GetItemLineL( KTestModule );
+    CleanupStack::PushL( item );
+
+    // Parsing integer
+    ret_parsing = item->GetString( KTestModule, tmp );
+    if( ret_parsing == KErrNone || ret_parsing == KErrNotFound )
+        {
+        __TRACE( KVerbose, ( _L("ReadRebootParams(): TestModule: %S" ), &tmp ) );
+        }
+    else
+        {
+        __TRACE( KError, 
+            ( _L("ReadRebootParams(): TestModule parsing fails with error: " ), 
+                ret_parsing ) );
+        User::Leave( ret_parsing );        
+        }
+    iRebootParams->SetTestModuleNameL( tmp );
+    CleanupStack::PopAndDestroy( item );
+
+    // ----------------------Testcase parsing
+    item = section->GetItemLineL( KTestCaseFile );
+    CleanupStack::PushL( item );
+
+    // Parsing string
+    ret_parsing = item->GetString( KTestCaseFile, tmp );
+    if( ret_parsing == KErrNone ) 
+        {
+        __TRACE( KVerbose, ( _L("ReadRebootParams(): TestCaseFile: %S" ), &tmp ) );
+        iRebootParams->SetTestCaseFileNameL( tmp );
+        }
+    else if( ret_parsing == KErrNotFound )
+        {
+        __TRACE( KVerbose, 
+            ( _L("ReadRebootParams(): No testcasefile defined for test module" )) );
+        }
+    else
+        {
+        __TRACE( KError, 
+            ( _L("ReadRebootParams(): TestCaseFile parsing fails with error: %d " ), 
+                ret_parsing ) );
+        User::Leave( ret_parsing );  
+        }
+    CleanupStack::PopAndDestroy( item );
+
+    // ----------------------Testcase number parsing
+    item = section->GetItemLineL( KTestCaseNumber );
+    CleanupStack::PushL( item );    
+    
+    // Parsing integer
+    ret_parsing = item->GetInt( KTestCaseNumber, iRebootParams->iCaseNumber );
+    if( ret_parsing == KErrNone || ret_parsing == KErrNotFound )
+        {
+        __TRACE( KVerbose, ( _L("ReadRebootParams(): TestCaseNumber: %d" ), 
+            iRebootParams->iCaseNumber ) );
+        }
+    else
+        {
+        __TRACE( KError,
+            ( _L("ReadRebootParams(): TestCaseNumber parsing fails with error: %d " ), 
+                ret_parsing ) );
+         User::Leave( ret_parsing );  
+        }
+    CleanupStack::PopAndDestroy( item );
+
+    // --.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--
+    // --.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--
+    // Next state code and name parsing if no error found
+    // --.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--
+
+    // ----------------------State code parsing
+    item = section->GetItemLineL( KStateCode );
+    CleanupStack::PushL( item );   
+
+    // Parsing integer
+    ret_parsing = item->GetInt( KStateCode, iRebootParams->iStateCode );
+    if( ret_parsing == KErrNone || ret_parsing == KErrNotFound )
+        {
+        __TRACE( KVerbose, ( _L("ReadRebootParams(): StateCode: %d" ), 
+            iRebootParams->iStateCode ) );
+        }
+    else
+        {
+        __TRACE( KError, 
+            ( _L("ReadRebootParams(): StateCode parsing fails with error: %d " ), 
+            ret_parsing ) );
+        User::Leave( ret_parsing );  
+        }
+    CleanupStack::PopAndDestroy( item );
+    
+    // ----------------------State name parsing
+    ret_parsing = section->GetLine( KStateName, tmp, ENoTag );
+    if( ret_parsing != KErrNone )
+        {
+        __TRACE( KError, 
+            ( _L("ReadRebootParams(): State name parsing fails with error: %d " ), 
+            ret_parsing ) );
+        User::Leave( ret_parsing );         
+        }
+
+    iRebootParams->SetTestCaseStateL( tmp );
+
+    __TRACE( KVerbose, ( _L("ReadRebootParams() ends" ) ) );
+
+    CleanupStack::PopAndDestroy( section );
+    CleanupStack::PopAndDestroy( parser );
+
+    // Delete file
+    RFs rf;
+    TInt retVal = rf.Connect();
+	if( retVal != KErrNone )
+		{
+		User::Leave( retVal ); 
+		}
+		
+    TFileName file( *iRebootPath );
+    file.Append( *iRebootFilename );
+    rf.Delete( file );
+    rf.Close();
+    
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: PauseAllTestCases
+
+    Description: Pause all test case(s) which are/is running.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::PauseAllTestCases()
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::PauseAllTestCases()" ) ) );
+
+    TInt count( 0 );
+    count = iTestCaseArray.Count();
+
+    for( TInt a = 0; a < count; a++ )
+        {
+         // Pause test case
+         iTestCaseArray[a]->Pause();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: FlushAtsLogger
+
+    Description: Flush ATS logger's
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::FlushAtsLogger()
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::FlushAtsLogger()" ) ) );
+
+    TInt count( 0 );
+    count = iModules.Count();
+
+    for( TInt a = 0; a < count; a++ )
+        {
+         // Pause test case
+         iModules[a]->AtsLogger().SaveForRebootL();
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: GetDeviceResetDllName
+
+    Description: Get device reset module's DLL name.
+
+    Parameters: None
+
+    Return Values: TPtrC
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TPtrC CTestEngine::GetDeviceResetDllName()
+    {
+    __TRACE( KVerbose, ( _L( "CTestEngine::GetDeviceResetDllName()" ) ) );
+
+    return iDeviceResetDllName->Des();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: EnableStifMeasurement
+
+    Description: Set measurements related information, enable measurement.
+
+    Parameters: const TName& aInfoType: in: Enabled measurement type
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::EnableStifMeasurement( const TDesC& aInfoType )
+    {
+    __TRACE( KInit, ( _L( "Measurement [%S] enabled" ), &aInfoType ) );
+
+    if( aInfoType == KStifMeasurement01 )
+        {
+        iDisableMeasurement &= ~EMeasurement01;
+        }
+    else if( aInfoType == KStifMeasurement02 )
+        {
+        iDisableMeasurement &= ~EMeasurement02;
+        }
+    else if( aInfoType == KStifMeasurement03 )
+        {
+        iDisableMeasurement &= ~EMeasurement03;
+        }
+    else if( aInfoType == KStifMeasurement04 )
+        {
+        iDisableMeasurement &= ~EMeasurement04;
+        }
+    else if( aInfoType == KStifMeasurement05 )
+        {
+        iDisableMeasurement &= ~EMeasurement05;
+        }
+    else if( aInfoType == KStifMeasurementBappea )
+        {
+        iDisableMeasurement &= ~EBappea;
+        }
+    else if( aInfoType == KStifMeasurementDisableAll )
+        {
+        __TRACE( KInit, ( _L( "All measurements are disabled" ) ) );
+        iDisableMeasurement &= EDisableAll; // Does change anything !!!
+        }
+    else if( aInfoType ==  KStifMeasurementEnableAll )
+        {
+        __TRACE( KInit, ( _L( "All measurements types are enabled" ) ) );
+        iDisableMeasurement &= EEnableAll;
+        }
+    else
+        {
+        __TRACE( KInit, ( _L( "Measurement [%S] not recognized" ), &aInfoType ) );
+        return KErrArgument;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: DisableStifMeasurement
+
+    Description: Set measurements related information, disable measurement.
+
+    Parameters: const TName& aInfoType: in: Disabled measurement type 
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::DisableStifMeasurement( const TDesC& aInfoType )
+    {
+    __TRACE( KInit, ( _L( "Measurement [%S] disabled" ), &aInfoType ) );
+
+    if( aInfoType == KStifMeasurement01 )
+        {
+        iDisableMeasurement |=  EMeasurement01;
+        }
+    else if( aInfoType ==  KStifMeasurement02 )
+        {
+        iDisableMeasurement |=  EMeasurement02;
+        }
+    else if( aInfoType ==  KStifMeasurement03 )
+        {
+        iDisableMeasurement |= EMeasurement03;
+        }
+    else if( aInfoType ==  KStifMeasurement04 )
+        {
+        iDisableMeasurement |=  EMeasurement04;
+        }
+    else if( aInfoType ==  KStifMeasurement05 )
+        {
+        iDisableMeasurement |=  EMeasurement05;
+        }
+    else if( aInfoType ==  KStifMeasurementBappea )
+        {
+        iDisableMeasurement |=  EBappea;
+        }
+    else if( aInfoType ==  KStifMeasurementDisableAll )
+        {
+        __TRACE( KInit, ( _L( "All measurements are disabled" ) ) );
+        iDisableMeasurement |=  EDisableAll;
+        }
+    else if( aInfoType ==  KStifMeasurementEnableAll )
+        {
+        __TRACE( KInit, ( _L( "All measurements types are enabled" ) ) );
+        iDisableMeasurement |=  EEnableAll; // Does change anything !!!
+        }
+    // This option can be defined in TestFramework.ini file
+    else if( aInfoType ==  KStifMeasurementDisableNone )
+        {
+        __TRACE( KInit, ( _L( "All measurements types are enabled" ) ) );
+        iDisableMeasurement =  EEnableAll; // Sets to 0
+        }
+    else
+        {
+        __TRACE( KInit, ( _L( "Measurement [%S] not recognized" ), &aInfoType ) );
+        return KErrArgument;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: StifMeasurement
+
+    Description: Get measurements related information. Returns is measurement
+                 disable.
+
+    Parameters: None
+
+    Return Values: TInt: Indication what measurement types is/are disabled.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::StifMeasurement()
+    {
+    return iDisableMeasurement;
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: TestModuleCrash
+
+    Description: This method is called only when test module crashed 
+                 with KErrServerTerminated (-15). 
+                 Clones new TestModuleController:
+                 - Find crashed testmodulecontroller
+                 - Creates new copy of that testmodulecontroller
+                 - Replaces old crashed testmodulecontroller with this new one
+
+    Parameters: CTestModuleController* aTestModuleController: in: TestModuleController
+    Return Values: None
+
+    Errors/Exceptions: Leaves if error happens when adding clone to the list
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::TestModuleCrash(CTestModuleController* aTestModuleController)
+    {
+    TName crashModuleName = aTestModuleController->ModuleName(KNullDesC);
+    __TRACE(KInit, (_L("Handling crashed test module [%S]"), &crashModuleName));
+    TBool isTestScripter(EFalse);
+    
+    // Find crashed test module controller
+    CTestScripterController* testScripterController = aTestModuleController->iTestScripterController;
+    if(testScripterController)
+        {
+        isTestScripter = ETrue;
+        }
+
+    // If UITestingSupport or SeparateProcesses is enabled, there is no need
+    // to create clone of Test Module Controller, because it will be created
+    // automatically when needed.
+    if(iUITestingSupport && crashModuleName.Find(KTestScripterName) == 0 
+       || iSeparateProcesses
+       || (crashModuleName.Find(KPythonScripter) == 0)
+      )
+        {
+        __TRACE(KInit, (_L("Handling crashed test module with enabled UITestingSupport or SeparateProcesses is not needed")));
+        aTestModuleController->iTestModuleCrashDetected = ETrue;
+        return;
+        }
+        
+    // Clone crashed module
+    TBool afterReset = EFalse;
+    if(iRebootParams && iRebootParams->iTestModule == crashModuleName)
+        {
+        afterReset = ETrue;
+        }  
+    
+    CTestModuleController* clone;    
+    clone = aTestModuleController->CloneL(aTestModuleController, afterReset, testScripterController);  
+    
+    // Replaces crashed testmodulecontroller with this new one    
+    // Note: Old Testmodulecontroller is deleted in CTestModuleController::CaseFinished 
+    //       that is called from  CTestCase::~CTestCase() 
+
+    TInt index = KErrNotFound;
+    if(isTestScripter)
+        {
+        index = testScripterController->iTestScripter.Find(aTestModuleController);
+        __TRACE(KInit, (_L("Crashed module index [%d]"), index));
+        if(index != KErrNotFound)
+            {
+            testScripterController->iTestScripter.Remove(index);
+            }
+        testScripterController->iTestScripter.Append(clone);            
+        }
+    else
+        {
+        index = iModules.Find(aTestModuleController);
+        __TRACE(KInit, (_L("Crashed module index [%d]"), index));
+        if(index != KErrNotFound)
+            {
+            iModules.Remove(index);
+            }
+        iModules.Append(clone);
+        }
+    __TRACE(KInit, (_L("End of handling crashed test module")));
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: ExecuteCommandL
+
+    Description: Executes command received from test case.
+                 The method was created to allow test case to kill itself.
+
+    Parameters: aTestCaseHandle: handler to test case
+    Return Values: None
+
+    Errors/Exceptions: Leaves if error happens when adding clone to the list
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngine::ExecuteCommandL(TCommand aCommand, TDesC8& aParamsPckg)
+    {
+    TInt testCaseHandle = 0;
+    // Get params
+    switch(aCommand)
+        {
+        case EStopExecution:
+            {
+            //Unpack received parameters
+            TStopExecutionCommandParams par;
+            TStopExecutionCommandParamsPckg parPack(par);
+            parPack.Copy(aParamsPckg);
+
+            __TRACE(KInit, (_L("CTestEngine::ExecuteCommandL received command [%d] type [%d] code [%d] test handle [%d]"), TInt(aCommand), TInt(par.iType), TInt(par.iCode), par.iTestCaseHandle));
+
+            //Get test case handle
+            testCaseHandle = par.iTestCaseHandle;
+
+            break;
+            }
+        case ESendTestModuleVersion:
+        	{
+        	TSendTestModuleVesionCommandParams par;
+        	TSendTestModuleVesionCommandParamsPckg parPack(par);
+        	parPack.Copy(aParamsPckg);
+
+        	TTestModuleVersionInfo testModuleVersionInfo;
+        	testModuleVersionInfo.iMajor = par.iMajor;
+        	testModuleVersionInfo.iMinor = par.iMinor;
+        	testModuleVersionInfo.iBuild = par.iBuild;
+        	testModuleVersionInfo.iTestModuleName = par.iTestModuleName;
+        	if(iTestReport)
+        	    {
+        	    iTestReport->AddTestModuleVersion(testModuleVersionInfo);
+        	    }
+        	
+        	return;
+        	}
+        default:
+            __TRACE(KError, (_L("CTestEngine::ExecuteCommandL Unknown command [%d]"), TInt(aCommand)));
+            return;
+        }
+
+    // Get test case from container
+    CTestCase* testCase = (CTestCase*)iTestCases->At(testCaseHandle);
+
+    // Log some info if invalid handle
+    if(testCase == NULL)
+        {
+        __TRACE(KInit, ( _L( "CTestEngine::ExecuteCommandL - invalid handle. Unable to get test case to execute command [%d]"), TInt(aCommand)));
+        return;
+        }
+
+    testCase->ExecuteCommandL(aCommand, aParamsPckg);
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: GetIndexForNewTestModuleController
+
+    Description: Returns new index for test module controller.
+                 This number is appended to module controller name.
+                 This method is used when option to run every test case in 
+                 separate process is set to on.
+
+    Parameters: aTestCaseHandle: handler to test case
+    Return Values: None
+
+    Errors/Exceptions: Leaves if error happens when adding clone to the list
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::GetIndexForNewTestModuleController(void)
+    {
+    return iIndexTestModuleControllers++;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngine
+
+    Method: AddTestCaseToTestReport
+
+    Description: Get parameters from message and add test case to test report.
+
+    Parameters: aMessage: message
+    Return Values: error id
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestEngine::AddTestCaseToTestReport(const RMessage2& aMessage)
+    {
+    if(iTestReport)
+        {
+        // Read test data
+        TTestInfo testInfo;
+        TTestInfoPckg testInfoPckg(testInfo);
+    
+        TFullTestResult fullTestResult;
+        TFullTestResultPckg fullTestResultPckg(fullTestResult);
+        
+        TRAPD(err, aMessage.ReadL(0, testInfoPckg));
+        if(err)
+            {
+            __TRACE(KError, (_L("Leave when reading TTestInfo in AddTestCaseToTestReport [%d]"), err));
+            return err;
+            }
+    
+        TRAP(err, aMessage.ReadL(1, fullTestResultPckg));
+        if(err)
+            {
+            __TRACE(KError, (_L("Leave when reading TFullTestResult in AddTestCaseToTestReport [%d]"), err));
+            return err;
+            }
+            
+        TRAP(err, iTestReport->AddTestCaseResultL(testInfo, fullTestResult, aMessage.Int2()));
+        if(err)
+            {
+            __TRACE(KError, (_L("Leave from test report in AddTestCaseToTestReport [%d]"), err));
+            return err;
+            }
+        }
+    else
+        {
+        __TRACE(KError, (_L("TestReport not initialized in AddTestCaseToTestReport")));
+        return KErrNotReady;
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestEngineSubSession class member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineSubSession
+
+    Method: CTestEngineSubSession
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: CTestEngine* aEngine: in: Pointer to Test Engine
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestEngineSubSession::CTestEngineSubSession( CTestEngine* aEngine ) :
+    iTestEngine( aEngine )
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineSubSession
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestEngineSubSession::ConstructL()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineSubSession
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to Test Engine
+
+    Return Values: CTestEngineSubSession* : pointer to created CTestEngineSubSession object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEngineSubSession* CTestEngineSubSession::NewL( CTestEngine* aEngine )    
+    {
+    CTestEngineSubSession* self = new ( ELeave ) CTestEngineSubSession( aEngine );
+    CleanupClosePushL( *self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestEngineSubSession
+
+    Method: ~CTestEngineSubSession
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestEngineSubSession::~CTestEngineSubSession()
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestCase class member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: CTestCase
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: CTestEngine* aEngine: in: Pointer to Test Engine
+                CTestModuleController* aModuleController: in: Pointer to 
+                  Module Controller
+                TTestInfo& aTestInfo: in: Test info for this test case
+                CTestModuleController* aRealModuleController: in: Pointer to
+                  module controller used inside in scripter controller
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestCase::CTestCase( CTestEngine* aEngine,
+                     CTestModuleController* aModuleController,
+                     TTestInfo& aTestInfo,
+                     CTestModuleController* aRealModuleController ) :
+    iTestEngine( aEngine ),
+    iTestModule( aModuleController ),
+    iRealModuleController (aRealModuleController)
+    {
+    
+    // This method must be called to find out how
+    // many testcases are currently ongoing by increasing iTestCaseCounter. 
+    // This is a part of the implementation for 
+    //  supporting test module crashing with -15
+    iTestModule->CaseCreated();  
+
+    // Store handle to RTestServer
+    //If test scripter is used (it uses internally module controllers)
+    //then use it (real module controller). 
+    if(iRealModuleController)
+        {
+        iTestServer = iRealModuleController->Server(aTestInfo); 
+        }
+    else
+        {
+        iTestServer = iTestModule->Server( aTestInfo );
+        }
+
+    //If real test module controller is provided, increase test case count
+    if(iRealModuleController)
+        {
+        iRealModuleController->CaseCreated();
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: CTestReport* aTestReport: in: Pointer to Test Report
+                TTestInfo& aTestInfo: in: Test Info for this test case
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if RTestExecution::Open returns error
+                       Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::ConstructL( CTestReport* aTestReport,
+                           TTestInfo& aTestInfo )
+    {
+    __TRACE( KVerbose, ( _L( "CTestCase::ConstructL" ) ) );
+
+    // Open handle to RTestExecution
+    User::LeaveIfError( iTestExecution.Open( iTestServer,
+        aTestInfo.iTestCaseInfo.iCaseNumber, aTestInfo.iConfig ) );
+
+    // Make new test case runner
+    iTestCaseController = CTestCaseController::NewL( iTestEngine,
+        aTestReport, iTestModule->AtsLogger(), iTestExecution, aTestInfo );
+
+    // Make new test case printer
+    iTestCasePrint = CTestProgressNotifier::NewL( iTestEngine,
+                                                  iTestExecution );
+
+    iTestCaseEvent = CTestEventNotifier::NewL( iTestEngine, iTestExecution );
+
+    iTestCaseRemoteCmd = CTestRemoteCmdNotifier::NewL( iTestEngine,
+                                                    iTestExecution,
+                                                    iTestCaseController,
+                                                    iTestModule->AtsLogger() );
+
+    iTestCaseCommand = CTestCommandNotifier::NewL(iTestEngine, iTestExecution);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to Test Engine
+                CTestModuleController* aModuleController: in: Pointer to
+                 Module Controller
+                CTestReport* aTestReport: in: Pointer to Test Report
+                TTestInfo& aTestInfo: in: Test Info for this test case
+
+    Return Values: CTestCase* : pointer to created CTestCase object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCase* CTestCase::NewL( CTestEngine* aEngine,
+            CTestModuleController* aModuleController,
+            CTestReport* aTestReport,
+            TTestInfo& aTestInfo,
+            CTestModuleController* aRealModuleController )    
+    {
+    CTestCase* self = new ( ELeave ) CTestCase( aEngine, aModuleController, aTestInfo, aRealModuleController );
+    CleanupClosePushL( *self );
+    self->ConstructL( aTestReport, aTestInfo );
+    CleanupStack::Pop();
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: ~CTestCase
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCase::~CTestCase()
+    {
+    CloseTestCase();
+    
+    // This added method call is a part of the implementation for 
+    // supporting test module crashing with -15.
+    // It checks that can old Testmodulecontroller be deletd or not 
+	if( iTestModule != NULL )
+		{
+		iTestModule->CaseFinished();    
+		}
+	
+    //If real test module controller is provided, decrease test case count
+    if( iRealModuleController != NULL )
+        {
+        iRealModuleController->CaseFinished();
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: CloseTestCase
+
+    Description: Close session
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::CloseTestCase()
+    {
+    __TRACE( KVerbose, ( _L( "CTestCase::CloseTestCase" ) ) );
+
+    // Free allocated resources
+    delete iTestCaseController;
+    iTestCaseController = NULL;
+    delete iTestCasePrint;
+    iTestCasePrint = NULL;
+    delete iTestCaseRemoteCmd;
+    iTestCaseRemoteCmd = NULL;
+
+    delete iTestCaseEvent;
+    iTestCaseEvent = NULL;
+
+    delete iTestCaseCommand;
+    iTestCaseCommand = NULL;
+
+    iTestExecution.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: RunTestCaseL
+
+    Description: Enumerates test cases
+
+    Parameters: const RMessage& aMessage: in: Server Message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::RunTestCaseL( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestCase::RunTestCaseL" ) ) );
+    // Start active objects for running test case
+    iTestCaseController->StartL( aMessage );
+    iTestCaseEvent->Start();
+    iTestCaseCommand->Start();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: Pause
+
+    Description: Suspend the test case execution
+
+    Parameters: None
+
+    Return Values: TInt: Return value from RTestExecution::Pause
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCase::Pause()
+    {
+    __TRACE( KVerbose, ( _L( "CTestCase::Pause" ) ) );
+
+    return iTestExecution.Pause();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: Resume
+
+    Description: Resume the suspended test case execution
+
+    Parameters: None
+
+    Return Values: TInt: Return value from RTestExecution::Resume
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCase::Resume()
+    {
+    __TRACE( KVerbose, ( _L( "CTestCase::Resume" ) ) );
+
+    return iTestExecution.Resume();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: NotifyProgressL
+
+    Description: Notifies progresses from Test Module
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called StartL method leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::NotifyProgressL( const RMessage2& aMessage )
+    {
+    __TRACE( KVerbose, ( _L( "CTestCase::NotifyProgressL" ) ) );
+    iTestCasePrint->StartL( aMessage );
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: NotifyRemoteTypeL
+
+    Description: Notifies remote commands from Test Module
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called StartL method leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::NotifyRemoteTypeL( const RMessage2& aMessage )
+    {
+    
+    __TRACE( KVerbose, ( _L( "CTestCase::NotifyRemoteTypeL" ) ) );
+    iTestCaseRemoteCmd->EnableReceive( aMessage );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: NotifyRemoteMsgL
+
+    Description: Notifies remote commands from Test Module
+
+    Parameters: const RMessage& aMessage: in: Server message
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if called StartL method leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::NotifyRemoteMsgL( const RMessage2& aMessage )
+    {
+    
+    __TRACE( KVerbose, ( _L( "CTestCase::NotifyRemoteMsgL" ) ) );
+    switch( aMessage.Int1() )
+        {
+        case EStifCmdSend:
+            {
+            iTestCaseRemoteCmd->GetReceivedMsg( aMessage );
+            }
+            break;
+        case EStifCmdReceive:
+            {
+            TInt len = aMessage.Int2();
+            if( len <= 0 )
+                {
+                User::Leave( KErrGeneral );
+                }
+            HBufC8* buf = HBufC8::NewLC( len );
+
+            TPtr8 tmp = buf->Des();
+            aMessage.ReadL( 0, tmp );
+
+            TInt ret = iTestExecution.ReadRemoteCmdInfo( tmp, EStifCmdReceive );
+
+            CleanupStack::PopAndDestroy( buf );
+            
+            aMessage.Complete( ret );
+            }
+            break;
+        case EStifCmdRebootProceed:
+            {
+            TInt value = 0;
+            TPckg<TInt> tmp( value );
+            aMessage.ReadL( 0, tmp );
+
+            TInt ret = iTestExecution.ReadRemoteCmdInfo( tmp, 
+                                                         EStifCmdRebootProceed,
+                                                         value );        
+            aMessage.Complete( ret );
+            }
+            break;
+        default:
+            {
+            User::Leave( KErrGeneral );
+            }  
+        }            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: CancelAsyncRequest
+
+    Description: Asynchronous requests are canceled by this function.
+
+    Parameters: const RMessage aMessage
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::CancelAsyncRequest( const RMessage2& aMessage )
+    {
+    switch ( aMessage.Int0() )
+        {
+        case ETestCaseRunTestCase:
+            {
+            iTestCaseController->Cancel();
+            iTestCaseEvent->Cancel();
+            break;
+            }
+        case ETestCaseNotifyProgress:
+            {
+            iTestCasePrint->Cancel();
+            break;
+            }
+        case ETestCaseNotifyRemoteType:
+            {
+            iTestCaseRemoteCmd->CancelReq();
+            break;
+            }
+        case ETestCaseNotifyCommand:
+            {
+            iTestCaseCommand->Cancel();
+            break;
+            }
+        default:
+            iTestEngine->PanicClient( EBadRequest, aMessage );
+            break;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: ModuleName
+
+    Description: Return the name of Test Module.
+
+    Parameters: None
+
+    Return Values: const TFileName& : Test Module owning this test case
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestCase::ModuleName()
+    {
+    return iTestModule->ModuleName( KNullDesC );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: CtlEvent
+
+    Description: Control events
+
+    Parameters: const TEventIf& aEvent: in: Event
+                TRequestStatus& aStatus: in: Request status
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::CtlEvent( const TEventIf& aEvent, TRequestStatus& aStatus )
+    {
+    __ASSERT_ALWAYS( iTestCaseEvent, User::Panic( _L( "TestEngine event panic" ), KErrArgument ) );
+        
+    iTestCaseEvent->CtlEvent( aEvent, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: CheckCtlEvent
+
+    Description: Check if CtlEvent should be called
+
+    Parameters: const TEventIf& aEvent: in: Event
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestCase::CheckCtlEvent( const TEventIf& aEvent )
+    {
+    return iTestCaseEvent->CheckCtlEvent( aEvent );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: Logger
+
+    Description: Return the pointer to Logger.
+
+    Parameters: None
+
+    Return Values: CStifLogger*: Pointer to StifLogger
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CStifLogger* CTestCase::Logger()
+    {
+    return iTestEngine->Logger();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: ExecuteCommaandL
+
+    Description: Executes command received from test case.
+
+    Parameters: aStifCommand command to be executed
+                aParam1      parameter to command
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::ExecuteCommandL(TCommand aCommand, TDesC8& aParamsPckg)
+    {
+    switch(aCommand)
+        {
+        case EStopExecution:
+            {
+            //Unpack received parameters
+            TStopExecutionCommandParams par;
+            TStopExecutionCommandParamsPckg parPack(par);
+            parPack.Copy(aParamsPckg);
+
+            __TRACE(KVerbose, (_L("CTestCase::ExecuteCommandL command [%d] type [%d] code [%d]"), TInt(aCommand), TInt(par.iType), par.iCode));
+
+            iTestCaseController->Suicide(par.iType, par.iCode);
+            break;
+            }
+        default:
+            __TRACE(KVerbose, (_L("CTestCase::ExecuteCommandL unknown command [%d]"), TInt(aCommand)));
+            return;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: GetModuleControllers
+
+    Description: Return module controller and real module controller
+
+    Parameters: aRealModuleController: out: real module controller
+
+    Return Values: module controller
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleController* CTestCase::GetModuleControllers(CTestModuleController** aRealModuleController)
+    {
+    *aRealModuleController = iRealModuleController;
+    return iTestModule;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: ResetModuleController
+
+    Description: Set new module controller for test case (only in case when 
+                 original controller crashed)
+
+    Parameters: aModuleController: in: new module controller
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::ResetModuleController(CTestModuleController* aModuleController)
+    {
+    iTestModule = aModuleController;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCase
+
+    Method: ResetRealModuleController
+
+    Description: Set new real module controller for test case (only in case 
+                 when original controller crashed).
+
+    Parameters: aRealModuleController: in: new real module controller
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCase::ResetRealModuleController(CTestModuleController* aRealModuleController)
+    {
+    iRealModuleController = aRealModuleController;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    Default constructor
+
+-------------------------------------------------------------------------------
+*/
+CTestReportSettings::CTestReportSettings()
+    {
+    iCreateTestReport = ETrue;
+    iPath = NULL;
+    iName = NULL;
+    iFormat = CStifLogger::ETxt;
+    iOutput = CStifLogger::EFile;
+    iOverwrite = ETrue; 
+    iXML = EFalse;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    Two-phased constructor.
+
+-------------------------------------------------------------------------------
+*/
+CTestReportSettings* CTestReportSettings::NewL()
+    {
+    CTestReportSettings* self = new ( ELeave ) CTestReportSettings();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    Symbian OS second phase constructor
+
+-------------------------------------------------------------------------------
+*/
+void CTestReportSettings::ConstructL()
+    {
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    Destructor
+
+-------------------------------------------------------------------------------
+*/
+CTestReportSettings::~CTestReportSettings()
+    { 
+    delete iPath; 
+    iPath = NULL;
+    delete iName;
+    iName = NULL;
+    } 
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CRebootParams class member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRebootParams
+
+    Method: CRebootParams
+
+    Description: Default constructor
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CRebootParams::CRebootParams()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRebootParams
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if RTestExecution::Open returns error
+                       Leaves if some of called leaving methods leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CRebootParams::ConstructL()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRebootParams
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: none
+    
+    Return Values: CRebootParams* : pointer to created CRebootParams object
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CRebootParams* CRebootParams::NewL()    
+    {
+    
+    CRebootParams* self = new ( ELeave ) CRebootParams();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRebootParams
+
+    Method: ~CRebootParams
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CRebootParams::~CRebootParams()
+    {
+    
+    delete iTestModuleBuf;
+    iTestModuleBuf = 0;
+    delete iTestCaseFileBuf;
+    iTestCaseFileBuf = 0;
+    delete iTestCaseTitleBuf;
+    iTestCaseTitleBuf = 0;
+    delete iStateNameBuf;
+    iStateNameBuf = 0;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRebootParams
+
+    Method: SetTestModuleNameL
+
+    Description: Setter
+
+    Parameters: const TDesC& aName: in: name to set
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation fails
+    
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+void CRebootParams::SetTestModuleNameL( const TDesC& aName )
+    {
+    
+    delete iTestModuleBuf;
+    iTestModuleBuf = 0;
+    iTestModuleBuf = aName.AllocLC();
+    iTestModule.Set( iTestModuleBuf->Des() );
+    CleanupStack::Pop( iTestModuleBuf );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRebootParams
+
+    Method: SetTestModuleNameL
+
+    Description: Setter
+
+    Parameters: const TDesC& aName: in: name to set
+
+    Return Values: None
+
+    Errors/Exceptions:  Leaves if memory allocation fails
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+void CRebootParams::SetTestCaseFileNameL( const TDesC& aName )
+    {
+    
+    delete iTestCaseFileBuf;
+    iTestCaseFileBuf = 0;
+    iTestCaseFileBuf = aName.AllocLC();
+    iTestCaseFile.Set( iTestCaseFileBuf->Des() );
+    CleanupStack::Pop( iTestCaseFileBuf );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRebootParams
+
+    Method: SetTestModuleNameL
+
+    Description: Setter
+
+    Parameters: const TDesC& aName: in: name to set
+
+    Return Values: None
+
+    Errors/Exceptions:  Leaves if memory allocation fails
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+void CRebootParams::SetTestCaseTitleL( const TDesC& aName )
+    {
+    
+    delete iTestCaseTitleBuf;
+    iTestCaseTitleBuf = 0;
+    iTestCaseTitleBuf = aName.AllocLC();
+    iTestCaseTitle.Set( iTestCaseTitleBuf->Des() );
+    CleanupStack::Pop( iTestCaseTitleBuf );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRebootParams
+
+    Method: SetTestModuleNameL
+
+    Description: Setter
+
+    Parameters: const TDesC& aName: in: name to set
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation fails
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+void CRebootParams::SetTestCaseStateL( const TDesC& aName )
+    {
+    
+    delete iStateNameBuf;
+    iStateNameBuf = 0;
+    iStateNameBuf = aName.AllocLC();
+    iStateName.Set( iStateNameBuf->Des() );
+    CleanupStack::Pop( iStateNameBuf );
+    
+    }
+
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of TEventMsg class member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEventMsg
+
+    Method: TEventMsg
+
+    Description: Default constructor
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/    
+TEventMsg::TEventMsg():
+    TEventIf(),
+    iWaitPending(EFalse), 
+    iStateEventPending(EFalse),
+    iStatus( NULL )
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEventMsg
+
+    Method: ~TEventMsg
+
+    Description: Destructor
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/    
+TEventMsg::~TEventMsg()
+    {
+    if( iWaitPending )
+        {
+        iWaitMsg.Complete( KErrCancel );
+        iWaitPending = EFalse;
+        }
+        
+    if( iStatus )
+        {
+        User::RequestComplete( iStatus, KErrCancel );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEventMsg
+
+    Method: Set
+
+    Description: Set event.
+    
+    Parameters: TEventType aEventType: in: Event type
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/    
+void TEventMsg::Set( TEventType aEventType )
+    {
+    iEventType = aEventType;
+    if( aEventType == EState )
+        {
+        iStateEventPending = ETrue;
+        }
+    if( iWaitPending )
+        {
+        TEventIf event;
+        event.Copy( *this );
+        TEventIfPckg eventIfPckg( event );
+        iWaitMsg.WriteL( 0, eventIfPckg );
+
+        iWaitMsg.Complete( KErrNone );
+        iWaitPending = EFalse;
+        }
+    } 
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEventMsg
+
+    Method: Wait
+
+    Description: Wait event.
+    
+    Parameters: const RMessage& aMessage: in: Message
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void TEventMsg::Wait( const RMessage2& aMessage )
+    { 
+    if( iStateEventPending )
+        {
+        TEventIf event;
+        event.Copy( *this );
+        TEventIfPckg eventIfPckg( event );
+        aMessage.WriteL( 0, eventIfPckg );
+        aMessage.Complete( KErrNone );
+        }
+    else
+        {
+        iWaitMsg = aMessage;
+        iWaitPending = ETrue;
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEventMsg
+
+    Method: CancelWait
+
+    Description: Cancel pending Wait
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/    
+void TEventMsg::CancelWait()
+    {
+    if( iWaitPending )
+        {
+        iWaitMsg.Complete( KErrCancel );
+        iWaitPending = EFalse;
+        } 
+    } 
+             
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEventMsg
+
+    Method: Release
+
+    Description: Release event. Unset released.
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/    
+void TEventMsg::Release()
+    { 
+    
+    if( iStatus )
+        {
+        User::RequestComplete( iStatus, KErrNone );
+        }
+        
+    } 
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEventMsg
+
+    Method: Unset
+
+    Description: Unset event. Blocks until Release is called.
+    
+    Parameters: TRequestStatus& aStatus: in: Status 
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/    
+void TEventMsg::Unset( TRequestStatus& aStatus )
+    { 
+    
+    iStatus = &aStatus;
+    
+    } 
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Function: StartEngine
+
+    Description: This is called from the client.
+
+    Parameters: None
+
+    Return Values: TInt KErrNone: No errors occured
+                        KErrNoMemory: Memory is too low to create Test Engine
+                        Other error code: Error got from iEngineThread.Create()
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt StartEngine()
+    {
+    __UHEAP_MARK;
+
+    // check server not already started
+    TFindServer findTestEngineServer( KTestEngineName );
+    TFullName name;
+    if ( findTestEngineServer.Next( name ) == KErrNone )
+        {   
+        // Server already started, nothing to do    
+        __UHEAP_MARKEND;
+        return KErrNone;
+        }
+
+    // Construct start-up information object
+    TThreadStartTestEngine* startInfo = new TThreadStartTestEngine();
+    if ( startInfo == NULL )
+        {
+        __UHEAP_MARKEND;
+        return KErrNoMemory;
+        }
+
+    startInfo->iStarted.CreateLocal( 0 );     // Create start-up semaphore
+
+    // Create thread    
+    TInt ret = startInfo->iEngineThread.Create(
+        KTestEngineName ,                               // name of thread
+        CTestEngineServer::ThreadFunction,              // thread function
+        KDefaultStackSize*4,                            // stack
+        KTestEngineMinHeapSize,KTestEngineMaxHeapSize*4,// Heap
+        startInfo                                       // parameter to thread
+                                                        // function
+        );
+
+    if ( ret != KErrNone )
+        {
+        startInfo->iStarted.Close();
+        delete startInfo;
+        __UHEAP_MARKEND;
+        return ret;
+        }
+
+    // Now start thread
+    startInfo->iEngineThread.SetPriority( EPriorityMuchMore );  // set its
+                                                                // priority
+    startInfo->iEngineThread.Resume();                          // kick it
+                                                                // into life
+
+    // Wait until the thread is started
+    startInfo->iStarted.Wait(); 
+
+    // Clean-up 
+    startInfo->iEngineThread.Close();
+    startInfo->iStarted.Close(); 
+
+
+    delete startInfo;
+
+    __UHEAP_MARKEND;
+
+    return KErrNone;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/TestEngineClient.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,852 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* RTestEngineServer class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include "TestEngineClient.h"
+#include "TestEngineCommon.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngineServer
+
+    Method: Connect
+
+    Description: Connect method creates new RTestEngineServer session.
+
+    RTestEngineServer session is used to manage the test case execution.
+
+    Parameters: None
+
+    Return Values: TInt KErrNone : TestEngineServer created successfully
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngineServer::Connect()
+    {
+    TInt ret = StartEngine();
+    if ( ret == KErrNone)
+        {
+        ret = CreateSession( KTestEngineName, Version() );
+        }
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngineServer
+
+    Method: Version
+
+    Description: Return client side version number from RTestEngineServer.
+
+    Parameters: None
+
+    Return Values: TVersion : Version number from RTestEngineServer
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TVersion RTestEngineServer::Version() const
+    {
+    return ( TVersion( KTestEngineMajorVersionNumber,
+        KTestEngineMinorVersionNumber, KTestEngineBuildVersionNumber ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngineServer
+
+    Method: Close
+
+    Description: Closes the RTestEngineServer session.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestEngineServer::Close()
+    {
+    // Check that server is connected
+    if ( Handle() != 0 )
+        {
+        TIpcArgs args( TIpcArgs::ENothing, TIpcArgs::ENothing, TIpcArgs::ENothing );
+        SendReceive( ETestEngineServerCloseSession, args );
+        }
+    RSessionBase::Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of RTestEngine class member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: Open
+
+    Description: Open creates a subsession to TestEngine.
+
+    Parameters: RTestEngineServer& aServer : Handle to Test Engine Server
+                const TFileName& aIniFile : Ini file to be used for 
+                 initialization of the Test Engine
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::Open( RTestEngineServer& aServer,
+                                 const TFileName& aIniFile )
+    {
+    TIpcArgs args( &aIniFile, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return CreateSubSession( aServer, ETestEngineCreateSubSession, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: Close
+
+    Description: Close the RTestEngine subsession.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestEngine::Close()
+    {
+    RSubSessionBase::CloseSubSession( ETestEngineCloseSubSession );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: SetAttribute
+
+    Description: Sets attributes to Test Framework
+
+    Parameters: TAttribute aAttribute: in: Attribute type
+                const TDesC& aValue: in: Attribute value
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::SetAttribute( TAttribute aAttribute,
+                                          const TDesC& aValue )
+    {
+    TIpcArgs args( aAttribute, &aValue, TIpcArgs::ENothing );
+    return SendReceive( ETestEngineSetAttribute, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: AddTestModule
+
+    Description: Load dynamically a new Test Module to the Test Framework.
+
+    Parameters: const TName& aTestModule : Name of the Test Module to be added
+                const TFileName& aIniFile : Initialization file of Test Module
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::AddTestModule( const TName& aTestModule,
+                                          const TFileName& aIniFile )
+    {
+    TIpcArgs args( &aTestModule, &aIniFile, TIpcArgs::ENothing );
+    return SendReceive( ETestEngineAddTestModule, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: RemoveTestModule
+
+    Description: Remove the existing Test Module from the Test Framework.
+
+    Parameters: const TName& aTestModule : Name of the Test Module to be 
+                                           removed
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::RemoveTestModule( const TName& aTestModule )
+    {
+    TIpcArgs args( &aTestModule, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestEngineRemoveTestModule, args );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: AddConfigFile
+
+    Description: Add new config file to Test Module.
+
+    Parameters: const TName& aTestModule : Name of Test Module where the config
+                 file will be added
+                const TFileName& aConfigFile : Name of config file to be added
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::AddConfigFile( const TName& aTestModule,
+                                          const TFileName& aConfigFile )
+    {
+    TIpcArgs args( &aTestModule, &aConfigFile, TIpcArgs::ENothing );
+    return SendReceive( ETestEngineAddConfigFile, args );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: RemoveConfigFile
+
+    Description: Remove config file from Test Module.
+
+    Parameters: const TName& aTestModule : Test Module name
+                const TFileName& aConfigFile : Name of config file to be removed
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::RemoveConfigFile( const TName& aTestModule,
+                                             const TFileName& aConfigFile )
+    {
+    TIpcArgs args( &aTestModule, &aConfigFile, TIpcArgs::ENothing );
+    return SendReceive( ETestEngineRemoveConfigFile, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: EnumerateTestCases
+
+    Description: First phase of two-phased test case query operation.
+
+    Test cases are inquired by two-phased operation calling first the 
+    EnumerateTestCases method and then the GetTestCases. 
+
+    Parameters: TInt& aCount : Test case count
+                TRequestStatus& aStatus : Request status
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestEngine::EnumerateTestCases( TCaseCount& aCount,
+                                              TRequestStatus& aStatus )
+    {
+    TIpcArgs args( &aCount, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    SendReceive( ETestEngineEnumerateTestCases, args, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: GetTestCases
+
+    Description: Second phase of two-phased test case query operation.
+
+    GetTestCases retrieves test cases from Test Modules to aTestCases that is
+    a list consisting of several TTestInfo objects.
+
+    Parameters: CArrayFixFlat<TTestInfo>& aTestCaseBuffer : Test case array
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::GetTestCases( 
+                     CFixedFlatArray<TTestInfo>& aTestCaseBuffer )
+    {
+    // Construct and send message
+    TIpcArgs args( &aTestCaseBuffer.Des(), TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestEngineGetTestCases, args );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: ErrorNotification
+
+    Description: Obtains error notifications from Test Engine and Test
+    Servers via Test Engine.
+
+    Parameters: TTestProgressPckg& aError : Error package
+                TRequestStatus& aStatus : Request status
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C void RTestEngine::ErrorNotification( TErrorNotificationPckg& aError,
+                                              TRequestStatus& aStatus )
+    {
+    TIpcArgs args( &aError, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    SendReceive( ETestEngineErrorNotification, args, aStatus );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: CancelAsyncRequest
+
+    Description: Asynchronous requests can be canceled by this function.
+
+    Parameters: TInt aReqToCancel : Request to be cancelled
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::CancelAsyncRequest( TInt aReqToCancel )
+    {
+    TIpcArgs args( aReqToCancel, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestEngineCancelAsyncRequest, args );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: Event
+
+    Description: Used to control STIF Test Framework event system.
+
+    Parameters: TEventIfPckg& aEvent : in : Event information
+                 TRequestStatus& aStatus : in :  Request status
+
+    Return Values: TInt KErrNone : No errors occurred
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestEngine::Event( TEventIfPckg& aEvent, 
+                                  TRequestStatus& aStatus )
+    {
+    TIpcArgs args( &aEvent, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    SendReceive( ETestEngineEvent, args, aStatus );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: OpenLoggerSession
+
+    Description: Open created subsession to TestEngine.
+
+    Parameters: RTestEngineServer& aServer : Handle to Test Engine Server
+                TLoggerSettings& aLoggerSettings: in: Logger's overwrite struct
+
+    Return Values: TInt KErrNone: TestEngine opened and initialized
+                                  succesfully
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::OpenLoggerSession( RTestEngineServer& aServer, 
+                                            TLoggerSettings& aLoggerSettings )
+    {
+    // Package
+    TPckg<TLoggerSettings> loggerSettingsPckg( aLoggerSettings );
+
+    TIpcArgs args( &loggerSettingsPckg, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    // Goes to CTestEngine's DispatchMessageL() method
+    CreateSubSession( aServer, ETestEngineLoggerSettings, args );
+    RSubSessionBase::CloseSubSession( ETestEngineCloseLoggerSettings );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestEngine
+
+    Method: AddTestCaseResultToTestReport
+
+    Description: Sends info about executed test cases to test engine, which
+                 will forward it to test report.
+                 This is used when after reboot UIStore reads info about 
+                 executed test cases before reboot.
+
+    Parameters: TTestIngo& aTestInfo : test info structure
+                TFullTestResult& aTestResult: test result structure
+                TInt aError: error
+
+    Return Values: TInt error code returned by test engine
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestEngine::AddTestCaseResultToTestReport(const TTestInfo& aTestInfo,
+                                                         const TFullTestResult& aTestResult,
+                                                         const TInt aError)
+    {
+    // Create packages
+    TTestInfoPckg testInfoPckg(aTestInfo);
+    TFullTestResultPckg fullTestResultPckg(aTestResult);
+
+    // Create argument list
+    TIpcArgs args(&testInfoPckg, &fullTestResultPckg, aError);
+
+    // Send it to test engine
+    TInt res = SendReceive(ETestEngineReportTestCase, args);
+
+    return res;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of RTestCase class member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: Open
+
+    Description: Open creates a subsession to TestCase.
+
+    Parameters: RTestEngineServer& aServer : Handle to Test Engine Server
+                const TTestInfoPckg& aTestCaseInfo : TTestInfoPckg : Test info
+                                                                     package
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestCase::Open( RTestEngineServer& aServer,
+                              const TTestInfoPckg& aTestCaseInfo )
+    {
+    TIpcArgs args( &aTestCaseInfo, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return CreateSubSession( aServer, ETestCaseCreateSubSession, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: Close
+
+    Description: Close the RTestCase subsession.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestCase::Close()
+    {
+    RSubSessionBase::CloseSubSession( ETestCaseCloseSubSession );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: RunTestCase
+
+    Description: Run a test case asynchronously.
+
+    Parameters: TFullTestResultPckg& aTestResult : TFullTestResult :
+                 Test Result package
+                TRequestStatus& aStatus : Request status
+
+    Return Values: TInt KErrNone : Test case could be run
+                        Other error code : Reason the test case couldn't be run
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestCase::RunTestCase( TFullTestResultPckg& aTestResult,
+                                     TRequestStatus& aStatus )
+    {
+    TIpcArgs args( &aTestResult, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    SendReceive( ETestCaseRunTestCase, args, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: RunTestCase
+
+    Description: Run a test case asynchronously.
+
+    Parameters: TFullTestResultPckg& aTestResult : TFullTestResult :
+                 Test Result package
+                const TDesC& aTestCaseArgs: Test case arguments
+                TRequestStatus& aStatus : Request status
+
+    Return Values: TInt KErrNone : Test case could be run
+                        Other error code : Reason the test case couldn't be run
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestCase::RunTestCase( TFullTestResultPckg& aTestResult,
+                                      const TDesC& aTestCaseArgs,
+                                      TRequestStatus& aStatus )
+    {
+    TIpcArgs args( &aTestResult, &aTestCaseArgs, TIpcArgs::ENothing );
+    SendReceive( ETestCaseRunTestCase, args, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: Pause
+
+    Description: Pause suspends the execution of the test case.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestCase::Pause()
+    {
+    TIpcArgs args( TIpcArgs::ENothing, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestCasePause, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: Resume
+
+    Description: Resume the test case suspended previously.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestCase::Resume()
+    {
+    TIpcArgs args( TIpcArgs::ENothing, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestCaseResume, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: NotifyProgress
+
+    Description: Request different progress information from the test case.
+
+    Parameters: TTestProgressPckg& aProgress : TTestProgress : Test Progress
+                                                               package
+                TRequestStatus& aStatus : Request status
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestCase::NotifyProgress( TTestProgressPckg& aProgress,
+                                         TRequestStatus& aStatus )
+    {
+    TIpcArgs args( &aProgress, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    SendReceive( ETestCaseNotifyProgress, args, aStatus );
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: NotifyRemoteType
+
+    Description: Request remote commands information from the test case.
+
+    Parameters: TRemoteCommandPckg& aType: in: Request type
+                TRequestStatus& aStatus : Request status
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestCase::NotifyRemoteType( TStifCommandPckg& aType,
+                                           TPckg<TInt>& aMsgSize,
+                                           TRequestStatus& aStatus )
+    {
+    TIpcArgs args( &aType, &aMsgSize, TIpcArgs::ENothing );
+    SendReceive( ETestCaseNotifyRemoteType, args, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: NotifyRemoteMsg
+
+    Description: Request remote commands information from the test case.
+
+    Parameters: TDesC& aMessage: in: Message buffer
+                TRemoteCmdType aType: in: Message direction
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestCase::NotifyRemoteMsg( TDes8& aMessage,
+                                          TStifCommand aType )
+    {
+    TIpcArgs args( &aMessage, aType, aMessage.Length() );
+    return SendReceive( ETestCaseNotifyRemoteMsg, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestCase
+
+    Method: CancelAsyncRequest
+
+    Description: Asynchronous requests can be canceled by this function.
+
+    Parameters: TInt aReqToCancel : Request to be cancelled
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestCase::CancelAsyncRequest( TInt aReqToCancel )
+    {
+    TIpcArgs args( aReqToCancel, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestCaseCancelAsyncRequest, args );
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/TestModuleController.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3107 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestModuleController class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include <stifinternal/TestServerClient.h>
+#include <StifLogger.h>
+#include "TestEngine.h"
+#include "TestModuleController.h"
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+#define LOGGER iEngine->Logger()
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: CTestModuleController
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleController::CTestModuleController( CTestEngine* aEngine ) :
+    CActive( CActive::EPriorityStandard ),
+    iEngine( aEngine ),
+    iState( ETestModuleIdle )
+    {
+    CActiveScheduler::Add( this );
+    iTestScripterController = NULL;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: const TName& aName: in: Test module name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation for iConfigFiles fails
+                       Leaves if memory allocation for iTestCaseArray fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::ConstructL( 
+                            const TName& aName,
+                            TBool aAfterReboot,
+                            CTestScripterController* aTestScripterController )
+    {
+    iTestScripterController = aTestScripterController;
+    iTestScripterIndicator = 0;
+    
+    iAfterReboot = aAfterReboot;
+
+    __TRACE ( KInit, ( _L( "Creating CTestModuleController [%S]" ), &aName ) );
+
+    iTestCaseArray = RPointerArray<TTestCaseArray>();
+
+    // Check aName length
+    if( aName.Length() <= 0 )
+        {
+        iEngine->LeaveWithNotifyL( KErrArgument );
+        }
+
+    // Remove optional '.DLL' from file name
+    TName name = aName;
+    name.LowerCase();
+    TParse parse;
+    parse.Set( name, NULL, NULL );
+
+    if ( parse.Ext() == _L(".dll") )
+        {
+        const TInt len = parse.Ext().Length();
+        name.Delete ( name.Length()-len, len );
+        }
+
+    iName = name.AllocL();
+
+    // HBufC to TPtrC
+    TPtrC atsName;
+
+    TFileName newNameBuffer;
+    TInt check = GenerateModuleName( iName->Des(), newNameBuffer );
+    if( check == KErrNone )
+        {
+        // Load the module(TestScripter)
+        atsName.Set( newNameBuffer );
+        }
+    else
+        {
+        // Load the module(Others)
+        atsName.Set( iName->Des() );
+        }
+
+    // Moved the implementation to a new function, ConstructASTLoggerL, due to
+    // CW 3.0 compiler error with multiple TRAPDs
+    TRAPD(err, ConstructASTLoggerL( atsName, aAfterReboot));
+
+    if( err != KErrNone )
+        {
+         __TRACE ( KError, ( _L( "CTestModuleController[%S]::ConstructL: Creation of ATS logger failed" ), iName ) );
+        iEngine->LeaveWithNotifyL( err, _L("Creation of ATS logger failed") );
+        }
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: ConstructASTLoggerL
+
+    Description: Construct ATS logger
+
+    Parameters: TDesC& atsName, TBool& aAfterReboot
+
+    Return Values: TInt
+
+    Errors/Exceptions: Leaves if error got from ATS logger NewL
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+
+TInt CTestModuleController::ConstructASTLoggerL( TDesC& atsName, TBool& aAfterReboot )
+    {
+    TRAPD( err, iAtsLogger = CAtsLogger::NewL( atsName, aAfterReboot ); );
+    if( err == KErrNotFound && aAfterReboot )
+        {
+        // If file does not exist, create new 
+        aAfterReboot = EFalse;
+        iAtsLogger = CAtsLogger::NewL( atsName, aAfterReboot );
+        }
+    User::LeaveIfError( err );
+    iAtsLogger->SetFullReporting( ETrue );
+    if( aAfterReboot )
+        {
+        iAtsLogger->ContinueAfterRebootL();
+        }
+    else
+        {
+        // Begin reporting
+        iAtsLogger->BeginTestReportL();
+          
+        // Begin test set
+        iAtsLogger->BeginTestSetL();
+        }
+    return KErrNone;
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: InitL
+
+    Description: Initialize test module.
+
+    Parameters: TFileName& aIniFile: in: Initialization file of Test Module
+                const TDesC& aConfigFile: in: Test case(config) file name(Used 
+                in TestScripter case).
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if error got from Test Server
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::InitL( TFileName& aIniFile, 
+                                    const TDesC& aConfigFile )
+    {
+    __TRACE( KInit, (_L( "Initialising test module [%S] with initialization file [%S]" ),
+        iName, &aIniFile ) );
+
+    // HBufC to TPtrC
+    TPtrC name( iName->Des() );
+
+    // Connect to server
+    TInt r = iServer.Connect( name, aConfigFile );
+
+    if ( r != KErrNone )
+        {
+        if ( r == KErrBadName )
+            {
+            __TRACE( KError, ( CStifLogger::ERed, _L( "Test Module name or Configuration File name is too long: [%S]" ), &name) );
+            LeaveWithNotifyL( r,  _L( "Test Module name or Configuration File name is too long." ) );
+            }
+        __TRACE( KError, ( CStifLogger::ERed, _L( "Can't connect to test module [%S], IniFile [%S]" ), &name, &aIniFile ) );
+        LeaveWithNotifyL( r,  _L( "Can't connect to test module" ) );
+        }
+
+    // Open session 
+    r = iModule.Open( iServer, aIniFile );
+    if ( r != KErrNone )
+        {
+        __TRACE( KError, ( CStifLogger::ERed, _L( "Can't open session to test module [%S], IniFile=[%S]" ), &name, &aIniFile ) );
+        LeaveWithNotifyL( r, _L( "Can't open session to test module" ) );
+        }
+
+    iErrorPrinter = CErrorPrinter::NewL( iEngine );
+    iErrorPrinter->StartL( iModule );
+
+    iServerStateHandler = CServerStateHandler::NewL( iEngine, this );
+    iServerStateHandler->StartL( iServer );
+    __TRACE( KInit, (_L( "Initialising test module [%S] with initialization file [%S] done" ),
+        iName, &aIniFile ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: CTestEngine object.
+                const TName& aName: in: module name.
+                TBool aAfterReboot: in: reboot indicator.
+                TBool aCreateTestScripterCont: in: Indications to
+                TestModule or TestScripter creation
+                CTestScripterController* aTestScripterController: in:
+                CTestEngine object.
+
+
+    Return Values: CTestModuleController* : pointer to created object
+
+    Errors/Exceptions: Leaves if called ConstructL method leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleController* CTestModuleController::NewL( 
+                            CTestEngine* aEngine,
+                            const TName& aName,
+                            TBool aAfterReboot,
+                            TBool aCreateTestScripterCont,
+                            CTestScripterController* aTestScripterController )
+    {
+    // Create CTestScripterController
+    if( aCreateTestScripterCont )
+        {
+        CTestScripterController* testScripterController = NULL;
+        testScripterController = CTestScripterController::NewL(
+            aEngine, aName, aAfterReboot );
+        return testScripterController;  
+        }
+
+
+    CTestModuleController* self =
+        new ( ELeave ) CTestModuleController( aEngine );
+    CleanupStack::PushL( self );
+    self->ConstructL( aName, aAfterReboot, aTestScripterController );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: ~CTestModuleController
+
+    Description: Destructor
+
+    Deallocate all allocated resources
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleController::~CTestModuleController()
+    {
+
+    // If CTestScripterController is created there is deleted base class(
+    // CTestModuleController) also and this has no iName.
+    if( iName )
+        {
+        __TRACE(KVerbose, (_L( "Deleting CTestModuleController [%S]" ), iName ) );
+        }
+
+    Cancel();
+
+    // If CTestScripterController is created there is deleted base class(
+    // CTestModuleController) also and this has no iAtsLogger.
+    if( iAtsLogger )
+        {
+        // End test set
+        TRAPD( err, iAtsLogger->EndTestSetL() );
+        // End AtsLogger reporting, has to be trapped in destructor
+        TRAPD( err2, iAtsLogger->EndTestReportL() );
+        if( ( err != KErrNone ) || ( err2 != KErrNone ) )
+            {
+            // Print error if error got from trap
+            __TRACE( KError, ( 
+                _L( "Destructor of CTestModuleController [%S]: XML log closing failed" ),
+                iName ) );
+            }
+        }
+
+    // Delete Atslogger
+    delete iAtsLogger;
+
+    // Stop error printer
+    delete iErrorPrinter;
+    iErrorPrinter = NULL;
+    // Delete server state handler
+    delete iServerStateHandler;
+    iServerStateHandler = NULL;
+
+    // Close RTestModule session
+    iModule.Close();
+    // Close RTestServer session
+    iServer.Close();
+
+    // Release the test case array
+    iTestCaseArray.Close();
+
+    // Release the config file array
+    iConfigFiles.ResetAndDestroy();
+    iConfigFiles.Close();
+
+    // Release the config file array
+    iFailedEnumerateConfig.ResetAndDestroy();
+    iFailedEnumerateConfig.Close();
+    
+    // Release the children array
+    iChildrenControllers.ResetAndDestroy();
+    iChildrenControllers.Close();
+
+    delete iName;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: AddConfigFileL
+
+    Description: Add config file
+
+    Parameters: TFileName& aConfigFile: in: Config file for Test Module
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if AppendL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::AddConfigFileL( TFileName& aConfigFile )
+    {
+    __TRACE( KInit,
+        ( _L( "CTestModuleController::AddConfigFileL [%S] aConfigFile=[%S]" ),
+        iName, &aConfigFile ) );
+    // Check that this config file does not already exists
+    for ( TInt i = 0; i < iConfigFiles.Count(); i++ )
+        {
+        // HBufC to TPtrC
+        TPtrC name( iConfigFiles[i]->Des() );
+        if ( KErrNone == aConfigFile.CompareF( name ) )
+            {
+            LeaveWithNotifyL( KErrAlreadyExists,  
+                _L( "Adding config file failed: Config file already exists" ) );
+            }
+        }
+    HBufC* configFile = aConfigFile.AllocLC();
+
+    User::LeaveIfError( iConfigFiles.Append( configFile ) );
+    CleanupStack::Pop( configFile );
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: RemoveConfigFileL
+
+    Description: Remove config file
+
+    Parameters: TFileName& aConfigFile: in: Config file name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::RemoveConfigFileL( TFileName& aConfigFile )
+    {
+    __TRACE( KInit, ( 
+        _L( "CTestModuleController::RemoveConfigFileL [%S] aConfigFile=[%S]" ),
+        iName, &aConfigFile ) );
+    // Find config file
+    for ( TInt i = 0; i < iConfigFiles.Count(); i++ )
+        {
+        // HBufC to TPtrC
+        TPtrC name( iConfigFiles[i]->Des() );
+        if ( KErrNone == aConfigFile.CompareF( name ) )
+            {
+            HBufC* configFile = iConfigFiles[i];
+            iConfigFiles.Remove(i);
+            delete configFile;
+            // Cancel enumerate and free test cases
+            Cancel();
+            FreeTestCases();
+            return;
+            }
+        }
+        
+    LeaveWithNotifyL( KErrNotFound, 
+        _L( "Removing config file failed: Config file not found" ) );
+            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: StartEnumerateL
+
+    Description: Start test case enumeration
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::StartEnumerateL()
+    {
+    __TRACE( KVerbose, ( 
+        _L( "CTestModuleController::StartEnumerateL [%S]" ), iName ) ); 
+    iTestCaseCount = 0;
+    iEnumerateCount = 0;
+    iFailedEnumerateCount = 0;
+    iFailedEnumerateConfig.Reset();
+    iEnumerateComplete = EFalse;
+
+    iState = ETestModuleEnumerateCases;
+
+    if ( iConfigFiles.Count() > 0 )
+        {
+        // HBufC to TPtrC
+        iEnumConfigFile.Set( iConfigFiles[0]->Des() );
+        }
+
+    __TRACE( KInit, ( 
+        _L( "Getting testcases from module [%S], test case file [%S]" ),
+        iName, &iEnumConfigFile ) );
+
+    SetActive();
+    iModule.EnumerateTestCases( iEnumConfigFile, iEnumResultPackage, iStatus );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if iStatus is not KErrNone
+                       Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::RunL()
+    {
+
+    // If CTestScripterController is used then move execution to the
+    // CTestScripterController size
+    if( iTestScripterController )
+        {
+        iTestScripterController->RunLEmulator( this );
+        return;
+        }
+
+    __TRACE( KVerbose, ( _L( "CTestModuleController::RunL [%S] [iStatus = %d]"),
+        iName, iStatus.Int() ) );
+
+    // Note:
+    // If test case not found there may be existing cases from previous
+    // enumerations, so those cases are valid. e.g. case: "add test case file",
+    // "add test case file that not exist" and "get test cases".
+
+    TInt ret( KErrNone );
+    // Check that request was successful
+    if( iStatus.Int() == KErrNone )
+        {
+        // Get enumerated test cases and append them to array
+        CFixedFlatArray<TTestCaseInfo>* testCases = 
+            CFixedFlatArray<TTestCaseInfo>::NewL( iEnumResultPackage() );
+        CleanupStack::PushL( testCases );
+        ret = iModule.GetTestCases( *testCases );
+        __TRACE( KInit, ( _L( "RunL()'s GetTestCases method returns: %d" ), ret ) );
+
+        iTestCaseCount += testCases->Count();
+
+        if ( testCases->Count() == 0 )
+            {
+
+            if (iConfigFiles.Count() > 0)
+                {
+                __TRACE( KInit, ( CStifLogger::EBold, 
+                    _L( "Module [%S], test case file [%S] returned 0 cases" ),
+                    iName,  iConfigFiles[iEnumerateCount] ) );
+                }
+            else
+                {
+                __TRACE( KInit, ( CStifLogger::EBold, 
+                    _L( "Module [%S] without test case file, returned 0 cases" ),
+                    iName ) );
+                }
+            iEngine->ErrorPrint( 1, _L("Someone returned 0 test cases. Check testengine log"));
+            iAtsLogger->CommentL( _L("Test module returned 0 test cases") );   
+            }
+
+        // Store test cases for later use
+        User::LeaveIfError( iTestCaseArray.Append( testCases ) );
+        CleanupStack::Pop( testCases );
+        
+        }
+    else
+        {
+        // Calculate failed enumeration count
+        iFailedEnumerateCount++;
+        // Add failed config(test case) file to array for later removing
+        if( iConfigFiles.Count() != NULL )
+            {
+            __TRACE( KError, (
+                CStifLogger::ERed, 
+                _L( "Test case[%S] enumeration fails with error: %d" ),
+                iConfigFiles[iEnumerateCount], iStatus.Int() ) );
+            // Append
+            iFailedEnumerateConfig.Append( iConfigFiles[iEnumerateCount] );
+            }
+        }
+
+    iEnumerateCount++;
+
+    if ( iEnumerateCount < iConfigFiles.Count() )
+        {
+        // Continue enumeration
+        __TRACE( KInit, ( 
+            _L( "Getting testcases from module [%S], test case file [%S]" ),
+            iName, iConfigFiles[iEnumerateCount] ) );
+        SetActive();
+        iModule.EnumerateTestCases( *iConfigFiles[iEnumerateCount],
+                                    iEnumResultPackage, iStatus );
+        }
+    else if( iTestCaseCount == 0 )
+        {
+        // Total count of succesfully enumerations
+        iEnumerateCount -= iFailedEnumerateCount;
+        User::Leave( KErrNotFound );
+        }
+    else
+        {
+        // Total count of succesfully enumerations
+        iEnumerateCount -= iFailedEnumerateCount;
+        // Remove faulty config (test case) file(s)
+        for( TInt a= 0; a < iFailedEnumerateConfig.Count(); a++ )
+            {
+            TInt index( 0 );
+            // Find removed config(test case) file
+            index = iConfigFiles.Find( iFailedEnumerateConfig[a] );
+            if( index != KErrNotFound )
+                {
+                __TRACE( KInit, ( _L( "Removing test case file[%S]" ),
+                    iConfigFiles[index] ) );
+                // Remove
+                iConfigFiles.Remove( index );
+                }
+            }
+
+        // All test cases enumerated
+        iState = ETestModuleEnumerateCasesCompleted;
+        iEnumerateComplete = ETrue;
+
+        iEngine->EnumerationCompleted( iTestCaseCount );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: TestCasesL
+
+    Description: Return Test Cases
+
+    Parameters: None
+
+    Return Values: CFixedFlatArray<TTestInfo>* :Pointer to created array
+
+    Errors/Exceptions: Leaves if NewL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CFixedFlatArray<TTestInfo>* CTestModuleController::TestCasesL()
+    {
+    CFixedFlatArray<TTestInfo>* testCases = 
+        CFixedFlatArray<TTestInfo>::NewL( iTestCaseCount );
+
+    CleanupStack::PushL( testCases );
+
+    // Loop through all test cases from all config files
+    TInt totalCount = 0;
+    // HBufC to TPtrC
+    TPtrC name( iName->Des() );
+    for ( TInt i = 0; i < iEnumerateCount; i++ )
+        {
+        TTestInfo tmpInfo;
+        tmpInfo.iModuleName = name;
+        if ( iConfigFiles.Count() > 0 )
+            {
+            tmpInfo.iConfig = *iConfigFiles[i];
+            }
+
+        // Get test cases from iTestCaseArray at [i]
+        //if( (iTestCaseArray)[i] )
+		if ( iTestCaseArray.Count() > 0) 
+            {
+            CFixedFlatArray<TTestCaseInfo>* tempTestCases = (iTestCaseArray)[i];
+            for ( TInt j = 0; j < tempTestCases->Count(); j++ )
+                {
+                tmpInfo.iTestCaseInfo = (*tempTestCases)[j];
+                // Set TestCaseInfo to testCases array
+                testCases->Set( totalCount, tmpInfo );
+                totalCount++;
+                }
+            }
+        }
+
+    CleanupStack::Pop( testCases );
+
+    return testCases;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: FreeTestCases
+
+    Description: Free memory used for test cases
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::FreeTestCases()
+    {
+    // Reset and destroy test cases
+    iTestCaseArray.ResetAndDestroy();
+    iTestCaseArray.Close();
+
+    iTestCaseCount = 0;
+    iEnumerateComplete = EFalse;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::DoCancel()
+    {
+
+    // If CTestScripterController is used then move execution to the
+    // CTestScripterController size
+    if( iTestScripterController )
+        {
+        iTestScripterController->DoCancelEmulator( this );
+        return;
+        }
+
+    __TRACE( KVerbose, ( _L( "CTestModuleController::DoCancel [%S]" ), iName ) );
+
+    switch ( iState )
+        {
+        case ETestModuleEnumerateCases:
+            iModule.CancelAsyncRequest( ETestModuleEnumerateTestCases );
+            iEnumerateComplete = ETrue;
+            // Enumeration canceled, complete with KErrCancel
+            iEngine->EnumerationCompleted( 0, KErrCancel );
+
+            // Free allocated test cases because EnumerateTestCases was
+            // canceled
+            FreeTestCases();
+            break;
+        case ETestModuleIdle:
+        case ETestModuleEnumerateCasesCompleted:
+        default:
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestModuleController, "CTestModuleController" );
+            User::Panic( KTestModuleController, EDoCancelDisorder );
+            break;
+        }
+
+    iAtsLogger->ErrorL( _L("Test case enumeration cancelled") );   
+
+    iState = ETestModuleIdle;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: RunError
+
+    Description: Handle errors.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleController::RunError( TInt aError )
+    {
+
+    // If CTestScripterController is used then move execution to the
+    // CTestScripterController size
+    if( iTestScripterController )
+        {
+        return iTestScripterController->RunErrorEmulator( aError, this );
+        }
+
+    __TRACE( KError, ( CStifLogger::ERed, 
+        _L( "CTestModuleController::RunError [%S] aError=[%d]" ),
+        iName, aError ) );
+    if( aError == KErrNoMemory )
+        {
+        __TRACE( KError, ( CStifLogger::ERed, 
+            _L( "No memory available. Test case file's size might be too big." ) ) );
+        }
+
+    iEnumerateComplete = ETrue;
+
+    iAtsLogger->ErrorL( _L("Test module did not return any test cases") );
+    
+    _LIT( KErrorText, " did not return any test cases [error: ");
+    if( KErrorText().Length() + iName->Length() + 1 < KMaxName )
+        {
+        // Enumeration failed, print warning and complete with KErrNone
+        TName error( iName->Des() );
+        error.Append( KErrorText );  
+        error.AppendNum( aError );  
+        error.Append( _L("]") );  
+        iEngine->ErrorPrint ( 0, error );
+    
+        iEngine->EnumerationCompleted( 0, KErrNone );
+        }
+    else 
+        {
+        // Cannot only print warning, complete with error
+        iEngine->EnumerationCompleted( 0, aError );
+        }        
+
+    // Free allocated test cases because EnumerateTestCases failed
+    FreeTestCases();
+    iEnumerateComplete = ETrue;
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: Server
+
+    Description: Return handle to Test Server
+
+    Parameters: TTestInfo& aTestInfo: in: Test info for this test case
+
+    Return Values: RTestServer& : Reference to RTestServer
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+RTestServer& CTestModuleController::Server( TTestInfo& /*aTestInfo*/ )
+    {
+    return iServer;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: GetFreeOrCreateModuleControllerL
+
+    Description: Return pointer to module controller.
+                 Find module controller which does not run test case
+                 and if this is not possible then create new one.
+                 (Only for test scripter).
+
+    Parameters: TTestInfo& aTestInfo: in: Test info for this test case
+                TBool aUITestingSupport: in: Is UI testing mode enabled
+
+    Return Values: CTestModuleController* : pointer to module controller
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleController* CTestModuleController::GetFreeOrCreateModuleControllerL(TTestInfo& /*aTestInfo*/, TBool /*aUItestingSupport*/)
+    {
+    return NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: ModuleName
+
+    Description: Return the name of Test Module
+
+    Parameters: const TDesC& aModuleName: in Modulename
+
+    Return Values: const TDesC : Name of Test Module
+
+    Errors/Exceptions: None
+
+    Status: proposal
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestModuleController::ModuleName( const TDesC& /*aModuleName*/ )
+    {
+    return *iName;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: EnumerationComplete
+
+    Description: Is enumeration of test cases complete.
+
+    Parameters: None
+    
+    Return Values: TBool ETrue: Enumeration of test cases is complete
+                         EFalse: Enumeration is not complete
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestModuleController::EnumerationComplete()
+    {
+    return iEnumerateComplete;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: LeaveWithNotifyL
+
+    Description: Print out info and leave.
+
+    Parameters: TInt aCode: in: Error code 
+                const TDesC& aText: in: Test info
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleController::LeaveWithNotifyL( TInt aCode, const TDesC& aText )
+    {
+
+    __TRACE( KError, ( CStifLogger::ERed, aText ) );
+    if( iAtsLogger )
+        {
+        iAtsLogger->ErrorL( aText );
+        }
+    iEngine->LeaveWithNotifyL( aCode );
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: CaseCreated
+
+    Description: Increases the value of iTestCaseCounter
+
+    Parameters: None
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/  
+void CTestModuleController::CaseCreated()
+    {
+    // Number of ongoing testcases
+    iTestCaseCounter++;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: CaseFinished
+
+    Description: Decreases the value of iTestCaseCounter and deletes this pointer
+                 only in test module crash situations (KErrServerTerminated -15)
+
+    Parameters: None:
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/  
+void CTestModuleController::CaseFinished()
+    {
+    // Number of ongoing testcases
+    iTestCaseCounter--;
+    
+    // iTestModuleCrashDetected tells is TestModuleController cloned or not
+    // TestModuleController is cloned only when testmodule is crashed with KErrServerTerminated -15
+    if (iTestCaseCounter == 0 && iTestModuleCrashDetected)
+       {
+       // Delete this in case where it has been replaced with it clone
+       // and no one have pointer to this. This happens only when test module
+       // crashes    
+  	   delete this;
+  	   // Mem::Fill(this, sizeof(CTestModuleController), 0xa1a1a1a1);
+       }
+       
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: CloneL
+
+    Description: 
+
+    Parameters: 
+    
+    Return Values: 
+    
+    Errors/Exceptions: 
+
+    Status: 
+
+-------------------------------------------------------------------------------
+*/    
+CTestModuleController* CTestModuleController::CloneL( 
+                            CTestModuleController* aTestModuleController,
+                            TBool aAfterReset,
+                            CTestScripterController* aTestScripterController )
+    {
+    __TRACE( KInit, ( _L( "Cloning CTestModuleController" ) ) );
+   
+    
+    TName crashModuleName;
+    crashModuleName = aTestModuleController->ModuleName( crashModuleName );
+    
+    CTestModuleController* clone = CTestModuleController::NewL( iEngine, crashModuleName, aAfterReset, EFalse, aTestScripterController );
+    
+    clone->InitL( aTestModuleController->iInifile, KNullDesC );
+
+	// Give ATS logger to clone
+	clone->iAtsLogger = iAtsLogger;
+	iAtsLogger = NULL; 
+	
+    for ( TInt i = 0; i < aTestModuleController->iConfigFiles.Count(); i++ )
+	    {
+		TPtrC configFile = aTestModuleController->iConfigFiles[i]->Des();
+		TFileName config = configFile;
+   	    clone->AddConfigFileL( config );
+   	    }   
+	
+	iTestModuleCrashDetected = ETrue;       
+	
+    __TRACE( KVerbose, ( _L( "Cloning of CTestModuleController finished " ) ) );
+    return clone; 
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: DeleteModuleController
+
+    Description: In that class this method does nothing. It is implemented
+                 in CTestScripterController.
+
+    Parameters: CTestModuleController* aRealModuleController: not used
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: 
+
+-------------------------------------------------------------------------------
+*/    
+void CTestModuleController::DeleteModuleController(CTestModuleController* /*aRealModuleController*/)
+    {
+    } 
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: RemoveModuleController
+
+    Description: In that class this method does nothing. It is implemented
+                 in CTestScripterController.
+
+    Parameters: CTestModuleController* aRealModuleController: not used
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: 
+
+-------------------------------------------------------------------------------
+*/    
+void CTestModuleController::RemoveModuleController(CTestModuleController* /*aRealModuleController*/)
+    {
+    } 
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleController
+
+    Method: EnumerateSynchronously
+
+    Description: Enumerates test module controller. Used only when new
+                 test module controller is created during test case
+                 execution.
+
+    Parameters: None
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: 
+
+-------------------------------------------------------------------------------
+*/    
+void CTestModuleController::EnumerateSynchronously(void)
+    {
+    TInt i;
+    TInt cfgfiles = iConfigFiles.Count();
+    __TRACE(KInit, (_L("Module controller will enumerate synchronously [%d] config files"), cfgfiles));
+    
+    for(i = 0; i < cfgfiles; i++)
+        {
+        TRequestStatus status; 
+        iModule.EnumerateTestCases(*iConfigFiles[i],
+                                   iEnumResultPackage, 
+                                   status);
+        User::WaitForRequest(status);
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestScripterController class member
+    functions.
+
+-------------------------------------------------------------------------------
+*/
+#define LOGGER iEngine->Logger()
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: CTestScripterController
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to CTestEngine
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestScripterController::CTestScripterController( CTestEngine* aEngine ) :
+    CTestModuleController( aEngine )
+    {
+    // None
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: const TName& aName: in: Test module name
+                TBool aAfterReboot: in: Reboot indication
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::ConstructL( const TName& aName,
+                                          TBool aAfterReboot )
+    {
+    __TRACE( KInit, ( 
+        _L( "NOTE: Test module is TestScripter and each test case(config) file(s) will have own server(s)" ) ) );
+
+    // Remove optional '.DLL' from file name
+    TName name = aName;
+    name.LowerCase();
+    TParse parse;
+    parse.Set( name, NULL, NULL );
+
+    if ( parse.Ext() == _L(".dll") )
+        {
+        const TInt len = parse.Ext().Length();
+        name.Delete ( name.Length()-len, len );
+        }
+
+    iName = name.AllocL();
+
+    iAfterReboot = aAfterReboot;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: InitL
+
+    Description: Initialize test module.
+
+    Parameters: TFileName& aIniFile: in: Initialization file of Test Module
+                const TDesC& aConfigFile: in: Test case(config) file name(Used 
+                in TestScripter case).
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::InitL( TFileName& aIniFile, 
+                                     const TDesC& /*aConfigFile*/ )
+    {
+    // Take initialization file of Test Module
+    iInifile = aIniFile;
+
+    // Just empty, don't create TestServer operations. TestServer
+    // creation will be do in AddTestCaseFile()-method.
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestEngine* aEngine: in: CTestEngine object
+                const TName& aName: in: Test module name
+                TBool aAfterReboot: in: Reboot indication
+
+    Return Values: CTestScripterController* : pointer to created object
+
+    Errors/Exceptions: Leaves if called ConstructL method leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestScripterController* CTestScripterController::NewL( CTestEngine* aEngine,
+                                                        const TName& aName,
+                                                        TBool aAfterReboot )
+    {
+    CTestScripterController* self =
+        new ( ELeave ) CTestScripterController( aEngine );
+    CleanupStack::PushL( self );
+    self->ConstructL( aName, aAfterReboot );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: ~CTestScripterController
+
+    Description: Destructor
+
+    Deallocate all allocated resources. Delete CTestScripterController's
+    CTestModuleController(s). After this is deleted base class also, see:
+    CTestModuleController::~CTestModuleController(). 
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestScripterController::~CTestScripterController()
+    {
+    // Delete CTestScripterController(s).
+    iTestScripter.ResetAndDestroy();
+    iTestScripter.Close();
+
+    // After this is deleted base class also, see:
+    // CTestModuleController::~CTestModuleController(). 
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: AddConfigFileL
+
+    Description: Add config file.
+                 - Creates CTestModuleController(Gives test case file name)
+                 - Initializes CTestModuleController( creates a server session)
+                 - Adds config file
+
+    Parameters: TFileName& aConfigFile: in: Config file for TestScripter
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if AppendL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::AddConfigFileL( TFileName& aConfigFile )
+    {
+    // Check that this config file does not already exists
+    for(  TInt a = 0; a < iTestScripter.Count(); a++ )
+        {
+        for ( TInt i = 0; i < iTestScripter[a]->iConfigFiles.Count(); i++ )
+            {
+            // HBufC to TPtrC
+            TPtrC name( iTestScripter[a]->iConfigFiles[i]->Des() );
+            if ( KErrNone == aConfigFile.CompareF( name ) )
+                {
+                LeaveWithNotifyL( KErrAlreadyExists,  
+                    _L( "Adding config file failed: Config file already exists" ) );
+                }
+            }
+        }
+
+    __TRACE( KInit, ( 
+        _L( "CTestScripterController::AddConfigFileL aConfigFile=[%S]" ) ,
+        &aConfigFile ) );
+
+    HBufC* testScripterAndTestCaseFile = NULL; // InitL() takes TFileName
+    testScripterAndTestCaseFile = CreateTestScripterNameL( 
+                                            aConfigFile,
+                                            testScripterAndTestCaseFile );
+    // Add to cleanup stack here, because CreateTestScripterNameL needs to be
+    // trapped in other methods.
+    CleanupStack::PushL( testScripterAndTestCaseFile );
+
+    //Create server and active object(This uses CTestModuleController::InitL())
+    CTestModuleController* module = CTestModuleController::NewL( 
+                                        iEngine,
+                                        testScripterAndTestCaseFile->Des(),
+                                        iAfterReboot, EFalse, this );
+    CleanupStack::PopAndDestroy( testScripterAndTestCaseFile );
+    CleanupStack::PushL( module );
+
+    User::LeaveIfError( iTestScripter.Append( module ) );
+
+    // Now is used TestScripter so give test case file also(used
+    // in caps modifier cases). 
+    TRAPD ( err, module->InitL( iInifile, aConfigFile ) );
+    if( err != KErrNone )
+        {
+        __TRACE( KInit, ( _L( "InitL fails with error: %d" ), err ) );
+        User::Leave( err );
+        }
+
+    module->AddConfigFileL( aConfigFile );
+
+    CleanupStack::Pop( module );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: RemoveConfigFileL
+
+    Description: Remove config file
+
+    Parameters: TFileName& aConfigFile: in: Config file name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::RemoveConfigFileL( TFileName& aConfigFile )
+    {
+     __TRACE( KInit, ( _L( "CTestScripterController::RemoveConfigFileL" ) ) );
+
+    HBufC* testScripterAndTestCaseFile = NULL;
+    testScripterAndTestCaseFile = CreateTestScripterNameL( aConfigFile,
+                                         testScripterAndTestCaseFile );
+    // Add to cleanup stack here, because CreateTestScripterNameL needs to be
+    // trapped in other methods.
+    CleanupStack::PushL( testScripterAndTestCaseFile );
+
+    // Get correct iTestScripter
+    TInt index( -1 );
+    for( TInt a = 0; a < iTestScripter.Count(); a++ )
+        {
+        if( ( iTestScripter[a]->iName->CompareF( 
+                        testScripterAndTestCaseFile->Des() ) == KErrNone ) )
+            {
+            index = a;
+            break;
+            }
+        }
+
+    CleanupStack::PopAndDestroy( testScripterAndTestCaseFile );
+
+    if( index == -1 )
+        {
+        LeaveWithNotifyL( KErrNotFound, 
+            _L( "Removing config file failed: Config file not found" ) );
+        }
+
+    __TRACE( KInit, ( 
+        _L( "CTestScripterController[%S]::RemoveConfigFileL aConfigFile=[%S]"),
+        iTestScripter[index]->iName, &aConfigFile ) );
+
+    // Find config file
+    for ( TInt i = 0; i < iTestScripter[index]->iConfigFiles.Count(); i++ )
+        {
+        // HBufC to TPtrC
+        TPtrC name( iTestScripter[index]->iConfigFiles[i]->Des() );
+        if ( KErrNone == aConfigFile.CompareF( name ) )
+            {
+            HBufC* configFile = iTestScripter[index]->iConfigFiles[i];
+            iTestScripter[index]->iConfigFiles.Remove(i);
+            delete configFile;
+            // Cancel enumerate and free test cases
+            Cancel();
+            FreeTestCases();
+            // Testcasefile(config) is found, so we can return
+            return;
+            }
+        }
+
+    LeaveWithNotifyL( KErrNotFound, 
+        _L( "Removing config file failed: Config file not found" ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: StartEnumerateL
+
+    Description: Start test case enumeration
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: LeaveWithNotifyL if no test case added. 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::StartEnumerateL()
+    {
+    if( iTestScripter.Count() <= 0 )
+        {
+        RDebug::Print( 
+            _L( "There is no test case file for TestScripter registered yet. Enumeraton aborted." ) );
+        LeaveWithNotifyL( KErrNotFound,
+            _L( "There is no test case file for TestScripter registered yet. Enumeraton aborted." ) );
+        return;
+        }
+
+    for( TInt a = 0; a < iTestScripter.Count(); a++ )
+        {
+        __TRACE( KVerbose, ( 
+                _L( "CTestScripterController[%S]::StartEnumerateL" ),
+                iTestScripter[a]->iName ) );
+        iTestScripter[a]->iTestCaseCount = 0;
+        iTestScripter[a]->iEnumerateCount = 0;
+        iTestScripter[a]->iFailedEnumerateCount = 0;
+        iTestScripter[a]->iFailedEnumerateConfig.Reset();
+        iTestScripter[a]->iEnumerateComplete = EFalse;
+
+        iTestScripter[a]->iState = ETestModuleEnumerateCases;
+        
+        if ( iTestScripter[a]->iConfigFiles.Count() > 0 )
+            {
+            // HBufC to TPtrC
+            iTestScripter[a]->iEnumConfigFile.Set( 
+                                iTestScripter[a]->iConfigFiles[0]->Des() );
+            }
+
+        __TRACE( KInit, ( 
+            _L( "Getting testcases from module [%S], test case file[%S]" ),
+            iTestScripter[a]->iName, &iTestScripter[a]->iEnumConfigFile ) );
+        
+        iTestScripter[a]->SetActive();
+        iTestScripter[a]->iModule.EnumerateTestCases( 
+                                    iTestScripter[a]->iEnumConfigFile,
+                                    iTestScripter[a]->iEnumResultPackage,
+                                    iTestScripter[a]->iStatus );
+        } // End of for-loop
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: GetCurrentIndex
+
+    Description: Get current CTestScripterController.
+
+    Parameters: CTestModuleController* aTestModuleController: in:
+                Pointer current to CTestModuleController
+
+    Return Values: KErrNotFound returned if CTestModuleController not found
+                   else current index returned.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestScripterController::GetCurrentIndex( CTestModuleController*
+                                                    aTestModuleController )
+    {
+    // Get correct iTestScripter
+    return iTestScripter.Find( aTestModuleController );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: RunL
+
+    Description: RunL handles completed requests.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::RunL()
+    {
+    // Should never come here because one TestScripter have one test case
+    // file per server session.
+    // CTestScripterController's base class is an active object but this class
+    // not used as an active object. So there not used RunL => Panic.
+
+    User::Panic( _L( "CTestScripterController::RunL()" ), KErrCorrupt );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: RunLEmulator
+
+    Description: RunLEmulator handles completed requests(Emulates RunL()).
+                 This is called from CTestModuleController::RunL.
+
+    Parameters: CTestModuleController* aTestModuleController: in: pointer to
+                CTestModuleController.
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::RunLEmulator( CTestModuleController*
+                                                    aTestModuleController )
+    {
+    iTestScripterIndicator++;
+    TInt index = GetCurrentIndex( aTestModuleController );
+    if( index < KErrNone )
+        {
+        User::Leave( KErrNotFound );
+        }
+
+    __TRACE( KVerbose, ( 
+        _L( "CTestScripterController[%S]::RunLEmulator [iStatus = %d]"),
+        iTestScripter[index]->iName, iTestScripter[index]->iStatus.Int() ) );
+
+    // Note:
+    // If test case not found there may be existing cases from previous
+    // enumerations, so those cases are valid. e.g. case: "add test case file",
+    // "add test case file that not exist" and "get test cases".
+
+    TInt ret( KErrNone );
+
+    // Check that request was successful
+    if( iTestScripter[index]->iStatus.Int() == KErrNone )
+        {
+        // Get enumerated test cases and append them to array
+        CFixedFlatArray<TTestCaseInfo>* testCases = 
+                        CFixedFlatArray<TTestCaseInfo>::NewL( 
+                        iTestScripter[index]->iEnumResultPackage() );
+        CleanupStack::PushL( testCases );
+        ret = iTestScripter[index]->iModule.GetTestCases( *testCases );
+        __TRACE( KInit, ( 
+                _L( "RunL()'s GetTestCases method returns: %d" ), ret ) );
+
+        iTestScripter[index]->iTestCaseCount += testCases->Count();
+
+        if ( testCases->Count() == 0 )
+            {
+
+            if (iTestScripter[index]->iConfigFiles.Count() > 0)
+                {
+                __TRACE( KInit, ( 
+                    CStifLogger::EBold, 
+                    _L( "Module [%S], test case file[%S] returned 0 cases" ),
+                    iTestScripter[index]->iName,
+                    iTestScripter[index]->iConfigFiles[iTestScripter[index]->iEnumerateCount] ) );
+                }
+            else
+                {
+                __TRACE( KInit, ( CStifLogger::EBold,
+                    _L("Module [%S] without test case file, returned 0 cases"),
+                    iTestScripter[index]->iName ) );
+                }
+            iTestScripter[index]->iEngine->ErrorPrint( 1,
+                _L("Someone returned 0 test cases. Check testengine log"));
+            iTestScripter[index]->iAtsLogger->CommentL( 
+                _L("Test module returned 0 test cases") );   
+            }
+
+        // Store test cases for later use
+        User::LeaveIfError( iTestScripter[index]->iTestCaseArray.Append( 
+                                                                testCases ) );
+        CleanupStack::Pop( testCases );
+        
+        }
+    else
+        {
+        // Calculate failed enumeration count
+        iTestScripter[index]->iFailedEnumerateCount++;
+        // Add failed config(test case) file to array for later removing
+        if( iTestScripter[index]->iConfigFiles.Count() != NULL )
+            {
+            __TRACE( KError, (
+                CStifLogger::ERed, 
+                _L( "Test case[%S] enumeration fails with error: %d" ),
+                iTestScripter[index]->iConfigFiles[iTestScripter[index]->iEnumerateCount],
+                iTestScripter[index]->iStatus.Int() ) );
+            // Append
+            iTestScripter[index]->iFailedEnumerateConfig.Append(
+                iTestScripter[index]->iConfigFiles[iTestScripter[index]->iEnumerateCount] );
+            }
+        }
+
+    TInt count = iTestScripter.Count();
+
+    // All TestScripter enumerations is finished for cleaning if necessarily
+    // and complete request up to engine.
+    if( count == iTestScripterIndicator )
+        {
+        TInt testCaseCount( 0 );
+        for( TInt a = 0; a < count; a++  )
+            {
+            // Remove faulty config (test case) file(s) and 
+            // iEnumerateCount not increased.
+            if( iTestScripter[a]->iTestCaseCount == 0 )
+                {
+                // Check that test case file is not allready removed.
+                if( iTestScripter[a]->iConfigFiles.Count() != 0 )
+                    {
+                    iTestScripter[a]->iConfigFiles.Remove( 0 );
+                    }
+                }
+            else
+                {
+                iTestScripter[a]->iEnumerateCount++;
+                testCaseCount += iTestScripter[a]->iTestCaseCount;
+                }
+
+            // All test cases enumerated
+            iTestScripter[a]->iState = ETestModuleEnumerateCasesCompleted;
+            iTestScripter[a]->iEnumerateComplete = ETrue;
+            }
+
+        iTestScripterIndicator = 0; // Initialization back to 0, enumerations
+                                    // are done at this run.
+        iEngine->EnumerationCompleted( testCaseCount );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: TestCasesL
+
+    Description: Return Test Cases
+
+    Parameters: None
+
+    Return Values: CFixedFlatArray<TTestInfo>*: Pointer to created array
+
+    Errors/Exceptions: Leaves if NewL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CFixedFlatArray<TTestInfo>* CTestScripterController::TestCasesL()
+    {
+    TInt testCaseCount( 0 );
+    for( TInt i = 0; i < iTestScripter.Count(); i++  )
+        {
+        testCaseCount += iTestScripter[i]->iTestCaseCount;
+        }
+
+    CFixedFlatArray<TTestInfo>* testCases = 
+        CFixedFlatArray<TTestInfo>::NewL( testCaseCount );
+
+    CleanupStack::PushL( testCases );
+
+    // Loop through all test cases from all config files
+    TInt totalCount = 0;
+    // HBufC to TPtrC
+    for( TInt a = 0; a < iTestScripter.Count(); a++ )
+        {
+        TPtrC name( iTestScripter[a]->iName->Des() );
+        for ( TInt i = 0; i < iTestScripter[a]->iEnumerateCount; i++ )
+            {
+            TTestInfo tmpInfo;
+            tmpInfo.iModuleName = name;
+            if ( iTestScripter[a]->iConfigFiles.Count() > 0 )
+                {
+                tmpInfo.iConfig = *iTestScripter[a]->iConfigFiles[i];
+                }
+
+            // Get test cases from iTestCaseArray at [i]
+            if( (iTestScripter[a]->iTestCaseArray)[i] )
+                {
+                CFixedFlatArray<TTestCaseInfo>* tempTestCases = 
+                                    (iTestScripter[a]->iTestCaseArray)[i];
+                for ( TInt j = 0; j < tempTestCases->Count(); j++ )
+                    {
+                    tmpInfo.iTestCaseInfo = (*tempTestCases)[j];
+                    // Set TestCaseInfo to testCases array
+                    testCases->Set( totalCount, tmpInfo );
+                    totalCount++;
+                    }
+                }
+            }
+        }
+
+    CleanupStack::Pop( testCases );
+
+    return testCases;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: FreeTestCases
+
+    Description: Free memory used for test cases
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::FreeTestCases()
+    {
+    for( TInt a = 0; a < iTestScripter.Count(); a++ )
+        {
+        // Reset and destroy test cases
+        iTestScripter[a]->iTestCaseArray.ResetAndDestroy();
+        iTestScripter[a]->iTestCaseArray.Close();
+
+        iTestScripter[a]->iTestCaseCount = 0;
+        iTestScripter[a]->iEnumerateComplete = EFalse;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::DoCancel()
+    {
+    // Should never come here because one TestScripter have one test case
+    // file per server session.
+    // CTestScripterController's base class is an active object but this class
+    // not used as an active object. So there not used DoCancel => Panic.
+
+    User::Panic( _L( "CTestScripterController::DoCancel()" ), KErrCorrupt );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: DoCancelEmulator
+
+    Description: Cancel active request(Emulates DoCancel)
+                 This is called from CTestModuleController::DoCancel.
+
+    Parameters: CTestModuleController* aTestModuleController: in: pointer to
+                CTestModuleController.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripterController::DoCancelEmulator(
+                                CTestModuleController* aTestModuleController )
+    {
+    TInt index = GetCurrentIndex( aTestModuleController );
+    if( index < KErrNone )
+        {
+        User::Leave( KErrNotFound );
+        }
+
+    __TRACE( KVerbose, ( 
+        _L( "CTestScripterController[%S]::RunDoCancelEmulator" ),
+        iTestScripter[index]->iName ) );
+
+    switch ( iTestScripter[index]->iState )
+        {
+        case ETestModuleEnumerateCases:
+            iTestScripter[index]->iModule.CancelAsyncRequest(
+                                            ETestModuleEnumerateTestCases );
+            iTestScripter[index]->iEnumerateComplete = ETrue;
+            // Enumeration canceled, complete with KErrCancel
+            iTestScripter[index]->iEngine->EnumerationCompleted(
+                                                            0, KErrCancel );
+
+            // Free allocated test cases because EnumerateTestCases was
+            // canceled
+            FreeTestCases();
+            break;
+        case ETestModuleIdle:
+        case ETestModuleEnumerateCasesCompleted:
+        default:
+            // DoCancel called in wrong state => Panic
+            _LIT( KTestModuleController, "CTestModuleController" );
+            User::Panic( KTestModuleController, EDoCancelDisorder );
+            break;
+        }
+
+    iTestScripter[index]->iAtsLogger->ErrorL( 
+                        _L("Test case enumeration cancelled") );
+    iTestScripter[index]->iState = ETestModuleIdle;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: RunError
+
+    Description: Handle errors.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestScripterController::RunError( TInt /*aError*/ )
+    {
+    // Should never come here because one TestScripter have one test case
+    // file per server session.
+    // CTestScripterController's base class is an active object but this class
+    // not used as an active object. So there not used RunError => Panic.
+
+    User::Panic( _L( "CTestScripterController::RunError()" ), KErrCorrupt );
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: RunErrorEmulator
+
+    Description: Handle errors(Emulates RunError).
+                 This is called from CTestModuleController::RunError.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code.
+                CTestModuleController* aTestModuleController: in: pointer to
+                CTestModuleController.
+
+    Return Values: TInt KErrNone: Always returned KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestScripterController::RunErrorEmulator( TInt aError,
+                                CTestModuleController* aTestModuleController )
+    {
+    TInt index = GetCurrentIndex( aTestModuleController );
+    if( index < KErrNone )
+        {
+        User::Leave( KErrNotFound );
+        }
+    
+    __TRACE( KError, ( CStifLogger::ERed,
+        _L( "CTestScripterController[%S]::RunErrorEmulator aError=[%d]" ),
+        iTestScripter[index]->iName, aError ) );
+    if( aError == KErrNoMemory )
+        {
+        __TRACE( KError, ( CStifLogger::ERed, 
+            _L( "No memory available. Test case file's size might be too big." ) ) );
+        }
+
+    iTestScripter[index]->iEnumerateComplete = ETrue;
+
+    iTestScripter[index]->iAtsLogger->ErrorL( 
+                            _L("Test module did not return any test cases") );
+    
+    _LIT( KErrorText, " did not return any test cases [error: ");
+    if( KErrorText().Length() +
+            iTestScripter[index]->iName->Length() +
+            1 < KMaxName )
+        {
+        // Enumeration failed, print warning and complete with KErrNone
+        TName error( iTestScripter[index]->iName->Des() );
+        error.Append( KErrorText );  
+        error.AppendNum( aError );  
+        error.Append( _L("]") );  
+        iEngine->ErrorPrint ( 0, error );
+    
+        iTestScripter[index]->iEngine->EnumerationCompleted( 0, KErrNone );
+        }
+    else 
+        {
+        // Cannot only print warning, complete with error
+        iTestScripter[index]->iEngine->EnumerationCompleted( 0, aError );
+        }
+
+    // Free allocated test cases because EnumerateTestCases failed
+    FreeTestCases();
+    iTestScripter[index]->iEnumerateComplete = ETrue;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: EnumerationComplete
+
+    Description: Is enumeration of test cases complete.
+
+    Parameters: None
+    
+    Return Values: TBool ETrue: Enumeration of test cases is complete
+                         EFalse: Enumeration is not complete
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestScripterController::EnumerationComplete()
+    {
+    for( TInt a = 0; a < iTestScripter.Count(); a++ )
+        {
+        if( !iTestScripter[a]->iEnumerateComplete )
+            {
+            return EFalse;
+            }
+        }
+    return ETrue;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: Server
+
+    Description: Return handle to Test Server
+
+    Parameters: TTestInfo& aTestInfo: in: Test info for this test case
+
+    Return Values: RTestServer& : Reference to RTestServer
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+RTestServer& CTestScripterController::Server( TTestInfo& aTestInfo )
+    {
+    HBufC* testScripterAndTestCaseFile = NULL;
+    TRAPD( ret, testScripterAndTestCaseFile = CreateTestScripterNameL( 
+                                            aTestInfo.iConfig,
+                                            testScripterAndTestCaseFile ) );
+    // Add to cleanup stack here, because CreateTestScripterNameL needs to be
+    // trapped in other methods.
+    CleanupStack::PushL( testScripterAndTestCaseFile );
+    if( ret != KErrNone )
+        {
+        User::Panic( 
+            _L( "CTestScripterController::Server(): CreateTestScripterNameL" ),
+            ret );
+        }
+
+    // Get correct handle
+    TInt index( KErrNotFound );
+    for( TInt a = 0; a < iTestScripter.Count(); a++ )
+        {
+        if( testScripterAndTestCaseFile->Des() == 
+                                            iTestScripter[a]->iName->Des() )
+            {
+            index = a;
+            break;
+            }
+        }
+
+    CleanupStack::PopAndDestroy( testScripterAndTestCaseFile );
+
+    if( index == KErrNotFound )
+        {
+        User::Panic(
+            _L( "CTestScripterController::Server(): Index not found" ),
+            KErrNotFound );
+        }
+
+    // Return handle
+    return iTestScripter[index]->iServer;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: GetFreeOrCreateModuleControllerL
+
+    Description: Return pointer to test module controller.
+                 Find controller which does not run test case
+                 and if this is not possible then create new one.
+
+    Parameters: TTestInfo& aTestInfo: in: Test info for this test case
+                TBool aUITestingSupport: in: Is UI testing mode enabled
+
+    Return Values: CTestModuleController* : pointer to controller
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleController* CTestScripterController::GetFreeOrCreateModuleControllerL(TTestInfo& aTestInfo, TBool aUITestingSupport)
+    {
+    HBufC* testScripterAndTestCaseFile = NULL;
+    TRAPD(ret, testScripterAndTestCaseFile = CreateTestScripterNameL(aTestInfo.iConfig, testScripterAndTestCaseFile));
+
+    // Add to cleanup stack here, because CreateTestScripterNameL needs to be trapped in other methods.
+    CleanupStack::PushL(testScripterAndTestCaseFile);
+    if(ret != KErrNone)
+        {
+        User::Panic(_L("CTestScripterController::GetFreeOrCreateModuleControllerL(): CreateTestScripterNameL"), ret);
+        }
+
+    CTestModuleController* resultController = NULL;
+    CTestModuleController* parentController = NULL;
+    TInt j;
+    
+    __TRACE(KInit, (_L("Find free real module controller (or create new one)")));
+
+    // Get handle to correct "parent" module controller
+    __TRACE(KInit, (_L("Searching for parent module controller named [%S]"), testScripterAndTestCaseFile));
+    for(TInt a = 0; a < iTestScripter.Count(); a++)
+        {
+        //Check if module name matches to given name
+        if(iTestScripter[a]->iName->Des() == testScripterAndTestCaseFile->Des())
+            {
+            parentController = iTestScripter[a]; 
+            __TRACE(KInit, (_L("Parent module controller [%S] has been found. Checking its %d children"), parentController->iName, parentController->iChildrenControllers.Count()));
+            //Now check all its children and find free one
+            //In UI testing mode always create new module controller
+            if(!aUITestingSupport)
+                {
+                for(j = 0; j < parentController->iChildrenControllers.Count(); j++)
+                    {
+                    if(parentController->iChildrenControllers[j]->iTestCaseCounter == 0)
+                        {
+                        resultController = parentController->iChildrenControllers[j];
+                        __TRACE(KInit, (_L("Free real module controller found [%S]"), resultController->iName));
+                        break;
+                        }
+                    else
+                        {
+                        __TRACE(KInit, (_L("Module controller found [%S] but is not free (it runs %d test cases)"), parentController->iChildrenControllers[j]->iName, parentController->iChildrenControllers[j]->iTestCaseCounter));
+                        }
+                    }
+                }
+            else
+                {
+                __TRACE(KInit, (_L("In UITestingSupport mode new module controller will be always created")));
+                }
+            }
+        }
+
+    //Append underscore to name
+    TPtr ptr = testScripterAndTestCaseFile->Des();
+    ptr.Append(_L("@"));
+
+    //Create new module controller if free one has not been found
+    if(!resultController)
+        {
+        TBuf<10> ind;
+        ind.Format(_L("%d"), iEngine->GetIndexForNewTestModuleController());
+        TPtr ptr = testScripterAndTestCaseFile->Des();
+        ptr.Append(ind);
+        __TRACE(KInit, (_L("Free real module controller not found. Creating new one [%S]."), testScripterAndTestCaseFile));
+            
+        //Create server and active object (This uses CTestModuleController::InitL())
+        CTestModuleController* module = CTestModuleController::NewL( 
+                                            iEngine,
+                                            testScripterAndTestCaseFile->Des(),
+                                            iAfterReboot, EFalse, this);
+        CleanupStack::PushL(module);
+        parentController->iChildrenControllers.AppendL(module);
+        __TRACE(KInit, (_L("Child added to [%S] controller. Currently it has %d children:"), parentController->iName, parentController->iChildrenControllers.Count()));
+        for(j = 0; j < parentController->iChildrenControllers.Count(); j++)
+            {
+            __TRACE(KInit, (_L("    %d. [%S]"), j + 1, parentController->iChildrenControllers[j]->iName));
+            }
+
+        // Now is used TestScripter so give test case file also(used
+        // in caps modifier cases). 
+        TRAPD(err, module->InitL(iInifile, aTestInfo.iConfig));
+        if(err != KErrNone)
+            {
+            __TRACE(KVerbose, (_L("InitL fails with error: %d" ), err));
+            User::Leave(err);
+            }
+
+        module->AddConfigFileL(aTestInfo.iConfig);
+
+        __TRACE(KInit, (_L("New module controller created [%S]."), testScripterAndTestCaseFile));
+
+        //Enumerate test cases
+        module->EnumerateSynchronously();
+
+        CleanupStack::Pop(module);
+        resultController = module;
+        }
+
+    CleanupStack::PopAndDestroy(testScripterAndTestCaseFile);
+
+    // Return handle
+    return resultController;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: ModuleName
+
+    Description: Return the name of Test Scripter
+
+    Parameters: const TDesC& aModuleName: in: Module name
+
+    Return Values: const TDesC : Name of Test Scripter
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestScripterController::ModuleName( const TDesC& aModuleName )
+    {
+    // If test case file not added yet.
+    if( iTestScripter.Count() == 0 || aModuleName == KTestScripterName )
+        {
+        return *iName;
+        }
+
+    // Test case(s) is(are) added. Scan the name from corrent TestScripter
+    // session
+    for( TInt a = 0; a < iTestScripter.Count(); a++ )
+        {
+        if( aModuleName == iTestScripter[a]->iName->Des() )
+            {
+            return *iTestScripter[a]->iName;
+            }
+        }
+
+    return KNullDesC;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: CreateTestScripterNameL
+
+    Description: Create name according to TestScripter and Test case file.
+
+    Parameters: TFileName& aTestCaseFile: in: Test case file with path and name
+                TFileName& aCreatedName: inout: Created name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves is test case file is too long
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+HBufC* CTestScripterController::CreateTestScripterNameL( 
+                                                    TFileName& aTestCaseFile,
+                                                    HBufC* aCreatedName )
+    {
+    TParse parse;
+    parse.Set( aTestCaseFile, NULL, NULL );
+
+    TInt length( 0 );
+    length = parse.Name().Length();
+    length += ( KTestScripterNameLength + 1 );
+    length += 10; //this will be used to add unique identifier (when run test case in separate process is on)
+
+    // aCreatedName to CleanupStack
+    aCreatedName = HBufC::NewLC( length );
+    TPtr ptr = aCreatedName->Des();
+
+    // Maximum length of TestScripter's name(Max limitation from
+    // CTestModuleController creation)
+    TInt maximumLength = KMaxName - ( KTestScripterNameLength + 1 );
+
+    // Start create name. Format is testscripter_testcasefile
+    ptr.Copy( KTestScripterName );
+    ptr.Append( _L( "_" ) );
+    if( parse.Name().Length() < maximumLength )
+        {
+        ptr.Append( parse.Name() );
+        ptr.LowerCase();
+        }
+    else
+        {
+        __TRACE( KInit, ( CStifLogger::ERed,
+            _L( "TestScripter test case file(config)'s name is too long. Current length[%d], allowed max length[%d]. Cannot continue" ),
+            parse.Name().Length(), maximumLength ) );
+        User::Leave( KErrArgument );
+        }
+
+    // Pop here because this method can be trapped and trap panics with
+    // E32USER-CBase if cleap up stack is not empty.
+    CleanupStack::Pop( aCreatedName );
+
+    return aCreatedName;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: DeleteModuleController
+
+    Description: Finds specified module controller and deletes it.
+
+    Parameters: CTestModuleController* aRealModuleController: module controller
+                   to be deleted.
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: 
+
+-------------------------------------------------------------------------------
+*/    
+void CTestScripterController::DeleteModuleController(CTestModuleController* aRealModuleController)
+    {
+    __TRACE(KInit, (_L("Attempting to delete real module controller [%S]"), aRealModuleController->iName));
+
+    TInt i, j, k;
+    TInt children;
+    TInt subcontrollers = iTestScripter.Count();
+    
+    for(k = 0; k < subcontrollers; k++)
+        {
+        children = iTestScripter[k]->iChildrenControllers.Count();
+        __TRACE(KInit, (_L("...checking controller [%S] which has %d children"), iTestScripter[k]->iName, children));
+
+        for(i = 0; i < children; i++)
+            {
+            if(iTestScripter[k]->iChildrenControllers[i] == aRealModuleController)
+                {
+                __TRACE(KInit, (_L("Real module controller found... deleting")));
+                delete iTestScripter[k]->iChildrenControllers[i];
+                iTestScripter[k]->iChildrenControllers.Remove(i);
+    
+                __TRACE(KInit, (_L("Child removed from [%S] controller. Currently it has %d children:"), iTestScripter[k]->iName, iTestScripter[k]->iChildrenControllers.Count()));
+                for(j = 0; j < iTestScripter[k]->iChildrenControllers.Count(); j++)
+                    {
+                    __TRACE(KInit, (_L("    %d. [%S]"), j + 1, iTestScripter[k]->iChildrenControllers[j]->iName));
+                    }
+    
+                return;
+                }
+            }
+        }
+    __TRACE(KInit, (_L("Real module controller NOT found... NOT deleting")));
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestScripterController
+
+    Method: RemoveModuleController
+
+    Description: Finds specified module controller and removes it from children list.
+
+    Parameters: CTestModuleController* aRealModuleController: module controller
+                   to be removed.
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: 
+
+-------------------------------------------------------------------------------
+*/    
+void CTestScripterController::RemoveModuleController(CTestModuleController* aRealModuleController)
+    {
+    __TRACE(KInit, (_L("Attempting to remove real module controller [%x]"), aRealModuleController));
+
+    TInt i, j, k;
+    TInt children;
+    TInt subcontrollers = iTestScripter.Count();
+    
+    for(k = 0; k < subcontrollers; k++)
+        {
+        children = iTestScripter[k]->iChildrenControllers.Count();
+        __TRACE(KInit, (_L("...checking controller [%S] which has %d children"), iTestScripter[k]->iName, children));
+
+        for(i = 0; i < children; i++)
+            {
+            if(iTestScripter[k]->iChildrenControllers[i] == aRealModuleController)
+                {
+                __TRACE(KInit, (_L("Real module controller found... removing")));
+                iTestScripter[k]->iChildrenControllers.Remove(i);
+    
+                __TRACE(KInit, (_L("Child removed from [%S] controller. Currently it has %d children:"), iTestScripter[k]->iName, iTestScripter[k]->iChildrenControllers.Count()));
+                for(j = 0; j < iTestScripter[k]->iChildrenControllers.Count(); j++)
+                    {
+                    __TRACE(KInit, (_L("    %d. [%S]"), j + 1, iTestScripter[k]->iChildrenControllers[j]->iName));
+                    }
+    
+                return;
+                }
+            }
+        }
+    __TRACE(KInit, (_L("Real module controller NOT found... NOT removing")));
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CErrorPrinter class member
+    functions.
+
+-------------------------------------------------------------------------------
+*/
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrinter
+
+    Method: NewL
+
+    Description: Create a testcase runner.
+
+    Parameters: CTestEngine* aMain: in: Pointer to console main
+
+    Return Values: CErrorPrinter* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CErrorPrinter* CErrorPrinter::NewL( CTestEngine* aTestEngine )
+    {
+    CErrorPrinter* self = new ( ELeave ) CErrorPrinter();
+    CleanupStack::PushL( self );
+    self->ConstructL( aTestEngine );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrinter
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CTestEngine* aEngine: in: Pointer to Engine
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CErrorPrinter::ConstructL( CTestEngine* aEngine )
+    {
+    iEngine = aEngine;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrinter
+
+    Method: CErrorPrinter
+
+    Description: Constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CErrorPrinter::CErrorPrinter( ) : CActive( EPriorityStandard ),
+                                      iErrorPckg( iError )
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrinter
+
+    Method: ~CErrorPrinter
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CErrorPrinter::~CErrorPrinter( )
+    {
+    Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrinter
+
+    Method: StartL
+
+    Description: Starts a test case and sets the active object to active.
+
+    Parameters: RTestModule& aServer: in: Reference to the server object
+
+    Return Values: None
+
+    Errors/Exceptions: TInt: Return KErrNone
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CErrorPrinter::StartL( RTestModule& aServer )
+    {
+    iServer = aServer;
+
+    CActiveScheduler::Add ( this );
+
+    SetActive();
+    aServer.ErrorNotification ( iErrorPckg, iStatus );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrinter
+
+    Method: RunL
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CErrorPrinter::RunL()
+    {
+
+    if ( iStatus.Int() != KErrNone )
+        {
+        __TRACE( KVerbose, ( _L( "In CErrorPrinter::RunL [iStatus = %d]" ), iStatus.Int() ) );
+        }
+    else
+       {
+        // Forward error print to UI and set request again active.
+        iEngine->ErrorPrint( iErrorPckg );
+        SetActive();
+        iServer.ErrorNotification ( iErrorPckg, iStatus );
+       }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrinter
+
+    Method: DoCancel
+
+    Description: Cancels the asynchronous request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CErrorPrinter::DoCancel()
+    {
+    iServer.CancelAsyncRequest ( ETestModuleErrorNotification );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrinter
+
+    Method: RunError
+
+    Description: Handles errors. RunL can't leave so just forward error
+    and let framework handle error.
+
+    Parameters: TInt aError: in: Error code
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CErrorPrinter::RunError( TInt aError )
+    {
+    return aError;
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CServerStateHandler
+
+    Method: NewL
+
+    Description: Constructs a new CServerStateHandler object.
+
+    Parameters: CTestEngine* aMain
+
+    Return Values: CServerStateHandler*: New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CServerStateHandler* CServerStateHandler::NewL( CTestEngine* aTestEngine, 
+                                                CTestModuleController* aTestModuleController )
+    {
+
+    CServerStateHandler* self = 
+                        new( ELeave ) CServerStateHandler( aTestEngine, aTestModuleController );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CServerStateHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CServerStateHandler::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CServerStateHandler
+
+    Method: CServerStateHandler
+
+    Description: Constructor
+
+    Parameters: CTestEngine* aMain
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CServerStateHandler::CServerStateHandler( CTestEngine* aTestEngine, 
+                                          CTestModuleController* aTestModuleController ) :
+    CActive( CActive::EPriorityStandard ),
+    iEngine( aTestEngine ),
+    iTestModuleController( aTestModuleController )
+    {
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CServerStateHandler
+
+    Method: ~CServerStateHandler
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CServerStateHandler::~CServerStateHandler()
+    {
+    
+    Cancel();
+
+    iServerThread.Close();
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CServerStateHandler
+
+    Method: StartL
+
+    Description: Starts to monitor server thread.
+
+    Parameters: RTestServer& aServer
+
+    Return Values: TInt: 
+
+    Errors/Exceptions: 
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CServerStateHandler::StartL( RTestServer& aServer )
+    {
+    
+    __TRACE( KVerbose, ( _L( "CServerStateHandler::StartL" ) ) );
+     
+    TThreadId serverThreadId; 
+     
+    iStatus = KRequestPending;
+  
+    // Asks from server its thread ID value
+    User::LeaveIfError( aServer.GetServerThreadId ( serverThreadId ) ); 
+      
+    // Opens handle to thread
+    User::LeaveIfError( iServerThread.Open( serverThreadId ) );
+    
+    CActiveScheduler::Add( this );
+        
+    // Requests notification when this thread dies, normally or otherwise   
+    iServerThread.Logon( iStatus ); // Miten RThread hanska ko serveriin..
+   
+    SetActive();
+
+    return KErrNone;
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CServerStateHandler
+
+    Method: RunL
+
+    Description: Handles thread death.
+  
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CServerStateHandler::RunL()
+    {
+    
+    // something went badly wrong!
+    __TRACE( KInit, ( CStifLogger::ERed, 
+        _L( "Test case execution fails. Possible reason: KErrServerTerminated" ) ) );
+ 
+    RDebug::Print( _L("Test case execution fails. Possible reason: KErrServerTerminated") );     
+             
+    // Note: 
+    // More Info about STIF panic with KErrServerTerminated 
+    // will be informed to the user via testengine log and testreport    
+    // in CTestCaseController::RunL() method
+   
+    // TestModuleCrash is called for doing all needed recovering operations for enabling STIF 
+    // to continue test case execution
+    iEngine->TestModuleCrash( iTestModuleController );
+      
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CServerStateHandler
+
+    Method: DoCancel
+
+    Description: Stops listening TestServer status.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CServerStateHandler::DoCancel()
+    {
+
+    __TRACE( KVerbose, ( _L( "CServerStateHandler::DoCancel" ) ) );
+
+    // Cancels an outstanding request for notification of the death of this thread.
+    iServerThread.LogonCancel( iStatus );
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CServerStateHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError: in: Error code
+
+    Return Values:  TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CServerStateHandler::RunError( TInt aError )
+    {
+    __TRACE( KError,( _L( "CServerStateHandler::RunError" ) ) );
+    return aError;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: GenerateModuleName
+
+    Description: Check is module TestScripter. Does parsing and returns new
+                 module name and error codes(Needed operations when creating
+                 server sessions to TestScripter). 
+
+    Parameters: const TFileName& aModuleName: in: Module name for checking.
+                TFileName& aNewModuleName: inout: Parsed module name.
+
+    Return Values: KErrNone if TestScripter releated module.
+                   KErrNotFound if not TestScripter releated module.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+
+TInt GenerateModuleName(const TDesC& aModuleName,
+                        TDes& aNewModuleName)
+    {
+    // Check that length is greated than KTestScripterNameLength
+    if( aModuleName.Length() < KTestScripterNameLength )
+        {
+        return KErrNotFound;
+        }
+    // Check is TestScripter
+    TPtrC check( aModuleName.Mid( 0, KTestScripterNameLength ) );
+    TInt ret = check.CompareF( KTestScripterName );
+    if( ret == KErrNone )
+        {
+        aNewModuleName.Copy( aModuleName.Mid( 0, KTestScripterNameLength ) );
+        aNewModuleName.LowerCase();
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+
+    return KErrNone;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/TestModuleInfo.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1001 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestModuleList class and CTestModuleInfo class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include "TestModuleInfo.h"
+#include <e32svr.h>
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+#define LOGGER iLogger
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: CTestModuleInfo
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleInfo::CTestModuleInfo()
+    {
+	iLogger = NULL;
+    iModuleName = NULL;
+    iIniFileName = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: aModuleName: module name
+                aLogger: pointer to stif logger
+
+    Return Values: None
+
+    Errors/Exceptions:
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleInfo::ConstructL(TDesC& aModuleName, CStifLogger* aLogger)
+    {
+	iLogger = aLogger;
+
+	if(iModuleName)
+	    {
+        delete iModuleName;
+		iModuleName = NULL;
+        }
+    iModuleName = aModuleName.AllocL();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: aModuleName: module name
+                aLogger: pointer to stif logger
+
+    Return Values: CTestModuleInfo* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleInfo* CTestModuleInfo::NewL(TDesC& aModuleName, CStifLogger* aLogger)
+    {
+    CTestModuleInfo* self = new (ELeave) CTestModuleInfo();
+    CleanupStack::PushL(self);
+    self->ConstructL(aModuleName, aLogger);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: ~CTestModuleInfo
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleInfo::~CTestModuleInfo()
+    {
+    delete iModuleName;
+    delete iIniFileName;
+
+    iCfgFiles.ResetAndDestroy();
+    iCfgFiles.Close();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: SetIniFile
+
+    Description: Set ini file
+
+    Parameters: aIniFileName: initialization file name
+
+    Return Values: KErrNone if everything went ok
+                   KErrAlreadyExists if ini file was already set
+                   Symbian error code otherwise
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleInfo::SetIniFile(TDesC& aIniFileName)
+    {
+	if(iIniFileName)
+	    {
+        return KErrAlreadyExists;
+        }
+
+    TRAPD(err, iIniFileName = aIniFileName.AllocL());
+    if(err != KErrNone)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Could not create descriptor (CTestModuleInfo::SetIniFile) for string '%S'. Error %d."), &aIniFileName, err));
+            }
+        else
+            {
+            RDebug::Print(_L("Could not create descriptor (CTestModuleInfo::SetIniFile) for string '%S'. Error %d."), &aIniFileName, err);
+            }
+        return err;
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: AddCfgFile
+
+    Description: Add config file if it is not yet added to the array
+
+    Parameters: aCfgFileName: file name
+
+    Return Values: KErrNone if everything went ok
+                   KErrAlreadyExists if config file is already present
+                   Symbian error code otherwise
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleInfo::AddCfgFile(TDesC& aCfgFileName)
+    {
+    //Check if given file name does not exist already
+    TInt cnt = iCfgFiles.Count();
+    TInt i;
+    TFileName cfgFileName;
+
+    //Check if given module is already on the list
+    for(i = 0; i < cnt; i++)
+        {
+        iCfgFiles[i]->GetCfgFileName(cfgFileName);
+        if(cfgFileName == aCfgFileName)
+            {
+            return KErrAlreadyExists;
+			}
+        }
+
+    //Add to array
+    TInt err = KErrNone;
+    CTestCaseFileInfo* tmp = NULL;
+    TRAP(err, tmp = CTestCaseFileInfo::NewL(aCfgFileName, iLogger));
+    if(err != KErrNone)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Could not create CTestCaseFileInfo object (CTestModuleInfo::AddCfgFile). Error %d."), err));
+            }
+        else
+            {
+            RDebug::Print(_L("Could not create CTestCaseFileInfo object (CTestModuleInfo::AddCfgFile). Error %d."), err);
+            }
+		return err;
+        }
+    if(!tmp)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Could not create CTestCaseFileInfo object (CTestModuleInfo::AddCfgFile)")));
+            }
+        else
+            {
+            RDebug::Print(_L("Could not create CTestCaseFileInfo object (CTestModuleInfo::AddCfgFile)"));
+            }
+		return KErrGeneral;
+        }
+
+    err = iCfgFiles.Append(tmp);
+    if(err != KErrNone)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Could not append CTestCaseFileInfo object to array (CTestModuleInfo::AddCfgFile). Error %d."), err));
+            }
+        else
+            {
+            RDebug::Print(_L("Could not append CTestCaseFileInfo object to array (CTestModuleInfo::AddCfgFile). Error %d."), err);
+            }
+        delete tmp;
+        return err;
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: CountCfgFiles
+
+    Description: Return number of config files
+
+    Parameters: None
+
+    Return Values: number of config files
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleInfo::CountCfgFiles(void)
+    {
+    return iCfgFiles.Count();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: GetModuleName
+
+    Description: Get module name
+
+    Parameters: None
+
+    Return Values:
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleInfo::GetModuleName(TDes& aModuleName)
+    {
+    aModuleName.Zero();
+    if(iModuleName)
+        {
+        aModuleName.Copy(*iModuleName);
+        }
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: GetIniFileName
+
+    Description: Get module ini file name
+
+    Parameters: None
+
+    Return Values:
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleInfo::GetIniFileName(TDes& aIniFileName)
+    {
+    aIniFileName.Zero();
+    if(iIniFileName)
+        {
+        aIniFileName.Copy(*iIniFileName);
+        }
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: GetCfgFileName
+
+    Description: Get config file name
+
+    Parameters: aIndex: index of config file
+
+    Return Values: TDesC&: config file name
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleInfo::GetCfgFileName(TInt aIndex, TDes& aCfgFileName)
+    {
+    aCfgFileName.Zero();
+    TInt cnt = iCfgFiles.Count();
+
+    //Check index
+    if(aIndex >= cnt || aIndex < 0)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Given index reaches out of array (CTestModuleInfo::GetCfgFileName). Given index: %d. Max allowed index: %d"), aIndex, cnt - 1));
+            }
+        else
+            {
+            RDebug::Print(_L("Given index reaches out of array (CTestModuleInfo::GetCfgFileName). Given index: %d. Max allowed index: %d"), aIndex, cnt - 1);
+            }
+        return KErrArgument;
+        }
+
+    TInt ret = iCfgFiles[aIndex]->GetCfgFileName(aCfgFileName);
+    return ret;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleInfo
+
+    Method: GetUncheckedCfgFile
+
+    Description: Get first unchecked test case file
+
+    Parameters: None
+
+    Return Values: Pointer to CTestCaseFileInfo object if found
+                   Null otherwise
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseFileInfo* CTestModuleInfo::GetUncheckedCfgFile(void)
+    {
+    TInt cnt = iCfgFiles.Count();
+    TInt i;
+
+    for(i = 0; i < cnt; i++)
+        {
+        if(!iCfgFiles[i]->IsChecked())
+            {
+            return iCfgFiles[i];
+            }
+        }
+
+    return NULL;
+    }
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: CTestModuleList
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleList::CTestModuleList()
+    {
+	iLogger = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: aLogger: pointer to stif logger
+
+    Return Values: None
+
+    Errors/Exceptions:
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleList::ConstructL(CStifLogger* aLogger)
+    {
+	iLogger = aLogger;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: aLogger: pointer to stif logger
+
+    Return Values: CTestModuleList* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestModuleList* CTestModuleList::NewL(CStifLogger* aLogger)
+    {
+    CTestModuleList* self = new (ELeave) CTestModuleList();
+    CleanupStack::PushL(self);
+    self->ConstructL(aLogger);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: ~CTestModuleList
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestModuleList::~CTestModuleList()
+    {
+    iTestModules.ResetAndDestroy();
+    iTestModules.Close();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: AddTestModule
+
+    Description: Adds new test module to list if specified module is not already added.
+
+    Parameters: aModuleName: module name
+
+    Return Values: KErrNone if opereation succeeded
+                   KErrAlreadyExists if module is already present on the list
+                   Symbian error code otherwise
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleList::AddTestModule(TDesC& aModuleName)
+    {
+    //Check if given module is already on the list
+    CTestModuleInfo* tmp = GetModule(aModuleName);
+    if(tmp)
+        {
+        return KErrAlreadyExists;
+        }
+
+    //There is no module on the list, so create new info object
+    TInt err = KErrNone;
+    TRAP(err, tmp = CTestModuleInfo::NewL(aModuleName, iLogger));
+    if(err != KErrNone)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Could not create CTestModuleInfo object (CTestModuleList::AddTestModule). Error %d."), err));
+            }
+        else
+            {
+            RDebug::Print(_L("Could not create CTestModuleInfo object (CTestModuleList::AddTestModule). Error %d."), err);
+            }
+		return err;
+        }
+    if(!tmp)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Could not create CTestModuleInfo object (CTestModuleList::AddTestModule)")));
+            }
+        else
+            {
+            RDebug::Print(_L("Could not create CTestModuleInfo object (CTestModuleList::AddTestModule)"));
+            }
+		return KErrGeneral;
+        }
+
+    //Add to list
+    err = iTestModules.Append(tmp);
+    if(err != KErrNone)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Could not append CTestModuleInfo object to array (CTestModuleList::AddTestModule). Error %d."), err));
+            }
+        else
+            {
+            RDebug::Print(_L("Could not append CTestModuleInfo object to array (CTestModuleList::AddTestModule). Error %d."), err);
+            }
+        delete tmp;
+        return err;
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: Count
+
+    Description: Counts test modules
+
+    Parameters: None
+
+    Return Values: Number of test modules on list
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleList::Count()
+    {
+	return iTestModules.Count();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: GetModule
+
+    Description: Searches test module with given name
+
+    Parameters: aModuleName: module name
+
+    Return Values: Pointer to found object or NULL when not found
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestModuleInfo* CTestModuleList::GetModule(TDesC& aModuleName)
+    {
+    TInt cnt = iTestModules.Count();
+    TInt i;
+    CTestModuleInfo* tmp;
+    TName moduleName;
+
+    //Check if given module is already on the list
+    for(i = 0; i < cnt; i++)
+        {
+        tmp = iTestModules[i];
+        tmp->GetModuleName(moduleName);
+        if(moduleName == aModuleName)
+            {
+            return tmp;
+			}
+        }
+    return NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: GetModule
+
+    Description: Searches test module with given index
+
+    Parameters: aIndex: module index
+
+    Return Values: Pointer to found object or NULL when not found
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestModuleInfo* CTestModuleList::GetModule(TInt aIndex)
+    {
+    TInt cnt = iTestModules.Count();
+
+    //Check index
+    if(aIndex >= cnt || aIndex < 0)
+        {
+        if(iLogger)
+            {
+            __TRACE(KError, (_L("Given index reaches out of array (CTestModuleList::GetModule). Given index: %d. Max allowed index: %d"), aIndex, cnt - 1));
+            }
+        else
+            {
+            RDebug::Print(_L("Given index reaches out of array (CTestModuleList::GetModule). Given index: %d. Max allowed index: %d"), aIndex, cnt - 1);
+            }
+        return NULL;
+        }
+
+    //return module
+    return iTestModules[aIndex];
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleList
+
+    Method: GetUncheckedCfgFile
+
+    Description: Get first unchecked test case file (module: testscripter and testcombiner)
+
+    Parameters: None
+
+    Return Values: Pointer to CTestCaseFileInfo object if found
+                   Null otherwise
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestCaseFileInfo* CTestModuleList::GetUncheckedCfgFile(void)
+    {
+    CTestCaseFileInfo* ret = NULL;
+
+    TBuf<12> modname(_L("testscripter"));
+    CTestModuleInfo* mod = GetModule(modname);
+
+    if(mod)
+        {
+        ret = mod->GetUncheckedCfgFile();
+        }
+
+    if(!ret)
+	    {
+        modname.Copy(_L("testcombiner"));
+        mod = GetModule(modname);
+        if(mod)
+            {
+            ret = mod->GetUncheckedCfgFile();
+            }
+        }
+
+    return ret;
+    }
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseFileInfo
+
+    Method: CTestCaseFileInfo
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseFileInfo::CTestCaseFileInfo()
+    {
+	iLogger = NULL;
+    iCfgFileName = NULL;
+    iChecked = EFalse;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseFileInfo
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: aCfgFileName: config file name
+                aLogger: pointer to Stif logger
+
+    Return Values: None
+
+    Errors/Exceptions:
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseFileInfo::ConstructL(TDesC& aCfgFileName, CStifLogger* aLogger)
+    {
+	iLogger = aLogger;
+
+	if(iCfgFileName)
+	    {
+        delete iCfgFileName;
+		iCfgFileName = NULL;
+        }
+    iCfgFileName = aCfgFileName.AllocL();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseFileInfo
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: aCfgFileName: config file name
+                aLogger: pointer to stif logger
+
+    Return Values: CTestCaseFileInfo* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseFileInfo* CTestCaseFileInfo::NewL(TDesC& aCfgFileName, CStifLogger* aLogger)
+    {
+    CTestCaseFileInfo* self = new (ELeave) CTestCaseFileInfo();
+    CleanupStack::PushL(self);
+    self->ConstructL(aCfgFileName, aLogger);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseFileInfo
+
+    Method: ~CTestCaseFileInfo
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseFileInfo::~CTestCaseFileInfo()
+    {
+    delete iCfgFileName;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseFileInfo
+
+    Method: GetCfgFileName
+
+    Description: Get config file name
+
+    Parameters: None
+
+    Return Values: TDesC& : config file name
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestCaseFileInfo::GetCfgFileName(TDes& aCfgFileName)
+    {
+    aCfgFileName.Zero();
+    if(iCfgFileName)
+        {
+        aCfgFileName.Copy(*iCfgFileName);
+        }
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseFileInfo
+
+    Method: SetChecked
+
+    Description: Set configuration file as already checked
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CTestCaseFileInfo::SetChecked(void)
+    {
+    iChecked = ETrue;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseFileInfo
+
+    Method: IsChecked
+
+    Description: Return if config file has been checked
+
+    Parameters: None
+
+    Return Values: 0 if test case file has not been checked yet
+                   other value otherwise
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestCaseFileInfo::IsChecked(void)
+    {
+    return iChecked;
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/TestReport.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1421 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CTestReport 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include <f32file.h>
+#include <hal.h>
+#include "TestReport.h"
+#include "TestEngineCommon.h"
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+const TInt KMaxLenEol = 6;
+const TInt KMaxReportData = 256;
+typedef TBuf<KMaxReportData> TPrintInfo;
+const TInt KSummaryLineEndLen = 12;
+_LIT( KSummaryLineEnd,  "            ");
+
+// XML Tags (alphabetically)
+_LIT(KXMLCaseNumberTag,          "<CaseNumber>");
+_LIT(KXMLCaseNumberTagEnd,       "</CaseNumber>");
+_LIT(KXMLCaseTitleTag,           "<Title>");
+_LIT(KXMLCaseTitleTagEnd,        "</Title>");
+_LIT(KXMLConfigFileTag,          "<Config>");
+_LIT(KXMLConfigFileTagEnd,       "</Config>");
+_LIT(KXMLCpuSpeedTag,            "<CPUSpeed>");
+_LIT(KXMLCpuSpeedTagEnd,         "</CPUSpeed>");
+_LIT(KXMLCpuTag,                 "<CPU>");
+_LIT(KXMLCpuTagEnd,              "</CPU>");
+_LIT(KXMLCrashedTag,             "<Crashed>");
+_LIT(KXMLCrashedTagEnd,          "</Crashed>");
+_LIT(KXMLDateTag,                "<Date>");
+_LIT(KXMLDateTagEnd,             "</Date>");
+_LIT(KXMLDllSummaryTag,          "<Dlls>");
+_LIT(KXMLDllSummaryTagEnd,       "</Dlls>");
+_LIT(KXMLDllTag,                 "<Dll>");
+_LIT(KXMLDllTagEnd,              "</Dll>");
+_LIT(KXMLEndTimeTag,             "<EndTime>");
+_LIT(KXMLEndTimeTagEnd,          "</EndTime>");
+_LIT(KXMLEnvironmentInfoTag,     "<EnvironmentInfo>");
+_LIT(KXMLEnvironmentInfoTagEnd,  "</EnvironmentInfo>");
+_LIT(KXMLExecutionResultTag,     "<ExecutionResultCode>");
+_LIT(KXMLExecutionResultTagEnd,  "</ExecutionResultCode>");
+_LIT(KXMLFailedTag,              "<Failed>");
+_LIT(KXMLFailedTagEnd,           "</Failed>");
+_LIT(KXMLFileNameTag,            "<FileName>");
+_LIT(KXMLFileNameTagEnd,         "</FileName>");
+_LIT(KXMLHardwareInfoTag,        "<HardwareInfo>");
+_LIT(KXMLHardwareInfoTagEnd,     "</HardwareInfo>");
+_LIT(KXMLHwRevisionTag,          "<HwRevision>");
+_LIT(KXMLHwRevisionTagEnd,       "</HwRevision>");
+_LIT(KXMLLanguageTag,            "<Language>");
+_LIT(KXMLLanguageTagEnd,         "</Language>");
+_LIT(KXMLMachineUidTag,          "<MachineUID>");
+_LIT(KXMLMachineUidTagEnd,       "</MachineUID>");
+_LIT(KXMLManufacturerTag,        "<Manufacturer>");
+_LIT(KXMLManufacturerTagEnd,     "</Manufacturer>");
+_LIT(KXMLMemoryInfoTag,          "<MemoryInfo>");
+_LIT(KXMLMemoryInfoTagEnd,       "</MemoryInfo>");
+_LIT(KXMLModelTag,               "<Model>");
+_LIT(KXMLModelTagEnd,            "</Model>");
+_LIT(KXMLModuleNameTag,          "<ModuleName>");
+_LIT(KXMLModuleNameTagEnd,       "</ModuleName>");
+_LIT(KXMLModuleSummaryTag,       "<Modules>");
+_LIT(KXMLModuleSummaryTagEnd,    "</Modules>");
+_LIT(KXMLModuleTag,              "<Module>");
+_LIT(KXMLModuleTagEnd,           "</Module>");
+_LIT(KXMLPassedTag,              "<Passed>");
+_LIT(KXMLPassedTagEnd,           "</Passed>");
+_LIT(KXMLRamFreeTag,             "<RAMFree>");
+_LIT(KXMLRamFreeTagEnd,          "</RAMFree>");
+_LIT(KXMLRamTag,                 "<RAM>");
+_LIT(KXMLRamTagEnd,              "</RAM>");
+_LIT(KXMLResultDescrTag,         "<ResultDescription>");
+_LIT(KXMLResultDescrTagEnd,      "</ResultDescription>");
+_LIT(KXMLResultTag,              "<Result>");
+_LIT(KXMLResultTagEnd,           "</Result>");
+_LIT(KXMLSoftwareInfoTag,        "<SoftwareInfo>");
+_LIT(KXMLSoftwareInfoTagEnd,     "</SoftwareInfo>");
+_LIT(KXMLStartTimeTag,           "<StartTime>");
+_LIT(KXMLStartTimeTagEnd,        "</StartTime>");
+_LIT(KXMLSwBuildTag,             "<SwBuild>");
+_LIT(KXMLSwBuildTagEnd,          "</SwBuild>");
+_LIT(KXMLSwRevisionTag,          "<SwRevision>");
+_LIT(KXMLSwRevisionTagEnd,       "</SwRevision>");
+_LIT(KXMLTestCasesSummaryTag,    "<TestCasesSummary>");
+_LIT(KXMLTestCasesSummaryTagEnd, "</TestCasesSummary>");
+_LIT(KXMLTestCasesTag,           "<TestCases>");
+_LIT(KXMLTestCasesTagEnd,        "</TestCases>");
+_LIT(KXMLTestCaseTag,            "<TestCase>");
+_LIT(KXMLTestCaseTagEnd,         "</TestCase>");
+_LIT(KXMLTestReportTag,          "<TestReport>");
+_LIT(KXMLTestReportTagEnd,       "</TestReport>");
+_LIT(KXMLTestResultTag,          "<ResultCode>");
+_LIT(KXMLTestResultTagEnd,       "</ResultCode>");
+_LIT(KXMLTimeoutedTag,           "<Timeout>");
+_LIT(KXMLTimeoutedTagEnd,        "</Timeout>");
+_LIT(KXMLTimeTag,                "<Time>");
+_LIT(KXMLTimeTagEnd,             "</Time>");
+_LIT(KXMLTotalTag,               "<Total>");
+_LIT(KXMLTotalTagEnd,            "</Total>");
+_LIT(KXMLVersionTag,             "<Version>");
+_LIT(KXMLVersionTagEnd,          "</Version>");
+_LIT(KXMLSTIFVersionTag,         "<STIFVersion>");
+_LIT(KXMLSTIFVersionTagEnd,      "</STIFVersion>");
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: CTestReport
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: const TTestReportMode aReportMode: in: Report mode
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestReport::CTestReport( const TTestReportMode aReportMode ):
+    iReportMode( aReportMode ) 
+    {
+    iXML = EFalse;
+    iReportHWInfo = TTestHWInfo();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: CTestReportSettings& aTestReportSettings: in: Report settings
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation for iTotalSummary fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::ConstructL( CTestReportSettings& aTestReportSettings )
+    {
+    // Create summary for all test cases
+    _LIT( KName, "All test cases" );
+    iTotalSummary = new ( ELeave ) TTestSummary( KName() );
+
+    User::LeaveIfError( iFs.Connect() );
+    
+    TPtrC path;
+    path.Set( aTestReportSettings.iPath->Des() );
+    TPtrC name;
+    name.Set( aTestReportSettings.iName->Des() );
+
+    iFormat = aTestReportSettings.iFormat;
+    iOutput = aTestReportSettings.iOutput;
+    iXML = aTestReportSettings.iXML;
+    
+    // XML format can be used only when report is of txt file type.
+    if(iFormat != CStifLogger::ETxt && iOutput != CStifLogger::EFile && iXML)
+        {
+        RDebug::Print(_L("Stif: XML report is available only when TestReportFormat is TXT and TestReportOutput is FILE"));
+        iXML = EFalse;
+        }
+    
+    if( iOutput == CStifLogger::EFile )
+        {
+        iFs.MkDirAll( path );
+        
+        HBufC* pathAndFileBuf = HBufC::NewLC( path.Length() + name.Length() + 5 );
+        TPtr pathAndFile(pathAndFileBuf->Des() );
+        pathAndFile.Append( path );
+        pathAndFile.Append( name );
+
+        if(iXML)
+            {
+            pathAndFile.Append( _L(".xml") );
+            }
+        else
+            {
+            if( ( iFormat == CStifLogger::EHtml ) && 
+                ( iOutput == CStifLogger::EFile ) )
+                {
+                pathAndFile.Append( _L(".html") );
+                }
+            else 
+                {
+                pathAndFile.Append( _L(".txt") );
+                }
+            }
+        
+        if( aTestReportSettings.iOverwrite )
+            {
+            User::LeaveIfError( iFile.Replace( iFs, 
+                           pathAndFile,
+                           EFileWrite | EFileStreamText | EFileShareExclusive ) );
+            }
+        else
+            {
+            TInt fileOpen = iFile.Open( iFs, 
+                                        pathAndFile, 
+                                        EFileWrite | EFileStreamText | EFileShareAny );
+            if( fileOpen == KErrNotFound )
+                {
+                User::LeaveIfError( 
+                    iFile.Create( iFs, 
+                                  pathAndFile, 
+                                  EFileWrite | EFileStreamText | EFileShareExclusive ) );
+                }
+            else if( fileOpen == KErrNone )
+                {
+                TInt endPosOfFile = 0;
+                User::LeaveIfError( iFile.Seek( ESeekEnd, endPosOfFile ) );
+                }
+            else
+                {
+                User::Leave( fileOpen );
+                }
+            }
+       
+        CleanupStack::PopAndDestroy( pathAndFileBuf );
+        }
+            
+    WriteHeaderL();
+    
+    // Add temporarily closing tags to keep valid xml structure
+    CloseXMLTagsInUnfinishedFileL();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestReportSettings& aTestReportSettings: in: Report settings
+                const TTestReportMode aReportMode: in: Report mode
+    
+    Return Values: CTestReport* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestReport* CTestReport::NewL( CTestReportSettings& aTestReportSettings,
+                                const TTestReportMode aReportMode )
+    {
+    CTestReport* self = new ( ELeave ) CTestReport( aReportMode );
+    CleanupStack::PushL( self );
+    self->ConstructL( aTestReportSettings );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: ~CTestReport
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestReport::~CTestReport()
+    {
+    iTestModulesVersionsInfo.ResetAndDestroy();
+    iTestModulesVersionsInfo.Close();
+        
+    // Reset and destroy arrays
+    iTestSummaries.ResetAndDestroy();
+    delete iTotalSummary;
+    if( iOutput != CStifLogger::ERDebug )
+        {
+        // Delete file
+        iFile.Close();
+        iFs.Close();
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: AddTestCaseResultL
+
+    Description: Add new test case result.
+
+    Parameters: const TTestInfo& aTestInfo: in: TTestInfo: Test info
+                const TFullTestResult& aTestResult: in: TTestResult: Testresult
+                const TInt aError: in: Symbian OS error: Additional error code
+
+    Return Values: None
+
+    Errors/Exceptions: Leave is iReportGenerated is generated
+                       Leave if summary creation fails
+                       Leave if summary adding fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::AddTestCaseResultL( const TTestInfo& aTestInfo,
+                                        const TFullTestResult& aTestResult,
+                                        const TInt aError )
+    {
+    // Create summary for this test case
+    TTestCaseSummary summary;
+    
+    summary.iTestInfo = aTestInfo;
+    summary.iFullTestResult = aTestResult;
+
+    TBool passed( EFalse );
+    TBool crashed( EFalse );
+    TBool timeout( EFalse );
+    if( ( aError == KErrNone ) && 
+         ( summary.iFullTestResult.iCaseExecutionResultType == TFullTestResult::ECaseExecuted ) &&
+         ( KErrNone == summary.iFullTestResult.iTestResult.iResult ) )
+        {
+        passed = ETrue;
+        }
+    else if( summary.iFullTestResult.iCaseExecutionResultType == TFullTestResult::ECaseTimeout )
+        {
+        timeout = ETrue;
+        }
+    else if( ( summary.iFullTestResult.iCaseExecutionResultCode != KErrNone )
+    		|| ( summary.iFullTestResult.iCaseExecutionResultType == TFullTestResult::ECasePanic )
+    		|| ( summary.iFullTestResult.iCaseExecutionResultType == TFullTestResult::ECaseException ) )
+        {
+        crashed = ETrue;
+        }
+
+    if ( iReportMode & ETestReportCases )
+        {
+        // Print summary to file
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLTestCaseTag);
+            WriteLineL(_L("%S%S%S"), &KXMLModuleNameTag, &summary.iTestInfo.iModuleName, &KXMLModuleNameTagEnd);
+            if(summary.iTestInfo.iConfig != KNullDesC)
+                {
+                WriteLineL(_L("%S%S%S"), &KXMLConfigFileTag, &summary.iTestInfo.iConfig, &KXMLConfigFileTagEnd);
+                }
+            WriteLineL(_L("%S%d%S"), &KXMLCaseNumberTag, summary.iTestInfo.iTestCaseInfo.iCaseNumber, &KXMLCaseNumberTagEnd);
+            WriteLineL(_L("%S%S%S"), &KXMLCaseTitleTag, &summary.iTestInfo.iTestCaseInfo.iTitle, &KXMLCaseTitleTagEnd);
+            }
+        else
+            {
+            WriteLineL( _L("[%S][%S][%d] Title:[%S]"),
+                &summary.iTestInfo.iModuleName,
+                &summary.iTestInfo.iConfig,
+                summary.iTestInfo.iTestCaseInfo.iCaseNumber,
+                &summary.iTestInfo.iTestCaseInfo.iTitle );
+            }
+
+        const TInt KTimeFieldLength = 30;
+        TBuf<KTimeFieldLength> startTime;
+        TBuf<KTimeFieldLength> endTime;
+        _LIT(KDateString4,"%-B%:0%J%:1%T%:2%S%.%*C4%:3%+B");
+        summary.iFullTestResult.iStartTime.FormatL(
+            startTime,KDateString4 );
+        summary.iFullTestResult.iEndTime.FormatL(
+            endTime,KDateString4 );
+            
+        // Result description needs max length 0x80(Must be same as
+        // TResultDes length) + specific characters see below.
+        TBuf<KMaxReportData> printBuf2;
+        TInt code = CStifLogger::ENoStyle;
+        if( ( summary.iFullTestResult.iCaseExecutionResultType 
+        	!= TFullTestResult::ECasePanic ) &&
+        	( summary.iFullTestResult.iCaseExecutionResultCode 
+            == KErrNone ) )
+            {
+            printBuf2.AppendFormat( _L("\tResult: %d [%S]"),
+                summary.iFullTestResult.iTestResult.iResult,
+                &summary.iFullTestResult.iTestResult.iResultDes );
+
+            if ( KErrNone == 
+                 summary.iFullTestResult.iTestResult.iResult )
+                {
+                printBuf2.AppendFormat( _L(" ==> PASSED"));
+                }
+            else
+                {
+                code = CStifLogger::ERed;
+                printBuf2.AppendFormat( _L(" ==> FAILED"));
+                }
+            }
+        else
+            {
+            code = CStifLogger::ERed;
+            printBuf2.AppendFormat( _L("\tCaseExecutionResult: %S with %d"),
+                &summary.iFullTestResult.iTestResult.iResultDes,
+                summary.iFullTestResult.iCaseExecutionResultCode );
+            }
+
+        if(iXML)
+            {
+            WriteLineL(_L("%S%S%S"), &KXMLStartTimeTag, &startTime, &KXMLStartTimeTagEnd);
+            WriteLineL(_L("%S%S%S"), &KXMLEndTimeTag, &endTime, &KXMLEndTimeTagEnd);
+            WriteLineL(_L("%S%d%S"), &KXMLTestResultTag, summary.iFullTestResult.iTestResult.iResult, &KXMLTestResultTagEnd);
+            WriteLineL(_L("%S%S%S"), &KXMLResultDescrTag, &summary.iFullTestResult.iTestResult.iResultDes, &KXMLResultDescrTagEnd);
+            WriteLineL(_L("%S%d%S"), &KXMLExecutionResultTag, summary.iFullTestResult.iCaseExecutionResultCode, &KXMLExecutionResultTagEnd);
+            }
+        else
+            {
+            WriteLineL( _L("\tStartTime: %S, EndTime: %S"),
+                &startTime,
+                &endTime );
+            WriteLineL( printBuf2, code );
+            WriteDelimiterL( _L( "- " ), 10 );
+            WriteLineL( _L( "" ) );
+            }
+        }
+        
+    // Add test summary
+    // Check if the module already exists for this test case
+    TTestSummary* moduleSummary = NULL;
+    TInt count = iTestSummaries.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if ( iTestSummaries[i]->iName == aTestInfo.iModuleName )
+            {
+            moduleSummary = iTestSummaries[i];
+            break;
+            }
+        }
+    
+    if( moduleSummary == NULL )
+        {
+        // Create new module array
+        moduleSummary = new ( ELeave ) TTestSummary( aTestInfo.iModuleName );
+        User::LeaveIfError( iTestSummaries.Append( moduleSummary ) );
+        }
+
+    if( passed )
+        {
+        moduleSummary->iPassedCases++;
+        iTotalSummary->iPassedCases++;
+        if(iXML && (iReportMode & ETestReportCases))
+            {
+            WriteLineL(_L("%SPASSED%S"), &KXMLResultTag, &KXMLResultTagEnd);
+            }
+        }
+    else if( timeout )
+        {
+        moduleSummary->iTimeoutCases++;
+        iTotalSummary->iTimeoutCases++;
+        if(iXML && (iReportMode & ETestReportCases))
+            {
+            WriteLineL(_L("%STIMEOUT%S"), &KXMLResultTag, &KXMLResultTagEnd);
+            }
+        }
+    else if( crashed ||
+           ( aError != KErrNone ) )
+        {
+        moduleSummary->iCrashedCases++;
+        iTotalSummary->iCrashedCases++;
+        if(iXML && (iReportMode & ETestReportCases))
+            {
+            WriteLineL(_L("%SCRASHED%S"), &KXMLResultTag, &KXMLResultTagEnd);
+            }
+        }
+    else
+        {
+        moduleSummary->iFailedCases++;
+        iTotalSummary->iFailedCases++;
+        if(iXML && (iReportMode & ETestReportCases))
+            {
+            WriteLineL(_L("%SFAILED%S"), &KXMLResultTag, &KXMLResultTagEnd);
+            }
+        }
+
+    if(iXML && (iReportMode & ETestReportCases))
+        {
+        WriteLineL(_L("%S"), &KXMLTestCaseTagEnd);
+        }
+
+    // Add temporarily closing tags to keep valid xml structure
+    CloseXMLTagsInUnfinishedFileL();
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: WriteHeaderL
+
+    Description: Write test report header.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::WriteHeaderL()
+    {
+    if( ( iFormat == CStifLogger::EHtml ) && 
+        ( iOutput == CStifLogger::EFile ) )
+        {        
+        // Html start tags to whole page and header section
+        iFile.Write(
+            _L8( "\n<html>\n<head>\n<title>TestReport</title>\n</head>\n\n\n<body>\n" ) );
+        }
+    
+    if(iXML)
+        {
+        WriteLineL(_L("<?xml version=\"1.0\" ?>"));
+        WriteLineL(_L("%S"), &KXMLTestReportTag);            
+        }
+    else
+        {
+        WriteDelimiterL( _L( "***" ), 25 );
+        }
+
+    // Generate date and time
+    TTime time;
+    time.HomeTime();
+    TBuf<30> date;
+    TBuf<30> clock;
+    // Date
+    _LIT( KDate, "%E%D%X%N%Y %1 %2 %3" );
+    time.FormatL( date, KDate );
+    // Time
+    _LIT( KClock,"%-B%:0%J%:1%T%:2%S%:3%+B" );
+    time.FormatL( clock,KClock );
+    // Add date and time
+    if(iXML)
+        {
+        WriteLineL(_L("%S%S%S"), &KXMLDateTag, &date, &KXMLDateTagEnd);
+        WriteLineL(_L("%S%S%S"), &KXMLTimeTag, &clock, &KXMLTimeTagEnd);
+        }
+    else
+        {
+        WriteLineL( _L( "%S" ), &date );
+        WriteLineL( _L( "%S" ), &clock );
+        }
+
+    // Add STIF version info
+    TInt majorV;
+    TInt minorV;
+    TInt buildV;
+    TBuf<30> relDate;
+    TStifUtil::STIFVersion(majorV, minorV, buildV, relDate);
+    if(iXML)
+        {
+        WriteLineL(_L("%S%d.%d.%d (%S)%S"), &KXMLSTIFVersionTag, majorV, minorV, buildV, &relDate, &KXMLSTIFVersionTagEnd);
+        }
+    else
+        {
+        WriteLineL(_L("v.%d.%d.%d (%S)"), majorV, minorV, buildV, &relDate);
+        }
+    
+    if ( iReportMode & ETestReportSummary )
+        {
+        if( iOutput == CStifLogger::EFile )
+            {
+            // Get current file position
+            iSummaryPos = 0;
+            User::LeaveIfError( iFile.Seek( ESeekCurrent, iSummaryPos ) );
+            }
+        // Generate Summary to Report
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLTestCasesSummaryTag);
+            WriteLineL(_L("%S%S%S"), &KXMLPassedTag, &KXMLPassedTagEnd, &KSummaryLineEnd);
+            WriteLineL(_L("%S%S%S"), &KXMLFailedTag, &KXMLFailedTagEnd, &KSummaryLineEnd);
+            WriteLineL(_L("%S%S%S"), &KXMLTimeoutedTag, &KXMLTimeoutedTagEnd, &KSummaryLineEnd);
+            WriteLineL(_L("%S%S%S"), &KXMLCrashedTag, &KXMLCrashedTagEnd, &KSummaryLineEnd);
+            WriteLineL(_L("%S%S%S"), &KXMLTotalTag, &KXMLTotalTagEnd, &KSummaryLineEnd);
+            WriteLineL(_L("%S"), &KXMLTestCasesSummaryTagEnd);
+            }
+        else
+            {
+            WriteDelimiterL( _L( "-- " ), 25 );
+            WriteLineL(_L("SUMMARY:") );
+            WriteLineL(_L("\tPassed cases: %S"), &KSummaryLineEnd );
+            WriteLineL(_L("\tFailed cases: %S"), &KSummaryLineEnd );
+            WriteLineL(_L("\tTimeout cases: %S"), &KSummaryLineEnd );
+            WriteLineL(_L("\tCrashed cases: %S"), &KSummaryLineEnd );
+            WriteLineL(_L("\tTotal cases: %S"), &KSummaryLineEnd );
+            WriteLineL( _L( "" ));
+            }   
+        }
+
+    if ( iReportMode & ETestReportEnvironment )
+        {
+        const TInt KMegaByte = 1024*1024;
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLEnvironmentInfoTag);
+            WriteLineL(_L("%S"), &KXMLHardwareInfoTag);
+            WriteLineL(_L("%S0x%x%S"), &KXMLManufacturerTag, iReportHWInfo.iHwInfo.iManufacturer, &KXMLManufacturerTagEnd);
+            WriteLineL(_L("%S0x%x%S"), &KXMLMachineUidTag, iReportHWInfo.iHwInfo.iMachineUid, &KXMLMachineUidTagEnd);
+            WriteLineL(_L("%S0x%x%S"), &KXMLModelTag, iReportHWInfo.iHwInfo.iModel, &KXMLModelTagEnd);
+            WriteLineL(_L("%S0x%x%S"), &KXMLHwRevisionTag, iReportHWInfo.iHwInfo.iHwRev, &KXMLHwRevisionTagEnd);
+            WriteLineL(_L("%S0x%x%S"), &KXMLCpuTag, iReportHWInfo.iHwInfo.iCpu, &KXMLCpuTagEnd);
+            WriteLineL(_L("%S%d%S"), &KXMLCpuSpeedTag, iReportHWInfo.iHwInfo.iCpuSpeed/1000, &KXMLCpuSpeedTagEnd);
+            WriteLineL(_L("%S%d%S"), &KXMLLanguageTag, iReportHWInfo.iHwInfo.iLanguage, &KXMLLanguageTagEnd);
+            WriteLineL(_L("%S"), &KXMLHardwareInfoTagEnd);
+            WriteLineL(_L("%S"), &KXMLSoftwareInfoTag);
+            WriteLineL(_L("%S0x%x%S"), &KXMLSwRevisionTag, iReportHWInfo.iSwInfo.iSwRev, &KXMLSwRevisionTagEnd);
+            WriteLineL(_L("%S0x%x%S"), &KXMLSwBuildTag, iReportHWInfo.iSwInfo.iSwBuild, &KXMLSwBuildTagEnd);
+            WriteLineL(_L("%S"), &KXMLSoftwareInfoTagEnd);
+            WriteLineL(_L("%S"), &KXMLMemoryInfoTag);
+            WriteLineL(_L("%S%d%S"), &KXMLRamTag, iReportHWInfo.iMemoryInfo.iRAM/KMegaByte, &KXMLRamTagEnd);
+            WriteLineL(_L("%S%d%S"), &KXMLRamFreeTag, iReportHWInfo.iMemoryInfo.iRAMFree/KMegaByte, &KXMLRamFreeTagEnd);
+            WriteLineL(_L("%S"), &KXMLMemoryInfoTagEnd);            
+            WriteLineL(_L("%S"), &KXMLEnvironmentInfoTagEnd);            
+            }
+        else
+            {
+            // HW Info
+            WriteDelimiterL( _L( "-- " ), 25 );
+            WriteLineL( _L("ENVIRONMENT INFO:") );
+            WriteLineL( _L("HW Info:") );
+    
+            WriteLineL(
+                _L("\tManufacturer: 0x%x, MachineUid: 0x%x, Model: 0x%x "),
+                    iReportHWInfo.iHwInfo.iManufacturer,
+                    iReportHWInfo.iHwInfo.iMachineUid,
+                    iReportHWInfo.iHwInfo.iModel );
+            WriteLineL(
+                _L("\tHW Rev: 0x%x, CPU: 0x%x, CPU Speed: %d MHz "),
+                    iReportHWInfo.iHwInfo.iHwRev,
+                    iReportHWInfo.iHwInfo.iCpu,
+                    iReportHWInfo.iHwInfo.iCpuSpeed/1000 );
+            WriteLineL(_L("\tLanguage: %d "),
+                iReportHWInfo.iHwInfo.iLanguage );
+    
+            // SW Info
+            WriteLineL(_L("SW Info:") );
+            WriteLineL(_L("\tSW Rev: 0x%x, SW Build: 0x%x"),
+                iReportHWInfo.iSwInfo.iSwRev,
+                iReportHWInfo.iSwInfo.iSwBuild );
+    
+            // Memory Info
+            WriteLineL(_L("Memory Info:") );
+            WriteLineL(_L("\tRAM: %d MB, RAM Free: %d MB"),
+                ( iReportHWInfo.iMemoryInfo.iRAM/KMegaByte ),
+                ( iReportHWInfo.iMemoryInfo.iRAMFree/KMegaByte ) );
+    
+            WriteLineL( _L( "" ) );
+            }
+        }
+        
+    if ( iReportMode & ETestReportCases )
+        {
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLTestCasesTag);
+            }
+        else
+            {
+            // Generate Test Cases to Report
+            WriteDelimiterL( _L( "-- " ), 25 );
+            WriteLineL( _L("TESTCASE SUMMARY:") );
+            }
+        }
+
+    if ( iReportMode == ETestReportBlank )
+        {
+        if(!iXML)
+            {
+            WriteLineL( _L( "") );
+            WriteLineL( _L( "'Empty' configuration given in initialization file's [Engine_Defaults] section" ) );
+            WriteLineL( _L( "No test report created" ) );
+            }
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: WriteTrailerL
+
+    Description: Write test report trailer.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::WriteTrailerL()
+    {
+    if(iXML && (iReportMode & ETestReportCases))
+        {
+        WriteLineL(_L("%S"), &KXMLTestCasesTagEnd);
+        }
+
+    if ( iReportMode & ETestReportSummary )
+        {
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLModuleSummaryTag);            
+            }
+        else
+            {
+            WriteDelimiterL( _L( "-- " ), 25 );
+            WriteLineL(_L("TESTMODULE SUMMARIES:") );
+            }
+        // Generate module related reports
+        for ( TInt k = 0; k < iTestSummaries.Count(); k++ )
+            {
+            if(iXML)
+                {
+                WriteLineL(_L("%S"), &KXMLModuleTag);
+                WriteLineL(_L("%S%S%S"), &KXMLModuleNameTag, &iTestSummaries[k]->iName, &KXMLModuleNameTagEnd);
+                WriteLineL(_L("%S%d%S"), &KXMLPassedTag, iTestSummaries[k]->iPassedCases, &KXMLPassedTagEnd);
+                WriteLineL(_L("%S%d%S"), &KXMLFailedTag, iTestSummaries[k]->iFailedCases, &KXMLFailedTagEnd);
+                WriteLineL(_L("%S%d%S"), &KXMLTimeoutedTag, iTestSummaries[k]->iTimeoutCases, &KXMLTimeoutedTagEnd);
+                WriteLineL(_L("%S%d%S"), &KXMLCrashedTag, iTestSummaries[k]->iCrashedCases, &KXMLCrashedTagEnd);
+                WriteLineL(_L("%S%d%S"), &KXMLTotalTag, iTestSummaries[k]->iPassedCases + iTestSummaries[k]->iFailedCases + iTestSummaries[k]->iTimeoutCases + iTestSummaries[k]->iCrashedCases, &KXMLTotalTagEnd);
+                WriteLineL(_L("%S"), &KXMLModuleTagEnd);
+                }
+            else
+                {
+                WriteLineL(_L("Module: [%S]"),
+                    &iTestSummaries[k]->iName );
+                WriteLineL(_L("\tPassed cases: %d"),
+                    iTestSummaries[k]->iPassedCases );
+                WriteLineL(_L("\tFailed cases: %d"),
+                    iTestSummaries[k]->iFailedCases );
+                WriteLineL(_L("\tTimeout cases: %d"),
+                    iTestSummaries[k]->iTimeoutCases );
+                WriteLineL(_L("\tCrashed cases: %d"),
+                    iTestSummaries[k]->iCrashedCases );
+                TInt moduleTotal = iTestSummaries[k]->iPassedCases +
+                    iTestSummaries[k]->iFailedCases +
+                    iTestSummaries[k]->iTimeoutCases +
+                    iTestSummaries[k]->iCrashedCases;
+                WriteLineL(_L("\tTotal cases: %d"), moduleTotal );
+                WriteLineL( _L( "" ) );
+                }
+            }
+
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLModuleSummaryTagEnd);            
+            }
+
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLDllSummaryTag);            
+            }
+        else
+            {
+            WriteDelimiterL(_L( "-- " ), 25 );
+            WriteLineL(_L("TEST MODULES VERSIONS:"));
+            }
+
+        // Generate test module versions info
+        for( TInt i = 0; i < iTestModulesVersionsInfo.Count(); i++ )
+            {
+            TTestModuleVersionInfo* versionInfo = (TTestModuleVersionInfo*)iTestModulesVersionsInfo[i];
+            if(iXML)
+                {
+                WriteLineL(_L("%S"), &KXMLDllTag);
+                WriteLineL(_L("%S%S%S"), &KXMLFileNameTag, &(versionInfo->iTestModuleName), &KXMLFileNameTagEnd);
+                WriteLineL(_L("%S%d.%d.%d%S"), &KXMLVersionTag, versionInfo->iMajor, versionInfo->iMinor, versionInfo->iBuild, &KXMLVersionTagEnd);
+                WriteLineL(_L("%S"), &KXMLDllTagEnd);
+                }
+            else
+                {
+                WriteLineL(_L("%S %d.%d.%d"), &(versionInfo->iTestModuleName), versionInfo->iMajor, versionInfo->iMinor, versionInfo->iBuild);
+                }
+            }
+
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLDllSummaryTagEnd);            
+            }
+        }
+    
+    if(!iXML)
+        {
+        WriteLineL( _L( "" ) );
+        }
+    
+    if( ( iFormat == CStifLogger::EHtml ) && 
+        ( iOutput == CStifLogger::EFile ) )
+        {        
+        // Html start tags to whole page and header section
+        iFile.Write(
+            _L8( "\n\n\n</html>\n</body>\n\n\n" ) );
+        }
+
+    if(iXML)
+        {
+        WriteLineL(_L("%S"), &KXMLTestReportTagEnd);            
+        }
+    }
+            
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: UpdateReportSummaryL
+
+    Description: Updates the test report summary.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::UpdateReportSummaryL()
+    {
+    TInt currentPos = 0;
+    // Add numeric information to summary
+    if ( iReportMode & ETestReportSummary )
+        {
+        // Go to the summary start position of the file
+        if( iOutput == CStifLogger::EFile )
+            {
+            User::LeaveIfError(iFile.Seek(ESeekCurrent, currentPos));//Get current position
+            User::LeaveIfError( iFile.Seek( ESeekStart, iSummaryPos ) );
+            }
+        TBuf<KSummaryLineEndLen> numStr;        
+        // Generate Summary to Report
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLTestCasesSummaryTag);
+            }
+        else
+            {
+            WriteDelimiterL( _L( "-- " ), 25 );
+            WriteLineL(_L("SUMMARY:") );
+            }
+        numStr.Num( iTotalSummary->iPassedCases );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLPassedTag, &numStr, &KXMLPassedTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tPassed cases: %S"), &numStr );
+            }
+        
+        numStr.Num( iTotalSummary->iFailedCases );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLFailedTag, &numStr, &KXMLFailedTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tFailed cases: %S"), &numStr );
+            }
+            
+        numStr.Num( iTotalSummary->iTimeoutCases );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLTimeoutedTag, &numStr, &KXMLTimeoutedTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tTimeout cases: %S"), &numStr );
+            }
+        
+        numStr.Num( iTotalSummary->iCrashedCases );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLCrashedTag, &numStr, &KXMLCrashedTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tCrashed cases: %S"), &numStr );
+            }
+        
+        TInt total = iTotalSummary->iPassedCases +
+            iTotalSummary->iFailedCases +
+            iTotalSummary->iTimeoutCases +
+            iTotalSummary->iCrashedCases;
+        numStr.Num( total );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLTotalTag, &numStr, &KXMLTotalTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tTotal cases: %S"), &numStr );
+            }
+
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLTestCasesSummaryTagEnd);
+            }
+
+        if(iOutput == CStifLogger::EFile)
+            {
+            User::LeaveIfError(iFile.Seek(ESeekStart, currentPos));
+            }
+        }
+    }
+            
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: GenerateReportL
+
+    Description: Generate the test report.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::GenerateReportL()
+    {
+    WriteTrailerL();
+    
+    // Add numeric information to summary
+    if ( iReportMode & ETestReportSummary )
+        {
+        // Go to the summary start position of the file
+        if( iOutput == CStifLogger::EFile )
+            {
+            User::LeaveIfError( iFile.Seek( ESeekStart, iSummaryPos ) );
+            }
+        TBuf<KSummaryLineEndLen> numStr;
+        // Generate Summary to Report
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLTestCasesSummaryTag);
+            }
+        else
+            {
+            WriteDelimiterL( _L( "-- " ), 25 );
+            WriteLineL(_L("SUMMARY:") );
+            }
+
+        numStr.Num( iTotalSummary->iPassedCases );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLPassedTag, &numStr, &KXMLPassedTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tPassed cases: %S"), &numStr );
+            }
+
+        numStr.Num( iTotalSummary->iFailedCases );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLFailedTag, &numStr, &KXMLFailedTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tFailed cases: %S"), &numStr );
+            }
+        
+        numStr.Num( iTotalSummary->iTimeoutCases );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLTimeoutedTag, &numStr, &KXMLTimeoutedTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tTimeout cases: %S"), &numStr );
+            }
+        
+        numStr.Num( iTotalSummary->iCrashedCases );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLCrashedTag, &numStr, &KXMLCrashedTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tCrashed cases: %S"), &numStr );
+            }
+        
+        TInt total = iTotalSummary->iPassedCases +
+            iTotalSummary->iFailedCases +
+            iTotalSummary->iTimeoutCases +
+            iTotalSummary->iCrashedCases;
+        numStr.Num( total );
+        if(iXML)
+            {
+            TPtrC spaces(KSummaryLineEnd().Ptr(), KSummaryLineEnd().Length() - numStr.Length());
+            WriteLineL(_L("%S%S%S%S"), &KXMLTotalTag, &numStr, &KXMLTotalTagEnd, &spaces);
+            }
+        else
+            {
+            numStr.Append( KSummaryLineEnd().Ptr(), 
+                           KSummaryLineEnd().Length() - numStr.Length() );
+            WriteLineL(_L("\tTotal cases: %S"), &numStr );
+            }
+
+        if(iXML)
+            {
+            WriteLineL(_L("%S"), &KXMLTestCasesSummaryTagEnd);
+            }
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: WriteLine
+
+    Description: Write line to file.
+
+    Parameters: TRefByValue<const TDesC> aStr: in: test to print
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::WriteLineL( TRefByValue<const TDesC> aStr,... )
+    {
+    
+    VA_LIST list;
+    VA_START( list, aStr );
+    TPrintInfo line;
+
+    // Parse parameters
+    line.AppendFormatList( aStr, list, NULL );
+    
+    if( iOutput == CStifLogger::ERDebug )
+        {
+        // RDebug output
+        RDebug::Print( line );
+        return;
+        }
+    
+    HBufC8* buf = HBufC8::NewLC( line.Length() + KMaxLenEol );
+    TPtr8 ptr( buf->Des() );
+    ptr.Copy( line );    
+            
+    if( ( iFormat == CStifLogger::EHtml ) && 
+        ( iOutput == CStifLogger::EFile ) )
+        {
+        // Html output, add linefeed
+        ptr.Append( _L8("<BR>\r\n") );
+        }
+    else 
+        {
+        // Default: Text format to file
+        // Add linefeed
+        ptr.Append( _L8("\r\n") );
+        }
+    
+    // Write to file    
+    iFile.Write( ptr );
+    CleanupStack::PopAndDestroy( buf );
+    
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: WriteDelimiter
+
+    Description: Write delimiter line to file.
+
+    Parameters: const TDesC& aDelimiter: in: delimiter mark
+                TInt aCount: in: number of delimiters written
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::WriteDelimiterL( const TDesC& aDelimiter, TInt aCount )
+    {
+    
+     if( iOutput == CStifLogger::ERDebug )
+        {
+        // RDebug output
+        // Nothing is printed
+        return;
+        }
+    
+    HBufC8* buf = HBufC8::NewLC( aDelimiter.Length() );
+    TPtr8 ptr( buf->Des() );
+    ptr.Copy( aDelimiter );    
+    
+    for( TInt i = 0; i<aCount; i++ )
+        {
+        // Write to file    
+        iFile.Write( ptr );
+        }
+    CleanupStack::PopAndDestroy( buf );
+    
+    TBuf8<KMaxLenEol> linefeed;        
+    if( ( iFormat == CStifLogger::EHtml ) && 
+        ( iOutput == CStifLogger::EFile ) )
+        {
+        // Html output, add linefeed
+        linefeed.Append( _L8("<BR>\r\n") );
+        }
+    else 
+        {
+        // Default: Text format to file
+        // Add linefeed
+        linefeed.Append( _L8("\r\n") );
+        }
+     // Write to file    
+    iFile.Write( linefeed );
+    
+    }        
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: TTestReportHeader::TTestReportHeader
+
+    Description: Constructor of TTestReportHeader
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestReport::TTestHWInfo::TTestHWInfo()
+    {
+    // Initialize, fills a specified block of data with binary zeroes
+    Mem::FillZ( this, sizeof( CTestReport::TTestHWInfo ) );
+
+    // Get HW Info
+    HAL::Get( HALData::EManufacturer, iHwInfo.iManufacturer );
+    HAL::Get( HALData::EMachineUid, iHwInfo.iMachineUid );
+    HAL::Get( HALData::EManufacturerHardwareRev, iHwInfo.iHwRev );
+    HAL::Get( HALData::EModel, iHwInfo.iModel );
+    HAL::Get( HALData::ECPU, iHwInfo.iCpu );
+    HAL::Get( HALData::ECPUSpeed, iHwInfo.iCpuSpeed );
+    HAL::Get( HALData::ELanguageIndex, iHwInfo.iLanguage );
+
+    // Get SW Info
+    HAL::Get( HALData::EManufacturerSoftwareRev, iSwInfo.iSwRev );
+    HAL::Get( HALData::EManufacturerSoftwareBuild, iSwInfo.iSwBuild );
+
+    // Memory Info
+    HAL::Get( HALData::EMemoryRAM, iMemoryInfo.iRAM );
+    HAL::Get( HALData::EMemoryRAMFree, iMemoryInfo.iRAMFree );
+
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: TTestSummary::TTestSummary
+
+    Description: Constructor of TTestSummary.
+
+    Parameters: const TName& aName: in: Name of summary
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestReport::TTestSummary::TTestSummary( const TName& aName ) :
+    iName( aName ),
+    iPassedCases( 0 ),
+    iFailedCases( 0 ),
+    iCrashedCases( 0 ),
+    iTimeoutCases( 0 )
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+	Class: CTestReport
+
+    Method: AddTestModuleVersion
+    
+    Description: Method adds version of a test module to the list of versions
+    			 that will be printed when stif is stopped.
+    			 
+    Parameters: TTestModuleVersionInfo aVersion : object contains information about version and
+    			name of test module.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+-------------------------------------------------------------------------------
+*/
+
+void CTestReport::AddTestModuleVersion(TTestModuleVersionInfo& aVersion)
+	{
+	for(TInt i = 0; i < iTestModulesVersionsInfo.Count(); i++)
+		{
+		if( aVersion.iTestModuleName == iTestModulesVersionsInfo[i]->iTestModuleName )
+			{
+			return;
+			}
+		}
+	
+	TTestModuleVersionInfo* testModuleVersionInfo = new (ELeave) TTestModuleVersionInfo;
+	testModuleVersionInfo->iMajor = aVersion.iMajor;
+	testModuleVersionInfo->iMinor = aVersion.iMinor;
+	testModuleVersionInfo->iBuild = aVersion.iBuild;
+	testModuleVersionInfo->iTestModuleName = aVersion.iTestModuleName;
+	
+	TInt res = iTestModulesVersionsInfo.Append(testModuleVersionInfo);
+	if( res != KErrNone )
+		{
+		delete testModuleVersionInfo;
+		}
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: TTestCaseSummary::TTestCaseSummary
+
+    Description: Constructor of TTestCaseSummary.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestReport::TTestCaseSummary::TTestCaseSummary()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestReport
+
+    Method: CloseXMLTagsInUnfinishedFileL
+
+    Description: Adds needed tags to get valid xml file.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Seek operations may cause leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestReport::CloseXMLTagsInUnfinishedFileL(void)
+    {
+    // For xml file keep current position in file.
+    if(iXML)
+        {
+        TInt currentPos = 0;
+        User::LeaveIfError(iFile.Seek(ESeekCurrent, currentPos));
+        
+        // Add closing tags to get valid xml file
+        WriteLineL(_L("%S"), &KXMLTestCasesTagEnd);
+        WriteLineL(_L("%S"), &KXMLTestReportTagEnd);
+        
+        // Move back to previous position
+        User::LeaveIfError(iFile.Seek(ESeekStart, currentPos));
+        }
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestEngine/src/Testcasetimeout.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,321 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestCaseTimeout class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include <hal.h>
+#include <StifLogger.h>
+#include "TestReport.h"
+#include "TestEngine.h"
+#include "TestEngineCommon.h"
+#include "TestCaseController.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseTimeout
+
+    Method: CTestCaseTimeout
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseTimeout::CTestCaseTimeout() : CActive (CActive::EPriorityStandard)
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseTimeout
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: 
+
+    Return Values: None
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseTimeout::ConstructL( CTestCaseController* aCase,
+                                   TTimeIntervalMicroSeconds aTimeout )
+    {
+    iCase = aCase;
+    iTimeout = aTimeout;  
+    iTimer.CreateLocal();
+
+	iTestCaseTimeout = 0;  // Initialize
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseTimeout
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: const TTestReportOutput aReportOutput: in: Report output type
+
+    Return Values: CTestCaseTimeout* : pointer to created object
+
+    Errors/Exceptions: Leaves if memory allocation for object fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseTimeout* CTestCaseTimeout::NewL( CTestCaseController* aCase, 
+                                          TTimeIntervalMicroSeconds aTimeout )
+    {
+    CTestCaseTimeout* self = new ( ELeave ) CTestCaseTimeout();
+    CleanupStack::PushL( self );
+    self->ConstructL( aCase, aTimeout );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseTimeout
+
+    Method: ~CTestCaseTimeout
+
+    Description: Destructor.
+
+    Cancel request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCaseTimeout::~CTestCaseTimeout()
+    {
+    Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseTimeout
+
+    Method: Start
+
+    Description: Start timeout counting
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseTimeout::Start()
+    {
+    // Add to active scheduler
+    CActiveScheduler::Add ( this );
+    SetActive();
+
+    // Request timer
+    TTime timeout;
+    timeout.HomeTime();
+    timeout = timeout + iTimeout;
+    
+    // Store absolute timeout
+    iTestCaseTimeout = timeout;
+
+    // Note: iTimer.After() method cannot use because there needed
+    // TTimeIntervalMicroSeconds32 and it is 32 bit. So then cannot create 
+    // timeout time that is long enough. At() uses 64 bit value=>Long enough.
+    iTimer.At( iStatus, timeout );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseTimeout
+
+    Method: RunL
+
+    Description: RunL handles completed timeouts.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseTimeout::RunL()
+    {
+    // Timeout
+	TTime timeout;
+	timeout.HomeTime();
+	// Handle the abort case when system time gets changed, but timeout is
+    // still valid. All other cases should timeout since they invalidate the
+    // logic of the timers.
+	if ( iStatus == KErrAbort)
+		{
+		if ( iTestCaseTimeout > timeout )
+			{  
+			RDebug::Print( _L( "Absolute timer still valid. Restaring timer. iStatus: %d" ), iStatus.Int() );
+			// Start new timer
+			iStatus = KErrNone; // reset value
+			iTimer.At ( iStatus, iTestCaseTimeout );  // restart timer
+			SetActive();
+			}
+		else
+			{
+			// Absolute timer no longer valid. Must timeout.
+			iCase->Timeout();
+			}
+
+		}
+	else
+		{
+		// Status was not KErrAbort. Timing out!
+		iCase->Timeout();
+		}
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseTimeout
+
+    Method: DoCancel
+
+    Description: Cancel active request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCaseTimeout::DoCancel()
+    {
+    iTimer.Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCaseTimeout
+
+    Method: RunError
+
+    Description: Handle errors. Just let framework handle errors because
+    RunL does not leave.
+
+    Parameters: TInt aError: in: Symbian OS error: Error code
+
+    Return Values: TInt: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCaseTimeout::RunError( TInt aError )
+    {
+    return aError;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/BMARM/StifTestInterfaceu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,122 @@
+EXPORTS
+	__9TTestInfo @ 1 NONAME R3UNUSED ; TTestInfo::TTestInfo(void)
+	Append__14CStifTFwIfProtPFi_7TPtrC16i @ 2 NONAME R3UNUSED ; CStifTFwIfProt::Append(TPtrC16 (*)(int), int)
+	Append__14CStifTFwIfProtPFi_7TPtrC16iRC7TDesC16 @ 3 NONAME ; CStifTFwIfProt::Append(TPtrC16 (*)(int), int, TDesC16 const &)
+	Append__14CStifTFwIfProtPFi_7TPtrC16iT1i @ 4 NONAME ; (null)
+	Append__14CStifTFwIfProtPFi_7TPtrC16ii @ 5 NONAME ; CStifTFwIfProt::Append(TPtrC16 (*)(int), int, int)
+	Append__14CStifTFwIfProtRC7TDesC16 @ 6 NONAME R3UNUSED ; CStifTFwIfProt::Append(TDesC16 const &)
+	CallTestClass__11CScriptBaseRC7TDesC16 @ 7 NONAME R3UNUSED ; CScriptBase::CallTestClass(TDesC16 const &)
+	CancelEvent__13CTestModuleIfR8TEventIfP14TRequestStatus @ 8 NONAME R3UNUSED ; CTestModuleIf::CancelEvent(TEventIf &, TRequestStatus *)
+	CancelSignal__11CScriptBase @ 9 NONAME R3UNUSED ; CScriptBase::CancelSignal(void)
+	CheckAllowResult__13CTestModuleIfi @ 10 NONAME R3UNUSED ; CTestModuleIf::CheckAllowResult(int)
+	CmdType__14CStifTFwIfProti @ 11 NONAME R3UNUSED ; CStifTFwIfProt::CmdType(int)
+	CreateL__14CStifTFwIfProti @ 12 NONAME R3UNUSED ; CStifTFwIfProt::CreateL(int)
+	CreationResult__11CStifLogger @ 13 NONAME R3UNUSED ; CStifLogger::CreationResult(void)
+	DstDevId__14CStifTFwIfProt @ 14 NONAME R3UNUSED ; CStifTFwIfProt::DstDevId(void)
+	DstId__14CStifTFwIfProt @ 15 NONAME R3UNUSED ; CStifTFwIfProt::DstId(void)
+	DstTestId__14CStifTFwIfProt @ 16 NONAME R3UNUSED ; CStifTFwIfProt::DstTestId(void)
+	EnableSignal__11CScriptBaseR14TRequestStatus @ 17 NONAME R3UNUSED ; CScriptBase::EnableSignal(TRequestStatus &)
+	EventStatusParams__14CStifTFwIfProti @ 18 NONAME R3UNUSED ; CStifTFwIfProt::EventStatusParams(int)
+	EventStatus__14CStifTFwIfProti @ 19 NONAME R3UNUSED ; CStifTFwIfProt::EventStatus(int)
+	EventType__14CStifTFwIfProti @ 20 NONAME R3UNUSED ; CStifTFwIfProt::EventType(int)
+	Event__13CTestModuleIfR8TEventIf @ 21 NONAME R3UNUSED ; CTestModuleIf::Event(TEventIf &)
+	Event__13CTestModuleIfR8TEventIfR14TRequestStatus @ 22 NONAME R3UNUSED ; CTestModuleIf::Event(TEventIf &, TRequestStatus &)
+	GetChar__15CStifItemParserRC7TDesC16R5TChar @ 23 NONAME R3UNUSED ; CStifItemParser::GetChar(TDesC16 const &, TChar &)
+	GetInt__15CStifItemParserRC7TDesC16RUi6TRadix @ 24 NONAME ; CStifItemParser::GetInt(TDesC16 const &, unsigned int &, TRadix)
+	GetInt__15CStifItemParserRC7TDesC16Ri @ 25 NONAME R3UNUSED ; CStifItemParser::GetInt(TDesC16 const &, int &)
+	GetItemLineL__18CStifSectionParserRC7TDesC1617TTagToReturnValue @ 26 NONAME R3UNUSED ; CStifSectionParser::GetItemLineL(TDesC16 const &, TTagToReturnValue)
+	GetLine__18CStifSectionParserRC7TDesC16R7TPtrC1617TTagToReturnValue @ 27 NONAME ; CStifSectionParser::GetLine(TDesC16 const &, TPtrC16 &, TTagToReturnValue)
+	GetMeasurementOptions__13CTestModuleIfRi @ 28 NONAME R3UNUSED ; CTestModuleIf::GetMeasurementOptions(int &)
+	GetNextChar__15CStifItemParserR5TChar @ 29 NONAME R3UNUSED ; CStifItemParser::GetNextChar(TChar &)
+	GetNextChar__15CStifItemParserRC7TDesC16R5TChar @ 30 NONAME R3UNUSED ; CStifItemParser::GetNextChar(TDesC16 const &, TChar &)
+	GetNextInt__15CStifItemParserRC7TDesC16RUi6TRadix @ 31 NONAME ; CStifItemParser::GetNextInt(TDesC16 const &, unsigned int &, TRadix)
+	GetNextInt__15CStifItemParserRC7TDesC16Ri @ 32 NONAME R3UNUSED ; CStifItemParser::GetNextInt(TDesC16 const &, int &)
+	GetNextInt__15CStifItemParserRUi6TRadix @ 33 NONAME R3UNUSED ; CStifItemParser::GetNextInt(unsigned int &, TRadix)
+	GetNextInt__15CStifItemParserRi @ 34 NONAME R3UNUSED ; CStifItemParser::GetNextInt(int &)
+	GetNextItemLineL__18CStifSectionParser @ 35 NONAME R3UNUSED ; CStifSectionParser::GetNextItemLineL(void)
+	GetNextItemLineL__18CStifSectionParserRC7TDesC1617TTagToReturnValue @ 36 NONAME R3UNUSED ; CStifSectionParser::GetNextItemLineL(TDesC16 const &, TTagToReturnValue)
+	GetNextLine__18CStifSectionParserR7TPtrC16 @ 37 NONAME R3UNUSED ; CStifSectionParser::GetNextLine(TPtrC16 &)
+	GetNextLine__18CStifSectionParserRC7TDesC16R7TPtrC1617TTagToReturnValue @ 38 NONAME ; CStifSectionParser::GetNextLine(TDesC16 const &, TPtrC16 &, TTagToReturnValue)
+	GetNextString__15CStifItemParserR7TPtrC16 @ 39 NONAME R3UNUSED ; CStifItemParser::GetNextString(TPtrC16 &)
+	GetNextString__15CStifItemParserRC7TDesC16R7TPtrC16 @ 40 NONAME R3UNUSED ; CStifItemParser::GetNextString(TDesC16 const &, TPtrC16 &)
+	GetPosition__18CStifSectionParser @ 41 NONAME R3UNUSED ; CStifSectionParser::GetPosition(void)
+	GetStoredState__13CTestModuleIfRiRt4TBuf1i128 @ 42 NONAME R3UNUSED ; CTestModuleIf::GetStoredState(int &, TBuf<128> &)
+	GetString__15CStifItemParserRC7TDesC16R7TPtrC16 @ 43 NONAME R3UNUSED ; CStifItemParser::GetString(TDesC16 const &, TPtrC16 &)
+	GetTestObject__11CScriptBaseRC7TDesC16 @ 44 NONAME R3UNUSED ; CScriptBase::GetTestObject(TDesC16 const &)
+	Log__11CStifLoggerGt11TRefByValue1ZC6TDesC8e @ 45 NONAME ; CStifLogger::Log(TRefByValue<TDesC8 const>,...)
+	Log__11CStifLoggerGt11TRefByValue1ZC7TDesC16e @ 46 NONAME ; CStifLogger::Log(TRefByValue<TDesC16 const>,...)
+	Log__11CStifLoggerRC6TDesC8 @ 47 NONAME R3UNUSED ; CStifLogger::Log(TDesC8 const &)
+	Log__11CStifLoggerRC7TDesC16 @ 48 NONAME R3UNUSED ; CStifLogger::Log(TDesC16 const &)
+	Log__11CStifLoggeriGt11TRefByValue1ZC6TDesC8e @ 49 NONAME ; CStifLogger::Log(int, TRefByValue<TDesC8 const>,...)
+	Log__11CStifLoggeriGt11TRefByValue1ZC7TDesC16e @ 50 NONAME ; CStifLogger::Log(int, TRefByValue<TDesC16 const>,...)
+	Log__11CStifLoggeriRC6TDesC8 @ 51 NONAME R3UNUSED ; CStifLogger::Log(int, TDesC8 const &)
+	Log__11CStifLoggeriRC7TDesC16 @ 52 NONAME R3UNUSED ; CStifLogger::Log(int, TDesC16 const &)
+	MsgType__14CStifTFwIfProti @ 53 NONAME R3UNUSED ; CStifTFwIfProt::MsgType(int)
+	NewL__11CStifLoggerRC7TDesC16T1Q211CStifLogger11TLoggerTypeQ211CStifLogger7TOutputiiiiiiii @ 54 NONAME ; CStifLogger::NewL(TDesC16 const &, TDesC16 const &, CStifLogger::TLoggerType, CStifLogger::TOutput, int, int, int, int, int, int, int, int)
+	NewL__11CStifLoggerRC7TDesC16T1R15TLoggerSettings @ 55 NONAME R3UNUSED ; CStifLogger::NewL(TDesC16 const &, TDesC16 const &, TLoggerSettings &)
+	NewL__11CStifParserRC7TDesC16Q211CStifParser12TCommentType @ 56 NONAME R3UNUSED ; CStifParser::NewL(TDesC16 const &, CStifParser::TCommentType)
+	NewL__11CStifParserRC7TDesC16T1Q211CStifParser12TCommentType @ 57 NONAME R3UNUSED ; CStifParser::NewL(TDesC16 const &, TDesC16 const &, CStifParser::TCommentType)
+	NewL__13CTestModuleIfP20CTestThreadContainerP15CTestModuleBase @ 58 NONAME R3UNUSED ; CTestModuleIf::NewL(CTestThreadContainer *, CTestModuleBase *)
+	NewL__14CStifTFwIfProt @ 59 NONAME R3UNUSED ; CStifTFwIfProt::NewL(void)
+	NewL__15CStifItemParserG7TPtrC16ii @ 60 NONAME ; CStifItemParser::NewL(TPtrC16, int, int)
+	NewL__20CSTIFTestMeasurementP15CTestModuleBaseQ220CSTIFTestMeasurement20TSTIFMeasurementTypeRC7TDesC16 @ 61 NONAME R3UNUSED ; CSTIFTestMeasurement::NewL(CTestModuleBase *, CSTIFTestMeasurement::TSTIFMeasurementType, TDesC16 const &)
+	NewL__21CTestModuleParamVer01 @ 62 NONAME R3UNUSED ; CTestModuleParamVer01::NewL(void)
+	NewL__21MSTIFTestInterferenceP15CTestModuleBaseQ221MSTIFTestInterference29TStifTestInterferenceCategory @ 63 NONAME R3UNUSED ; MSTIFTestInterference::NewL(CTestModuleBase *, MSTIFTestInterference::TStifTestInterferenceCategory)
+	NextSectionL__11CStifParserRC7TDesC16T1i @ 64 NONAME ; CStifParser::NextSectionL(TDesC16 const &, TDesC16 const &, int)
+	NextSubSectionL__18CStifSectionParserRC7TDesC16T1i @ 65 NONAME ; CStifSectionParser::NextSubSectionL(TDesC16 const &, TDesC16 const &, int)
+	OutputType__11CStifLogger @ 66 NONAME R3UNUSED ; CStifLogger::OutputType(void)
+	ParsingType__15CStifItemParser @ 67 NONAME R3UNUSED ; CStifItemParser::ParsingType(void)
+	Printf__13CTestModuleIfiRC7TDesC16Gt11TRefByValue1ZC7TDesC16e @ 68 NONAME ; CTestModuleIf::Printf(int, TDesC16 const &, TRefByValue<TDesC16 const>,...)
+	Reboot__13CTestModuleIfi @ 69 NONAME R3UNUSED ; CTestModuleIf::Reboot(int)
+	Remainder__15CStifItemParserR7TPtrC16 @ 70 NONAME R3UNUSED ; CStifItemParser::Remainder(TPtrC16 &)
+	RemoteReceiveCancel__13CTestModuleIf @ 71 NONAME R3UNUSED ; CTestModuleIf::RemoteReceiveCancel(void)
+	RemoteReceive__13CTestModuleIfR6TDes16R14TRequestStatus @ 72 NONAME R3UNUSED ; CTestModuleIf::RemoteReceive(TDes16 &, TRequestStatus &)
+	RemoteSend__13CTestModuleIfRC7TDesC16 @ 73 NONAME R3UNUSED ; CTestModuleIf::RemoteSend(TDesC16 const &)
+	RemoteType__14CStifTFwIfProti @ 74 NONAME R3UNUSED ; CStifTFwIfProt::RemoteType(int)
+	ResetAllowResult__13CTestModuleIf @ 75 NONAME R3UNUSED ; CTestModuleIf::ResetAllowResult(void)
+	RespParam__14CStifTFwIfProti @ 76 NONAME R3UNUSED ; CStifTFwIfProt::RespParam(int)
+	ResultCategory__14CStifTFwIfProti @ 77 NONAME R3UNUSED ; CStifTFwIfProt::ResultCategory(int)
+	RunInternalL__11CScriptBasePC17TStifFunctionInfoiR15CStifItemParser @ 78 NONAME ; CScriptBase::RunInternalL(TStifFunctionInfo const *, int, CStifItemParser &)
+	RunParams__14CStifTFwIfProti @ 79 NONAME R3UNUSED ; CStifTFwIfProt::RunParams(int)
+	RunStatusParams__14CStifTFwIfProti @ 80 NONAME R3UNUSED ; CStifTFwIfProt::RunStatusParams(int)
+	RunStatus__14CStifTFwIfProti @ 81 NONAME R3UNUSED ; CStifTFwIfProt::RunStatus(int)
+	SaveData__11CStifLoggerR6TDesC8 @ 82 NONAME R3UNUSED ; CStifLogger::SaveData(TDesC8 &)
+	SaveData__11CStifLoggerR7TDesC16 @ 83 NONAME R3UNUSED ; CStifLogger::SaveData(TDesC16 &)
+	SectionL__11CStifParserRC7TDesC16T1i @ 84 NONAME ; CStifParser::SectionL(TDesC16 const &, TDesC16 const &, int)
+	SetAllowResult__13CTestModuleIfi @ 85 NONAME R3UNUSED ; CTestModuleIf::SetAllowResult(int)
+	SetBehavior__13CTestModuleIfQ213CTestModuleIf13TTestBehaviorPv @ 86 NONAME R3UNUSED ; CTestModuleIf::SetBehavior(CTestModuleIf::TTestBehavior, void *)
+	SetCmdType__14CStifTFwIfProtQ214CStifTFwIfProt8TCmdType @ 87 NONAME R3UNUSED ; CStifTFwIfProt::SetCmdType(CStifTFwIfProt::TCmdType)
+	SetDstId__14CStifTFwIfProtUl @ 88 NONAME R3UNUSED ; CStifTFwIfProt::SetDstId(unsigned long)
+	SetExitReason__13CTestModuleIfQ213CTestModuleIf11TExitReasoni @ 89 NONAME R3UNUSED ; CTestModuleIf::SetExitReason(CTestModuleIf::TExitReason, int)
+	SetL__14CStifTFwIfProtRC7TDesC16 @ 90 NONAME R3UNUSED ; CStifTFwIfProt::SetL(TDesC16 const &)
+	SetMsgType__14CStifTFwIfProtQ214CStifTFwIfProt8TMsgType @ 91 NONAME R3UNUSED ; CStifTFwIfProt::SetMsgType(CStifTFwIfProt::TMsgType)
+	SetParsingType__15CStifItemParserQ215CStifItemParser12TParsingType @ 92 NONAME R3UNUSED ; CStifItemParser::SetParsingType(CStifItemParser::TParsingType)
+	SetPosition__18CStifSectionParseri @ 93 NONAME R3UNUSED ; CStifSectionParser::SetPosition(int)
+	SetRespType__14CStifTFwIfProtQ214CStifTFwIfProt8TMsgType @ 94 NONAME R3UNUSED ; CStifTFwIfProt::SetRespType(CStifTFwIfProt::TMsgType)
+	SetResult__11TTestResultiRC7TDesC16 @ 95 NONAME R3UNUSED ; TTestResult::SetResult(int, TDesC16 const &)
+	SetScripter__11CScriptBasePFP13CTestScripter19TStifTSCallBackTypeRC7TDesC16_iP13CTestScripter @ 96 NONAME R3UNUSED ; CScriptBase::SetScripter(int (*)(CTestScripter *, TStifTSCallBackType, TDesC16 const &), CTestScripter *)
+	SetSrcId__14CStifTFwIfProtUl @ 97 NONAME R3UNUSED ; CStifTFwIfProt::SetSrcId(unsigned long)
+	Signal__11CScriptBasei @ 98 NONAME R3UNUSED ; CScriptBase::Signal(int)
+	SrcDevId__14CStifTFwIfProt @ 99 NONAME R3UNUSED ; CStifTFwIfProt::SrcDevId(void)
+	SrcId__14CStifTFwIfProt @ 100 NONAME R3UNUSED ; CStifTFwIfProt::SrcId(void)
+	SrcTestId__14CStifTFwIfProt @ 101 NONAME R3UNUSED ; CStifTFwIfProt::SrcTestId(void)
+	StartSession__Fv @ 102 NONAME R3UNUSED ; StartSession(void)
+	Start__20CSTIFTestMeasurement @ 103 NONAME R3UNUSED ; CSTIFTestMeasurement::Start(void)
+	StifMacroError__13CTestModuleIfiPCUcPCciiiiiii @ 104 NONAME ; CTestModuleIf::StifMacroError(int, unsigned char const *, char const *, int, int, int, int, int, int, int)
+	Stop__20CSTIFTestMeasurement @ 105 NONAME R3UNUSED ; CSTIFTestMeasurement::Stop(void)
+	StoreState__13CTestModuleIfiRt4TBuf1i128 @ 106 NONAME R3UNUSED ; CTestModuleIf::StoreState(int, TBuf<128> &)
+	SubSectionL__18CStifSectionParserRC7TDesC16T1i @ 107 NONAME ; CStifSectionParser::SubSectionL(TDesC16 const &, TDesC16 const &, int)
+	TestModuleIf__11CScriptBase @ 108 NONAME R3UNUSED ; CScriptBase::TestModuleIf(void)
+	WriteDelimiter__11CStifLoggerRC6TDesC8i @ 109 NONAME R3UNUSED ; CStifLogger::WriteDelimiter(TDesC8 const &, int)
+	WriteDelimiter__11CStifLoggerRC7TDesC16i @ 110 NONAME R3UNUSED ; CStifLogger::WriteDelimiter(TDesC16 const &, int)
+	"_._11CStifParser" @ 111 NONAME R3UNUSED ; CStifParser::~CStifParser(void)
+	"_._14CStifTFwIfProt" @ 112 NONAME R3UNUSED ; CStifTFwIfProt::~CStifTFwIfProt(void)
+	"_._21CTestModuleParamVer01" @ 113 NONAME R3UNUSED ; CTestModuleParamVer01::~CTestModuleParamVer01(void)
+	__11CScriptBaseR13CTestModuleIf @ 114 NONAME R3UNUSED ; CScriptBase::CScriptBase(CTestModuleIf &)
+	__11TTestResult @ 115 NONAME R3UNUSED ; TTestResult::TTestResult(void)
+	__13TTestCaseInfo @ 116 NONAME R3UNUSED ; TTestCaseInfo::TTestCaseInfo(void)
+	__13TTestProgress @ 117 NONAME R3UNUSED ; TTestProgress::TTestProgress(void)
+	__15TFullTestResult @ 118 NONAME R3UNUSED ; TFullTestResult::TFullTestResult(void)
+	__18TErrorNotification @ 119 NONAME R3UNUSED ; TErrorNotification::TErrorNotification(void)
+	AppendId__14CStifTFwIfProtUl @ 120 NONAME R3UNUSED ; CStifTFwIfProt::AppendId(unsigned long)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/BWINS/StifTestInterfaceu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,141 @@
+EXPORTS
+	??0CScriptBase@@IAE@AAVCTestModuleIf@@@Z @ 1 NONAME ; CScriptBase::CScriptBase(class CTestModuleIf &)
+	??0TErrorNotification@@QAE@XZ @ 2 NONAME ; TErrorNotification::TErrorNotification(void)
+	??0TFullTestResult@@QAE@XZ @ 3 NONAME ; TFullTestResult::TFullTestResult(void)
+	??0TTestCaseInfo@@QAE@XZ @ 4 NONAME ; TTestCaseInfo::TTestCaseInfo(void)
+	??0TTestInfo@@QAE@XZ @ 5 NONAME ; TTestInfo::TTestInfo(void)
+	??0TTestProgress@@QAE@XZ @ 6 NONAME ; TTestProgress::TTestProgress(void)
+	??0TTestResult@@QAE@XZ @ 7 NONAME ; TTestResult::TTestResult(void)
+	??1CStifParser@@UAE@XZ @ 8 NONAME ; CStifParser::~CStifParser(void)
+	??1CStifTFwIfProt@@UAE@XZ @ 9 NONAME ; CStifTFwIfProt::~CStifTFwIfProt(void)
+	??1CTestModuleParamVer01@@UAE@XZ @ 10 NONAME ; CTestModuleParamVer01::~CTestModuleParamVer01(void)
+	?Append@CStifTFwIfProt@@QAEHABVTDesC16@@@Z @ 11 NONAME ; int CStifTFwIfProt::Append(class TDesC16 const &)
+	?Append@CStifTFwIfProt@@QAEHP6A?AVTPtrC16@@H@ZH0H@Z @ 12 NONAME ; int CStifTFwIfProt::Append(class TPtrC16 (*)(int), int, class TPtrC16 (*)(int), int)
+	?Append@CStifTFwIfProt@@QAEHP6A?AVTPtrC16@@H@ZH@Z @ 13 NONAME ; int CStifTFwIfProt::Append(class TPtrC16 (*)(int), int)
+	?Append@CStifTFwIfProt@@QAEHP6A?AVTPtrC16@@H@ZHABVTDesC16@@@Z @ 14 NONAME ; int CStifTFwIfProt::Append(class TPtrC16 (*)(int), int, class TDesC16 const &)
+	?Append@CStifTFwIfProt@@QAEHP6A?AVTPtrC16@@H@ZHH@Z @ 15 NONAME ; int CStifTFwIfProt::Append(class TPtrC16 (*)(int), int, int)
+	?AppendId@CStifTFwIfProt@@QAEHK@Z @ 16 NONAME ; int CStifTFwIfProt::AppendId(unsigned long)
+	?CallTestClass@CScriptBase@@QAEHABVTDesC16@@@Z @ 17 NONAME ; int CScriptBase::CallTestClass(class TDesC16 const &)
+	?CancelEvent@CTestModuleIf@@QAEHAAVTEventIf@@PAVTRequestStatus@@@Z @ 18 NONAME ; int CTestModuleIf::CancelEvent(class TEventIf &, class TRequestStatus *)
+	?CancelSignal@CScriptBase@@AAEXXZ @ 19 NONAME ; void CScriptBase::CancelSignal(void)
+	?CheckAllowResult@CTestModuleIf@@QAEHH@Z @ 20 NONAME ; int CTestModuleIf::CheckAllowResult(int)
+	?CmdType@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 21 NONAME ; class TPtrC16 CStifTFwIfProt::CmdType(int)
+	?CreateL@CStifTFwIfProt@@QAEXH@Z @ 22 NONAME ; void CStifTFwIfProt::CreateL(int)
+	?CreationResult@CStifLogger@@QAEHXZ @ 23 NONAME ; int CStifLogger::CreationResult(void)
+	?DstDevId@CStifTFwIfProt@@QAEGXZ @ 24 NONAME ; unsigned short CStifTFwIfProt::DstDevId(void)
+	?DstId@CStifTFwIfProt@@QAEKXZ @ 25 NONAME ; unsigned long CStifTFwIfProt::DstId(void)
+	?DstTestId@CStifTFwIfProt@@QAEGXZ @ 26 NONAME ; unsigned short CStifTFwIfProt::DstTestId(void)
+	?EnableSignal@CScriptBase@@AAEXAAVTRequestStatus@@@Z @ 27 NONAME ; void CScriptBase::EnableSignal(class TRequestStatus &)
+	?Event@CTestModuleIf@@QAEHAAVTEventIf@@@Z @ 28 NONAME ; int CTestModuleIf::Event(class TEventIf &)
+	?Event@CTestModuleIf@@QAEXAAVTEventIf@@AAVTRequestStatus@@@Z @ 29 NONAME ; void CTestModuleIf::Event(class TEventIf &, class TRequestStatus &)
+	?EventStatus@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 30 NONAME ; class TPtrC16 CStifTFwIfProt::EventStatus(int)
+	?EventStatusParams@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 31 NONAME ; class TPtrC16 CStifTFwIfProt::EventStatusParams(int)
+	?EventType@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 32 NONAME ; class TPtrC16 CStifTFwIfProt::EventType(int)
+	?GetChar@CStifItemParser@@QAEHABVTDesC16@@AAVTChar@@@Z @ 33 NONAME ; int CStifItemParser::GetChar(class TDesC16 const &, class TChar &)
+	?GetInt@CStifItemParser@@QAEHABVTDesC16@@AAH@Z @ 34 NONAME ; int CStifItemParser::GetInt(class TDesC16 const &, int &)
+	?GetInt@CStifItemParser@@QAEHABVTDesC16@@AAIW4TRadix@@@Z @ 35 NONAME ; int CStifItemParser::GetInt(class TDesC16 const &, unsigned int &, enum TRadix)
+	?GetItemLineL@CStifSectionParser@@QAEPAVCStifItemParser@@ABVTDesC16@@W4TTagToReturnValue@@@Z @ 36 NONAME ; class CStifItemParser * CStifSectionParser::GetItemLineL(class TDesC16 const &, enum TTagToReturnValue)
+	?GetLine@CStifSectionParser@@QAEHABVTDesC16@@AAVTPtrC16@@W4TTagToReturnValue@@@Z @ 37 NONAME ; int CStifSectionParser::GetLine(class TDesC16 const &, class TPtrC16 &, enum TTagToReturnValue)
+	?GetMeasurementOptions@CTestModuleIf@@QAEHAAH@Z @ 38 NONAME ; int CTestModuleIf::GetMeasurementOptions(int &)
+	?GetNextChar@CStifItemParser@@QAEHAAVTChar@@@Z @ 39 NONAME ; int CStifItemParser::GetNextChar(class TChar &)
+	?GetNextChar@CStifItemParser@@QAEHABVTDesC16@@AAVTChar@@@Z @ 40 NONAME ; int CStifItemParser::GetNextChar(class TDesC16 const &, class TChar &)
+	?GetNextInt@CStifItemParser@@QAEHAAH@Z @ 41 NONAME ; int CStifItemParser::GetNextInt(int &)
+	?GetNextInt@CStifItemParser@@QAEHAAIW4TRadix@@@Z @ 42 NONAME ; int CStifItemParser::GetNextInt(unsigned int &, enum TRadix)
+	?GetNextInt@CStifItemParser@@QAEHABVTDesC16@@AAH@Z @ 43 NONAME ; int CStifItemParser::GetNextInt(class TDesC16 const &, int &)
+	?GetNextInt@CStifItemParser@@QAEHABVTDesC16@@AAIW4TRadix@@@Z @ 44 NONAME ; int CStifItemParser::GetNextInt(class TDesC16 const &, unsigned int &, enum TRadix)
+	?GetNextItemLineL@CStifSectionParser@@QAEPAVCStifItemParser@@ABVTDesC16@@W4TTagToReturnValue@@@Z @ 45 NONAME ; class CStifItemParser * CStifSectionParser::GetNextItemLineL(class TDesC16 const &, enum TTagToReturnValue)
+	?GetNextItemLineL@CStifSectionParser@@QAEPAVCStifItemParser@@XZ @ 46 NONAME ; class CStifItemParser * CStifSectionParser::GetNextItemLineL(void)
+	?GetNextLine@CStifSectionParser@@QAEHAAVTPtrC16@@@Z @ 47 NONAME ; int CStifSectionParser::GetNextLine(class TPtrC16 &)
+	?GetNextLine@CStifSectionParser@@QAEHABVTDesC16@@AAVTPtrC16@@W4TTagToReturnValue@@@Z @ 48 NONAME ; int CStifSectionParser::GetNextLine(class TDesC16 const &, class TPtrC16 &, enum TTagToReturnValue)
+	?GetNextString@CStifItemParser@@QAEHAAVTPtrC16@@@Z @ 49 NONAME ; int CStifItemParser::GetNextString(class TPtrC16 &)
+	?GetNextString@CStifItemParser@@QAEHABVTDesC16@@AAVTPtrC16@@@Z @ 50 NONAME ; int CStifItemParser::GetNextString(class TDesC16 const &, class TPtrC16 &)
+	?GetPosition@CStifSectionParser@@QAEHXZ @ 51 NONAME ; int CStifSectionParser::GetPosition(void)
+	?GetStoredState@CTestModuleIf@@QAEHAAHAAV?$TBuf@$0IA@@@@Z @ 52 NONAME ; int CTestModuleIf::GetStoredState(int &, class TBuf<128> &)
+	?GetString@CStifItemParser@@QAEHABVTDesC16@@AAVTPtrC16@@@Z @ 53 NONAME ; int CStifItemParser::GetString(class TDesC16 const &, class TPtrC16 &)
+	?GetTestObject@CScriptBase@@QAEPAV1@ABVTDesC16@@@Z @ 54 NONAME ; class CScriptBase * CScriptBase::GetTestObject(class TDesC16 const &)
+	?Log@CStifLogger@@QAAHHV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 55 NONAME ; int CStifLogger::Log(int, class TRefByValue<class TDesC16 const >, ...)
+	?Log@CStifLogger@@QAAHHV?$TRefByValue@$$CBVTDesC8@@@@ZZ @ 56 NONAME ; int CStifLogger::Log(int, class TRefByValue<class TDesC8 const >, ...)
+	?Log@CStifLogger@@QAAHV?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 57 NONAME ; int CStifLogger::Log(class TRefByValue<class TDesC16 const >, ...)
+	?Log@CStifLogger@@QAAHV?$TRefByValue@$$CBVTDesC8@@@@ZZ @ 58 NONAME ; int CStifLogger::Log(class TRefByValue<class TDesC8 const >, ...)
+	?Log@CStifLogger@@QAEHABVTDesC16@@@Z @ 59 NONAME ; int CStifLogger::Log(class TDesC16 const &)
+	?Log@CStifLogger@@QAEHABVTDesC8@@@Z @ 60 NONAME ; int CStifLogger::Log(class TDesC8 const &)
+	?Log@CStifLogger@@QAEHHABVTDesC16@@@Z @ 61 NONAME ; int CStifLogger::Log(int, class TDesC16 const &)
+	?Log@CStifLogger@@QAEHHABVTDesC8@@@Z @ 62 NONAME ; int CStifLogger::Log(int, class TDesC8 const &)
+	?MsgType@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 63 NONAME ; class TPtrC16 CStifTFwIfProt::MsgType(int)
+	?NewL@CSTIFTestMeasurement@@SAPAV1@PAVCTestModuleBase@@W4TSTIFMeasurementType@1@ABVTDesC16@@@Z @ 64 NONAME ; class CSTIFTestMeasurement * CSTIFTestMeasurement::NewL(class CTestModuleBase *, enum CSTIFTestMeasurement::TSTIFMeasurementType, class TDesC16 const &)
+	?NewL@CStifItemParser@@SAPAV1@VTPtrC16@@HH@Z @ 65 NONAME ; class CStifItemParser * CStifItemParser::NewL(class TPtrC16, int, int)
+	?NewL@CStifLogger@@KAPAV1@ABVTDesC16@@0AAUTLoggerSettings@@@Z @ 66 NONAME ; class CStifLogger * CStifLogger::NewL(class TDesC16 const &, class TDesC16 const &, struct TLoggerSettings &)
+	?NewL@CStifLogger@@SAPAV1@ABVTDesC16@@0W4TLoggerType@1@W4TOutput@1@HHHHHHHH@Z @ 67 NONAME ; class CStifLogger * CStifLogger::NewL(class TDesC16 const &, class TDesC16 const &, enum CStifLogger::TLoggerType, enum CStifLogger::TOutput, int, int, int, int, int, int, int, int)
+	?NewL@CStifParser@@SAPAV1@ABVTDesC16@@0W4TCommentType@1@@Z @ 68 NONAME ; class CStifParser * CStifParser::NewL(class TDesC16 const &, class TDesC16 const &, enum CStifParser::TCommentType)
+	?NewL@CStifParser@@SAPAV1@ABVTDesC16@@W4TCommentType@1@@Z @ 69 NONAME ; class CStifParser * CStifParser::NewL(class TDesC16 const &, enum CStifParser::TCommentType)
+	?NewL@CStifTFwIfProt@@SAPAV1@XZ @ 70 NONAME ; class CStifTFwIfProt * CStifTFwIfProt::NewL(void)
+	?NewL@CTestModuleIf@@SAPAV1@PAVCTestThreadContainer@@PAVCTestModuleBase@@@Z @ 71 NONAME ; class CTestModuleIf * CTestModuleIf::NewL(class CTestThreadContainer *, class CTestModuleBase *)
+	?NewL@CTestModuleParamVer01@@SAPAV1@XZ @ 72 NONAME ; class CTestModuleParamVer01 * CTestModuleParamVer01::NewL(void)
+	?NewL@MSTIFTestInterference@@SAPAV1@PAVCTestModuleBase@@W4TStifTestInterferenceCategory@1@@Z @ 73 NONAME ; class MSTIFTestInterference * MSTIFTestInterference::NewL(class CTestModuleBase *, enum MSTIFTestInterference::TStifTestInterferenceCategory)
+	?NextSectionL@CStifParser@@QAEPAVCStifSectionParser@@ABVTDesC16@@0H@Z @ 74 NONAME ; class CStifSectionParser * CStifParser::NextSectionL(class TDesC16 const &, class TDesC16 const &, int)
+	?NextSubSectionL@CStifSectionParser@@QAEPAV1@ABVTDesC16@@0H@Z @ 75 NONAME ; class CStifSectionParser * CStifSectionParser::NextSubSectionL(class TDesC16 const &, class TDesC16 const &, int)
+	?OutputType@CStifLogger@@QAE?AW4TOutput@1@XZ @ 76 NONAME ; enum CStifLogger::TOutput CStifLogger::OutputType(void)
+	?ParsingType@CStifItemParser@@QAE?AW4TParsingType@1@XZ @ 77 NONAME ; enum CStifItemParser::TParsingType CStifItemParser::ParsingType(void)
+	?Printf@CTestModuleIf@@QAAXHABVTDesC16@@V?$TRefByValue@$$CBVTDesC16@@@@ZZ @ 78 NONAME ; void CTestModuleIf::Printf(int, class TDesC16 const &, class TRefByValue<class TDesC16 const >, ...)
+	?Reboot@CTestModuleIf@@QAEHH@Z @ 79 NONAME ; int CTestModuleIf::Reboot(int)
+	?Remainder@CStifItemParser@@QAEHAAVTPtrC16@@@Z @ 80 NONAME ; int CStifItemParser::Remainder(class TPtrC16 &)
+	?RemoteReceive@CTestModuleIf@@QAEXAAVTDes16@@AAVTRequestStatus@@@Z @ 81 NONAME ; void CTestModuleIf::RemoteReceive(class TDes16 &, class TRequestStatus &)
+	?RemoteReceiveCancel@CTestModuleIf@@QAEXXZ @ 82 NONAME ; void CTestModuleIf::RemoteReceiveCancel(void)
+	?RemoteSend@CTestModuleIf@@QAEHABVTDesC16@@@Z @ 83 NONAME ; int CTestModuleIf::RemoteSend(class TDesC16 const &)
+	?RemoteType@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 84 NONAME ; class TPtrC16 CStifTFwIfProt::RemoteType(int)
+	?ResetAllowResult@CTestModuleIf@@QAEHXZ @ 85 NONAME ; int CTestModuleIf::ResetAllowResult(void)
+	?RespParam@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 86 NONAME ; class TPtrC16 CStifTFwIfProt::RespParam(int)
+	?ResultCategory@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 87 NONAME ; class TPtrC16 CStifTFwIfProt::ResultCategory(int)
+	?RunInternalL@CScriptBase@@MAEHQBVTStifFunctionInfo@@HAAVCStifItemParser@@@Z @ 88 NONAME ; int CScriptBase::RunInternalL(class TStifFunctionInfo const * const, int, class CStifItemParser &)
+	?RunParams@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 89 NONAME ; class TPtrC16 CStifTFwIfProt::RunParams(int)
+	?RunStatus@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 90 NONAME ; class TPtrC16 CStifTFwIfProt::RunStatus(int)
+	?RunStatusParams@CStifTFwIfProt@@SA?AVTPtrC16@@H@Z @ 91 NONAME ; class TPtrC16 CStifTFwIfProt::RunStatusParams(int)
+	?SaveData@CStifLogger@@QAEHAAVTDesC16@@@Z @ 92 NONAME ; int CStifLogger::SaveData(class TDesC16 &)
+	?SaveData@CStifLogger@@QAEHAAVTDesC8@@@Z @ 93 NONAME ; int CStifLogger::SaveData(class TDesC8 &)
+	?SectionL@CStifParser@@QAEPAVCStifSectionParser@@ABVTDesC16@@0H@Z @ 94 NONAME ; class CStifSectionParser * CStifParser::SectionL(class TDesC16 const &, class TDesC16 const &, int)
+	?SetAllowResult@CTestModuleIf@@QAEHH@Z @ 95 NONAME ; int CTestModuleIf::SetAllowResult(int)
+	?SetBehavior@CTestModuleIf@@QAEHW4TTestBehavior@1@PAX@Z @ 96 NONAME ; int CTestModuleIf::SetBehavior(enum CTestModuleIf::TTestBehavior, void *)
+	?SetCmdType@CStifTFwIfProt@@QAEHW4TCmdType@1@@Z @ 97 NONAME ; int CStifTFwIfProt::SetCmdType(enum CStifTFwIfProt::TCmdType)
+	?SetDstId@CStifTFwIfProt@@QAEHK@Z @ 98 NONAME ; int CStifTFwIfProt::SetDstId(unsigned long)
+	?SetExitReason@CTestModuleIf@@QAEXW4TExitReason@1@H@Z @ 99 NONAME ; void CTestModuleIf::SetExitReason(enum CTestModuleIf::TExitReason, int)
+	?SetL@CStifTFwIfProt@@QAEHABVTDesC16@@@Z @ 100 NONAME ; int CStifTFwIfProt::SetL(class TDesC16 const &)
+	?SetMsgType@CStifTFwIfProt@@QAEHW4TMsgType@1@@Z @ 101 NONAME ; int CStifTFwIfProt::SetMsgType(enum CStifTFwIfProt::TMsgType)
+	?SetParsingType@CStifItemParser@@QAEHW4TParsingType@1@@Z @ 102 NONAME ; int CStifItemParser::SetParsingType(enum CStifItemParser::TParsingType)
+	?SetPosition@CStifSectionParser@@QAEHH@Z @ 103 NONAME ; int CStifSectionParser::SetPosition(int)
+	?SetRespType@CStifTFwIfProt@@QAEHW4TMsgType@1@@Z @ 104 NONAME ; int CStifTFwIfProt::SetRespType(enum CStifTFwIfProt::TMsgType)
+	?SetResult@TTestResult@@QAEXHABVTDesC16@@@Z @ 105 NONAME ; void TTestResult::SetResult(int, class TDesC16 const &)
+	?SetScripter@CScriptBase@@AAEXP6AHPAVCTestScripter@@W4TStifTSCallBackType@@ABVTDesC16@@@Z0@Z @ 106 NONAME ; void CScriptBase::SetScripter(int (*)(class CTestScripter *, enum TStifTSCallBackType, class TDesC16 const &), class CTestScripter *)
+	?SetSrcId@CStifTFwIfProt@@QAEHK@Z @ 107 NONAME ; int CStifTFwIfProt::SetSrcId(unsigned long)
+	?Signal@CScriptBase@@QAEXH@Z @ 108 NONAME ; void CScriptBase::Signal(int)
+	?SrcDevId@CStifTFwIfProt@@QAEGXZ @ 109 NONAME ; unsigned short CStifTFwIfProt::SrcDevId(void)
+	?SrcId@CStifTFwIfProt@@QAEKXZ @ 110 NONAME ; unsigned long CStifTFwIfProt::SrcId(void)
+	?SrcTestId@CStifTFwIfProt@@QAEGXZ @ 111 NONAME ; unsigned short CStifTFwIfProt::SrcTestId(void)
+	?Start@CSTIFTestMeasurement@@QAEHXZ @ 112 NONAME ; int CSTIFTestMeasurement::Start(void)
+	?StartSession@@YAHXZ @ 113 NONAME ; int StartSession(void)
+	?StifMacroError@CTestModuleIf@@QAEHHPBEPBDHHHHHHH@Z @ 114 NONAME ; int CTestModuleIf::StifMacroError(int, unsigned char const *, char const *, int, int, int, int, int, int, int)
+	?Stop@CSTIFTestMeasurement@@QAEHXZ @ 115 NONAME ; int CSTIFTestMeasurement::Stop(void)
+	?StoreState@CTestModuleIf@@QAEHHAAV?$TBuf@$0IA@@@@Z @ 116 NONAME ; int CTestModuleIf::StoreState(int, class TBuf<128> &)
+	?SubSectionL@CStifSectionParser@@QAEPAV1@ABVTDesC16@@0H@Z @ 117 NONAME ; class CStifSectionParser * CStifSectionParser::SubSectionL(class TDesC16 const &, class TDesC16 const &, int)
+	?TestModuleIf@CScriptBase@@QAEAAVCTestModuleIf@@XZ @ 118 NONAME ; class CTestModuleIf & CScriptBase::TestModuleIf(void)
+	?WriteDelimiter@CStifLogger@@QAEHABVTDesC16@@H@Z @ 119 NONAME ; int CStifLogger::WriteDelimiter(class TDesC16 const &, int)
+	?WriteDelimiter@CStifLogger@@QAEHABVTDesC8@@H@Z @ 120 NONAME ; int CStifLogger::WriteDelimiter(class TDesC8 const &, int)
+	?StopExecution@CTestModuleIf@@QAEHW4TStopExecutionType@@H@Z @ 121 NONAME ; int CTestModuleIf::StopExecution(enum TStopExecutionType, int)
+	?GetConstantValue@CScriptBase@@IAEHABVTDesC16@@AAH@Z @ 122 NONAME ; int CScriptBase::GetConstantValue(class TDesC16 const &, int &)
+	?GetConstantValue@CScriptBase@@IAEHABVTDesC16@@AAN@Z @ 123 NONAME ; int CScriptBase::GetConstantValue(class TDesC16 const &, double &)
+	?GetConstantValue@CScriptBase@@IAEHABVTDesC16@@AAVTDes16@@@Z @ 124 NONAME ; int CScriptBase::GetConstantValue(class TDesC16 const &, class TDes16 &)
+	?CorrectFilePathL@TStifUtil@@SAXAAVTDes16@@@Z @ 125 NONAME ; void TStifUtil::CorrectFilePathL(class TDes16 &)
+	?GetTestCaseTitleL@CTestModuleIf@@QAEXAAVTDes16@@@Z @ 126 NONAME ; void CTestModuleIf::GetTestCaseTitleL(class TDes16 &)
+	?STIFVersion@TStifUtil@@SAXAAH00AAVTDes16@@@Z @ 127 NONAME ; void TStifUtil::STIFVersion(int &, int &, int &, class TDes16 &)
+	?GetUiEnvProxy@CTestModuleIf@@QAEPAVCUiEnvProxy@@XZ @ 128 NONAME ; class CUiEnvProxy * CTestModuleIf::GetUiEnvProxy(void)
+	?UITesting@CTestModuleIf@@QAEHXZ @ 129 NONAME ; int CTestModuleIf::UITesting(void)
+	?SendTestModuleVersion@CTestModuleIf@@QAEHVTVersion@@V?$TBuf@$0BAA@@@@Z @ 130 NONAME ; int CTestModuleIf::SendTestModuleVersion(class TVersion, class TBuf<256>)
+	?SendTestModuleVersion@CTestModuleIf@@QAEHAAVTVersion@@ABVTDesC16@@H@Z @ 131 NONAME ; int CTestModuleIf::SendTestModuleVersion(class TVersion &, class TDesC16 const &, int)
+	?SetResultDescription@CScriptBase@@QAEXABVTDesC16@@@Z @ 132 NONAME ; void CScriptBase::SetResultDescription(class TDesC16 const &)
+	?SetLocalValue@CScriptBase@@IAEHABVTDesC16@@0@Z @ 133 NONAME ; int CScriptBase::SetLocalValue(class TDesC16 const &, class TDesC16 const &)
+	?SetLocalValue@CScriptBase@@IAEHABVTDesC16@@H@Z @ 134 NONAME ; int CScriptBase::SetLocalValue(class TDesC16 const &, int)
+	?SetLocalValue@CScriptBase@@IAEHABVTDesC16@@N@Z @ 135 NONAME ; int CScriptBase::SetLocalValue(class TDesC16 const &, double)
+	?GetLocalValue@CScriptBase@@IAEHABVTDesC16@@AAH@Z @ 136 NONAME ; int CScriptBase::GetLocalValue(class TDesC16 const &, int &)
+	?GetLocalValue@CScriptBase@@IAEHABVTDesC16@@AAN@Z @ 137 NONAME ; int CScriptBase::GetLocalValue(class TDesC16 const &, double &)
+	?GetLocalValue@CScriptBase@@IAEHABVTDesC16@@AAVTDes16@@@Z @ 138 NONAME ; int CScriptBase::GetLocalValue(class TDesC16 const &, class TDes16 &)
+	?GetTestCaseArguments@CTestModuleIf@@QBEABVTDesC16@@XZ @ 139 NONAME ; class TDesC16 const & CTestModuleIf::GetTestCaseArguments(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/eabi/StifTestInterfaceu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,187 @@
+EXPORTS
+	_Z12StartSessionv @ 1 NONAME
+	_ZN11CScriptBase11SetScripterEPFiP13CTestScripter19TStifTSCallBackTypeRK7TDesC16ES1_ @ 2 NONAME
+	_ZN11CScriptBase12CancelSignalEv @ 3 NONAME
+	_ZN11CScriptBase12EnableSignalER14TRequestStatus @ 4 NONAME
+	_ZN11CScriptBase12RunInternalLEPK17TStifFunctionInfoiR15CStifItemParser @ 5 NONAME
+	_ZN11CScriptBase12TestModuleIfEv @ 6 NONAME
+	_ZN11CScriptBase13CallTestClassERK7TDesC16 @ 7 NONAME
+	_ZN11CScriptBase13GetTestObjectERK7TDesC16 @ 8 NONAME
+	_ZN11CScriptBase6SignalEi @ 9 NONAME
+	_ZN11CScriptBaseC2ER13CTestModuleIf @ 10 NONAME
+	_ZN11CStifLogger10OutputTypeEv @ 11 NONAME
+	_ZN11CStifLogger14CreationResultEv @ 12 NONAME
+	_ZN11CStifLogger14WriteDelimiterERK6TDesC8i @ 13 NONAME
+	_ZN11CStifLogger14WriteDelimiterERK7TDesC16i @ 14 NONAME
+	_ZN11CStifLogger3LogE11TRefByValueIK6TDesC8Ez @ 15 NONAME
+	_ZN11CStifLogger3LogE11TRefByValueIK7TDesC16Ez @ 16 NONAME
+	_ZN11CStifLogger3LogERK6TDesC8 @ 17 NONAME
+	_ZN11CStifLogger3LogERK7TDesC16 @ 18 NONAME
+	_ZN11CStifLogger3LogEi11TRefByValueIK6TDesC8Ez @ 19 NONAME
+	_ZN11CStifLogger3LogEi11TRefByValueIK7TDesC16Ez @ 20 NONAME
+	_ZN11CStifLogger3LogEiRK6TDesC8 @ 21 NONAME
+	_ZN11CStifLogger3LogEiRK7TDesC16 @ 22 NONAME
+	_ZN11CStifLogger4NewLERK7TDesC16S2_NS_11TLoggerTypeENS_7TOutputEiiiiiiii @ 23 NONAME
+	_ZN11CStifLogger4NewLERK7TDesC16S2_R15TLoggerSettings @ 24 NONAME
+	_ZN11CStifLogger8SaveDataER6TDesC8 @ 25 NONAME
+	_ZN11CStifLogger8SaveDataER7TDesC16 @ 26 NONAME
+	_ZN11CStifParser12NextSectionLERK7TDesC16S2_i @ 27 NONAME
+	_ZN11CStifParser4NewLERK7TDesC16NS_12TCommentTypeE @ 28 NONAME
+	_ZN11CStifParser4NewLERK7TDesC16S2_NS_12TCommentTypeE @ 29 NONAME
+	_ZN11CStifParser8SectionLERK7TDesC16S2_i @ 30 NONAME
+	_ZN11CStifParserD0Ev @ 31 NONAME
+	_ZN11CStifParserD1Ev @ 32 NONAME
+	_ZN11CStifParserD2Ev @ 33 NONAME
+	_ZN11TTestResult9SetResultEiRK7TDesC16 @ 34 NONAME
+	_ZN11TTestResultC1Ev @ 35 NONAME
+	_ZN11TTestResultC2Ev @ 36 NONAME
+	_ZN13CTestModuleIf10RemoteSendERK7TDesC16 @ 37 NONAME
+	_ZN13CTestModuleIf10StoreStateEiR4TBufILi128EE @ 38 NONAME
+	_ZN13CTestModuleIf11CancelEventER8TEventIfP14TRequestStatus @ 39 NONAME
+	_ZN13CTestModuleIf11SetBehaviorENS_13TTestBehaviorEPv @ 40 NONAME
+	_ZN13CTestModuleIf13RemoteReceiveER6TDes16R14TRequestStatus @ 41 NONAME
+	_ZN13CTestModuleIf13SetExitReasonENS_11TExitReasonEi @ 42 NONAME
+	_ZN13CTestModuleIf14GetStoredStateERiR4TBufILi128EE @ 43 NONAME
+	_ZN13CTestModuleIf14SetAllowResultEi @ 44 NONAME
+	_ZN13CTestModuleIf14StifMacroErrorEiPKhPKciiiiiii @ 45 NONAME
+	_ZN13CTestModuleIf16CheckAllowResultEi @ 46 NONAME
+	_ZN13CTestModuleIf16ResetAllowResultEv @ 47 NONAME
+	_ZN13CTestModuleIf19RemoteReceiveCancelEv @ 48 NONAME
+	_ZN13CTestModuleIf21GetMeasurementOptionsERi @ 49 NONAME
+	_ZN13CTestModuleIf4NewLEP20CTestThreadContainerP15CTestModuleBase @ 50 NONAME
+	_ZN13CTestModuleIf5EventER8TEventIf @ 51 NONAME
+	_ZN13CTestModuleIf5EventER8TEventIfR14TRequestStatus @ 52 NONAME
+	_ZN13CTestModuleIf6PrintfEiRK7TDesC1611TRefByValueIS1_Ez @ 53 NONAME
+	_ZN13CTestModuleIf6RebootEi @ 54 NONAME
+	_ZN13TTestCaseInfoC1Ev @ 55 NONAME
+	_ZN13TTestCaseInfoC2Ev @ 56 NONAME
+	_ZN13TTestProgressC1Ev @ 57 NONAME
+	_ZN13TTestProgressC2Ev @ 58 NONAME
+	_ZN14CStifTFwIfProt10RemoteTypeEi @ 59 NONAME
+	_ZN14CStifTFwIfProt10SetCmdTypeENS_8TCmdTypeE @ 60 NONAME
+	_ZN14CStifTFwIfProt10SetMsgTypeENS_8TMsgTypeE @ 61 NONAME
+	_ZN14CStifTFwIfProt11EventStatusEi @ 62 NONAME
+	_ZN14CStifTFwIfProt11SetRespTypeENS_8TMsgTypeE @ 63 NONAME
+	_ZN14CStifTFwIfProt14ResultCategoryEi @ 64 NONAME
+	_ZN14CStifTFwIfProt15RunStatusParamsEi @ 65 NONAME
+	_ZN14CStifTFwIfProt17EventStatusParamsEi @ 66 NONAME
+	_ZN14CStifTFwIfProt4NewLEv @ 67 NONAME
+	_ZN14CStifTFwIfProt4SetLERK7TDesC16 @ 68 NONAME
+	_ZN14CStifTFwIfProt5DstIdEv @ 69 NONAME
+	_ZN14CStifTFwIfProt5SrcIdEv @ 70 NONAME
+	_ZN14CStifTFwIfProt6AppendEPF7TPtrC16iEi @ 71 NONAME
+	_ZN14CStifTFwIfProt6AppendEPF7TPtrC16iEiRK7TDesC16 @ 72 NONAME
+	_ZN14CStifTFwIfProt6AppendEPF7TPtrC16iEiS2_i @ 73 NONAME
+	_ZN14CStifTFwIfProt6AppendEPF7TPtrC16iEii @ 74 NONAME
+	_ZN14CStifTFwIfProt6AppendERK7TDesC16 @ 75 NONAME
+	_ZN14CStifTFwIfProt7CmdTypeEi @ 76 NONAME
+	_ZN14CStifTFwIfProt7CreateLEi @ 77 NONAME
+	_ZN14CStifTFwIfProt7MsgTypeEi @ 78 NONAME
+	_ZN14CStifTFwIfProt8AppendIdEm @ 79 NONAME
+	_ZN14CStifTFwIfProt8DstDevIdEv @ 80 NONAME
+	_ZN14CStifTFwIfProt8SetDstIdEm @ 81 NONAME
+	_ZN14CStifTFwIfProt8SetSrcIdEm @ 82 NONAME
+	_ZN14CStifTFwIfProt8SrcDevIdEv @ 83 NONAME
+	_ZN14CStifTFwIfProt9DstTestIdEv @ 84 NONAME
+	_ZN14CStifTFwIfProt9EventTypeEi @ 85 NONAME
+	_ZN14CStifTFwIfProt9RespParamEi @ 86 NONAME
+	_ZN14CStifTFwIfProt9RunParamsEi @ 87 NONAME
+	_ZN14CStifTFwIfProt9RunStatusEi @ 88 NONAME
+	_ZN14CStifTFwIfProt9SrcTestIdEv @ 89 NONAME
+	_ZN14CStifTFwIfProtD0Ev @ 90 NONAME
+	_ZN14CStifTFwIfProtD1Ev @ 91 NONAME
+	_ZN14CStifTFwIfProtD2Ev @ 92 NONAME
+	_ZN15CStifItemParser10GetNextIntERK7TDesC16Ri @ 93 NONAME
+	_ZN15CStifItemParser10GetNextIntERK7TDesC16Rj6TRadix @ 94 NONAME
+	_ZN15CStifItemParser10GetNextIntERi @ 95 NONAME
+	_ZN15CStifItemParser10GetNextIntERj6TRadix @ 96 NONAME
+	_ZN15CStifItemParser11GetNextCharER5TChar @ 97 NONAME
+	_ZN15CStifItemParser11GetNextCharERK7TDesC16R5TChar @ 98 NONAME
+	_ZN15CStifItemParser11ParsingTypeEv @ 99 NONAME
+	_ZN15CStifItemParser13GetNextStringER7TPtrC16 @ 100 NONAME
+	_ZN15CStifItemParser13GetNextStringERK7TDesC16R7TPtrC16 @ 101 NONAME
+	_ZN15CStifItemParser14SetParsingTypeENS_12TParsingTypeE @ 102 NONAME
+	_ZN15CStifItemParser4NewLE7TPtrC16ii @ 103 NONAME
+	_ZN15CStifItemParser6GetIntERK7TDesC16Ri @ 104 NONAME
+	_ZN15CStifItemParser6GetIntERK7TDesC16Rj6TRadix @ 105 NONAME
+	_ZN15CStifItemParser7GetCharERK7TDesC16R5TChar @ 106 NONAME
+	_ZN15CStifItemParser9GetStringERK7TDesC16R7TPtrC16 @ 107 NONAME
+	_ZN15CStifItemParser9RemainderER7TPtrC16 @ 108 NONAME
+	_ZN15TFullTestResultC1Ev @ 109 NONAME
+	_ZN15TFullTestResultC2Ev @ 110 NONAME
+	_ZN18CStifSectionParser11GetNextLineER7TPtrC16 @ 111 NONAME
+	_ZN18CStifSectionParser11GetNextLineERK7TDesC16R7TPtrC1617TTagToReturnValue @ 112 NONAME
+	_ZN18CStifSectionParser11GetPositionEv @ 113 NONAME
+	_ZN18CStifSectionParser11SetPositionEi @ 114 NONAME
+	_ZN18CStifSectionParser11SubSectionLERK7TDesC16S2_i @ 115 NONAME
+	_ZN18CStifSectionParser12GetItemLineLERK7TDesC1617TTagToReturnValue @ 116 NONAME
+	_ZN18CStifSectionParser15NextSubSectionLERK7TDesC16S2_i @ 117 NONAME
+	_ZN18CStifSectionParser16GetNextItemLineLERK7TDesC1617TTagToReturnValue @ 118 NONAME
+	_ZN18CStifSectionParser16GetNextItemLineLEv @ 119 NONAME
+	_ZN18CStifSectionParser7GetLineERK7TDesC16R7TPtrC1617TTagToReturnValue @ 120 NONAME
+	_ZN18TErrorNotificationC1Ev @ 121 NONAME
+	_ZN18TErrorNotificationC2Ev @ 122 NONAME
+	_ZN20CSTIFTestMeasurement4NewLEP15CTestModuleBaseNS_20TSTIFMeasurementTypeERK7TDesC16 @ 123 NONAME
+	_ZN20CSTIFTestMeasurement4StopEv @ 124 NONAME
+	_ZN20CSTIFTestMeasurement5StartEv @ 125 NONAME
+	_ZN21CTestModuleParamVer014NewLEv @ 126 NONAME
+	_ZN21CTestModuleParamVer01D0Ev @ 127 NONAME
+	_ZN21CTestModuleParamVer01D1Ev @ 128 NONAME
+	_ZN21CTestModuleParamVer01D2Ev @ 129 NONAME
+	_ZN21MSTIFTestInterference4NewLEP15CTestModuleBaseNS_29TStifTestInterferenceCategoryE @ 130 NONAME
+	_ZN9TTestInfoC1Ev @ 131 NONAME
+	_ZN9TTestInfoC2Ev @ 132 NONAME
+	_ZTI10CTxtLogger @ 133 NONAME ; #<TI>#
+	_ZTI11CDataLogger @ 134 NONAME ; #<TI>#
+	_ZTI11CFileOutput @ 135 NONAME ; #<TI>#
+	_ZTI11CHtmlLogger @ 136 NONAME ; #<TI>#
+	_ZTI11CNullOutput @ 137 NONAME ; #<TI>#
+	_ZTI11CScriptBase @ 138 NONAME ; #<TI>#
+	_ZTI11CStifLogger @ 139 NONAME ; #<TI>#
+	_ZTI11CStifParser @ 140 NONAME ; #<TI>#
+	_ZTI13CRDebugOutput @ 141 NONAME ; #<TI>#
+	_ZTI13CTestModuleIf @ 142 NONAME ; #<TI>#
+	_ZTI14CStifTFwIfProt @ 143 NONAME ; #<TI>#
+	_ZTI15CStifItemParser @ 144 NONAME ; #<TI>#
+	_ZTI18CStifSectionParser @ 145 NONAME ; #<TI>#
+	_ZTI21CTestModuleParamVer01 @ 146 NONAME ; #<TI>#
+	_ZTI25TDesLoggerOverflowHandler @ 147 NONAME ; #<TI>#
+	_ZTI26TDes8LoggerOverflowHandler @ 148 NONAME ; #<TI>#
+	_ZTI7COutput @ 149 NONAME ; #<TI>#
+	_ZTV10CTxtLogger @ 150 NONAME ; #<VT>#
+	_ZTV11CDataLogger @ 151 NONAME ; #<VT>#
+	_ZTV11CFileOutput @ 152 NONAME ; #<VT>#
+	_ZTV11CHtmlLogger @ 153 NONAME ; #<VT>#
+	_ZTV11CNullOutput @ 154 NONAME ; #<VT>#
+	_ZTV11CScriptBase @ 155 NONAME ; #<VT>#
+	_ZTV11CStifLogger @ 156 NONAME ; #<VT>#
+	_ZTV11CStifParser @ 157 NONAME ; #<VT>#
+	_ZTV13CRDebugOutput @ 158 NONAME ; #<VT>#
+	_ZTV13CTestModuleIf @ 159 NONAME ; #<VT>#
+	_ZTV14CStifTFwIfProt @ 160 NONAME ; #<VT>#
+	_ZTV15CStifItemParser @ 161 NONAME ; #<VT>#
+	_ZTV18CStifSectionParser @ 162 NONAME ; #<VT>#
+	_ZTV21CTestModuleParamVer01 @ 163 NONAME ; #<VT>#
+	_ZTV25TDesLoggerOverflowHandler @ 164 NONAME ; #<VT>#
+	_ZTV26TDes8LoggerOverflowHandler @ 165 NONAME ; #<VT>#
+	_ZTV7COutput @ 166 NONAME ; #<VT>#
+	_ZN13CTestModuleIf13StopExecutionE18TStopExecutionTypei @ 167 NONAME
+	_ZN11CScriptBase16GetConstantValueERK7TDesC16R6TDes16 @ 168 NONAME
+	_ZN11CScriptBase16GetConstantValueERK7TDesC16Rd @ 169 NONAME
+	_ZN11CScriptBase16GetConstantValueERK7TDesC16Ri @ 170 NONAME
+	_ZN9TStifUtil16CorrectFilePathLER6TDes16 @ 171 NONAME
+	_ZN13CTestModuleIf17GetTestCaseTitleLER6TDes16 @ 172 NONAME
+	_ZN9TStifUtil11STIFVersionERiS0_S0_R6TDes16 @ 173 NONAME
+	_ZN13CTestModuleIf13GetUiEnvProxyEv @ 174 NONAME
+	_ZN13CTestModuleIf9UITestingEv @ 175 NONAME
+	_ZN13CTestModuleIf21SendTestModuleVersionE8TVersion4TBufILi256EE @ 176 NONAME
+	_ZN13CTestModuleIf21SendTestModuleVersionER8TVersionRK7TDesC16i @ 177 NONAME
+	_ZN11CScriptBase20SetResultDescriptionERK7TDesC16 @ 178 NONAME
+	_ZN11CScriptBase13GetLocalValueERK7TDesC16R6TDes16 @ 179 NONAME
+	_ZN11CScriptBase13GetLocalValueERK7TDesC16Rd @ 180 NONAME
+	_ZN11CScriptBase13GetLocalValueERK7TDesC16Ri @ 181 NONAME
+	_ZN11CScriptBase13SetLocalValueERK7TDesC16S2_ @ 182 NONAME
+	_ZN11CScriptBase13SetLocalValueERK7TDesC16d @ 183 NONAME
+	_ZN11CScriptBase13SetLocalValueERK7TDesC16i @ 184 NONAME
+	_ZNK13CTestModuleIf20GetTestCaseArgumentsEv @ 185 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/group/TestInterface.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestInterface 
+* module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          StifTestInterface.dll
+TARGETTYPE      dll
+
+CAPABILITY	ALL -TCB
+VENDORID 	0x101FB657
+SECUREID        0x102073E1
+
+DEFFILE         StifTestInterface.def
+
+LIBRARY         euser.lib   		// For TInt, etc.
+LIBRARY         efsrv.lib   		// For RFs file server
+LIBRARY         stiftestengine.lib 	// For testengine server
+LIBRARY         stiftestserver.lib 	// For testengine server
+LIBRARY         testscripter.lib 	// For testengine server
+LIBRARY         hal.lib     		// For logging (HAL)
+//LIBRARY         bafl.lib			// For file system utilities
+
+OS_LAYER_SYSTEMINCLUDE
+
+// ------- Logger -------
+USERINCLUDE     ../../Logger/inc
+SOURCEPATH      ../../Logger/src
+
+SOURCE          StifLogger.cpp
+SOURCE          Output.cpp
+SOURCE          FileOutput.cpp
+SOURCE		    RDebugOutput.cpp
+SOURCE          NullOutput.cpp
+SOURCE          TxtLogger.cpp
+SOURCE          HtmlLogger.cpp
+SOURCE          DataLogger.cpp
+SOURCE          LoggerOverFlow.cpp
+
+// ------- Parser -------
+USERINCLUDE     ../../Parser/inc
+SOURCEPATH      ../../Parser/src
+
+SOURCE          StifParser.cpp
+SOURCE          StifSectionParser.cpp
+SOURCE          StifItemParser.cpp
+SOURCE          StifFileParser.cpp
+
+// ------- TestInterface -------
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+SOURCEPATH      ../src
+
+SOURCE          TestInterface.cpp
+SOURCE          TestModuleIf.cpp
+SOURCE          StifTFwIfProt.cpp 
+SOURCE          TestModuleParameters.cpp 
+
+// ------- TestScripter's TestClass API -------
+USERINCLUDE     ../../TestScripter/inc
+SOURCEPATH      ../../TestScripter/src
+
+SOURCE          TestScripterInternal.cpp
+
+// ------- TestInterference -------
+USERINCLUDE     ../../TestInterference/inc
+SOURCEPATH      ../../TestInterference/src
+
+SOURCE          StifTestInterference.cpp
+
+// First UID is DLL UID, Second UID is STIF Test Framework UID
+UID             0x1000008D 0x101FB3DE
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for STIF Test Framework's TestInterface.
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	TestInterface.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/src/StifTFwIfProt.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2051 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file conatins StifTfIfProt implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include "StifTFwIfProt.h"
+
+#include <StifLogger.h>
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define DEBUG(a) RDebug::Print(a)
+//#define DEBUG2(a,b) RDebug::Print(a,b)
+//#define DEBUG3(a,b,c) RDebug::Print(a,b,c)
+#define DEBUG(a)
+#define DEBUG2(a,b)
+#define DEBUG3(a,b,c)
+#define ERROR RDebug::Print
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Function: <function name>
+
+    Description: <one line description>
+
+    <Description of the functionality 
+    description continues and...
+    continues>
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+/*
+<type function_name(
+    <arg_type arg,>  
+    <arg_type arg >)  	
+    {
+    // <comment>
+    <code> 
+    
+    // <comment>
+    <code>
+    }
+*/
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CStifTFwIfProt class 
+	member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: CStifTFwIfProt
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters:	none
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+CStifTFwIfProt::CStifTFwIfProt(): iMessage(0,0)
+    { 
+    };
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CStifTFwIfProt::ConstructL()
+    {        
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters:    None
+
+     Return Values: CStifTFwIfProt*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves and in oom.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifTFwIfProt* CStifTFwIfProt::NewL()
+    {
+     
+    CStifTFwIfProt* self = new (ELeave) CStifTFwIfProt();
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: ~CStifTFwIfProt
+
+    Description: Destructor
+
+    Parameters:	None
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/    
+
+EXPORT_C CStifTFwIfProt::~CStifTFwIfProt()
+    {
+    
+    delete iItem;
+    delete iMessageBuf;
+    iMessageBuf = NULL;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: CreateL
+
+    Description: Create new empty protocol message.
+
+    Parameters:	TInt aLength: in: protocol message length
+    
+    Return Values: None
+    
+    Errors/Exceptions: Leave if oom.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CStifTFwIfProt::CreateL( TInt aLength )
+    {
+    
+    // Delete previous if exists
+    delete iMessageBuf;
+    iMessageBuf = NULL;
+    iMessage.Set( 0, 0, 0 );
+    
+    iMessageBuf = HBufC::NewL( aLength );
+    iMessage.Set( iMessageBuf->Des() );
+            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: Append
+
+    Description: Append string to protocol message.
+
+    Parameters:	TInt aLength: in: protocol message length
+    
+    Return Values: None
+    
+    Errors/Exceptions: Leave if oom.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/   
+EXPORT_C TInt CStifTFwIfProt::Append( const TDesC& aStr )
+    {
+    
+    if( ( aStr.Length() + 1 ) >
+        ( iMessage.MaxLength() - iMessage.Length() ) )
+        {
+        ERROR( _L("No space left for string") );
+        return KErrOverflow;   
+        }
+    iMessage.Append( aStr );
+    iMessage.Append( _L(" ") );
+    
+    return KErrNone;
+
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: Append
+
+    Description: Append hexadecimal value to protocol message.
+
+    Parameters:	TInt aLength: in: protocol message length
+    
+    Return Values: None
+    
+    Errors/Exceptions: Leave if oom.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/   
+EXPORT_C TInt CStifTFwIfProt::AppendId( TUint32 aId )
+    {
+    
+     if( ( KMaxValueLength + 1 ) >
+        ( iMessage.MaxLength() - iMessage.Length() ) )
+        {
+        ERROR( _L("No space left for string") );
+        return KErrOverflow;   
+        }
+        
+    iMessage.AppendNumFixedWidth( aId, EHex, KProtocolIdLength );
+    iMessage.Append( _L(" ") );
+    
+    return KErrNone;
+
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: Append
+
+    Description: Append string to protocol message.
+
+    Parameters:	TInt aLength: in: protocol message length
+    
+    Return Values: None
+    
+    Errors/Exceptions: Leave if oom.
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/   
+EXPORT_C TInt CStifTFwIfProt::Append( KeywordFunc aFunc, TInt aKeyword )
+    {
+    
+    if( ( aFunc( aKeyword ).Length() + 1 ) >
+        ( iMessage.MaxLength() - iMessage.Length() ) )
+        {
+        ERROR( _L("No space left for string") );
+        return KErrOverflow;   
+        }
+    iMessage.Append( aFunc( aKeyword ) );
+    iMessage.Append( _L(" ") );
+    
+    return KErrNone;
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: Append
+
+    Description: Append type-value string to protocol message.
+
+    Parameters:	TInt aLength: in: protocol message length
+    
+    Return Values: None
+    
+    Errors/Exceptions: Leave if oom.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/   
+EXPORT_C TInt CStifTFwIfProt::Append( KeywordFunc aFunc, 
+                                      TInt aKeyword, 
+                                      const TDesC& aStr )
+    {
+    
+     if( ( aFunc( aKeyword ).Length() + 2 +  aStr.Length() ) >
+        ( iMessage.MaxLength() - iMessage.Length() ) )
+        {
+        ERROR( _L("No space left for string") );
+        return KErrOverflow;
+        }
+        
+    iMessage.Append( aFunc( aKeyword ) );
+    iMessage.Append( _L("=") );
+    iMessage.Append( aStr );
+    iMessage.Append( _L(" ") );
+    
+    return KErrNone;
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: Append
+
+    Description: Append type-value string to protocol message.
+
+    Parameters:	TInt aLength: in: protocol message length
+    
+    Return Values: None
+    
+    Errors/Exceptions: Leave if oom.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/   
+EXPORT_C TInt CStifTFwIfProt::Append( KeywordFunc aFunc, 
+                                      TInt aKeyword, 
+                                      KeywordFunc aValueFunc, 
+                                      TInt aValue )
+    {
+    
+     if( ( aFunc( aKeyword ).Length() + 2 +  aValueFunc( aValue ).Length() ) >
+        ( iMessage.MaxLength() - iMessage.Length() ) )
+        {
+        ERROR( _L("No space left for string") );
+        return KErrOverflow;   
+        }
+        
+    iMessage.Append( aFunc( aKeyword ) );
+    iMessage.Append( _L("=") );
+    iMessage.Append( aValueFunc( aValue ) );
+    iMessage.Append( _L(" ") );
+    
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: Append
+
+    Description: Append type-value string to protocol message.
+
+    Parameters:	TInt aLength: in: protocol message length
+    
+    Return Values: None
+    
+    Errors/Exceptions: Leave if oom.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/   
+EXPORT_C TInt CStifTFwIfProt::Append( KeywordFunc aFunc, 
+                                       TInt aKeyword, 
+                                       TInt aValue )
+    {
+    
+     if( ( aFunc( aKeyword ).Length() + 2 + KMaxValueLength ) >
+        ( iMessage.MaxLength() - iMessage.Length() ) )
+        {
+        ERROR( _L("No space left for string") );
+        return KErrOverflow;   
+        }
+        
+    iMessage.Append( aFunc( aKeyword ) );
+    iMessage.Append( _L("=") );
+    iMessage.AppendNum( aValue );
+    iMessage.Append( _L(" ") );
+    
+    return KErrNone;
+
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: SetL
+
+    Description: Set and parse protocol message.
+
+    Parameters:	TDesC& aMessage: in: protocol message
+    
+    Return Values: Symbian OS error code: If protocol message parsing fails, 
+        i.e. message prsing after header <msg type> <sdcid> <dstid>
+    
+    Errors/Exceptions: Leaves if protocol header parsing fails and oom.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIfProt::SetL( const TDesC& aMessage )
+    {
+    
+    // Delete previous if exists
+    delete iMessageBuf;
+    iMessageBuf = NULL;
+    iMessage.Set( 0,0,0 );
+    
+    iMessageBuf = aMessage.AllocL();
+    iMessage.Set( iMessageBuf->Des() );
+    
+    return ParseMessageL();
+        
+    }
+            
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: SetL
+
+    Description: Get protocol source identifier.
+
+    Parameters:	None
+    
+    Return Values: Source identifier.
+    
+    Errors/Exceptions: None.
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TUint32 CStifTFwIfProt::SrcId()
+    {
+    
+    return iSrcId;    
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: SetL
+
+    Description: Get protocol source device identifier.
+
+    Parameters:	None
+    
+    Return Values: Source device identifier.
+    
+    Errors/Exceptions: None.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TUint16 CStifTFwIfProt::SrcDevId()
+    {
+    
+    return DEVID( iSrcId );  
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: SetL
+
+    Description: Get protocol source test identifier.
+
+    Parameters:	None
+    
+    Return Values: Source test identifier.
+    
+    Errors/Exceptions: None.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TUint16 CStifTFwIfProt::SrcTestId()
+    {
+
+    return TESTID( iSrcId );  
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: SetL
+
+    Description: Get protocol destination identifier.
+
+    Parameters:	None
+    
+    Return Values: Destination identifier.
+    
+    Errors/Exceptions: None.
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TUint32 CStifTFwIfProt::DstId()
+    {
+    
+    return iDstId;  
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: SetL
+
+    Description: Get protocol destination device identifier.
+
+    Parameters:	None
+    
+    Return Values: Destination device identifier.
+    
+    Errors/Exceptions: None.
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TUint16 CStifTFwIfProt::DstDevId()
+    {
+
+    return DEVID( iDstId );  
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: SetL
+
+    Description: Get protocol destination test identifier.
+
+    Parameters:	None
+    
+    Return Values: Destination test identifier.
+    
+    Errors/Exceptions: None.
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TUint16 CStifTFwIfProt::DstTestId()
+    {
+
+    return TESTID( iDstId );  
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: ParseMessageL
+
+    Description: Parse protocol message.
+
+    Parameters:	None
+
+    Return Values: None.
+
+    Errors/Exceptions: None.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStifTFwIfProt::ParseMessageL()
+    {
+    RDebug::Print(_L("CStifTFwIfProt::ParseMessageL start"));
+
+    RDebug::Print(_L("CStifTFwIfProt::ParseMessageL message content: (next line)"));
+    RDebug::Print(iMessage);
+
+    iItem = CStifItemParser::NewL( iMessage, 0, iMessage.Length() );
+
+    ParseHeaderL();
+
+    TRAPD( err,
+    switch( iMsgType )
+        {
+        case EMsgReserve:
+            RDebug::Print(_L("CStifTFwIfProt::ParseMessageL EMsgReserve"));
+            ParseReserveL();
+            break;
+        case EMsgRelease:
+            RDebug::Print(_L("CStifTFwIfProt::ParseMessageL EMsgRelease"));
+            break;
+        case EMsgRemote:
+            RDebug::Print(_L("CStifTFwIfProt::ParseMessageL EMsgRemote"));
+            ParseRemoteL();
+            break;
+        case EMsgResponse:
+            RDebug::Print(_L("CStifTFwIfProt::ParseMessageL EMsgResponse"));
+            ParseResponseL();
+            break;
+        default:
+            RDebug::Print(_L("CStifTFwIfProt::ParseMessageL ERROR invalid message type. Leaving!!!"));
+            ERROR( _L("Invalid message type") );        
+            User::Leave( KErrArgument );
+        }
+    );
+    
+    delete iItem;
+    iItem = 0;
+    
+    return err;
+           
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: ParseHeaderL
+
+    Description: Parse protocol header.
+
+    Parameters:	None
+    
+    Return Values: None.
+    
+    Errors/Exceptions: None.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void CStifTFwIfProt::ParseHeaderL()
+    {
+    
+    TPtrC tmp;
+    TInt ret;
+    TInt tmpMsgType;
+    
+    // Get and parse message type    
+    ret = iItem->GetString( _L(""), tmp );
+    if( ret != KErrNone )
+        {
+        ERROR( _L("No message type given") );        
+        User::Leave( KErrNotFound );
+        }
+        
+    tmpMsgType = Parse( tmp, MsgType );
+    if( tmpMsgType < 0 )
+        {
+        ERROR( _L("Invalid message type given") );        
+        User::Leave( KErrArgument );
+        }
+	iMsgType = ( TMsgType )tmpMsgType;
+
+    // Get and parse srcid    
+    ret = iItem->GetNextString( tmp );
+    if( ret != KErrNone )
+        {
+        ERROR( _L("No srcid given") );        
+        User::Leave( KErrNotFound );
+        }
+    // Check id length
+    if( tmp.Length() != KProtocolIdLength )
+        {
+        ERROR( _L("Invalid srcid length [%d]"), tmp.Length() );        
+        User::Leave( KErrArgument );
+        }    
+    TUint32 id;
+    TLex lex( tmp );
+    if( lex.Val( id, EHex ) != KErrNone )
+        {
+        ERROR( _L("Invalid srcid given") );        
+        User::Leave( KErrArgument );
+        }        
+    iSrcId = id;
+
+
+    // Get and parse dstid    
+    ret = iItem->GetNextString( tmp );
+    if( ret != KErrNone )
+        {
+        ERROR( _L("No dstid given") );        
+        User::Leave( KErrNotFound );
+        }
+    // Check id length
+    if( tmp.Length() != KProtocolIdLength )
+        {
+        ERROR( _L("Invalid srcid length [%d]"), tmp.Length() );        
+        User::Leave( KErrArgument );
+        }                    
+    lex.Assign( tmp );
+    if( lex.Val( id, EHex ) != KErrNone )
+        {
+        ERROR( _L("Invalid dstid given") );        
+        User::Leave( KErrArgument );
+        }        
+    iDstId = id;
+    
+    }
+    
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: ParseReserveL
+
+    Description: Parse protocol reserve message.
+
+    Parameters:	None
+    
+    Return Values: None.
+    
+    Errors/Exceptions: None.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void CStifTFwIfProt::ParseReserveL()
+    {
+    
+    TPtrC tmp;
+    TInt ret;
+	TInt tmpRemoteType;
+    
+    // Get and parse remote type    
+    ret = iItem->GetNextString( tmp );
+    if( ret != KErrNone )
+        {
+        ERROR( _L("No remote type given") );        
+        User::Leave( KErrNotFound );
+        }
+            
+    tmpRemoteType = Parse( tmp, RemoteType );
+    if( tmpRemoteType < 0 )
+        {
+        iRemoteType = ERemoteUnknown;
+        }
+    else 
+    	{
+    	iRemoteType = ( TRemoteType ) tmpRemoteType;
+    	}
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: ParseRemoteL
+
+    Description: Parse protocol remote message.
+
+    Parameters:	None
+    
+    Return Values: None.
+    
+    Errors/Exceptions: None.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void CStifTFwIfProt::ParseRemoteL()
+    {
+    RDebug::Print(_L("CStifTFwIfProt::ParseRemoteL start"));
+
+    TPtrC tmp;
+    TInt ret;
+    TInt tmpCmdType;
+
+    // Set mode of item parser to be able to read titles with spaces inside
+    iItem->SetParsingType(CStifItemParser::EQuoteStyleParsing);
+
+    // Get and parse command
+    ret = iItem->GetNextString( tmp );
+    if( ret != KErrNone )
+        {
+        ERROR( _L("No command given") );
+        User::Leave( KErrNotFound );
+        }
+
+    iCmdDes.Set( tmp );
+    tmpCmdType = Parse( tmp, CmdType );
+    RDebug::Print(_L("CStifTFwIfProt::ParseRemoteL readed command %d"), tmpCmdType);
+    if( tmpCmdType < 0 )
+        {
+        iCmdType = ECmdUnknown;
+        DEBUG( _L("Unknown command given") );        
+        }
+    else
+    	{
+    	iCmdType = ( TCmdType ) tmpCmdType;
+    	}
+        
+    switch( iCmdType )
+        {
+        case ECmdRun:
+            {
+            RDebug::Print(_L("CStifTFwIfProt::ParseRemoteL iCmdType ECmdRun"));
+            // Parse run parameters
+            TPtrC arg; 
+            TPtrC val;
+            iTestCaseNumber = KErrNotFound;
+            while( iItem->GetNextString( tmp ) == KErrNone )
+                {
+                if( ParseOptArg( tmp, arg, val ) == KErrNone )
+                    {              
+                    TInt param = Parse( arg, RunParams );
+                    if( param < 0 )
+                        {
+                        ERROR( _L("Invalid run parameter given") );        
+                        User::Leave( KErrArgument );
+                        }
+                    
+                    switch( param )
+                        {
+                        case ERunModule:
+                            iModule.Set( val );
+                            break;
+                        case ERunInifile:
+                            iIniFile.Set( val );
+                            break;
+                        case ERunTestcasefile:
+                            iTestCaseFile.Set( val );
+                            break;
+                        case ERunTestcasenum:
+                            {
+                            TLex ptr( val );
+                            if( ptr.Val( iTestCaseNumber ) != KErrNone )
+                                {
+                                ERROR( _L("Invalid test case number given") );        
+                                User::Leave( KErrArgument );
+                                }  
+                            }
+                            break;
+                        case ERunTitle:
+                            iTitle.Set(val);
+                            break;
+                        default:
+                            ERROR( _L("Invalid run parameter given") );        
+                            User::Leave( KErrArgument );
+                        }
+                    }
+                else
+                    {
+                    ERROR( _L("Invalid run parameter given") );        
+                    User::Leave( KErrArgument );
+                    }
+                }
+            if( iModule.Length() == 0 )
+                {
+                ERROR( _L("No mandatory test module name given as run parameter") );        
+                //User::Leave( KErrNotFound );
+                }    
+            if(iTestCaseNumber < 0 && iTitle.Length() == 0) //No test case number and no title
+                {
+                ERROR( _L("No mandatory test case number given as run parameter") );        
+                //User::Leave( KErrNotFound );
+                }    
+            }   
+            break;
+        case ECmdPause:
+        case ECmdResume:
+        case ECmdCancel:
+            RDebug::Print(_L("CStifTFwIfProt::ParseRemoteL iCmdType ECmdPause,Resume,Cancel"));
+            break;
+        case ECmdRequest:
+        case ECmdRelease:
+            RDebug::Print(_L("CStifTFwIfProt::ParseRemoteL iCmdType ECmdRequest,Release"));
+            ret = iItem->GetNextString( tmp );
+            if( ret != KErrNone )
+                {
+                ERROR( _L("No event name given") );        
+                //User::Leave( KErrNotFound );
+                iEventName.Set( 0, 0 );
+                }
+            else
+                {
+                iEventName.Set( tmp );
+                }
+            break;
+        case ECmdSendReceive:
+            {
+            RDebug::Print(_L("CStifTFwIfProt::ParseRemoteL iCmdType ECmdSendReceive"));
+            DEBUG( _L("sendreceive") );
+            break;
+            }
+        default:
+            RDebug::Print(_L("CStifTFwIfProt::ParseRemoteL iCmdType UNKNOWN!!!"));
+            DEBUG( _L("Unknown command") );
+            break;
+        }
+    }    
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: ParseResponseL
+
+    Description: Parse protocol response message.
+
+    Parameters:	None
+    
+    Return Values: None.
+    
+    Errors/Exceptions: None.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void CStifTFwIfProt::ParseResponseL()
+    {
+
+    TPtrC tmp;
+    TInt ret;
+    TInt tmpRespType;
+    TInt tmpCmdType;
+
+    // Get and parse request response type
+    ret = iItem->GetNextString( tmp );
+    if( ret != KErrNone )
+        {
+        ERROR( _L("No request type given") );
+        User::Leave( KErrNotFound );
+        }
+
+    tmpRespType = Parse( tmp, MsgType );
+    if( tmpRespType < 0 )
+        {
+        ERROR( _L("Invalid request type given") );
+        User::Leave( KErrArgument );
+        }
+    else
+    	{
+    	iRespType = ( TMsgType ) tmpRespType;
+    	}
+
+    ret = iItem->GetNextString( tmp );
+
+    // First check if this is a response to a remote command
+    if( iRespType == EMsgRemote )
+        {
+        if( ret != KErrNone )
+            {
+            ERROR( _L("No arguments for remote response given") );
+            User::Leave( KErrNotFound );
+            }
+
+        iCmdDes.Set( tmp );
+        tmpCmdType = Parse( tmp, CmdType );;
+        if( tmpCmdType >= 0 )
+            {
+			iCmdType = ( TCmdType ) tmpCmdType;
+            DEBUG2( _L("Remote response for %S"), &tmp );
+            ParseCmdResponseL();
+            // Get and parse general response parameters
+            ret = iItem->GetNextString( tmp );
+            }
+        else
+            {
+            iCmdType = (TCmdType)KErrNotFound;
+            }
+        }
+    while( ret == KErrNone )
+        {
+        TPtrC arg;
+        TPtrC val;
+        if( ParseOptArg( tmp, arg, val ) == KErrNone )
+            {              
+            TInt param = Parse( arg, RespParam );
+            if( param < 0 )
+                {
+                ERROR( _L("Invalid parameter given") );        
+                User::Leave( KErrArgument );
+                }
+            
+            switch( param )
+                {
+                case ERespResult:
+                    {
+                    TLex ptr( val );
+                    if( ptr.Val( iResult ) != KErrNone )
+                        {
+                        ERROR( _L("Invalid error code given") );        
+                        User::Leave( KErrArgument );
+                        }   
+                    }
+                    break;
+                default:
+                    ERROR( _L("Invalid parameter given") );        
+                    User::Leave( KErrArgument );
+                }       
+            }
+#if 0 // Check all parameters anyway
+        else 
+            {
+            ERROR( _L("Invalid parameter given") );        
+            User::Leave( KErrArgument ); 
+            }
+#endif
+        ret = iItem->GetNextString( tmp );
+
+        }
+    
+    }    
+    
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifTFwIfProt
+
+    Method: ParseCmdResponseL
+
+    Description: Parse protocol command response parameters.
+
+    Parameters:	None
+    
+    Return Values: None.
+    
+    Errors/Exceptions: None.
+    
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void CStifTFwIfProt::ParseCmdResponseL()
+    {
+    
+    TPtrC tmp;
+    TPtrC arg; 
+    TPtrC val;
+    TInt ret;
+    TInt tmpRunStatus;
+    TInt tmpResultCategory;
+    TInt tmpEventStatus;
+    TInt tmpEventType;	
+    
+    RDebug::Print(_L("CStifTFwIfProt::ParseCmdResponseL start"));
+    switch( iCmdType )
+        {
+        case ECmdRun:
+            {
+            RDebug::Print(_L("CStifTFwIfProt::ParseCmdResponseL ECmdRun"));
+            // Parse run response status 
+            ret = iItem->GetNextString( tmp );
+            if( ret != KErrNone )
+                {
+                ERROR( _L("No run response status given") );        
+                User::Leave( KErrNotFound );
+                }
+            
+            tmpRunStatus = Parse( tmp, RunStatus );;
+            if( tmpRunStatus < 0 )
+                {
+                ERROR( _L("Invalid run status in response given") );        
+                User::Leave( KErrArgument );
+                }
+            else
+            	{
+            	iRunStatus = (TRunStatus) tmpRunStatus;
+            	}
+            
+            // Parse runs status parameters
+            while( iItem->GetNextString( tmp ) == KErrNone )
+                {
+                if( ParseOptArg( tmp, arg, val ) == KErrNone )
+                    {              
+                    TInt param = Parse( arg, RunStatusParams );
+                    if( param < 0 )
+                        {
+                        ERROR( _L("Invalid run status parameter given") );        
+                        User::Leave( KErrArgument );
+                        }
+                    
+                    switch( param )
+                        {
+                        case ERunResult:
+                            {
+                            TLex ptr( val );
+                            if( ptr.Val( iResult ) != KErrNone )
+                                {
+                                ERROR( _L("Invalid run result given") );        
+                                User::Leave( KErrArgument );
+                                }  
+                            }
+                            break;
+                        case ERunCategory:
+                            tmpResultCategory = Parse( val, ResultCategory );
+                            if( tmpResultCategory < 0 )
+                                {
+                                ERROR( _L("Invalid run result category given") );        
+                                User::Leave( KErrArgument );
+                                }
+                            else 
+                            	{
+                            	iResultCategory = ( TResultCategory ) tmpResultCategory;
+                            	}
+                            break;
+                        default:
+                            ERROR( _L("Invalid run status parameter given") );        
+                            User::Leave( KErrArgument );
+                        }
+                    }
+                else
+                    {
+                    ERROR( _L("Invalid run status parameter given") );        
+                    User::Leave( KErrArgument );                    
+                    }
+                }
+            }           
+            break;
+        case ECmdPause:
+        case ECmdResume:
+        case ECmdCancel:
+            RDebug::Print(_L("CStifTFwIfProt::ParseCmdResponseL ECmdPause,Resume,Cancel"));
+            break;
+        case ECmdRequest:
+            {
+            RDebug::Print(_L("CStifTFwIfProt::ParseCmdResponseL ECmdRequest"));
+            // Parse event request response status
+            ret = iItem->GetNextString( tmp );
+            if( ret != KErrNone )
+                {
+                ERROR( _L("No request response status given") );        
+                User::Leave( KErrNotFound );
+                }
+            
+            tmpEventStatus = Parse( tmp, EventStatus );
+            if( tmpEventStatus < 0 )
+                {
+                ERROR( _L("Invalid request status in response given") );        
+                User::Leave( KErrArgument );
+                }
+            else
+            	{
+            	iEventStatus = (TEventStatus) tmpEventStatus;
+            	}
+            
+            // Parse request response event name
+            ret = iItem->GetNextString( tmp );
+            if( ret != KErrNone )
+                {
+                ERROR( _L("No request response event name given") );        
+                User::Leave( KErrNotFound );
+                }
+            iEventName.Set( tmp );    
+            
+            // Parse request response status parameters
+            while( iItem->GetNextString( tmp ) == KErrNone )
+                {
+                if( ParseOptArg( tmp, arg, val ) == KErrNone )
+                    {              
+                    TInt param = Parse( arg, EventStatusParams );
+                    if( param < 0 )
+                        {
+                        ERROR( _L("Invalid request response status parameter given") );        
+                        User::Leave( KErrArgument );
+                        }
+                    
+                    switch( param )
+                        {
+                        case EEventResult:
+                            {
+                            TLex ptr( val );
+                            if( ptr.Val( iResult ) != KErrNone )
+                                {
+                                ERROR( _L("Invalid request response status parameter result given") );        
+                                User::Leave( KErrArgument );
+                                }  
+                            }
+                            break;
+                        case EEventType:
+                            tmpEventType = Parse( val, EventType );;
+                            if( tmpEventType < 0 )
+                                {
+                                ERROR( _L("Invalid request response status parameter event type given") );        
+                                User::Leave( KErrArgument );
+                                }
+                            else
+                            	{
+                            	iEventType = ( TEventIf::TEventType ) tmpEventType;
+                            	}
+                            break;
+                        default:
+                            ERROR( _L("Invalid request response status parameter given") );        
+                            User::Leave( KErrArgument );
+                        }
+                    }
+                else
+                    {
+                    ERROR( _L("Invalid request response status parameter given") );        
+                    User::Leave( KErrArgument );            
+                    }    
+                }
+            }
+            break;
+        case ECmdRelease:
+            RDebug::Print(_L("CStifTFwIfProt::ParseCmdResponseL ECmdRelease"));
+            // Parse release response event name
+            ret = iItem->GetNextString( tmp );
+            if( ret != KErrNone )
+                {
+                ERROR( _L("No release response event name given") );        
+                User::Leave( KErrNotFound );
+                }
+            iEventName.Set( tmp );    
+            break;
+        case ECmdSetEvent:
+        case ECmdUnsetEvent:
+            RDebug::Print(_L("CStifTFwIfProt::ParseCmdResponseL ECmdSetEvent,UnsetEvent"));
+            // Parse release response event name
+            ret = iItem->GetNextString( tmp );
+            if( ret != KErrNone )
+                {
+                ERROR( _L("No set/unset response event name given") );
+                User::Leave( KErrNotFound );
+                }
+            iEventName.Set( tmp );
+            break;
+        case ECmdSendReceive:
+            {
+            RDebug::Print(_L("CStifTFwIfProt::ParseCmdResponseL ECmdSendReceive"));
+            // Parse sendreceive response status
+            ret = iItem->GetNextString( tmp );
+            if( ret != KErrNone )
+                {
+                ERROR( _L("No run response status given") );        
+                User::Leave( KErrNotFound );
+                }
+            
+            tmpRunStatus = Parse( tmp, RunStatus );
+            if( tmpRunStatus < 0 )
+                {
+                ERROR( _L("Invalid run status in response given") );        
+                User::Leave( KErrArgument );
+                }
+            else
+            	{
+            	iRunStatus = (TRunStatus) tmpRunStatus;
+            	}
+            break;
+            }
+        default:
+            ERROR( _L("Invalid command response") );        
+            User::Leave( KErrArgument );
+        
+        }      
+    }
+    
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: MsgType
+
+     Description: Returns a string desrciptor corresponding 
+        to message type number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::MsgType( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"reserve",
+        (TText*)L"release",
+        (TText*)L"remote",
+        (TText*)L"response",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: ResultCategory
+
+     Description: Returns a string desrciptor corresponding 
+        to result category number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::CmdType( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"run",
+        (TText*)L"pause",
+        (TText*)L"resume",
+        (TText*)L"cancel",
+        (TText*)L"request",
+        (TText*)L"release",
+        (TText*)L"sendreceive",
+        (TText*)L"set",
+        (TText*)L"unset",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: RemoteType
+
+     Description: Returns a string desrciptor corresponding 
+        to remote type number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::RemoteType( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"phone",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: RunParams
+
+     Description: Returns a string desrciptor corresponding 
+        to run parameter number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::RunParams( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"module",
+        (TText*)L"inifile",
+        (TText*)L"testcasefile",
+        (TText*)L"testcasenum",
+        (TText*)L"title",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+  
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: RunStatus
+
+     Description: Returns a string desrciptor corresponding 
+        to run status number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::RunStatus( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"started",
+        (TText*)L"error",
+        (TText*)L"ready",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: RunStatusParams
+
+     Description: Returns a string desrciptor corresponding 
+        to run status parameter number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::RunStatusParams( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"result",
+        (TText*)L"category",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: ResultCategory
+
+     Description: Returns a string desrciptor corresponding 
+        to command type number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::ResultCategory( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"normal",
+        (TText*)L"panic",
+        (TText*)L"exception",
+        (TText*)L"timeout",
+        (TText*)L"leave",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: EventStatus
+
+     Description: Returns a string desrciptor corresponding 
+        to command type number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::EventStatus( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"active",
+        (TText*)L"set",
+        (TText*)L"error",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: EventStatusParams
+
+     Description: Returns a string desrciptor corresponding 
+        to command type number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::EventStatusParams( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"result",
+        (TText*)L"type",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: EventType
+
+     Description: Returns a string desrciptor corresponding 
+        to event type number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::EventType( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"indication",
+        (TText*)L"state",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: RespParam
+
+     Description: Returns a string desrciptor corresponding 
+        to response parameter number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TPtrC CStifTFwIfProt::RespParam( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"result",
+        };
+    
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+    
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: SetSrcId
+
+     Description: Set protocol source identifier.
+
+     Parameters: TUint32 aSrcId: in: source identifier
+     
+     Return Values: Symbian OS error code
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIfProt::SetSrcId( TUint32 aSrcId )
+    {
+    
+    iSrcId = aSrcId;
+    return AppendId( iSrcId );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: SetDstId
+
+     Description: Set protocol destination identifier.
+
+     Parameters: TUint32 aDstId: in: destination identifier
+     
+     Return Values: Symbian OS error code
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CStifTFwIfProt::SetDstId( TUint32 aDstId )
+    {
+    
+    iDstId = aDstId;
+    return AppendId( iDstId );
+    
+    }
+    
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: SetMsgType
+
+     Description: Set message type.
+
+     Parameters: TMsgType iMsgType: in: message type
+     
+     Return Values: Symbian OS error code
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CStifTFwIfProt::SetMsgType( TMsgType aMsgType )
+    {
+    
+    iMsgType = aMsgType;
+    return Append( CStifTFwIfProt::MsgType, iMsgType );
+    
+    }
+    
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: SetRespType
+
+     Description: Set response type.
+
+     Parameters:    TMsgType iMsgType : in: set response type
+     
+     Return Values: Symbian OS error code
+     
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/ 
+EXPORT_C TInt CStifTFwIfProt::SetRespType( TMsgType aRespType )
+    {
+    
+    iRespType = aRespType;
+    return Append( CStifTFwIfProt::MsgType, iRespType );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: SetCmdType
+
+     Description: Set command type.
+
+     Parameters: TCmdType iCmdType: in: command type
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CStifTFwIfProt::SetCmdType( TCmdType aCmdType )
+    {
+    
+    iCmdType = aCmdType;
+    return Append( CStifTFwIfProt::CmdType, iCmdType );
+    
+    }
+
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: Parse
+
+     Description: Returns a keyword enum corresponding to keyword 
+                  string descriptor.
+
+     Parameters:    TPtrC aKeyword: in: keyword descriptor.
+                    KeywordFunc aFunc: in: Function pointer to keyword parser 
+     
+     Return Values: TInt: keyword index
+                    KErrNotFound: Keyword does not exists
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+------------------------------------------------------------------------------
+*/
+TInt CStifTFwIfProt::Parse( TDesC& aKeyword, KeywordFunc aFunc )
+    {
+    TInt ind;
+    for( ind = 0; aFunc( ind ).Length() > 0; ind++ )
+        {
+        if( aFunc( ind ) == aKeyword )
+            {
+            return ind;
+            }
+        }
+    return KErrNotFound;
+    };
+    
+    
+    /*
+-------------------------------------------------------------------------------
+
+     Class: CStifTFwIfProt
+
+     Method: ParseOptArgL
+
+     Description: Parses optional argument 
+  
+     Parameters: const TDesC& aOptArg: in: 
+                    argument-value pair (format arg=value)
+                 TPtrC& aArg: out: parsed argument  
+                 TPtrC& aVal: out: parsed value
+     
+     Return Values: KErrNone: Everything ok
+                    Symbian OS error code: Not a valid optarg
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CStifTFwIfProt::ParseOptArg( const TDesC& aOptArg, 
+                                   TPtrC& aArg, 
+                                   TPtrC& aVal )
+    { 
+    TInt length = aOptArg.Length();
+    for( TInt i=0; i < length; i++) 
+        {
+        // find the '=' sign 
+        if( aOptArg[i] == '=' )
+            {
+            if( i+1 >= length )
+                {
+                return KErrArgument;
+                }
+            aArg.Set( aOptArg.Left( i ) );
+            aVal.Set( aOptArg.Mid( i+1 ) );
+            DEBUG3(  _L( "arg '%S', val '%S'" ),
+                &aArg, &aVal );        
+            return KErrNone;
+            }
+        }
+    return KErrArgument;
+    
+    }     
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/src/TestInterface.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,620 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains TestInterface implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32std.h>
+#include "StifTestInterface.h"
+#include "TestServerModuleIf.h"
+#include "StifTestModule.h"
+#include <stifinternal/TestServerClient.h>
+//#include <bautils.h>
+#include "version.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: StifDriveLetters
+
+    Description: This defines drive letters that is available in STIF TF.
+
+    Parameters: TInt aDriveNumber: in: Number to indicate drive letter
+                TInt& aCount: inout: Counts of drives that is available
+
+    Return Values: const TChar: Returns a drive letter that is select by
+                   aDriveNumber
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+//@spe
+/*
+EXPORT_C const TChar StifDriveLetters( TInt aDriveNumber, TInt& aCount )
+    {
+    static TChar* const EStifDriveLetters[] =
+        {
+        ( TChar* )L"a",
+        ( TChar* )L"b",
+        ( TChar* )L"c",
+        ( TChar* )L"d",
+        ( TChar* )L"e",
+        ( TChar* )L"f",
+        ( TChar* )L"g",
+        ( TChar* )L"h",
+        ( TChar* )L"i",
+        ( TChar* )L"j",
+        ( TChar* )L"k",
+        ( TChar* )L"l",
+        ( TChar* )L"m",
+        ( TChar* )L"n",
+        ( TChar* )L"o",
+        ( TChar* )L"p",
+        ( TChar* )L"q",
+        ( TChar* )L"r",
+        ( TChar* )L"s",
+        ( TChar* )L"t",
+        ( TChar* )L"u",
+        ( TChar* )L"v",
+        ( TChar* )L"w",
+        ( TChar* )L"x",
+        ( TChar* )L"y",
+        ( TChar* )L"z",
+        };
+    aCount = (sizeof( EStifDriveLetters )/sizeof(TChar*));
+    return TChar( *EStifDriveLetters[aDriveNumber] );
+
+    }
+*/
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TTestCaseInfo class 
+    member function.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TTestCaseInfo
+
+    Method: TTestCaseInfo
+
+    Description: This method is the constructor of class TTestCaseInfo.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TTestCaseInfo::TTestCaseInfo() 
+    {
+    iCaseNumber = -1;
+    iTitle.Zero();
+    iTimeout = 0;
+    iPriority = EPriorityNormal;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TTestInfo class 
+    member function.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TTestInfo
+
+    Method: TTestInfo
+
+    Description: This method is the constructor of class TTestInfo.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TTestInfo::TTestInfo()
+    {
+
+    iModuleName.Zero();
+    iConfig.Zero();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TTestResult class 
+    member function.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TTestResult
+
+    Method: TTestResult
+
+    Description: This method is the constructor of class TTestResult.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TTestResult::TTestResult()
+    {
+    iResult = 0;
+    iResultDes.Zero();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TTestResult
+
+    Method: TTestResult
+
+    Description: Sets result and result description of the test case.
+    
+    Parameters: TInt aResultCode: in: Symbian error code
+                const TResultDes& aResultDes: in: Result description of the
+                test case
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void TTestResult::SetResult( TInt aResultCode,
+                                        const TDesC& aResultDes )
+    {
+    iResult = aResultCode;
+    // If description is too length then cut.
+    if( aResultDes.Length() > KStifMaxResultDes )
+        {
+        iResultDes = aResultDes.Left( KStifMaxResultDes );
+        }
+    else
+        {
+        iResultDes = aResultDes;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TFullTestResult class 
+    member function.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TFullTestResult
+
+    Method: TFullTestResult
+
+    Description: This method is the constructor of class TFullTestResult.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TFullTestResult::TFullTestResult():
+    iStartTime( 0 ),
+    iEndTime( 0 )
+    {    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TTestProgress class 
+    member function.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TTestProgress
+
+    Method: TTestProgress
+
+    Description: This method is the constructor of class TTestProgress.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TTestProgress::TTestProgress()
+    {
+    iPosition = 0;
+    iDescription.Zero();
+    iText.Zero();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TErrorNotification class 
+    member function.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TErrorNotification
+
+    Method: TErrorNotification
+
+    Description: This method is the constructor of class TTestProgress.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TErrorNotification::TErrorNotification()
+    {
+    iPriority = 0;
+    iModule.Zero();
+    iText.Zero();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: StartSession
+
+    Description: This works and used only in EKA2 environment and used from
+                 STIF TestFramework internally.
+                 Executable module uses defined capabilities(PlatSec's
+                 Capability model) to start session. Function for starting
+                 the TestServer and Testmodule/TestClass.
+    
+                 Starts a new server. Server will be running its own
+                 thread and this functions returns when server is up and
+                 running or server start-up fails.
+
+    Parameters: None
+    
+    Return Values: TInt Error code / KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt StartSession()
+    {
+    //__UHEAP_MARK;
+
+    // Get module name from command line
+	const TInt length = User::CommandLineLength();
+    HBufC* cmdLine = HBufC::New( length );
+    
+    if ( cmdLine == NULL )
+        {
+        //__UHEAP_MARKEND;
+        return KErrNoMemory;
+        }
+
+    TPtr moduleName = cmdLine->Des();
+    User::CommandLine( moduleName );
+
+    RDebug::Print(_L("StartSession() Received data [%S]"), &moduleName);
+
+    // Extract semaphore name passed in data    
+    TInt index = moduleName.Find(_L(" "));
+    RDebug::Print(_L("StartSession() Space separator found at position [%d]"), index);
+    TPtrC semaphoreName = moduleName.Mid(index + 1);
+    moduleName = moduleName.Left(index);
+
+    RDebug::Print(_L("StartSession() Extracted module name [%S] and sempahore name [%S]"), &moduleName, &semaphoreName);
+   
+    // Open start-up synchronization semaphore
+    RSemaphore startup;
+    RDebug::Print(_L(" Opening start-up semaphore"));
+//    TName semaphoreName = _L("startupSemaphore");
+//    semaphoreName.Append( moduleName );
+    
+    TInt res = startup.OpenGlobal(semaphoreName);
+    RDebug::Print(_L("Opening result %d"), res);    
+
+
+    TFileName serverName;
+    TInt r = StartNewServer ( moduleName, serverName, EFalse, startup);    
+
+    if ( r ==   KErrAlreadyExists )
+        {        
+        // Ok, server was already started
+        RDebug::Print(_L("Server already started, signaling semaphore and exiting"));
+        startup.Signal();        
+        //__UHEAP_MARKEND;
+        
+        delete cmdLine;
+        
+        return KErrNone;
+        }
+    else
+        {       
+        RDebug::Print(_L("Server is finished, code %d"), r);
+        }
+
+    //__UHEAP_MARKEND;
+
+	// Program execution never comes here, because StartNewServer doesn't return
+	// unless server is already started.
+	
+    delete cmdLine;
+    
+    // Return start-up result.
+    return r;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TStifUtil
+
+    Method: CorrectFilePath
+
+    Description: Checks if file path contains drive letter. If not file is serched
+                 on all drives and first hit is added to file name.
+
+    Parameters: TDes& aFilePath: in/out: file path to correct
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void TStifUtil::CorrectFilePathL( TDes& aFilePath )
+	{
+	_LIT( KDriveSelector, ":\\" );
+	_LIT( KDriveSelectorFormat_1, "%c:" );                                                                  
+	_LIT( KDriveSelectorFormat_2, "%c:\\" );                                                                
+	TChar KDriveZ = EDriveZ;//'Z';                                                                          
+	                                                                                                              
+	_LIT( KBackslash, "\\" );                                                                              
+	                                                                                                                
+	TInt length = aFilePath.Length();                                                                      
+	                                                                                                                
+	if (length == 0 )                                                                                     
+	   {                                                                                                  
+	   return;                                                                                            
+	   }                                                                                                  
+	if (length > 2 )                                                                                      
+	   {                                                                                                  
+	   // Check if file path contains drive selector                                                      
+	   if ( aFilePath.Mid( 1, 2 ) == KDriveSelector )                                                     
+	       {                                                                                               
+	       // File path contains selector letter so we have nothing to do here                             
+	       return;                                                                                         
+	       }                                                                                               
+	   }                                                                                                  
+	                                                                                                                
+	// Check if file path contains backslash at the begining and                                          
+	// select proper drive selector format according to this information                                  
+	TInt driveSelectorFormat = 2;                                                                         
+	if ( aFilePath.Mid( 0, 1 ) == KBackslash )                                                            
+	   {                                                                                               
+	   driveSelectorFormat = 1;                                                                        
+	   }                                                                                               
+	                                                                                                                
+	RFs rfs;                                                                                              
+	if ( rfs.Connect() != KErrNone )                                                                      
+	   {                                                                                                  
+	   return;                                                                                            
+	   }                                                                                                  
+	                                                                                                                
+	// Get available drives list, revers it order and move z drive at                                     
+	// the end of the list.  
+	TDriveList drivesList; 
+	rfs.DriveList(drivesList); 
+
+	// Set drive variable to last drive (except for Z, which will be checked at the end)
+	char drive = 'Y' ;
+
+	// Loop through all the drives in following order: YX..CBAZ
+	while(drive >= 'A' && drive <= 'Z')
+	     {
+	     // Do further action only if drive exists
+	     TInt driveint;
+	     rfs.CharToDrive(drive, driveint);
+	     if(drivesList[driveint])
+	          {
+	          //further checking (drive selector and file existence)
+	          
+	          // Prepare drive selector                                                                         
+	          TBuf<3> driveSelector;                                                                            
+	          if ( driveSelectorFormat == 1 )                                                                   
+	              {                                                                                           
+	              driveSelector.Format( KDriveSelectorFormat_1, drive );                                    
+	              }                                                                                           
+	          else if ( driveSelectorFormat == 2 )                                                              
+	              {                                                                                           
+	              driveSelector.Format( KDriveSelectorFormat_2, drive );                                    
+	              }                                                                                           
+	                                                                                                                
+	          aFilePath.Insert( 0, driveSelector );                                                             
+	                                                                                                                
+	          TEntry entry;                                                                                     
+	          if ( rfs.Entry(aFilePath, entry) == KErrNone )                                                    
+	              {                                                                                         
+	              rfs.Close();                                                                                
+	              return;                                                                                     
+	              }                                                                                           
+	                                                                                                                
+	          // File does not exists on selected drive. Restoring orginal file path                            
+	          aFilePath.Delete( 0, driveSelector.Length() );    	         
+	          }//if(drivesList[driveint])       
+	            
+	   // Select next drive
+	   if(drive == 'Z')
+	       break; // the last driver
+	   else if(drive ==  'A' )
+	       drive = 'Z'; //after checking A check Z
+	   else
+	       drive =  (TChar)(TInt(drive)-1) ; //after checking Y check X and so on in reverse alphabetical order
+	   } //while 
+	rfs.Close(); 
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TStifUtil
+
+    Method: STIFVersion
+
+    Description: Method used to retrieve version of STIF by both STIF and STIF UI 
+
+    Parameters: TInt& aMajorV - parameter used to pass major STIF version
+     			TInt& aMinorV - parameter used to pass minor STIF version
+     			TInt& aBuildV - parameter used to pass build version of STIF
+     			TDes& aRelDate - parameter used to pass information about release date
+
+    Return Values: None
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void TStifUtil::STIFVersion(TInt& aMajorV, TInt& aMinorV, TInt& aBuildV, TDes& aRelDate)
+	{
+	aMajorV = STIF_MAJOR_VERSION;
+	aMinorV = STIF_MINOR_VERSION;
+	aBuildV = STIF_BUILD_VERSION;
+	aRelDate = TO_UNICODE(STIF_REL_DATE);
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/src/TestModuleIf.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1746 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains TestModuleIf implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include "StifTFwIfProt.h"
+#include "StifTestInterface.h"
+#include "TestServerModuleIf.h"
+#include "StifTestModule.h"
+#include "TestThreadContainer.h"
+#include "STIFMeasurement.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// Debugging is enabled with next define
+#define __TRACING_ENABLED
+#ifdef __TRACING_ENABLED
+#define __RDEBUG(p) RDebug::Print p 
+#else
+#define __RDEBUG(p)
+#endif
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    TDesOverflowHandler class contains a simple overflow handler implementation.
+
+-------------------------------------------------------------------------------
+*/
+class TDesOverflowHandler : public TDes16Overflow
+    {
+    public:
+        TDesOverflowHandler( CTestModuleIf* aModuleIf, 
+                             const TInt aPriority, 
+                             const TDesC& aDefinition)
+            {
+            iModuleIf = aModuleIf;
+            iPriority = aPriority;
+            iDefinition = aDefinition;
+            }
+
+        void Overflow(TDes16& /*aDes*/ )
+            { 
+            }
+    
+        CTestModuleIf* iModuleIf;
+        TInt iPriority;
+        TStifInfoName iDefinition;
+    };
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CTestModuleIf class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: CTestModuleIf
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters: None
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTestModuleIf::CTestModuleIf( CTestThreadContainer* aTestExecution ) :
+    iTestExecution( aTestExecution )
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: CTestExecution* aTestExecution: in: Pointer to TestExecution
+                CTestModuleBase* aTestModule: in: Pointer to TestModule
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModuleIf::ConstructL( CTestModuleBase* aTestModule )
+    {
+
+    if ( aTestModule->iTestModuleIf != NULL)
+        {
+        delete aTestModule->iTestModuleIf;
+        aTestModule->iTestModuleIf = NULL;
+        }
+    aTestModule->iTestModuleIf = this; 
+
+    iIsRebootReady = EFalse;
+    iStoreStateCounter = 0;
+
+    // Used to "resets" iTestCaseResults array
+    iAllowTestCaseResultsCount = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestExecution* aTestExecution: in: Pointer to TestExecution
+                CTestModuleBase* aTestModule: in: Pointer to TestModule
+    
+    Return Values: CTestModuleIf object.
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestModuleIf* CTestModuleIf::NewL( CTestThreadContainer* aExecutionSession, 
+                                             CTestModuleBase* aTestModule )
+    {
+
+    CTestModuleIf* self = 
+        new (ELeave) CTestModuleIf( aExecutionSession );
+    
+    CleanupStack::PushL( self );
+    self->ConstructL( aTestModule );
+
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: ~CTestModuleIf
+
+    Description: Destructor
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+    
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/    
+CTestModuleIf::~CTestModuleIf()
+    {
+    iTestExecution = NULL;
+
+    // Used to "resets" iTestCaseResults array
+    iAllowTestCaseResultsCount = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: Printf
+
+    Description: Printing
+
+    Printf is used to provide different information up to the UI 
+    that can be then printed e.g. to the Console Screen. 
+    The priority can be used in the UI to decide if the information 
+    received from the Test DLL will be discarded or not in 
+    the different performance situations. The priority is also 
+    used in the Test DLL server and in the Test Engine to queue 
+    the Printf responses.
+    This method is implemented in Test DLL Server and the Test DLL 
+    can call it to provide printable information to the UI.
+
+    Parameters:  const TInt aPriority: in: 
+                    Importance of the returned information
+                 const TDesC& aDefinition: in: 
+                    Definition of data to be printed 
+                 TRefByValue<const TDesC> aFmt: in: Printed data
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CTestModuleIf::Printf( const TInt aPriority, 
+                                     const TDesC& aDefinition, 
+                                     TRefByValue<const TDesC> aFmt,
+                                     ... 
+                                   )
+    {           
+
+    if( !IsServerAlive() )
+        {
+        return;
+        }
+
+    VA_LIST list;
+    VA_START(list,aFmt);
+    TName aBuf;
+    RBuf buf;
+    TInt ret = buf.Create(1024);
+    if(ret != KErrNone)
+        {
+        __RDEBUG((_L("STF: Printf: Buffer creation failed [%d]"), ret));
+        return;
+        }
+
+    // Cut the description length
+    TInt len = aDefinition.Length();
+    if ( len > KMaxInfoName )
+        {
+        len = KMaxInfoName;
+        }
+
+    TStifInfoName shortDescription = aDefinition.Left(len);
+
+    // Create overflow handler
+    TDesOverflowHandler overFlowHandler (this, aPriority, shortDescription);
+
+    // Parse parameters
+    buf.AppendFormatList(aFmt, list, &overFlowHandler);
+    
+    if(buf.Length() == 0)
+        {
+        __RDEBUG((_L("STF: Printf: Unable to prepare print buffer (probably printed string is too long)")));
+        }
+
+    // Print
+    aBuf.Copy(buf.Left(aBuf.MaxLength()));
+    buf.Close();
+
+    iTestExecution->DoNotifyPrint( aPriority, shortDescription, aBuf );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: Event
+
+    Description: Event control.
+
+    Event function is used to control and use the event system. 
+    TEventIf &aEvent encapsulates the request type and 
+    the event name, see StifTestEventInterface.h for more information.
+    This method is implemented in Test DLL Server and the Test DLL 
+    can call it to control the event system.
+  
+    Parameters: TEventIf& aEvent: in: Event command
+    
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TInt CTestModuleIf::Event( TEventIf& aEvent )
+    {
+
+    if( !IsServerAlive() )
+        {
+        return KErrGeneral;
+        }
+
+    // All event commands are handled in testserver and testengine
+    return iTestExecution->DoNotifyEvent( aEvent );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: Event
+
+    Description: Event control.
+
+    Asynchronous version of event control function.
+    It is used to control and use the event system asynchronously. 
+    TEventIf &aEvent encapsulates the request type and 
+    the event number, see StifTestEventInterface.h for more information.
+    This method is implemented in Test DLL Server and the Test DLL 
+    can call it to control the event system.
+  
+    Parameters: TEventIf& aEvent: in: Event command
+                TRequestStatus& aStatus: in: Request status parameter
+
+    Return Values: None. 
+    
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C void CTestModuleIf::Event( TEventIf& aEvent, TRequestStatus& aStatus )
+    {
+    TInt ret = KErrNone;
+
+    if( !IsServerAlive() )
+        {
+        __RDEBUG( (_L("iTestExecution not initialised")));
+        ret = KErrGeneral;
+        }
+    else
+        {        
+        aStatus = KRequestPending;
+
+        // All event commands are handled in testserver and testengine
+        ret = iTestExecution->DoNotifyEvent( aEvent, &aStatus );
+        }
+    if( ret != KErrNone )
+        {
+        TRequestStatus* rs = &aStatus;
+        User::RequestComplete( rs, ret );
+        }
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: CancelEvent
+
+    Description: Cancel asynchronous event control call.
+  
+    Parameters: TEventIf& aEvent: in: Event command to be cancelled.
+                const TRequestStatus* aStatus: in: 
+                    Pointer to TRequestStatus parameter that is cancelled
+
+    Return Values: Symbian OS error code.
+    
+    Errors/Exceptions: None
+    
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C TInt CTestModuleIf::CancelEvent( TEventIf& aEvent,
+                                          TRequestStatus* aStatus )
+    {
+     if( !IsServerAlive() )
+        {
+        __RDEBUG( (_L("iTestExecution not initialised")));
+        return KErrGeneral;
+        }
+
+    // All event commands are handled in testserver and testengine
+    iTestExecution->CancelEvent( aEvent, aStatus );
+    
+    return KErrNone;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: SetExitReason
+
+    Description: Set exit reason
+  
+    Parameters: const TExitReason aExitReason in: Exit reason
+                const TInt aExitCode in: Exit code
+
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/      
+EXPORT_C void CTestModuleIf::SetExitReason( const CTestModuleIf::TExitReason aExitReason, 
+                                            const TInt aExitCode )
+        
+    {
+
+     if( !IsServerAlive() )
+        {
+        __RDEBUG( (_L("iTestExecution not initialised")));
+        return;
+        }
+    
+    iTestExecution->SetExitReason( aExitReason, aExitCode );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: RemoteSend
+
+    Description: RemoteSend is used to send control protocol messages to slaves
+        (e.g. another phone, call box, ...). 
+    
+    Parameters:  const TDesC& aRemoteMsg: in: 
+                    Remote command protocol message 
+                 
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::RemoteSend( const TDesC& aRemoteMsg )
+    {           
+
+    if( !IsServerAlive() )
+        {
+        __RDEBUG( ( _L("iTestExecution not initialised") ) );
+        return KErrNotReady;
+        }
+
+    TParams params;
+    params.aRemoteMsgConstRef = &aRemoteMsg;
+
+    TRequestStatus status = KRequestPending; 
+
+    // Forward
+    iTestExecution->DoRemoteReceive( EStifCmdSend, params, 
+                                     aRemoteMsg.Length(), status );
+    
+    User::WaitForRequest( status );
+
+    return status.Int();
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: RemoteReceive
+
+    Description: RemoteReceive is used to receive control protocol messages to 
+        slaves (e.g. another phone, call box, ...). 
+    
+    Parameters:  const TDesC& aRemoteMsg: in: 
+                    Remote command protocol message 
+                 TRequestStatus& aStatus: in: Request status parameter
+
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CTestModuleIf::RemoteReceive( TDes& aRemoteMsg, 
+                                            TRequestStatus& aStatus )
+    {           
+    aStatus = KRequestPending;
+    if( !IsServerAlive() )
+        {
+        __RDEBUG( ( _L("iTestExecution not initialised") ) );
+        TRequestStatus* rs = &aStatus;
+        User::RequestComplete( rs, KErrNotReady );
+        }
+
+    TParams params;
+    params.aRemoteMsgRef = &aRemoteMsg;
+
+    iTestExecution->DoRemoteReceive( EStifCmdReceive, params, 
+                                     aRemoteMsg.Length(), aStatus );
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: RemoteReceiveCancel
+
+    Description: RemoteReceiveCancel is used to cancel RemoteReceive.
+     
+    Parameters:  None
+    
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CTestModuleIf::RemoteReceiveCancel()
+    {           
+    if( !IsServerAlive() )
+        {
+        __RDEBUG( ( _L("iTestExecution not initialised") ) );
+        return;
+        }
+
+    // Forward
+    iTestExecution->DoRemoteReceiveCancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: Reboot
+
+    Description: Start a reboot operation.
+
+    Parameters: TInt aType: in: Reboot type
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: KErrNotReady returned if iTestExecution is NULL.
+                       KErrNotReady returned if reboot not allowed(Store state
+                       not called).
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::Reboot( TInt aType )
+    {           
+    if ( !IsServerAlive() )
+        {
+        __RDEBUG( ( _L( "iTestExecution not initialised" ) ) );
+        return KErrNotReady;
+        }
+    if( !iIsRebootReady )
+        {
+        __RDEBUG( ( _L( "Reboot operation not ready" ) ) );
+        return KErrNotReady;
+        }
+     
+/*    switch( aType )
+        {
+        case EDefaultReset:
+            __RDEBUG( ( _L( "Reboot, type default" )) );
+            break;
+        case EKernelReset:
+            __RDEBUG( ( _L( "Reboot, type KernelReset" )) );
+            break;
+        case EDeviceReset0:
+            __RDEBUG( ( _L( "Reboot, type Reset 0" )) );
+            break;
+        case EDeviceReset1:
+            __RDEBUG( ( _L( "Reboot, type Reset 1" )) );
+            break;
+        case EDeviceReset2:
+            __RDEBUG( ( _L( "Reboot, type Reset 2" )) );
+            break;
+        case EDeviceReset3:
+            __RDEBUG( ( _L( "Reboot, type Reset 3" )) );
+            break;
+        case EDeviceReset4:
+            __RDEBUG( ( _L( "Reboot, type Reset 4" )) );
+            break;
+        case EDeviceReset5:
+            __RDEBUG( ( _L( "Reboot, type Reset 5" )) );
+            break;
+        default:
+            __RDEBUG( ( _L( "Reboot type %d not supported" ), aType ) );
+            return KErrNotSupported;    
+        }
+*/
+
+    TParams params;
+    TRebootParams rebootParams;
+    
+    params.aRebootType = &rebootParams;
+    rebootParams.aType = ( TRebootType )aType;
+    
+    TRequestStatus status = KRequestPending; 
+
+    // Forward
+    iTestExecution->DoRemoteReceive( EStifCmdReboot, params, sizeof( aType ), status );
+    
+    User::WaitForRequest( status );
+
+    return status.Int();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: StoreState
+
+    Description: Stores the current state before reboot.
+
+    Parameters: TInt aCode: in: Reboot releated integer value.
+                TName& aName: in: Reboot related string value.
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: KErrNotReady returned if iTestExecution is NULL.
+                       KErrOverflow returned if aName length is over TName.
+                       KErrInUse returned if method is called more than once.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::StoreState( TInt aCode, TName& aName )
+    {
+    iStoreStateCounter++;   // Store state counter
+
+    if ( !IsServerAlive() )
+        {
+        __RDEBUG( ( _L( "iTestExecution not initialised" ) ) );
+        return KErrNotReady;
+        }
+    // Check aName length
+    if ( aName.Length() > KMaxName )
+        {
+        __RDEBUG( ( _L( "CTestModuleIf::StoreState(): aName length is not valid" ) ) );
+        return KErrOverflow;
+        }
+    // Only one store state call may be done
+    if( iStoreStateCounter > 1 )
+        {
+        __RDEBUG( ( _L( "Store state allready called" ) ) );
+        return KErrInUse;
+        }
+
+    TParams params;
+    TRebootStateParams rebootStateParams;
+    params.aRebootState = &rebootStateParams;
+    rebootStateParams.aCode = aCode;
+    rebootStateParams.aName = aName;
+
+    TRequestStatus status = KRequestPending; 
+
+    // Forward
+    iTestExecution->DoRemoteReceive( EStifCmdStoreState, params,
+                                     sizeof( TRebootStateParams), status );
+    
+    User::WaitForRequest( status );
+
+    // If store state is done successfully reboot operation is allowed
+    if( status.Int() == KErrNone )
+        {
+        iIsRebootReady = ETrue;
+        }
+
+    return status.Int();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: GetStoredState
+
+    Description: Get saved store information after the reboot.
+
+    Parameters: TInt aCode: inout: Get reboot releated integer value.
+                TName& aName: inout: Get reboot related string value.
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: KErrNotReady returned if iTestExecution is NULL.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::GetStoredState( TInt& aCode, TName& aName )
+    {           
+    if( !IsServerAlive() )
+        {
+        __RDEBUG( ( _L( "iTestExecution not initialised" ) ) );
+        return KErrNotReady;
+        }
+
+    TInt code;
+    TName name;
+    
+    TParams params;
+    TGetRebootStoredParamsRef getRebootStoredParamsRef( code, name );
+    
+    params.aRebootStoredRef = &getRebootStoredParamsRef;
+
+    TRequestStatus status = KRequestPending; 
+
+    // Forward
+    iTestExecution->DoRemoteReceive( EStifCmdGetStoredState, params,
+                                     sizeof( TRebootStateParams), status );
+    
+    User::WaitForRequest( status );
+
+    // Return results if getting state is done without error
+    if(status.Int() == KErrNone)
+        {
+        aCode = code;
+        aName = name;
+        }
+
+    return status.Int();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: SetBehavior
+
+    Description: Set test case behavior.
+
+    Parameters: TInt aCode: inout: Get reboot releated integer value.
+                TName& aName: inout: Get reboot related string value.
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: KErrNotReady returned if iTestExecution is NULL.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::SetBehavior( TTestBehavior aType, TAny* aPtr )
+    {         
+    
+    if( !IsServerAlive() )
+        {
+        return KErrGeneral;
+        }
+
+    // All event commands are handled in testserver and testengine
+    return iTestExecution->SetBehavior( aType, aPtr );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: StifMacroError
+
+    Description: STIF TF's macros. Saves information for later use.
+
+    Parameters: TInt aMacroType: in: Macro type(0:TL, 1:T1L, 2:T2L, etc.)
+                const TText8* aFile: in: Uses __FILE__ macro and this includes
+                path and file name. Maximun length for this is
+                KStifMacroMaxFile. If length is more then cutted from left.
+                char* aFunction: in: Uses __FUNCTION__ macro and this includes
+                function name. Maximun length for this is
+                KStifMacroMaxFunction. If length is more then cutted from
+                rigth.
+                TInt aLine: in: Uses __LINE__ macro and includes line number.
+                TInt aResult: in: Result from called operations.
+                TInt aExpected1: in: Users expected result.
+                TInt aExpected2: in: Users expected result.
+                TInt aExpected3: in: Users expected result.
+                TInt aExpected4: in: Users expected result.
+                TInt aExpected5: in: Users expected result.
+
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::StifMacroError( TInt aMacroType, 
+                                             const TText8* aFile,
+                                             const char* aFunction,
+                                             TInt aLine,
+                                             TInt aResult,
+                                             TInt aExpected1,
+                                             TInt aExpected2,
+                                             TInt aExpected3,
+                                             TInt aExpected4,
+                                             TInt aExpected5 )
+    {
+    if( !IsServerAlive() )
+        {
+        return KErrGeneral;
+        }
+
+    return iTestExecution->StifMacroError( aMacroType, aFile,
+                                           aFunction, aLine,
+                                           aResult, aExpected1,
+                                           aExpected2, aExpected3,
+                                           aExpected4, aExpected5 );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: ServerAlive
+
+    Description: Get saved store information after the reboot.
+
+    Parameters: TInt aCode: inout: Get reboot releated integer value.
+                TName& aName: inout: Get reboot related string value.
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: KErrNotReady returned if iTestExecution is NULL.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestModuleIf::IsServerAlive()
+    {
+    
+    if( iTestExecution == NULL )
+        {
+        __RDEBUG( ( _L( "iTestExecution not initialised" ) ) );
+        // Execution not initialized
+        return EFalse;
+        }
+       
+    return ETrue;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: AddInterferenceThread
+
+    Description: 
+
+    Parameters: RThread aSTIFTestInterference: in: Handle to RThread
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: 
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleIf::AddInterferenceThread( RThread aSTIFTestInterference )
+    {
+    // Add thread to Array. Via array can handle test interference thread's
+    // kill in panic etc. cases
+    return iTestExecution->AddInterferenceThread( aSTIFTestInterference );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: RemoveInterferenceThread
+
+    Description: 
+
+    Parameters: RThread aSTIFTestInterference: in: Handle to RThread
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: 
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleIf::RemoveInterferenceThread( RThread aSTIFTestInterference )
+    {
+    // Remove thread from Array.Test interference thread is stopped and killed
+    // successfully
+    return iTestExecution->RemoveInterferenceThread( aSTIFTestInterference );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: HandleMeasurementProcess
+
+    Description: With this can be stored information about test measurement
+                 to TestServer space.
+
+    Parameters: RProcess aTestMeasurement: in: Handle to RProcess
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleIf::HandleMeasurementProcess( 
+            CSTIFTestMeasurement::TStifMeasurementStruct aSTIFMeasurementInfo )
+    {
+    // Add process to Array. Via array can handle test measurement process's
+    // kill in panic etc. cases
+    return iTestExecution->HandleMeasurementProcess( aSTIFMeasurementInfo );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: GetMeasurementOptions
+
+    Description: Get measurement option(s) given from initialization file etc.
+
+    Parameters: TInt& aOptions: inout: Get measurement option(s)
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: KErrNotReady returned if iTestExecution is NULL.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::GetMeasurementOptions( TInt& aOptions )
+    {           
+    if( !IsServerAlive() )
+        {
+        __RDEBUG( ( _L( "iTestExecution not initialised" ) ) );
+        return KErrNotReady;
+        }
+
+    TParams params;
+    TGetMeasurementOptionsRef getMeasurementOptionsRef( aOptions );
+    params.aMeasurementOption = &getMeasurementOptionsRef;
+
+    TRequestStatus status = KRequestPending; 
+
+    // Forward
+    iTestExecution->DoRemoteReceive( EStifCmdMeasurement, params,
+                                     sizeof( TGetMeasurementOptions ), status );
+    
+    User::WaitForRequest( status );
+
+    aOptions = getMeasurementOptionsRef.iOptions;
+    
+    return status.Int();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: SetAllowResult
+
+    Description: Use with TAL, TA1L, TA2L, TA3L, TA4L and TA5L macros to allow
+                 results.
+                 Set test case allow result given by user. In TestScripter
+                 cases allow result can set by 'allownextresult' or
+                 'allowerrorcodes' keywords. In Normal and Hardcoded test
+                 modules allow result can be set with this method, reset should
+                 be done with ResetAllowResult method.
+
+    Parameters: TInt aResult: in: Result value to be appended.
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::SetAllowResult( TInt aResult )
+    {
+    for( TInt a = 0; a < iAllowTestCaseResultsCount; a++ )
+        {
+        // Check that result is not given already
+        if ( iTestCaseResults[a] == aResult )
+            {
+            return KErrNone;
+            }
+        }
+    // If values are given more that allow(see KSTIFMacroResultArraySize).
+    // Array starts from 0...9 -> 10 => 10th should fail
+    if( iAllowTestCaseResultsCount >= KSTIFMacroResultArraySize )
+        {
+        __RDEBUG( ( 
+            _L( "STIF macro's SetAllowResult() allow only %d results, fails with %d" ),
+            KSTIFMacroResultArraySize, KErrOverflow  ) );
+        return KErrOverflow;
+        }
+
+    // New result
+    iAllowTestCaseResultsCount++;
+    iTestCaseResults[iAllowTestCaseResultsCount-1] = aResult;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: CheckAllowResult
+
+    Description: This is mainly used by STIF's TAL-TA5L macros internally.
+                 Check is macros result allowed result.
+
+    Parameters: TInt aResult: in: Result value to be checked.
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::CheckAllowResult( TInt aResult )
+    {
+    // Check is result allowed
+    for( TInt a = 0; a < iAllowTestCaseResultsCount; a++ )
+        {
+        if ( iTestCaseResults[a] == aResult )
+            {
+            // Result is allow
+            __RDEBUG( ( _L( "STIF TAL-TA5L macro's result check. Test case result[%d] allowed" ),
+                aResult ) );
+            return KErrNone;
+            }
+        }
+
+    __RDEBUG( ( 
+        _L( "STIF TAL-TA5L macro's result check. Test case result[%d] not allowed" ),
+        aResult ) );
+    // No match with allow result
+    return KErrGeneral;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: ResetAllowResult
+
+    Description: Use with TAL, TA1L, TA2L, TA3L, TA4L and TA5L macros to reset
+                 allowed results.
+                 Reset allow result(s) given with SetAllowResult. In
+                 TestScripter cases this will be called automatically by STIF.
+                 Normal and Hardcoded cases this should be called by user.
+
+    Parameters: None.
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::ResetAllowResult()
+    {
+    // Used to "resets" iTestCaseResults array
+    iAllowTestCaseResultsCount = 0;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: StopExecution
+
+    Description: Causes that test case is going to be cancelled.
+
+    Parameters: None
+
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestModuleIf::StopExecution(TStopExecutionType aType, TInt aCode)
+    {
+
+    //Check parameters
+    if((aType == EOk) && (aCode != KErrNone))
+        {
+        return KErrArgument;
+        }
+    else if((aType != EOk) && (aCode == KErrNone))
+        {
+        return KErrArgument;
+        }
+
+    //Check server
+    if(!IsServerAlive())
+        {
+        return KErrGeneral;
+        }
+
+    //Everything is ok, we can continue with processing command
+    _LIT(KStopExecution, "StopExecution");
+    const TInt KPrintPriority = 30;
+
+    switch(aType)
+        {
+        case EOk:
+            Printf(KPrintPriority, KStopExecution, _L("***Test case PASSED***\n\n"));
+            break;
+        case EFail:
+            Printf(KPrintPriority, KStopExecution, _L("***Test case FAILED***\n\n"));
+            break;
+        case EAbort:
+            Printf(KPrintPriority, KStopExecution, _L("***Test case KILLED***\n\n"));
+            break;
+        default:
+            return KErrNotFound;
+        }
+
+    TStopExecutionCommandParams params;
+    params.iType = aType;
+    params.iCode = aCode;
+    __RDEBUG((_L("CTestModuleIf::StopExecution(): type [%d] code [%d]"), TInt(aType), aCode));
+
+    TStopExecutionCommandParamsPckg pckg(params);
+
+    TInt res = Command(EStopExecution, pckg);
+    return res;
+    }
+
+/*
+------------------------------------------------------------------------------
+
+	Class: CTestModuleIf
+
+    Method: SendTestModuleVersion
+    
+    Description: SendTestModuleVersion method is used to pass version of test module
+    
+------------------------------------------------------------------------------
+ */
+EXPORT_C TInt CTestModuleIf::SendTestModuleVersion(TVersion aVersion, TFileName aModuleName)
+	{
+	if( aModuleName.Length() == 0 )
+		{
+		return KErrArgument;
+		}
+	
+	//Check server
+	if(!IsServerAlive())
+	    {
+	    return KErrGeneral;
+	    }
+	
+	const TInt KPrintPriority = 30;
+	_LIT(KVersion ,"SendTestModuleVersion");
+	Printf(KPrintPriority, KVersion, _L("Sending test module version"));
+	
+	TSendTestModuleVesionCommandParams params;
+	params.iMajor = aVersion.iMajor;
+	params.iMinor = aVersion.iMinor;
+	params.iBuild = aVersion.iBuild;
+	params.iTestModuleName = aModuleName;
+	
+	TSendTestModuleVesionCommandParamsPckg pckg(params);
+	TInt res = Command( ESendTestModuleVersion, pckg );
+	return res;
+	}
+
+
+/*
+------------------------------------------------------------------------------
+
+	Class: CTestModuleIf
+
+    Method: SendTestModuleVersion
+    
+    Description: SendTestModuleVersion method is used to pass version of test module.
+    			This version uses three parameters to enable the overloading of version with
+    			two parameters. The version with two params has params passed by value which
+    			is incorrect. The "old" version (with two parameters) is left here not to cause
+    			binary break. Only this version (with three parameters) should be used.
+    
+------------------------------------------------------------------------------
+ */
+EXPORT_C TInt CTestModuleIf::SendTestModuleVersion(TVersion& aVersion, const TDesC& aModuleName, TBool /*aNewVersion*/)
+	{
+	if( aModuleName.Length() == 0 )
+		{
+		return KErrArgument;
+		}
+	
+	//Check server
+	if(!IsServerAlive())
+	    {
+	    return KErrGeneral;
+	    }
+	
+	const TInt KPrintPriority = 30;
+	_LIT(KVersion ,"SendTestModuleVersion");
+	Printf(KPrintPriority, KVersion, _L("Sending test module version"));
+	
+	TSendTestModuleVesionCommandParams params;
+	params.iMajor = aVersion.iMajor;
+	params.iMinor = aVersion.iMinor;
+	params.iBuild = aVersion.iBuild;
+	params.iTestModuleName = aModuleName;
+	
+	TSendTestModuleVesionCommandParamsPckg pckg(params);
+	TInt res = Command( ESendTestModuleVersion, pckg );
+	return res;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: Command
+
+    Description: Sends specific command to TestServer.
+
+    Parameters: aCommand - command to be send
+
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleIf::Command(TCommand aCommand, const TDesC8& aParamsPckg)
+    {
+    TInt res = KErrNone;
+
+    if( !IsServerAlive() )
+        {
+        return KErrGeneral;
+        }
+
+    switch(aCommand)
+        {
+        case EStopExecution:
+            iTestExecution->DoNotifyCommand(aCommand, aParamsPckg);
+            break;
+        case ESendTestModuleVersion:
+        	iTestExecution->DoNotifyCommand(aCommand, aParamsPckg);
+        	break;
+        default:
+            __RDEBUG((_L("Command [%d] not recognized."), aCommand));
+        }
+
+    return res;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: GetTestCaseTitleL
+
+    Description: Returns title of current test case.
+
+    Parameters: aCommand - command to be send
+
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CTestModuleIf::GetTestCaseTitleL(TDes& aTestCaseTitle)
+    {
+    iTestExecution->GetTestCaseTitleL(aTestCaseTitle);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: GetTestCaseArguments
+
+    Description: Returns test case arguments.
+
+    Parameters: none
+
+    Return Values: test case arguments.
+
+    Errors/Exceptions: None
+
+    Status: proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C const TDesC& CTestModuleIf::GetTestCaseArguments() const
+    {
+    return iTestExecution->GetTestCaseArguments();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: UITesting
+
+    Description: Gets information if it is UI test or not
+
+    Parameters: none
+
+    Return Values: True if it is UI test, in other case it returns false.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TBool CTestModuleIf::UITesting()
+	{
+	return iTestExecution->UITesting();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleIf
+
+    Method: GetUiEnvProxy
+
+    Description: Gets UiEnvProxy
+
+    Parameters: none
+
+    Return Values: Pointer to UiEnvProxy
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CUiEnvProxy* CTestModuleIf::GetUiEnvProxy()
+	{
+	return iTestExecution->GetUiEnvProxy();
+	}
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CSTIFTestMeasurement class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestMeasurement
+
+    Method: CSTIFTestMeasurement
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: CTestModuleBase* aTestModuleBase: in: Pointer to STIF
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFTestMeasurement::CSTIFTestMeasurement( CTestModuleBase* aTestModuleBase ) :
+    iTestModuleBase( aTestModuleBase ),
+    iMeasurementOption( 0 )
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestMeasurement
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: TSTIFMeasurement aType: in: Measurement type
+                const TDesC& aConfigurationInfo: in: Configuration issues
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if HandleMeasurementProcess returns error code
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CSTIFTestMeasurement::ConstructL( TSTIFMeasurementType aType,
+                                    const TDesC& aConfigurationInfo )
+    {
+    // aType into struct here. This is compared to
+    iMeasurementStruct.iMeasurementType = aType;
+
+    // Check that measurement is not disabled(This is given from UI level or
+    // from TestFramework.ini file)
+    TInt ret( 0 );
+    ret = iTestModuleBase->TestModuleIf().GetMeasurementOptions( 
+                                                        iMeasurementOption );
+    if( ret != KErrNone )
+        {
+        __RDEBUG( ( _L( "GetMeasurementOptions() return an error[%d]" ), ret ) );
+        User::Leave( ret );
+        }
+
+    // Check that measurement is not disabled
+    if( ( iMeasurementOption & EDisableAll ) == EDisableAll )
+        {
+        __RDEBUG( _L( "Measurement disable option [KStifMeasurementDisableAll] is given by user" ) );
+        return;
+        }
+    if( ( ( iMeasurementOption & EMeasurement01 ) == EMeasurement01 ) && aType == KStifMeasurementPlugin01 )
+        {
+        __RDEBUG( _L( "Measurement disable option [KStifMeasurement01] is given by user" ) );
+        return;
+        }
+    if( ( ( iMeasurementOption & EMeasurement02 ) == EMeasurement02 ) && aType == KStifMeasurementPlugin02 )
+        {
+        __RDEBUG( _L( "Measurement disable option [KStifMeasurement02] is given by user" ) );
+        return;
+        }
+    if( ( ( iMeasurementOption & EMeasurement03 ) == EMeasurement03 ) && aType == KStifMeasurementPlugin03 )
+        {
+        __RDEBUG( _L( "Measurement disable option [KStifMeasurement03] is given by user" ) );
+        return;
+        }
+    if( ( ( iMeasurementOption & EMeasurement04 ) == EMeasurement04 ) && aType == KStifMeasurementPlugin04 )
+        {
+        __RDEBUG( _L( "Measurement disable option [KStifMeasurement04] is given by user" ) );
+        return;
+        }
+    if( ( ( iMeasurementOption & EMeasurement05 ) == EMeasurement05 ) && aType == KStifMeasurementPlugin05 )
+        {
+        __RDEBUG( _L( "Measurement disable option [KStifMeasurement05] is given by user" ) );
+        return;
+        }
+    if( ( ( iMeasurementOption & EBappea ) == EBappea ) && aType == KStifMeasurementBappeaProfiler )
+        {
+        __RDEBUG( _L( "Measurement disable option [KStifMeasurementBappea] is given by user" ) );
+        return;
+        }
+
+    iMeasurementStruct.iConfigurationInfo = aConfigurationInfo;
+    iMeasurementStruct.iMeasurementOperation = KMeasurementNew;
+    iMeasurementStruct.iPointerToMeasurementModule = iTestModuleBase;
+
+    // Move measurement execution initialization forward to TestServer.
+    User::LeaveIfError( iTestModuleBase->iTestModuleIf->HandleMeasurementProcess(
+            iMeasurementStruct ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestMeasurement
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: CTestModuleBase* aTestModuleBase: in: Pointer to STIF.
+                TSTIFMeasurement aType: in: Measurement type.
+                const TDesC& aConfigurationInfo: in: Configuration info.
+    
+    Return Values: CSTIFTestMeasurement object.
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CSTIFTestMeasurement* CSTIFTestMeasurement::NewL( 
+                                            CTestModuleBase* aTestModuleBase,
+                                            TSTIFMeasurementType aType, 
+                                            const TDesC& aConfigurationInfo )
+    {
+    CSTIFTestMeasurement* self = 
+            new (ELeave) CSTIFTestMeasurement( aTestModuleBase );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aType, aConfigurationInfo );
+
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestMeasurement
+
+    Method: ~CSTIFTestMeasurement
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFTestMeasurement::~CSTIFTestMeasurement()
+    {
+    // None
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFTestMeasurement
+
+    Method: Start
+
+    Description: Start commant for measurement.
+
+    Parameters: None
+
+    Return Values: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestMeasurement::Start()
+    {
+    // Check that measurement is not disabled
+    if( iMeasurementOption  == iMeasurementStruct.iMeasurementType )
+        {
+        __RDEBUG( ( _L( "Measurement with type[%d] is disabled by user" ), iMeasurementOption ) );
+        // Cannot return error code because this causes problems in
+        // TestScripter and TestCombiner error handling. Now testing continue
+        // without measurement.
+        return KErrNone;
+        }
+
+    iMeasurementStruct.iMeasurementOperation = KMeasurementStart;
+
+    // Move measurement start execution forward to TestServer.
+    return iTestModuleBase->iTestModuleIf->HandleMeasurementProcess(
+                                                        iMeasurementStruct );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestMeasurement
+
+    Method: Stop
+
+    Description: Stop command for measurement.
+
+    Parameters: None
+
+    Return Values: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CSTIFTestMeasurement::Stop()
+    {
+    // Check that measurement is not disabled
+    if( iMeasurementOption  == iMeasurementStruct.iMeasurementType )
+        {
+        __RDEBUG( ( _L( "Measurement with type[%d] is disabled by user" ), iMeasurementOption ) );
+        // Cannot return error code because this causes problems in
+        // TestScripter and TestCombiner error handling. Now testing continue
+        // without measurement.
+        return KErrNone;
+        }
+
+    iMeasurementStruct.iMeasurementOperation = KMeasurementStop;
+
+    // Move measurement stop execution forward to TestServer.
+    return iTestModuleBase->iTestModuleIf->HandleMeasurementProcess(
+                                                        iMeasurementStruct );
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterface/src/TestModuleParameters.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestModuleParamVer01 class and CTestModuleParamVer01 class 
+* member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <stifinternal/TestServerClient.h>
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleParamVer01
+
+    Method: NewL
+
+    Description: Creates CTestModuleParamVer01
+      
+    Parameters: None
+
+    Return Values: CTestModuleParamVer01: CTestModuleParamVer01 object
+
+    Errors/Exceptions: Leaves if memory allocation fails.
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestModuleParamVer01* CTestModuleParamVer01::NewL()
+    {
+    CTestModuleParamVer01* self = new( ELeave ) CTestModuleParamVer01();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleParamVer01
+
+    Method: CTestModuleParamVer01
+
+    Description: Constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleParamVer01::CTestModuleParamVer01()
+    {
+    iVersio = EVersio1;
+
+    // Default test module thread heap and stack sizes.
+    iTestThreadStackSize = KStackSize;
+	iTestThreadMinHeap = KTestThreadMinHeap;
+	iTestThreadMaxHeap = KTestThreadMaxHeap;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleParamVer01
+
+    Method: ~CTestModuleParamVer01
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestModuleParamVer01::~CTestModuleParamVer01()
+    {
+    // None
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleParamVer01
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleParamVer01::ConstructL()
+    {
+	// None
+
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterference/inc/TestInterferenceImplementation.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,501 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains declaration of STIF interference
+* classes.
+*
+*/
+
+#ifndef TESTINTERFERENCEIMPLEMENTATION_H
+#define TESTINTERFERENCEIMPLEMENTATION_H
+
+// INCLUDES
+#include <StifTestInterference.h>
+#include <StifLogger.h>
+#include <e32std.h>
+#include <e32base.h>
+#include <e32svr.h>
+
+// Needed by interference test cases
+#include <f32file.h>
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// DATA TYPES
+//enum ?declaration
+//typedef ?declaration
+//extern ?data_type;
+
+// FUNCTION PROTOTYPES
+//?type ?function_name(?arg_list);
+
+// FORWARD DECLARATIONS
+class CExecuteInterference;
+
+// CLASS DECLARATION
+
+/**
+*  This is a CSTIFInterferenceAO class.
+*  This class is inherited from CActive and class implements MSTIFTestInterference.
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS( CSTIFInterferenceAO ) : public CActive, 
+										   public MSTIFTestInterference
+    {
+
+     public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSTIFInterferenceAO* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSTIFInterferenceAO();
+
+    public: // New functions
+
+        /**
+        * StartL method starts test interference.
+        */
+        TInt StartL( TStifTestInterferenceType aType,
+                    TInt aIdleTime,
+                    TInt aActiveTime );
+
+        /**
+        * Stop method stops test interference.
+        */
+        TInt Stop();
+
+        /**
+        * Sets thread or active object priority. This should use before
+        * test interference is started otherwise error code will return.
+        */
+        TInt SetPriority( TInt aPriority );
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * From CActive RunL handles request completion.
+        */
+        void RunL();
+
+        /**
+        * From CActive DoCancel handles request cancellation.
+        */
+        void DoCancel();
+
+        /**
+        * From CActive RunError handles error situations.
+        */
+        TInt RunError( TInt aError );
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CSTIFInterferenceAO();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // 
+        TStifTestInterferenceType   iInterferenceType;
+        // Test interference idle time
+        TInt                        iIdleTime;
+        // Test interference active time
+        TInt                        iActiveTime;
+
+        // Timer for executing idle time
+        RTimer                      iAOIdleTimer;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+
+        // CExecuteInterference object
+        CExecuteInterference*       iExecuteInterference;
+
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+/**
+*  This a CSTIFInterferenceThread class.
+*  This class is inherited from CBase and class implements MSTIFTestInterference.
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS( CSTIFInterferenceThread ) : public CBase,
+											   public MSTIFTestInterference
+    {
+
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSTIFInterferenceThread* NewL( CTestModuleBase* aTestModuleBase );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSTIFInterferenceThread();
+
+    public: // New functions
+
+        /**
+        * StartL method starts test interference.
+        */
+        TInt StartL( TStifTestInterferenceType aType,
+                    TInt aIdleTime,
+                    TInt aActiveTime );
+
+        /**
+        * Stop method stops test interference.
+        */
+        TInt Stop();
+
+        /**
+        * Sets thread or active object priority. This should use before
+        * test interference is started otherwise error code will return.
+        */
+        TInt SetPriority( TInt aPriority );
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+        static TInt ThreadFunction( TAny* aStarted );
+
+        /**
+        * Executes interference.
+        */
+        static void ExecuteInterferenceL( TStifTestInterferenceType aType, TInt aIdleTime, TInt aActiveTime );
+    public: // Functions from base classes
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CSTIFInterferenceThread();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL( CTestModuleBase* aTestModuleBase );
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+
+        // Struct that keeps thread related informations.
+        struct TThreadParam
+            {
+            RSemaphore                  iStarted;
+            TStifTestInterferenceType   iType;
+            TInt                        iIdleTime;
+            TInt                        iActiveTime;
+            // Note: Be carefully if adding pointers to struct
+            };
+
+        // RThread object
+        RThread                         iThread;
+
+        // TThreadParam object(Struct that keeps thread related informations)
+        TThreadParam*                   iThreadParam;
+
+        // Pointer to STIF size
+        CTestModuleBase*                iTestModuleBase;
+
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+/**
+*  This is a CExecuteInterference class.
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS( CExecuteInterference ) : public CBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CExecuteInterference* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CExecuteInterference();
+
+    public: // New functions
+
+        /**
+        * Start implement the test interference according to aType parameter.
+        */
+        TInt InterferenceL( 
+                    MSTIFTestInterference::TStifTestInterferenceType aType,
+                    TInt aActiveTime );
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CExecuteInterference();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+        /**
+        * Searches a file from given drive
+        */        
+        TInt SearchAFileForReading( TDes &aDriveName, RFs &aFileserver );
+
+        /**
+        * Prepares file system for test cases
+        */        
+        TInt PrepareFileSystemL( TDesC &aDriveName,
+                                 TDesC &aFileName );
+
+        /**
+        * Deletes files recursively starting from aStartDirectory
+        */        
+        TInt DeleteFilesRecursivelyL( RFs &aFileserver, 
+                                      TDes &aStartDirectory,
+                                      const TTime &aEndTime );
+
+        /**
+        * Empties file system using DeleteFilesRecursivelyL method
+        */        
+        TInt EmptyTheFileSystemL( TDes &aFilePath,
+                                 const TTime &aEndTime );
+
+        /**
+        * Creates CPU load
+        */        
+        TInt CPULoad( const TTimeIntervalMicroSeconds32 &aActiveTime );
+       
+        /**
+        * Writes data to file asynchronously
+        */                   
+        TInt WriteToFileAsynchL( TDes &aFilePath,
+                                RFs &aFileserver,
+                                const TTime & aEndTime );
+        /**
+        * Repeats write until aActiveTime has expired
+        */                                       
+        TInt RepeatWriteToFileL( 
+                    TDes &aFilePath,
+                    const TTime &aActiveTime );
+        
+        /**
+        * Repeats read until aActiveTime has expired
+        */              
+        TInt RepeatReadFromFileL( TDes &aFilePath,
+                                 const TTimeIntervalMicroSeconds32 &aActiveTime );
+                
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+
+        // RTimer object
+        RTimer                          iTimer;
+
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+#endif      // TESTINTERFERENCEIMPLEMENTATION_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestInterference/src/StifTestInterference.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1999 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* MSTIFTestInterference class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestInterference.h>
+#include "TestInterferenceImplementation.h"
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// For test interference thread's heap size
+const TUint KMaxHeapSize        = 0x20000; // 128 K
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: MSTIFTestInterference
+
+    Method: MSTIFTestInterference
+
+    Description: Create test interference object according to the paramater.
+
+    Parameters: CTestModuleBase* aTestModuleBase: inout: CTestModuleBase object
+                for get test interference handle to STIF's side(Used if test
+                case panic so test interference thread can be kill by STIF).
+                TStifTestInterferenceCategory aCategory: in: Test interference
+                category
+
+    Return Values: MSTIFTestInterference*: pointer to MSTIFTestInterference 
+                   object
+
+    Errors/Exceptions: Leaves if object creation fails.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C MSTIFTestInterference* MSTIFTestInterference::NewL(
+                                    CTestModuleBase* aTestModuleBase,
+                                    TStifTestInterferenceCategory aCategory )
+    {
+    if( aCategory == EActiveObject )        // Active object
+        {
+        CSTIFInterferenceAO* self = NULL;
+        self = CSTIFInterferenceAO::NewL();
+        return (MSTIFTestInterference*)self;
+        }
+    else                                    // EThread
+        {
+        CSTIFInterferenceThread* self = NULL;
+        self = CSTIFInterferenceThread::NewL( aTestModuleBase );
+        return (MSTIFTestInterference*)self;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: MSTIFTestInterference
+
+    Method: MSTIFTestInterference
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+MSTIFTestInterference::~MSTIFTestInterference()
+    {
+    // None
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CSTIFInterferenceAO class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: CSTIFInterferenceAO
+
+    Description: C++ default constructor can NOT contain any code, that
+                 might leave 
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFInterferenceAO::CSTIFInterferenceAO() :
+                                    CActive ( CActive::EPriorityStandard )
+    {
+    iInterferenceType = ENone;
+    iIdleTime = 0;
+    iActiveTime = 0;
+    iExecuteInterference = NULL;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: ConstructL
+
+    Description: Symbian 2nd phase constructor can leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leave if CreateLocal fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CSTIFInterferenceAO::ConstructL()
+    {
+    CActiveScheduler::Add ( this );
+
+    User::LeaveIfError( iAOIdleTimer.CreateLocal() );
+
+    iExecuteInterference = CExecuteInterference::NewL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: None
+
+    Return Values: CSTIFInterferenceAO*: pointer to CSTIFInterferenceAO object
+
+    Errors/Exceptions: Leaves if object creation fails.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFInterferenceAO* CSTIFInterferenceAO::NewL()
+    {
+    CSTIFInterferenceAO* self = new (ELeave) CSTIFInterferenceAO();
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: ~CSTIFInterferenceAO
+
+    Description: Destructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFInterferenceAO::~CSTIFInterferenceAO()
+    {
+    Cancel(); // Cancel itself
+    // If test case panic etc. do close operations here.
+    delete iExecuteInterference;
+    iExecuteInterference = NULL;
+
+    iAOIdleTimer.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: RunL
+
+    Description: Derived from CActive, handles test interference execution.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if InterferenceL leaves.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CSTIFInterferenceAO::RunL( )
+    {
+    iExecuteInterference->InterferenceL( iInterferenceType, iActiveTime );
+    
+    // Start idle timer
+    iAOIdleTimer.After( iStatus, iIdleTime );
+    SetActive();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: DoCancel
+
+    Description: Derived from CActive handles the Cancel
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CSTIFInterferenceAO::DoCancel( )
+    {
+    iAOIdleTimer.Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: RunError
+
+    Description: Derived from CActive handles errors from active handler.
+
+    Parameters: TInt aError: in: error from CActive 
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CSTIFInterferenceAO::RunError( TInt aError )
+    {
+    RDebug::Print( _L( "CSTIFInterferenceAO::RunError() with [%d]" ), aError );
+
+    return aError;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: StartL
+
+    Description: StartL method starts test interference.
+
+    Parameters: TStifTestInterferenceType aType: in: Test interference type.
+                TInt aIdleTime: in: Test interference idle time.
+                TInt aActiveTime: in: Test interference active time.
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: Leaves if active object is active.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CSTIFInterferenceAO::StartL( TStifTestInterferenceType aType,
+                                    TInt aIdleTime,
+                                    TInt aActiveTime )
+    {
+    if( IsActive() )
+        {
+        User::Leave( KErrAlreadyExists );
+        }
+
+    switch( aType )
+    	{
+    	case ENone:
+    	case ECpuLoad:
+    	case EFileSystemReadC:
+    	case EFileSystemReadD:
+    	case EFileSystemReadE:
+    	case EFileSystemReadZ:
+    	case EFileSystemWriteC:
+    	case EFileSystemWriteD:
+    	case EFileSystemWriteE:
+    	case EFileSystemFillAndEmptyC:
+    	case EFileSystemFillAndEmptyD:
+    	case EFileSystemFillAndEmptyE:
+    		aIdleTime = aIdleTime * 1000;
+    		aActiveTime = aActiveTime * 1000;
+    		break;
+    	case ENoneMicroSeconds:
+    		aType = ENone;
+    		break;
+    	case ECpuLoadMicroSeconds:
+			aType = ECpuLoad;
+			break;
+    	case EFileSystemReadCMicroSeconds:
+			aType = EFileSystemReadC;
+			break;
+    	case EFileSystemReadDMicroSeconds:
+			aType = EFileSystemReadD;
+			break;
+    	case EFileSystemReadEMicroSeconds:
+			aType = EFileSystemReadE;
+			break;
+    	case EFileSystemReadZMicroSeconds:
+			aType = EFileSystemReadZ;
+			break;
+    	case EFileSystemWriteCMicroSeconds:
+			aType = EFileSystemWriteC;
+			break;
+    	case EFileSystemWriteDMicroSeconds:
+			aType = EFileSystemWriteD;
+			break;
+    	case EFileSystemWriteEMicroSeconds:
+			aType = EFileSystemWriteE;
+			break;
+    	case EFileSystemFillAndEmptyCMicroSeconds:
+			aType = EFileSystemFillAndEmptyC;
+			break;
+    	case EFileSystemFillAndEmptyDMicroSeconds:
+			aType = EFileSystemFillAndEmptyD;
+			break;
+    	case EFileSystemFillAndEmptyEMicroSeconds:
+			aType = EFileSystemFillAndEmptyE;
+			break;
+    	}    
+    
+    iInterferenceType = aType;
+    iIdleTime = aIdleTime;
+    iActiveTime = aActiveTime;
+
+    // Set request to pending and active object to active
+    iStatus = KRequestPending;
+    SetActive();
+    // Complete request immediately
+    TRequestStatus* status = &iStatus;
+    User::RequestComplete( status, KErrNone );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: Stop
+
+    Description: Stop method stops test interference.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CSTIFInterferenceAO::Stop()
+    {
+    Cancel();
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceAO
+
+    Method: SetPriority
+
+    Description: Sets thread or active object priority. This should use before
+                 test interference is started otherwise error code will return.
+
+    Parameters: TInt aPriority: in: New priority for active object given by
+                user.
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CSTIFInterferenceAO::SetPriority( TInt aPriority )
+    {
+    if( IsActive() )
+        {
+        RDebug::Print( _L( "STIF: Priority cannot set because active object is active" ) );
+        return KErrGeneral;
+        }
+
+    CActive::SetPriority( (TPriority)aPriority );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CSTIFInterferenceThread class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: CSTIFInterferenceThread
+
+    Description: C++ default constructor can NOT contain any code, that
+                 might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFInterferenceThread::CSTIFInterferenceThread()
+    {
+    // None
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: ConstructL
+
+    Description: C++ default constructor can NOT contain any code, that
+                 might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CSTIFInterferenceThread::ConstructL( CTestModuleBase* aTestModuleBase )
+    {
+    iTestModuleBase = aTestModuleBase;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: None
+
+    Return Values: CSTIFInterferenceThread*: pointer to CSTIFInterferenceThread
+                   object
+
+    Errors/Exceptions: Leaves if object creation fails.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFInterferenceThread* CSTIFInterferenceThread::NewL( 
+                                            CTestModuleBase* aTestModuleBase )
+    {
+    CSTIFInterferenceThread* self = new (ELeave) CSTIFInterferenceThread();
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aTestModuleBase );
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: ~CSTIFInterferenceThread
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSTIFInterferenceThread::~CSTIFInterferenceThread()
+    {
+    // If test case crash etc. do stop operations here also
+    if( iThreadParam != NULL )
+        {
+        iThreadParam->iStarted.Close();
+        }
+    delete iThreadParam;
+    iThreadParam = NULL;
+    if( iThread.Handle() != NULL )
+        {
+        iThread.Kill( KErrNone );
+        iThread.Close();
+        }    
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: StartL
+
+    Description: StartL method starts test interference.
+
+    Parameters: TStifTestInterferenceType aType: in: Test interference type.
+                TInt aIdleTime: in: Test interference idle time.
+                TInt aActiveTime: in: Test interference active time.
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: Leaves if iThreadParam exists.
+                       Leaves if thread creation fails.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CSTIFInterferenceThread::StartL( TStifTestInterferenceType aType,
+                                        TInt aIdleTime,
+                                        TInt aActiveTime )
+    {
+    //__UHEAP_MARK;
+
+    if( iThreadParam )
+        {
+        User::Leave( KErrAlreadyExists );
+        }
+
+    // Thread related parameters
+    iThreadParam = new TThreadParam;
+    iThreadParam->iStarted.CreateLocal( 0 );
+    iThreadParam->iType = aType;
+    iThreadParam->iIdleTime = aIdleTime;
+    iThreadParam->iActiveTime = aActiveTime;
+
+    // Temporary thread unique name
+    _LIT( KThreadFirstName, "STIFInterference_%x" );
+     
+    TBuf<32> tmpThreadName;
+    TInt uniqueCounter = 1;
+    
+    TInt ret = KErrNone;
+    do
+    	{
+    	tmpThreadName.Format( KThreadFirstName, uniqueCounter );
+    	// Create thread
+    	ret = iThread.Create(
+    		    					tmpThreadName,       // thread name
+    		                        ThreadFunction,         // thread function
+    		                        KDefaultStackSize*4,    // stack
+    		                        KMinHeapSize,           // Heap, min
+    		                        KMaxHeapSize*2,         // Heap, max
+    		                        (TAny*) iThreadParam    // parameter to thread function
+    		                        );
+    	uniqueCounter++;
+    	}
+    while( ret == KErrAlreadyExists );
+    
+    // If thread creation failed
+    if( ret != KErrNone )        
+        {
+        iThreadParam->iStarted.Close();         // Close semaphore
+        delete iThreadParam;
+        iThreadParam = NULL;
+        //__UHEAP_MARKEND;
+        User::Leave( ret );
+        }
+
+    // Add thread pointer to STIF side for cases where need to kill
+    // thread e.g. if test case is crashed etc. before Stop(give by user).
+    iTestModuleBase->iTestModuleIf->AddInterferenceThread( iThread );
+
+    // Create unique thread name
+    const TInt name = 17; // Name parts
+    const TInt id = 8;    // Unique id parts
+    _LIT( KThreadUniqueName, "STIFInterference_" );
+    TBuf<name+id> threadUniqueName;
+    threadUniqueName.Copy( KThreadUniqueName );
+    // Appends id in hexadesimal format 
+    threadUniqueName.AppendFormat(  _L( "%x" ), (TInt)iThread.Id() );
+    //RDebug::Print(threadUniqueName);
+
+    // Reneme thread with unique name
+    iThread.RenameMe( threadUniqueName );
+
+    // Thread is currently in suspend state
+
+    // Now start thread
+    iThread.SetPriority( EPriorityMuchMore ); // set its priority
+    iThread.Resume();                         // kick it into life in
+                                              // sometimes(depend on scheduler)
+
+    // This block execution here and continue when signal is said in thread
+    // execution side.
+    // Wait until the thread is started
+    iThreadParam->iStarted.Wait();
+
+    //__UHEAP_MARKEND;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: Stop
+
+    Description:  Stop method stops test interference.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CSTIFInterferenceThread::Stop()
+    {
+    // Ensures that remove(Stop()) sequence won't do two times for one thread.
+    if( iThread.Handle() != NULL )
+        {
+        // Remove pointer from array
+        iTestModuleBase->iTestModuleIf->RemoveInterferenceThread( iThread );
+        }
+
+    // If test case crash etc. do stop operations here also
+    if( iThreadParam != NULL )
+        {
+        iThreadParam->iStarted.Close();
+        }
+    delete iThreadParam;
+    iThreadParam = NULL;
+    if( iThread.Handle() != NULL )
+        {
+        iThread.Kill( KErrNone );
+        iThread.Close();
+        }    
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: SetPriority
+
+    Description: Sets thread or active object priority. This should use before
+                 test interference is started otherwise error code will return.
+
+    Parameters: TInt aPriority: in: New priority for active object given by
+                user.
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CSTIFInterferenceThread::SetPriority( TInt aPriority )
+    {
+    // RThread priority can set during interference executions time. User
+    // should be sure that given value is acceptable, otherwise SetPriority
+    // panics.
+
+    RThread thisThread;
+    thisThread.SetPriority ( (TThreadPriority) aPriority );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: ThreadFunction
+
+    Description: Implements thread code
+
+    Parameters: TAny* aThreadArg: in : Thread related informations
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CSTIFInterferenceThread::ThreadFunction( TAny* aThreadArg )
+        {
+        // Thread code here
+
+        // Create clean-up stack
+        CTrapCleanup* tc = CTrapCleanup::New();
+
+        // Take local copy of incoming parameters. 
+        // This object is in stack -> no manual deletion
+        TThreadParam params = *(TThreadParam*)aThreadArg;
+        
+        // Signal to continue from CSTIFInterferenceThread::StartL
+        params.iStarted.Signal();
+
+        TInt ret = KErrNone;
+
+        // Construct and install active scheduler
+        CActiveScheduler* activeScheduler = new CActiveScheduler;
+        CActiveScheduler::Install( activeScheduler );
+
+        TRAP( ret, ExecuteInterferenceL( params.iType, params.iIdleTime, params.iActiveTime ) );
+
+    	User::LeaveIfError( ret );
+        
+        delete activeScheduler;
+        
+        // Delete clean-up stack
+        delete tc;
+        tc = NULL;
+
+        return KErrNone;
+        }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSTIFInterferenceThread
+
+    Method: ExecuteInterferenceL
+
+    Description: Executes interference.
+
+    Parameters: aType		Interference type.
+    			aIdleTime	Idle time.
+    			aActiveTime Active time.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CSTIFInterferenceThread::ExecuteInterferenceL( TStifTestInterferenceType aType, TInt aIdleTime, TInt aActiveTime )
+	{
+	CSTIFInterferenceAO* interferenceAO = CSTIFInterferenceAO::NewL();
+	CleanupStack::PushL( interferenceAO );
+
+	interferenceAO->StartL( aType, aIdleTime, aActiveTime );
+
+	CActiveScheduler::Start();
+	
+	CleanupStack::PopAndDestroy( interferenceAO );
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CExecuteInterference class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: CExecuteInterference
+
+    Description: C++ default constructor can NOT contain any code, that
+                 might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CExecuteInterference::CExecuteInterference()
+    {
+    iTimer.CreateLocal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: ConstructL
+
+    Description: C++ default constructor can NOT contain any code, that
+                 might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CExecuteInterference::ConstructL()
+    {
+    // None
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: None
+
+    Return Values: CExecuteInterference*: pointer to CExecuteInterference
+                   object
+
+    Errors/Exceptions: Leaves if object creation fails.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CExecuteInterference* CExecuteInterference::NewL()
+    {
+    CExecuteInterference* self = new (ELeave) CExecuteInterference();
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: ~CExecuteInterference
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CExecuteInterference::~CExecuteInterference()
+    {
+    iTimer.Cancel();
+    iTimer.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: Interference
+
+    Description: Start implement the test interference according to aType
+                 parameter.
+
+    Parameters: MSTIFTestInterference::TStifTestInterferenceType aType: in:
+                    Test interference type.
+                TInt aActiveTime: in: Test interference active time
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: Leaves if CleanupClosePushL leave
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::InterferenceL( 
+                    MSTIFTestInterference::TStifTestInterferenceType aType,
+                    TInt aActiveTime )
+    {
+    TTimeIntervalMicroSeconds32 myActiveTime( aActiveTime );    
+    
+    TTime endTime;
+    endTime.HomeTime();           
+    endTime = endTime + myActiveTime;   
+        
+    TFileName myFile;    
+        
+    switch( aType )
+        {
+        case MSTIFTestInterference::ECpuLoad:
+            {
+            return CPULoad( myActiveTime );
+            }
+        case MSTIFTestInterference::EFileSystemReadC:
+            {           
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemReadC" ) );
+            
+            _LIT( KDrive, "c:\\" );   
+            myFile.Format( KDrive );
+            
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );                                                                        
+
+            err = fileserver.SetSessionPath( myFile );
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive C is not ready!" ) );                                
+                // R Classes have not created with New, no delete needed
+                CleanupStack::Pop( &fileserver );
+                fileserver.Close();
+                return KErrNone;
+                }                           
+                
+            RDebug::Print( _L( "SearchAFileForReading" ) );                  
+            err = SearchAFileForReading( myFile, fileserver );                        
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "File not found!" ) );                  
+                return KErrNone;
+                }                            
+
+            RDebug::Print( _L( "File's name is: %S" ), &myFile );                     
+                        
+            return RepeatReadFromFileL( myFile, myActiveTime );
+            }
+        case MSTIFTestInterference::EFileSystemReadD:
+            {
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemReadD" ) );            
+            _LIT( KDrive, "D\x3a\\" );   
+            myFile.Format( KDrive );
+            
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );                                                                        
+            err = fileserver.SetSessionPath( myFile );
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive D is not ready!" ) );                                
+                // R Classes have not created with New, no delete needed
+                CleanupStack::Pop( &fileserver );
+                fileserver.Close();
+                return KErrNone;
+                }                           
+            RDebug::Print( _L( "Fileserver created" ) );                  
+                        
+            err = SearchAFileForReading( myFile, fileserver );                        
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "File not found!" ) );                  
+                return KErrNone;
+                }                                                  
+            return RepeatReadFromFileL( myFile, myActiveTime );
+            }
+        case MSTIFTestInterference::EFileSystemReadE:
+            {
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemReadE" ) );            
+            _LIT( KDrive, "E\x3a\\" );   
+            myFile.Format( KDrive );
+           
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );                                                                        
+            RDebug::Print( _L( "Fileserver created" ) );                  
+            err = fileserver.SetSessionPath( myFile );
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive E is not ready!" ) );
+                // R Classes have not created with New, no delete needed
+                CleanupStack::Pop( &fileserver );
+                fileserver.Close();
+                return KErrNone;
+                }                           
+            
+            err = SearchAFileForReading( myFile, fileserver );                        
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "File not found!" ) );                  
+                return KErrNone;
+                }                                                  
+            
+            return RepeatReadFromFileL( myFile, myActiveTime );
+            }
+        case MSTIFTestInterference::EFileSystemReadZ:
+            {
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemReadZ" ) );            
+            _LIT( KDrive, "Z:\\" );   
+            myFile.Format( KDrive );
+
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );                                                        
+            RDebug::Print( _L( "Fileserver created" ) );                  
+            err = fileserver.SetSessionPath( myFile );
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive Z is not ready!" ) );                                
+                // R Classes have not created with New, no delete needed
+                CleanupStack::Pop( &fileserver );
+                fileserver.Close();
+                return KErrNone;
+                }                           
+
+            err = SearchAFileForReading( myFile, fileserver );                        
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "File not found!" ) );                  
+                return KErrNone;
+                }                                                  
+            
+            return RepeatReadFromFileL( myFile, myActiveTime );
+            }           
+        case MSTIFTestInterference::EFileSystemWriteC:
+            {            
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemWriteC" ) );            
+            _LIT( KDrive, "C:\\" );
+            _LIT( KFileName,  "FileSystemWriteC.txt" );                                    
+            TBufC<20> myFileName( KFileName );            
+            myFile.Format( KDrive );
+
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );                                                        
+            RDebug::Print( _L( "Fileserver created" ) );                  
+                        
+            err = fileserver.SetSessionPath( myFile );                       
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive C is not ready!" ) );
+                return KErrNone;
+                }
+            
+            PrepareFileSystemL( myFile, myFileName );
+            myFile.Append( myFileName );
+            return RepeatWriteToFileL( myFile, endTime );
+            }
+        case MSTIFTestInterference::EFileSystemWriteD:
+            {
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemWriteD" ) );            
+            _LIT( KDrive, "D\x3a\\" );
+            _LIT( KFileName,  "FileSystemWriteD.txt" );                                    
+            TBufC<20> myFileName( KFileName );            
+            myFile.Format( KDrive );
+
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );                                            
+            RDebug::Print( _L( "Fileserver created" ) );                  
+            err = fileserver.SetSessionPath( myFile );                       
+                        
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive D is not ready!" ) );
+                return KErrNone;
+                }
+                            
+            PrepareFileSystemL( myFile, myFileName );
+            myFile.Append( myFileName );
+            return RepeatWriteToFileL( myFile, endTime );
+            }
+        case MSTIFTestInterference::EFileSystemWriteE:
+            {            
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemWriteE" ) );            
+            _LIT( KDrive, "E\x3a\\" );
+            _LIT( KFileName,  "FileSystemWriteE.txt" );
+            TBufC<20> myFileName( KFileName );            
+            myFile.Format( KDrive );
+            
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );                                
+            RDebug::Print( _L( "Fileserver created" ) );                  
+                        
+            err = fileserver.SetSessionPath( myFile );                       
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive E is not ready!" ) );
+                return KErrNone;
+                }            
+            PrepareFileSystemL( myFile, myFileName );
+            myFile.Append( myFileName );
+
+            return RepeatWriteToFileL( myFile, endTime );
+            }
+        case MSTIFTestInterference::EFileSystemFillAndEmptyC:
+            {                       
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemFillAndEmptyC" ) );            
+            _LIT( KDrive, "C:\\" );
+            _LIT( KFileName,  "FillAndEmptyFile.txt" );                      
+            TBufC<20> myFileName( KFileName );            
+            myFile.Format( KDrive );
+            
+            RFs fileserver;            
+            TInt err = fileserver.Connect();             
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );                    
+            RDebug::Print( _L( "Fileserver created" ) );                  
+                        
+            err = fileserver.SetSessionPath( myFile );                       
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive C is not ready!" ) );
+                return KErrNone;
+                }                
+            PrepareFileSystemL( myFile, myFileName );
+            myFile.Append( myFileName );
+
+            RepeatWriteToFileL( myFile, endTime );                        
+            EmptyTheFileSystemL( myFile, endTime );
+            
+            return KErrNone;
+            }
+        case MSTIFTestInterference::EFileSystemFillAndEmptyD:
+            {
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemFillAndEmptyD" ) );            
+            _LIT( KDrive, "D\x3a\\" );
+            _LIT( KFileName,  "FillAndEmptyFile.txt" );                      
+            TBufC<20> myFileName( KFileName );            
+            myFile.Format( KDrive );
+            
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }      
+            CleanupClosePushL( fileserver );                    
+            RDebug::Print( _L( "Fileserver created" ) );                  
+                        
+            err = fileserver.SetSessionPath( myFile );                       
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive D is not ready!" ) );
+                return KErrNone;
+                }                
+            PrepareFileSystemL( myFile, myFileName );
+            myFile.Append( myFileName );
+
+            RepeatWriteToFileL( myFile, endTime );                        
+            EmptyTheFileSystemL( myFile, endTime );
+            
+            return KErrNone;
+            }
+        case MSTIFTestInterference::EFileSystemFillAndEmptyE:
+            {
+            RDebug::Print( _L( "STIFTestInterference::EFileSystemFillAndEmptyE" ) );            
+            _LIT( KDrive, "E\x3a\\" );
+            _LIT( KFileName,  "FillAndEmptyFile.txt" );                      
+            TBufC<20> myFileName( KFileName );            
+            myFile.Format( KDrive );
+            
+            RFs fileserver;            
+            TInt err = fileserver.Connect(); 
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+                return err;
+                }          
+            CleanupClosePushL( fileserver );
+            RDebug::Print( _L( "Fileserver created" ) );                  
+                        
+            err = fileserver.SetSessionPath( myFile );                       
+            // R Classes have not created with New, no delete needed
+            CleanupStack::Pop( &fileserver );
+            fileserver.Close();
+
+            if( err != KErrNone )
+                {
+                RDebug::Print( _L( "Drive E is not ready!" ) );
+                return KErrNone;
+                }                
+            PrepareFileSystemL( myFile, myFileName );
+            myFile.Append( myFileName );
+
+            RepeatWriteToFileL( myFile, endTime );                        
+            EmptyTheFileSystemL( myFile, endTime );
+            
+            return KErrNone;
+            }       
+        default:
+            {
+            return KErrNone;
+            }
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: SearchAFileForReading
+
+    Description: Searches a file from given directory
+
+    Parameters: TDes &aPath, TDes &aFileserver
+
+    Return Values: TInt Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::SearchAFileForReading( TDes &aPath, RFs &aFileserver )
+    {
+    RDebug::Print( _L( "CExecuteInterference::SearchAFileForReading" ) );    
+    
+    CDir * filelist;
+    CDir * dirlist;
+    TInt ret = KErrNotFound;       
+    aFileserver.SetSessionPath( aPath );        
+    
+    aFileserver.GetDir( aPath, KEntryAttNormal, ESortByName, filelist, dirlist );        
+    
+    if( !filelist || !dirlist )
+        {
+        return KErrArgument;
+        }
+
+    if( filelist->Count() > 0 )
+        {
+        RDebug::Print( _L( "Filelist > 0" ) );    
+            
+        // File found! 
+        
+        // Check file size and accept it only if the size is ~10kb
+        // at miminum, or something like that
+        aPath.Append( (*filelist)[0].iName );                        
+        ret = KErrNone;
+        
+        RDebug::Print( _L( "File name: %S" ), &(*filelist)[0].iName );        
+        }
+    else
+        {
+        RDebug::Print( _L( "Filelist < 0, lets check other dirs" ) );            
+        TFileName tmp;
+        tmp.Append( aPath );
+        for( TInt x=0; x<dirlist->Count(); x++ )
+            {            
+            aPath.Format( tmp );
+            aPath.Append( (*dirlist)[0].iName );
+            aPath.Append( _L("\\") );
+            ret = SearchAFileForReading( aPath, aFileserver );
+            if( ret == KErrNone )
+                {
+                break;
+                }
+            }
+        }
+    
+    delete filelist;
+    delete dirlist;    
+       
+    return ret;        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: PrepareFileSystemLL
+
+    Description: Creates directory and file for test cases, if necessary
+
+    Parameters: TDes &aDriveName, TDes &aFileName
+
+    Return Values: TInt Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::PrepareFileSystemL( TDesC &aDriveName,
+                                              TDesC &aFileName )
+    {
+    // Note that aDriveName must be in format drivename:\\, e.g. "c:\\"
+    
+    RDebug::Print(_L("CExecuteInterference::PrepareFileSystemL"));
+    TFileName tmp;
+    tmp.Append( aDriveName );
+    
+    RFs fileserver;
+    TInt err = fileserver.Connect(); 
+    if( err != KErrNone )
+        {
+        RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+        return err;
+        }      
+    CleanupClosePushL( fileserver );                    
+            
+    _LIT( KSTIFDirName, "STIFInterference\\" );                                          
+
+    err = fileserver.SetSessionPath( tmp );                           
+    if( err != KErrNone )
+        {
+        CleanupStack::Pop( &fileserver );
+        fileserver.Close();
+        return err;
+        }
+    
+    tmp.Append( KSTIFDirName );
+    err = fileserver.MkDir( tmp );
+    if( err != KErrNone && err != KErrAlreadyExists )
+        {
+        RDebug::Print( _L( "MkDir failed with error: %d" ), err );
+        // R Classes have not created with New, no delete needed
+        CleanupStack::Pop( &fileserver );
+        fileserver.Close();
+        return err;
+        }              
+    
+    tmp.Format( aDriveName );
+    tmp.Append( KSTIFDirName );        
+    fileserver.SetSessionPath( tmp );                               
+
+    RFile newFile;
+    CleanupClosePushL( newFile );                    
+    TInt ret = newFile.Create( fileserver, aFileName, EFileWrite );
+    if( ret != KErrNone && ret != KErrAlreadyExists )
+        {
+        RDebug::Print( _L( "File create failed with error: %d" ), err );            
+        }
+        
+    // R Classes have not created with New, no delete needed
+    CleanupStack::Pop( &newFile );
+    CleanupStack::Pop( &fileserver );
+    newFile.Close();
+    fileserver.Close();
+    
+    return ret;      
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: CPULoad
+
+    Description: Creates CPU load to the system
+
+    Parameters: const TTimeIntervalMicroSeconds32 &aActiveTime
+
+    Return Values: TInt Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::CPULoad( const TTimeIntervalMicroSeconds32 &aActiveTime )
+    {
+    RDebug::Print(_L("CExecuteInterference::CPULoad"));
+
+    TTime endTime;
+    TTime currentTime;
+
+    currentTime.HomeTime();
+    endTime.HomeTime();
+
+    endTime = endTime + aActiveTime;  
+
+    while ( currentTime < endTime )
+       {
+        currentTime.HomeTime();    
+       }
+
+    return KErrNone;    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: DeleteFilesRecursivelyL
+
+    Description: Delete files in current directory and its subdirectories
+
+    Parameters: RFs &aFileserver, 
+                TDes &aStartDirectory
+
+    Return Values: TInt Symbian error code
+
+    Errors/Exceptions: Leaves if GetDir fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::DeleteFilesRecursivelyL( RFs &aFileserver, 
+                                                    TDes &aStartDirectory,
+                                                    const TTime &aEndTime )
+    { 
+    TTime currentTime;
+    currentTime.HomeTime();      
+    if( currentTime >= aEndTime )
+        {
+        return KErrTimedOut;
+        }
+    
+    RDebug::Print( _L( "CExecuteInterference::DeleteFilesRecursivelyL" ) );    
+    
+    TFileName currentDir;   
+    CDir * filelist;
+    CDir * dirlist;       
+    
+    aFileserver.SetSessionPath( aStartDirectory );    
+    aFileserver.SessionPath( currentDir );
+    RDebug::Print( _L( "Hakemistopolku = %S" ), &currentDir );       
+    
+    User::LeaveIfError( aFileserver.GetDir( 
+            currentDir, KEntryAttNormal, ESortByName, filelist, dirlist ) );
+               
+    // Delete all files
+    for( TInt x=0; x<filelist->Count(); x++ )
+        {
+        RDebug::Print( _L( "CExecuteInterference::DeleteFilesRecursivelyL: delete: %S" ), &(*filelist)[x].iName );                    
+        aFileserver.Delete( (*filelist)[x].iName );    
+        }
+    
+    // Looping all directories recursively
+    for( TInt y= 0; y<dirlist->Count(); y++ )
+        {        
+        currentDir.Format( aStartDirectory );
+        currentDir.Append( (*dirlist)[y].iName );
+        currentDir.Append( _L("\\") );
+        DeleteFilesRecursivelyL( aFileserver, currentDir, aEndTime );
+        }    
+     
+    delete filelist;
+    delete dirlist;
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: EmptyTheFileSystemL
+
+    Description: Empty the file system using DeleteFilesRecursivelyL
+
+    Parameters: TDes &aFilePath
+
+    Return Values: TInt Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::EmptyTheFileSystemL( TDes &aFilePath, 
+                                               const TTime &aEndTime )
+    {
+    TTime currentTime;
+    currentTime.HomeTime();
+    if( currentTime >= aEndTime )
+        {
+        // End of time
+        return KErrTimedOut;
+        }    
+    
+    RDebug::Print( _L( "CExecuteInterference::EmptyTheFileSystemL" ) );    
+    RFs fileserver;
+    TInt err = fileserver.Connect(); 
+    if( err != KErrNone )
+        {
+        RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+        return err;
+        }      
+    CleanupClosePushL( fileserver );                           
+    TRAP( err, DeleteFilesRecursivelyL( fileserver, aFilePath, aEndTime ) );        
+    if( err != KErrNone )
+        {
+        RDebug::Print( _L( "DeleteFilesRecursivelyL failed with error: %d" ), err );
+        }    
+    // R Classes have not created with New, no delete needed
+    CleanupStack::Pop( &fileserver );   
+    fileserver.Close();
+    return err;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: WriteToFileAsynchL
+
+    Description: Writes data to a file asynchronously
+
+    Parameters: RFs &aFileserver,
+                const TTime &aEndTime 
+
+    Return Values: TInt Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::WriteToFileAsynchL( TDes &aFilePath,
+                                              RFs &aFileserver,
+                                              const TTime &aEndTime )
+    {
+    RFile myFile;
+
+    TInt err = myFile.Open( aFileserver, aFilePath, EFileWrite );
+    if( err != KErrNone )
+        {
+        RDebug::Print( _L( "Open file failed with error: %d" ), err );
+        return err;
+        }    
+    CleanupClosePushL( myFile );                      
+    TInt position = 0;
+    myFile.Seek( ESeekEnd, position );
+
+    _LIT8( KMyBuffer, "STIF Interference module: WriteToFile");
+    
+    // NOTE: this part has previous asynch implementation, doesn't work
+    // at the moment
+    /* 
+    TRequestStatus status;
+    myFile.Write( position, KMyBuffer, status );    
+    // Loop until either write operation is completed or the execution 
+    // time has expired    
+    while( doAlways ) 
+        {
+        if( status != KRequestPending )
+            {
+            return status.Int();
+            }
+        currentTime.HomeTime();                   
+        if( currentTime >= aEndTime )
+            {
+            return KErrTimedOut;
+            }
+         
+       }
+    */            
+
+    TTime currentTime;
+    currentTime.HomeTime();
+    
+    while( currentTime <= aEndTime )
+        {
+        myFile.Write( position, KMyBuffer );
+        currentTime.HomeTime();
+        }
+    // R Classes have not created with New, no delete needed
+    CleanupStack::Pop( &myFile );          
+    myFile.Close();
+    return KErrNone;      
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: RepeatWriteToFileL
+
+    Description: Repeats file writing using WriteToFileAsynchL method
+
+    Parameters: const TTimeIntervalMicroSeconds32 &aActiveTime
+
+    Return Values: TInt Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::RepeatWriteToFileL(
+                    TDes &aFilePath, 
+                    const TTime &aActiveTime )
+    {
+    RFs fileserver;
+    TInt err = fileserver.Connect(); 
+    if( err != KErrNone )
+        {
+        RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+        return err;
+        }      
+    CleanupClosePushL( fileserver );                           
+        
+    TTime currentTime;
+    currentTime.HomeTime();
+
+    TVolumeInfo myVolume;
+    fileserver.Volume( myVolume, EDriveC );   
+
+    while( ( currentTime <= aActiveTime ) && ( myVolume.iFree > 0 ) )    
+        {
+        WriteToFileAsynchL( aFilePath, fileserver, aActiveTime );        
+        currentTime.HomeTime();
+        }
+    
+    // R Classes have not created with New, no delete needed
+    CleanupStack::Pop( &fileserver );        
+    fileserver.Close();
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CExecuteInterference
+
+    Method: RepeatReadFromFileL
+
+    Description: Repeats file reading using ReadFromFileAsynch method
+
+    Parameters: const TTimeIntervalMicroSeconds32 &aActiveTime
+
+    Return Values: TInt Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CExecuteInterference::RepeatReadFromFileL( 
+                               TDes &aFilePath,
+                               const TTimeIntervalMicroSeconds32 &aActiveTime )
+    {
+    RDebug::Print( _L( "CExecuteInterference::RepeatReadFromFileL" ) );
+    
+    RFs fileserver;
+    TInt err = fileserver.Connect(); 
+    if( err != KErrNone )
+        {
+        RDebug::Print( _L( "RFs connection failed with error: %d" ), err );
+        return err;
+        }      
+    CleanupClosePushL( fileserver );                           
+    
+    TTime endTime;
+    TTime currentTime;
+    RFile myFile;
+    TBuf8<20> myReadBuffer;
+
+    RDebug::Print( _L( "RepeatReadFromFileL: Open" ) );                  
+
+    // Open file
+    err = myFile.Open( fileserver, aFilePath, EFileWrite );
+    if( err != KErrNone )
+        {
+        RDebug::Print( _L( "Open file failed with error: %d" ), err );
+        // R Classes have not created with New, no delete needed
+        CleanupStack::Pop( &fileserver );
+        fileserver.Close();
+        return err;
+        }        
+            
+    CleanupClosePushL( myFile );                                       
+    // This part has previous async implementation, doesn't work at moment
+    /*   
+    RDebug::Print( _L( "ReadFromFileAsynch: trequeststatus" ) );                        
+           
+    TRequestStatus timer;
+    TRequestStatus read;
+
+    RDebug::Print( _L( "ReadFromFileAsynch: asynk timer" ) );                    
+
+    RTimer clock;
+    clock.CreateLocal();
+    clock.At( timer, endTime);
+
+    RDebug::Print( _L( "ReadFromFileAsynch: asynk read" ) );
+    myFile.Read( myReadBuffer, 20, read );
+
+    RDebug::Print( _L( "ReadFromFileAsynch: ennen whilelooppia" ) );
+    while( timer == KRequestPending )
+        {
+        User::WaitForRequest( read, timer );
+        if( read != KRequestPending)
+            {
+            RDebug::Print( _L( "ReadFromFileAsynch: uudelleen asynk read" ) );
+            read = KRequestPending;                              
+    	    myFile.Read( myReadBuffer, 20, read );    	    
+            }
+        else
+            {  
+            RDebug::Print( _L( "ReadFromFileAsynch: cancel luku, timer kompletoitui" ) );                  
+            // Timer valmis         
+            //read = KRequestPending;   
+            myFile.ReadCancel( read );
+            User::WaitForRequest( read );
+            break;
+            }
+        }      
+    */
+
+    currentTime.HomeTime();
+    endTime.HomeTime();
+    endTime = endTime + aActiveTime;
+    
+    while( currentTime <= endTime )
+        {
+        myFile.Read( myReadBuffer );
+        currentTime.HomeTime();    	    
+        }
+        
+    //myFile.Close();
+    //fileserver.Close();
+    // R Classes have not created with New, no delete needed
+    CleanupStack::Pop( &myFile );
+    CleanupStack::Pop( &fileserver );
+    myFile.Close();
+    fileserver.Close();
+    //CleanupStack::PopAndDestroy( 2 );       
+   
+    RDebug::Print( _L( "CExecuteInterference::RepeatReadFromFileL success" ) );
+    return KErrNone;    
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/CapsModifierXXX/CreateCapsModifier.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,109 @@
+::
+:: Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+:: All rights reserved.
+:: This component and the accompanying materials are made available
+:: under the terms of "Eclipse Public License v1.0"
+:: which accompanies this distribution, and is available
+:: at the URL "http://www.eclipse.org/legal/epl-v10.html".
+::
+:: Initial Contributors:
+:: Nokia Corporation - initial contribution.
+::
+:: Contributors:
+:: 
+:: Description: This file contains capsmodifier implementation.
+::
+
+@perl -x CreateCapsModifier.bat %1 %2 %3 %4 %5 %6 %7 %8 %9 
+@goto end
+
+#!perl
+use strict;
+use File::Find;
+
+# Verify command line parameters
+if   ($#ARGV == -1 || $#ARGV > 1 )
+{
+	PrintHelp();
+}
+
+# Take module name
+my $moduleName = $ARGV[0];
+my $MODULENAME = $moduleName;
+$MODULENAME =~ tr/[a-z]/[A-Z]/;
+
+# Take target path or use default
+my $targetPath="\\";
+if ( $#ARGV == 1 )
+{
+	$targetPath = $ARGV[1];
+}
+
+
+# Create directory
+my $targetDir = $targetPath.$moduleName."_exe"."\\";
+
+print "Starting module creation to $targetDir\n";
+mkdir $targetDir, 0777 || die ("Can't create directory $targetDir");
+
+# Loop through the file structure
+find(\&renamerename, '.');
+
+unlink $targetDir."CreateCapsModifier.bat";
+print "Module created to $targetDir\n";
+
+# This function will be called for each file or directory
+sub renamerename
+{
+	my $oldName = $_;
+	print "Processing $oldName\n";
+
+	# Construct new filename if that needed
+	s/CapsModifierXXX/$moduleName/i;
+	my $newName = $targetDir.$File::Find::dir."/".$_;  
+
+	# Process directories
+	if (opendir(DIR, $oldName))
+	{
+		closedir (DIR);
+	
+		mkdir $newName, 0777 || die ("Can't create directory $newName");
+		return;
+	}
+                        
+	# Open input file
+	open (INFILE, $oldName ) || die ("Can not find $oldName");
+
+	#Open output file
+	my $newOutput = $newName."new";
+	open (OUTFILE, ">".$newOutput ) || die ("Can not open $newOutput");
+
+	# Replace text in files
+	while (<INFILE>)
+	{
+	  s/CapsModifierXXX/$moduleName/g;
+	  print OUTFILE $_;
+	}
+
+	# Close filehandles
+	close (INFILE);
+	close (OUTFILE);
+
+	# Rename result file
+	rename $newOutput,$newName;
+}
+
+sub PrintHelp()
+{
+	print "CreateModule ModuleName [path]\n";
+	print "\n";
+	print "Creates a new capsmodifier module\n";
+	print "If [path] is not given, module is created to root of current drive.\n";
+	print "If [path] is given, it must contain the final \'\\\' in path name.\n";
+	print "Command must be executed in directory where the template exist.\n";
+	exit;
+}
+
+
+__END__
+:end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/CapsModifierXXX/group/CapsModifierXXX_exe.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's CapsModifier 
+* module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          CapsModifierXXX.exe
+TARGETTYPE      exe
+
+/* Specify the capabilities according to your test environment */
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+OS_LAYER_SYSTEMINCLUDE
+
+/* Source files */
+SOURCEPATH      ../src
+
+
+SOURCE          CapsModifierXXX_exe.cpp
+
+/* Used libraries */
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+
+EPOCSTACKSIZE   40960
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/CapsModifierXXX/group/CapsModifierXXX_exe.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+; 
+; Description:
+;
+; 	Installation file for STIF
+;
+
+; Languages
+&EN
+
+; Provide value for uid
+#{"STIF"},(0x00000000),1,1,0,TYPE=SA
+
+; Series60 product id for S60 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Logo
+; None
+
+; Package signature - Optional
+; None
+
+; Start of Package body
+
+; Condition blocks
+; None
+
+; Options list
+; None
+
+; Install files
+"\epoc32\release\armv5\udeb\CapsModifierXXX.exe"   -   "!:\Sys\Bin\CapsModifierXXX.exe"
+  
+; Embedded SIS 
+; None
+
+; End of Package body
+
+; PKG dependencies
+; None
+
+; PKG capabilities
+; None
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/CapsModifierXXX/group/CapsModifierXXX_exe_nrm.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's CapsModifier 
+* module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          CapsModifierXXX.exe
+TARGETTYPE      exe
+
+/* Specify the capabilities according to your test environment */
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+OS_LAYER_SYSTEMINCLUDE
+
+/* Source files */
+SOURCEPATH      ../src
+
+SOURCE          CapsModifierXXX_exe.cpp
+
+/* Used libraries */
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+
+EPOCSTACKSIZE   40960
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/CapsModifierXXX/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for STIF Test Framework's
+*	CapsModifierXXX capability modifier module.
+*/
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	CapsModifierXXX_exe_nrm.mmp
+
+PRJ_TESTMMPFILES
+
+	CapsModifierXXX_exe.mmp
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/CapsModifierXXX/src/CapsModifierXXX_exe.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains capsmodifier implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <StifTestInterface.h>
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: E32Main
+
+    Description: 
+
+    Parameters: None
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+GLDEF_C TInt E32Main()
+    {
+    _LIT( KProcessMsgStart, "New process starting" );
+    RDebug::Print( KProcessMsgStart );
+
+
+    // This starts a new session that get capabilites that is used in 
+    // CapsModifierXXX_exe.mmp file.
+    TInt r = StartSession();
+
+    _LIT( KProcessMsgEnd, "New process ends" );
+    RDebug::Print( KProcessMsgEnd );
+
+    return r;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/Bmarm/HARDCODEDTESTMODULEXXXU.DEF	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	LibEntryL__Fv @ 1 NONAME R3UNUSED ; LibEntryL(void)
+	SetRequirements__FRP16CTestModuleParamRUl @ 2 NONAME R3UNUSED ; SetRequirements(CTestModuleParam *&, unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/Bwins/HardCodedTestModuleXXXu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	?LibEntryL@@YAPAVCTestModuleBase@@XZ @ 1 NONAME ; class CTestModuleBase * __cdecl LibEntryL(void)
+	?SetRequirements@@YAHAAPAVCTestModuleParam@@AAK@Z @ 2 NONAME ; int __cdecl SetRequirements(class CTestModuleParam * &,unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/createhardcodedmodule.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,111 @@
+::
+:: Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+:: All rights reserved.
+:: This component and the accompanying materials are made available
+:: under the terms of "Eclipse Public License v1.0"
+:: which accompanies this distribution, and is available
+:: at the URL "http://www.eclipse.org/legal/epl-v10.html".
+::
+:: Initial Contributors:
+:: Nokia Corporation - initial contribution.
+::
+:: Contributors:
+:: 
+:: Description: This file contains capsmodifier implementation.
+::
+
+@perl -x createhardcodedmodule.bat %1 %2 %3 %4 %5 %6 %7 %8 %9 
+@goto end
+
+#!perl
+use strict;
+use File::Find;
+
+# Verify command line parameters
+if   ($#ARGV == -1 || $#ARGV > 1 )
+{
+	PrintHelp();
+}
+
+# Take module name
+my $moduleName = $ARGV[0];
+my $MODULENAME = $moduleName;
+$MODULENAME =~ tr/[a-z]/[A-Z]/;
+
+# Take target path or use default
+my $targetPath="\\";
+if ( $#ARGV == 1 )
+{
+	$targetPath = $ARGV[1];
+}
+
+
+# Create directory
+my $targetDir = $targetPath.$moduleName."\\";
+
+print "Starting module creation to $targetDir\n";
+mkdir $targetDir, 0777 || die ("Can't create directory $targetDir");
+
+# Loop through the file structure
+find(\&renamerename, '.');
+
+unlink $targetDir."createhardcodedmodule.bat";
+print "Module created to $targetDir\n";
+
+# This function will be called for each file or directory
+sub renamerename
+{
+	my $oldName = $_;
+	print "Processing $oldName\n";
+
+	# Construct new filename if that needed
+	s/HardCodedTestModuleXXX/$moduleName/i;
+	my $newName = $targetDir.$File::Find::dir."/".$_;  
+
+	# Process directories
+	if (opendir(DIR, $oldName))
+	{
+		closedir (DIR);
+		mkdir $newName, 0777 || die ("Can't create directory $newName");
+		return;
+	}
+                        
+	# Open input file
+	open (INFILE, $oldName ) || die ("Can not find $oldName");
+
+	#Open output file
+	my $newOutput = $newName."new";
+	open (OUTFILE, ">".$newOutput ) || die ("Can not open $newOutput");
+
+	# Replace text in files
+	while (<INFILE>)
+	{
+	  s/HardCodedTestModuleXXX/$moduleName/g;
+	  s/HARDCODEDTESTMODULEXXX/$MODULENAME/g;
+	  s/XXX/$moduleName/g;
+	  s/HardCodedTargetDirYYY/$targetDir/g;
+	  print OUTFILE $_;
+	}
+
+	# Close filehandles
+	close (INFILE);
+	close (OUTFILE);
+
+	# Rename result file
+	rename $newOutput,$newName;
+}
+
+sub PrintHelp()
+{
+	print "createhardcodedmodule ModuleName [path]\n";
+	print "\n";
+	print "Creates a new test module\n";
+	print "If [path] is not given, module is created to root of current drive.\n";
+	print "If [path] is given, it must contain the final \'\\\' in path name.\n";
+	print "Command must be executed in directory where the template exist.\n";
+	exit;
+}
+
+
+__END__
+:end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/eabi/HardCodedTestModuleXXXu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	_Z9LibEntryLv @ 1 NONAME
+	_Z15SetRequirementsRP16CTestModuleParamRm @ 2 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/group/HardCodedTestModuleXXX.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,75 @@
+/*TYPE HARDCODED*/
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Hardcoded test 
+* module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          HardCodedTestModuleXXX.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+//TARGETPATH      ?target_path
+DEFFILE         HardCodedTestModuleXXX.def
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          HardCodedTestModuleXXX.cpp
+SOURCE          HardCodedTestModuleXXXCases.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// DEFFILE ?filename
+// AIF ?filename// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/group/HardCodedTestModuleXXX.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+; 
+; Description:
+;
+; 	Installation file for STIF
+;
+
+; Languages
+&EN
+
+; Provide value for uid
+#{"STIF"},(0x00000000),1,1,0,TYPE=SA
+
+; Series60 product id for S60 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Logo
+; None
+
+; Package signature - Optional
+; None
+
+; Start of Package body
+
+; Condition blocks
+; None
+
+; Options list
+; None
+
+; Install files
+"\epoc32\release\armv5\udeb\HardCodedTestModuleXXX.dll"   -   "!:\Sys\Bin\HardCodedTestModuleXXX.dll"
+  
+; Embedded SIS 
+; None
+
+; End of Package body
+
+; PKG dependencies
+; None
+
+; PKG capabilities
+; None
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/group/HardCodedTestModuleXXX_DoxyFile.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,240 @@
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+#
+# Contributors:
+# 
+# Description:
+#
+#
+
+# Doxyfile 1.4.1
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+PROJECT_NAME           = HardCodedTestModuleXXX
+PROJECT_NUMBER         = 
+OUTPUT_DIRECTORY       = HardCodedTargetDirYYY
+CREATE_SUBDIRS         = NO
+OUTPUT_LANGUAGE        = English
+USE_WINDOWS_ENCODING   = YES
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       = 
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = NO
+STRIP_FROM_PATH        = 
+STRIP_FROM_INC_PATH    = 
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = NO
+MULTILINE_CPP_IS_BRIEF = NO
+DETAILS_AT_TOP         = NO
+INHERIT_DOCS           = YES
+DISTRIBUTE_GROUP_DOC   = NO
+TAB_SIZE               = 8
+ALIASES                = 
+OPTIMIZE_OUTPUT_FOR_C  = YES
+OPTIMIZE_OUTPUT_JAVA   = NO
+SUBGROUPING            = YES
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = YES
+EXTRACT_PRIVATE        = NO
+EXTRACT_STATIC         = NO
+EXTRACT_LOCAL_CLASSES  = NO
+EXTRACT_LOCAL_METHODS  = NO
+HIDE_UNDOC_MEMBERS     = NO
+HIDE_UNDOC_CLASSES     = NO
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = YES
+CASE_SENSE_NAMES       = YES
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_BY_SCOPE_NAME     = NO
+GENERATE_TODOLIST      = NO
+GENERATE_TESTLIST      = NO
+GENERATE_BUGLIST       = NO
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       = 
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_DIRECTORIES       = YES
+FILE_VERSION_FILTER    = 
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           = 
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  = HardCodedTargetDirYYY
+FILE_PATTERNS          = *.h \
+                         *.rh \
+                         *.hrh
+RECURSIVE              = YES
+EXCLUDE                = 
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       = 
+EXAMPLE_PATH           = 
+EXAMPLE_PATTERNS       = 
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             = 
+INPUT_FILTER           = 
+FILTER_PATTERNS        = 
+FILTER_SOURCE_FILES    = NO
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = NO
+INLINE_SOURCES         = NO
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = YES
+REFERENCES_RELATION    = YES
+VERBATIM_HEADERS       = YES
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = NO
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          = 
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = NO
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            = 
+HTML_FOOTER            = 
+HTML_STYLESHEET        = 
+HTML_ALIGN_MEMBERS     = YES
+GENERATE_HTMLHELP      = YES
+CHM_FILE               = 
+HHC_LOCATION           = 
+GENERATE_CHI           = NO
+BINARY_TOC             = YES
+TOC_EXPAND             = YES
+DISABLE_INDEX          = YES
+ENUM_VALUES_PER_LINE   = 4
+GENERATE_TREEVIEW      = YES
+TREEVIEW_WIDTH         = 250
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = NO
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4wide
+EXTRA_PACKAGES         = 
+LATEX_HEADER           = 
+PDF_HYPERLINKS         = NO
+USE_PDFLATEX           = NO
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = YES
+RTF_OUTPUT             = Doc
+COMPACT_RTF            = YES
+RTF_HYPERLINKS         = YES
+RTF_STYLESHEET_FILE    = 
+RTF_EXTENSIONS_FILE    = 
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_SCHEMA             = 
+XML_DTD                = 
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX = 
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor   
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = YES
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           = 
+INCLUDE_FILE_PATTERNS  = 
+PREDEFINED             = NONSHARABLE_CLASS
+EXPAND_AS_DEFINED      = 
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references   
+#---------------------------------------------------------------------------
+TAGFILES               = 
+GENERATE_TAGFILE       = 
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool   
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = YES
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = NO
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+TEMPLATE_RELATIONS     = YES
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+DOT_PATH               = 
+DOTFILE_DIRS           = 
+MAX_DOT_GRAPH_WIDTH    = 1024
+MAX_DOT_GRAPH_HEIGHT   = 1024
+MAX_DOT_GRAPH_DEPTH    = 0
+DOT_TRANSPARENT        = NO
+DOT_MULTI_TARGETS      = NO
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to the search engine   
+#---------------------------------------------------------------------------
+SEARCHENGINE           = NO
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/group/HardCodedTestModuleXXX_nrm.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,75 @@
+/*TYPE HARDCODED*/
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Hardcoded test 
+* module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          HardCodedTestModuleXXX.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+//TARGETPATH      ?target_path
+DEFFILE         HardCodedTestModuleXXX.def
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          HardCodedTestModuleXXX.cpp
+SOURCE          HardCodedTestModuleXXXCases.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// DEFFILE ?filename
+// AIF ?filename// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+PRJ_PLATFORMS
+// specify the platforms your component needs to be built for here
+// defaults to WINS MARM so you can ignore this if you just build these
+
+	DEFAULT
+
+PRJ_TESTEXPORTS
+// NOTE: If using ARS requirements all export operations should be done under this.
+// 'abld test export'
+
+PRJ_EXPORTS
+// Specify the source file followed by its destination here
+// copy will be used to copy the source file to its destination
+// If there's no destination then the source file will be copied
+// to the same name in \epoc32\include
+// Example: 
+/*
+\agnmodel\inc\AGMCOMON.H
+*/
+
+PRJ_TESTMMPFILES
+
+	HardCodedTestModuleXXX.mmp
+
+PRJ_MMPFILES
+
+	HardCodedTestModuleXXX_nrm.mmp
+
+// Specify the .mmp files required for building the important component
+// releasables.
+//
+// Specify "tidy" if the component you need to build doesn't need to be
+// released. Specify "ignore" if the MMP file exists but should be
+// ignored.
+// Example:
+/*
+\agnmodel\group\agnmodel.mmp
+#if defined(MARM)
+\agnmodel\group\agsvexe.mmp
+#endif
+*/
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/inc/HardCodedTestModuleXXX.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,345 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIF hardcoded module declaration
+*
+*/
+
+#ifndef HARDCODEDTESTMODULEXXX_H
+#define HARDCODEDTESTMODULEXXX_H
+
+// INCLUDES
+#include "StifTestModule.h"
+#include <StifLogger.h>
+#include <NormalHardcodedAssert.h>
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+#define TEST_MODULE_VERSION_MAJOR 0
+#define TEST_MODULE_VERSION_MINOR 0
+#define TEST_MODULE_VERSION_BUILD 0
+
+// Logging path
+_LIT( KHardCodedTestModuleXXXLogPath, "\\logs\\testframework\\HardCodedTestModuleXXX\\" ); 
+// Log file
+_LIT( KHardCodedTestModuleXXXLogFile, "HardCodedTestModuleXXX.txt" ); 
+_LIT( KHardCodedTestModuleXXXLogFileWithTitle, "HardCodedTestModuleXXX_[%S].txt" );
+
+#define GETPTR &
+#define ENTRY(str,func) {_S(str), GETPTR func,0,0,0}
+#define FUNCENTRY(func) {_S(#func), GETPTR func,0,0,0}
+#define OOM_ENTRY(str,func,a,b,c) {_S(str), GETPTR func,a,b,c}
+#define OOM_FUNCENTRY(func,a,b,c) {_S(#func), GETPTR func,a,b,c}
+
+// FUNCTION PROTOTYPES
+//?type ?function_name(?arg_list);
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+class CHardCodedTestModuleXXX;
+
+// DATA TYPES
+//enum ?declaration
+//typedef ?declaration
+//extern ?data_type;
+// A typedef for function that does the actual testing,
+// function is a type 
+// TInt CHardCodedTestModuleXXX::<NameOfFunction> ( TTestResult& aResult )
+typedef TInt (CHardCodedTestModuleXXX::* TestFunction)(TTestResult&);
+
+// CLASS DECLARATION
+
+/**
+*  An internal structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TCaseInfoInternal
+    {
+    public:
+        const TText*    iCaseName;
+        TestFunction    iMethod;
+        TBool           iIsOOMTest;
+        TInt            iFirstMemoryAllocation;
+        TInt            iLastMemoryAllocation;
+    };
+
+// CLASS DECLARATION
+
+/**
+*  A structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TCaseInfo
+    {
+    public:
+        TPtrC iCaseName;
+        TestFunction iMethod;
+        TBool           iIsOOMTest;
+        TInt            iFirstMemoryAllocation;
+        TInt            iLastMemoryAllocation;
+
+    TCaseInfo( const TText* a ) : iCaseName( (TText*) a )
+        {
+        };
+
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  This a HardCodedTestModuleXXX class.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS(CHardCodedTestModuleXXX) : public CTestModuleBase
+    {
+    public:  // Constructors and destructor
+
+
+        /**
+        * Two-phased constructor.
+        */
+        static CHardCodedTestModuleXXX* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CHardCodedTestModuleXXX();
+
+    public: // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * From CTestModuleBase InitL is used to initialize the 
+        *       HardCodedTestModuleXXX. It is called once for every instance of 
+        *       TestModuleXXX after its creation.
+        * @since ?Series60_version
+        * @param aIniFile Initialization file for the test module (optional)
+        * @param aFirstTime Flag is true when InitL is executed for first 
+        *               created instance of HardCodedTestModuleXXX.
+        * @return Symbian OS error code
+        */
+        TInt InitL( TFileName& aIniFile, TBool aFirstTime );
+
+        /**
+        * From CTestModuleBase GetTestCasesL is used to inquiry test cases 
+        *   from HardCodedTestModuleXXX. 
+        * @since ?Series60_version
+        * @param aTestCaseFile Test case file (optional)
+        * @param aTestCases  Array of TestCases returned to test framework
+        * @return Symbian OS error code
+        */
+        TInt GetTestCasesL( const TFileName& aTestCaseFile, 
+                            RPointerArray<TTestCaseInfo>& aTestCases );
+
+        /**
+        * From CTestModuleBase RunTestCaseL is used to run an individual 
+        *   test case. 
+        * @since ?Series60_version
+        * @param aCaseNumber Test case number
+        * @param aTestCaseFile Test case file (optional)
+        * @param aResult Test case result returned to test framework (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error, which is 
+        *           not reported in aResult parameter as test case failure).
+        */   
+        TInt RunTestCaseL( const TInt aCaseNumber, 
+                           const TFileName& aTestCaseFile,
+                           TTestResult& aResult );
+
+        /**
+        * From CTestModuleBase; OOMTestQueryL is used to specify is particular
+        * test case going to be executed using OOM conditions
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailureType OOM failure type (optional)
+        * @param aFirstMemFailure The first heap memory allocation failure value (optional)
+        * @param aLastMemFailure The last heap memory allocation failure value (optional)
+        * @return TBool
+        */
+        virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */, 
+                                     const TInt /* aCaseNumber */, 
+                                     TOOMFailureType& aFailureType, 
+                                     TInt& /* aFirstMemFailure */, 
+                                     TInt& /* aLastMemFailure */ );
+
+        /**
+        * From CTestModuleBase; OOMTestInitializeL may be used to initialize OOM
+        * test environment
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        */
+        virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */, 
+                                    const TInt /* aCaseNumber */ ); 
+
+        /**
+        * From CTestModuleBase; OOMHandleWarningL
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailNextValue FailNextValue for OOM test execution (optional)
+        * @return None
+        *
+        * User may add implementation for OOM test warning handling. Usually no
+        * implementation is required.           
+        */
+        virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
+                                        const TInt /* aCaseNumber */, 
+                                        TInt& /* aFailNextValue */); 
+
+        /**
+        * From CTestModuleBase; OOMTestFinalizeL may be used to finalize OOM
+        * test environment
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        *
+        */
+        virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */, 
+                                       const TInt /* aCaseNumber */ );
+        
+        /**
+         * Method used to log version of test module
+         */
+        void SendTestModuleVersion();
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CHardCodedTestModuleXXX();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+        /**
+        * Function returning test case name and pointer to test case function.
+        * @since ?Series60_version
+        * @param aCaseNumber test case number
+        * @return TCaseInfo 
+        */
+        const TCaseInfo Case ( const TInt aCaseNumber ) const;
+
+        /**
+        * [test case declarations] - do not remove
+        */
+        //ADD NEW METHOD DEC HERE"
+
+        /**
+        * Printing test case.
+        * @since ?Series60_version
+        * @param aResult Test case result (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error 
+        *   that is not returned as test case result in aResult)
+        */
+        TInt PrintTest( TTestResult& aResult );
+
+        /**
+        * Printing loop test case.
+        * @since ?Series60_version
+        * @param aResult Test case result (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error 
+        *   that is not returned as test case result in aResult)
+        */
+        TInt LoopTest( TTestResult& aResult );
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+        // Pointer to test (function) to be executed
+        TestFunction iMethod;
+
+        // Pointer to logger
+        CStifLogger * iLog; 
+
+        // Normal logger
+        CStifLogger* iStdLog;
+
+        // Test case logger
+        CStifLogger* iTCLog;
+
+        // Flag saying if test case title should be added to log file name
+        TBool iAddTestCaseTitleToLogName;
+
+        // Flag saying if version of test module was already sent
+        TBool iVersionLogged;
+
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+#endif      // HARDCODEDTESTMODULEXXX_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/src/HardCodedTestModuleXXX.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,441 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains Hardcoded module implementation.
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <StifTestInterface.h>
+#include "HardCodedTestModuleXXX.h"
+#include <SettingServerClient.h>
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::CHardCodedTestModuleXXX
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CHardCodedTestModuleXXX::CHardCodedTestModuleXXX()
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::ConstructL
+// Symbian 2nd phase constructor can leave.
+//
+// Note: If OOM test case uses STIF Logger, then STIF Logger must be created
+// with static buffer size parameter (aStaticBufferSize). Otherwise Logger 
+// allocates memory from heap and therefore causes error situations with OOM 
+// testing. For more information about STIF Logger construction, see STIF Users 
+// Guide.
+// -----------------------------------------------------------------------------
+//
+void CHardCodedTestModuleXXX::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+    iAddTestCaseTitleToLogName = loggerSettings.iAddTestCaseTitle;
+
+    iStdLog = CStifLogger::NewL( KHardCodedTestModuleXXXLogPath, 
+                          KHardCodedTestModuleXXXLogFile);
+    iLog = iStdLog;
+
+    // Sample how to use logging
+    _LIT( KLogStart, "HardCodedTestModuleXXX logging starts!" );
+    iLog->Log( KLogStart );
+
+    iVersionLogged = EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CHardCodedTestModuleXXX* CHardCodedTestModuleXXX::NewL()
+    {
+    CHardCodedTestModuleXXX* self = new (ELeave) CHardCodedTestModuleXXX;
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+// Destructor
+CHardCodedTestModuleXXX::~CHardCodedTestModuleXXX()
+    {
+    iLog = NULL;
+    delete iStdLog;
+    iStdLog = NULL;
+    delete iTCLog;
+    iTCLog = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::InitL
+// InitL is used to initialize the Test Module.
+// -----------------------------------------------------------------------------
+//
+TInt CHardCodedTestModuleXXX::InitL( 
+    TFileName& /*aIniFile*/, 
+    TBool /*aFirstTime*/ )
+    {
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::GetTestCasesL
+// GetTestCases is used to inquire test cases from the Test Module. Test
+// cases are stored to array of test cases. The Test Framework will be 
+// the owner of the data in the RPointerArray after GetTestCases return
+// and it does the memory deallocation. 
+// -----------------------------------------------------------------------------
+//
+TInt CHardCodedTestModuleXXX::GetTestCasesL( 
+    const TFileName& /*aConfig*/, 
+    RPointerArray<TTestCaseInfo>& aTestCases )
+    {
+
+    // Loop through all test cases and create new
+    // TTestCaseInfo items and append items to aTestCase array    
+    for( TInt i = 0; Case(i).iMethod != NULL; i++ )
+        {
+
+        // Allocate new TTestCaseInfo from heap for a testcase definition.
+        TTestCaseInfo* newCase = new( ELeave ) TTestCaseInfo();
+
+        // PushL TTestCaseInfo to CleanupStack.    
+        CleanupStack::PushL( newCase );
+
+        // Set number for the testcase.
+        // When the testcase is run, this comes as a parameter to RunTestCaseL.
+        newCase->iCaseNumber = i;
+
+        // Set title for the test case. This is shown in UI to user.
+        newCase->iTitle.Copy( Case(i).iCaseName );
+
+        // Append TTestCaseInfo to the testcase array. After appended 
+        // successfully the TTestCaseInfo object is owned (and freed) 
+        // by the TestServer. 
+        User::LeaveIfError(aTestCases.Append ( newCase ) );
+
+        // Pop TTestCaseInfo from the CleanupStack.
+        CleanupStack::Pop( newCase );
+
+        }
+
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::RunTestCaseL
+// RunTestCaseL is used to run an individual test case specified 
+// by aTestCase. Test cases that can be run may be requested from 
+// Test Module by GetTestCases method before calling RunTestCase.
+// -----------------------------------------------------------------------------
+//
+TInt CHardCodedTestModuleXXX::RunTestCaseL( 
+    const TInt aCaseNumber,   
+    const TFileName& /*aConfig*/,
+    TTestResult& aResult )
+    {
+    if(!iVersionLogged)
+    	{
+    	SendTestModuleVersion();
+    	iVersionLogged = ETrue;
+    	}
+    
+    // Return value
+    TInt execStatus = KErrNone;
+
+    // Get the pointer to test case function
+    TCaseInfo tmp = Case ( aCaseNumber );
+
+    _LIT( KLogStartTC, "Starting testcase [%S]" );
+    iLog->Log( KLogStartTC, &tmp.iCaseName);
+
+    // Check that case number was valid
+    if ( tmp.iMethod != NULL )
+        {
+        //Open new log file with test case title in file name
+        if(iAddTestCaseTitleToLogName)
+            {
+            //Delete test case logger if exists
+            if(iTCLog)
+                {
+                delete iTCLog;
+                iTCLog = NULL;
+                }
+
+            TFileName logFileName;
+            TName title;
+            TestModuleIf().GetTestCaseTitleL(title);
+        
+            logFileName.Format(KHardCodedTestModuleXXXLogFileWithTitle, &title);
+
+            iTCLog = CStifLogger::NewL(KHardCodedTestModuleXXXLogPath, 
+                                       logFileName);
+            iLog = iTCLog;                                       
+            }
+
+        // Valid case was found, call it via function pointer
+        iMethod = tmp.iMethod;        
+        //execStatus  = ( this->*iMethod )( aResult );
+        TRAPD(err, execStatus  = ( this->*iMethod )( aResult ));
+        if(iAddTestCaseTitleToLogName)
+            {
+            //Restore standard log and destroy test case logger
+            iLog = iStdLog;
+            delete iTCLog; //Close test case log
+            iTCLog = NULL;
+            }
+        User::LeaveIfError(err);
+        }
+    else
+        {
+        // Valid case was not found, return error.
+        execStatus = KErrNotFound;
+        }
+
+    // Return case execution status (not the result of the case execution)
+    return execStatus;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::OOMTestQueryL
+// Used to check if a particular test case should be run in OOM conditions and 
+// which memory allocations should fail.    
+// -----------------------------------------------------------------------------
+//
+TBool CHardCodedTestModuleXXX::OOMTestQueryL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt aCaseNumber, 
+                                TOOMFailureType& /* aFailureType */, 
+                                TInt& aFirstMemFailure, 
+                                TInt& aLastMemFailure ) 
+    {
+    _LIT( KLogOOMTestQueryL, "CHardCodedTestModuleXXX::OOMTestQueryL" );
+    iLog->Log( KLogOOMTestQueryL );     
+
+    aFirstMemFailure = Case( aCaseNumber ).iFirstMemoryAllocation;
+    aLastMemFailure = Case( aCaseNumber ).iLastMemoryAllocation;
+
+    return Case( aCaseNumber ).iIsOOMTest;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::OOMTestInitializeL
+// Used to perform the test environment setup for a particular OOM test case. 
+// Test Modules may use the initialization file to read parameters for Test 
+// Module initialization but they can also have their own configure file or 
+// some other routine to initialize themselves.  
+//
+// NOTE: User may add implementation for OOM test environment initialization.
+// Usually no implementation is required.
+// -----------------------------------------------------------------------------
+//
+void CHardCodedTestModuleXXX::OOMTestInitializeL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt /* aCaseNumber */ )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::OOMHandleWarningL
+// In some cases the heap memory allocation should be skipped, either due to
+// problems in the OS code or components used by the code being tested, or even 
+// inside the tested components which are implemented this way on purpose (by 
+// design), so it is important to give the tester a way to bypass allocation 
+// failures.
+//
+// NOTE: User may add implementation for OOM test warning handling. Usually no
+// implementation is required.
+// -----------------------------------------------------------------------------
+//
+void CHardCodedTestModuleXXX::OOMHandleWarningL( 
+                                const TFileName& /* aTestCaseFile */,
+                                const TInt /* aCaseNumber */, 
+                                TInt& /* aFailNextValue */ )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::OOMTestFinalizeL
+// Used to perform the test environment cleanup for a particular OOM test case.
+//
+// NOTE: User may add implementation for OOM test environment finalization.
+// Usually no implementation is required.
+// -----------------------------------------------------------------------------
+//
+void CHardCodedTestModuleXXX::OOMTestFinalizeL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt /* aCaseNumber */ )
+    {
+    }
+
+//-----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::SendTestModuleVersion
+// Method used to send version of test module
+//-----------------------------------------------------------------------------
+//
+void CHardCodedTestModuleXXX::SendTestModuleVersion()
+	{
+	TVersion moduleVersion;
+	moduleVersion.iMajor = TEST_MODULE_VERSION_MAJOR;
+	moduleVersion.iMinor = TEST_MODULE_VERSION_MINOR;
+	moduleVersion.iBuild = TEST_MODULE_VERSION_BUILD;
+	
+	TFileName moduleName;
+	moduleName = _L("HardCodedTestModuleXXX.dll");
+
+	TBool newVersionOfMethod = ETrue;
+	TestModuleIf().SendTestModuleVersion(moduleVersion, moduleName, newVersionOfMethod);
+	}
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point
+// Returns: CTestModuleBase*: Pointer to Test Module object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CTestModuleBase* LibEntryL()
+    {
+    return CHardCodedTestModuleXXX::NewL();
+
+    }
+
+// -----------------------------------------------------------------------------
+// SetRequirements handles test module parameters(implements evolution
+// version 1 for test module's heap and stack sizes configuring).
+// Returns: TInt: Symbian error code.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt SetRequirements( CTestModuleParam*& /*aTestModuleParam*/, 
+                                TUint32& /*aParameterValid*/ )
+    {
+
+    /* --------------------------------- NOTE ---------------------------------
+    USER PANICS occurs in test thread creation when:
+    1) "The panic occurs when the value of the stack size is negative."
+    2) "The panic occurs if the minimum heap size specified is less
+       than KMinHeapSize".
+       KMinHeapSize: "Functions that require a new heap to be allocated will
+       either panic, or will reset the required heap size to this value if
+       a smaller heap size is specified".
+    3) "The panic occurs if the minimum heap size specified is greater than
+       the maximum size to which the heap can grow".
+    Other:
+    1) Make sure that your hardware or Symbian OS is supporting given sizes.
+       e.g. Hardware might support only sizes that are divisible by four.
+    ------------------------------- NOTE end ------------------------------- */
+
+    // Normally STIF uses default heap and stack sizes for test thread, see:
+    // KTestThreadMinHeap, KTestThreadMinHeap and KStackSize.
+    // If needed heap and stack sizes can be configured here by user. Remove
+    // comments and define sizes.
+
+/*
+    aParameterValid = KStifTestModuleParameterChanged;
+
+    CTestModuleParamVer01* param = CTestModuleParamVer01::NewL();
+    // Stack size
+    param->iTestThreadStackSize= 16384; // 16K stack
+    // Heap sizes
+    param->iTestThreadMinHeap = 4096;   // 4K heap min
+    param->iTestThreadMaxHeap = 1048576;// 1M heap max
+
+    aTestModuleParam = param;
+*/
+    return KErrNone;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/HardCodedTestModuleXXX/src/HardCodedTestModuleXXXCases.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,272 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains hardcoded module implementation.
+*
+*/
+
+
+// [INCLUDE FILES] - do not remove
+#include <e32math.h>
+#include "HardCodedTestModuleXXX.h"
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::Case
+// Returns a test case by number.
+//
+// This function contains an array of all available test cases 
+// i.e pair of case name and test function. If case specified by parameter
+// aCaseNumber is found from array, then that item is returned.
+// 
+// The reason for this rather complicated function is to specify all the
+// test cases only in one place. It is not necessary to understand how
+// function pointers to class member functions works when adding new test
+// cases. See function body for instructions how to add new test case.
+// -----------------------------------------------------------------------------
+//
+const TCaseInfo CHardCodedTestModuleXXX::Case ( 
+    const TInt aCaseNumber ) const 
+     {
+
+    /**
+    * To add new test cases, implement new test case function and add new 
+    * line to KCases array specify the name of the case and the function 
+    * doing the test case
+    * In practice, do following
+    * 1) Make copy of existing test case function and change its name
+    *    and functionality. Note that the function must be added to 
+    *    HardCodedTestModuleXXX.cpp file and to HardCodedTestModuleXXX.h 
+    *    header file.
+    *
+    * 2) Add entry to following KCases array either by using:
+    *
+    * 2.1: FUNCENTRY or ENTRY macro
+    * ENTRY macro takes two parameters: test case name and test case 
+    * function name.
+    *
+    * FUNCENTRY macro takes only test case function name as a parameter and
+    * uses that as a test case name and test case function name.
+    *
+    * Or
+    *
+    * 2.2: OOM_FUNCENTRY or OOM_ENTRY macro. Note that these macros are used
+    * only with OOM (Out-Of-Memory) testing!
+    *
+    * OOM_ENTRY macro takes five parameters: test case name, test case 
+    * function name, TBool which specifies is method supposed to be run using
+    * OOM conditions, TInt value for first heap memory allocation failure and 
+    * TInt value for last heap memory allocation failure.
+    * 
+    * OOM_FUNCENTRY macro takes test case function name as a parameter and uses
+    * that as a test case name, TBool which specifies is method supposed to be
+    * run using OOM conditions, TInt value for first heap memory allocation 
+    * failure and TInt value for last heap memory allocation failure. 
+    */ 
+
+    static TCaseInfoInternal const KCases[] =
+        {
+        // [test cases entries] - do not remove
+        
+        // NOTE: When compiled to GCCE, there must be Classname::
+        // declaration in front of the method name, e.g. 
+        // CHardCodedTestModuleXXX::PrintTest. Otherwise the compiler
+        // gives errors.
+        
+        FUNCENTRY( CHardCodedTestModuleXXX::PrintTest ),
+        ENTRY( "Loop test", CHardCodedTestModuleXXX::LoopTest ),
+        // Example how to use OOM functionality
+        //OOM_ENTRY( "Loop test with OOM", CHardCodedTestModuleXXX::LoopTest, ETrue, 2, 3),
+        //OOM_FUNCENTRY( CHardCodedTestModuleXXX::PrintTest, ETrue, 1, 3 ),
+        };
+
+    // Verify that case number is valid
+    if( (TUint) aCaseNumber >= sizeof( KCases ) / 
+                               sizeof( TCaseInfoInternal ) )
+        {
+        // Invalid case, construct empty object
+        TCaseInfo null( (const TText*) L"" );
+        null.iMethod = NULL;
+        null.iIsOOMTest = EFalse;
+        null.iFirstMemoryAllocation = 0;
+        null.iLastMemoryAllocation = 0;
+        return null;
+        } 
+
+    // Construct TCaseInfo object and return it
+    TCaseInfo tmp ( KCases[ aCaseNumber ].iCaseName );
+    tmp.iMethod = KCases[ aCaseNumber ].iMethod;
+    tmp.iIsOOMTest = KCases[ aCaseNumber ].iIsOOMTest;
+    tmp.iFirstMemoryAllocation = KCases[ aCaseNumber ].iFirstMemoryAllocation;
+    tmp.iLastMemoryAllocation = KCases[ aCaseNumber ].iLastMemoryAllocation;
+    return tmp;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::PrintTest
+// Simple printing to UI test.
+// -----------------------------------------------------------------------------
+//
+TInt CHardCodedTestModuleXXX::PrintTest( 
+    TTestResult& aResult )
+    {
+     /* Simple print test */
+    _LIT( KPrintTest, "PrintTest" );
+    _LIT( KEnter, "Enter" );
+    _LIT( KOnGoing, "On-going" );
+    _LIT( KExit, "Exit" );
+
+    TestModuleIf().Printf( 0, KPrintTest, KEnter );
+           
+    TestModuleIf().Printf( 1, KPrintTest, KOnGoing );
+    
+    TestModuleIf().Printf( 0, KPrintTest, KExit );
+
+    // Test case passed
+
+    // Sets test case result and description(Maximum size is KStifMaxResultDes)
+    _LIT( KDescription, "PrintTest passed" );
+    aResult.SetResult( KErrNone, KDescription );
+
+    // Case was executed
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CHardCodedTestModuleXXX::LoopTest
+// Another printing to UI test.
+// -----------------------------------------------------------------------------
+//
+TInt CHardCodedTestModuleXXX::LoopTest( TTestResult& aResult )
+    {
+
+    /* Simple print and wait loop */
+    _LIT( KState, "State" );
+    _LIT( KLooping, "Looping" );
+
+    TestModuleIf().Printf( 0, KState, KLooping );
+
+    _LIT( KRunning, "Running" );
+    _LIT( KLoop, "%d" );
+    for( TInt i=0; i<10; i++)
+        {
+        TestModuleIf().Printf( 1, KRunning, KLoop, i);
+        User::After( 1000000 );
+        }
+
+    _LIT( KFinished, "Finished" );
+    TestModuleIf().Printf( 0, KState, KFinished );
+
+    // Test case passed
+
+    // Sets test case result and description(Maximum size is KStifMaxResultDes)
+    _LIT( KDescription, "LoopTest passed" );
+    aResult.SetResult( KErrNone, KDescription );
+
+    // Case was executed
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// ?classname::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?classname::?member_function(
+   ?arg_type arg,
+   ?arg_type arg )
+   {
+
+   ?code
+
+   }
+*/
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// ?function_name implements...
+// ?implementation_description.
+// Returns: ?value_1: ?description
+//          ?value_n: ?description
+//                    ?description
+// -----------------------------------------------------------------------------
+//
+/*
+?type  ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg )  // ?description
+    {
+
+    ?code
+
+    }
+*/
+//  [End of File] - do not remove
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/Bmarm/STIFUNITXXXU.DEF	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	LibEntryL__Fv @ 1 NONAME R3UNUSED ; LibEntryL(void)
+	SetRequirements__FRP16CTestModuleParamRUl @ 2 NONAME R3UNUSED ; SetRequirements(CTestModuleParam *&, unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/Bwins/STIFUnitXXXu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	?LibEntryL@@YAPAVCTestModuleBase@@XZ @ 1 NONAME ; class CTestModuleBase * __cdecl LibEntryL(void)
+	?SetRequirements@@YAHAAPAVCTestModuleParam@@AAK@Z @ 2 NONAME ; int __cdecl SetRequirements(class CTestModuleParam * &,unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/CreateSTIFUnitModule.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,112 @@
+::
+:: Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+:: All rights reserved.
+:: This component and the accompanying materials are made available
+:: under the terms of "Eclipse Public License v1.0"
+:: which accompanies this distribution, and is available
+:: at the URL "http://www.eclipse.org/legal/epl-v10.html".
+::
+:: Initial Contributors:
+:: Nokia Corporation - initial contribution.
+::
+:: Contributors:
+:: 
+:: Description: This file contains capsmodifier implementation.
+::
+
+@perl -x CreateSTIFUnitModule.bat %1 %2 %3 %4 %5 %6 %7 %8 %9 
+@goto end
+
+#!perl
+use strict;
+use File::Find;
+
+# Verify command line parameters
+if   ($#ARGV == -1 || $#ARGV > 1 )
+{
+	PrintHelp();
+}
+
+# Take module name
+my $moduleName = $ARGV[0];
+my $MODULENAME = $moduleName;
+$MODULENAME =~ tr/[a-z]/[A-Z]/;
+
+# Take target path or use default
+my $targetPath="\\";
+if ( $#ARGV == 1 )
+{
+	$targetPath = $ARGV[1];
+}
+
+
+# Create directory
+my $targetDir = $targetPath.$moduleName."\\";
+
+print "Starting module creation to $targetDir\n";
+mkdir $targetDir, 0777 || die ("Can't create directory $targetDir");
+
+# Loop through the file structure
+find(\&renamerename, '.');
+
+unlink $targetDir."CreateSTIFUnitModule.bat";
+unlink $targetDir."CreateSTIFUnitModuleVar2.bat";
+print "Module created to $targetDir\n";
+
+# This function will be called for each file or directory
+sub renamerename
+{
+	my $oldName = $_;
+	print "Processing $oldName\n";
+
+	# Construct new filename if that needed
+	s/STIFUnitXXX/$moduleName/i;
+	my $newName = $targetDir.$File::Find::dir."/".$_;  
+
+	# Process directories
+	if (opendir(DIR, $oldName))
+	{
+		closedir (DIR);
+		mkdir $newName, 0777 || die ("Can't create directory $newName");
+		return;
+	}
+                        
+	# Open input file
+	open (INFILE, $oldName ) || die ("Can not find $oldName");
+
+	#Open output file
+	my $newOutput = $newName."new";
+	open (OUTFILE, ">".$newOutput ) || die ("Can not open $newOutput");
+
+	# Replace text in files
+	while (<INFILE>)
+	{
+	  s/STIFUnitXXX/$moduleName/g;
+	  s/STIFUNITXXX/$MODULENAME/g;
+	  s/XXX/$moduleName/g;
+	  s/STIFUnitYYY/$targetDir/g;
+	  print OUTFILE $_;
+	}
+
+	# Close filehandles
+	close (INFILE);
+	close (OUTFILE);
+
+	# Rename result file
+	rename $newOutput,$newName;
+}
+
+sub PrintHelp()
+{
+	print "createSTIFUnitModule ModuleName [path]\n";
+	print "\n";
+	print "Creates a new test module\n";
+	print "If [path] is not given, module is created to root of current drive.\n";
+	print "If [path] is given, it must contain the final \'\\\' in path name.\n";
+	print "Command must be executed in directory where the template exist.\n";
+	exit;
+}
+
+
+__END__
+:end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/CreateSTIFUnitModuleVar2.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,168 @@
+::
+:: Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+:: All rights reserved.
+:: This component and the accompanying materials are made available
+:: under the terms of "Eclipse Public License v1.0"
+:: which accompanies this distribution, and is available
+:: at the URL "http://www.eclipse.org/legal/epl-v10.html".
+::
+:: Initial Contributors:
+:: Nokia Corporation - initial contribution.
+::
+:: Contributors:
+:: 
+:: Description: This file contains capsmodifier implementation.
+::
+
+@perl -x CreateSTIFUnitModule.bat %1 %2 %3 %4 %5 %6 %7 %8 %9 
+@goto end
+
+#!perl
+use strict;
+use File::Find;
+
+# Verify command line parameters
+if   ($#ARGV == -1 || $#ARGV > 1 )
+{
+	PrintHelp();
+}
+
+# Take module name
+my $moduleName = $ARGV[0];
+my $MODULENAME = $moduleName;
+$MODULENAME =~ tr/[a-z]/[A-Z]/;
+
+# Take target path or use default
+my $targetPath="\\";
+if ( $#ARGV == 1 )
+{
+	$targetPath = $ARGV[1];
+}
+
+
+# Create directory
+my $targetDir = $targetPath;
+
+unless(-d $targetDir)
+{
+  die ("Specified target path does not exists. Cannot create test module.\n");
+}
+
+print "Starting module creation to $targetDir\n";
+mkdir $targetDir, 0777 || die ("Can't create directory $targetDir");
+
+# Loop through the file structure
+find(\&renamerename, '.');
+
+unlink $targetDir."CreateSTIFUnitModuleVar2.bat";
+unlink $targetDir."CreateSTIFUnitModule.bat";
+unlink $targetDir."/group/$moduleName"."_nrm.mmp";
+
+ModifyBldInf();
+
+print "Module created to $targetDir\n";
+
+# This function will be called for each file or directory
+sub renamerename
+{
+	my $oldName = $_;
+	print "Processing $oldName\n";
+
+	# Construct new filename if that needed
+	s/STIFUnitXXX/$moduleName/i;
+	my $newName = $targetDir.$File::Find::dir."/".$_;  
+
+	# Process directories
+	if (opendir(DIR, $oldName))
+	{
+		closedir (DIR);
+		mkdir $newName, 0777 || die ("Can't create directory $newName");
+		return;
+	}
+  
+  if (uc($oldName) eq "BLD.INF")
+  {
+    print "Skipping $oldName\n";
+    return;
+  }
+                        
+	# Open input file
+	open (INFILE, $oldName ) || die ("Can not find $oldName");
+
+	#Open output file
+	my $newOutput = $newName."new";
+	open (OUTFILE, ">".$newOutput ) || die ("Can not open $newOutput");
+
+	# Replace text in files
+	while (<INFILE>)
+	{
+	  s/STIFUnitXXX/$moduleName/g;
+	  s/STIFUNITXXX/$MODULENAME/g;
+	  s/XXX/$moduleName/g;
+	  s/STIFUnitYYY/$targetDir/g;
+	  print OUTFILE $_;
+	}
+
+	# Close filehandles
+	close (INFILE);
+	close (OUTFILE);
+
+	# Rename result file
+	rename $newOutput,$newName;
+}
+
+sub ModifyBldInf()
+{
+  print "Modifying bld.inf of existing project\n";
+  my $bldName = $targetDir."group/Bld.inf";
+  my $newBldName = $targetDir."group/Bld.inf.new";
+  my $found = 0;
+  
+  open INFILE, $bldName or die "Cannot open $bldName: $!";
+  open (OUTFILE, ">".$newBldName) or die "Cannot create $newBldName: $!";
+  
+  while (<INFILE>) 
+  {
+    print OUTFILE $_ unless /^warning:/i;
+    if ($found eq 0 && trim(uc($_)) eq "PRJ_TESTMMPFILES")
+    {
+      print OUTFILE "$moduleName.mmp\n";
+      $found = 1;
+    }
+  }
+  if($found eq 0)
+  {
+    print OUTFILE "PRJ_TESTMMPFILES\n$moduleName.mmp\n";
+  }
+  
+  close INFILE;
+  close OUTFILE;
+  
+  rename $bldName, "$bldName.old" or die "Could not rename $bldName to $bldName.old\n";
+  rename $newBldName, $bldName or die "Could not rename $newBldName to $bldName\n";
+  
+  print "Bld.inf file has been modified.\n";
+  print "Original file is stored as $bldName.old\n";
+}
+
+sub PrintHelp()
+{
+	print "createSTIFUnitModule ModuleName [path]\n";
+	print "\n";
+	print "Creates a new test module\n";
+	print "If [path] is not given, module is created to root of current drive.\n";
+	print "If [path] is given, it must contain the final \'\\\' in path name.\n";
+	print "Command must be executed in directory where the template exist.\n";
+	exit;
+}
+
+sub trim($)
+{
+	my $string = shift;
+	$string =~ s/^\s+//;
+	$string =~ s/\s+$//;
+	return $string;
+}
+
+__END__
+:end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/eabi/STIFUNITXXXu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	_Z9LibEntryLv @ 1 NONAME
+	_Z15SetRequirementsRP16CTestModuleParamRm @ 2 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/group/STIFUnitXXX.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,73 @@
+/*TYPE STIFUNIT*/
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's STIFUnit test module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          STIFUnitXXX.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+//TARGETPATH      ?target_path
+DEFFILE         STIFUnitXXX.def
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          STIFUnitXXX.cpp
+SOURCE          STIFUnitXXXCases.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// DEFFILE ?filename
+// AIF ?filename// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/group/STIFUnitXXX.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+; 
+; Description:
+;
+; 	Installation file for STIF
+;
+
+; Languages
+&EN
+
+; Provide value for uid
+#{"STIF"},(0x00000000),1,1,0,TYPE=SA
+
+; Series60 product id for S60 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Logo
+; None
+
+; Package signature - Optional
+; None
+
+; Start of Package body
+
+; Condition blocks
+; None
+
+; Options list
+; None
+
+; Install files
+"\epoc32\release\armv5\udeb\STIFUnitXXX.dll"   -   "!:\Sys\Bin\STIFUnitXXX.dll"
+  
+; Embedded SIS 
+; None
+
+; End of Package body
+
+; PKG dependencies
+; None
+
+; PKG capabilities
+; None
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/group/STIFUnitXXX_nrm.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,75 @@
+/*TYPE STIFUNIT*/
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's STIFUnit test 
+* module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          STIFUnitXXX.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+//TARGETPATH      ?target_path
+DEFFILE         STIFUnitXXX.def
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+
+SOURCE          STIFUnitXXX.cpp
+SOURCE          STIFUnitXXXCases.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// DEFFILE ?filename
+// AIF ?filename// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+PRJ_PLATFORMS
+// specify the platforms your component needs to be built for here
+// defaults to WINS MARM so you can ignore this if you just build these
+
+	DEFAULT
+
+PRJ_TESTEXPORTS
+// NOTE: If using ARS requirements all export operations should be done under this.
+// 'abld test export'
+
+PRJ_EXPORTS
+// Specify the source file followed by its destination here
+// copy will be used to copy the source file to its destination
+// If there's no destination then the source file will be copied
+// to the same name in \epoc32\include
+// Example: 
+/*
+\agnmodel\inc\AGMCOMON.H
+*/
+
+PRJ_TESTMMPFILES
+
+	STIFUnitXXX.mmp
+
+PRJ_MMPFILES
+
+	STIFUnitXXX_nrm.mmp
+
+// Specify the .mmp files required for building the important component
+// releasables.
+//
+// Specify "tidy" if the component you need to build doesn't need to be
+// released. Specify "ignore" if the MMP file exists but should be
+// ignored.
+// Example:
+/*
+\agnmodel\group\agnmodel.mmp
+#if defined(MARM)
+\agnmodel\group\agsvexe.mmp
+#endif
+*/
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/src/STIFUnitXXX.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,124 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains STIFUnit module implementation.
+*
+*/
+
+/******************************************************************************/
+/*
+ *
+ * Test module configuration 
+*/
+
+// Version
+#define TEST_MODULE_VERSION_MAJOR 0
+#define TEST_MODULE_VERSION_MINOR 0
+#define TEST_MODULE_VERSION_BUILD 0
+
+// Uncomment following defines, if you want to provide implementation
+// of enlisted virtual methods of test module.
+// Implementation part is located at the end of this file.
+//#define STIFUNIT_OOMTESTQUERYL
+//#define STIFUNIT_OOMTESTINITIALIZEL
+//#define STIFUNIT_OOMHANDLEWARNINGL
+//#define STIFUNIT_OOMTESTFINALIZEL
+// Uncomment following define, if you want to increase heap or stack size.
+// #define STIFUNIT_SETHEAPANDSTACKSIZE
+/******************************************************************************/
+
+
+/*
+ * Test module internals. Please do not edit them. 
+*/
+
+// Includes
+#include <e32base.h>
+
+// Literals
+_LIT( KUnitLogPath, "\\logs\\testframework\\STIFUnitXXX\\" ); 
+_LIT( KUnitLogFile, "STIFUnitXXX.txt" ); 
+_LIT( KLogStart, "STIFUnitXXX logging starts!" );
+
+// Defines
+#define STIF_UNIT_TEST_CASES "../src/STIFUnitXXXCases.cpp"
+#define STIF_UNIT_MODULE_CLASS_NAME CSTIFUnitXXX
+#define STIF_UNIT_MODULE_NAME _L("STIFUnitXXX.dll")
+
+// Include STIF unit generic file
+#include <StifUnitGeneric.h>
+
+/*
+ * Implementation of setHeapAndStack virtual methods.
+ * To changes heap and stack size provide new values to iTestThreadStackSize, iTestThreadMinHeap and iTestThreadMaxHeap. 
+*/
+
+#ifdef STIFUNIT_SETHEAPANDSTACKSIZE
+EXPORT_C TInt SetRequirements( CTestModuleParam*& aTestModuleParam, 
+                               TUint32& aParameterValid )
+    {
+    aParameterValid = KStifTestModuleParameterChanged;
+    CTestModuleParamVer01* param = CTestModuleParamVer01::NewL(); 
+    // Stack size 
+    param->iTestThreadStackSize= 16384; // 16K stack 
+    // Heap sizes 
+    param->iTestThreadMinHeap = 4096; // 4K heap min 
+    param->iTestThreadMaxHeap = 1048576;// 1M heap max 
+
+    return KErrNone;
+    }
+#undef STIFUNIT_SETHEAPANDSTACKSIZE
+#endif
+
+/*
+ * User implementation of OOM virtual methods.
+ * Providing own implementation requires uncommenting defines at the
+ * beginnig of this file.   
+*/
+#ifdef STIFUNIT_OOMTESTQUERYL
+TBool CSTIFUnitXXX::OOMTestQueryL( const TFileName& /*aTestCaseFile*/, 
+                                   const TInt aCaseNumber, 
+                                   TOOMFailureType& aFailureType, 
+                                   TInt& aFirstMemFailure, 
+                                   TInt& aLastMemFailure)
+    {
+    }
+#undef STIFUNIT_OOMTESTQUERYL
+#endif
+
+#ifdef STIFUNIT_OOMTESTINITIALIZEL
+void CSTIFUnitXXX::OOMTestInitializeL( const TFileName& /*aTestCaseFile*/, 
+                                       const TInt /*aCaseNumber*/ )
+    {
+    }
+#undef STIFUNIT_OOMTESTINITIALIZEL
+#endif
+
+#ifdef STIFUNIT_OOMHANDLEWARNINGL
+void CSTIFUnitXXX::OOMHandleWarningL( const TFileName& /*aTestCaseFile*/,
+                                      const TInt /*aCaseNumber*/, 
+                                      TInt& /*aFailNextValue*/)
+    {
+    }
+#undef STIFUNIT_OOMHANDLEWARNINGL
+#endif
+    
+#ifdef STIFUNIT_OOMTESTFINALIZEL
+void CSTIFUnitXXX::OOMTestFinalizeL( const TFileName& /*aTestCaseFile*/, 
+                                     const TInt /*aCaseNumber*/ )
+    {
+    }
+#undef STIFUNIT_OOMTESTFINALIZEL
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/STIFUnitXXX/src/STIFUnitXXXCases.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,90 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains STIFUnit implementation.
+*
+*/
+
+/**
+ * STIF_UNIT_INCLUDE SECTION - put all #includes between STIF_UNIT_INCLUDE_SECTION
+ *                             and STIF_UNIT_INCLUDE_SECTION_END
+ */
+#ifdef STIF_UNIT_INCLUDE_SECTION
+ 
+
+#endif //STIF_UNIT_INCLUDE_SECTION_END
+
+/**
+ * GLOBAL VARIABLES SECTION
+ */
+#ifdef TEST_VAR_DECLARATIONS
+	/**
+	 * Example of variable common for some test cases
+	 */
+	 RBuf buffer;
+	 
+#endif
+/**
+ * END OF GLOBAL VARIABLES SECTION
+ */
+
+
+/**
+ * TEST CASES SECTION
+ */
+#ifdef TEST_CASES
+/**
+ * STIF_SETUP defines activities needed before every test case.
+ */
+STIF_SETUP
+{
+	/** Example of use of STIF_SETUP - a variable common for some test cases is initialized
+	 */
+	buffer.CreateL(5);
+	buffer.CleanupClosePushL();
+}
+
+/**
+ * STIF_TEARDOWN defines activities needed after every test case
+ */
+STIF_TEARDOWN
+{
+	/** Example of use of STIF_TEARDOWN - a variable common for some test cases is destroyed
+	 */
+	CleanupStack::PopAndDestroy();	
+}
+
+/**
+ * STIF_TESTDEFINE defines a test case
+ *
+ *  Example test case - length of string is checked.
+ *  The only argument of macro is a name of test case.
+ */
+STIF_TESTDEFINE(test1)
+{
+	_LIT(KHello, "Hello");
+	buffer.Copy(KHello());
+	buffer.ReAllocL(11);
+
+	_LIT(KWorld, " World");
+	buffer.Append(KWorld);
+	
+	STIF_ASSERT_EQUALS(buffer.Length(), 11);
+}
+
+#endif
+/**
+ * END OF TEST CASES SECTION
+ */
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/CreateKernelTestClass.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,111 @@
+::
+:: Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+:: All rights reserved.
+:: This component and the accompanying materials are made available
+:: under the terms of "Eclipse Public License v1.0"
+:: which accompanies this distribution, and is available
+:: at the URL "http://www.eclipse.org/legal/epl-v10.html".
+::
+:: Initial Contributors:
+:: Nokia Corporation - initial contribution.
+::
+:: Contributors:
+:: 
+:: Description: This file contains capsmodifier implementation.
+::
+
+@perl -x CreateKernelTestClass.bat %1 %2 %3 %4 %5 %6 %7 %8 %9 
+@goto end
+
+#!perl
+use strict;
+use File::Find;
+
+# Verify command line parameters
+if   ($#ARGV == -1 || $#ARGV > 1 )
+{
+	PrintHelp();
+}
+
+# Take module name
+my $moduleName = $ARGV[0];
+my $MODULENAME = $moduleName;
+$MODULENAME =~ tr/[a-z]/[A-Z]/;
+
+# Take target path or use default
+my $targetPath="\\";
+if ( $#ARGV == 1 )
+{
+	$targetPath = $ARGV[1];
+}
+
+
+# Create directory
+my $targetDir = $targetPath.$moduleName."\\";
+
+print "Starting module creation to $targetDir\n";
+mkdir $targetDir, 0777 || die ("Can't create directory $targetDir");
+
+# Loop through the file structure
+find(\&renamerename, '.');
+
+unlink $targetDir."CreateKernelTestClass.bat";
+print "Module created to $targetDir\n";
+
+# This function will be called for each file or directory
+sub renamerename
+{
+	my $oldName = $_;
+	print "Processing $oldName\n";
+
+	# Construct new filename if that needed
+	s/TemplateKernelScriptXXX/$moduleName/i;
+	my $newName = $targetDir.$File::Find::dir."/".$_;  
+
+	# Process directories
+	if (opendir(DIR, $oldName))
+	{
+		closedir (DIR);
+		mkdir $newName, 0777 || die ("Can't create directory $newName");
+		return;
+	}
+                        
+	# Open input file
+	open (INFILE, $oldName ) || die ("Can not find $oldName");
+
+	#Open output file
+	my $newOutput = $newName."new";
+	open (OUTFILE, ">".$newOutput ) || die ("Can not open $newOutput");
+
+	# Replace text in files
+	while (<INFILE>)
+	{
+	  s/TemplateKernelScriptXXX/$moduleName/g;
+	  s/TEMPLATEKERNELSCRIPTXXX/$MODULENAME/g;
+	  s/XXX/$moduleName/g;
+	  s/TemplateKernelScriptTargetDirYYY/$targetDir/g;
+	  print OUTFILE $_;
+	}
+
+	# Close filehandles
+	close (INFILE);
+	close (OUTFILE);
+
+	# Rename result file
+	rename $newOutput,$newName;
+}
+
+sub PrintHelp()
+{
+	print "CreateScriptModule ScriptModuleName [path]\n";
+	print "\n";
+	print "Creates a new test module\n";
+	print "If [path] is not given, module is created to root of current drive.\n";
+	print "If [path] is given, it must contain the final \'\\\' in path name.\n";
+	print "Command must be executed in directory where the template exist.\n";
+	exit;
+}
+
+
+__END__
+:end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/conf/TemplateKernelScriptXXX.cfg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,8 @@
+[Test]
+title Example
+createkernel TemplateKernelScriptXXX foobar
+foobar Example pa ra me ters
+delete foobar
+[Endtest] 
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/group/TemplateKernelScriptXXX.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Kernel testclass 
+* test module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+#include        "kernel/kern_ext.mmh"
+
+SMPSAFE
+
+CAPABILITY      ALL
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+
+TARGET          TemplateKernelScriptXXX.ldd
+TARGETTYPE      ldd
+UID             0x100000af 0x101FB3E3
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          TemplateKernelScriptXXX.cpp
+SOURCE          TemplateKernelScriptXXXBlocks.cpp
+
+LIBRARY         ekern.lib
+
+
+LIBRARY         StifKernelTestClassBase.lib
+
+LANG            SC
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/group/TemplateKernelScriptXXX.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+; 
+; Description:
+;
+; 	Installation file for STIF
+;
+
+; Languages
+&EN
+
+; Provide value for uid
+#{"STIF"},(0x00000000),1,1,0,TYPE=SA
+
+; Series60 product id for S60 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Logo
+; None
+
+; Package signature - Optional
+; None
+
+; Start of Package body
+
+; Condition blocks
+; None
+
+; Options list
+; None
+
+; Install files
+"\epoc32\release\armv5_abiv2\udeb\TemplateKernelScriptXXX.ldd"   -   "!:\Sys\Bin\TemplateKernelScriptXXX.ldd"
+  
+; Embedded SIS 
+; None
+
+; End of Package body
+
+; PKG dependencies
+; None
+
+; PKG capabilities
+; None
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/group/TemplateKernelScriptXXX_DoxyFile.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,240 @@
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+#
+# Contributors:
+# 
+# Description:
+#
+#
+
+# Doxyfile 1.4.1
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+PROJECT_NAME           = TemplateKernelScriptXXX
+PROJECT_NUMBER         = 
+OUTPUT_DIRECTORY       = TemplateKernelScriptTargetDirYYY
+CREATE_SUBDIRS         = NO
+OUTPUT_LANGUAGE        = English
+USE_WINDOWS_ENCODING   = YES
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       = 
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = NO
+STRIP_FROM_PATH        = 
+STRIP_FROM_INC_PATH    = 
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = NO
+MULTILINE_CPP_IS_BRIEF = NO
+DETAILS_AT_TOP         = NO
+INHERIT_DOCS           = YES
+DISTRIBUTE_GROUP_DOC   = NO
+TAB_SIZE               = 8
+ALIASES                = 
+OPTIMIZE_OUTPUT_FOR_C  = YES
+OPTIMIZE_OUTPUT_JAVA   = NO
+SUBGROUPING            = YES
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = YES
+EXTRACT_PRIVATE        = NO
+EXTRACT_STATIC         = NO
+EXTRACT_LOCAL_CLASSES  = NO
+EXTRACT_LOCAL_METHODS  = NO
+HIDE_UNDOC_MEMBERS     = NO
+HIDE_UNDOC_CLASSES     = NO
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = YES
+CASE_SENSE_NAMES       = YES
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_BY_SCOPE_NAME     = NO
+GENERATE_TODOLIST      = NO
+GENERATE_TESTLIST      = NO
+GENERATE_BUGLIST       = NO
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       = 
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_DIRECTORIES       = YES
+FILE_VERSION_FILTER    = 
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           = 
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  = TemplateKernelScriptTargetDirYYY
+FILE_PATTERNS          = *.h \
+                         *.rh \
+                         *.hrh
+RECURSIVE              = YES
+EXCLUDE                = 
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       = 
+EXAMPLE_PATH           = 
+EXAMPLE_PATTERNS       = 
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             = 
+INPUT_FILTER           = 
+FILTER_PATTERNS        = 
+FILTER_SOURCE_FILES    = NO
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = NO
+INLINE_SOURCES         = NO
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = YES
+REFERENCES_RELATION    = YES
+VERBATIM_HEADERS       = YES
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = NO
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          = 
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = NO
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            = 
+HTML_FOOTER            = 
+HTML_STYLESHEET        = 
+HTML_ALIGN_MEMBERS     = YES
+GENERATE_HTMLHELP      = YES
+CHM_FILE               = 
+HHC_LOCATION           = 
+GENERATE_CHI           = NO
+BINARY_TOC             = YES
+TOC_EXPAND             = YES
+DISABLE_INDEX          = YES
+ENUM_VALUES_PER_LINE   = 4
+GENERATE_TREEVIEW      = YES
+TREEVIEW_WIDTH         = 250
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = NO
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4wide
+EXTRA_PACKAGES         = 
+LATEX_HEADER           = 
+PDF_HYPERLINKS         = NO
+USE_PDFLATEX           = NO
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = YES
+RTF_OUTPUT             = Doc
+COMPACT_RTF            = YES
+RTF_HYPERLINKS         = YES
+RTF_STYLESHEET_FILE    = 
+RTF_EXTENSIONS_FILE    = 
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_SCHEMA             = 
+XML_DTD                = 
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX = 
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor   
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = YES
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           = 
+INCLUDE_FILE_PATTERNS  = 
+PREDEFINED             = NONSHARABLE_CLASS
+EXPAND_AS_DEFINED      = 
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references   
+#---------------------------------------------------------------------------
+TAGFILES               = 
+GENERATE_TAGFILE       = 
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool   
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = YES
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = NO
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+TEMPLATE_RELATIONS     = YES
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+DOT_PATH               = 
+DOTFILE_DIRS           = 
+MAX_DOT_GRAPH_WIDTH    = 1024
+MAX_DOT_GRAPH_HEIGHT   = 1024
+MAX_DOT_GRAPH_DEPTH    = 0
+DOT_TRANSPARENT        = NO
+DOT_MULTI_TARGETS      = NO
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to the search engine   
+#---------------------------------------------------------------------------
+SEARCHENGINE           = NO
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/group/TemplateKernelScriptXXX_nrm.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Kernel testclass 
+* module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+#include        "kernel/kern_ext.mmh"
+
+SMPSAFE
+
+CAPABILITY      ALL
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+
+TARGET          TemplateKernelScriptXXX.ldd
+TARGETTYPE      ldd
+UID             0x100000af 0x101FB3E3
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          TemplateKernelScriptXXX.cpp
+SOURCE          TemplateKernelScriptXXXBlocks.cpp
+
+LIBRARY         ekern.lib
+
+
+LIBRARY         StifKernelTestClassBase.lib
+
+LANG            SC
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,64 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+//
+// TO DO: (mandatory)
+//
+// Add here a definition for your port (as declared in E32PLAT.PM)
+//
+// WINSCW added for debugging test programs
+PRJ_PLATFORMS
+
+	WINSCW
+
+PRJ_TESTEXPORTS
+// NOTE: If using ARS requirements all export operations should be done under this.
+// 'abld test export'
+
+PRJ_EXPORTS
+// Specify the source file followed by its destination here
+// copy will be used to copy the source file to its destination
+// If there's no destination then the source file will be copied
+// to the same name in \epoc32\include
+// Example: 
+/*
+\agnmodel\inc\AGMCOMON.H
+*/
+
+PRJ_TESTMMPFILES
+
+	TemplateKernelScriptXXX.mmp
+
+PRJ_MMPFILES
+
+	TemplateKernelScriptXXX_nrm.mmp
+
+// Specify the .mmp files required for building the important component
+// releasables.
+//
+// Specify "tidy" if the component you need to build doesn't need to be
+// released. Specify "ignore" if the MMP file exists but should be
+// ignored.
+// Example:
+/*
+\agnmodel\group\agnmodel.mmp
+#if defined(MARM)
+\agnmodel\group\agsvexe.mmp
+#endif
+*/
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/inc/TemplateKernelScriptXXX.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,103 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: Kernel testclass declaration
+*
+*/
+
+#ifndef TEMPLATEKERNELSCRIPTXXX_H
+#define TEMPLATEKERNELSCRIPTXXX_H
+
+//  INCLUDES
+#include <StifKernelTestClassBase.h>
+
+// CONSTANTS
+
+// MACROS
+_LIT( KDriverName, "TemplateKernelScriptXXX" );
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// DATA TYPES
+
+// CLASS DECLARATION
+
+// CLASS DECLARATION
+
+/**
+* DTemplateKernelScriptXXXDriver is the device driver factory that will
+* instantiate the physical channel, which is the actual
+* physical driver.
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class DTemplateKernelScriptXXXDriver : public DStifKernelTestClassBaseDriver
+    {
+
+    public:
+        DTemplateKernelScriptXXXDriver( const TDesC& aName ) :
+            DStifKernelTestClassBaseDriver( aName ){};
+
+    public:
+
+        // Logical Channel creation
+        TInt Create(DLogicalChannelBase*& aChannel);
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  DTemplateKernelScriptXXX is a kernel test class 
+*  for STIF Test Framework TestScripter.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class DTemplateKernelScriptXXX : public DStifKernelTestClassBase
+    {
+
+    public:
+        DTemplateKernelScriptXXX( DLogicalDevice* aDevice ) : 
+            DStifKernelTestClassBase( aDevice ){};
+        ~DTemplateKernelScriptXXX(){};
+
+    public:
+        // Derived class must implement, runs a script line        
+        TInt RunMethodL( const TDesC& aMethod, const TDesC& aParams );  
+
+        // Second phase constructor for DLogicalChannelBase object in EKA2
+        virtual TInt DoCreate( TInt aUnit, const TDesC8* aInfo, const TVersion& aVer );
+
+        // Called from destructor.
+        void Delete();
+
+    protected: 
+
+    private:
+        /**
+        * Test methods.
+        */
+        TInt ExampleL( const TDesC& aParams );
+
+    private:
+
+    };
+
+#endif      // TEMPLATEKERNELSCRIPTXXX_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/src/TemplateKernelScriptXXX.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,82 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains kernel testclass implementation.
+*
+*/
+
+// INCLUDE FILES
+#include "TemplateKernelScriptXXX.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// TInt DTSKernelTestDriver::Create(DLogicalChannelBase*& aChannel)
+// Creates the Logical Channel in EKA2
+// -----------------------------------------------------------------------------
+//
+TInt DTemplateKernelScriptXXXDriver::Create(DLogicalChannelBase*& aChannel)
+    {
+    aChannel = new DTemplateKernelScriptXXX( this );
+    return aChannel?KErrNone:KErrNoMemory;
+
+    }
+
+// -----------------------------------------------------------------------------
+// TInt DTSKernelTest::DoCreate
+// Second phase constructor for DLogicalChannelBase object in EKA2
+// -----------------------------------------------------------------------------
+//
+TInt DTemplateKernelScriptXXX::DoCreate( TInt /* aUnit */, 
+                                         const TDesC8* /* anInfo */, 
+                                         const TVersion& /* aVer */ )
+    {   
+    SetDfcQ(Kern::DfcQue0());
+    iMsgQ.Receive();
+
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// DECLARE_STANDARD_LDD()
+// EKA2 entry point
+// -----------------------------------------------------------------------------
+//
+DECLARE_STANDARD_LDD()
+    {
+    return new DTemplateKernelScriptXXXDriver( KDriverName );
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateKernelScriptXXX/src/TemplateKernelScriptXXXBlocks.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,146 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains kernel testclass implementation.
+*
+*/
+
+// INCLUDE FILES
+#include "TemplateKernelScriptXXX.h"
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// DTemplateKernelScriptXXX::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void DTemplateKernelScriptXXX::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// DTemplateKernelScriptXXX::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// 
+// Note that in EKA2 methods cannot leave and therefore RunMethodL isn't leaving 
+// function dispite of its name!    
+// -----------------------------------------------------------------------------
+//
+TInt DTemplateKernelScriptXXX::RunMethodL( 
+    const TDesC& aMethod, 
+    const TDesC& aParams )  
+    {
+
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+        ENTRY( "Example", DTemplateKernelScriptXXX::ExampleL ),
+
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aMethod, aParams );
+
+    }
+
+// -----------------------------------------------------------------------------
+// DTemplateKernelScriptXXX::ExampleL
+// Example test method function.
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+TInt DTemplateKernelScriptXXX::ExampleL( 
+    const TDesC& aParams )
+    {
+    Kern::Printf( ("DTemplateKernelScriptXXX::ExampleL(%S)"), &aParams );             
+
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// DTemplateKernelScriptXXX::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+/*
+TInt DTemplateKernelScriptXXX::?member_function(
+   const TDesC& aParams )
+   {
+
+   ?code
+
+   }
+*/
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/Bmarm/TEMPLATESCRIPTXXXU.DEF	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FR13CTestModuleIf @ 1 NONAME R3UNUSED ; LibEntryL(CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/Bwins/TemplateScriptXXXu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCScriptBase@@AAVCTestModuleIf@@@Z @ 1 NONAME ; class CScriptBase * __cdecl LibEntryL(class CTestModuleIf &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/CreateTestClass.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,111 @@
+::
+:: Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+:: All rights reserved.
+:: This component and the accompanying materials are made available
+:: under the terms of "Eclipse Public License v1.0"
+:: which accompanies this distribution, and is available
+:: at the URL "http://www.eclipse.org/legal/epl-v10.html".
+::
+:: Initial Contributors:
+:: Nokia Corporation - initial contribution.
+::
+:: Contributors:
+:: 
+:: Description: This file contains capsmodifier implementation.
+::
+
+@perl -x createtestclass.bat %1 %2 %3 %4 %5 %6 %7 %8 %9 
+@goto end
+
+#!perl
+use strict;
+use File::Find;
+
+# Verify command line parameters
+if   ($#ARGV == -1 || $#ARGV > 1 )
+{
+	PrintHelp();
+}
+
+# Take module name
+my $moduleName = $ARGV[0];
+my $MODULENAME = $moduleName;
+$MODULENAME =~ tr/[a-z]/[A-Z]/;
+
+# Take target path or use default
+my $targetPath="\\";
+if ( $#ARGV == 1 )
+{
+	$targetPath = $ARGV[1];
+}
+
+
+# Create directory
+my $targetDir = $targetPath.$moduleName."\\";
+
+print "Starting module creation to $targetDir\n";
+mkdir $targetDir, 0777 || die ("Can't create directory $targetDir");
+
+# Loop through the file structure
+find(\&renamerename, '.');
+
+unlink $targetDir."CreateTestClass.bat";
+print "Module created to $targetDir\n";
+
+# This function will be called for each file or directory
+sub renamerename
+{
+	my $oldName = $_;
+	print "Processing $oldName\n";
+
+	# Construct new filename if that needed
+	s/TemplateScriptXXX/$moduleName/i;
+	my $newName = $targetDir.$File::Find::dir."/".$_;  
+
+	# Process directories
+	if (opendir(DIR, $oldName))
+	{
+		closedir (DIR);
+		mkdir $newName, 0777 || die ("Can't create directory $newName");
+		return;
+	}
+                        
+	# Open input file
+	open (INFILE, $oldName ) || die ("Can not find $oldName");
+
+	#Open output file
+	my $newOutput = $newName."new";
+	open (OUTFILE, ">".$newOutput ) || die ("Can not open $newOutput");
+
+	# Replace text in files
+	while (<INFILE>)
+	{
+	  s/TemplateScriptXXX/$moduleName/g;
+	  s/TEMPLATESCRIPTXXX/$MODULENAME/g;
+	  s/XXX/$moduleName/g;
+	  s/TemplateScriptTargetDirYYY/$targetDir/g;
+	  print OUTFILE $_;
+	}
+
+	# Close filehandles
+	close (INFILE);
+	close (OUTFILE);
+
+	# Rename result file
+	rename $newOutput,$newName;
+}
+
+sub PrintHelp()
+{
+	print "CreateScriptModule ScriptModuleName [path]\n";
+	print "\n";
+	print "Creates a new test module\n";
+	print "If [path] is not given, module is created to root of current drive.\n";
+	print "If [path] is given, it must contain the final \'\\\' in path name.\n";
+	print "Command must be executed in directory where the template exist.\n";
+	exit;
+}
+
+
+__END__
+:end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/conf/TemplateScriptXXX.cfg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,8 @@
+[Test]
+title Example
+create TemplateScriptXXX foobar
+foobar Example pa ra me ters
+delete foobar
+[Endtest] 
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/eabi/TemplateScriptXXXu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLR13CTestModuleIf @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/group/TemplateScriptXXX.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,77 @@
+/*TYPE TESTCLASS*/
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestScripter 
+* testclass test module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          TemplateScriptXXX.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+//TARGETPATH      ?target_path
+DEFFILE         TemplateScriptXXX.def
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          TemplateScriptXXX.cpp
+SOURCE          TemplateScriptXXXBlocks.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// DEFFILE ?filename
+// AIF ?filename
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/group/TemplateScriptXXX.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+; 
+; Description:
+;
+; 	Installation file for STIF
+;
+
+; Languages
+&EN
+
+; Provide value for uid
+#{"STIF"},(0x00000000),1,1,0,TYPE=SA
+
+; Series60 product id for S60 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Logo
+; None
+
+; Package signature - Optional
+; None
+
+; Start of Package body
+
+; Condition blocks
+; None
+
+; Options list
+; None
+
+; Install files
+"\epoc32\release\armv5\udeb\TemplateScriptXXX.dll"   -   "!:\Sys\Bin\TemplateScriptXXX.dll"
+  
+; Embedded SIS 
+; None
+
+; End of Package body
+
+; PKG dependencies
+; None
+
+; PKG capabilities
+; None
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/group/TemplateScriptXXX_DoxyFile.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,240 @@
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+#
+# Contributors:
+# 
+# Description:
+#
+#
+
+# Doxyfile 1.4.1
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+PROJECT_NAME           = TemplateScriptXXX
+PROJECT_NUMBER         = 
+OUTPUT_DIRECTORY       = TemplateScriptTargetDirYYY
+CREATE_SUBDIRS         = NO
+OUTPUT_LANGUAGE        = English
+USE_WINDOWS_ENCODING   = YES
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       = 
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = NO
+STRIP_FROM_PATH        = 
+STRIP_FROM_INC_PATH    = 
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = NO
+MULTILINE_CPP_IS_BRIEF = NO
+DETAILS_AT_TOP         = NO
+INHERIT_DOCS           = YES
+DISTRIBUTE_GROUP_DOC   = NO
+TAB_SIZE               = 8
+ALIASES                = 
+OPTIMIZE_OUTPUT_FOR_C  = YES
+OPTIMIZE_OUTPUT_JAVA   = NO
+SUBGROUPING            = YES
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = YES
+EXTRACT_PRIVATE        = NO
+EXTRACT_STATIC         = NO
+EXTRACT_LOCAL_CLASSES  = NO
+EXTRACT_LOCAL_METHODS  = NO
+HIDE_UNDOC_MEMBERS     = NO
+HIDE_UNDOC_CLASSES     = NO
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = YES
+CASE_SENSE_NAMES       = YES
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_BY_SCOPE_NAME     = NO
+GENERATE_TODOLIST      = NO
+GENERATE_TESTLIST      = NO
+GENERATE_BUGLIST       = NO
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       = 
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_DIRECTORIES       = YES
+FILE_VERSION_FILTER    = 
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           = 
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  = TemplateScriptTargetDirYYY
+FILE_PATTERNS          = *.h \
+                         *.rh \
+                         *.hrh
+RECURSIVE              = YES
+EXCLUDE                = 
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       = 
+EXAMPLE_PATH           = 
+EXAMPLE_PATTERNS       = 
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             = 
+INPUT_FILTER           = 
+FILTER_PATTERNS        = 
+FILTER_SOURCE_FILES    = NO
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = NO
+INLINE_SOURCES         = NO
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = YES
+REFERENCES_RELATION    = YES
+VERBATIM_HEADERS       = YES
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = NO
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          = 
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = NO
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            = 
+HTML_FOOTER            = 
+HTML_STYLESHEET        = 
+HTML_ALIGN_MEMBERS     = YES
+GENERATE_HTMLHELP      = YES
+CHM_FILE               = 
+HHC_LOCATION           = 
+GENERATE_CHI           = NO
+BINARY_TOC             = YES
+TOC_EXPAND             = YES
+DISABLE_INDEX          = YES
+ENUM_VALUES_PER_LINE   = 4
+GENERATE_TREEVIEW      = YES
+TREEVIEW_WIDTH         = 250
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = NO
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4wide
+EXTRA_PACKAGES         = 
+LATEX_HEADER           = 
+PDF_HYPERLINKS         = NO
+USE_PDFLATEX           = NO
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = YES
+RTF_OUTPUT             = Doc
+COMPACT_RTF            = YES
+RTF_HYPERLINKS         = YES
+RTF_STYLESHEET_FILE    = 
+RTF_EXTENSIONS_FILE    = 
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_SCHEMA             = 
+XML_DTD                = 
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX = 
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor   
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = YES
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           = 
+INCLUDE_FILE_PATTERNS  = 
+PREDEFINED             = NONSHARABLE_CLASS
+EXPAND_AS_DEFINED      = 
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references   
+#---------------------------------------------------------------------------
+TAGFILES               = 
+GENERATE_TAGFILE       = 
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool   
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = YES
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = NO
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+TEMPLATE_RELATIONS     = YES
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+DOT_PATH               = 
+DOTFILE_DIRS           = 
+MAX_DOT_GRAPH_WIDTH    = 1024
+MAX_DOT_GRAPH_HEIGHT   = 1024
+MAX_DOT_GRAPH_DEPTH    = 0
+DOT_TRANSPARENT        = NO
+DOT_MULTI_TARGETS      = NO
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to the search engine   
+#---------------------------------------------------------------------------
+SEARCHENGINE           = NO
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/group/TemplateScriptXXX_nrm.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,77 @@
+/*TYPE TESTCLASS*/
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestScripter 
+* testclass test module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          TemplateScriptXXX.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E3
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+//TARGETPATH      ?target_path
+DEFFILE         TemplateScriptXXX.def
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          TemplateScriptXXX.cpp
+SOURCE          TemplateScriptXXXBlocks.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// DEFFILE ?filename
+// AIF ?filename
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+PRJ_PLATFORMS
+// specify the platforms your component needs to be built for here
+// defaults to WINS MARM so you can ignore this if you just build these
+	
+	DEFAULT
+
+PRJ_TESTEXPORTS
+// NOTE: If using ARS requirements all export operations should be done under this.
+// 'abld test export'
+
+PRJ_EXPORTS
+// Specify the source file followed by its destination here
+// copy will be used to copy the source file to its destination
+// If there's no destination then the source file will be copied
+// to the same name in \epoc32\include
+// Example: 
+/*
+\agnmodel\inc\AGMCOMON.H
+*/
+
+PRJ_TESTMMPFILES
+
+	TemplateScriptXXX.mmp
+
+PRJ_MMPFILES
+
+	TemplateScriptXXX_nrm.mmp
+
+// Specify the .mmp files required for building the important component
+// releasables.
+//
+// Specify "tidy" if the component you need to build doesn't need to be
+// released. Specify "ignore" if the MMP file exists but should be
+// ignored.
+// Example:
+/*
+\agnmodel\group\agnmodel.mmp
+#if defined(MARM)
+\agnmodel\group\agsvexe.mmp
+#endif
+*/
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/inc/TemplateScriptXXX.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,184 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIF testclass declaration
+*
+*/
+
+#ifndef TEMPLATESCRIPTXXX_H
+#define TEMPLATESCRIPTXXX_H
+
+//  INCLUDES
+#include <StifLogger.h>
+#include <TestScripterInternal.h>
+#include <StifTestModule.h>
+#include <TestclassAssert.h>
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+#define TEST_CLASS_VERSION_MAJOR 0
+#define TEST_CLASS_VERSION_MINOR 0
+#define TEST_CLASS_VERSION_BUILD 0
+
+// Logging path
+_LIT( KTemplateScriptXXXLogPath, "\\logs\\testframework\\TemplateScriptXXX\\" ); 
+// Log file
+_LIT( KTemplateScriptXXXLogFile, "TemplateScriptXXX.txt" ); 
+_LIT( KTemplateScriptXXXLogFileWithTitle, "TemplateScriptXXX_[%S].txt" );
+
+// FUNCTION PROTOTYPES
+//?type ?function_name(?arg_list);
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+class CTemplateScriptXXX;
+
+// DATA TYPES
+//enum ?declaration
+//typedef ?declaration
+//extern ?data_type;
+
+// CLASS DECLARATION
+
+/**
+*  CTemplateScriptXXX test class for STIF Test Framework TestScripter.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS(CTemplateScriptXXX) : public CScriptBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTemplateScriptXXX* NewL( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CTemplateScriptXXX();
+
+    public: // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * From CScriptBase Runs a script line.
+        * @since ?Series60_version
+        * @param aItem Script line containing method name and parameters
+        * @return Symbian OS error code
+        */
+        virtual TInt RunMethodL( CStifItemParser& aItem );
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CTemplateScriptXXX( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+        /**
+        * Frees all resources allocated from test methods.
+        * @since ?Series60_version
+        */
+        void Delete();
+
+        /**
+        * Test methods are listed below. 
+        */
+
+        /**
+        * Example test method.
+        * @since ?Series60_version
+        * @param aItem Script line containing parameters.
+        * @return Symbian OS error code.
+        */
+        virtual TInt ExampleL( CStifItemParser& aItem );
+        
+        /**
+         * Method used to log version of test class
+         */
+        void SendTestClassVersion();
+
+        //ADD NEW METHOD DEC HERE
+        //[TestMethods] - Do not remove
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+        
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+#endif      // TEMPLATESCRIPTXXX_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/src/TemplateScriptXXX.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,198 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains testclass implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "TemplateScriptXXX.h"
+#include <SettingServerClient.h>
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CTemplateScriptXXX::CTemplateScriptXXX
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CTemplateScriptXXX::CTemplateScriptXXX( 
+    CTestModuleIf& aTestModuleIf ):
+        CScriptBase( aTestModuleIf )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CTemplateScriptXXX::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CTemplateScriptXXX::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+
+    TFileName logFileName;
+    
+    if(loggerSettings.iAddTestCaseTitle)
+        {
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        logFileName.Format(KTemplateScriptXXXLogFileWithTitle, &title);
+        }
+    else
+        {
+        logFileName.Copy(KTemplateScriptXXXLogFile);
+        }
+
+    iLog = CStifLogger::NewL( KTemplateScriptXXXLogPath, 
+                          logFileName,
+                          CStifLogger::ETxt,
+                          CStifLogger::EFile,
+                          EFalse );
+    
+    SendTestClassVersion();
+    }
+
+// -----------------------------------------------------------------------------
+// CTemplateScriptXXX::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CTemplateScriptXXX* CTemplateScriptXXX::NewL( 
+    CTestModuleIf& aTestModuleIf )
+    {
+    CTemplateScriptXXX* self = new (ELeave) CTemplateScriptXXX( aTestModuleIf );
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+// Destructor
+CTemplateScriptXXX::~CTemplateScriptXXX()
+    { 
+
+    // Delete resources allocated from test methods
+    Delete();
+
+    // Delete logger
+    delete iLog; 
+
+    }
+
+//-----------------------------------------------------------------------------
+// CTemplateScriptXXX::SendTestClassVersion
+// Method used to send version of test class
+//-----------------------------------------------------------------------------
+//
+void CTemplateScriptXXX::SendTestClassVersion()
+	{
+	TVersion moduleVersion;
+	moduleVersion.iMajor = TEST_CLASS_VERSION_MAJOR;
+	moduleVersion.iMinor = TEST_CLASS_VERSION_MINOR;
+	moduleVersion.iBuild = TEST_CLASS_VERSION_BUILD;
+	
+	TFileName moduleName;
+	moduleName = _L("TemplateScriptXXX.dll");
+
+	TBool newVersionOfMethod = ETrue;
+	TestModuleIf().SendTestModuleVersion(moduleVersion, moduleName, newVersionOfMethod);
+	}
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point.
+// Returns: CScriptBase: New CScriptBase derived object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* LibEntryL( 
+    CTestModuleIf& aTestModuleIf ) // Backpointer to STIF Test Framework
+    {
+
+    return ( CScriptBase* ) CTemplateScriptXXX::NewL( aTestModuleIf );
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TemplateScriptXXX/src/TemplateScriptXXXBlocks.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,164 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains testclass implementation.
+*
+*/
+
+// [INCLUDE FILES] - do not remove
+#include <e32svr.h>
+#include <StifParser.h>
+#include <StifTestInterface.h>
+#include "TemplateScriptXXX.h"
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CTemplateScriptXXX::Delete
+// Delete here all resources allocated and opened from test methods. 
+// Called from destructor. 
+// -----------------------------------------------------------------------------
+//
+void CTemplateScriptXXX::Delete() 
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CTemplateScriptXXX::RunMethodL
+// Run specified method. Contains also table of test mothods and their names.
+// -----------------------------------------------------------------------------
+//
+TInt CTemplateScriptXXX::RunMethodL( 
+    CStifItemParser& aItem ) 
+    {
+
+    static TStifFunctionInfo const KFunctions[] =
+        {  
+        // Copy this line for every implemented function.
+        // First string is the function name used in TestScripter script file.
+        // Second is the actual implementation member function. 
+        ENTRY( "Example", CTemplateScriptXXX::ExampleL ),
+        //ADD NEW ENTRY HERE
+        // [test cases entries] - Do not remove
+
+        };
+
+    const TInt count = sizeof( KFunctions ) / 
+                        sizeof( TStifFunctionInfo );
+
+    return RunInternalL( KFunctions, count, aItem );
+
+    }
+
+// -----------------------------------------------------------------------------
+// CTemplateScriptXXX::ExampleL
+// Example test method function.
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+TInt CTemplateScriptXXX::ExampleL( CStifItemParser& aItem )
+    {
+
+    // Print to UI
+    _LIT( KTemplateScriptXXX, "TemplateScriptXXX" );
+    _LIT( KExample, "In Example" );
+    TestModuleIf().Printf( 0, KTemplateScriptXXX, KExample );
+    // Print to log file
+    iLog->Log( KExample );
+
+    TInt i = 0;
+    TPtrC string;
+    _LIT( KParam, "Param[%i]: %S" );
+    while ( aItem.GetNextString ( string ) == KErrNone )
+        {
+        TestModuleIf().Printf( i, KTemplateScriptXXX, 
+                                KParam, i, &string );
+        i++;
+        }
+
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CTemplateScriptXXX::?member_function
+// ?implementation_description
+// (other items were commented in a header).
+// -----------------------------------------------------------------------------
+//
+/*
+TInt CTemplateScriptXXX::?member_function(
+   CItemParser& aItem )
+   {
+
+   ?code
+
+   }
+*/
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+// None
+
+//  [End of File] - Do not remove
+
+// End of File
Binary file stif/TestModuleTemplates/TestModuleTemplates.zip has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/Bmarm/TESTMODULEXXXU.DEF	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	LibEntryL__Fv @ 1 NONAME R3UNUSED ; LibEntryL(void)
+	SetRequirements__FRP16CTestModuleParamRUl @ 2 NONAME R3UNUSED ; SetRequirements(CTestModuleParam *&, unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/Bwins/TestModuleXXXu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	?LibEntryL@@YAPAVCTestModuleBase@@XZ @ 1 NONAME ; class CTestModuleBase * __cdecl LibEntryL(void)
+	?SetRequirements@@YAHAAPAVCTestModuleParam@@AAK@Z @ 2 NONAME ; int __cdecl SetRequirements(class CTestModuleParam * &,unsigned long &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/createmodule.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,111 @@
+::
+:: Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+:: All rights reserved.
+:: This component and the accompanying materials are made available
+:: under the terms of "Eclipse Public License v1.0"
+:: which accompanies this distribution, and is available
+:: at the URL "http://www.eclipse.org/legal/epl-v10.html".
+::
+:: Initial Contributors:
+:: Nokia Corporation - initial contribution.
+::
+:: Contributors:
+:: 
+:: Description: This file contains capsmodifier implementation.
+::
+
+@perl -x createmodule.bat %1 %2 %3 %4 %5 %6 %7 %8 %9 
+@goto end
+
+#!perl
+use strict;
+use File::Find;
+
+# Verify command line parameters
+if   ($#ARGV == -1 || $#ARGV > 1 )
+{
+	PrintHelp();
+}
+
+# Take module name
+my $moduleName = $ARGV[0];
+my $MODULENAME = $moduleName;
+$MODULENAME =~ tr/[a-z]/[A-Z]/;
+
+# Take target path or use default
+my $targetPath="\\";
+if ( $#ARGV == 1 )
+{
+	$targetPath = $ARGV[1];
+}
+
+
+# Create directory
+my $targetDir = $targetPath.$moduleName."\\";
+
+print "Starting module creation to $targetDir\n";
+mkdir $targetDir, 0777 || die ("Can't create directory $targetDir");
+
+# Loop through the file structure
+find(\&renamerename, '.');
+
+unlink $targetDir."createmodule.bat";
+print "Module created to $targetDir\n";
+
+# This function will be called for each file or directory
+sub renamerename
+{
+	my $oldName = $_;
+	print "Processing $oldName\n";
+
+	# Construct new filename if that needed
+	s/TestModuleXXX/$moduleName/i;
+	my $newName = $targetDir.$File::Find::dir."/".$_;  
+
+	# Process directories
+	if (opendir(DIR, $oldName))
+	{
+		closedir (DIR);
+		mkdir $newName, 0777 || die ("Can't create directory $newName");
+		return;
+	}
+                        
+	# Open input file
+	open (INFILE, $oldName ) || die ("Can not find $oldName");
+
+	#Open output file
+	my $newOutput = $newName."new";
+	open (OUTFILE, ">".$newOutput ) || die ("Can not open $newOutput");
+
+	# Replace text in files
+	while (<INFILE>)
+	{
+	  s/TestModuleXXX/$moduleName/g;
+	  s/TESTMODULEXXX/$MODULENAME/g;
+	  s/XXX/$moduleName/g;
+	  s/TestModuleTargetDirYYY/$targetDir/g;
+	  print OUTFILE $_;
+	}
+
+	# Close filehandles
+	close (INFILE);
+	close (OUTFILE);
+
+	# Rename result file
+	rename $newOutput,$newName;
+}
+
+sub PrintHelp()
+{
+	print "CreateModule ModuleName [path]\n";
+	print "\n";
+	print "Creates a new test module\n";
+	print "If [path] is not given, module is created to root of current drive.\n";
+	print "If [path] is given, it must contain the final \'\\\' in path name.\n";
+	print "Command must be executed in directory where the template exist.\n";
+	exit;
+}
+
+
+__END__
+:end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/eabi/TestModuleXXXu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	_Z9LibEntryLv @ 1 NONAME
+	_Z15SetRequirementsRP16CTestModuleParamRm @ 2 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/group/TestModuleXXX.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Normal test module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          TestModuleXXX.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+
+DEFFILE         TestModuleXXX.def
+//TARGETPATH      ?target_path
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          TestModuleXXX.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCEPATH   ?source_path
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// AIF ?filename
+
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/group/TestModuleXXX.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+; 
+; Description:
+;
+; 	Installation file for STIF
+;
+
+; Languages
+&EN
+
+; Provide value for uid
+#{"STIF"},(0x00000000),1,1,0,TYPE=SA
+
+; Series60 product id for S60 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Logo
+; None
+
+; Package signature - Optional
+; None
+
+; Start of Package body
+
+; Condition blocks
+; None
+
+; Options list
+; None
+
+; Install files
+"\epoc32\release\armv5\udeb\TestModuleXXX.dll"   -   "!:\Sys\Bin\TestModuleXXX.dll"
+  
+; Embedded SIS 
+; None
+
+; End of Package body
+
+; PKG dependencies
+; None
+
+; PKG capabilities
+; None
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/group/TestModuleXXX_DoxyFile.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,240 @@
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+#
+# Contributors:
+# 
+# Description:
+#
+#
+
+# Doxyfile 1.4.1
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+PROJECT_NAME           = TestModuleXXX
+PROJECT_NUMBER         = 
+OUTPUT_DIRECTORY       = TestModuleTargetDirYYY
+CREATE_SUBDIRS         = NO
+OUTPUT_LANGUAGE        = English
+USE_WINDOWS_ENCODING   = YES
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       = 
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = NO
+STRIP_FROM_PATH        = 
+STRIP_FROM_INC_PATH    = 
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = NO
+MULTILINE_CPP_IS_BRIEF = NO
+DETAILS_AT_TOP         = NO
+INHERIT_DOCS           = YES
+DISTRIBUTE_GROUP_DOC   = NO
+TAB_SIZE               = 8
+ALIASES                = 
+OPTIMIZE_OUTPUT_FOR_C  = YES
+OPTIMIZE_OUTPUT_JAVA   = NO
+SUBGROUPING            = YES
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = YES
+EXTRACT_PRIVATE        = NO
+EXTRACT_STATIC         = NO
+EXTRACT_LOCAL_CLASSES  = NO
+EXTRACT_LOCAL_METHODS  = NO
+HIDE_UNDOC_MEMBERS     = NO
+HIDE_UNDOC_CLASSES     = NO
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = YES
+CASE_SENSE_NAMES       = YES
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_BY_SCOPE_NAME     = NO
+GENERATE_TODOLIST      = NO
+GENERATE_TESTLIST      = NO
+GENERATE_BUGLIST       = NO
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       = 
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_DIRECTORIES       = YES
+FILE_VERSION_FILTER    = 
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           = 
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  = TestModuleTargetDirYYY
+FILE_PATTERNS          = *.h \
+                         *.rh \
+                         *.hrh
+RECURSIVE              = YES
+EXCLUDE                = 
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       = 
+EXAMPLE_PATH           = 
+EXAMPLE_PATTERNS       = 
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             = 
+INPUT_FILTER           = 
+FILTER_PATTERNS        = 
+FILTER_SOURCE_FILES    = NO
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = NO
+INLINE_SOURCES         = NO
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = YES
+REFERENCES_RELATION    = YES
+VERBATIM_HEADERS       = YES
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = NO
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          = 
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = NO
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            = 
+HTML_FOOTER            = 
+HTML_STYLESHEET        = 
+HTML_ALIGN_MEMBERS     = YES
+GENERATE_HTMLHELP      = YES
+CHM_FILE               = 
+HHC_LOCATION           = 
+GENERATE_CHI           = NO
+BINARY_TOC             = YES
+TOC_EXPAND             = YES
+DISABLE_INDEX          = YES
+ENUM_VALUES_PER_LINE   = 4
+GENERATE_TREEVIEW      = YES
+TREEVIEW_WIDTH         = 250
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = NO
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4wide
+EXTRA_PACKAGES         = 
+LATEX_HEADER           = 
+PDF_HYPERLINKS         = NO
+USE_PDFLATEX           = NO
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = YES
+RTF_OUTPUT             = Doc
+COMPACT_RTF            = YES
+RTF_HYPERLINKS         = YES
+RTF_STYLESHEET_FILE    = 
+RTF_EXTENSIONS_FILE    = 
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_SCHEMA             = 
+XML_DTD                = 
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX = 
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor   
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = YES
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           = 
+INCLUDE_FILE_PATTERNS  = 
+PREDEFINED             = NONSHARABLE_CLASS
+EXPAND_AS_DEFINED      = 
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references   
+#---------------------------------------------------------------------------
+TAGFILES               = 
+GENERATE_TAGFILE       = 
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool   
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = YES
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = NO
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+TEMPLATE_RELATIONS     = YES
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+DOT_PATH               = 
+DOTFILE_DIRS           = 
+MAX_DOT_GRAPH_WIDTH    = 1024
+MAX_DOT_GRAPH_HEIGHT   = 1024
+MAX_DOT_GRAPH_DEPTH    = 0
+DOT_TRANSPARENT        = NO
+DOT_MULTI_TARGETS      = NO
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to the search engine   
+#---------------------------------------------------------------------------
+SEARCHENGINE           = NO
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/group/TestModuleXXX_nrm.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,77 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Normal test module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          TestModuleXXX.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+
+DEFFILE         TestModuleXXX.def
+//TARGETPATH      ?target_path
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          TestModuleXXX.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftestengine.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCEPATH   ?source_path
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// AIF ?filename
+
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+PRJ_PLATFORMS
+// specify the platforms your component needs to be built for here
+// defaults to WINS MARM so you can ignore this if you just build these
+	
+	DEFAULT
+
+PRJ_TESTEXPORTS
+// NOTE: If using ARS requirements all export operations should be done under this.
+// 'abld test export'
+
+PRJ_EXPORTS
+// Specify the source file followed by its destination here
+// copy will be used to copy the source file to its destination
+// If there's no destination then the source file will be copied
+// to the same name in \epoc32\include
+// Example: 
+/*
+\agnmodel\inc\AGMCOMON.H
+*/
+
+PRJ_TESTMMPFILES
+	
+	TestModuleXXX.mmp
+
+PRJ_MMPFILES
+	
+	TestModuleXXX_nrm.mmp
+
+// Specify the .mmp files required for building the important component
+// releasables.
+//
+// Specify "tidy" if the component you need to build doesn't need to be
+// released. Specify "ignore" if the MMP file exists but should be
+// ignored.
+// Example:
+/*
+\agnmodel\group\agnmodel.mmp
+#if defined(MARM)
+\agnmodel\group\agsvexe.mmp
+#endif
+*/
+
+//  End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/inc/TestModuleXXX.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,262 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIF normal test module declaration
+*
+*/
+
+#ifndef TESTMODULEXXX_H
+#define TESTMODULEXXX_H
+
+// INCLUDES
+#include "StifTestModule.h"
+#include <StifLogger.h>
+#include <NormalHardcodedAssert.h>
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+#define TEST_MODULE_VERSION_MAJOR 0
+#define TEST_MODULE_VERSION_MINOR 0
+#define TEST_MODULE_VERSION_BUILD 0
+
+// Logging path
+_LIT( KTestModuleXXXLogPath, "\\logs\\testframework\\TestModuleXXX\\" ); 
+// Log file
+_LIT( KTestModuleXXXLogFile, "TestModuleXXX.txt" ); 
+_LIT( KTestModuleXXXLogFileWithTitle, "TestModuleXXX_[%S].txt" );
+
+// DATA TYPES
+//enum ?declaration
+//typedef ?declaration
+//extern ?data_type;
+
+// FUNCTION PROTOTYPES
+//?type ?function_name(?arg_list);
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// CLASS DECLARATION
+
+/**
+*  This a TestModuleXXX class.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS(CTestModuleXXX) : public CTestModuleBase
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestModuleXXX* NewL();
+
+        /**
+        * Destructor.
+        */
+        virtual ~CTestModuleXXX();
+
+    public: // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * From CTestModuleBase InitL is used to initialize the TestModuleXXX. 
+        *       It is called once for every instance of TestModuleXXX after
+        *       its creation.
+        * @since ?Series60_version
+        * @param aIniFile Initialization file for the test module (optional)
+        * @param aFirstTime Flag is true when InitL is executed for first 
+        *               created instance of TestModuleXXX.
+        * @return Symbian OS error code
+        */
+        TInt InitL( TFileName& aIniFile, TBool aFirstTime );
+
+        /**
+        * From CTestModuleBase GetTestCasesL is used to inquiry test cases 
+        *   from TestModuleXXX. 
+        * @since ?Series60_version
+        * @param aTestCaseFile Test case file (optional)
+        * @param aTestCases  Array of TestCases returned to test framework
+        * @return Symbian OS error code
+        */
+        TInt GetTestCasesL( const TFileName& aTestCaseFile, 
+                            RPointerArray<TTestCaseInfo>& aTestCases );
+
+        /**
+        * From CTestModuleBase RunTestCaseL is used to run an individual 
+        *   test case. 
+        * @since ?Series60_version
+        * @param aCaseNumber Test case number
+        * @param aTestCaseFile Test case file (optional)
+        * @param aResult Test case result returned to test framework (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error, which is 
+        *           not reported in aResult parameter as test case failure).
+        */   
+        TInt RunTestCaseL( const TInt aCaseNumber, 
+                           const TFileName& aTestCaseFile,
+                           TTestResult& aResult );
+
+        /**
+        * From CTestModuleBase; OOMTestQueryL is used to specify is particular
+        * test case going to be executed using OOM conditions
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailureType OOM failure type (optional)
+        * @param aFirstMemFailure The first heap memory allocation failure value (optional)
+        * @param aLastMemFailure The last heap memory allocation failure value (optional)
+        * @return TBool
+        */
+        virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */, 
+                                     const TInt /* aCaseNumber */, 
+                                     TOOMFailureType& /* aFailureType */,
+                                     TInt& /* aFirstMemFailure */, 
+                                     TInt& /* aLastMemFailure */ );
+
+        /**
+        * From CTestModuleBase; User may add implementation for OOM test 
+        * environment initialization. Usually no implementation is required.
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        */
+        virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */, 
+                                    const TInt /* aCaseNumber */ ); 
+
+        /**
+        * From CTestModuleBase; OOMHandleWarningL. User may add implementation 
+        * for OOM test warning handling. Usually no implementation is required.
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailNextValue FailNextValue for OOM test execution (optional)
+        * @return None
+        */
+        virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
+                                        const TInt /* aCaseNumber */, 
+                                        TInt& /* aFailNextValue */);
+
+        /**
+        * From CTestModuleBase; OOMTestFinalizeL may be used to finalize OOM
+        * test environment. Usually no implementation is required.
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        */
+        virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */, 
+                                       const TInt /* aCaseNumber */ );
+
+        /**
+         * Method used to log version of test module
+         */
+        void SendTestModuleVersion();
+
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CTestModuleXXX();
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Check for settings and create logger with test case title in file name.
+        */
+        void CreateTitleLoggerL(void);
+
+        /**
+        * Check for logger settings and delete title logger.
+        */
+        void DeleteTitleLogger(void);
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        CStifLogger * iLog;
+
+        // Standard logger
+        CStifLogger *iStdLog;
+
+        // Logger for currently running test case
+        CStifLogger *iTCLog;
+        
+        // Flag saying if test case title should be added to log file name
+        TBool iAddTestCaseTitleToLogName;
+        
+        // Flag saying if test module version was already sent
+        TBool iVersionLogged;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+#endif      // TESTMODULEXXX_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/TestModuleXXX/src/TestModuleXXX.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,445 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include "TestModuleXXX.h"
+#include "SettingServerClient.h"
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::CTestModuleXXX
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CTestModuleXXX::CTestModuleXXX()
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::ConstructL
+// Symbian 2nd phase constructor can leave.
+// Note: If OOM test case uses STIF Logger, then STIF Logger must be created
+// with static buffer size parameter (aStaticBufferSize). Otherwise Logger 
+// allocates memory from heap and therefore causes error situations with OOM 
+// testing. For more information about STIF Logger construction, see STIF Users 
+// Guide.
+// -----------------------------------------------------------------------------
+//
+void CTestModuleXXX::ConstructL()
+    {
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+    iAddTestCaseTitleToLogName = loggerSettings.iAddTestCaseTitle;
+
+    iStdLog = CStifLogger::NewL( KTestModuleXXXLogPath, 
+                          KTestModuleXXXLogFile);
+    iLog = iStdLog;
+    
+    iVersionLogged = EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CTestModuleXXX* CTestModuleXXX::NewL()
+    {
+    CTestModuleXXX* self = new (ELeave) CTestModuleXXX;
+
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+// Destructor
+CTestModuleXXX::~CTestModuleXXX()
+    { 
+    iLog = NULL;
+    delete iStdLog;
+    iStdLog = NULL;
+    delete iTCLog;
+    iTCLog = NULL;
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::InitL
+// InitL is used to initialize the Test Module.
+// -----------------------------------------------------------------------------
+//
+TInt CTestModuleXXX::InitL( 
+    TFileName& /*aIniFile*/, 
+    TBool /*aFirstTime*/ )
+    {
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::CreateTitleLoggerL
+// Check for settings and create logger with test case title in file name.
+// -----------------------------------------------------------------------------
+//
+void CTestModuleXXX::CreateTitleLoggerL(void)
+    {
+    //Open new log file with test case title in file name
+    if(iAddTestCaseTitleToLogName)
+        {
+        // Check if there is no test case logger already created.
+        if(iTCLog) 
+            { 
+            delete iTCLog; 
+            iTCLog = NULL; 
+            } 
+            
+        TFileName logFileName;
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        
+        logFileName.Format(KTestModuleXXXLogFileWithTitle, &title);
+
+        iTCLog = CStifLogger::NewL(KTestModuleXXXLogPath, 
+                                 logFileName);
+        iLog = iTCLog; 
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::CreateStdLoggerL
+// Check for logger settings and create standard logger.
+// -----------------------------------------------------------------------------
+//
+void CTestModuleXXX::DeleteTitleLogger(void)
+    {
+    //Delete title logger
+    if(iAddTestCaseTitleToLogName)
+        {
+        iLog = iStdLog;
+        delete iTCLog;
+        iTCLog = NULL;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::GetTestCasesL
+// GetTestCases is used to inquire test cases from the Test Module. Test
+// cases are stored to array of test cases. The Test Framework will be 
+// the owner of the data in the RPointerArray after GetTestCases return
+// and it does the memory deallocation. 
+// -----------------------------------------------------------------------------
+//
+TInt CTestModuleXXX::GetTestCasesL( 
+    const TFileName& /*aConfig*/, 
+    RPointerArray<TTestCaseInfo>& aTestCases )
+    {
+
+    /**
+    * A sample code for testcase description allocation, filling and adding 
+    * to test case array. This is probably done somehow in a loop for 
+    * every testcase and information may be fetched from file 
+    * given as parameter or it can be hardcoded to the testmodule. 
+    * Another example can be found from DemoModule included 
+    * also in STIF Test Framework release. 
+
+    // Allocate new TTestCaseInfo from heap.
+    // It MUST be allocated from heap.
+    TTestCaseInfo* testCase = new ( ELeave ) TTestCaseInfo();
+
+    // Sample how to use logging
+    _LIT( KLogStart, "Logging starts!" );
+    iLog->Log( KLogStart );
+
+    // PushL TTestCaseInfo to CleanupStack.    
+    CleanupStack::PushL( testCase );
+
+    // Set number for the testcase.
+    // When the testcase is run, this comes as a parameter to RunTestCaseL.
+    testCase->iCaseNumber = 1;
+
+    // Set title for the test case. This is shown in UI to the user.
+    _LIT( KTestOne, "Test one" );
+    testCase->iTitle.Copy( KTestOne );
+
+    // Append TTestCaseInfo to the testcase array. After appended succesfully 
+    // the TTestCaseInfo object is owned (and freed) by the TestServer. 
+    User::LeaveIfError( aTestCases.Append( testCase ) );
+
+    // Pop TTestCaseInfo from the CleanupStack.
+    CleanupStack::Pop( testCase );
+
+    */
+
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::RunTestCaseL
+// RunTestCaseL is used to run an individual test case specified 
+// by aTestCase. Test cases that can be run may be requested from 
+// Test Module by GetTestCases method before calling RunTestCase.
+// -----------------------------------------------------------------------------
+//
+TInt CTestModuleXXX::RunTestCaseL(
+    const TInt /* aCaseNumber */,
+    const TFileName& /*aConfig*/,
+    TTestResult& aResult )
+    {
+    SendTestModuleVersion();
+
+    CreateTitleLoggerL();
+    //Test case implementation or function call here
+
+    // Sets test case result and description(Maximum size is KStifMaxResultDes)
+    _LIT( KDescription, "Test passed" );
+    aResult.SetResult( KErrNone, KDescription );
+
+    // Test case was executed
+    DeleteTitleLogger();
+    return KErrNone;
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::OOMTestQueryL
+// Used to check if a particular test case should be run in OOM conditions and 
+// which memory allocations should fail.    
+//
+// NOTE: This method is virtual and must be implemented only if test case
+// should be executed using OOM conditions.  
+// -----------------------------------------------------------------------------
+//
+TBool CTestModuleXXX::OOMTestQueryL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt /* aCaseNumber */, 
+                                TOOMFailureType& /* aFailureType */, 
+                                TInt& /* aFirstMemFailure */, 
+                                TInt& /* aLastMemFailure */ ) 
+    {
+    _LIT( KOOMTestQueryL, "CTestModuleXXX::OOMTestQueryL" );
+    iLog->Log( KOOMTestQueryL ); 
+
+    return EFalse;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::OOMTestInitializeL
+// Used to perform the test environment setup for a particular OOM test case. 
+// Test Modules may use the initialization file to read parameters for Test 
+// Module initialization but they can also have their own configure file or 
+// some other routine to initialize themselves.  
+//
+// NOTE: This method is virtual and must be implemented only if test case
+// should be executed using OOM conditions.  
+// -----------------------------------------------------------------------------
+//
+void CTestModuleXXX::OOMTestInitializeL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt /* aCaseNumber */ )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::OOMHandleWarningL
+// In some cases the heap memory allocation should be skipped, either due to
+// problems in the OS code or components used by the code being tested, or even 
+// inside the tested components which are implemented this way on purpose (by 
+// design), so it is important to give the tester a way to bypass allocation 
+// failures.
+//
+// NOTE: This method is virtual and must be implemented only if test case
+// should be executed using OOM conditions.  
+// -----------------------------------------------------------------------------
+//
+void CTestModuleXXX::OOMHandleWarningL( 
+                                const TFileName& /* aTestCaseFile */,
+                                const TInt /* aCaseNumber */, 
+                                TInt& /* aFailNextValue */ )
+    {
+    }
+
+// -----------------------------------------------------------------------------
+// CTestModuleXXX::OOMTestFinalizeL
+// Used to perform the test environment cleanup for a particular OOM test case.
+//
+// NOTE: This method is virtual and must be implemented only if test case
+// should be executed using OOM conditions.  
+// -----------------------------------------------------------------------------
+//                  
+void CTestModuleXXX::OOMTestFinalizeL( 
+                                const TFileName& /* aTestCaseFile */, 
+                                const TInt /* aCaseNumber */ )
+    {
+    }
+
+//-----------------------------------------------------------------------------
+// CTemplateScriptXXX::SendTestModuleVersion
+// Method used to send version of test module
+//-----------------------------------------------------------------------------
+//
+void CTestModuleXXX::SendTestModuleVersion()
+	{
+	if(iVersionLogged)
+		{
+		return;
+		}
+	
+	TVersion moduleVersion;
+	moduleVersion.iMajor = TEST_MODULE_VERSION_MAJOR;
+	moduleVersion.iMinor = TEST_MODULE_VERSION_MINOR;
+	moduleVersion.iBuild = TEST_MODULE_VERSION_BUILD;
+	
+	TFileName moduleName;
+	moduleName = _L("TestModuleXXX.dll");
+
+	TBool newVersionOfMethod = ETrue;
+	TestModuleIf().SendTestModuleVersion(moduleVersion, moduleName, newVersionOfMethod);
+	iVersionLogged = ETrue;
+	}
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point
+// Returns: CTestModuleBase*: Pointer to Test Module object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CTestModuleBase* LibEntryL()
+    {
+    return CTestModuleXXX::NewL();
+
+    }
+
+// -----------------------------------------------------------------------------
+// SetRequirements handles test module parameters(implements evolution
+// version 1 for test module's heap and stack sizes configuring).
+// Returns: TInt: Symbian error code.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt SetRequirements( CTestModuleParam*& /*aTestModuleParam*/, 
+                                TUint32& /*aParameterValid*/ )
+    {
+
+    /* --------------------------------- NOTE ---------------------------------
+    USER PANICS occurs in test thread creation when:
+    1) "The panic occurs when the value of the stack size is negative."
+    2) "The panic occurs if the minimum heap size specified is less
+       than KMinHeapSize".
+       KMinHeapSize: "Functions that require a new heap to be allocated will
+       either panic, or will reset the required heap size to this value if
+       a smaller heap size is specified".
+    3) "The panic occurs if the minimum heap size specified is greater than
+       the maximum size to which the heap can grow".
+    Other:
+    1) Make sure that your hardware or Symbian OS is supporting given sizes.
+       e.g. Hardware might support only sizes that are divisible by four.
+    ------------------------------- NOTE end ------------------------------- */
+
+    // Normally STIF uses default heap and stack sizes for test thread, see:
+    // KTestThreadMinHeap, KTestThreadMinHeap and KStackSize.
+    // If needed heap and stack sizes can be configured here by user. Remove
+    // comments and define sizes.
+
+/*
+    aParameterValid = KStifTestModuleParameterChanged;
+
+    CTestModuleParamVer01* param = CTestModuleParamVer01::NewL();
+    // Stack size
+    param->iTestThreadStackSize= 16384; // 16K stack
+    // Heap sizes
+    param->iTestThreadMinHeap = 4096;   // 4K heap min
+    param->iTestThreadMaxHeap = 1048576;// 1M heap max
+
+    aTestModuleParam = param;
+*/
+    return KErrNone;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestModuleTemplates/createtestmodule.bat	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,216 @@
+::
+:: Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+:: All rights reserved.
+:: This component and the accompanying materials are made available
+:: under the terms of "Eclipse Public License v1.0"
+:: which accompanies this distribution, and is available
+:: at the URL "http://www.eclipse.org/legal/epl-v10.html".
+::
+:: Initial Contributors:
+:: Nokia Corporation - initial contribution.
+::
+:: Contributors:
+:: 
+:: Description: This file contains capsmodifier implementation.
+::
+
+@perl -x createtestmodule.bat %*
+@goto end
+
+#!perl -w
+use strict;
+use Term::ReadLine;
+
+my $moduletype = "";
+my $modulename = "";
+my $modulepath = "";
+
+my $normal = "normal";
+my $hardcoded = "hardcoded";
+my $testclass = "testclass";
+my $kerneltestclass = "kerneltest";
+my $stifunit = "stifunit";
+my $stifunitvar2 = "stifunitvar2";
+my $capsmodifier = "capsmodifier";
+
+my $normali = "n";
+my $hardcodedi = "h";
+my $testclassi = "t";
+my $kerneltestclassi = "k";
+my $stifuniti = "s";
+my $stifunitvar2i = "d";
+my $capsmodifieri = "c";
+
+my $term = new Term::ReadLine 'Simple Perl calc';
+my $prompttype = "Enter ModuleType (name/short cut): ";
+my $promptname = "Enter ModuleName (or exit): ";  
+my $promptpath = "Enter path [default is drive root] (or exit): ";  
+my $exit = "exit";
+my $exiti = "e";   
+  
+sub PrintHelp();
+
+if ( $#ARGV >= 0 )
+{
+    $moduletype = $ARGV[0];
+    if( $moduletype eq "help" )
+    {
+    PrintHelp();
+    }
+}
+else
+{
+    print "Enter ModuleType :\n";
+	print "\t($normali) $normal = creates an empty test module.\n";
+	print "\t($hardcodedi) $hardcoded = creates test module that uses hardcoded test cases.\n";
+	print "\t($testclassi) $testclass = creates test class which is used with TestScripter.\n";
+	print "\t($kerneltestclassi) $kerneltestclass = creates kernel test class which is used with TestScripter (only for kernel testing!).\n";
+	print "\t($capsmodifieri) $capsmodifier = creates capability modification module\n";
+	print "\t($stifuniti) $stifunit = creates test module using xUnit test pattern\n";
+	print "\t($stifunitvar2i) $stifunitvar2 = adds STIFUnit module to already existing project\n";
+	print "\t($exiti) $exit = Exit.\n";  
+
+
+    $moduletype = $term->readline($prompttype);
+    if( $moduletype eq $exit || $moduletype eq $exiti)
+    {
+        exit;
+    }
+}
+if( $moduletype ne $normal && $moduletype ne $hardcoded && $moduletype ne $testclass && $moduletype ne $kerneltestclass && $moduletype ne $capsmodifier && $moduletype ne $stifunit && $moduletype ne $stifunitvar2 && $moduletype ne $normali && $moduletype ne $hardcodedi && $moduletype ne $testclassi && $moduletype ne $kerneltestclassi && $moduletype ne $capsmodifieri && $moduletype ne $stifuniti && $moduletype ne $stifunitvar2i)
+    {
+        print "\nInvalid module type\n";
+        print "See createtestmodule help\n";
+        exit;
+    }
+    
+if ( $#ARGV >= 1 )
+{
+    $modulename = $ARGV[1];
+}
+else
+{
+    
+	if( $moduletype eq $normal  || $moduletype eq $normali )
+	{   
+    		print "$normal module selected.\n";
+	}
+	elsif( $moduletype eq $hardcoded || $moduletype eq $hardcodedi )
+	{
+   	 	print "$hardcoded module selected.\n";
+	}
+	elsif( $moduletype eq $testclass || $moduletype eq $testclassi )
+	{
+  		print "$testclass module selected.\n";
+	}
+	elsif( $moduletype eq $kerneltestclass || $moduletype eq $kerneltestclassi )
+	{
+  		print "$kerneltestclass module selected.\n";
+	}
+	elsif( $moduletype eq $capsmodifier || $moduletype eq $capsmodifieri )
+	{
+ 		print "$capsmodifier module selected.\n";
+	}
+	elsif( $moduletype eq $stifunit || $moduletype eq $stifuniti || $moduletype eq $stifunitvar2 || $moduletype eq $stifunitvar2i )
+	{
+		print "$stifunit module selected.\n";
+	}
+	print "Enter ModuleName which has to be a valid C++ variable name.\n";
+    
+	$modulename = $term->readline($promptname);
+
+    if( $modulename eq $exit || $modulename eq $exiti)
+    {
+        exit;
+    }
+}
+if ( $#ARGV >= 2 )
+{
+    $modulepath = $ARGV[2];
+}
+else
+{
+    $modulepath = $term->readline($promptpath);
+    if( $modulepath eq $exit || $modulepath eq $exiti )
+    {
+        exit;
+    }
+}
+
+$modulepath.= "\\";
+
+print "Create test module of type $moduletype with name $modulename ";
+
+
+if ( $modulepath eq "" )
+{ 
+    print "to current drive root\n";
+}
+else
+{
+    print "to $modulepath\n";
+}
+
+my @args = ("$modulename", "$modulepath");
+
+if( $moduletype eq $normal  || $moduletype eq $normali )
+{   
+    chdir "TestModuleXXX";
+    system("perl -x createmodule.bat @args");
+}
+elsif( $moduletype eq $hardcoded || $moduletype eq $hardcodedi )
+{
+    chdir "HardCodedTestModuleXXX";
+    system("perl -x createhardcodedmodule.bat @args");
+}
+elsif( $moduletype eq $testclass || $moduletype eq $testclassi )
+{
+    chdir "TemplateScriptXXX";
+    system("perl -x CreateTestClass.bat @args");
+}
+elsif( $moduletype eq $kerneltestclass || $moduletype eq $kerneltestclassi )
+{
+    chdir "TemplateKernelScriptXXX";
+    system("perl -x CreateKernelTestClass.bat @args");
+}
+
+elsif( $moduletype eq $capsmodifier || $moduletype eq $capsmodifieri )
+{
+    chdir "CapsModifierXXX";
+    system("perl -x CreateCapsModifier.bat @args");
+}
+
+elsif( $moduletype eq $stifunit || $moduletype eq $stifuniti)
+{
+    chdir "STIFUnitXXX";
+    system("perl -x CreateSTIFUnitModule.bat @args");
+}
+
+elsif( $moduletype eq $stifunitvar2 || $moduletype eq $stifunitvar2i)
+{
+    chdir "STIFUnitXXX";
+    system("perl -x CreateSTIFUnitModuleVar2.bat @args");
+}
+
+exit;
+
+sub PrintHelp()
+{
+	print "CreateTestModule [ModuleType] [ModuleName] [path]\n";
+	print "\n";
+	print "Creates a new test module\n";
+	print "ModuleType defines the type of test module:.\n";
+	print "\tnormal = creates an empty test module.\n";
+	print "\thardcoded = creates test module that uses hardcoded test cases.\n";
+	print "\ttestclass = creates test class which is used with TestScripter.\n";
+	print "\tkerneltestclass = creates kernel test class which is used with TestScripter (only for kernel testing!).\n";
+	print "\tcapsmodifier = creates capability modification module\n";
+	print "\tstifunit = creates test module using xUnit test pattern\n";
+	print "If no arguments are given, they are asked from user.\n";
+	print "If [path] is given, it must contain the final \'\\\' in path name.\n";
+	print "Command must be executed in STIFTestFramework\\TestModuleTemplates directory\n";
+	exit;
+}
+
+__END__
+:end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/Bmarm/testscripteru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__Fv @ 1 NONAME R3UNUSED ; LibEntryL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/Bwins/testscripteru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,7 @@
+EXPORTS
+	?LibEntryL@@YAPAVCTestScripter@@XZ @ 1 NONAME ; class CTestScripter * LibEntryL(void)
+	?GetConstantValue@CTestScripter@@QAEHABVTDesC16@@AAVTDes16@@@Z @ 2 NONAME ; int CTestScripter::GetConstantValue(class TDesC16 const &, class TDes16 &)
+	?SetResultDescription@CTestScripter@@QAEXABVTDesC16@@@Z @ 3 NONAME ; void CTestScripter::SetResultDescription(class TDesC16 const &)
+	?SetLocalValue@CTestScripter@@QAEHABVTDesC16@@0@Z @ 4 NONAME ; int CTestScripter::SetLocalValue(class TDesC16 const &, class TDesC16 const &)
+	?GetLocalValue@CTestScripter@@QAEHABVTDesC16@@AAVTDes16@@@Z @ 5 NONAME ; int CTestScripter::GetLocalValue(class TDesC16 const &, class TDes16 &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/eabi/testscripteru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,21 @@
+EXPORTS
+	_Z9LibEntryLv @ 1 NONAME
+	_ZTI11CTestRunner @ 2 NONAME ; #<TI>#
+	_ZTI11TTestObject @ 3 NONAME ; #<TI>#
+	_ZTI13CDefinedValue @ 4 NONAME ; #<TI>#
+	_ZTI13CTestContinue @ 5 NONAME ; #<TI>#
+	_ZTI13CTestScripter @ 6 NONAME ; #<TI>#
+	_ZTI15TTestObjectBase @ 7 NONAME ; #<TI>#
+	_ZTI17TTestObjectKernel @ 8 NONAME ; #<TI>#
+	_ZTV11CTestRunner @ 9 NONAME ; #<VT>#
+	_ZTV11TTestObject @ 10 NONAME ; #<VT>#
+	_ZTV13CDefinedValue @ 11 NONAME ; #<VT>#
+	_ZTV13CTestContinue @ 12 NONAME ; #<VT>#
+	_ZTV13CTestScripter @ 13 NONAME ; #<VT>#
+	_ZTV15TTestObjectBase @ 14 NONAME ; #<VT>#
+	_ZTV17TTestObjectKernel @ 15 NONAME ; #<VT>#
+	_ZN13CTestScripter16GetConstantValueERK7TDesC16R6TDes16 @ 16 NONAME
+	_ZN13CTestScripter20SetResultDescriptionERK7TDesC16 @ 17 NONAME
+	_ZN13CTestScripter13GetLocalValueERK7TDesC16R6TDes16 @ 18 NONAME
+	_ZN13CTestScripter13SetLocalValueERK7TDesC16S2_ @ 19 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/group/TestScripter.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestScripter.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          testscripter.dll
+TARGETTYPE      dll
+
+CAPABILITY      ALL -TCB
+VENDORID        0x101FB657
+SECUREID        0x102073E2
+
+DEFFILE         testscripter.def
+
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         efsrv.lib 
+LIBRARY         stiftestengine.lib
+
+USERINCLUDE     ../inc 
+USERINCLUDE     ../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          TestScripter.cpp
+SOURCE          TestKeywords.cpp
+
+
+// First UID is DLL UID, Second UID is STIF Test Framework UID
+UID             0x1000008D 0x101FB3E7// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	Build information for STIF Test Framework's TestScripter.
+*/
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+	
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	TestScripter.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/inc/Logging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,75 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains Logging macros for TestScripter.
+*
+*/
+
+#ifndef LOGGINGDEFS_H
+#define LOGGINGDEFS_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+
+// CONSTANTS
+const TUint KError              = 0x1;
+const TUint KInit               = 0x2;
+const TUint KPrint              = 0x4;
+const TUint KMessage            = 0x10;
+const TUint KFunction           = 0x20;
+const TUint KVerbose            = 0x40;
+const TUint KAlways             = 0xFFFFFFFF;
+const TUint KDebugLevel         = ( KPrint | KError | KMessage );
+
+// MACROS
+#define __TRACING_ENABLED
+
+#ifdef __TRACING_ENABLED
+
+     // Disable conditional expression is constant -warning
+    #pragma warning( disable : 4127 )
+
+    // General tracing function
+    #define __TRACE(level,p) if ( ( (level) & KDebugLevel ) && LOGGER )\
+                                          {LOGGER->Log p;}
+              
+    // Direct RDebug::Print                            
+    #define __RDEBUG(p) if( KVerbose & KDebugLevel ){ RDebug::Print p ; } 
+
+     // Log function name
+    #define __TRACEFUNC() if( ( KFunction & KDebugLevel ) && LOGGER ){\
+                                const char* f = __FUNCTION__;\
+                                 TPtrC8 F((const unsigned char*)f);\
+                                 LOGGER->Log(F);}
+
+#else // __TRACING_ENABLED
+     // No tracing
+    #define __TRACE(level,p)
+    #define __RDEBUG(p)
+    #define __TRACEFUNC()
+#endif // __TRACING_ENABLED
+
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+#endif // LOGGINGDEFS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/inc/TestKeywords.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,143 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the keywords for the 
+* TestScripter module.
+*
+*/
+
+#ifndef TESTKEYWORDS_H
+#define TESTKEYWORDS_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <StifTestInterface.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+typedef TPtrC (*KeywordFunc)( TInt aKeyword );
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TestScripter Keyword class
+class TTestKeywords 
+    {
+    public: // Enumerations
+        // Keyword enum
+        enum TKeywords
+            {
+            ETitle,
+            ETimeout,
+            EPriority,
+            ECreate,
+            EDelete,
+            ERequest,
+            EWait,
+            ERelease,
+            ESet,
+            EUnset,
+            EPrint,
+            EAllowNextResult,
+            EWaitTestClass,
+            ECreateKernel,
+            EPause,
+            ELoop,
+            EEndLoop,
+            EOOMIgnoreFailure,
+            EOOMHeapFailNext,
+            EOOMHeapSetFail,
+            EOOMHeapToNormal,
+            ETestInterference,
+            EMeasurement,
+            EAllowErrorCodes,
+            EBringToForeground,
+            ESendToBackground,
+            EPressKey,
+            ETypeText,
+            EVar,
+            ECallSub,
+            ECreateX,
+            ESetResultDescription,
+            ESendPointerEvent,
+            };
+
+        // priorities
+        enum TPriority
+            {
+            EPriHigh,
+            EPriNormal,
+            EPriLow,
+            };
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+    public: // Constructors and destructor
+
+    public: // New functions
+
+        /**
+        * Returns a string desrciptor corresponding to keyword number. 
+        */
+        static TPtrC Keyword( TInt aKeyword );
+
+        /**
+        * Returns a string desrciptor corresponding to priority 
+        * enum value. 
+        */
+        static TPtrC Priority( TInt aArg );
+
+        /**
+        * Returns a keyword enum corresponding to keyword 
+        * string descriptor. 
+        */
+        static TInt Parse( TDesC& aKeyword, KeywordFunc aFunc );
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif        // TESTKEYWORDS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/inc/TestScripter.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,814 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the TestScripter 
+* module of STIF Test Framework.
+*
+*/
+
+#ifndef TestScripter_H
+#define TestScripter_H
+
+//  INCLUDES
+#include <e32std.h>
+
+#include <StifParser.h>
+#include <StifLogger.h>
+#include <StifTestModule.h>
+#include "TestScripterInternal.h"
+#include "TestKeywords.h"
+#include "StifKernelTestClass.h"
+#include "StifTestInterference.h"
+#include "STIFMeasurement.h"
+
+// CONSTANTS
+// Printing priorities
+const TInt KPrintPriLow = 10;
+const TInt KPrintPriNorm = 30;
+const TInt KPrintPriHigh = 50;
+// Log dir and file
+_LIT( KTestScripterLogDir, "\\Logs\\TestFramework\\TestScripter\\" );
+_LIT( KTestScripterLogFile, "TestScripter.txt" );
+_LIT( KTestScripterLogFileWithTitle, "TestScripter_[%S].txt");
+// Configuration file tags
+_LIT( KTestStartTag, "[Test]" );
+_LIT( KTestEndTag, "[Endtest]" );
+
+// Define tags
+_LIT( KDefineStartTag, "[Define]" );
+_LIT( KDefineEndTag, "[Enddefine]" );
+
+// Loop counter macro
+_LIT( KLoopCounter, "LOOP_COUNTER" );
+
+// MACROS
+// None
+
+// DATA TYPES
+class CTestRunner;
+typedef CScriptBase* (*CInterfaceFactory)( CTestModuleIf& aTestModuleIf );
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CTestRunner;
+class CTestContinue;
+class TTestModule;
+class TTestObjectBase;
+class TTestObject;
+class TTestInterference;
+class CStifTestMeasurement;
+class TTestMeasurement;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Predefined value entry
+class CDefinedValue
+    :public CBase
+    {
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CDefinedValue* NewL( TDesC& aName, TDesC& aValue );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CDefinedValue();
+
+    public: // New functions
+
+        /**
+        * Returns define name.
+        */
+        TDesC& Name();
+        
+        /**
+        * Returns define value.
+        */
+        TDesC& Value();
+        
+        /**
+        * Returns new define value.
+        */
+        void SetValueL( TDesC& aValue );
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CDefinedValue();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TDesC& aName, TDesC& aValue );
+
+    private: // Data
+
+        // Define name
+        HBufC* iNameBuf;
+        TPtrC  iName;
+
+        // Define value
+        HBufC* iValueBuf;
+        TPtrC  iValue;
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestScripter contains the Test Module interface of TestScripter 
+// for STIF Test Framework
+
+class CTestScripter 
+    :public CTestModuleBase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CTestScripter* NewL();
+          
+        /**
+        * Destructor.
+        */
+        ~CTestScripter();
+
+    public: // New functions
+
+        /**
+        * Call specified tst class object.
+        */
+        TInt CallTestClass( const TDesC& aLine );
+
+        /**
+        * Get pointer to test class object.
+        */
+        TInt GetTestScriptObject( const TDesC& aObjectName );
+
+        /**
+        * Return runner handle.
+        */ 
+        CTestRunner& TestRunner(){ return *iTestRunner; };
+
+    public: // Functions from base classes
+
+        /**
+        * Test module initialization.
+        */ 
+        TInt InitL( TFileName& aIniFile, TBool aFirstTime );
+
+       /**
+        * GetTestCasesL is used to inquire testcases. 
+        */
+        TInt GetTestCasesL( const TFileName& aConfigFile, 
+                            RPointerArray<TTestCaseInfo>& aTestCases );
+
+        /**
+        * RunTestCase is used to run an individual test case specified 
+        * by aTestCase. 
+        */
+        TInt RunTestCaseL( const TInt aCaseNumber, 
+                           const TFileName& aConfig, 
+                           TTestResult& aResult );
+    	
+	    /**
+	     * Internal fuction to get const value defined in 
+	     * [Define]...[Enddefine] section of script file
+	     */        
+        IMPORT_C TInt GetConstantValue( const TDesC& aName, TDes& aValue );    
+
+        /**
+        * Set result description of test case.
+        */        
+        IMPORT_C void SetResultDescription(const TDesC& aDescr);
+
+        /**
+        * Internal fuction to set local value.
+        */        
+        IMPORT_C TInt SetLocalValue(const TDesC& aName, const TDesC& aValue);
+
+        /**
+        * Internal fuction to get local value.
+        */        
+        IMPORT_C TInt GetLocalValue(const TDesC& aName, TDes& aValue);
+        
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CTestScripter();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * GetTestCaseL gets the specified test case section 
+        * from the onfigfile.
+        */
+        CStifSectionParser* GetTestCaseL( TInt aCaseNumber, 
+                                            const TFileName& aConfig );
+
+        /**
+        * RunTestL runs the testcase specified in section.
+        */
+        void RunTestL();
+
+        /**
+        * LoadTestModuleL loads test module.
+        */
+        TTestModule* LoadTestModuleL( TDesC& aModule );
+
+        /**
+        * CreateObjectL create new object.
+        */
+        void CreateObjectL( TDesC& aModule, TDesC& aObjectId );
+
+        /**
+        * CreateKernelObjectL create new kernel object.
+        */
+        void CreateKernelObjectL( TDesC& aDriver, TDesC& aObjectId );
+
+        /**
+        * DeleteObjectL deletes object with aObjectId.
+        */
+        TInt DeleteObjectL( TDesC& aObjectId );
+
+        /**
+        * GetObject returns object corresponding to aObjectId.
+        */
+        TTestObjectBase* GetObject( const TDesC& aObjectId );
+
+        /**
+        * Read initialization from file.
+        */
+        void ReadInitializationL( const TDesC& aIniFile, 
+                                  RPointerArray<CDefinedValue>& aDefines );
+
+        /**
+        * Read sub section from test case file.
+        */
+        CStifSectionParser* GetSubL(const TDesC& aSubName);
+        
+        /**
+        * Updates result of test case.
+        */        
+        void UpdateTestCaseResult(const TInt aError, const TDesC& aDescr);
+
+    public: // Data
+        // Logger 
+        CStifLogger*                    iLog;
+
+    protected: // Data
+
+    private: // Data
+        // Test case array of running/runned test cases 
+        RPointerArray<TTestObjectBase>      iTestObjects;
+        // Array of test modules
+        RPointerArray<TTestModule>          iTestModules;
+
+        // Test case result of the TestScripter
+        TTestResult                         iResult;
+
+        // Sectionparser for the current testcase
+        CStifSectionParser*                 iSectionParser;
+        
+        // Currently used section parser (changed when executing a function (sub))
+        CStifSectionParser*                 iCurrentParser;
+        
+        // It says if we need to call GetLine or GetNextLine for the parser
+        TBool                               iCurrentParserReadFirstLine;
+        
+        // Stack of parsers for called functions (subs)
+        RPointerArray<CStifSectionParser>   iParserStack;
+
+        // Pointer to used testrunner
+        CTestRunner*                        iTestRunner;
+
+        // Predefined values are listed here
+        RPointerArray<CDefinedValue>        iDefinedIni;
+        RPointerArray<CDefinedValue>        iDefinedRuntime;
+        RPointerArray<CDefinedValue>        iDefinedLocal;
+
+        // Flag for OOM testing. If true test class's build
+        // block execution result will ignored.
+        TBool                               iOOMIgnoreFailure;
+
+        // Flag which says if heap balance should be checked (affects only 
+        // EKA2 environment). May be set in StifSettings section.
+        TBool                               iCheckHeapBalance;
+        
+        // Standard logger 
+        CStifLogger*                        iStdLog;
+
+        // Test case Logger 
+        CStifLogger*                        iTCLog;
+
+        // Flag which says if test case title should be appended to the
+        // log file name. This is read from SettingServer
+        TBool                               iAddTestCaseTitleToLogName;
+
+        // The running test case's config file name
+        TFileName                           iConfig;
+
+    public:      // Friend classes
+
+    protected:  // Friend classes
+
+    private:     // Friend classes
+        friend class CTestRunner;
+        friend class CTestContinue;
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestRunner parses the TestScripter configuration file and 
+// runs a testcase. CTestRunner is the friend of CTestScripter
+// and uses its private member variables directly.
+
+class CTestRunner 
+    :public CActive
+    {
+    public: // Enumerations
+         
+    private: // Enumerations
+        enum TRunnerState{
+            ERunnerIdle,
+            ERunnerRunning,
+            ERunnerCancel,
+            ERunnerError,
+            ERunnerPaused,
+            };
+
+    public:  // Constructors and destructor  
+        /**
+        * Two-phased constructor.
+        */
+        static CTestRunner* NewL( CTestScripter* aTestScripter );
+
+        /**
+        * Destructor.
+        */
+        ~CTestRunner();
+
+    public: // New functions
+        /**
+        * Calls SetActive() from CActive.
+        */
+        void SetRunnerActive();
+
+        /**
+        * Get test case result handle.
+        */
+        RArray<TInt>& TestCaseResults(){ return iTestCaseResults; }; 
+
+
+    public: // Functions from base classes     
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CTestRunner( CTestScripter* aTestScripter );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Executes one script line.
+        */
+        TBool ExecuteLineL( TDesC& aKeyword,
+                            CStifItemParser* aItem );
+
+        /**
+        * Executes method call to object script line.
+        */
+        TBool ExecuteCommandL( TDesC& aObject,
+                               CStifItemParser* aItem );
+
+        /**
+        * Executes event control script line.
+        */                       
+        TBool ExecuteEventL( TDesC& aKeyword,
+                                CStifItemParser* aItem );
+
+        /**
+        * Preprocess hardcoded values in test case.
+        */
+        CStifItemParser* PreprocessLineL( TDesC& line );
+        
+        /**
+        * Checks if aWord is defined value.
+        */
+        TInt CheckDefined( TPtrC& aWord );
+
+        /**
+        * Checks if aWord is a local variable.
+        */
+        TInt CheckDefinedLocals( TPtrC& aWord );
+
+        /**
+        * Handles 'oomignorefailure' keyword parsing.
+        */
+        void OOMIgnoreFailureL( CStifItemParser* aItem );
+
+        /**
+        * Handles 'oomheapfailnext' keyword parsing.
+        */
+        void OOMHeapFailNextL( CStifItemParser* aItem );
+
+        /**
+        * Handles 'oomheapsetfail' keyword parsing.
+        */
+        void OOMHeapSetFailL( CStifItemParser* aItem );
+
+        /**
+        * Initialize all OOM related variables.
+        */
+        void OOMHeapToNormal();
+
+        /**
+        * Handles 'testinterference' keyword parsing.
+        */
+        void TestInterferenceL( CStifItemParser* aItem );
+
+        /**
+        * Starts test interference.
+        */
+        void StartInterferenceL( TDesC& aName, CStifItemParser* aItem );
+
+        /**
+        * Stops test interference.
+        */
+        void StopInterferenceL( TDesC& aName );
+
+        /**
+        * Handles 'measurement' keyword parsing.
+        */
+        void MeasurementL( CStifItemParser* aItem );
+
+        /**
+        * Starts measurement.
+        */
+        void StartMeasurementL( const TDesC& aType, CStifItemParser* aItem );
+
+        /**
+        * Stops measurementplugin's measurement.
+        */
+        void StopMeasurementL( const TDesC& aType );
+
+        /**
+        * Adds new test case result. Used with 'allownextresult'
+        * and 'allowerrorcodes' keywords.
+        */
+        void AddTestCaseResultL( CStifItemParser* aItem );
+        
+        /**
+        * Sends key press event to AppUi
+        */
+        TBool PressKeyL( CStifItemParser* aItem );
+
+        /**
+        * Sends text to AppUi
+        */
+        TBool TypeTextL( CStifItemParser* aItem );
+
+        /**
+        * Sends pointer event to AppUi
+        */
+        TBool SendPointerEventL( CStifItemParser* aItem );
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+        // Runner state
+        TRunnerState            iState;
+
+        // Backpointer to CTestScripter
+        CTestScripter*          iTestScripter;
+
+        // Allowed test case results
+        RArray<TInt>            iTestCaseResults; 
+
+        // Temporary line buffer 
+        HBufC*                  iLine;
+
+        // Store for requested events
+        RPointerArray<HBufC>    iEventArray;
+
+        // Pause timer
+        RTimer                  iPauseTimer;
+
+        // Pause value for timer
+        TInt                     iRemainingTimeValue;
+
+        // Loop times, counter and start position
+        TInt                    iLoopTimes;
+        TInt                    iLoopCounter;
+        TInt                    iLoopStartPos;
+        TBuf<10>                iLoopCounterDes;
+
+        // Loop (timed loop option)
+        TBool                   iTimedLoop;
+        TTime                   iStartTime;
+        TTimeIntervalMicroSeconds iExpectedLoopTime;
+
+        // For OOM heap testing, FAILNEXT: count
+        TInt                    iHeapFailNext;
+        // For OOM heap testing, SETFAIL: type and value(rate)
+        RHeap::TAllocFail       iHeapSetFailType;
+        TInt                    iHeapSetFailValue;
+
+        // Array for test interference
+        RPointerArray<TTestInterference>    iTestInterferenceArray;
+
+        // CStifTestMeasurement object
+        RPointerArray<TTestMeasurement>     iTestMeasurementArray;
+
+		// Message displayed when leave occurs during script parsing
+        TBuf<256> iRunErrorMessage;
+        
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestContinue gets ContinueScript signals from test class
+class CTestContinue 
+    :public CActive
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor  
+        /**
+        * Two-phased constructor.
+        */
+        static CTestContinue* NewL( CTestScripter* aTestScripter,
+                                    TTestObject* aObject );
+
+        /**
+        * Destructor.
+        */
+        ~CTestContinue();
+
+    public: // New functions
+
+    public: // Functions from base classes     
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel.
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CTestContinue( CTestScripter* aTestScripter,
+                       TTestObject* aObject );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:     //Data
+
+    protected:  // Data
+
+    private:    // Data
+        // Backpointer to CTestScripter
+        CTestScripter*  iTestScripter;
+
+        // Objectid for this object
+        TTestObject*    iObject;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TTestObjectBase contains test object base information
+class TTestObjectBase
+    {
+    public:
+        enum TObjectType
+            {
+            EObjectNormal,
+            EObjectKernel,
+            };
+
+    public: 
+        TTestObjectBase( TObjectType aType );
+        virtual ~TTestObjectBase();
+    public:
+        TName& ObjectId(){return iName;}
+        TObjectType ObjectType(){ return iType; };
+
+        virtual TInt RunMethodL( CStifItemParser& aItem ) = 0;
+        virtual TBool Signal() = 0;
+        virtual TBool Wait() = 0; 
+
+    public: 
+        TInt        iAsyncResult;
+
+    protected:
+        TObjectType iType;
+
+    private:
+        TName       iName;
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TTestObject contains test object information
+class TTestObject : public TTestObjectBase
+    {
+    public: 
+        TTestObject();
+        virtual ~TTestObject();
+
+    public:
+        TInt RunMethodL( CStifItemParser& aItem );
+        inline TBool Signal(){ return ( iCount++ < 0 ); };
+        inline TBool Wait(){ return ( --iCount >= 0 ); }; 
+
+    public:
+        CScriptBase*    iScript;
+        CTestContinue*  iContinue;
+
+    private:
+        TInt iCount;
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TTestObjectKernel contains kernel test object information
+class TTestObjectKernel : public TTestObjectBase
+    {
+    public: 
+        TTestObjectKernel();
+        virtual ~TTestObjectKernel();
+
+    public:
+        TInt RunMethodL( CStifItemParser& aItem );
+
+        // Signal and Wait not supported
+        TBool Signal(){ return ETrue; };
+        TBool Wait(){ return ETrue; }; 
+
+        TName& LddName(){ return iLddName; }
+        RStifKernelTestClass& KernelTestClass(){ return iTestClass; }
+
+    private:
+        RStifKernelTestClass    iTestClass;
+        TName                   iLddName;
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TTestModule contains test module information
+class TTestModule
+    {
+    public: 
+        TTestModule(){};
+        ~TTestModule(){ iLibrary.Close(); };
+
+    public:
+        TName& ModuleName(){return iName;}
+
+    public:
+        RLibrary iLibrary;
+        CInterfaceFactory iLibEntry;
+
+    private:
+        TName iName;
+
+    };
+
+// DESCRIPTION
+// TTestInterference contains test interference object information
+class TTestInterference
+    {
+    public: 
+        TTestInterference(){ iInterference = NULL; };
+        ~TTestInterference(){ delete iInterference; };
+
+    public:
+
+    public:
+        // "object" name given in test case file.
+        TName                   iName;
+        // MSTIFTestInterference object.
+        MSTIFTestInterference*  iInterference;
+
+    private:
+
+    };
+
+// DESCRIPTION
+// TTestMeasurement contains test measurement module information
+class TTestMeasurement
+    {
+    public: 
+        TTestMeasurement(){ iMeasurement = NULL; };
+        ~TTestMeasurement(){ delete iMeasurement; };
+
+    public:
+
+    public:
+        // "object" name given in test case file.
+        TName                   iName;
+        // MSTIFTestInterference object.
+        CSTIFTestMeasurement*  iMeasurement;
+
+    private:
+
+    };
+
+#endif        // TestScripter_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/src/TestKeywords.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,198 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* TTestKeywords class member functions.
+*
+*/
+
+
+// INCLUDE FILES
+#include "TestKeywords.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestKeywords
+
+     Method: Keyword
+
+     Description: Returns a string desrciptor corresponding to keyword number. 
+
+     Parameters:    TInt aKeyword: in: keyword index.
+     
+     Return Values: TPtrC8: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Approved 
+    
+-------------------------------------------------------------------------------
+*/
+TPtrC TTestKeywords::Keyword( TInt aKeyword )
+    {
+    static TText* const keywords[] =
+        {
+        (TText*)L"title",
+        (TText*)L"timeout",
+        (TText*)L"priority",
+        (TText*)L"create",
+        (TText*)L"delete",
+        (TText*)L"request",
+        (TText*)L"wait",
+        (TText*)L"release",
+        (TText*)L"set",
+        (TText*)L"unset",
+        (TText*)L"print",
+        (TText*)L"allownextresult",
+        (TText*)L"waittestclass",
+        (TText*)L"createkernel",
+        (TText*)L"pause",
+        (TText*)L"loop",
+        (TText*)L"endloop",
+        (TText*)L"oomignorefailure",
+        (TText*)L"oomheapfailnext",
+        (TText*)L"oomheapsetfail",
+        (TText*)L"oomheaptonormal",
+        (TText*)L"testinterference",
+        (TText*)L"measurement",
+        (TText*)L"allowerrorcodes",
+        (TText*)L"bringtoforeground",
+        (TText*)L"sendtobackground",
+        (TText*)L"presskey",
+        (TText*)L"typetext",        
+        (TText*)L"var",
+        (TText*)L"callsub",
+        (TText*)L"createx",
+        (TText*)L"setresultdescription",
+        (TText*)L"sendpointerevent",
+        };
+
+    if( (TUint)aKeyword >= (sizeof( keywords )/sizeof(TText*)) )
+          {
+          TPtrC null;
+          return null;
+          } 
+
+    TPtrC keyword( keywords[ aKeyword ] ); 
+    return keyword;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestKeywords
+
+     Method: Priority
+
+     Description: Returns a string desrciptor corresponding to priority 
+                    keywords optional argument number. 
+
+     Parameters:   TInt aArg: in: argument index.
+     
+     Return Values: TPtrC8: keyword descriptor
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/
+TPtrC TTestKeywords::Priority( TInt aArg )
+    {
+    static TText* const priority[] =
+        {
+        (TText*)L"high",
+        (TText*)L"normal",
+        (TText*)L"low",
+        };
+
+    if( aArg >= (TInt)(sizeof( priority )/sizeof(TText*)) )
+        {
+        TPtrC null;
+        return null;
+        } 
+
+    TPtrC arg( priority[ aArg ] ); 
+    return arg;
+    
+    }
+      
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestKeywords
+
+     Method: Parse
+
+     Description: Returns a keyword enum corresponding to keyword 
+                      string descriptor.
+
+     Parameters:    TPtrC aKeyword: in: keyword descriptor.
+                    KeywordFunc aFunc: in: Function pointer to keyword parser 
+     
+     Return Values: TInt: keyword index
+
+     Errors/Exceptions: None
+     
+     Status: Draft 
+    
+-------------------------------------------------------------------------------
+*/
+TInt TTestKeywords::Parse( TDesC& aKeyword, KeywordFunc aFunc )
+    {
+    TInt ind;
+    for( ind = 0; aFunc( ind ).Length() > 0; ind++ )
+        {
+        if( aFunc( ind ) == aKeyword )
+            {
+            return ind;
+            }
+        }
+    return KErrNotFound;
+    };
+    
+// ================= OTHER EXPORTED FUNCTIONS =================================
+// None
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/src/TestScripter.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,5169 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains TestScripter implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestEventInterface.h>
+#include <StifLogger.h>
+#include "TestScripter.h"
+#include "TestKeywords.h"
+#include "Logging.h"
+#include "TestEngineClient.h"
+#include "SettingServerClient.h"
+
+#include <stifinternal/UiEnvProxy.h>
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iLog
+
+// LOCAL CONSTANTS AND MACROS
+// None
+ 
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: -
+
+     Method: CallBack
+
+     Description: (Function pointer) Called from CScriptBase class. Generic
+                  method for call back operations from Test Script Class to
+                  TestScripter.
+  
+     Parameters: CTestScripter* aTestScripter: in: Pointer to TestScripter
+                 TStifTSCallBackType aCallType: in: Call back type
+                 const TDesC& aLine: in Script line
+                    
+     Return Values: TInt: Symbian error code
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CallBack( CTestScripter* aTestScripter,
+                TStifTSCallBackType aCallType,
+                const TDesC& aLine )
+    {
+    TInt ret( 0 );
+    switch( aCallType )
+        {
+        case EStifTSCallClass:
+            {
+            ret = aTestScripter->CallTestClass( aLine );
+            break;
+            }
+        case EStifTSGetObject:
+            {
+            ret = aTestScripter->GetTestScriptObject( aLine );
+            break;
+            }
+        default:
+            {
+            ret = KErrArgument;
+            break;
+            }
+        }
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CTestScripter class 
+    member functions.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: CTestScripter
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestScripter::CTestScripter()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripter::ConstructL()
+    {
+    __TRACE( KPrint, ( _L("New TestScripter") ) );
+    iStdLog = CStifLogger::NewL( KTestScripterLogDir,
+                                KTestScripterLogFile );
+    iLog = iStdLog;
+
+    iOOMIgnoreFailure = EFalse; // OFF for default
+
+    iCheckHeapBalance = EFalse; // No checking heap balance by default
+
+    //Read logger settings to check whether test case name is to be
+    //appended to log file name.
+    RSettingServer settingServer;
+    TInt ret = settingServer.Connect();
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        }
+    // Struct to StifLogger settigs.
+    TLoggerSettings loggerSettings; 
+    // Parse StifLogger defaults from STIF initialization file.
+    ret = settingServer.GetLoggerSettings(loggerSettings);
+    if(ret != KErrNone)
+        {
+        User::Leave(ret);
+        } 
+    // Close Setting server session
+    settingServer.Close();
+    iAddTestCaseTitleToLogName = loggerSettings.iAddTestCaseTitle;
+    
+    // Initialize parser variables
+    iCurrentParser = NULL;
+    iCurrentParserReadFirstLine = EFalse;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters:    None
+
+     Return Values: CTestScripter*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestScripter* CTestScripter::NewL()
+    {
+     
+    CTestScripter* self = new (ELeave) CTestScripter();
+    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: ~CTestScripter
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestScripter::~CTestScripter()
+    {
+    iTestObjects.ResetAndDestroy();
+    iTestModules.ResetAndDestroy();
+    iDefinedIni.ResetAndDestroy();
+    iDefinedRuntime.ResetAndDestroy();
+    iDefinedLocal.ResetAndDestroy();
+    iParserStack.ResetAndDestroy();
+    iTestObjects.Close();
+    iTestModules.Close();
+    iDefinedIni.Close();
+    iDefinedRuntime.Close();
+    iDefinedLocal.Close();
+    iParserStack.Close();
+
+    iCurrentParser = NULL;
+    delete iSectionParser;
+    delete iTestRunner;
+
+    iLog = NULL;
+    delete iStdLog;
+    iStdLog = NULL;
+    delete iTCLog;
+    iTCLog = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: InitL
+
+     Description: InitL is used to initialize the Test Module.
+
+     Parameters: const TFileName& aIniFile: in: Initialization file
+                 TBool aFirstTime: in: First time flag 
+                         
+     Return Values: Symbian OS error code
+
+     Errors/Exceptions: Leaves if ReadInitializationL leaves
+     
+     Status: Draft
+
+-------------------------------------------------------------------------------
+*/        
+TInt CTestScripter::InitL( TFileName& aIniFile, 
+                           TBool /*aFirstTime*/ )
+    {
+ 
+    __TRACEFUNC();
+ 
+    if( aIniFile.Length() > 0 )
+        {
+        // Read initialization from test case file
+        ReadInitializationL( aIniFile, iDefinedIni );
+        }
+        
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetTestCases
+
+     Description: GetTestCases is used to inquired test cases
+
+     Parameters:    const TFileName& aConfigFile: in: Test case file
+                    RPointerArray<RTestEngine::TTestCaseInfo>& aTestCases: out: 
+                          Array of TestCases 
+     
+     Return Values: KErrNone: Success
+                    Symbian OS error code
+
+     Errors/Exceptions: Leaves if CStifParser::SectionL leaves
+                        Leaves if CStifParser::NextSectionL leaves
+                        Leaves if memory allocation fails
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/        
+TInt CTestScripter::GetTestCasesL( const TFileName& aConfigFile, 
+                                   RPointerArray<TTestCaseInfo>& aTestCases )
+    {
+    __TRACEFUNC();
+    
+    if( aConfigFile.Length() == 0 )
+        {
+        __TRACE( KError, (_L("No test case script file given") ) );
+        __RDEBUG( (_L("No test case script file given") ) );
+        return KErrNotFound;
+        }
+
+    CStifParser* parser = NULL; 
+    
+    // Open test case file
+    TRAPD( err, 
+        parser = CStifParser::NewL( _L(""), 
+                                    aConfigFile, 
+                                    CStifParser::ECStyleComments ) );
+    if( err != KErrNone )
+        {
+        __TRACE( KError, (_L("Given test case script file [%S] not found"),
+            &aConfigFile ) );
+        __RDEBUG( (_L("Given test case script file [%S] not found"),
+            &aConfigFile ) );
+        return err;
+        }
+        
+    CleanupStack::PushL( parser );
+    CStifSectionParser* section;
+    TPtrC tmp;
+    TInt index = 0;
+    TInt ret = KErrNone;
+
+    // Find first section
+    section = parser->SectionL( KTestStartTag, KTestEndTag );
+    if( section == NULL )
+        {
+        ret = KErrNotFound;
+        }
+    else
+        {    
+        // Parse all sections
+        while( section )
+            {
+            CleanupStack::PushL( section );
+             
+            // Get title line
+            if( section->GetLine( TTestKeywords::Keyword( TTestKeywords::ETitle ),
+                tmp, ENoTag ) != KErrNone )
+                {
+                __TRACE( KError, (_L("Title not given for test case")));
+                User::Leave( KErrNotFound );
+                }
+            else
+                {
+                if( tmp.Length() > KMaxName )
+                    {
+                    tmp.Set( tmp.Left( KMaxName ) );
+                    }   
+                TTestCaseInfo* tc = new ( ELeave ) TTestCaseInfo();
+                CleanupStack::PushL( tc );
+                __TRACE( KVerbose, (_L("TestCase: %S"), &tmp));
+                tc->iTitle.Copy( tmp );
+                tc->iCaseNumber = ++index;
+                 
+                 // Get timeout if defined
+                CStifItemParser* item = section->GetItemLineL(  
+                   TTestKeywords::Keyword( TTestKeywords::ETimeout ) );
+                if( item )
+                    {
+                    TInt timeout; // In milliseconds
+                    ret = item->GetInt( 
+                        TTestKeywords::Keyword( TTestKeywords::ETimeout ), 
+                        timeout ); 
+                    if( ret != KErrNone )
+                        {
+                        __TRACE( KError, (_L("Illegal timeout")));
+                        User::Leave( ret ); 
+                        }
+                        
+                    // Type cast timeout to TInt64    
+                    tc->iTimeout = TInt64( timeout ) * 1000;
+                    __TRACE( KMessage, (_L("Timeout: %i"), tc->iTimeout.Int64() ));
+                    }
+                    
+                 // Get priority if defined
+                item = section->GetItemLineL(  
+                   TTestKeywords::Keyword( TTestKeywords::EPriority ) );
+                if( item )
+                    {
+                    // First try to interpret as integer
+                    ret = item->GetInt( 
+                        TTestKeywords::Keyword( TTestKeywords::EPriority ), 
+                        tc->iPriority ); 
+                    if( ret != KErrNone )
+                        {
+                        TPtrC priority;
+                        // If priority was not given as integer, it must be 
+                        // one of the predefined values
+                        ret = item->GetString( 
+                            TTestKeywords::Keyword( TTestKeywords::EPriority ),
+                            priority );
+                        if( ret != KErrNone )
+                            {
+                            __TRACE( KError, (_L("Illegal priority")));
+                            User::Leave( ret ); 
+                            }
+                        switch( TTestKeywords::Parse( priority, 
+                                                       TTestKeywords::Priority ) )
+                            {
+                            case TTestKeywords::EPriHigh:
+                                tc->iPriority = TTestCaseInfo::EPriorityHigh;
+                                break;
+                            case TTestKeywords::EPriNormal:
+                                tc->iPriority = TTestCaseInfo::EPriorityNormal;
+                                break;
+                            case TTestKeywords::EPriLow:
+                                tc->iPriority = TTestCaseInfo::EPriorityLow;
+                                break;
+                            default:
+                                __TRACE( KError, (_L("Illegal priority")));
+                                User::Leave( KErrArgument ); 
+                            }
+                        }
+                    __TRACE( KMessage, (_L("Priority: %i"), tc->iPriority ));
+                    }
+                    
+                aTestCases.Append(tc);
+                CleanupStack::Pop( tc );
+                }
+            CleanupStack::PopAndDestroy( section );
+            section = parser->NextSectionL( KTestStartTag, KTestEndTag );
+            }
+        }
+          
+    CleanupStack::PopAndDestroy( parser );
+
+    __TRACE( KPrint, (  _L( "Configfile '%S', testcases %d" ),
+        &aConfigFile, index ));     
+     
+    return ret;
+     
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetConstantValue
+
+     Description: Internal fuction to get const value defined in 
+                  [Define]...[Enddefine] section of script file
+
+     GetConstantValue gets const value defined in [Define]...[Enddefine] 
+     section of script file
+
+     Parameters:    const TDesC& aName: in: constant name 
+                    TDes& avalue: out: constant value
+
+     Return Values: KErrNone: Value is returned succesfully.
+                    KErrNotFound: Constant was not found
+                    Any other SymbianOS error
+                    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestScripter::GetConstantValue( const TDesC& aName, TDes& aValue )
+	{
+	
+	__TRACEFUNC();
+
+    TInt count = iDefinedLocal.Count();
+    for(TInt i = 0; i < count; i++)
+        {
+        if(iDefinedLocal[i]->Name() == aName)
+            {
+            aValue.Copy(iDefinedLocal[i]->Value());
+            return KErrNone;
+            }
+        }	
+
+	  count = iDefinedIni.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( iDefinedIni[i]->Name() == aName )
+            {
+            aValue.Copy( iDefinedIni[i]->Value() );
+            return KErrNone;
+            }
+        }	
+	
+    count = iDefinedRuntime.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( iDefinedRuntime[i]->Name() == aName )
+            {
+            aValue.Copy( iDefinedRuntime[i]->Value() );
+            return KErrNone;
+            }
+        }	
+    return KErrNotFound;
+	}
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: RunTestCaseL
+
+     Description: Run a specified testcase.
+
+     RunTestCaseL is used to run an individual test case. 
+  
+     Parameters:    const TInt aCaseNumber: in: Testcase number 
+                    const TFileName& aConfig: in: Test case file
+                    TTestResult& aResult: out: test case result
+
+     Return Values: KErrNone: Test case started succesfully.
+                    KErrNotFound: Testcase not found
+                    KErrUnknown: Unknown TestScripter error
+                    Any other SymbianOS error
+
+     Errors/Exceptions: Leaves if GetTestCaseL leaves
+                        Leaves if RunTestL leaves
+                        Leaves if memory allocation fails
+     
+     Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestScripter::RunTestCaseL( const TInt aCaseNumber,
+                                  const TFileName& aConfig,
+                                  TTestResult& aResult )
+    {
+
+    // Heap is checked by test server
+    //__UHEAP_MARK;
+
+    __TRACEFUNC();
+
+    //Open new log file with test case title in file name
+    if(iAddTestCaseTitleToLogName)
+        {
+        //Delete test case logger if exists
+        if(iTCLog)
+            {
+            delete iTCLog;
+            iTCLog = NULL;
+            }
+            
+        TFileName logFileName;
+        TName title;
+        TestModuleIf().GetTestCaseTitleL(title);
+        
+        logFileName.Format(KTestScripterLogFileWithTitle, &title);
+        iTCLog = CStifLogger::NewL(KTestScripterLogDir, logFileName);
+        iLog = iTCLog;
+        }
+
+    __TRACE( KMessage, (_L("\n\n***Testcase started***")));
+
+    // Remove locally defined variables 
+    iDefinedLocal.ResetAndDestroy();
+    // Remove existing function parsers (there shouldn't be any)
+    iParserStack.ResetAndDestroy();
+    
+    // Keep file name of config file
+    iConfig = aConfig;
+
+    // Read initialization from test case file
+    ReadInitializationL( aConfig, iDefinedRuntime );
+
+    // Get case from test case file
+    iSectionParser = GetTestCaseL( aCaseNumber, aConfig );
+    iCurrentParser = iSectionParser;
+    iCurrentParserReadFirstLine = EFalse;
+
+    // Check parsing result
+    if( iSectionParser == NULL )
+        {
+        __TRACE( KError, (_L("***Parsing testcase failed***\n\n")));
+        // Delete runtime defines
+        iDefinedRuntime.ResetAndDestroy();
+        //__UHEAP_MARKEND;
+        return KErrNotFound;
+        }
+
+    // When option is set in cfg file, on EKA2 env memory leaking is enabled
+	TInt memCellsBef = 0; //memory in current thread allocated before the test case is run
+	TInt memCellsAft = 0; //memory in current thread allocated after the test case has run
+
+   	memCellsBef = User::Heap().Count();
+	__TRACE(KMessage, (_L("Allocated memory cells before the test case: %d"), memCellsBef));
+
+    CActiveScheduler* activeScheduler =
+        new ( ELeave ) CActiveScheduler();
+    CleanupStack::PushL( activeScheduler );
+     
+    if ( CActiveScheduler::Current() == NULL )
+    	{
+    	CActiveScheduler::Install( activeScheduler );
+    	}
+
+    // Run the given testcase described in iSectionParser section
+    RunTestL();
+
+    iTestObjects.ResetAndDestroy();
+    iTestModules.ResetAndDestroy();
+
+    // TestScripter must stop Active Scheduler after test
+    // object is destroyed. Otherwise if unexpected error occurs
+    // handling is erronous.
+    CleanupStack::PopAndDestroy( activeScheduler );
+
+	// Check for memory leak.
+	// It is reported in log always, but result of test case is changed only
+	// when option in cfg file is enabled.
+	memCellsAft = User::Heap().Count();
+	__TRACE(KMessage, (_L("Allocated memory cells after the test case: %d"), memCellsAft));
+
+	// if there is a difference report memory leak
+	if(memCellsAft != memCellsBef)
+		{
+		__TRACE(KError, (_L("Memory leak, %d cell(s) is missing"), memCellsAft - memCellsBef));
+		if(iCheckHeapBalance)
+			{
+			// Memory leaks detection is disabled for UI components testing
+			if ( !( TestModuleIf().UITesting() ) )
+				{
+				UpdateTestCaseResult(KErrGeneral, _L("Memory leak has occured"));
+				}
+			}
+		}
+
+    // Delete parser and set current parser to NULL
+    iCurrentParser = NULL;
+    delete iSectionParser;
+    iSectionParser = NULL;  
+    
+    // Erase config file name
+    iConfig = KNullDesC; 
+    
+    // Return result 
+    aResult = iResult;
+    
+    if( iResult.iResult == KErrNone )
+        {
+        __TRACE( KPrint, (_L("***Testcase PASSED***\n\n")));
+        TestModuleIf().Printf( KPrintPriNorm, _L("TestScripter"), 
+            _L("***Testcase PASSED***\n\n"));
+        }
+    else
+        {        
+        __TRACE( KPrint, (_L("***Testcase FAILED***\n\n")));
+        TestModuleIf().Printf( KPrintPriNorm, _L("TestScripter"), 
+            _L("***Testcase FAILED***\n\n"));
+        }
+    User::After(300000);
+    // Delete runtime defines
+    iDefinedRuntime.ResetAndDestroy();
+    
+    //__UHEAP_MARKEND;
+             
+    //If log was replaced then restore it
+    if(iAddTestCaseTitleToLogName)
+        {
+        iLog = iStdLog;
+        delete iTCLog;
+        iTCLog = NULL;
+        }
+    
+    return KErrNone;
+     
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: ReadInitializationL
+
+     Description: Read initialization from file.
+
+     Parameters:    const TDesC& aIniFile: in: File that contains initialization
+                    
+     Return Values: None
+     
+     Errors/Exceptions: None
+     
+     Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestScripter::ReadInitializationL(
+    const TDesC& aIniFile,
+    RPointerArray<CDefinedValue>& aDefines )
+    {
+
+    CStifParser* parser = NULL;
+
+    // Open file
+    TRAPD( err,
+        parser = CStifParser::NewL( _L(""),
+                                    aIniFile,
+                                    CStifParser::ECStyleComments ) );
+    if( ( err == KErrNone ) && parser )
+        {
+        CleanupStack::PushL( parser );
+        __TRACE( KMessage, (_L("Read initialization from [%S]"),
+            &aIniFile ) );
+
+        CStifSectionParser* section = parser->SectionL( KDefineStartTag,
+                                                        KDefineEndTag );
+        while(section)
+            {
+            CleanupStack::PushL( section );
+            __TRACE( KMessage, (_L("Read defines")) );
+
+            TPtrC name;
+            TPtrC value;
+            CStifItemParser* item = section->GetItemLineL( _L("") );
+            while( item )
+                {
+                CleanupStack::PushL( item );
+
+                if( item->GetString( _L(""), name ) != KErrNone )
+                    {
+                    __TRACE( KError, (_L("No define name given")) );
+                    User::Leave( KErrGeneral );
+                    }
+                if( item->Remainder( value ) != KErrNone )
+                    {
+                    __TRACE( KError, (_L("No define value given")) );
+                    User::Leave( KErrGeneral );
+                    }
+                TInt count = aDefines.Count();
+                TInt i = 0;
+                for( ; i < count; i++ )
+                    {
+                    if( aDefines[i]->Name() == name )
+                        {
+                        // Update existing
+                        aDefines[i]->SetValueL( value );
+                        __TRACE(KMessage, (_L("Update define [%S]: [%S]"), &name, &value));
+                        break;
+                        }
+                    }
+                if( i == count)
+                    {
+                    // New define, store it
+                    CDefinedValue* define = CDefinedValue::NewL( name, value );
+                    CleanupStack::PushL( define );
+                    User::LeaveIfError( aDefines.Append( define ) );
+                    CleanupStack::Pop( define );
+                    }
+
+                CleanupStack::PopAndDestroy( item );
+                item = section->GetNextItemLineL();
+                }
+            CleanupStack::PopAndDestroy( section );
+            section = parser->NextSectionL(KDefineStartTag, KDefineEndTag);
+            }
+
+		//Read StifSettings section and find value for CheckHeapBalance.
+		//(In cfg file in settings section User may also set CapsModifier
+		// option. This is handled in TestServerClient.cpp in 
+		// RTestServer::GetCapsModifier method).
+		section = parser->SectionL(KStifSettingsStartTag, KStifSettingsEndTag);
+
+		if(section)
+			{
+			CleanupStack::PushL(section);
+			__TRACE(KMessage, (_L("Read stif settings")));
+
+			TPtrC value;
+			CStifItemParser* item = section->GetItemLineL(_L(""));
+			while(item)
+				{
+				CleanupStack::PushL(item);
+				__TRACE( KMessage, (_L("Got settings line")));
+
+				if(item->GetString(_L("CheckHeapBalance="), value) == KErrNone)
+					{
+					__TRACE(KMessage, (_L("Got CheckHeapBalance item, value=%S"), &value));
+					if(value.Compare(_L("off")) == 0)
+		       			{
+		       			iCheckHeapBalance = EFalse;
+		       			}
+					else if(value.Compare(_L("on")) == 0)
+						{
+						iCheckHeapBalance = ETrue;
+		       			}
+					else
+						{
+						__TRACE(KError, (_L("Value '%S' for CheckHeapBalance setting is not supported. Aborting"), &value));
+						User::Leave(KErrNotSupported);
+						}
+					}
+				CleanupStack::PopAndDestroy(item);
+				item = section->GetNextItemLineL();
+				}
+			CleanupStack::PopAndDestroy(section);
+			}
+
+        CleanupStack::PopAndDestroy( parser );
+        }
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetTestCaseL
+
+     Description: Get specified test case section from configfile.
+
+     Parameters:    const TInt aCaseNumber: in: Test case number
+                    const TFileName& aConfig: in: Configfile name 
+     
+     Return Values: CStifSectionParser*: pointer to test case section
+
+     Errors/Exceptions: Leaves if CStifParser::NewL leaves
+                        Leaves if CStifParser::SectionL leaves
+                        Leaves if memory allocation fails
+                                
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CStifSectionParser* CTestScripter::GetTestCaseL( const TInt aCaseNumber, 
+                                             const TFileName& aConfig )
+    {
+    __TRACEFUNC();
+    CStifParser* parser = NULL;
+    
+    TRAPD( err, 
+        parser = CStifParser::NewL( _L(""), 
+                                    aConfig, 
+                                    CStifParser::ECStyleComments ); );
+    if( err != KErrNone )
+        {
+        __TRACE( KError, (_L("Test case file [%S] not found"), &aConfig ));
+        User::Leave( err );
+        }
+    CleanupStack::PushL( parser );
+
+    CStifSectionParser* section = NULL;
+    TRAP( err, 
+        section =parser->SectionL( KTestStartTag, KTestEndTag, aCaseNumber ););
+    if( err != KErrNone )
+        {
+        __TRACE( KError, 
+            (_L("Section [%S/%d] not found"), &aConfig, aCaseNumber ));
+        User::Leave( err );
+        }
+
+    CleanupStack::PopAndDestroy( parser );
+    return section;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetSubL
+
+     Description: Get specified function (sub) from stored config file.
+
+     Parameters:    const TDesC& aSubName: in: function name 
+     
+     Return Values: CStifSectionParser*: pointer to test function section
+
+     Errors/Exceptions: Leaves if CStifParser::NewL leaves
+                        Leaves if CStifParser::SectionL leaves
+                        Leaves if memory allocation fails
+                                
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CStifSectionParser* CTestScripter::GetSubL(const TDesC& aSubName)
+    {
+    __TRACE(KMessage, (_L("Searching sub [%S]."), &aSubName));
+    // Check if config file is set
+    if(iConfig.Length() == 0)
+        {
+        __TRACE(KError, (_L("Searching sub [%S]. Config file is not set."), &aSubName));
+        User::Leave(KErrBadName);
+        }
+        
+    // Create parser
+    CStifParser* parser = NULL;
+    CStifSectionParser* section = NULL;
+        
+    TRAPD(err, 
+          parser = CStifParser::NewL(_L(""), iConfig, CStifParser::ECStyleComments);
+         );
+    if(err != KErrNone)
+        {
+        __TRACE(KError, (_L("Searching sub [%S]. Error [%d] when loading config file [%S]."), &aSubName, err, &iConfig));
+        User::Leave(err);
+        }
+    CleanupStack::PushL(parser);
+
+    // Set section tags
+    _LIT(KEndSubTag, "[EndSub]");
+    TName startSubTag;
+    startSubTag.Copy(_L("[Sub "));
+    startSubTag.Append(aSubName);
+    startSubTag.Append(_L("]"));
+    
+    // Load section
+    TRAP(err, 
+         section = parser->SectionL(startSubTag, KEndSubTag, 1);
+        );
+    if(err != KErrNone)
+        {
+        __TRACE(KError, (_L("Searching sub [%S]. Searching section %S%S ended with error [%d]."), &aSubName, &startSubTag, &KEndSubTag, err));
+        User::Leave(err);
+        }
+    if(!section)
+        {
+        __TRACE(KError, (_L("Searching sub [%S]. Section %S%S not found."), &aSubName, &startSubTag, &KEndSubTag));
+        User::Leave(err);
+        }
+    else
+        {
+        __TRACE(KMessage, (_L("Searching sub [%S]. Section %S%S found."), &aSubName, &startSubTag, &KEndSubTag));
+        }
+
+    CleanupStack::PopAndDestroy(parser);
+    return section;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: RunTestL
+
+     Description: Run a testcase specified by iSectionParser.
+
+     Parameters:    None
+     
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if CSectionParser::GetItemLineL leaves
+                        Leaves if CTestRunner::NewL leaves
+                        Leaves if memory allocation fails                                
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestScripter::RunTestL()
+    {
+    __TRACEFUNC();
+    iResult.iResult = KErrNone;
+    iResult.iResultDes.Zero();
+     
+    // "title" keyword must be in the first line
+    TPtrC title;
+    if( iCurrentParser->GetLine( 
+        TTestKeywords::Keyword( TTestKeywords::ETitle ), title, ENoTag ) 
+        != KErrNone )
+        {
+        __TRACE( KError, (_L("title not found from section")));
+        User::Leave( KErrNotFound ); 
+        }
+    iCurrentParserReadFirstLine = ETrue;
+
+    __TRACE( KMessage, (_L("RunTest: %S"), &title ));
+     
+    iTestRunner = CTestRunner::NewL( this );
+
+    TestModuleIf().Printf( KPrintPriNorm, _L("RunTest"), _L("%S"), &title );
+    
+    // Rest of the job is done by test runner
+    iTestRunner->SetRunnerActive();
+
+    // Start activeScheduler looping testcase lines
+    __TRACE( KMessage, (_L("Start CActiveScheduler")));
+    CActiveScheduler::Current()->Start();
+  
+    delete iTestRunner;
+    iTestRunner = NULL;
+    __TRACE( KMessage, ( _L("RunTestL: Done")));
+ 
+    // Destroy locally defined variables 
+    iDefinedLocal.ResetAndDestroy();
+    // Destroy function parsers (there shouldn't be any)
+    iParserStack.ResetAndDestroy();
+    }     
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetTestModuleL
+
+     Description: Load testmodule if not already loaded, otherwise return
+                  description of the loaded testmodule.
+
+     Parameters:    TDesC& aModule: in: module name
+                    TDesC& aIniFile: in: ini file name
+     
+     Return Values: CTCTestModule*: pointer to testmodules description
+     
+     Errors/Exceptions: Leaves if CTCTestModule::NewL leaves
+                        Leaves if RPointerArray::Append fails  
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/              
+TTestModule* CTestScripter::LoadTestModuleL( TDesC& aModule )
+    {     
+    __TRACEFUNC();
+    TInt count = iTestModules.Count();
+    for( TInt i=0; i < count; i++ )
+        {
+        if( iTestModules[i]->ModuleName() == aModule )
+            {
+            // Found test module, return description
+            __TRACE( KMessage, 
+                (_L("GetTestModuleL: Use already loaded TestModule (%S)"), 
+                &aModule ));
+            return iTestModules[i];
+            }
+        }
+         
+    __TRACE( KMessage, (_L("GetTestModuleL: Load new TestModule (%S)"), 
+        &aModule ));
+    TTestModule* module = new (ELeave) TTestModule();
+    CleanupStack::PushL( module );
+    module->ModuleName() = aModule;
+    User::LeaveIfError( iTestModules.Append( module ) );
+    CleanupStack::Pop( module );
+
+    TInt ret = module->iLibrary.Load ( aModule );
+    
+    if( ret != KErrNone )
+        {
+        __TRACE( KMessage, (_L("GetTestModuleL: %S loading failed"), 
+            &aModule ));
+        TestModuleIf().Printf( KMessage, _L("Load dll"), _L("%S failed"), 
+            &aModule );
+        
+        User::Leave( ret );
+        }
+         
+    // Get pointer to first exported function    
+    module->iLibEntry = (CInterfaceFactory) module->iLibrary.Lookup(1);
+    return module;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: CreateObjectL
+
+     Description: Load testmodule if not already loaded, otherwise return
+                  description of the loaded testmodule.
+
+     Parameters:    TDesC& aModule: in: module name
+                    TDesC& aObjectId: in: object id name
+     
+     Return Values: None
+     
+     Errors/Exceptions: Leaves on error
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestScripter::CreateObjectL( TDesC& aModule, TDesC& aObjectId )
+    {     
+    __TRACEFUNC();
+
+    // Load module and get pointer
+    TTestModule* module = LoadTestModuleL( aModule );
+    TTestObject* object = new (ELeave) TTestObject();
+    CleanupStack::PushL( object );
+    object->ObjectId() = aObjectId;
+    User::LeaveIfError( iTestObjects.Append( object ) );
+    CleanupStack::Pop( object );
+        
+    // Create object    
+    object->iScript = module->iLibEntry( TestModuleIf() );
+    //User::LeaveIfNull ( object->iScript );
+    if( object->iScript == NULL )
+        {
+        User::Leave( KErrGeneral );
+        }
+
+    // Create continue callback 
+    object->iContinue = CTestContinue::NewL( this, object );
+
+    // Create function pointer operation to possible
+    object->iScript->SetScripter( &CallBack, this );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: CreateKernelObjectL
+
+     Description: Load testdriver if not already loaded, otherwise return
+                  description of the loaded testdriver.
+
+     Parameters:    TDesC& aDriver: in: driver name
+                    TDesC& aObjectId: in: object id name
+     
+     Return Values: None
+     
+     Errors/Exceptions: Leaves on error
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestScripter::CreateKernelObjectL( TDesC& aDriver, TDesC& aObjectId )
+    {     
+
+    __TRACEFUNC();
+    
+    if( ( aDriver.Length() > KMaxName ) ||
+        ( aObjectId.Length() > KMaxName ) )
+        {
+        __TRACE( KError, (_L("CreateKernelObjectL: Max lenght exceeded") ) );
+        User::Leave( KErrArgument );
+        }
+    TInt ret = User::LoadLogicalDevice( aDriver );
+    if( ( ret != KErrNone ) && ( ret != KErrAlreadyExists ) )
+        {
+        __TRACE( KError, 
+            (_L("CreateKernelObjectL: User::LoadLogicalDevice failed %d"), 
+                ret ) );
+        User::Leave( ret );
+        } 
+        
+    TTestObjectKernel* object = new (ELeave) TTestObjectKernel();
+    CleanupStack::PushL( object );
+    object->ObjectId() = aObjectId;
+    object->LddName().Copy( aDriver );
+    ret = object->KernelTestClass().Open( 
+                object->KernelTestClass().VersionRequired(), 
+                aDriver );
+    if( ret != KErrNone )
+        {
+        __TRACE( KError, 
+            (_L("CreateKernelObjectL: KernelTestClass().Open failed %d"), 
+                ret ) );
+        User::Leave( ret );
+        }
+        
+    User::LeaveIfError( iTestObjects.Append( object ) );
+    CleanupStack::Pop( object );
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetTestModuleL
+
+     Description: Load testmodule if not already loaded, otherwise return
+                  description of the loaded testmodule.
+
+     Parameters:    TDesC& aModule: in: module name
+                    TDesC& aIniFile: in: ini file name
+     
+     Return Values: CTCTestModule*: pointer to testmodules description
+     
+     Errors/Exceptions: Leaves if CTCTestModule::NewL leaves
+                        Leaves if RPointerArray::Append fails  
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestScripter::DeleteObjectL( TDesC& aObjectId )
+    {     
+    __TRACEFUNC();
+
+    TInt count = iTestObjects.Count();
+    for( TInt i=0; i < count; i++ )
+        {
+        if( iTestObjects[i]->ObjectId() == aObjectId )
+            {
+            TTestObjectBase* object = iTestObjects[i];
+            iTestObjects.Remove( i );
+            delete object;
+            return KErrNone;
+            }
+        }
+     
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetTest
+
+     Description: Get test case from testcase array.
+
+     Parameters:    TDesC& aTestId: in: TestId for testcase
+     
+     Return Values: CTCTestCase*: running/runned testcase
+                    NULL: Testcase with aTestId not running/runned 
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TTestObjectBase* CTestScripter::GetObject( const TDesC& aObjectId )
+    {
+    __TRACEFUNC();
+    
+    TInt count = iTestObjects.Count();
+    for( TInt i=0; i < count; i++ )
+        {
+        if( iTestObjects[i]->ObjectId() == aObjectId )
+            {
+            // Found testcase with specified TestId
+            return iTestObjects[i];
+            }
+        }
+    // Object with iTestObjects not found
+    return NULL;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: CallTestClass
+
+     Description: For sub classing operations.
+  
+     Parameters: const TDesC& aLine: in: script line
+                    
+     Return Values: TInt: Symbian error code
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestScripter::CallTestClass( const TDesC& aLine )
+    {
+    CStifItemParser* item = CStifItemParser::NewL( aLine, 0, aLine.Length() );
+    CleanupStack::PushL( item );
+
+    TPtrC objectName;
+    TInt ret( KErrNone );
+    ret = item->GetString( _L( "" ), objectName );
+    if( ret != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( item);
+        return ret;
+        }
+
+    TTestObjectBase* obj = GetObject( objectName );
+    if( obj == NULL )
+        {
+        CleanupStack::PopAndDestroy(item );
+        return KErrNotFound;
+        }
+
+    TRAPD( commandResult, commandResult = obj->RunMethodL( *item ) );
+
+    CleanupStack::PopAndDestroy(item );
+
+    return commandResult;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetTestScriptObject
+
+     Description: Get object address.
+  
+     Parameters: const TDesC& aObjectName: in: object name
+                    
+     Return Values: TInt: Symbian error code
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestScripter::GetTestScriptObject( const TDesC& aObjectName )
+    {
+
+    TTestObjectBase* objBase = GetObject( aObjectName );
+    if( ( objBase == NULL ) || 
+        ( objBase->ObjectType() != TTestObjectBase::EObjectNormal ) )
+        {
+        return KErrNotFound;
+        }
+    
+    TTestObject* object = ( TTestObject* )objBase;
+    
+    return (TInt) object->iScript;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: UpdateTestCaseResult
+
+     Description: Updates result of test case. If there is already some
+                  description stored, it is put in the [] brackets.
+  
+     Parameters: const TInt aResult: in: error code
+                 const TDesC& aDescr: in: description
+                    
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestScripter::UpdateTestCaseResult(const TInt aResult, const TDesC& aDescr)
+    {
+    // Create buffer
+    RBuf buf;
+
+    TInt ret = buf.Create(iResult.iResultDes.Length() + aDescr.Length() + 5);
+    if(ret != KErrNone)
+        {
+        __TRACE(KError, (_L("UpdateResultDescription: descriptor creation failed [%d]"), ret));
+        return;
+        }
+    CleanupClosePushL(buf);
+
+    // Update result
+    iResult.iResult = aResult;
+    if(iResult.iResultDes.Length() > 0)
+        {
+        buf.Format(_L("%S [%S]"), &aDescr, &iResult.iResultDes);
+        }
+    else
+        {
+        buf.Copy(aDescr);
+        }
+
+    SetResultDescription(buf);
+    
+    // Close buffer
+    CleanupStack::PopAndDestroy(&buf);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: SetResultDescription
+
+     Description: Sets result description of test case.
+  
+     Parameters: const TDesC& aDescr: in: new description
+                    
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void CTestScripter::SetResultDescription(const TDesC& aDescr)
+    {
+    if(aDescr.Length() > KStifMaxResultDes)
+        {
+        iResult.iResultDes.Copy(aDescr.Mid(0, KStifMaxResultDes));
+        }
+    else
+        {
+        iResult.iResultDes.Copy(aDescr);
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: SetLocalValue
+
+     Description: Internal fuction to set value of local variable defined in script 
+
+     Parameters:    const TDesC& aName: in: local variable name 
+                    const TDesC& avalue: in: local variable value
+
+     Return Values: KErrNone: Value is returned succesfully.
+                    KErrNotFound: Variable was not found
+                    Any other SymbianOS error
+                    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestScripter::SetLocalValue(const TDesC& aName, const TDesC& aValue)
+    {	
+    __TRACEFUNC();
+
+    TInt count = iDefinedLocal.Count();
+    for(TInt i = 0; i < count; i++)
+        {
+        if(iDefinedLocal[i]->Name() == aName)
+            {
+            iDefinedLocal[i]->SetValueL(const_cast<TDesC&>(aValue));
+            return KErrNone;
+            }
+        }	
+
+    return KErrNotFound;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestScripter
+
+     Method: GetLocalValue
+
+     Description: Internal fuction to get value of local variable 
+
+     Parameters:    const TDesC& aName: in: local variable name 
+                    const TDesC& avalue: in: local variable value
+
+     Return Values: KErrNone: Value is returned succesfully.
+                    KErrNotFound: Variable was not found
+                    Any other SymbianOS error
+                    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt CTestScripter::GetLocalValue(const TDesC& aName, TDes& aValue)
+    {
+    __TRACEFUNC();
+
+    TInt count = iDefinedLocal.Count();
+    for(TInt i = 0; i < count; i++)
+        {
+        if(iDefinedLocal[i]->Name() == aName)
+            {
+            aValue.Copy(iDefinedLocal[i]->Value());
+            return KErrNone;
+            }
+        }	
+
+    return KErrNotFound;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CTestRunner class 
+    member functions. CTestRunner is used to execute TestScripter testcase by 
+    CTestScripter.
+
+-------------------------------------------------------------------------------
+*/
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iTestScripter->iLog
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: CTestRunner
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: CTestScripter* aTestScripter: in: Backpointer to CTestScripter
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestRunner::CTestRunner( CTestScripter* aTestScripter ): 
+    CActive(  CActive::EPriorityHigh ), // Executed with highest priority 
+    iState( ERunnerIdle ),
+    iTestScripter( aTestScripter ),
+    iRemainingTimeValue( 0 )
+    {
+    CActiveScheduler::Add( this );
+    __TRACEFUNC();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::ConstructL()
+    {
+    
+    iPauseTimer.CreateLocal();
+    
+    // Initiaze all OOM related variables to default.
+    OOMHeapToNormal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters: CTestScripter* aTestScripter: in: Backpointer to CTestScripter
+
+     Return Values: CTestRunner*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+
+CTestRunner* CTestRunner::NewL( CTestScripter* aTestScripter )
+    {
+    CTestRunner* self = new (ELeave) CTestRunner( aTestScripter );
+     
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ~CTestRunner
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/     
+
+CTestRunner::~CTestRunner()
+    {
+    __TRACEFUNC();
+    Cancel();
+
+    iPauseTimer.Close();
+    
+    delete iLine;
+    iLine = NULL;
+    
+    TInt count = iEventArray.Count();
+    TEventIf event( TEventIf::ERelEvent ); 
+    for( TInt i = 0; i < count; i++ )
+        {
+        HBufC* tmp = iEventArray[0];
+        event.SetName( iEventArray[0]->Des() );
+        iEventArray.Remove(0);
+		if( iTestScripter != NULL )
+			{
+			iTestScripter->TestModuleIf().Event( event );
+			}
+        delete tmp;
+        }
+     
+    iTestCaseResults.Reset();
+    iEventArray.ResetAndDestroy();
+    iTestCaseResults.Close();
+    iEventArray.Close();
+
+    // Reset test case allow result to CTestModuleIf side too. This is
+    // used in TAL-TA5L macro handling.
+	if( iTestScripter != NULL )
+		{
+		User::LeaveIfError( 
+			iTestScripter->TestModuleIf().ResetAllowResult() );
+		}
+		
+    // Stop all remaining interference object
+    TInt count_inter = iTestInterferenceArray.Count();
+    for( TInt a = 0; a < count_inter; a++ )
+        {
+		if( iTestInterferenceArray[a] != NULL )
+			{
+			iTestInterferenceArray[a]->iInterference->Stop();
+			}
+        }
+    iTestInterferenceArray.ResetAndDestroy();
+    iTestInterferenceArray.Close();
+    
+    // Stop all remaining measurement modules
+    const TInt count_meas = iTestMeasurementArray.Count();
+    for( TInt b = 0; b < count_meas; b++ )
+        {
+		if( iTestMeasurementArray[b] != NULL )
+			{
+			iTestMeasurementArray[b]->iMeasurement->Stop();
+			}
+        }
+    iTestMeasurementArray.ResetAndDestroy();
+    iTestMeasurementArray.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: RunL
+
+     Description: Derived from CActive, handles testcase execution.
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::RunL()
+    {
+    __TRACEFUNC();
+    __TRACE( KMessage, (_L("CTestRunner::RunL: [%d] "), iStatus.Int() ));
+     
+    // Check if we need to Pause test case again  
+    if( iStatus == KErrNone && iRemainingTimeValue > 0 )
+        {           
+        // Maximum time for one RTimer::After request                   
+        TInt maximumTime = KMaxTInt / 1000;                       
+        
+        __TRACE( KMessage, (_L("CTestRunner::RunL: Going to reissue After request ") ) );           
+        __TRACE( KMessage, (_L("CTestRunner::RunL: iRemainingTimeValue = %d"), iRemainingTimeValue ) );        
+        
+        if( iRemainingTimeValue < maximumTime )
+            {                           
+            iPauseTimer.After( iStatus, ( iRemainingTimeValue * 1000  ) );
+            iRemainingTimeValue = 0;
+            }
+        else
+            {            
+            iRemainingTimeValue -= maximumTime;
+            iPauseTimer.After( iStatus, ( maximumTime * 1000 ) );                
+            }     
+        SetActive();
+        }     
+    else    
+        {  
+        TBool continueTask = EFalse;
+
+        User::LeaveIfError( iStatus.Int() );
+
+        if( ( iTestScripter == NULL ) || 
+            ( iTestScripter->iCurrentParser == NULL ) )
+            {
+            __TRACE( KError, (_L("CTestRunner invalid arguments")));
+            User::Leave( KErrGeneral );
+            }
+           
+        iState = ERunnerIdle;
+
+        // Get next execution line from configuration section
+        TPtrC line;
+        // If current parser already has read the first line, then read next line.
+        // Otherwise read the first line.
+        if(iTestScripter->iCurrentParserReadFirstLine && iTestScripter->iCurrentParser->GetNextLine(line) == KErrNone 
+           || !iTestScripter->iCurrentParserReadFirstLine && iTestScripter->iCurrentParser->GetLine(KNullDesC, line) == KErrNone)
+            {
+            iTestScripter->iCurrentParserReadFirstLine = ETrue;
+            
+            // Got new execution line 
+            __TRACE( KMessage, (_L("Executing line [%S]"), &line));
+            
+            CStifItemParser* item = PreprocessLineL( line );
+                
+            CleanupStack::PushL( item ); 
+              
+            TPtrC keyword;
+             // Get first word from line, i.e. keyword
+            User::LeaveIfError( item->GetString( _L(""), keyword ) );
+
+            __TRACE( KMessage, (_L("CTestRunner execute %S"), &keyword ));
+
+            // Execute script line 
+            continueTask = ExecuteLineL( keyword, item );
+            __TRACE( KMessage, (_L("CTestRunner %S executed"), &keyword ));
+                         
+            if( continueTask )
+                {
+                  __TRACE( KMessage, (_L("RunL: continueTask")));
+                 // Set CTestRunner active again to perform 
+                 // next execution line
+                 // from testcase section 
+                SetRunnerActive();
+                }
+
+            CleanupStack::PopAndDestroy( item );
+            }
+        else // Stop execution if end of test case
+            {
+            __TRACE( KMessage, (_L("Executing line: no more lines from this section")));
+            // There is no more lines in current parser, but it needs to be
+            // checked if the parser is not taken for function (sub).
+            // If this is true, then we have to get back to the parser which
+            // has called the function.
+            TInt lastParserIndex = iTestScripter->iParserStack.Count() - 1;
+            if(lastParserIndex >= 0)
+                {
+                // Delete current (the last one) parser
+                delete iTestScripter->iParserStack[lastParserIndex];
+                iTestScripter->iParserStack.Remove(lastParserIndex);
+                if(lastParserIndex >= 1) //There is some other parser on the stack
+                    {
+                    iTestScripter->iCurrentParser = iTestScripter->iParserStack[lastParserIndex - 1];
+                    }
+                else //The parser stack is empty
+                    {
+                    iTestScripter->iCurrentParser = iTestScripter->iSectionParser;
+                    }
+                __TRACE(KMessage, (_L("Returning to calling parser stored on section stack")));
+                
+                // Continue with the test case
+                __TRACE(KMessage, (_L("RunL: continueTask (end of Sub reached)")));
+                SetRunnerActive();
+                return;
+                }
+            // No more execution lines in testcase section
+            __TRACE( KMessage, 
+                (_L("CTestRunner::RunL: Testcase script done") ));
+            iTestScripter->TestModuleIf().Printf( KPrintPriLow, 
+                _L("RunL"), _L("Script done"));
+            
+       
+            __TRACE( KMessage, 
+                (_L("RunL: All TestCases done, stop CActiveScheduler")));
+            CActiveScheduler::Current()->Stop();
+            // Now testcase section is executed, 
+            // so CTestRunner has done its job and stops
+            }
+        }
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: DoCancel
+
+     Description: Derived from CActive handles the Cancel
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::DoCancel()
+    {
+    __TRACEFUNC();
+    __TRACE( KMessage, (_L("CTestRunner::DoCancel")));
+    iTestScripter->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), _L("DoCancel"));
+    
+    if( iState == ERunnerPaused )
+        {
+        iPauseTimer.Cancel();
+        }
+   
+    CActiveScheduler::Current()->Stop();
+         
+    iState = ERunnerCancel;
+      
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: RunError
+
+     Description: Derived from CActive handles errors from active handler.
+  
+     Parameters:    TInt aError: in: error from CActive
+     
+     Return Values: KErrNone: success
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestRunner::RunError( TInt aError )
+    {
+    __TRACEFUNC();
+    __TRACE( KMessage, (_L("CTestRunner::RunError %d"), aError));
+
+    if ( iRunErrorMessage.Length() != 0 )
+    	{
+	    iTestScripter->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), 
+	            _L("RunError : %S"), &iRunErrorMessage );  
+	    iRunErrorMessage = KNullDesC;
+    	}
+    else
+    	{
+	    iTestScripter->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), 
+	            _L("RunError"));        	
+    	}
+
+    iState = ERunnerError;
+    
+    // Return error from here, if none given from execution
+    if( iTestScripter->iResult.iResult == KErrNone )
+        {
+        iTestScripter->UpdateTestCaseResult(aError, _L("CTestRunner::RunError"));
+        }
+        
+    CActiveScheduler::Current()->Stop();
+        
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: PreprocessLineL
+
+     Description: Preprocesses script line
+  
+     Parameters:  TPtrC& line: in: script line
+                  CStifItemParser*& aItem: out: New CItemParser for script line.
+                    
+     Return Values: HBufC* pointer if new memory that has been allocated
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/        
+CStifItemParser* CTestRunner::PreprocessLineL( TDesC& line )
+    {
+    CStifItemParser* item = NULL;
+    TPtrC tmp;
+    TInt len = 0;
+    TInt ret = 0;
+        
+    // Decide how long buffer should be allocated
+    if( line.Length() < KMaxName/2 )
+        {
+        len = KMaxName;
+        }
+    else 
+        {
+        len = line.Length() + KMaxName;
+        }
+    delete iLine;
+    iLine = 0;
+    iLine = HBufC::NewL(len);
+    TPtr parsedLine(iLine->Des());
+    len = 0;
+    
+    HBufC* sourceLine = line.AllocL();
+    CleanupStack::PushL(sourceLine);
+    
+    //Check for local variable definitions
+    item = CStifItemParser::NewL(sourceLine->Des(), 0, sourceLine->Length());
+    CleanupStack::PushL(item);
+    
+    ret = item->GetString(KNullDesC, tmp);
+    TBool isVarDefinition = (tmp == TTestKeywords::Keyword(TTestKeywords::EVar));
+         
+    if(!isVarDefinition)
+        {
+        while( ret == KErrNone )
+            {
+            len += CheckDefinedLocals(tmp);
+            if((parsedLine.Length() + tmp.Length() + 1) > parsedLine.MaxLength())
+                {
+                // Allocate bigger buffer
+                HBufC* tmpBuf = HBufC::NewL(parsedLine.MaxLength() + KMaxName);
+                CleanupStack::PushL(tmpBuf);
+                TPtrC ptr(iLine->Des());
+                parsedLine.Set(tmpBuf->Des());
+                parsedLine.Copy(ptr);
+                delete iLine;
+                iLine = tmpBuf;
+                CleanupStack::Pop(tmpBuf);
+                } 
+            parsedLine.Append(tmp);        
+            ret = item->GetNextString(tmp);
+            if(ret == KErrNone)
+                {
+                // Add space only if we got new string
+                parsedLine.Append(_L(" "));        
+                }
+            }
+        CleanupStack::PopAndDestroy(item);
+        item = NULL;
+        CleanupStack::PopAndDestroy(sourceLine);
+        sourceLine = NULL;
+        
+        //Prepare data for checking for defines
+        sourceLine = parsedLine.AllocL();
+        CleanupStack::PushL(sourceLine);
+        parsedLine.Zero();
+        
+        item = CStifItemParser::NewL(sourceLine->Des(), 0, sourceLine->Length());
+        CleanupStack::PushL(item);
+    
+        ret = item->GetString(KNullDesC, tmp);
+        }
+
+    //Check for defines
+    while(ret == KErrNone)
+        {
+        if(!isVarDefinition)
+            {
+            len += CheckDefined(tmp);
+            }
+        
+        if((parsedLine.Length() + tmp.Length() + 1) > parsedLine.MaxLength())
+            {
+            // Allocate bigger buffer
+            HBufC* tmpBuf = HBufC::NewL(parsedLine.MaxLength() + KMaxName);
+            CleanupStack::PushL(tmpBuf);
+            TPtrC ptr(iLine->Des());
+            parsedLine.Set(tmpBuf->Des());
+            parsedLine.Copy(ptr);
+            delete iLine;
+            iLine = tmpBuf;
+            CleanupStack::Pop(tmpBuf);
+            } 
+        parsedLine.Append(tmp);        
+        ret = item->GetNextString(tmp);
+        if( ret == KErrNone )
+            {
+            // Add space only if we got new string
+            parsedLine.Append(_L(" "));        
+            }
+        }
+    
+    //Cleaning...
+    CleanupStack::PopAndDestroy(item);
+    item = NULL;
+    CleanupStack::PopAndDestroy(sourceLine);
+    sourceLine = NULL;
+
+    __TRACE(KMessage, (_L("Preprocessed line [%S]"), &parsedLine));
+    item = CStifItemParser::NewL( parsedLine, 0, parsedLine.Length() );
+    
+    return item;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: CheckDefined
+
+     Description: Check if aWord is some defined word
+  
+     Parameters:  TPtrC& aWord: inout: Parsed word, defined or original returned
+                    
+     Return Values: TInt: length diference between new and old word
+     
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/   
+TInt CTestRunner::CheckDefined( TPtrC& aWord )
+    {
+    
+    TInt len = 0;
+    TInt i = 0;
+
+    // KLoopCounter word changing to current loop count value.
+    if( aWord == KLoopCounter )
+        {
+        iLoopCounterDes.Zero();
+        iLoopCounterDes.AppendNum( iLoopCounter );
+        len = iLoopCounterDes.Length() - aWord.Length();
+        aWord.Set( iLoopCounterDes );
+        return len;
+        }
+
+    // First, check values defined in test case file
+    TInt count = iTestScripter->iDefinedRuntime.Count();
+    for( i = 0; i < count; i++ )
+        {
+        if( iTestScripter->iDefinedRuntime[i]->Name() == aWord )
+            { 
+            len = iTestScripter->iDefinedRuntime[i]->Value().Length() - aWord.Length();
+            aWord.Set( iTestScripter->iDefinedRuntime[i]->Value() );
+            return len;
+            }
+        }
+
+    // Second, check values defined in test module initialization file
+    count = iTestScripter->iDefinedIni.Count();
+    for( i = 0; i < count; i++ )
+        {
+        if( iTestScripter->iDefinedIni[i]->Name() == aWord )
+            { 
+            len = iTestScripter->iDefinedIni[i]->Value().Length() - aWord.Length();
+            aWord.Set( iTestScripter->iDefinedIni[i]->Value() );
+            return len;
+            }
+        }
+
+    return len;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: CheckDefinedLocals
+
+     Description: Check if aWord is a local variable
+  
+     Parameters:  TPtrC& aWord: inout: Parsed word, defined or original returned
+                    
+     Return Values: TInt: length diference between new and old word
+     
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/   
+TInt CTestRunner::CheckDefinedLocals( TPtrC& aWord )
+    {
+    
+    TInt len = 0;
+    TInt i = 0;
+
+    TInt count = iTestScripter->iDefinedLocal.Count();
+    for(i = 0; i < count; i++)
+        {
+        if(iTestScripter->iDefinedLocal[i]->Name() == aWord)
+            { 
+            len = iTestScripter->iDefinedLocal[i]->Value().Length() - aWord.Length();
+            aWord.Set(iTestScripter->iDefinedLocal[i]->Value());
+            return len;
+            }
+        }
+
+    return len;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteLineL
+
+     Description: Executes script line
+  
+     Parameters:    TDesC& aKeyword: in: keyword string
+                    CStifItemParser* aItem: in: script line
+                    
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteLineL( TDesC& aKeyword,
+                                 CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgDeleteNoParam, "Delete: Name of object is not defined" );
+    _LIT( KErrMsgDeleteObjNotFound, "Delete: Can't delete object %S. Object does not exists." );
+    _LIT( KErrMsgPauseTimeoutNotDefined, "Pause: No timeout value given or value has invalid format" );
+    _LIT( KErrMsgPauseTimeoutNotPositive, "Pause: Timeout value can't be <0" );
+    _LIT( KErrMsgCreateTestModeleNotDefined, "Create: Name of test module is not defined" );
+    _LIT( KErrMsgCreateObjectIdNotDefined, "Create: Name of test module object is not defined" );
+    _LIT( KErrMsgCreateKernelDriverNotDefined, "CreateKernel: Kernel driver name is not defined" );
+    _LIT( KErrMsgCreateKernelObjectNameNotDefined, "CreateKernel: Kernel driver object name is not defined" );
+    _LIT( KErrMsgCreateKernelFailed, "CreateKernel: Can't creeate kernel driver %S" );
+    _LIT( KErrMsgWaitTestClassNameNotDefined, "WaitTestClass: Test class object name is not defined" );
+    _LIT( KErrMsgWaitTestClassObjNotFound, "WaitTestClass: Test class object %S does not exists" );
+    _LIT( KErrMsgLoopNested, "Loop: Nested loop are not supported" );
+    _LIT( KErrMsgLoopNoParam, "Loop: No loop iterations count given or value has invalid format" );
+    _LIT( KErrMsgLoopInvalidParam, "Loop: Loop count must be >0" );
+    _LIT( KErrMsgLoopUnknownUnexpectedOption, "Loop: Unknown or unexpected loop option");
+    _LIT( KErrMsgEndLoopNotOpened, "Endloop: Can't execute endloop. No opened loop exists" );
+    _LIT( KErrMsgBringToForegroundNotSupported, "BringToForeground: BringToForeground is not supported in non s60 environment" );
+    _LIT( KErrMsgSendToBackgroundNotSupported, "SendToBackground: SendToBackground is not supported in non s60 environment" );    
+    _LIT( KErrMsgPressKeyNotSupported, "PressKey: PressKey is not supported in non s60 environment. Check if .cfg file name contains ui_ prefix and UITestingSupport= YES entry is defined in TestFrameworkd.ini" );
+    _LIT( KErrMsgTypeTextNotSupported, "TypeText: TypeText is not supported in non s60 environment. Check if .cfg file name contains ui_ prefix and UITestingSupport= YES entry is defined in TestFrameworkd.ini" );
+    _LIT( KErrMsgSendPointerEventNotSupported, "SendPointerEvent: SendPointerEvent is not supported in non s60 environment. Check if .cfg file name contains ui_ prefix and UITestingSupport= YES entry is defined in TestFrameworkd.ini" );
+    _LIT( KErrVarNameError, "Variable: Could not get variable name");
+    _LIT( KErrVarValueError, "Variable: Value too long");
+    _LIT( KErrSubNameError, "Sub: Could not get name of Sub to be called");
+    _LIT( KErrSubGetError, "Sub: Could not get Sub section");
+    
+    iRunErrorMessage = KNullDesC;    
+    TBool continueTask = ETrue;
+    
+    TInt key = TTestKeywords::Parse( aKeyword, TTestKeywords::Keyword );
+
+    switch( key )
+        {
+        // Test case execution control cases
+        case TTestKeywords::ECreate:
+        case TTestKeywords::ECreateX:
+            {
+            TPtrC tmp;
+            TName module;
+
+            // Testmodule name
+            TInt ret = aItem->GetNextString( tmp );
+            if ( ret != KErrNone )
+            	{
+            	iRunErrorMessage = KErrMsgCreateTestModeleNotDefined;
+            	User::Leave( KErrArgument );
+            	}
+            TParse p;
+            p.Set( tmp, NULL, NULL );
+            // Check if exists in module name
+            if( p.ExtPresent() )
+                {
+                module.Copy( tmp );
+                }
+            else 
+                {
+                // No extension in module name, add it here
+                _LIT( KDllExtension, ".dll");
+                module.Copy( tmp );
+                module.Append( KDllExtension );
+                }
+
+            // objectid
+            ret = aItem->GetNextString( tmp );
+            if ( ret != KErrNone )
+            	{
+            	iRunErrorMessage = KErrMsgCreateObjectIdNotDefined;
+            	User::Leave( KErrArgument );
+            	}        
+
+            __TRACE( KMessage, (_L("%S %S"), &aKeyword, &tmp));
+            iTestScripter->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), 
+                _L("%S %S"), &aKeyword, &tmp);
+
+            iTestScripter->CreateObjectL( module, tmp );
+            }
+            break;
+        case TTestKeywords::ECreateKernel:
+            {
+            TPtrC obj;
+            TPtrC driver;
+
+            // Testdriver name
+            TInt ret = aItem->GetNextString( driver );
+            if ( ret != KErrNone )
+            	{
+            	iRunErrorMessage = KErrMsgCreateKernelDriverNotDefined;
+            	User::Leave( ret );
+            	}
+
+            // objectid            
+            ret = aItem->GetNextString( obj );
+            if ( ret != KErrNone )
+            	{
+            	iRunErrorMessage = KErrMsgCreateKernelObjectNameNotDefined;
+            	User::Leave( ret );
+            	}
+
+            __TRACE( KMessage, (_L("%S %S"), &aKeyword, &obj));
+            iTestScripter->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), 
+                _L("%S %S"), &aKeyword, &obj);
+            TInt leaveErr = KErrNone;
+            TRAP( leaveErr, iTestScripter->CreateKernelObjectL( driver, obj ));
+            if ( leaveErr != KErrNone )
+            	{
+            	iRunErrorMessage.Format( KErrMsgCreateKernelFailed, &driver );
+                User::Leave( leaveErr );
+            	}
+            }
+            break;
+        case TTestKeywords::EDelete:
+            {
+            TPtrC tmp;
+            // objectid
+            TInt ret = aItem->GetNextString( tmp );
+            if ( ret != KErrNone )
+            	{
+                iRunErrorMessage = KErrMsgDeleteNoParam;
+            	User::Leave( ret );
+            	}
+
+            __TRACE( KMessage, (_L("%S %S"), &aKeyword, &tmp));
+            iTestScripter->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), 
+                _L("%S %S"), &aKeyword, &tmp);
+
+            ret = iTestScripter->DeleteObjectL( tmp );
+            if ( ret != KErrNone )
+            	{
+            	iRunErrorMessage.Format( KErrMsgDeleteObjNotFound, &tmp );
+            	User::Leave( ret );
+            	}
+            }
+            break;
+        case TTestKeywords::ERequest:
+        case TTestKeywords::EWait:
+        case TTestKeywords::ERelease:
+        case TTestKeywords::ESet:
+        case TTestKeywords::EUnset:
+            continueTask = ExecuteEventL( aKeyword, aItem );
+            break;
+        case TTestKeywords::EPrint:
+            {
+            __TRACE( KMessage, (_L("%S"), &aKeyword));
+            iTestScripter->TestModuleIf().Printf( KPrintPriLow, _L("Runner"), 
+                _L("%S"), &aKeyword );
+
+            RBuf buf;
+            buf.CreateL(1024);
+            CleanupClosePushL(buf);
+            
+            TPtrC tmp;
+
+            while( aItem->GetNextString( tmp ) == KErrNone )
+                {
+                if( buf.Length() + tmp.Length() >= buf.MaxLength() )
+                    {
+                    buf.ReAllocL(buf.MaxLength() + tmp.Length() * 10);
+                    }
+                buf.Append( tmp );
+                buf.Append( _L(" ") );
+                }
+            
+            iTestScripter->TestModuleIf().Printf( KPrintPriNorm, 
+                _L("Test"), 
+                _L("%S"), &buf);
+            RDebug::Print( _L("Print : Test : %S"), &buf );
+            CleanupStack::PopAndDestroy(&buf);
+            }
+            break;
+        case TTestKeywords::EAllowNextResult:
+            {
+            AddTestCaseResultL( aItem );
+            }
+            break;
+        case TTestKeywords::EWaitTestClass:
+            {
+            // Just stop script running, continue event is signaled 
+            // from test class with specified object name
+            TPtrC objectName;
+            // Get Object name
+            TInt ret = aItem->GetNextString( objectName );
+            if ( ret != KErrNone )
+            	{
+               	iRunErrorMessage = KErrMsgWaitTestClassNameNotDefined;
+            	User::Leave( ret );
+            	}
+            TTestObjectBase* obj = iTestScripter->GetObject ( objectName );
+            //User::LeaveIfNull( obj );
+            if( obj == NULL )
+                {
+               	iRunErrorMessage.Format( KErrMsgWaitTestClassObjNotFound, &objectName );
+                User::Leave( KErrGeneral );
+                }
+            continueTask = obj->Wait();
+            
+            if( continueTask )
+                {
+                // If OOM testing is ongoing ignore result check(given by user)
+                if( !iTestScripter->iOOMIgnoreFailure )
+                    {
+                    if( iTestCaseResults.Count() == 0 )
+                        {
+                        // KErrNone is the default result expected 
+                        // if nothing else is given 
+                        User::LeaveIfError( iTestCaseResults.Append( 
+                                                                KErrNone ) );
+                        }
+                    
+                    if( iTestCaseResults.Find( obj->iAsyncResult ) < 0 ) 
+                        {
+                        __TRACE( KError, ( _L("Command for [%S] failed (%d)"), 
+                                &objectName, obj->iAsyncResult ));
+                        iTestScripter->UpdateTestCaseResult(obj->iAsyncResult, _L("CTestRunner::ExecuteLineL: asynchronous method returned error"));
+                        // Stops execution from CTestRunner::RunError
+                        User::Leave( KErrGeneral );
+                        }
+                    }
+                else
+                    {
+                    __TRACE( KMessage, ( 
+                        _L( "OOM test: 'oomignorefailure' is ON, test case result will reset" ) ) );
+                    }
+
+                iTestCaseResults.Reset();
+                // Reset test case allow result to CTestModuleIf side too. This is
+                // used in TAL-TA5L macro handling.
+                User::LeaveIfError( 
+                    iTestScripter->TestModuleIf().ResetAllowResult() );
+                }
+
+            }
+            break;
+        case TTestKeywords::EPause:
+            {
+            // Maximum time for one RTimer::After request
+            TInt maximumTime = KMaxTInt / 1000;
+            // Set iRemainingTimeValue to zero
+            iRemainingTimeValue = 0;
+
+            TInt timeout;
+            // Read valid results to timeout
+            if( aItem->GetNextInt( timeout ) != KErrNone )
+                {
+                __TRACE( KError, (_L("CTestRunner::ExecuteLineL: No timeout value given for pause")));
+                iRunErrorMessage = KErrMsgPauseTimeoutNotDefined;
+                User::Leave( KErrArgument );
+                }
+
+            // Test case file parsing was success
+
+            __TRACE( KMessage, (_L("CTestRunner::ExecuteLineL: Pause for %d milliseconds"), timeout));
+
+            if( timeout < 0 )
+                {
+                __TRACE( KError, (_L("CTestRunner::ExecuteLineL: Given pause value < 0")));
+                iRunErrorMessage = KErrMsgPauseTimeoutNotPositive;
+                User::Leave( KErrArgument );
+                }
+            else
+                {
+                // Check is pause value suitable for RTimer::After
+                if( timeout < maximumTime )
+                    {
+                    iPauseTimer.After( iStatus, ( timeout * 1000  ) );
+                    }
+                else
+                    {
+                    // Given pause value after multiplication with 1000 is
+                    // larger than KMaxTInt, so we need to split it and 
+                    // re-request After with remaining value from RunL
+
+                    iRemainingTimeValue =  timeout - maximumTime;
+                    iPauseTimer.After( iStatus, maximumTime * 1000 );
+                    }
+
+                SetActive();
+
+                // Stop execution after paused for given timeout
+                continueTask = EFalse;
+                }
+            }
+            break;
+        case TTestKeywords::ELoop:
+            {
+            if( iLoopTimes > 0 )
+                {
+                __TRACE( KError, (_L("ExecuteLineL: Nested loop are not supported")));
+                iRunErrorMessage = KErrMsgLoopNested;
+                User::Leave( KErrNotSupported );
+                }
+            iLoopTimes = 0;
+            iLoopCounter = 0;
+            iTimedLoop = EFalse;
+            if( aItem->GetNextInt( iLoopTimes ) != KErrNone )
+                {
+                __TRACE( KError, (_L("ExecuteLineL: No loop count value given for loop")));
+                iRunErrorMessage = KErrMsgLoopNoParam;
+                User::Leave( KErrArgument );
+                }
+            if( iLoopTimes < 1 )
+            	{
+                __TRACE( KError, (_L("ExecuteLineL: Loop count must be >0")));
+                iRunErrorMessage = KErrMsgLoopInvalidParam;
+                User::Leave( KErrArgument );
+            	}
+            __TRACE( KMessage, (_L("ExecuteLineL: Loop for %d times" ), iLoopTimes ) );
+            
+            //Check loop options
+            TPtrC option;
+            TInt ret = aItem->GetNextString(option);
+            if(ret == KErrNone)
+                {
+                if(option.Compare(_L("msec")) == 0) //time loop option
+                    {
+                    iTimedLoop = ETrue;
+                    iStartTime.HomeTime();
+                    iExpectedLoopTime = TInt64(iLoopTimes) * TInt64(1000); //convert to micro seconds
+                    __TRACE(KMessage, (_L("ExecuteLineL: Timed loop for %d msec" ), iLoopTimes));
+                    
+                    ret = aItem->GetNextString(option); //Get next option
+                    }
+                }
+                
+            if(ret == KErrNone)
+                {
+                __TRACE( KError, (_L("ExecuteLineL: Unknown or unexpected loop option [%S]"), &option));
+                iRunErrorMessage = KErrMsgLoopUnknownUnexpectedOption;
+                User::Leave( KErrNotSupported );
+                }
+            
+            iLoopStartPos = iTestScripter->iCurrentParser->GetPosition();
+            }
+            break;
+        case TTestKeywords::EEndLoop:
+            {
+            if( iLoopTimes == 0 )
+            	{
+            	__TRACE( KError, (_L("ExecuteLineL: Can't execute endloop. No opened loop exists")));
+            	iRunErrorMessage = KErrMsgEndLoopNotOpened;
+            	User::Leave( KErrNotFound );
+            	}
+            iLoopCounter++;
+            __TRACE( KMessage, 
+                (_L("ExecuteLineL: Loop executed for %d times" ), 
+                    iLoopCounter ) );
+
+            TTime currTime;
+            currTime.HomeTime();
+            if(((!iTimedLoop) && (iLoopCounter < iLoopTimes)) //Normal loop
+               ||
+               iTimedLoop && (currTime.MicroSecondsFrom(iStartTime) < iExpectedLoopTime)) //Timed loop
+                {
+                // Go to beginning of the loop
+                User::LeaveIfError(
+                    iTestScripter->iCurrentParser->SetPosition( iLoopStartPos ));
+                }
+            else
+                {            
+                // End looping
+                iLoopCounter = 0;
+                iLoopTimes = 0;
+                iLoopStartPos = 0;
+                }
+            }
+            break;
+        case TTestKeywords::ETimeout:
+        case TTestKeywords::EPriority:
+            // not used here
+            break;
+        case TTestKeywords::EOOMIgnoreFailure:
+            {
+            OOMIgnoreFailureL( aItem );  // Handle parsing
+            break;
+            }
+        case TTestKeywords::EOOMHeapFailNext:
+            {
+            OOMHeapFailNextL( aItem );   // Handle parsing
+            break;
+            }
+        case TTestKeywords::EOOMHeapSetFail:
+            {
+            OOMHeapSetFailL( aItem );    // Handle parsing
+            break;
+            }
+       case TTestKeywords::EOOMHeapToNormal:
+            {
+            // Initialize all OOM related variables back to default.
+            OOMHeapToNormal();
+            __TRACE( KMessage, (
+                _L( "'oomheaptonormal' called, OOM initialization or ending OOM test") ) );
+            break;
+            }
+       case TTestKeywords::ETestInterference:
+            {
+            TestInterferenceL( aItem );  // Handle parsing
+            break;
+            }
+       case TTestKeywords::EMeasurement:
+            {
+            MeasurementL( aItem );      // Handle parsing
+            break;
+            }
+       case TTestKeywords::EAllowErrorCodes:
+            {
+            // Check is KErrNone already appended to iTestCaseResults array.
+            if( iTestCaseResults.Find( KErrNone ) < 0 )
+                {
+                // 'allowerrorcodes' keyword sets KErrNone as a default
+                User::LeaveIfError( iTestCaseResults.Append( KErrNone ) );
+                // Set test case allow result to CTestModuleIf side too. This
+                // is used in TAL-TA5L macro handling.
+                User::LeaveIfError( 
+                    iTestScripter->TestModuleIf().SetAllowResult( KErrNone ) );
+                }
+
+            // Set user given specific error code to be allowed.
+            AddTestCaseResultL( aItem );
+            }
+            break;
+
+       case TTestKeywords::EBringToForeground:
+    	   {
+    	   if ( iTestScripter->TestModuleIf().UITesting() == true )
+    		   {
+    		   iTestScripter->TestModuleIf().GetUiEnvProxy()->BringToForeground();
+    		   }
+    	   else
+    		   {
+	           	__TRACE( KError, (_L("ExecuteLineL: Can't execute bringtoforeground in non s60 environment. Check if .cfg file name contains ui_ prefix and UITestingSupport= YES entry is defined in TestFrameworkd.ini")));
+	        	iRunErrorMessage = KErrMsgBringToForegroundNotSupported;
+	        	User::Leave( KErrNotSupported );    		   
+    		   }
+    	   }
+       		break;
+       case TTestKeywords::ESendToBackground:
+    	   {
+    	   if ( iTestScripter->TestModuleIf().UITesting() == true )
+    		   {
+    		   iTestScripter->TestModuleIf().GetUiEnvProxy()->SendToBackground();
+    		   }
+    	   else
+    		   {
+	           	__TRACE( KError, (_L("ExecuteLineL: Can't execute sendtobackground in non s60 environment. Check if .cfg file name contains ui_ prefix and UITestingSupport= YES entry is defined in TestFrameworkd.ini")));
+	        	iRunErrorMessage = KErrMsgSendToBackgroundNotSupported;
+	        	User::Leave( KErrNotSupported );    		   
+    		   }
+    	   }
+       		break;
+       case TTestKeywords::EPressKey:
+    	   {
+    	   if ( iTestScripter->TestModuleIf().UITesting() == true )
+    		   {
+    		   continueTask = PressKeyL( aItem );
+    		   }
+    	   else
+    		   {
+    		   __TRACE( KError, (_L("ExecuteLineL: Can't execute presskey in non s60 environment. Check if .cfg file name contains ui_ prefix and UITestingSupport= YES entry is defined in TestFrameworkd.ini")));
+    		   iRunErrorMessage = KErrMsgPressKeyNotSupported;
+    		   User::Leave( KErrNotSupported );    		   
+    		   }	
+
+    	   // Check if it was global or local presskey
+    	   if ( !continueTask )
+    		   {
+	           // Stop execution after key is pressed and wait until it is handled
+	           SetActive();
+    		   }           
+    	   }
+       		break;
+       case TTestKeywords::ETypeText:
+    	   {
+    	   if ( iTestScripter->TestModuleIf().UITesting() == true )
+    		   {
+    		   continueTask = TypeTextL( aItem );
+    		   }
+    	   else
+    		   {
+    		   __TRACE( KError, (_L("ExecuteLineL: Can't execute typetext in non s60 environment. Check if .cfg file name contains ui_ prefix and UITestingSupport= YES entry is defined in TestFrameworkd.ini")));
+    		   iRunErrorMessage = KErrMsgTypeTextNotSupported;
+    		   User::Leave( KErrNotSupported );    		   
+    		   }
+
+    	   // Check if it was global or local typetext
+    	   if ( !continueTask )
+    		   {
+	           // Stop execution after key is pressed and wait until it is handled
+	           SetActive();
+    		   }           
+    	   }
+       		break;
+        case TTestKeywords::EVar:
+            {
+            TName name;
+            TName buf;
+            TPtrC tmp;
+            
+            //Get variable name
+            if(aItem->GetNextString(tmp) == KErrNone)
+                {
+                name.Copy(tmp);
+                }
+            else
+                {
+                //Error when getting variable name
+                __TRACE(KError, (_L("ExecuteLineL: Could not read variable name")));
+                iRunErrorMessage = KErrVarNameError;
+                User::Leave(KErrArgument);                
+                }
+
+            //Get value for variable
+            while(aItem->GetNextString(tmp) == KErrNone)
+                {
+                if(buf.Length() + tmp.Length() >= buf.MaxLength())
+                    {
+                    //Error when getting variable name
+                    __TRACE(KError, (_L("ExecuteLineL: Variable value too long")));
+                    iRunErrorMessage = KErrVarValueError;
+                    User::Leave(KErrArgument);                
+                    }
+                buf.Append(tmp);
+                buf.Append(_L(" "));
+                }
+            //Remove last space
+            if(buf.Length() > 0)
+                {
+                buf.SetLength(buf.Length() - 1);
+                }
+                
+            //Store local variable
+            TInt count = iTestScripter->iDefinedLocal.Count();
+            TInt i;
+            for(i = 0; i < count; i++)
+                {
+                if(iTestScripter->iDefinedLocal[i]->Name() == name)
+                    {
+                    // Update existing
+                    iTestScripter->iDefinedLocal[i]->SetValueL(buf);
+                    __TRACE(KMessage, (_L("Update local variable [%S]: [%S]"), &name, &buf));
+                    break;
+                    }
+                }
+            if(i == count)
+                {
+                // New define, store it
+                CDefinedValue* define = CDefinedValue::NewL(name, buf);
+                CleanupStack::PushL(define);
+                User::LeaveIfError(iTestScripter->iDefinedLocal.Append(define));
+                CleanupStack::Pop(define);
+                __TRACE(KMessage, (_L("Add local variable [%S]: [%S]"), &name, &buf));
+                }
+            }
+            break;
+        case TTestKeywords::ECallSub:
+            {
+            // Get sub name
+            TPtrC subName;
+            
+            //Get sub name
+            TInt err = aItem->GetNextString(subName);
+            if(err != KErrNone)
+                {
+                //Error when getting sub name
+                __TRACE(KError, (_L("ExecuteLineL: Could not read sub name [%d]"), err));
+                iRunErrorMessage = KErrSubNameError;
+                User::Leave(KErrArgument);                
+                }
+            
+            // Load section
+            CStifSectionParser* subSection = NULL;
+            TRAP(err, 
+                 subSection = iTestScripter->GetSubL(subName);
+                );
+            if((err != KErrNone) || (!subSection))
+                {
+                //Error when getting sub name
+                if(err == KErrNone)
+                    {
+                    err = KErrArgument;
+                    }
+                __TRACE(KError, (_L("ExecuteLineL: Could not get section for sub [%d]"), err));
+                iRunErrorMessage = KErrSubGetError;
+                User::Leave(err);                
+                }
+            
+            // Handle new section parser
+            CleanupStack::PushL(subSection);
+            iTestScripter->iParserStack.AppendL(subSection);
+            __TRACE(KMessage, (_L("ExecuteLineL: Section for sub [%S] appended to section stack"), &subName));
+            CleanupStack::Pop(subSection);
+            iTestScripter->iCurrentParser = subSection;
+            iTestScripter->iCurrentParserReadFirstLine = EFalse; //Change it to false, becaue subSection is a new parser and it has nothing read
+            }
+            break;
+        case TTestKeywords::ESetResultDescription:
+            {
+            __TRACE(KMessage, (_L("%S"), &aKeyword));
+            iTestScripter->TestModuleIf().Printf(KPrintPriLow, _L("Runner"), _L("%S"), &aKeyword);
+
+            TName buf;
+            TPtrC tmp;
+
+            while(aItem->GetNextString(tmp) == KErrNone)
+                {
+                if(buf.Length() + tmp.Length() >= buf.MaxLength())
+                    {
+                    break;
+                    }
+                if(buf.Length() > 0)
+                    {
+                    buf.Append(_L(" "));
+                    }
+                buf.Append(tmp);
+                }
+            
+            iTestScripter->SetResultDescription(buf);
+            RDebug::Print( _L("SetDescription to [%S]"), &buf );
+            }
+            break;
+        case TTestKeywords::ESendPointerEvent:
+     	   {
+     	   if ( iTestScripter->TestModuleIf().UITesting() == true )
+     		   {
+     		   continueTask = SendPointerEventL( aItem );
+     		   }
+     	   else
+     		   {
+     		   __TRACE( KError, (_L("ExecuteLineL: Can't execute sendpointerevent in non s60 environment. Check if .cfg file name contains ui_ prefix and UITestingSupport= YES entry is defined in TestFrameworkd.ini")));
+     		   iRunErrorMessage = KErrMsgSendPointerEventNotSupported;
+     		   User::Leave( KErrNotSupported );    		   
+     		   }
+
+     	   // Check if it was global or local sendpointerevent
+     	   if ( !continueTask )
+     		   {
+ 	           // Stop execution after pointer event is send and wait until it is handled
+ 	           SetActive();
+     		   }           
+     	   }
+     	   break;
+        default:
+            {
+            continueTask = ExecuteCommandL( aKeyword, aItem );
+            }
+            break;
+        }
+
+    __TRACE( KMessage, (_L("ExecuteLineL: TestCase line executed")));
+
+    return continueTask;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: PressKeyL
+
+     Description: Send key press event to AppUi
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: None
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::PressKeyL( CStifItemParser* aItem )
+	{
+    _LIT( KErrMsgSendKeyEventInvalidParameterValue, "PressKey: Invalid parameter %s value " );
+    _LIT( KErrMsgSendKeyEventInvalidParameter, "PressKey: Invalid parameter %s" );    
+    
+    _LIT( KKeyCodeParameter, "keycode=" );
+    _LIT( KKeyScanCodeParameter, "keyscancode=" );
+    _LIT( KModifierParameter, "modifier=" );
+    _LIT( KRepeatsParameter, "repeats=" );
+    
+    _LIT( KModeGlobal, "global" );
+    _LIT( KModeLocal, "local" );
+    
+    TBool globalMode = EFalse;
+	TUint keyCode = 0; 
+	TInt keyScanCode = 0; 
+	TUint keyModifiers = 0; 
+	TInt keyRepeats = 0;
+		
+	TPtrC parameter;
+		
+	CUiEnvProxy* uiEnvProxy = iTestScripter->TestModuleIf().GetUiEnvProxy();
+	
+	while( aItem->GetNextString( parameter ) == KErrNone )
+		{
+		if ( parameter.Find( KKeyCodeParameter ) == 0 )
+			{
+			TPtrC parameterValue = parameter.Right( parameter.Length() - KKeyCodeParameter().Length() );
+			TLex parameterValueParser( parameterValue );
+			if ( parameterValueParser.Val( keyCode ) != KErrNone )
+				{
+					if ( uiEnvProxy->ParseKeyCode( parameterValue, keyCode ) != KErrNone )
+						{
+						__TRACE( KError, (_L("SendKeyEvent: Invalid parameter value")));
+						TBuf<128> errMsg;
+						errMsg.Format( KErrMsgSendKeyEventInvalidParameterValue, &KKeyCodeParameter() );
+						iRunErrorMessage = errMsg;
+						User::Leave( KErrArgument );    		   				
+						}
+				}
+			}
+		else if ( parameter.Find( KKeyScanCodeParameter ) == 0 )
+			{
+			TPtrC parameterValue = parameter.Right( parameter.Length() - KKeyScanCodeParameter().Length() );
+			TLex parameterValueParser( parameterValue );
+			if ( parameterValueParser.Val( keyScanCode ) != KErrNone )
+				{
+				if ( uiEnvProxy->ParseKeyScanCode( parameterValue, keyScanCode ) != KErrNone )
+					{
+					__TRACE( KError, (_L("SendKeyEvent: Invalid parameter value")));
+					TBuf<128> errMsg;
+					errMsg.Format( KErrMsgSendKeyEventInvalidParameterValue, &KKeyCodeParameter() );
+					iRunErrorMessage = errMsg;
+					User::Leave( KErrArgument );    		   				
+					}
+				}
+			}
+		else if ( parameter.Find( KModifierParameter ) == 0 )
+			{
+			TPtrC parameterValue = parameter.Right( parameter.Length() - KModifierParameter().Length() );
+			TLex parameterValueParser( parameterValue );
+			if ( parameterValueParser.Val( keyModifiers ) != KErrNone )
+				{
+				if ( uiEnvProxy->ParseModifier( parameterValue, keyModifiers ) != KErrNone )
+					{
+					__TRACE( KError, (_L("SendKeyEvent: Invalid parameter value")));
+					TBuf<128> errMsg;
+					errMsg.Format( KErrMsgSendKeyEventInvalidParameterValue, &KModifierParameter() );
+					iRunErrorMessage = errMsg;
+					User::Leave( KErrArgument );    		   				
+					}
+				}
+			}
+		else if ( parameter.Find( KRepeatsParameter ) == 0 )
+			{
+			TPtrC parameterValue = parameter.Right( parameter.Length() - KRepeatsParameter().Length() );
+			TLex parameterValueParser( parameterValue );
+			if ( parameterValueParser.Val( keyRepeats ) != KErrNone )
+				{
+				__TRACE( KError, (_L("SendKeyEvent: Invalid parameter value")));
+				TBuf<128> errMsg;
+				errMsg.Format( KErrMsgSendKeyEventInvalidParameterValue, &KRepeatsParameter() );
+				iRunErrorMessage = errMsg;
+				User::Leave( KErrArgument );    		   				
+				}
+			}
+		else if ( parameter == KModeGlobal )
+			{
+			globalMode = ETrue;
+			}
+		else if ( parameter == KModeLocal )
+			{
+			globalMode = EFalse;
+			}
+		else if ( uiEnvProxy->ParseKeyCode( parameter, keyCode ) == KErrNone ) 
+			{			
+			}			
+		else if ( parameter.Length() == 1 )
+			{
+			keyCode = parameter[ 0 ];
+			}
+		else
+			{
+			__TRACE( KError, (_L("PressKey: Invalid parameter")));
+			TBuf<128> errMsg;
+			errMsg.Format( KErrMsgSendKeyEventInvalidParameter, &parameter );
+			iRunErrorMessage = errMsg;
+			User::Leave( KErrArgument );   			
+			}
+		}
+	
+	if ( globalMode )
+		{
+		uiEnvProxy->PressKeyL( keyCode, keyScanCode, keyModifiers, keyRepeats );			
+		}
+	else
+		{
+		uiEnvProxy->PressKeyL( &iStatus, keyCode, keyScanCode, keyModifiers, keyRepeats );
+		}
+		
+	return globalMode;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: TypeTextL
+
+     Description: Sends text to AppUi
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: None
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::TypeTextL( CStifItemParser* aItem )
+	{
+	_LIT( KErrMsgTypeTextInvalidParameter, "TypeText: Invalid parameter %S" );
+	_LIT( KErrMsgTypeTextNotEnoughParameters, "TypeText: Not enough parameters" );
+	
+	TBool globalMode = EFalse;
+	
+	TPtrC command;
+	TPtrC text;
+	aItem->SetParsingType( CStifItemParser::EQuoteStyleParsing );
+	
+	// Read first parameter
+	TInt ret = aItem->GetNextString( command );
+	
+	if ( ret != KErrNone )
+		{
+		__TRACE( KError, (_L("TypeText: Not enough parameters")));
+		iRunErrorMessage = KErrMsgTypeTextNotEnoughParameters;
+		User::Leave( ret );
+		}
+	
+	// Read second parameter
+	ret = aItem->GetNextString( text );
+	
+	// Check if second can be read. if yes then check if first parameters is
+	// 'global' parameter
+	if ( ret != KErrNone )
+		{
+		// normal type text
+		text.Set( command );
+		iTestScripter->TestModuleIf().GetUiEnvProxy()->TypeTextL( &iStatus, text );
+		globalMode = EFalse;
+		}
+	else if ( command == _L("global") )
+		{
+		iTestScripter->TestModuleIf().GetUiEnvProxy()->TypeTextL( text );
+		globalMode = ETrue;
+		}
+	else
+		{
+		__TRACE( KError, (_L("TypeText: Invalid parameter")));
+		TBuf<128> errMsg;
+		errMsg.Format( KErrMsgTypeTextInvalidParameter, &command );
+		iRunErrorMessage = errMsg;
+		User::Leave( KErrNotSupported );
+		}
+		
+	return globalMode;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: SendPointerEventL
+
+     Description: Send key press event to AppUi
+  
+     Parameters:    CStifItemParser* aItem: in: script line
+     
+     Return Values: None
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::SendPointerEventL( CStifItemParser* aItem )
+	{
+	// Error messages
+    _LIT( KErrMsgNotEnoughParameters, "SendPointerEvent: Not enough parameters" );
+    _LIT( KErrMsgPointerEventTypeNotDefined, "SendPointerEvent: Pointer event type not defined" );
+    _LIT( KErrMsgInvalidUnknownPointerEventType, "SendPointerEvent: Invalid/Unknown pointer event type %S" );
+    _LIT( KErrMsgPositionXNotDefined, "SendPointerEvent: x co-ordinate is not defined" );
+    _LIT( KErrMsgPositionYNotDefined, "SendPointerEvent: y co-ordinate is not defined" );
+    _LIT( KErrMsgPositionXInvalidValue, "SendPointerEvent: Invalid value of x co-ordinate" );
+    _LIT( KErrMsgPositionYInvalidValue, "SendPointerEvent: Invalid value of y co-ordinate" );
+
+    // Parameters keywords
+    _LIT( KModeGlobal, "global" );
+    _LIT( KModeLocal, "local" );
+    
+    TBool globalMode = EFalse;
+	TUint eventType = 0; 
+	TPoint position( 0, 0 );
+	TPoint parentPosition( 0, 0 );
+		
+	TPtrC parameter;
+
+	CUiEnvProxy* uiEnvProxy = iTestScripter->TestModuleIf().GetUiEnvProxy();
+
+	// Get first parameter
+	if ( aItem->GetNextString( parameter ) != KErrNone )
+		{
+		__TRACE( KError, (_L("SendPointerEvent: Not enough parameters")));
+		iRunErrorMessage = KErrMsgNotEnoughParameters;
+		User::Leave( KErrArgument );   			
+		}
+	else
+		{
+		TBool modeSelected = EFalse;
+		// Check if global/local mode is defined
+		if ( parameter == KModeLocal )
+			{
+			globalMode = false;
+			modeSelected = ETrue;
+			}
+		else if ( parameter == KModeGlobal )
+			{
+			globalMode = true;
+			modeSelected = ETrue;
+			}
+		
+		if ( modeSelected )
+			{
+			// First parameter was mode so we need get next parameter which should 
+			// contain event type
+			if ( aItem->GetNextString( parameter ) != KErrNone )
+				{
+				__TRACE( KError, (_L("SendPointerEvent: Pointer event type not defined")));
+				iRunErrorMessage = KErrMsgPointerEventTypeNotDefined;
+				User::Leave( KErrArgument );   			
+				}
+			}
+		}
+	
+	// Parse event type
+	if ( uiEnvProxy->ParsePointerEventType( parameter, eventType ) != KErrNone )
+		{
+		__TRACE( KError, (_L("PressKey: Invalid/Unknown pointer event type %S"), &parameter ));
+		iRunErrorMessage.Format( KErrMsgInvalidUnknownPointerEventType, &parameter );
+		User::Leave( KErrArgument );   			
+		}
+	
+	if ( aItem->GetNextString( parameter ) != KErrNone )
+		{
+		__TRACE( KError, (_L("SendPointerEvent: x co-ordinate is not defined")));
+		iRunErrorMessage = KErrMsgPositionXNotDefined;
+		User::Leave( KErrArgument );   			
+		}
+
+	TLex parameterParser( parameter );
+	if ( parameterParser.Val( position.iX ) != KErrNone )
+		{
+		__TRACE( KError, (_L("SendPointerEvent: Invalid value of x co-ordinate")));
+		iRunErrorMessage = KErrMsgPositionXInvalidValue;
+		User::Leave( KErrArgument );   			
+		}
+
+	if ( aItem->GetNextString( parameter ) != KErrNone )
+		{
+		__TRACE( KError, (_L("SendPointerEvent: y co-ordinate is not defined")));
+		iRunErrorMessage = KErrMsgPositionYNotDefined;
+		User::Leave( KErrArgument );   			
+		}
+
+	parameterParser.Assign( parameter );
+	if ( parameterParser.Val( position.iY ) != KErrNone )
+		{
+		__TRACE( KError, (_L("SendPointerEvent: Invalid value of y co-ordinate")));
+		iRunErrorMessage = KErrMsgPositionYInvalidValue;
+		User::Leave( KErrArgument );   			
+		}		
+		
+	// Send pointer event
+	if ( globalMode )
+		{
+		uiEnvProxy->SendPointerEventL( eventType, position );			
+		}
+	else
+		{
+		uiEnvProxy->SendPointerEventL( &iStatus, eventType, position );
+		}
+
+	return globalMode;
+	}
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteEventL
+
+     Description: Executes event command script line
+  
+     Parameters:    TDesC& aKeyword: in: keyword string
+                    CStifItemParser* aItem: in: script line
+     
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteEventL( TDesC& aKeyword,
+                                  CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgEventNameNotDefined, "%S : Event name not defined" );
+    _LIT( KErrMsgUnknowKeyword, "Unknow keyword %S" );
+    
+    TInt ret = KErrNone;
+    TInt key = TTestKeywords::Parse( aKeyword, TTestKeywords::Keyword );
+    TBool continueTask = ETrue;
+     
+    TPtrC eventName;
+    // read eventname
+    ret = aItem->GetNextString( eventName );
+    if ( ret != KErrNone )
+    	{
+    	iRunErrorMessage.Format( KErrMsgEventNameNotDefined, &aKeyword );
+    	User::Leave( ret );
+    	}
+    
+    TEventIf event;
+    event.SetName( eventName );
+    
+    __TRACE( KMessage, (_L("%S %S"), &aKeyword, &eventName));
+    iTestScripter->TestModuleIf().Printf( KPrintPriLow, _L("Event"), 
+        _L("%S %S"), &aKeyword, &eventName);
+
+    switch( key )
+        {
+        case TTestKeywords::ERequest:
+            {
+            HBufC* eName = eventName.AllocLC();
+            User::LeaveIfError( iEventArray.Append( eName ) );
+            CleanupStack::Pop( eName );
+            event.SetType( TEventIf::EReqEvent );
+            ret = iTestScripter->TestModuleIf().Event( event );
+            }
+            break;
+        case TTestKeywords::EWait:
+            {
+            event.SetType( TEventIf::EWaitEvent );
+            iTestScripter->TestModuleIf().Event( event, iStatus );
+            SetActive();
+            continueTask = EFalse;
+            }
+            break;
+        case TTestKeywords::ERelease:
+            {
+            event.SetType( TEventIf::ERelEvent );
+            ret = iTestScripter->TestModuleIf().Event( event );
+            if( ret == KErrNone )
+                {
+                TPtrC eName;
+                TInt count = iEventArray.Count();
+                for( TInt i = 0; i < count; i++ )
+                    {
+                    eName.Set( iEventArray[i]->Des() );
+                    if( eName == eventName )
+                        {
+                        HBufC* tmp = iEventArray[i];
+                        iEventArray.Remove(i);
+                        delete tmp;
+                        break;
+                        }
+                    }
+                }
+            }
+            break;
+        case TTestKeywords::ESet:
+            {
+            event.SetType( TEventIf::ESetEvent );
+            
+            TPtrC tmp;
+            // Get optional set argument
+            if( aItem->GetNextString( tmp ) == KErrNone )
+                {                      
+                // Parse optional set argument
+                if( tmp == _L("state") )
+                    {
+                    __TRACE( KMessage, (_L("State event")));
+                    event.SetEventType( TEventIf::EState );
+                    }
+                else
+                    {
+                    __TRACE( KError, 
+                        (_L("Unknown argument for set %S"), 
+                        &tmp));
+                    }
+                }      
+            
+            ret = iTestScripter->TestModuleIf().Event( event );
+            }
+            break;
+        case TTestKeywords::EUnset:
+            {
+            event.SetType( TEventIf::EUnsetEvent );
+            event.SetEventType( TEventIf::EState );
+            ret = iTestScripter->TestModuleIf().Event( event );
+            }
+            break;
+        default:
+            __TRACE( KError, (_L("Unknown keyword %S"), &aKeyword));
+            iRunErrorMessage.Format( KErrMsgUnknowKeyword, &aKeyword );
+            User::Leave( KErrGeneral );
+            break;
+        }
+    if( ret != KErrNone )
+        {
+        TName resultDescr;
+        resultDescr.Format(_L("Event %S returned error: %d"), &aKeyword, ret);
+        iTestScripter->UpdateTestCaseResult(ret, resultDescr);
+        // Stops execution from CTestRunner::RunError
+        User::Leave( KErrGeneral );
+        }
+
+    return continueTask;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: ExecuteCommandL
+
+     Description: Executes script line
+
+     Parameters:    TDesC& aObject: in: object name 
+                    CStifItemParser* aItem: in: script line
+
+     Return Values: ETrue: continue script file execution
+                    EFalse: stop script file execution
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestRunner::ExecuteCommandL( TDesC& aObject, CStifItemParser* aItem)
+    {
+    _LIT( KErrMsgUnknownObjOrKeyword, "Unknow keyword/object %S" );
+    
+    TTestObjectBase* obj = iTestScripter->GetObject ( aObject );    
+    if( obj == NULL )
+        {
+        iRunErrorMessage.Format( KErrMsgUnknownObjOrKeyword, &aObject );
+        User::Leave( KErrGeneral );
+        }
+
+    if( iTestCaseResults.Count() == 0 )
+        {
+        // KErrNone is the default result expected if nothing else is given 
+        User::LeaveIfError( iTestCaseResults.Append( KErrNone ) );
+        }
+
+    // OOM heap testing with FAILNEXT
+    if( iHeapFailNext > 0 )
+        {
+        __TRACE( KPrint, ( 
+            _L( "OOM FAILNEXT is used with count value: %d " ),
+            iHeapFailNext) );
+        User::__DbgSetAllocFail( RHeap::EUser, RHeap::EFailNext, iHeapFailNext  );
+        }
+    // OOM heap testing with SETFAIL
+    if( iHeapSetFailValue > 0 )
+        {
+        __TRACE( KPrint, (
+            _L("OOM SETFAIL is used with type:[%d] and value(rate):[%d]"),
+            iHeapSetFailType, iHeapSetFailValue ) );
+        User::__DbgSetAllocFail( RHeap::EUser, iHeapSetFailType, iHeapSetFailValue );
+        }
+
+    TInt commandResult = KErrNone;
+    TRAP( commandResult, commandResult = obj->RunMethodL( *aItem ) );
+
+    
+    // Reset OOM macro immediately(Otherwise other allocations
+    // will be blocked)
+    User::__DbgSetAllocFail( RHeap::EUser, RHeap::ENone, 1 );
+
+    // OOM test class's build block handling
+    if( iTestScripter->iOOMIgnoreFailure )
+        {
+        __TRACE( KPrint, ( 
+            _L( "----------< OOM related test information >----------" ) ) );
+        if( iHeapFailNext > 0 )
+            {
+            __TRACE( KPrint, ( 
+                _L( "'oomignorefailure' is:[ON] and 'failnextvalue' count is:[%d]" ),
+                iHeapFailNext ) );
+            }
+        if( iHeapSetFailValue > 0 )
+            {
+            __TRACE( KPrint, ( 
+                _L( "'oomignorefailure' is:[ON], 'setfailtype' type is:[%d] and value is:[%d]" ),
+                iHeapSetFailType, iHeapSetFailValue ) );
+            }
+        __TRACE( KPrint, ( 
+            _L( "Test class build block execution with result:[%d]" ),
+            commandResult ) );
+        __TRACE( KPrint, ( 
+            _L( "----------------------------------------------------" ) ) );
+
+        // Continue testing, despite the memory error situations
+        iTestCaseResults.Reset();
+        return ETrue; // Continue script executions
+        }
+
+    // Normal test class's build block handling
+    if( iTestCaseResults.Find( commandResult ) < 0 ) 
+        {
+        __TRACE( KError, ( _L("Command for [%S] failed (%d)"), 
+                &aObject, commandResult ));
+
+        // Added more logging for this special case
+        if( commandResult == KErrNone )
+            {
+            __TRACE( KError, (_L("Test fails with result KErrGeneral, because execution result was KErrNone and expected results given with 'allownextresult' were Symbian's error codes (<0)")));    
+            }
+           
+        iTestScripter->UpdateTestCaseResult(commandResult, _L("CTestRunner::ExecuteCommandL returned error"));
+
+        // Stops execution from CTestRunner::RunError
+        User::Leave( KErrGeneral );
+        }
+        
+    iTestCaseResults.Reset();
+    // Reset test case allow result to CTestModuleIf side too. This is
+    // used in TAL-TA5L macro handling.
+    User::LeaveIfError( 
+        iTestScripter->TestModuleIf().ResetAllowResult() );
+        
+    return ETrue;
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: SetRunnerActive
+
+     Description: Set CTestRunner active and complete.
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::SetRunnerActive()
+     {
+     __TRACEFUNC();
+     // Update state
+     iState = ERunnerRunning;
+
+     iStatus = KRequestPending;
+     TRequestStatus* rs = &iStatus;
+     SetActive();
+     User::RequestComplete( rs, KErrNone );
+
+     }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: OOMIgnoreFailure
+
+     Description: Handles 'oomignorefailure' keyword parsing.
+  
+     Parameters: CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::OOMIgnoreFailureL( CStifItemParser* aItem )
+    {
+    _LIT( KerrMsgOOMIgnoreFailureUnknownArgument, "OOMIgnoreFailure : Invalid argument %S" );
+    _LIT( KerrMsgOOMIgnoreFailureNoArgument, "OOMIgnoreFailure : Parameter not defined" );
+    
+    __TRACEFUNC();
+
+    TPtrC tmp;
+    // Get result
+    if( aItem->GetNextString( tmp ) == KErrNone )
+        {                      
+        if( tmp == _L("ON") || tmp == _L("on") )
+            {
+            __TRACE( KMessage, (_L("OOM related 'oomignorefailure': ON")));
+            iTestScripter->iOOMIgnoreFailure = ETrue;
+            }
+        else if( tmp == _L("OFF") || tmp == _L("off") )
+            {
+            __TRACE( KMessage, (_L("OOM related 'oomignorefailure': OFF")));
+            iTestScripter->iOOMIgnoreFailure = EFalse;
+            }
+        else
+            {
+            __TRACE( KError, 
+                (_L("Unknown argument for 'oomignorefailure': [%S]"), 
+                &tmp));
+            iRunErrorMessage.Format( KerrMsgOOMIgnoreFailureUnknownArgument, &tmp );
+            User::Leave( KErrArgument );
+            }
+        }
+    else
+        {
+        __TRACE( KError, ( _L( "Unknown argument for 'oomignorefailure'" ) ) );
+        iRunErrorMessage = KerrMsgOOMIgnoreFailureNoArgument;
+        User::Leave( KErrArgument );
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: OOMHeapFailNext
+
+     Description: Handles 'oomheapfailnext' keyword parsing.
+  
+     Parameters: CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::OOMHeapFailNextL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgHeapFailNextNoArgument, "HeapFailNext : Parameters is not defined or has invalid value" );
+    _LIT( KErrMsgHeapFailNextInvalidValue, "HeapFailNext : Argument value can't be <0" );
+    __TRACEFUNC();
+
+    TInt heapfailNext( 0 );
+    // If LOOP_COUNTER is used the GetNextInt returns a correct
+    // value(Because of the LOOP_COUNTER implementation).
+    if( aItem->GetNextInt( heapfailNext ) == KErrNone )
+        {
+        if( heapfailNext < 0 )
+        	{
+        	__TRACE( KError, ( _L( "Argument value must be >0" ) ) );
+            iRunErrorMessage = KErrMsgHeapFailNextInvalidValue;
+            User::Leave( KErrArgument );        	
+        	}
+        // OOM heap's FAILNEXT range is from 1 to n
+        iHeapFailNext = heapfailNext + 1;
+        __TRACE( KMessage, ( _L( "'oomheapfailnext' count value(rate): %d" ),
+            iHeapFailNext ) );
+        }
+    else
+        {
+        __TRACE( KError, ( _L( "Unknown argument for 'oomheapfailnext'" ) ) );
+        iRunErrorMessage = KErrMsgHeapFailNextNoArgument;
+        User::Leave( KErrArgument );
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: OOMHeapSetFail
+
+     Description: Handles 'oomheapsetfail' keyword parsing.
+  
+     Parameters: CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::OOMHeapSetFailL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgOOMHeapSetFailTypeNotDefined, "OOMHeapSetFail : Parameter type is not defined" );
+    _LIT( KErrMsgOOMHeapSetFailRateNotDefined, "OOMHeapSetFail : Parameter rate is not defined" );
+    _LIT( KErrMsgOOMHeapSetFailTypeInvalidValue, "OOMHeapSetFail : Parameter type has invalid value" );
+    _LIT( KErrMsgOOMHeapSetFailRateInvalidValue, "OOMHeapSetFail : Parameter rate can't be <0" );
+    __TRACEFUNC();
+
+    TPtrC type;
+    TInt value( 0 );
+
+    // NOTE: If error in type or value parsing => return without changing
+    //       iHeapSetFailType or iHeapSetFailValue valiables.
+
+    // Get type
+    if( aItem->GetNextString( type ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'oomheapsetfail' type" ) ) );
+        iRunErrorMessage = KErrMsgOOMHeapSetFailTypeNotDefined;
+        User::Leave( KErrArgument );
+        }
+    // Get value(rate)
+    if( aItem->GetNextInt( value ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'oomheapsetfail' value(rate)" ) ) );
+        iRunErrorMessage = KErrMsgOOMHeapSetFailRateNotDefined;
+        User::Leave( KErrArgument );
+        }    
+    
+    // All parsing operations are passed, get type and value
+
+    // Get type
+    if( type == _L("random") )
+        {
+        __TRACE( KMessage, (_L("'oomheapsetfail' type: random")));
+        iHeapSetFailType = RHeap::ERandom;
+        }
+    else if( type == _L("truerandom") )
+        {
+        __TRACE( KMessage, (_L("'oomheapsetfail' type: truerandom")));
+        iHeapSetFailType = RHeap::ETrueRandom;
+        }
+    else if( type == _L("deterministic") )
+        {
+        __TRACE( KMessage, (_L("'oomheapsetfail' type: deterministic")));
+        iHeapSetFailType = RHeap::EDeterministic;
+        }
+    else if( type == _L("none") )
+        {
+        __TRACE( KMessage, (_L("'oomheapsetfail' type: none")));
+        iHeapSetFailType = RHeap::ENone;
+        }
+    else if( type == _L("failnext") )
+        {
+        __TRACE( KMessage, (_L("'oomheapsetfail' type: failnext")));
+        iHeapSetFailType = RHeap::EFailNext;
+        }
+    else
+        {
+        __TRACE( KError, 
+            ( _L( "Unknown argument for 'oomheapsetfail' type: [%S]" ),
+            &type ) );
+        iRunErrorMessage = KErrMsgOOMHeapSetFailTypeInvalidValue;
+        User::Leave( KErrArgument );
+        }
+
+    if( value < 0 )
+    	{
+        __TRACE( KError, _L( "'oomheapsetfail' value(rate) can't be <0" ) );    	    	
+        iRunErrorMessage = KErrMsgOOMHeapSetFailRateInvalidValue;
+        User::Leave( KErrArgument );
+    	}
+    // Get value
+    // OOM heap's SETFAIL range is from 1 to n
+    iHeapSetFailValue = value + 1;
+    __TRACE( KMessage, ( 
+        _L( "'oomheapsetfail' value(rate): %d" ), iHeapSetFailValue ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: OOMHeapToNormal
+
+     Description: Initialize all OOM related variables.
+  
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::OOMHeapToNormal()
+    {
+    __TRACEFUNC();
+
+    if( iTestScripter )
+        {
+        // This should initialize also
+        iTestScripter->iOOMIgnoreFailure = EFalse;
+        }
+
+    iHeapFailNext = 0;
+    iHeapSetFailType = RHeap::ENone;
+    iHeapSetFailValue = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: TestInterference
+
+     Description: Starts test interference.
+  
+     Parameters: CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::TestInterferenceL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgTestInterferenceNameNotDefined, "TestInterference : Parameter name is not defined" );
+    _LIT( KErrMsgTestInterferenceCommandNotDefined, "TestInterference : Parameter command is not defined" );
+    _LIT( KErrMsgTestInterferenceCommandInvalidValue, "TestInterference : Parameter command has invalid value" );
+    __TRACEFUNC();
+    TPtrC name;
+    TPtrC command;
+
+    // Get name
+    if( aItem->GetNextString( name ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' name" ) ) );
+        iRunErrorMessage = KErrMsgTestInterferenceNameNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+    // Get command
+    if( aItem->GetNextString( command ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' command" ) ) );
+        iRunErrorMessage = KErrMsgTestInterferenceCommandNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+
+    if( command == _L( "start" ) )
+        {
+        __TRACE( KMessage, ( _L( "'testinterference' called, starts test interference") ) );
+        StartInterferenceL( name, aItem );
+        }
+    else if( command == _L( "stop" ) )
+        {
+        __TRACE( KMessage, ( _L( "'testinterference' called, stops and releases test interference") ) );
+        StopInterferenceL( name );
+        }
+    else
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown command for 'testinterference'[%S]" ), &command ) );
+        iRunErrorMessage = KErrMsgTestInterferenceCommandInvalidValue;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: StartInterference
+
+     Description: 
+  
+     Parameters: CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::StartInterferenceL( TDesC& aName, CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgStartInterferenceCategoryNotDefined, "TestInterference : Parameter category is not defined" );
+    _LIT( KErrMsgStartInterferenceCategoryInvalidValue, "TestInterference : Parameter category has invalid value" );
+    _LIT( KErrMsgStartInterferenceTypeNotDefined, "TestInterference : Parameter type is not defined" );
+    _LIT( KErrMsgStartInterferenceTypeInvalidValue, "TestInterference : Parameter type has invalid value" );
+    _LIT( KErrMsgStartInterferenceIdleNotDefined, "TestInterference : Parameter idle is not defined or has invalid value" );
+    _LIT( KErrMsgStartInterferenceIdleInvalidValue, "TestInterference : Parameter idle has invalid value" );
+    _LIT( KErrMsgStartInterferenceActiveNotDefined, "TestInterference : Parameter active is not defined or has invalid value" );
+    _LIT( KErrMsgStartInterferenceActiveInvalidValue, "TestInterference : Parameter active has invalid value" );
+    
+    __TRACEFUNC();
+    TPtrC category;
+    TPtrC type;
+    TInt idle( 0 );
+    TInt active( 0 );
+    TInt priority( 0 );
+
+    // Get category
+    if( aItem->GetNextString( category ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' category" ) ) );
+        iRunErrorMessage = KErrMsgStartInterferenceCategoryNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+    // Get type
+    if( aItem->GetNextString( type ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' type" ) ) );
+        iRunErrorMessage = KErrMsgStartInterferenceTypeNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+
+    TPtrC timeStr;
+    TReal time;
+    // Get idle time
+    if( aItem->GetNextString( timeStr ) != KErrNone )
+        {        
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' idle" ) ) );
+        iRunErrorMessage = KErrMsgStartInterferenceIdleNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+    if ( TLex( timeStr ).Val( time, '.' ) != KErrNone )
+    	{
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' idle" ) ) );
+        iRunErrorMessage = KErrMsgStartInterferenceIdleNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave    	
+    	}
+    // Convert idle time from milli to micro seconds
+   	idle = static_cast<TInt>( time * 1000.0);
+
+    if( idle < 0 )
+    	{
+        __TRACE( KError, ( 
+                _L( "Argument 'testinterference' idle can't be <0" ) ) );
+    	iRunErrorMessage = KErrMsgStartInterferenceIdleInvalidValue;
+    	User::Leave( KErrArgument );
+    	}
+   // Get active time
+    if( aItem->GetNextString( timeStr ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' active" ) ) );
+        iRunErrorMessage = KErrMsgStartInterferenceActiveNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+    if ( TLex( timeStr ).Val( time, '.' ) != KErrNone )
+    	{
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' idle" ) ) );
+        iRunErrorMessage = KErrMsgStartInterferenceIdleNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave    	
+    	}
+    
+    // Convert active time from milli to micro seconds
+   	active = static_cast<TInt>( time * 1000.0 );
+   	
+    if( active < 0 )
+    	{
+        __TRACE( KError, ( 
+                _L( "Argument 'testinterference' active can't be <0" ) ) );
+    	iRunErrorMessage = KErrMsgStartInterferenceActiveInvalidValue;
+    	User::Leave( KErrArgument );
+    	}
+    
+   // Get priority
+    if( aItem->GetNextInt( priority ) != KErrNone )
+        {
+        // Log information only do not return. Priority value is optional.
+        __TRACE( KInit, ( 
+            _L( "Unknown argument for 'testinterference' priority or value not given, default priority will be used" ) ) );
+        }    
+
+    MSTIFTestInterference* interference = NULL;
+
+    // Get category
+    if( category == _L("activeobject") )
+        {
+        interference = MSTIFTestInterference::NewL( iTestScripter,
+                            MSTIFTestInterference::EActiveObject );
+        }
+    else if( category == _L("thread") )
+        {
+        interference = MSTIFTestInterference::NewL( iTestScripter,
+                            MSTIFTestInterference::EThread );
+        }
+    else
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' category[%S]" ), &category ) );
+        iRunErrorMessage = KErrMsgStartInterferenceCategoryInvalidValue;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+
+    // Create object that include test interference information and append this
+    // to array.
+    TTestInterference* object = new (ELeave) TTestInterference();
+    object->iName = aName;
+    object->iInterference = interference;
+
+    // Array for handling test interference between different objects
+    TInt ret = iTestInterferenceArray.Append( object );
+    if( ret != KErrNone )
+        {
+        delete object;
+        __TRACE( KError, ( 
+            _L( "CTestRunner::StartInterference: iTestInterferenceArray.Append fails:[%d]" ), ret ) );
+        User::Leave( ret );
+        }
+
+    // Set priority if user given
+    if( priority != 0 )
+        {
+        interference->SetPriority( priority );
+        }
+
+    // Get type
+    if( type == _L("cpuload") )
+        {
+        interference->StartL( MSTIFTestInterference::ECpuLoadMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemreadc") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemReadCMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemreadd") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemReadDMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemreade") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemReadEMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemreadz") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemReadZMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemwritec") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemWriteCMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemwrited") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemWriteDMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemwritee") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemWriteEMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemfillandemptyc") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemFillAndEmptyCMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemfillandemptyd") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemFillAndEmptyDMicroSeconds, idle , active );
+        }
+    else if( type == _L("filesystemfillandemptye") )
+        {
+        interference->StartL( MSTIFTestInterference::EFileSystemFillAndEmptyEMicroSeconds, idle , active );
+        }
+    else
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'testinterference' type[%S]" ), &type ) );
+        iRunErrorMessage = KErrMsgStartInterferenceTypeInvalidValue;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: StopInterference
+
+     Description: Stops test interference.
+  
+     Parameters: TDesC& aName: in: Indicates right test interference object.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::StopInterferenceL( TDesC& aName )
+    {    
+    _LIT( KErrMsgStopInterference, "TestInterference : testinterference %S was not start" );
+    __TRACEFUNC();
+    
+    TInt count = iTestInterferenceArray.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( iTestInterferenceArray[i]->iName == aName )
+            {
+            // Found test module, return description
+            iTestInterferenceArray[i]->iInterference->Stop();
+            // Delete data
+            delete iTestInterferenceArray[i];
+            // Remove pointer to deleted data(Append())
+            iTestInterferenceArray.Remove( i );
+            // iTestMeasurementArray can contain only one type of measurement
+            // so we can break when type is removed.
+            return;
+            }
+        }
+    __TRACE( KError, ( 
+            _L( "'testinterference' type[%S] was not start" ), &aName ) );
+    iRunErrorMessage.Format( KErrMsgStopInterference, &aName );
+    User::Leave( KErrArgument ); // Error in parsing => Leave
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: MeasurementL
+
+     Description: Starts test measurement.
+  
+     Parameters: CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if StartBappeaMeasurementL() fails.
+                        Leaves if StopBappeaMeasurementL() fails.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::MeasurementL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgMeasurementCommandNotDefined, "TestMeasurement : Parameter command is not defined" );
+    _LIT( KErrMsgMeasurementTypeNotDefined, "TestMeasurement : Parameter type is not defined" );
+    _LIT( KErrMsgMeasurementUnknownType, "TestMeasurement : Unknown measurement type %S" );
+    _LIT( KErrMsgMeasurementUnknownCommand, "TestMeasurement : Unknown command %S" );
+    __TRACEFUNC();
+    TPtrC type;
+    TPtrC command;
+
+    // Get command
+    if( aItem->GetNextString( command ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'measurement' command" ) ) );
+        iRunErrorMessage = KErrMsgMeasurementCommandNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+    // Get name
+    if( aItem->GetNextString( type ) != KErrNone )
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown argument for 'measurement' type" ) ) );
+        iRunErrorMessage = KErrMsgMeasurementTypeNotDefined;
+        User::Leave( KErrArgument ); // Error in parsing => Leave
+        }
+
+    // Verify measurement type
+    if( !( type == KParamMeasurement01 ||
+                type == KParamMeasurement02 ||
+                type == KParamMeasurement03 ||
+                type == KParamMeasurement04 ||
+                type == KParamMeasurement05 ||
+                type == KParamMeasurementBappea ) )
+
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown measurement type:[%S]" ), &type ) );
+        iRunErrorMessage.Format( KErrMsgMeasurementUnknownType, &type );
+        User::Leave( KErrArgument ); // Error in types => Leave
+        }
+
+    // Verify command
+   if( command == _L( "start" ) )
+        {
+        // START measurement's process
+        __TRACE( KMessage, ( _L( "Start 'measurement' with '%S'"), &type ) );
+        StartMeasurementL( type, aItem );
+        }
+    else if( command == _L( "stop" ) )
+        {
+        // STOP measurement's process
+        __TRACE( KMessage, ( _L( "'Stop 'measurement' with '%S'"), &type ) );
+        StopMeasurementL( type );
+        }
+    else
+        {
+        __TRACE( KError, ( 
+            _L( "Unknown command for 'measurement' command:[%S] or type:[%S]" ), &command, &type ) );
+        iRunErrorMessage.Format( KErrMsgMeasurementUnknownCommand, &command );
+        User::Leave( KErrArgument ); // Error in commands => Leave
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: StartMeasurementL
+
+     Description: Start measurement
+  
+     Parameters: const TDesC& aType: in: Plugin type.
+                 CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves is measurement operation fails.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::StartMeasurementL( const TDesC& aType,
+                                           CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgMeasurementUnknownPlugin, "Measurement : Unknown measurement plugin %S" );
+    _LIT( KErrMsgMeasurementStartFail, "Measurement : Measurement start fails" );
+    __TRACEFUNC();
+
+    CSTIFTestMeasurement* testMeasurement = NULL;
+
+    // Get Measurement configuration info
+    TPtrC configurationInfo( KNullDesC() );
+    if( aItem->Remainder( configurationInfo ) != KErrNone )
+        {
+        __TRACE( KInit, ( 
+            _L( "Using default path and file name for measurement configure" ) ) );
+        } 
+
+    if( aType == KParamMeasurement01 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    iTestScripter, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin01,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurement02 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    iTestScripter, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin02,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurement03 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    iTestScripter, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin03,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurement04 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    iTestScripter, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin04,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurement05 )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    iTestScripter, 
+                    CSTIFTestMeasurement::KStifMeasurementPlugin05,
+                    configurationInfo );
+        }
+    else if( aType == KParamMeasurementBappea )
+        {
+        testMeasurement = CSTIFTestMeasurement::NewL( 
+                    iTestScripter, 
+                    CSTIFTestMeasurement::KStifMeasurementBappeaProfiler,
+                    configurationInfo );
+        }
+    else
+        {
+        __TRACE( KError, ( _L( "Unknown plugin[%S] for 'measurement'" ), &aType ) );
+        iRunErrorMessage.Format( KErrMsgMeasurementUnknownPlugin, &aType );        
+        User::Leave( KErrArgument );
+        }
+
+    // Start test measurement
+    TInt start_ret( KErrNone );
+    start_ret = testMeasurement->Start();
+    if( start_ret != KErrNone )
+        {
+        delete testMeasurement;
+        //CleanupStack::PopAndDestroy( setting_buf );
+        __TRACE( KError, ( 
+            _L( "CTestRunner::StartMeasurementL(): Measurement Start() fails:[%d]" ), start_ret ) );
+        iRunErrorMessage = KErrMsgMeasurementStartFail;
+        User::Leave( start_ret );
+        }
+
+    TTestMeasurement* object = new (ELeave) TTestMeasurement();
+    object->iName = aType;
+    object->iMeasurement = testMeasurement;
+
+    // Array for handling test measurement between different objects
+    TInt ret = iTestMeasurementArray.Append( object );
+    if( ret != KErrNone )
+        {
+        delete object;
+        __TRACE( KError, ( 
+            _L( "CTestRunner::StartMeasurementL(): iTestMeasurementArray.Append fails:[%d]" ), ret ) );
+        User::Leave( ret );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: StopMeasurementL
+
+     Description: Stops test measurement.
+  
+     Parameters: None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::StopMeasurementL( const TDesC& aType )
+    {
+    _LIT( KErrMsgMeasurementNotStarted, "Measurement : Measurement %S was not start" );
+    __TRACEFUNC();
+
+    TInt count = iTestMeasurementArray.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        if( iTestMeasurementArray[i]->iName == aType )
+            {
+            // Found measurement module, stop
+            iTestMeasurementArray[i]->iMeasurement->Stop();
+            // Delete data
+            delete iTestMeasurementArray[i];
+            // Remove pointer to deleted data(Append())
+            iTestMeasurementArray.Remove( i );
+            // iTestMeasurementArray can contain only one type of measurement
+            // so we can break when type is removed.
+            return;
+            }
+        }
+
+    __TRACE( KError, ( 
+            _L( "CTestRunner::StopMeasurementL(): Measurement %S was not start" ), &aType ) );
+    iRunErrorMessage.Format( KErrMsgMeasurementNotStarted, &aType  );
+    User::Leave( KErrArgument );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestRunner
+
+     Method: AddTestCaseResultL
+
+     Description: Adds new test case result. Used with 'allownextresult'
+                  and 'allowerrorcodes' keywords.
+  
+     Parameters: CStifItemParser* aItem: in: Item object for parsing.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if iTestCaseResults.Append fails.
+                        Leaves if aItem->GetNextInt() fails.
+
+     Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestRunner::AddTestCaseResultL( CStifItemParser* aItem )
+    {
+    _LIT( KErrMsgAllowNextResultInvalidValue, "No expected result value given or value has invalid format" );
+    TInt result;
+
+    TPtrC codeBuf;
+    TBool found = EFalse;
+    while( aItem->GetNextString( codeBuf ) == KErrNone )
+    	{
+    	TLex codeParser( codeBuf );
+    	if ( codeParser.Val( result ) != KErrNone )
+    		{
+            __TRACE( KError, (_L("ExecuteLineL: No expected result value given")));
+            iRunErrorMessage = KErrMsgAllowNextResultInvalidValue;
+            User::Leave( KErrArgument );    		
+    		}
+    	else
+    		{
+    	    User::LeaveIfError( iTestCaseResults.Append( result ) );
+    	    // Set test case allow result to CTestModuleIf side too. This is
+    	    // used in TAL-TA5L macro handling.
+    	    User::LeaveIfError( 
+    	        iTestScripter->TestModuleIf().SetAllowResult( result ) );
+    	    found = ETrue;
+    		}
+    	}
+
+    if ( !found )
+    	{
+        __TRACE( KError, (_L("ExecuteLineL: No expected result value given")));
+        iRunErrorMessage = KErrMsgAllowNextResultInvalidValue;
+        User::Leave( KErrArgument );
+    	}    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CTestContinue class
+    member functions. CTestContinue handles ContinueScript calls from 
+    TestScripter.
+
+-------------------------------------------------------------------------------
+*/
+// MACROS
+#ifdef LOGGER
+#undef LOGGER
+#endif
+#define LOGGER iTestScripter->iLog
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestContinue
+
+     Method: CTestContinue
+
+     Description: Default constructor
+
+     Parameters: CTestRunner* aTestRunner: in: Backpointer to CTestRunner
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestContinue::CTestContinue( CTestScripter* aTestScripter,
+                              TTestObject* aObject ): 
+    // Executed with lowest priority, must be lower than CTesRunner priority 
+    CActive(  CActive::EPriorityLow ),
+    iTestScripter( aTestScripter ),
+    iObject( aObject )
+    {
+    CActiveScheduler::Add( this );
+    __TRACEFUNC();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestContinue
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestContinue::ConstructL()
+    {
+    
+    iObject->iScript->EnableSignal( iStatus );
+    SetActive();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestContinue
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters: CTestRunner* aTestRunner: in: Backpointer to CTestRunner
+
+     Return Values: CTestContinue*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+
+CTestContinue* CTestContinue::NewL( CTestScripter* aTestScripter,
+                                    TTestObject* aObject )
+    {
+    CTestContinue* self = 
+        new (ELeave) CTestContinue( aTestScripter, aObject );
+     
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestContinue
+
+     Method: ~CTestContinue
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/     
+
+CTestContinue::~CTestContinue()
+    {
+    __TRACEFUNC();
+    Cancel();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestContinue
+
+     Method: RunL
+
+     Description: Derived from CActive, handles testcase execution.
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: Leaves on error situations.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestContinue::RunL()
+    {
+
+    __TRACEFUNC();
+    __TRACE( KMessage, (_L("CTestContinue::RunL: [%d] "), iStatus.Int() ));
+
+    if( iObject->Signal() ) 
+        {
+        // If OOM testing is ongoing ignore result check(given by user).
+        if( !iTestScripter->iOOMIgnoreFailure )
+            {
+            // Erronous case RunError will called and test handling continue 
+            // from there.
+            if( iTestScripter->TestRunner().TestCaseResults().Count() == 0 )
+                {
+                // KErrNone is the default result expected 
+                // if nothing else is given 
+                User::LeaveIfError( iTestScripter->TestRunner().
+                    TestCaseResults().Append( KErrNone ) );
+                }
+            
+            if( iTestScripter->TestRunner().TestCaseResults().
+                    Find( iStatus.Int() ) < 0 ) 
+                {
+                __TRACE( KError, ( _L("Command for [%S] failed (%d)"), 
+                    &iObject->ObjectId(), iStatus.Int() ));
+
+
+                if( iStatus.Int() == KErrNone )
+                    {
+                    User::Leave( KErrGeneral );
+                    }
+                else
+                    {
+                    User::Leave( iStatus.Int() );
+                    }
+                }
+            }
+        else
+            {
+            __TRACE( KMessage, ( 
+                _L( "OOM test: 'oomignorefailure' is ON, signal result[%d] ignored" ),
+                iStatus.Int() ));
+            }
+
+        iTestScripter->TestRunner().TestCaseResults().Reset();
+        
+         __TRACE( KMessage, (_L("CTestContinue::RunL: Set runner active ")));
+        iTestScripter->iTestRunner->SetRunnerActive();   
+        }
+    else
+        {
+        // Signal called from test side but 'waittestclass' not yet processed
+        iObject->iAsyncResult = iStatus.Int();
+        }        
+        
+    iObject->iScript->EnableSignal( iStatus );
+    SetActive();
+    
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestContinue
+
+     Method: DoCancel
+
+     Description: Derived from CActive handles the Cancel
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestContinue::DoCancel()
+    {
+
+    __TRACEFUNC();
+    __TRACE( KMessage, (_L("CTestContinue::DoCancel")));
+
+    iObject->iScript->CancelSignal();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestContinue
+
+     Method: RunError
+
+     Description: Derived from CActive handles the Cancel
+
+     Parameters:    None.
+
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestContinue::RunError( TInt aError )
+    {
+
+    // Return error from here, if none given from execution
+    if( iTestScripter->iResult.iResult == KErrNone )
+        {
+        iTestScripter->UpdateTestCaseResult(aError, _L("CTestContinue::RunError"));
+        }
+    CActiveScheduler::Current()->Stop();
+     
+    return KErrNone;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of CDefinedValue class
+    member functions. 
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: CDefinedValue
+
+     Description: Default constructor
+
+     C++ default constructor can NOT contain any code, that
+     might leave.
+     
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CDefinedValue::CDefinedValue()
+    {
+    }
+     
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: ConstructL
+
+     Description: Symbian OS second phase constructor
+
+     Symbian OS default constructor can leave.
+
+     Parameters:    TDesC& aName: in: Define name
+                    TDesC& aValue: in: Define value
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CDefinedValue::ConstructL( TDesC& aName, TDesC& aValue )
+    {    
+
+    iNameBuf = aName.AllocLC();
+    iName.Set( iNameBuf->Des() );
+    iValueBuf = aValue.AllocLC();
+    iValue.Set( iValueBuf->Des() );
+    CleanupStack::Pop( iValueBuf );
+    CleanupStack::Pop( iNameBuf );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: NewL
+
+     Description: Two-phased constructor.
+          
+     Parameters:    TDesC& aName: in: Define name
+                    TDesC& aValue: in: Define value
+
+     Return Values: CDefinedValue*: new object
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CDefinedValue* CDefinedValue::NewL( TDesC& aName, TDesC& aValue )
+    {
+
+    CDefinedValue* self = new (ELeave) CDefinedValue();
+     
+    CleanupStack::PushL( self );
+    self->ConstructL( aName, aValue );
+    CleanupStack::Pop();
+
+    return self;
+
+    }    
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: ~CDefinedValue
+
+     Description: Destructor
+     
+     Parameters:    None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/     
+CDefinedValue::~CDefinedValue()
+    {
+    
+    delete iValueBuf;
+    delete iNameBuf;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: SetValueL
+
+     Description: Set new define value
+
+     Parameters:    TDesC& aValue: in: Define value
+
+     Return Values: None
+
+     Errors/Exceptions: Leaves on error.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CDefinedValue::SetValueL( TDesC& aValue )
+    {
+    delete iValueBuf;
+    iValueBuf = 0;
+    iValueBuf = aValue.AllocLC();
+    iValue.Set( iValueBuf->Des() );
+    CleanupStack::Pop( iValueBuf );
+    
+    }
+
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: Name
+
+     Description: Returns define name.
+
+     Parameters:  None
+
+     Return Values: TDesC: Define name
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TDesC& CDefinedValue::Name()
+    { 
+    return iName; 
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+     Class: CDefinedValue
+
+     Method: Value
+
+     Description: Returns define value.
+
+     Parameters:  None
+
+     Return Values: TDesC: Define value
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TDesC& CDefinedValue::Value()
+    { 
+    return iValue; 
+    }
+    
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TTestObjectBase class
+    member functions. 
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestObjectBase
+
+     Method: TTestObjectBase
+
+     Description: Constructor
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/    
+TTestObjectBase::TTestObjectBase( TObjectType aType ) : 
+    iAsyncResult( KErrNone ),
+    iType( aType )
+    {
+    
+    RDebug::Print( _L("TTestObjectBase::TTestObjectBase") );
+    iName.Zero(); 
+    
+    }
+    
+    /*
+-------------------------------------------------------------------------------
+
+     Class: TTestObjectBase
+
+     Method: ~TTestObjectBase
+
+     Description: Destructor
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/    
+TTestObjectBase::~TTestObjectBase()
+    {
+    
+    RDebug::Print( _L("TTestObjectBase::~TTestObjectBase") );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TTestObject class
+    member functions. 
+-------------------------------------------------------------------------------
+*/
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestObject
+
+     Method: TTestObject
+
+     Description: Constructor
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/    
+TTestObject::TTestObject() :
+    TTestObjectBase( EObjectNormal ),
+    iScript(0),
+    iContinue(0),
+    iCount(0)
+    {
+
+    RDebug::Print( _L("TTestObject::TTestObject") );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestObject
+
+     Method: ~TTestObject
+
+     Description: Destructor
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TTestObject::~TTestObject()
+    { 
+    
+    RDebug::Print( _L("TTestObject::~TTestObject") );
+    delete iContinue; 
+    delete iScript;
+    
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestObject
+
+     Method: RunMethodL
+
+     Description: Run specified method from testclass.
+
+     Parameters: CStifItemParser* aItem: in: itemparser
+
+     Return Values: Symbian OS error code
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt TTestObject::RunMethodL( CStifItemParser& aItem )
+    { 
+    
+    return iScript->RunMethodL( aItem ); 
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains the implementation of TTestObjectKernel class
+    member functions. 
+-------------------------------------------------------------------------------
+*/
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestObjectKernel
+
+     Method: TTestObjectKernel
+
+     Description: Constructor
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/    
+TTestObjectKernel::TTestObjectKernel() : 
+    TTestObjectBase( EObjectKernel )
+    {
+    
+    RDebug::Print( _L("TTestObjectKernel::TTestObjectKernel") );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestObjectKernel
+
+     Method: ~TTestObjectKernel
+
+     Description: Destructor
+
+     Parameters: None
+
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TTestObjectKernel::~TTestObjectKernel()
+    { 
+    
+    RDebug::Print( _L("TTestObjectKernel::~TTestObjectKernel") );
+    
+    iTestClass.Close(); 
+    User::FreeLogicalDevice( iLddName );
+    
+    }
+   
+/*
+-------------------------------------------------------------------------------
+
+     Class: TTestObjectKernel
+
+     Method: RunMethodL
+
+     Description: Run specified method from kernel testclass.
+
+     Parameters: CStifItemParser& aItem: in: itemparser
+
+     Return Values: Symbian OS error code
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt TTestObjectKernel::RunMethodL( CStifItemParser& aItem )
+    { 
+    
+    TPtrC method;
+    TPtrC params;
+    
+    User::LeaveIfError( aItem.GetNextString( method ) );
+    aItem.Remainder( params );
+    
+    TInt result;
+    TMethodResultDes resultDes;
+          
+    // Need to change descriptors from 16bit to 8bit for EKA2 kernel
+    // because STIF Parser doesn't support 8bit parsing
+    HBufC8 * myBuf1 = HBufC8::NewL( method.Length() );
+    TPtr8 met8 = myBuf1->Des();   
+    met8.Copy( method );
+        
+    HBufC8 * myBuf2 = HBufC8::NewL( params.Length() );
+    TPtr8 par8 = myBuf2->Des();   
+    par8.Copy( params );
+    
+    TInt ret =  iTestClass.RunMethod( met8, par8, result, resultDes );
+
+    delete myBuf1;
+    delete myBuf2;
+    
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    return result;                             
+                                     
+    };
+    
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+    
+     Function: LibEntryL
+
+     Description: Polymorphic Dll Entry Point
+
+     Parameters:    None.
+
+     Return Values: CTestScripter*: pointer to new CTestScripter
+
+     Errors/Exceptions: Leaves if NewL leaves.
+
+     Status: Draft
+     
+-------------------------------------------------------------------------------
+*/
+
+EXPORT_C CTestScripter* LibEntryL()
+    {
+    return CTestScripter::NewL();
+    
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestScripter/src/TestScripterInternal.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,390 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains TestScripterImp implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <StifTestInterface.h>
+#include <StifParser.h>
+#include "TestScripterInternal.h"
+#include "TestScripter.h"
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// None
+
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CScriptBase::CScriptBase
+// Constructor.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase::CScriptBase( CTestModuleIf& aTestModuleIf ):
+    iTestModuleIf( aTestModuleIf )
+    {
+	// Handles multible 'waittestclass' given in test configure file.
+    iSignalErrors.Reset();
+
+    }
+
+       
+// -----------------------------------------------------------------------------
+// CScriptBase::TestModuleIf
+// Get reference to TestModuleIf API.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CTestModuleIf& CScriptBase::TestModuleIf()
+    { 
+    
+    return iTestModuleIf; 
+    
+    }
+        
+// -----------------------------------------------------------------------------
+// CScriptBase::Signal
+// Signal TestScripter to continue from waittestclass.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScriptBase::Signal( TInt aError )
+    { 
+    
+    if( iStatus ) 
+        {
+        User::RequestComplete( iStatus, aError ); 
+        }
+    else
+    	{
+		// Handles multible 'waittestclass' given in test configure file.
+		// There is active object in CTestRunner also and it has higher
+		// priority than CTestContinue(It must be higher that e.g.
+		// 'allownextresult' is gotten right from configure file). That why we
+		// have to use this array and take signal "count" to the array for
+		// later handling.
+    	iSignalErrors.Append( aError );
+    	}
+        
+    }
+
+// -----------------------------------------------------------------------------
+// CScriptBase::CallTestClass
+// Called from test class. TestScripter forwards
+// operations to other test class object.
+// aLine: in: <object name> <method name> <parameters>
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::CallTestClass( const TDesC& aLine )
+    { 
+    
+    if( iFunc )
+        {
+        return iFunc( iTestScripter, EStifTSCallClass, aLine ); 
+        }
+    
+    return KErrNotSupported;
+    
+    };
+
+// -----------------------------------------------------------------------------
+// CScriptBase::GetTestObject
+// Get test class object address.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CScriptBase* CScriptBase::GetTestObject( const TDesC& aObjectName )
+    { 
+    
+    if( iFunc )
+        {
+        TInt ret = iFunc( iTestScripter, EStifTSGetObject, aObjectName );
+        if( ret > 0 )
+            {
+            return( CScriptBase* )ret;
+            } 
+        }
+    
+    return NULL;
+    };
+
+// -----------------------------------------------------------------------------
+// CScriptBase::EnableSignal
+// Enable Signal().
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScriptBase::EnableSignal( TRequestStatus& aStatus )
+    { 
+    
+    aStatus = KRequestPending; 
+    iStatus = &aStatus; 
+
+	// Handles multible 'waittestclass' given in test configure file.
+    if( iSignalErrors.Count() > 0 )
+    	{
+		// Complete signal and remove it from array.
+    	TInt error = iSignalErrors[0];
+    	iSignalErrors.Remove( 0 );
+    	User::RequestComplete( iStatus, error ); 
+    	}
+    
+    }
+   
+// -----------------------------------------------------------------------------
+// CScriptBase::CancelSignal
+// Cancel Signal().
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScriptBase::CancelSignal()
+    { 
+    if(iStatus!=NULL)
+        {
+        User::RequestComplete( iStatus, KErrCancel ); 
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CScriptBase::SetScripter
+// Set scripter callback.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScriptBase::SetScripter( CallBackFunc aFunc, CTestScripter* aTestScripter )
+    { 
+    
+    iTestScripter = aTestScripter; 
+    iFunc = aFunc; 
+    
+    }
+
+// -----------------------------------------------------------------------------
+// CScriptBase::RunInternalL
+// Run specified method from test class.
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::RunInternalL ( 
+    TStifFunctionInfo const aFunctions[], 
+    TInt aCount, 
+    CStifItemParser& aItem  ) 
+    {
+
+    TInt ret = KErrNotFound;
+    
+    TPtrC command; 
+    User::LeaveIfError ( aItem.GetNextString( command ) );
+    TInt i = 0;
+    TName funcName;
+    
+    // Search function from table and call it
+    for ( i = 0; i < aCount; i++ )
+        {
+        funcName = aFunctions[i].iFunctionName;      
+        if ( command == funcName )
+            {
+            if( iLog )
+                {
+                iLog->Log(_L("Calling [%S]"), &command );
+                }
+            ret  = ( this->*(aFunctions[i].iMethod) )( aItem );    
+
+            break;            
+            }
+    
+        }
+
+    if( i == aCount )
+        {
+        iLog->Log( _L("[%S] not found"), &command );
+        }
+
+    return ret;
+
+    }
+    
+// -----------------------------------------------------------------------------
+// CScriptBase::GetConstantValue
+// Internal fuction to get const value defined in 
+// [Define]...[Enddefine] section of script file
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::GetConstantValue( const TDesC& aName, TDes& aValue )
+	{	
+		return iTestScripter->GetConstantValue( aName, aValue );
+	}
+
+    
+// -----------------------------------------------------------------------------
+// CScriptBase::GetConstantValue
+// Internal fuction to get const value defined in 
+// [Define]...[Enddefine] section of script file
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::GetConstantValue( const TDesC& aName, TInt& aValue )
+	{	
+	TInt ret = KErrNone;
+	TBuf<32> valStr;
+	ret = iTestScripter->GetConstantValue( aName, valStr );
+	if ( ret != KErrNone )
+	{
+		return ret;
+	}
+
+	TLex converter( valStr );
+	ret = converter.Val( aValue );
+
+	return ret;
+	}
+    
+// -----------------------------------------------------------------------------
+// CScriptBase::GetConstantValue
+// Internal fuction to get const value defined in 
+// [Define]...[Enddefine] section of script file
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::GetConstantValue( const TDesC& aName, TReal& aValue )
+	{	
+	TInt ret = KErrNone;
+	TBuf<32> valStr;
+	ret = iTestScripter->GetConstantValue( aName, valStr );
+	if ( ret != KErrNone )
+	{
+		return ret;
+	}
+
+	TLex converter( valStr );
+	ret = converter.Val( aValue );
+
+	return ret;
+	}
+
+// -----------------------------------------------------------------------------
+// CScriptBase::SetResultDescription
+// Result description can be set from within the test class method 
+// -----------------------------------------------------------------------------
+//
+EXPORT_C void CScriptBase::SetResultDescription(const TDesC& aDescription)
+	{
+	iTestScripter->SetResultDescription(aDescription);
+	}
+
+// -----------------------------------------------------------------------------
+// CScriptBase::SetLocalValue
+// Internal fuction to set local value
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::SetLocalValue(const TDesC& aName, const TDesC& aValue)
+    {	
+		return iTestScripter->SetLocalValue(aName, aValue);
+    }
+	
+// -----------------------------------------------------------------------------
+// CScriptBase::SetLocalValue
+// Internal fuction to set local value
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::SetLocalValue(const TDesC& aName, const TInt aValue)
+    {
+    TBuf<20> buf;
+    buf.Format(_L("%d"), aValue);
+    return iTestScripter->SetLocalValue(aName, buf);
+    }
+	
+// -----------------------------------------------------------------------------
+// CScriptBase::SetLocalValue
+// Internal fuction to set local value
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::SetLocalValue(const TDesC& aName, const TReal aValue )
+    {	
+    TBuf<50> buf;
+    buf.Format(_L("%g"), aValue);
+    return iTestScripter->SetLocalValue(aName, buf);
+    }	
+
+// -----------------------------------------------------------------------------
+// CScriptBase::GetLocalValue
+// Internal fuction to get local value
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::GetLocalValue(const TDesC& aName, TDes& aValue)
+    {	
+		return iTestScripter->GetLocalValue(aName, aValue);
+    }
+	
+// -----------------------------------------------------------------------------
+// CScriptBase::GetLocalValue
+// Internal fuction to get local value
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::GetLocalValue(const TDesC& aName, TInt& aValue)
+    {
+    TInt ret = KErrNone;
+    TBuf<50> valStr;
+    ret = iTestScripter->GetLocalValue(aName, valStr);
+    if(ret != KErrNone)
+        {
+        return ret;
+        }
+
+    TLex converter(valStr);
+    ret = converter.Val(aValue);
+
+    return ret;
+    }
+	
+// -----------------------------------------------------------------------------
+// CScriptBase::GetLocalValue
+// Internal fuction to get local value
+// -----------------------------------------------------------------------------
+//
+EXPORT_C TInt CScriptBase::GetLocalValue(const TDesC& aName, TReal& aValue )
+    {
+    TInt ret = KErrNone;
+    TBuf<50> valStr;
+    ret = iTestScripter->GetLocalValue(aName, valStr);
+    if(ret != KErrNone)
+        {
+        return ret;
+        }
+
+    TLex converter(valStr);
+    ret = converter.Val(aValue);
+
+    return ret;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/BMARM/StifTestServeru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,25 @@
+EXPORTS
+	__11RTestServer @ 1 NONAME R3UNUSED ; RTestServer::RTestServer(void)
+	CancelAsyncRequest__14RTestExecutioni @ 2 NONAME R3UNUSED ; RTestExecution::CancelAsyncRequest(int)
+	Close__11RTestModule @ 3 NONAME R3UNUSED ; RTestModule::Close(void)
+	Close__11RTestServer @ 4 NONAME R3UNUSED ; RTestServer::Close(void)
+	Close__14RTestExecution @ 5 NONAME R3UNUSED ; RTestExecution::Close(void)
+	Connect__11RTestServerRCt4TBuf1i256RC7TDesC16 @ 6 NONAME R3UNUSED ; RTestServer::Connect(TBuf<256> const &, TDesC16 const &)
+	EnumerateTestCases__11RTestModuleR7TDesC16Rt8TPckgBuf1ZiR14TRequestStatus @ 7 NONAME ; RTestModule::EnumerateTestCases(TDesC16 &, TPckgBuf<int> &, TRequestStatus &)
+	ErrorNotification__11RTestModuleRt5TPckg1Z18TErrorNotificationR14TRequestStatus @ 8 NONAME R3UNUSED ; RTestModule::ErrorNotification(TPckg<TErrorNotification> &, TRequestStatus &)
+	GetTestCases__11RTestModuleRt15CFixedFlatArray1Z13TTestCaseInfo @ 9 NONAME R3UNUSED ; RTestModule::GetTestCases(CFixedFlatArray<TTestCaseInfo> &)
+	NotifyEvent__14RTestExecutionRt5TPckg1Z8TEventIfR14TRequestStatusi @ 10 NONAME ; RTestExecution::NotifyEvent(TPckg<TEventIf> &, TRequestStatus &, int)
+	NotifyProgress__14RTestExecutionRt5TPckg1Z13TTestProgressR14TRequestStatus @ 11 NONAME R3UNUSED ; RTestExecution::NotifyProgress(TPckg<TTestProgress> &, TRequestStatus &)
+	NotifyRemoteCmd__14RTestExecutionRt5TPckg1Z12TStifCommandRt5TPckg1ZiR14TRequestStatus @ 12 NONAME ; RTestExecution::NotifyRemoteCmd(TPckg<TStifCommand> &, TPckg<int> &, TRequestStatus &)
+	Open__11RTestModuleR11RTestServerRt4TBuf1i256 @ 13 NONAME R3UNUSED ; RTestModule::Open(RTestServer &, TBuf<256> &)
+	Open__14RTestExecutionR11RTestServeriRCt4TBuf1i256 @ 14 NONAME ; RTestExecution::Open(RTestServer &, int, TBuf<256> const &)
+	Pause__14RTestExecution @ 15 NONAME R3UNUSED ; RTestExecution::Pause(void)
+	ReadRemoteCmdInfo__14RTestExecutionR5TDes812TStifCommandi @ 16 NONAME ; RTestExecution::ReadRemoteCmdInfo(TDes8 &, TStifCommand, int)
+	Resume__14RTestExecution @ 17 NONAME R3UNUSED ; RTestExecution::Resume(void)
+	RunTestCase__14RTestExecutionRt5TPckg1Z15TFullTestResultR14TRequestStatus @ 18 NONAME R3UNUSED ; RTestExecution::RunTestCase(TPckg<TFullTestResult> &, TRequestStatus &)
+	StartNewServer__FRCt4TBuf1i256Rt4TBuf1i256 @ 19 NONAME R3UNUSED ; StartNewServer(TBuf<256> const &, TBuf<256> &)
+	StartNewServer__FRCt4TBuf1i256Rt4TBuf1i256iG10RSemaphore @ 20 NONAME ; StartNewServer(TBuf<256> const &, TBuf<256> &, int, RSemaphore)
+	Version__C11RTestServer @ 21 NONAME R3UNUSED ; RTestServer::Version(void) const
+	CancelAsyncRequest__11RTestModulei @ 22 NONAME R3UNUSED ; RTestModule::CancelAsyncRequest(int)
+	GetServerThreadId__11RTestServerR9TThreadId @ 23 NONAME R3UNUSED ; RTestServer::GetServerThreadId(TThreadId &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/BWINS/StifTestServeru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,33 @@
+EXPORTS
+	??0RTestServer@@QAE@XZ @ 1 NONAME ; RTestServer::RTestServer(void)
+	?CancelAsyncRequest@RTestExecution@@QAEHH@Z @ 2 NONAME ; int RTestExecution::CancelAsyncRequest(int)
+	?CancelAsyncRequest@RTestModule@@QAEHH@Z @ 3 NONAME ; int RTestModule::CancelAsyncRequest(int)
+	?Close@RTestExecution@@QAEXXZ @ 4 NONAME ; void RTestExecution::Close(void)
+	?Close@RTestModule@@QAEXXZ @ 5 NONAME ; void RTestModule::Close(void)
+	?Close@RTestServer@@QAEXXZ @ 6 NONAME ; void RTestServer::Close(void)
+	?Connect@RTestServer@@QAEHABV?$TBuf@$0BAA@@@ABVTDesC16@@@Z @ 7 NONAME ; int RTestServer::Connect(class TBuf<256> const &, class TDesC16 const &)
+	?EnumerateTestCases@RTestModule@@QAEXAAVTDesC16@@AAV?$TPckgBuf@H@@AAVTRequestStatus@@@Z @ 8 NONAME ; void RTestModule::EnumerateTestCases(class TDesC16 &, class TPckgBuf<int> &, class TRequestStatus &)
+	?ErrorNotification@RTestModule@@QAEXAAV?$TPckg@VTErrorNotification@@@@AAVTRequestStatus@@@Z @ 9 NONAME ; void RTestModule::ErrorNotification(class TPckg<class TErrorNotification> &, class TRequestStatus &)
+	?GetTestCases@RTestModule@@QAEHAAV?$CFixedFlatArray@VTTestCaseInfo@@@@@Z @ 10 NONAME ; int RTestModule::GetTestCases(class CFixedFlatArray<class TTestCaseInfo> &)
+	?NotifyEvent@RTestExecution@@QAEHAAV?$TPckg@VTEventIf@@@@AAVTRequestStatus@@H@Z @ 11 NONAME ; int RTestExecution::NotifyEvent(class TPckg<class TEventIf> &, class TRequestStatus &, int)
+	?NotifyProgress@RTestExecution@@QAEHAAV?$TPckg@VTTestProgress@@@@AAVTRequestStatus@@@Z @ 12 NONAME ; int RTestExecution::NotifyProgress(class TPckg<class TTestProgress> &, class TRequestStatus &)
+	?NotifyRemoteCmd@RTestExecution@@QAEHAAV?$TPckg@W4TStifCommand@@@@AAV?$TPckg@H@@AAVTRequestStatus@@@Z @ 13 NONAME ; int RTestExecution::NotifyRemoteCmd(class TPckg<enum TStifCommand> &, class TPckg<int> &, class TRequestStatus &)
+	?Open@RTestExecution@@QAEHAAVRTestServer@@HABV?$TBuf@$0BAA@@@@Z @ 14 NONAME ; int RTestExecution::Open(class RTestServer &, int, class TBuf<256> const &)
+	?Open@RTestModule@@QAEHAAVRTestServer@@AAV?$TBuf@$0BAA@@@@Z @ 15 NONAME ; int RTestModule::Open(class RTestServer &, class TBuf<256> &)
+	?Pause@RTestExecution@@QAEHXZ @ 16 NONAME ; int RTestExecution::Pause(void)
+	?ReadRemoteCmdInfo@RTestExecution@@QAEHAAVTDes8@@W4TStifCommand@@H@Z @ 17 NONAME ; int RTestExecution::ReadRemoteCmdInfo(class TDes8 &, enum TStifCommand, int)
+	?Resume@RTestExecution@@QAEHXZ @ 18 NONAME ; int RTestExecution::Resume(void)
+	?RunTestCase@RTestExecution@@QAEXAAV?$TPckg@VTFullTestResult@@@@AAVTRequestStatus@@@Z @ 19 NONAME ; void RTestExecution::RunTestCase(class TPckg<class TFullTestResult> &, class TRequestStatus &)
+	?StartNewServer@@YAHABV?$TBuf@$0BAA@@@AAV1@@Z @ 20 NONAME ; int StartNewServer(class TBuf<256> const &, class TBuf<256> &)
+	?StartNewServer@@YAHABV?$TBuf@$0BAA@@@AAV1@HVRSemaphore@@@Z @ 21 NONAME ; int StartNewServer(class TBuf<256> const &, class TBuf<256> &, int, class RSemaphore)
+	?Version@RTestServer@@QBE?AVTVersion@@XZ @ 22 NONAME ; class TVersion RTestServer::Version(void) const
+	?GetServerThreadId@RTestServer@@QAEHAAVTThreadId@@@Z @ 23 NONAME ; int RTestServer::GetServerThreadId(class TThreadId &)
+	?NotifyCommand@RTestExecution@@QAEHAAV?$TPckg@W4TCommand@@@@AAV?$TBuf8@$0DC@@@AAVTRequestStatus@@H@Z @ 24 NONAME ; int RTestExecution::NotifyCommand(class TPckg<enum TCommand> &, class TBuf8<50> &, class TRequestStatus &, int)
+	?GetUiEnvProxy@CTestThreadContainer@@QAEPAVCUiEnvProxy@@XZ @ 25 NONAME ; class CUiEnvProxy * CTestThreadContainer::GetUiEnvProxy(void)
+	?NewL@CTestThreadContainerRunner@@SAPAV1@VTThreadId@@PAVCActiveScheduler@@@Z @ 26 NONAME ; class CTestThreadContainerRunner * CTestThreadContainerRunner::NewL(class TThreadId, class CActiveScheduler *)
+	?NewL@CTestThreadContainerRunnerFactory@@SAPAV1@VTThreadId@@PAVCActiveScheduler@@PAVCUiEnvProxy@@@Z @ 27 NONAME ; class CTestThreadContainerRunnerFactory * CTestThreadContainerRunnerFactory::NewL(class TThreadId, class CActiveScheduler *, class CUiEnvProxy *)
+	?StartNewServer@@YAHABV?$TBuf@$0BAA@@@AAV1@HVRSemaphore@@HPAVCTestThreadContainerRunnerFactory@@@Z @ 28 NONAME ; int StartNewServer(class TBuf<256> const &, class TBuf<256> &, int, class RSemaphore, int, class CTestThreadContainerRunnerFactory *)
+	?UITesting@CTestThreadContainer@@QAEHXZ @ 29 NONAME ; int CTestThreadContainer::UITesting(void)
+	?NotifyCommand2@RTestExecution@@QAEHAAV?$TPckg@W4TCommand@@@@AAVTDes8@@AAVTRequestStatus@@H@Z @ 30 NONAME ; int RTestExecution::NotifyCommand2(class TPckg<enum TCommand> &, class TDes8 &, class TRequestStatus &, int)
+	?RunTestCase@RTestExecution@@QAEXAAV?$TPckg@VTFullTestResult@@@@ABVTDesC16@@AAVTRequestStatus@@@Z @ 31 NONAME ; void RTestExecution::RunTestCase(class TPckg<class TFullTestResult> &, class TDesC16 const &, class TRequestStatus &)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/eabi/StifTestServeru.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,64 @@
+EXPORTS
+	_Z14StartNewServerRK4TBufILi256EERS0_ @ 1 NONAME
+	_Z14StartNewServerRK4TBufILi256EERS0_i10RSemaphore @ 2 NONAME
+	_ZN11RTestModule12GetTestCasesER15CFixedFlatArrayI13TTestCaseInfoE @ 3 NONAME
+	_ZN11RTestModule17ErrorNotificationER5TPckgI18TErrorNotificationER14TRequestStatus @ 4 NONAME
+	_ZN11RTestModule18CancelAsyncRequestEi @ 5 NONAME
+	_ZN11RTestModule18EnumerateTestCasesER7TDesC16R8TPckgBufIiER14TRequestStatus @ 6 NONAME
+	_ZN11RTestModule4OpenER11RTestServerR4TBufILi256EE @ 7 NONAME
+	_ZN11RTestModule5CloseEv @ 8 NONAME
+	_ZN11RTestServer5CloseEv @ 9 NONAME
+	_ZN11RTestServer7ConnectERK4TBufILi256EERK7TDesC16 @ 10 NONAME
+	_ZN11RTestServerC1Ev @ 11 NONAME
+	_ZN11RTestServerC2Ev @ 12 NONAME
+	_ZN14RTestExecution11NotifyEventER5TPckgI8TEventIfER14TRequestStatusi @ 13 NONAME
+	_ZN14RTestExecution11RunTestCaseER5TPckgI15TFullTestResultER14TRequestStatus @ 14 NONAME
+	_ZN14RTestExecution14NotifyProgressER5TPckgI13TTestProgressER14TRequestStatus @ 15 NONAME
+	_ZN14RTestExecution15NotifyRemoteCmdER5TPckgI12TStifCommandERS0_IiER14TRequestStatus @ 16 NONAME
+	_ZN14RTestExecution17ReadRemoteCmdInfoER5TDes812TStifCommandi @ 17 NONAME
+	_ZN14RTestExecution18CancelAsyncRequestEi @ 18 NONAME
+	_ZN14RTestExecution4OpenER11RTestServeriRK4TBufILi256EE @ 19 NONAME
+	_ZN14RTestExecution5CloseEv @ 20 NONAME
+	_ZN14RTestExecution5PauseEv @ 21 NONAME
+	_ZN14RTestExecution6ResumeEv @ 22 NONAME
+	_ZNK11RTestServer7VersionEv @ 23 NONAME
+	_ZTI11CPrintQueue @ 24 NONAME ; #<TI>#
+	_ZTI11CRcvHandler @ 25 NONAME ; #<TI>#
+	_ZTI11CSndHandler @ 26 NONAME ; #<TI>#
+	_ZTI11CTestModule @ 27 NONAME ; #<TI>#
+	_ZTI11CTestServer @ 28 NONAME ; #<TI>#
+	_ZTI11CUnderTaker @ 29 NONAME ; #<TI>#
+	_ZTI13CEventHandler @ 30 NONAME ; #<TI>#
+	_ZTI13CPrintHandler @ 31 NONAME ; #<TI>#
+	_ZTI14CTestExecution @ 32 NONAME ; #<TI>#
+	_ZTI18CErrorPrintHandler @ 33 NONAME ; #<TI>#
+	_ZTI20CTestModuleContainer @ 34 NONAME ; #<TI>#
+	_ZTI20CTestThreadContainer @ 35 NONAME ; #<TI>#
+	_ZTV11CPrintQueue @ 36 NONAME ; #<VT>#
+	_ZTV11CRcvHandler @ 37 NONAME ; #<VT>#
+	_ZTV11CSndHandler @ 38 NONAME ; #<VT>#
+	_ZTV11CTestModule @ 39 NONAME ; #<VT>#
+	_ZTV11CTestServer @ 40 NONAME ; #<VT>#
+	_ZTV11CUnderTaker @ 41 NONAME ; #<VT>#
+	_ZTV13CEventHandler @ 42 NONAME ; #<VT>#
+	_ZTV13CPrintHandler @ 43 NONAME ; #<VT>#
+	_ZTV14CTestExecution @ 44 NONAME ; #<VT>#
+	_ZTV18CErrorPrintHandler @ 45 NONAME ; #<VT>#
+	_ZTV20CTestModuleContainer @ 46 NONAME ; #<VT>#
+	_ZTV20CTestThreadContainer @ 47 NONAME ; #<VT>#
+	_ZN11RTestServer17GetServerThreadIdER9TThreadId @ 48 NONAME
+	_ZN14RTestExecution13NotifyCommandER5TPckgI8TCommandER5TBuf8ILi50EER14TRequestStatusi @ 49 NONAME
+	_Z14StartNewServerRK4TBufILi256EERS0_i10RSemaphoreiP33CTestThreadContainerRunnerFactory @ 50 NONAME
+	_ZN20CTestThreadContainer13GetUiEnvProxyEv @ 51 NONAME
+	_ZN20CTestThreadContainer9UITestingEv @ 52 NONAME
+	_ZN26CTestThreadContainerRunner4NewLE9TThreadIdP16CActiveScheduler @ 53 NONAME
+	_ZN33CTestThreadContainerRunnerFactory4NewLE9TThreadIdP16CActiveSchedulerP11CUiEnvProxy @ 54 NONAME
+	_ZTI26CTestThreadContainerRunner @ 55 NONAME ; #<TI>#
+	_ZTI33CTestThreadContainerRunnerFactory @ 56 NONAME ; #<TI>#
+	_ZTV26CTestThreadContainerRunner @ 57 NONAME ; #<VT>#
+	_ZTV33CTestThreadContainerRunnerFactory @ 58 NONAME ; #<VT>#
+	_ZN14RTestExecution14NotifyCommand2ER5TPckgI8TCommandER5TDes8R14TRequestStatusi @ 59 NONAME
+	_ZTI11CCommandDef @ 60 NONAME ; #<TI>#
+	_ZTV11CCommandDef @ 61 NONAME ; #<VT>#
+	_ZN14RTestExecution11RunTestCaseER5TPckgI15TFullTestResultERK7TDesC16R14TRequestStatus @ 62 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/group/TestServer.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,65 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestServer module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+#include        "../../inc/STIFConfiguration.mmh"
+
+SMPSAFE
+
+TARGET          StifTestServer.dll
+TARGETTYPE      dll
+
+CAPABILITY      ALL -TCB
+VENDORID        0x101FB657
+SECUREID        0x102073E3
+
+DEFFILE         StifTestServer.def
+
+UID             0x1000008D 0x101FB3E0
+
+/* Include paths */
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+/* Source files */
+SOURCEPATH      ../src
+
+SOURCE          TestServerClient.cpp
+SOURCE          TestServer.cpp
+SOURCE          Testserversession.cpp
+SOURCE          Testexecution.cpp
+SOURCE          TestExecutionThread.cpp
+SOURCE          TestModuleContainer.cpp
+SOURCE          Testundertaker.cpp
+SOURCE          Printqueue.cpp
+SOURCE          TestServerEvent.cpp
+SOURCE          TestThreadContainerRunner.cpp
+SOURCE          TestThreadContainerRunnerFactory.cpp
+
+/* Used libraries */
+LIBRARY         euser.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         efsrv.lib               // For RFs file server
+
+/* Flag to disable all memory, request and handle leaks 
+* Do NOT enable this!!! Only for special purposes. */
+//MACRO STIF_DISABLE_LEAK_CHECK
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  
+*
+*	bld.inf Toplevel build information for STIF Test Framework's TestServer.
+*/
+
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	TestServer.mmp
+
+PRJ_TESTMMPFILES
+
+
+/* End of File */// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/inc/Logging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,97 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the CPrintQueue and 
+* CPrintQueueItem class definitions.
+*
+*/
+
+#ifndef LOGGINGDEFS_H
+#define LOGGINGDEFS_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+
+// CONSTANTS
+const TUint KError           = 0x1;
+const TUint KInit            = 0x2;
+const TUint KThreadOperation = 0x4;
+const TUint KRunTestCase     = 0x8;
+const TUint KPrint           = 0x10;
+const TUint KMessage         = 0x20;
+const TUint KVerbose         = 0x40;
+const TUint KAlways          = 0xFFFFFFFF;
+const TUint KDebugLevel      = ( KMessage | KInit | KError );
+
+// MACROS
+#define __TRACING_ENABLED
+
+// Define USE_RDEBUG to use RDebug::Print for logging
+//#define USE_RDEBUG
+
+// Define USE_LOGGER to use logger for logging
+#define USE_LOGGER
+
+#ifdef __TRACING_ENABLED
+
+    // TRACE macro is used in server thread
+    
+    // Disable conditional expression is constant -warning
+    #pragma warning( disable : 4127 )
+
+    // Using logger and not RDebug
+    #if defined (USE_LOGGER) && !defined (USE_RDEBUG)
+    #define __TRACE(level,p) if ( (level) & KDebugLevel) { ((CStifLogger*) Dll::Tls())->Log p; }
+    #endif
+
+    // Using RDebug and not Logger
+    #if defined (USE_RDEBUG) && !defined (USE_LOGGER)
+    #define __TRACE(level,p) if ( (level) & KDebugLevel) { RDebug::Print p; }
+    #endif
+
+    // Using Logger and RDebug
+    #if defined (USE_RDEBUG) && defined (USE_LOGGER)
+    #define __TRACE(level,p) if ( (level) & KDebugLevel) {\
+    ((CStifLogger*) Dll::Tls())->Log p;\
+    RDebug::Print p;\
+    }
+    #endif
+
+    // Not using RDebug and not using logger
+    #if !defined(USE_RDEBUG) && !defined (USE_LOGGER)
+    #define __TRACE(level,p);
+    #endif
+    
+    #define __RDEBUG(x) if( KVerbose & KDebugLevel){ RDebug::Print x ; }
+
+#else
+    // No tracing
+    #define __TRACE(level,p);
+    
+    #define  __RDEBUG(x)
+#endif
+
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+#endif // LOGGINGDEFS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/inc/PrintQueue.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,191 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the CPrintQueue and 
+* TPrintQueueItem class definitions.
+*
+*/
+
+#ifndef PRINTQUEUE_H
+#define PRINTQUEUE_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifTestInterface.h>
+
+
+// CONSTANTS
+
+// The print queue maximum length. If queue overflows, the lowest
+// priority item is discarded from queue.
+const TInt KQueueMaxLen = 20;
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TPrintQueueItem is a print queue item class.
+class TPrintQueueItem 
+        :public CBase
+    {
+    public: // Enumerations
+         // None
+    
+    protected: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        /** 
+        * C++ default constructor.
+        */
+        TPrintQueueItem( const TInt aPriority,
+                         const TStifInfoName& aText1,
+                         const TName& aText2 );
+
+    public: // New functions
+        // None
+
+    protected:  // New functions
+        // None
+
+    private:    // New functions
+
+    public:  // Functions from base classes        
+        
+    protected:  // Functions from base classes
+        // None
+
+    private:
+       // None
+       
+    public:   //Data
+        TStifInfoName     iData1;                    // Description
+        TName         iData2;                    // Text
+        TInt          iPriority;                 // Priority
+        static const  TInt iOffset;              // Queue link offset
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        TSglQueLink   iSlink;                    // Queue link
+    
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None 
+
+    };
+
+// DESCRIPTION
+// CPrintQueue is a queue for test module prints
+class CPrintQueue
+        :public CBase
+    {
+    public: // Enumerations
+        // None
+
+    protected: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */        
+        static CPrintQueue* NewL();
+
+        /**
+        * Destructor of CPrintQueue.
+        */
+        virtual ~CPrintQueue();
+
+
+    public: // New functions
+
+        /**
+        * Pops item from queue
+        */
+        TPrintQueueItem*  Pop();
+    
+
+        /**
+        * Push item to queue
+        */
+        TInt Push( TPrintQueueItem& anItem );
+
+        /**
+        * Returns the count
+        */
+        TInt Count();
+        
+
+    public: // Functions from base classes
+        // None
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CPrintQueue();
+        
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        TSglQue<TPrintQueueItem>     iQueue;
+        TSglQueIter<TPrintQueueItem> iQueueIterator;
+        TInt                         iQueueLen;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif  // PRINTQUEUE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/inc/TestServer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1685 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CTestServer.
+*
+*/
+
+#ifndef TEST_SERVER_H
+#define TEST_SERVER_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include "PrintQueue.h"
+#include <StifLogger.h>
+#include "Logging.h"
+#include <StifTestModule.h>
+#include <StifTestInterface.h>
+
+// CONSTANTS
+
+// KDefaultHeapSize needed for creating server thread.
+const TUint KDefaultHeapSize = 0x10000;
+const TUint KMaxHeapSize     = 0x20000;
+
+// MACROS
+
+// FUNCTION PROTOTYPES
+typedef CTestModuleBase*( *CTestInterfaceFactory )();
+
+// DATA TYPES
+
+// Panic reasons
+enum TTestServerPanic
+    {
+    EBadRequest,
+    EBadDescriptor,
+    EDescriptorNonNumeric,
+    EMainSchedulerError,
+    ESvrCreateServer,
+    ECreateTrapCleanup,
+    EBadRemove, 
+    EBadSubsessionHandle,
+    ENoStartupInformation,
+    EEnumerateHasNotBeenCalled,
+    EClosingWhileTestRunning,
+    EPrintMutexNotFreed,
+    EThreadMutexNotFreed,
+    EEventMutexNotFreed,
+    EEventArrayMutexNotFreed,
+    ETestModuleMutexNotFreed,
+    EInvalidCTestExecution,
+    EPrintQueueBroken,
+    EInvalidRequestCancel,
+    EWrongEventQueueDeleteContext,
+    EReInitializingTestModule,
+    ETestModuleNotInitialized,
+    EInvalidTestModuleOperation,
+    EWrongHeapInUse,
+    ENullTestModuleFunction,
+    ENullTestModuleContainer,
+    ENullTestModule,
+    ECannotCreateEventArray,
+    EPreviousRequestStillOngoing,
+    ECannotOpenServerThread,
+    ENullModuleSession,
+    EInvalidThreadState,
+    EUnknownEventCmd,
+    EUnknownRemoteCmd,
+    ENullTestThreadContainer,
+    ENullExecution,
+    EAlreadyActive,
+    };
+
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class TEvent;
+class CTestModule;
+class CTestModuleContainer;
+class CTestExecution;
+class CTestThreadContainer;
+class CErrorPrintHandler;
+class CTestThreadContainerRunnerFactory;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CUnderTaker class is an active object that handles thread death
+// notifications.
+class CUnderTaker 
+        :public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CUnderTaker* NewL( CTestModuleContainer* aContainer );
+
+        /**
+        * Destructor of CUnderTaker.
+        */
+        virtual ~CUnderTaker();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        TInt StartL();
+
+        /**
+        * Is undertaker completed?
+        */
+        TBool Completed();
+
+		/**
+        * Sets or unsets local processing mode
+        */
+        void SetSynchronousMode(const TBool aMode);
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CUnderTaker();
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CTestModuleContainer* aContainer );
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestModuleContainer* iModuleContainer;           // Pointer to parent
+         TBool iCancelNeeded;                              // Is cancel needed?
+		 TBool iSynchronousMode;                           // In synchronous mode
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+
+
+// DESCRIPTION
+// CTestModuleContainer is a class, which contains the test execution thread
+// and interface functions to do operations in that thread context.
+class CTestModuleContainer 
+       :public CActive  
+    {
+
+    public: // Enumerations
+        enum TOperation
+            {
+            EInitializeModule,
+            EEnumerateInThread,
+            EExecuteTestInThread,
+            EFreeEnumerationData,
+            EExit,
+            };
+        
+        enum TRequestType
+            {
+            ERqTestCase,
+            ERqErrorPrint,
+            };
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestModuleContainer* NewL( const TDesC& aName, 
+                                           CTestModule* aSession,
+                                           const TDesC& aConfig );
+
+        /**
+        * Destructor of CTestModuleContainer.
+        */
+        virtual ~CTestModuleContainer();
+
+
+    public: // New functions
+
+        /**
+        * Initialize the test module
+        */
+        TInt Initialize( const TFileName& aName,
+                         const TBool aFirstTime );
+
+        /**
+        * Enumerate test cases
+        */
+        TInt EnumerateTestCases( const TFileName& aName );
+
+
+        /**
+        * Frees the enumeration data
+        */
+        TInt FreeEnumerationData();
+
+        /**
+        * Run a test case
+        */
+        void RunTestCase( const TFileName& aName,
+                          const TInt aCaseNumber,
+                          const RMessage2& aMessage );
+
+
+        /**
+        * Changes the operation, can fail
+        */
+        TInt ChangeOperation( const TOperation aOperation, 
+                              const TFileName& aNameBuffer,
+                              const TInt aInt );
+
+        /**
+        * Changes the operation
+        */
+		void ChangeOperationNoError( const TOperation aOperation,
+                                     const TInt aInt );
+
+        /**
+        * Return the operation
+        */
+        //@spe const TOperation Operation();
+        TOperation Operation();
+
+        /**
+        * Set a new execution subsession
+        */
+        void SetExecutionSubSession( CTestExecution* aExecution );
+
+        /**
+        * Pauses the thread
+        */
+        TInt PauseThread();
+
+        /**
+        * Resumes the thread
+        */
+        TInt ResumeThread();
+
+        /**
+        * Returns pointer to test cases
+        */
+        const RPointerArray<TTestCaseInfo>* TestCases() const;
+
+        /**
+        * Returns error code from operation
+        */
+        TInt& OperationErrorResult();
+
+        /**
+        * Returns error code from module
+        */
+        TInt& ModuleResult();
+
+        /**
+        * Kill the thread
+        */
+        void KillThread( const TInt aCode );
+        
+        /**
+        * Error print handler.
+        */
+        void DoErrorPrint();
+
+        /**
+        * Make sure that any of the test interference thread's won't stay
+        * to run if test case is crashed of test interference object is not
+        * deleted.
+        */ 
+        void KillTestinterferenceThread();
+
+        /**
+        * Make sure that any of the test measurement process's won't stay
+        * to run if test case is crashed of test measurement object is not
+        * deleted.
+        */
+        void KillTestMeasurement();
+
+    public: 
+    
+        /**
+        * Get semaphore handles.
+        */
+        TInt OperationStartSemHandle(){ return iOperationStartSemaphore.Handle(); };
+        TInt OperationChangeSemHandle(){ return iOperationChangeSemaphore.Handle(); };
+    
+        /** 
+        * Access to "shared" memory.
+        * Called from test thread'
+        */
+        void SetThreadContainer( CTestThreadContainer* aThread )
+            { iThreadContainer = aThread; };
+        
+        const TDesC& OperationName(){ return iOperationName; };
+
+        TDes& OperationText(){ return iOperationText; };
+        
+        TInt& OperationIntBuffer(){ return iOperationIntBuffer; };
+        
+        TOperation OperationType(){ return iOperationType; };
+        
+        const TDesC& TestModuleName();
+        const TDesC& TestModuleIniFile();
+        
+        CTestModuleIf::TExitReason& AllowedExitReason()
+            { return iAllowedExitReason; };   
+
+        TInt& AllowedExitCode(){ return iAllowedExitCode; };        
+      
+        TThreadId ServerThreadId(){ return iServerThreadId; };
+        
+        CTestExecution* TestExecution()
+            { return iCTestExecution; };
+
+        TRequestStatus* GetRequest( TRequestType aType );
+        
+        TErrorNotification& ErrorNotification(){ return iErrorPrint; };
+        
+        TInt ErrorPrintSemHandle(){ return iErrorPrintSem.Handle(); };
+        
+        /**
+        * Get title of currently running test case
+        */ 
+        void GetTestCaseTitleL(TDes& aTestCaseTitle);
+
+        /**
+         * Gets pointer to test module
+         */
+        CTestModule* GetTestModule();        
+        
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aName, 
+                         CTestModule* aSession,
+                         const TDesC& aConfig );
+
+	private:  // New functions
+
+		/**
+        * Start and wait until operation is completed.
+        */
+        TInt StartAndWaitOperation();
+
+        /**
+        * Completes operation from test execution thread or from undertaker
+        */
+        void Complete(  const TInt aCompletionCode );
+
+        /**
+        * Function that initialise module in execution thread context.
+        */
+        TInt InitializeModuleInThread( RLibrary& aModule );
+
+        /**
+        * Function that enumerates test cases in execution thread context.
+        */
+        TInt EnumerateInThread();
+
+        /**
+        * Function that frees the enumeration data in execution thread context.
+        */
+        void FreeEnumerationDataInThread();
+
+        /**
+        * Function that executes test case in execution thread context.
+        */
+        TInt ExecuteTestCaseInThread();
+
+		
+        /**
+        * Delete a test module instance
+        */
+		void DeleteTestModule();
+
+        /**
+        * Function that resolves test case completion code
+        */
+        TInt ResolveCompletionCode( TInt aLeaveCode,
+                                    TInt aErrorCode );
+
+        /**
+        * Test case execution thread thread function
+        */
+        static TInt ExecutionThread( TAny* aParams );
+
+        /**
+        * Parse stack and heap information for TestScripter's
+        * test case (config) file.
+        */
+		TInt ReadParametersFromScriptFileL( const TDesC& aConfig,
+                                            TInt& aStackSize,
+											TInt& aHeapMinSize,
+											TInt& aHeapMaxSize );
+
+        /**
+        * Loads dynamically testmodule and calls SetRequirements()-
+		* method for test module parameter handling.
+        */
+        TInt ReadParametersFromTestModule( const TDesC& aModuleName,
+										CTestModuleParam*& aTestModuleParam );
+
+        /**
+        * Load test module dynamically. If loading is done succesfully
+		* then get test module's parameters according to version.
+        * Verifies received parameters also.
+        */
+        TInt GetTestModuleParams( const TDesC& aModuleName,
+                                    const TDesC& aConfig,
+									TInt& aStackSize,
+									TInt& aHeapMinSize,
+									TInt& aHeapMaxSize );
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CTestModuleContainer();
+
+    public:     // Data
+
+    protected:  // Data
+        // None
+
+    private:    // Data     
+        CTestExecution* iCTestExecution;         // Handle to "parent" test execution
+        CTestModule* iCTestModule;               // Handle to "parent"  module
+        CUnderTaker* iUnderTaker;                // Pointer to thread undertaker
+        CTestThreadContainer*   iThreadContainer;// Pointer thread container
+
+        RThread iThread;                         // Thread where test module lives in
+        TBool iUpAndRunning;                     // Is the thread running
+        TOperation iOperationType;               // What to do?
+
+        RSemaphore iOperationStartSemaphore;     // Used to wait until something to do
+        RSemaphore iOperationChangeSemaphore;    // Protects the operation changes
+
+        TPtr iOperationName;                     // Operation descriptor buffer
+        HBufC* iModuleNameBuffer;                // HBuffer for module name file;
+     
+        TInt iOperationIntBuffer;                // Transfers operation int to thread
+
+        RMessage2 iMessage;                      // Message to complete, used in RunTestCase
+
+        // Results from test module
+        TInt iModuleResult;                      // Low priority result from test module
+        TInt iErrorResult;                       // High priority error from operation
+        TRequestStatus iOperationStatus;         // Operation ongoing?
+        TThreadId iServerThreadId;               // Server thread Id. Used in completion
+		TBuf<30> iOperationText;                 // Human readable current operation for
+		
+        CTestModuleIf::TExitReason iAllowedExitReason;          // Allowed exit reason
+        TInt iAllowedExitCode;                   // Allowed exit code
+        
+        // Error print handler	    
+        CErrorPrintHandler*         iErrorPrintHandler;
+        
+        RSemaphore      iErrorPrintSem;          // Synchonize error messages
+        TErrorNotification  iErrorPrint;
+
+        // Indicates is pause operation executed. This value will be checked
+        // when test case is executed. Resume operation will be reset this
+        // value.
+        TBool  iIsPaused;
+
+		// This active scheduler is uses as a nested one        
+        CActiveSchedulerWait*       iNestedActiveScheduler;
+    
+    public:     // Friend classes
+        friend class CUnderTaker;                // Handles the thread deaths
+        friend class CErrorPrintHandler;
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+    };
+
+
+// DESCRIPTION
+// CTestServer is a server class.
+// Contains an object container index which provides subsessions with object containers.
+class CTestServer
+        :public CServer2
+    {
+    public: // Enumerations
+        enum { ETestServerPriority = CActive::EPriorityHigh };
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestServer* NewL( const TFileName& aName );
+
+        /**
+        * Destructor of CTestServer.
+        */
+        ~CTestServer();
+
+    public: // New functions
+
+        /**
+        * ThreadFunction is used to create new thread.
+        */
+        static TInt ThreadFunction( TAny* aStarted );
+
+        /**
+        * Return object container, guaranteed to produce object containers with
+        * unique ids within the server.
+        */
+        CObjectCon* NewContainerL();
+
+        /**
+        * Removes a container. Needed to close session properly.
+        */
+        void DeleteContainer( CObjectCon* aContainer );
+                    
+        /**
+        * Inform Server that session is closed.
+        */
+        void SessionClosed();
+        
+        /**
+        * Returns module name
+        */
+        const TDesC& ModuleName() const;
+
+        /**
+        * Is module inside this server already initialised?
+        */
+        //@spe const TBool FirstTime() const;
+        TBool FirstTime() const;
+
+        /**
+        * Clears the module first time flag.
+        */
+        void ClearFirstTime();
+
+        /**
+        * PanicServer panics the CTestServer
+        */
+        static void PanicServer( const TTestServerPanic aPanic );
+
+        /**
+        * GetServerThreadId for ServerStateHandler Active object usage
+        */
+        TInt GetServerThreadId ();
+        
+        /**
+         * Gets CTestThreadContainerRunner pointer which is used in UI testing
+         */
+        CTestThreadContainerRunnerFactory* GetTestThreadContainerRunnerFactory();
+                
+        /**
+         * Gets information that testserver supports UI testing or not
+         */
+        TBool UiTesting();
+        
+        /**
+         * Gets pointer to UiEnvProxy.
+         */
+        CUiEnvProxy* GetUiEnvProxy();
+    public: // Functions from base classes
+
+        /**
+        * NewSessionL creates new CTestServer session.
+        */
+        CSession2* NewSessionL( const TVersion &aVersion,
+                                const RMessage2& aMessage ) const;
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CTestServer();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TFileName& aName );
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CObjectConIx* iContainerIndex;           // Pointer to container
+        TPtr iModuleName;                        // Server name
+        HBufC* iModuleNameBuffer;                // HBuffer for module name file;
+        TBool iFirstTime;                        // Is module previously initialized?
+
+        // Container count
+        TInt                    iSessionCount;
+
+        TBool iUiTesting;						 // Indicates if it is testserver which supports UI testing
+        CTestThreadContainerRunnerFactory* iTestThreadContainerRunnerFactory; // Pointer to CTestThreadContainerRunnerFactory
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// CTestCasesList is a class, which contains list of test cases assosiated with
+// specified config file.
+NONSHARABLE_CLASS( CTestCasesList ): public CBase
+    {
+public:
+    /**
+    * NewL is first phase of two-phased constructor.
+    */
+    static CTestCasesList* NewL( const TDesC& aConfigFileName );
+public:
+    /**
+    * Destructor of CTestServer.
+    */
+    ~CTestCasesList();
+
+    /**
+     * Appends test case.
+     */
+    void AppendTestCaseL( const TDesC& aTestCaseTitle );
+    
+    /**
+     * Returns specified test case title.
+     */
+    const TDesC& GetTestCaseTitleL( TInt aIndex ) const;
+    
+    /**
+     * Returns config file name.
+     */
+    const TDesC& GetConfigFileName() const;
+    
+    /**
+     * Returns count of test cases.
+     */
+    TInt Count() const;
+    
+    /**
+     * Resets list of test cases.
+     */
+    void ResetAndDestroy();
+private:
+    /** 
+    * C++ default constructor.
+    */
+    CTestCasesList();
+    
+    /**
+    * By default Symbian OS constructor is private.
+    */
+    void ConstructL( const TDesC& aConfigFileName );
+private:
+    // Config file name
+    HBufC* iConfigFileName;
+    // List of test cases
+    RPointerArray<HBufC> iTestCases;
+    };
+
+        
+// DESCRIPTION
+// CTestModule is a session class.
+// Session for the CTestServer server, to a single client-side session
+// a session may own any number of CCounter objects
+class CTestModule
+        :public CSession2
+    {    
+    public:
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+
+        /**
+        * Construct a test module object.
+        */
+        static CTestModule* NewL( CTestServer* aServer );
+
+        /**
+        * Destructor
+        */
+        virtual ~CTestModule();
+
+    public: // New functions
+
+        /**
+        * Dispatch message
+        */
+        TInt DispatchMessageL( const RMessage2& aMessage );
+
+        /**
+        * Create Module Session
+        */
+        TInt CreateModuleSessionL( const RMessage2& aMessage );
+
+        /**
+        * Close the session to CTestServer.
+        */
+        TInt CloseSession( const RMessage2& aMessage );
+
+
+        /**
+        * Create CTestExecution subsession.
+        */
+        TInt NewTestExecutionL( const RMessage2& aMessage );
+
+        /**
+        * Destroy the created CTestExecution subsession.
+        * Cannot fail - can panic client.
+        */
+        void DeleteTestExecution( const TUint aHandle, const RMessage2& aMessage );
+
+        /**
+        * NumResources is used to provide reserver resources to client.
+        */
+        void NumResources( const RMessage2& aMessage );
+
+        /**
+        * Return the number of resources owned by the session.
+        */
+        TInt CountResources();
+
+        /**
+        * Enumerates test cases
+        */
+        TInt EnumerateTestCasesL( const RMessage2& aMessage );
+
+        /**
+        * Get test cases
+        */
+        TInt GetTestCasesL( const RMessage2& aMessage );
+
+        /**
+        * Handles error notifications
+        */
+        TInt HandleErrorNotificationL( const RMessage2& aMessage );
+
+        /**
+        * Get Server Thread Id
+        */
+        TInt GetServerThreadIdL( const RMessage2& aMessage );
+
+
+        /**
+        * Prints error notification
+        */
+        void ErrorPrint( const TInt aPriority, 
+                         TPtrC aError );
+
+        /**
+        * Cancels asynchronous request
+        */
+        TInt CancelAsyncRequestL( const RMessage2& aMessage );
+
+        /**
+        * Frees a test case specific data owned by module( i.e enumeration data )
+        */
+        TInt FreeCaseData();
+
+        /**
+        * Returns case corresponding handle
+        */
+        CTestExecution* CaseFromHandle( const TUint aHandle, const RMessage2& aMessage ) const;
+
+        /**
+        * Returns module initialisation file name
+        */
+        const TDesC& IniName() const;
+
+		/**
+        * Returns module name
+        */
+		const TDesC& Name() const;
+
+        /**
+        * Returns a test module.
+        */
+        TInt GetTestModule( CTestModuleContainer*& aContainer,
+                            const TDesC& aConfig );
+
+        /**
+        * Frees a test module.
+        */
+        TInt FreeTestModule( CTestModuleContainer* aModule );
+
+        /**
+        * Write is utility method.
+        */
+        void Write( const TAny* aPtr, const TDesC8& aDes, TInt anOffset = 0 );
+
+        /**
+        * PanicClient panics the user of CTestModule( RTestModule user )
+        */
+        void PanicClient( TInt aPanic, const RMessage2& aMessage ) const;
+
+        /**
+        * Get title of currently running test case
+        */ 
+        void GetTestCaseTitleL(TInt aTestCaseNumber, const TDesC& aConfigFile, TDes& aTestCaseTitle);
+
+        /**
+         * Get pointer to test server
+         */ 
+         CTestServer* GetTestServer();        
+        
+    public: // Functions from base classes
+
+        /**
+        * ServiceL handles the messages to CTestServer
+        */
+        virtual void ServiceL( const RMessage2& aMessage );
+
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CTestModule();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CTestServer* aServer );
+
+    public:   //Data
+        // None
+
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        RPointerArray<CTestModuleContainer>* iTestModuleInstances; // List of FREE test modules
+        CTestServer* iTestServer;                    // Pointer to "parent"
+        CObjectCon* iContainer;                  // Object container for this session
+        CObjectIx* iTestExecutionHandle;         // Object index( stores CTestExecutions,
+                                                 // (Unclosed)subsession handle )
+
+        TInt iResourceCount;                     // Total number of resources allocated
+        TPtr iIni;                               // Module initialisation( file ) name
+        HBufC* iIniBuffer;                       // HBuffer for ini name file;
+
+        CTestModuleContainer* iEnumerateModule;  // Module used in enumeration
+
+        RMessage2 iErrorMessage;                 // Error message
+
+        TBool iErrorMessageAvailable;            // Error message available?
+        
+        RPointerArray<CTestCasesList> iTestCaseTitlesMap;    //Test case titles
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CPrintHandler class is an active object that handles print
+// indication from test thread.
+class CPrintHandler 
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CPrintHandler* NewL( CTestExecution& aExecution );
+
+        /**
+        * Destructor of CPrintHandler.
+        */
+        virtual ~CPrintHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CPrintHandler( CTestExecution& aExecution );
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestExecution&        iExecution;     // Pointer to parent
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CEventHandler class is an active object that handles print
+// indication from test thread.
+class CEventHandler 
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CEventHandler* NewL( CTestExecution& aExecution );
+
+        /**
+        * Destructor of CEventHandler.
+        */
+        virtual ~CEventHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CEventHandler( CTestExecution& aExecution );
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestExecution&        iExecution;     // Pointer to parent
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CSndHandler class is an active object that handles print
+// indication from test thread.
+class CSndHandler 
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CSndHandler* NewL( CTestExecution& aExecution );
+
+        /**
+        * Destructor of CSndHandler.
+        */
+        virtual ~CSndHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CSndHandler( CTestExecution& aExecution );
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestExecution&        iExecution;     // Pointer to parent
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CRcvHandler class is an active object that handles print
+// indication from test thread.
+class CRcvHandler 
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CRcvHandler* NewL( CTestExecution& aExecution );
+
+        /**
+        * Destructor of CRcvHandler.
+        */
+        virtual ~CRcvHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CRcvHandler( CTestExecution& aExecution );
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestExecution&        iExecution;     // Pointer to parent
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+        
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CErrorPrintHandler class is an active object that handles print
+// indication from test thread.
+class CErrorPrintHandler 
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CErrorPrintHandler* NewL( CTestModuleContainer& aContainer );
+
+        /**
+        * Destructor of CErrorPrintHandler.
+        */
+        virtual ~CErrorPrintHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CErrorPrintHandler( CTestModuleContainer& aContainer );
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestModuleContainer&      iContainer;     // Pointer to parent
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestInterferenceHandler class is an active object that handles test
+// interference
+NONSHARABLE_CLASS( CInterferenceHandler ) 
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CInterferenceHandler* NewL( CTestExecution& aExecution );
+
+        /**
+        * Destructor of CInterferenceHandler.
+        */
+        virtual ~CInterferenceHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CInterferenceHandler( CTestExecution& aExecution );
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestExecution&        iExecution;     // Pointer to parent
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+// DESCRIPTION
+// CMeasurementHandler class is an active object that handles test
+// measurement
+NONSHARABLE_CLASS( CMeasurementHandler ) 
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMeasurementHandler* NewL( CTestExecution& aExecution );
+
+        /**
+        * Destructor of CMeasurementHandler.
+        */
+        virtual ~CMeasurementHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError( TInt aError );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CMeasurementHandler( CTestExecution& aExecution );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointer to test execution side
+        CTestExecution&        iExecution;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+/**
+* Check is module TestScripter. Does parsing and returns new module name and
+* error codes(Needed operations when creating server sessions to TestScripter).
+*/
+TInt CheckModuleName( TFileName aModuleName, TFileName& aNewModuleName );
+
+/**
+* Remove optional index appended to module name.
+* If it is found (@ char) then set new module name without it.
+* This feature is used when iSeparateProcesses is set in TestEngine.
+*/
+void RemoveOptionalIndex(const TDesC& aModuleName, TDes& aNewModuleName);
+
+// DESCRIPTION
+// CEventHandler class is an active object that handles print
+// indication from test thread.
+NONSHARABLE_CLASS(CCommandHandler)
+    : public CActive
+    {
+
+    public:  // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCommandHandler* NewL(CTestExecution& aExecution);
+
+        /**
+        * Destructor of CCommandHandler.
+        */
+        virtual ~CCommandHandler();
+
+    public: // New functions
+
+        /**
+        * Start monitoring
+        */
+        void StartL();
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+
+        /**
+        * RunError derived from CActive handles errors from active handler.
+        */
+        TInt RunError(TInt aError);
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CCommandHandler(CTestExecution& aExecution);
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+         CTestExecution&        iExecution;     // Pointer to parent
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif // TEST_SERVER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/inc/TestServerCommon.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains common data for Test Server.
+*
+*/
+
+
+#ifndef TEST_SERVER_COMMON_H
+#define TEST_SERVER_COMMON_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+
+// Server name
+_LIT( KTestServerName,"TestFrameworkServer" );
+
+// The server version.
+// A version must be specified when creating a session with the server.
+const TUint KTestServerMajorVersionNumber=0;
+const TUint KTestServerMinorVersionNumber=1;
+const TUint KTestServerBuildVersionNumber=1;
+
+
+#endif // TEST_SERVER_COMMON_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/inc/TestServerEvent.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,176 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the event 
+* interface.
+*
+*/
+
+#ifndef TESTSERVEREVENT_H
+#define TESTSERVEREVENT_H
+
+//  INCLUDES
+#include <StifTestEventInterface.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+
+// FUNCTION PROTOTYPES
+// None
+
+
+// FORWARD DECLARATIONS
+class CTestExecution;
+
+// CLASS DECLARATION
+
+
+// DESCRIPTION
+// Interface class for the test system.
+class TEvent
+    :public TEventIf
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        /**
+        * C++ default constructor.
+        */
+        TEvent( TThreadId aThreadId );
+        
+        /**
+        * C++ destructor.
+        */
+        ~TEvent();
+
+    public: // New functions
+        
+        /**
+        * Set event.
+        */
+        void Set( TEventType aEventType );
+        
+       	/** 
+        * Check event status.
+        */ 
+        TBool EventPending();
+        
+        /** 
+        * Check waiting status.
+        */ 
+        TBool WaitEventPending();
+        
+        /**
+        * First phase of waiting.
+        */
+		TInt SetWaitPending( TRequestStatus* aStatus = NULL );
+
+        /**
+        * Wait event.
+        */
+        void Wait();
+        
+        /**
+        * Complete pending wait.
+        */
+		void CompletePendingWait( TInt aError );
+
+        /**
+        * Release event. Completes conceivably pending unset.
+        */
+        void Release();
+        
+        /**
+        * Unset event. Unset blocks until Release is called 
+        * (i.e. iUnsetMessage is compeled from release).
+        */
+        TInt Unset( const RMessage2& aMessage, CTestExecution* aExecution );
+        
+        /**
+        * Get TRequestStatus of the event.
+        */ 
+        const TRequestStatus* RequestStatus() const { return iReq; }; 
+
+    public: // Functions from base classes
+        // None
+        
+    protected:  // New functions
+        // None
+        
+    protected:  // Functions from base classes
+        // None
+        
+    private:
+        // None
+        
+	public:   //Data
+	    // None
+        
+	protected:  // Data
+        // None
+        
+    private:    // Data
+        /**
+        * Request status.
+        */
+        TRequestStatus* iReq; 
+        TRequestStatus iRequestStatus;
+        
+        /**
+        * Thread id.
+        */
+        TThreadId iThread;
+
+        /**
+        * Unset message.
+        */
+        RMessage2 iUnsetMessage;
+
+        /**
+        * Flag for state event status.
+        */
+        TBool iEventPending;
+        /**
+        * Flag for indicating that iReq is owned by us.
+        */
+        TBool iOwnReq;
+        
+        /**
+        * Execution object. Is non-NULL if unset is pending.
+        */ 
+        CTestExecution* iExecution;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+    };
+
+#endif      // TESTSERVEREVENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/inc/TestThreadContainerRunner.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,180 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* TestThreadContainerRunner class.
+*
+*/
+
+#ifndef TESTTHREADCONTAINERRUNNER_H_
+#define TESTTHREADCONTAINERRUNNER_H_
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CTestThreadContainer;
+class CTestModuleContainer;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// This class is used to emulate CTestThreadContainer::ExecutionThread method
+// as an active object run in main thread of uitestserverstarter.
+class CTestThreadContainerRunner: public CActive
+	{
+	public: // Enumerations
+	    // None
+	
+	private: // Enumerations
+		// Current operation type
+		enum TOperationType { ENone,			// None 
+							  ESetup, 			// Setup
+							  ETearDown,		// TearDown
+							  ERunOneIteration,	// Emulate one iteration of while loop placed 
+							  					// in CTestThreadContainer::ExecutionThread   
+							};
+	
+	public:  // Constructors and destructor
+		/**
+		 * Performs first phase of two-phased constructor.
+		 */
+		IMPORT_C static CTestThreadContainerRunner* NewL( TThreadId aMainThreadId, 
+				CActiveScheduler* aMainThreadActiveScheduler );
+
+		/**
+		 * C++ destructor.
+		 */
+		~CTestThreadContainerRunner();
+	
+	private:  // Constructors and destructor
+		/**
+		 * C++ constructor.
+		 */
+		CTestThreadContainerRunner();
+		
+		/**
+		 * Performs second phase of two-phased constructor.
+		 */
+		void ConstructL( TThreadId aMainThreadId, 
+				CActiveScheduler* aMainThreadActiveScheduler );
+	
+	public: // New functions
+		/**
+		 * Performs TestThreadContainer setup.
+		 */
+		void Setup( CTestModuleContainer* aTestModuleContainer );
+		
+		/**
+		 * Runs one iteration of emulated CTestThreadContainer::ExecutionThread while loop.
+		 */
+		void RunOneIteration();
+		
+		/**
+		 * Performs cleanup of TestThreadContainer.
+		 */
+		void TeareDown();
+		
+		/**
+		 * Checks if operation change signal was signaled from suspend state. 
+		 */
+		void CheckSignalFromSuspend();
+
+		/**
+		 * Checks if test thread is reusable.
+		 */
+		TBool IsReusable();
+
+
+	public: // Functions from base classes
+		/**
+		 * RunL derived from CActive handles the completed requests.
+		 */
+		void RunL();
+
+		/**
+		 * DoCancel derived from CActive handles the Cancel.
+		 */
+		void DoCancel();
+
+    protected:	// New functions
+        // None
+        
+    protected:	// Functions from base classes
+        // None
+        
+    private:	// New functions
+    	/**
+    	 * Test thread exception handler. 
+    	 */
+		static void ExceptionHandler ( TExcType aType );
+	
+		/**
+		 * Raises panic.
+		 */
+		void Panic( TInt aReason );
+		
+		/**
+		 * Complets current operation request, what causes execution of RunL method 
+		 * in main thread of UITestServerStarter.
+		 */
+		void CompleteRequest();
+    private:	// Functions from base classes
+        // None    
+    
+	public:		//Data
+	    // None
+        
+	protected:	// Data
+        // None
+        
+    private:	// Data
+		TThreadId iMainThreadId;					// UITestServerStarter main thread id.
+		CActiveScheduler* iMainThreadActiveScheduler;	// Pointer to UITestServerStarter main thread active scheduler.		
+	    RLibrary iModule;							// Handle to test module library.
+		CTestModuleContainer* iTestModuleContainer; // Pointer to test module container.		
+		TOperationType iCurrentOperation;			// Current operation type.
+		CTestThreadContainer* iTestThreadContainer;	// Pointer to test thread container.
+	
+		RSemaphore iOperationOngoing;				// Current operation end semaphore.
+		
+	    TBool iReusable;             				// Is test module reusable.
+	    TBool iSignalFromSuspend;   				// Send signal from suspend state.
+	    TBool iInitialized;         				// Is module initialized.
+	    TInt iReturnCode;							// Lasst loop result code
+		
+    public:		// Friend classes
+        // None
+
+    protected:	// Friend classes
+        // None
+
+    private:	// Friend classes
+        // None
+	};
+
+#endif // TESTTHREADCONTAINERRUNNER_H_
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/inc/ThreadLogging.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: Logging definitions.
+*
+*/
+
+#ifndef LOGGINGDEFS_H
+#define LOGGINGDEFS_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+
+// CONSTANTS
+const TUint KError           = 0x1;
+const TUint KInit            = 0x2;
+const TUint KThreadOperation = 0x4;
+const TUint KRunTestCase     = 0x8;
+const TUint KPrint           = 0x10;
+const TUint KMessage         = 0x20;
+const TUint KVerbose         = 0x40;
+const TUint KAlways          = 0xFFFFFFFF;
+const TUint KDebugLevel      = ( KMessage | KInit | KError );
+
+// MACROS
+#define __TRACING_ENABLED
+
+// Define USE_RDEBUG to use RDebug::Print for logging
+//#define USE_RDEBUG
+
+// Define USE_LOGGER to use logger for logging
+#define USE_LOGGER
+
+#ifdef __TRACING_ENABLED
+
+    // TRACEI macro is used in test execution thread to allow the test use Tls for its own purposes
+    // Note that handles to server (i.e to fileserver) are thread specific.
+
+    // Disable conditional expression is constant -warning
+    #pragma warning( disable : 4127 )
+
+    // Using logger and not RDebug
+    #if defined (USE_LOGGER) && !defined (USE_RDEBUG)
+    #define __TRACEI(level,p) if ( (level) & KDebugLevel) { if(THREADLOGGER)THREADLOGGER->Log p; }
+    #endif
+
+    // Using RDebug and not Logger
+    #if defined (USE_RDEBUG) && !defined (USE_LOGGER)
+    #define __TRACEI(level,p) if ( (level) & KDebugLevel) { RDebug::Print p; }
+    #endif
+
+    // Using Logger and RDebug
+    #if defined (USE_RDEBUG) && defined (USE_LOGGER)
+
+    #define __TRACEI(level,p) if ( (level) & KDebugLevel) {\
+        if(THREADLOGGER)THREADLOGGER->Log p;\
+        RDebug::Print p;\
+    }
+
+    #endif
+
+    // Not using RDebug and not using logger
+    #if !defined(USE_RDEBUG) && !defined (USE_LOGGER)
+    #define __TRACEI(level,p);
+    #endif
+    
+    #define __RDEBUG(x) if( KVerbose & KDebugLevel){ RDebug::Print x ; }
+
+#else
+    // No tracing
+    #define __TRACEI(level,p);
+
+    #define  __RDEBUG(x)
+#endif
+
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+#endif // LOGGINGDEFS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/Printqueue.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,282 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CPrintQueue 
+* class and TPrintQueueItem class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include "PrintQueue.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+// Initialise the queue
+const TInt TPrintQueueItem::iOffset = _FOFF( TPrintQueueItem, iSlink );
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintQueue
+
+    Method: NewL
+
+    Description: Constructs a print queue.
+      
+    Parameters: None
+
+    Return Values: CPrintQueue*                     Pointer to new queue
+
+    Errors/Exceptions: Leaves if memory allocation fails.
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CPrintQueue* CPrintQueue::NewL()
+    {
+
+    CPrintQueue* self = new( ELeave ) CPrintQueue;
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintQueue
+
+    Method: CPrintQueue
+
+    Description: Constructor.
+    Initialises the queue and queue iterator.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CPrintQueue::CPrintQueue():
+     iQueue( TPrintQueueItem::iOffset ),
+     iQueueIterator( iQueue )
+    {
+
+    iQueueLen = 0;
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintQueue
+
+    Method: ~CPrintQueue
+
+    Description: Destructor.
+
+    Deletes all items in queue. Function requires that it is called from
+    the heap to where the items are constructed.
+       
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CPrintQueue::~CPrintQueue()
+    {
+    
+    TPrintQueueItem *item = NULL;
+
+    // Delete items in queue
+    while(( item = Pop() ) != NULL )
+        {
+        delete item;      // TPrintQueueItem destructor does't free the memory
+        }
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintQueue
+
+    Method: Push
+
+    Description:
+
+    Push item to queue. If queue is full, does not add item to queue.
+
+    Parameters: TPrintQueueItem& anItem       :in:  Item to push to queue
+
+    Return Values: TInt                             KErrNoMemory if queue is full
+                                                    KErrNone     otherwise
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CPrintQueue::Push( TPrintQueueItem& anItem )
+    {
+
+    if( iQueueLen < KQueueMaxLen  )
+        {
+        iQueue.AddLast( anItem  );
+        iQueueLen++;
+
+        // Added successfully
+        return KErrNone;
+        }
+    else
+        {    
+        // Do not add to queue
+        return KErrNoMemory;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintQueue
+
+    Method: Pop
+
+    Description: Removes first item from queue and returns that.
+    if queue is empty, then return NULL.
+
+    Parameters: None
+
+    Return Values: TPrintQueueItem*                 Queue item or NULL.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TPrintQueueItem* CPrintQueue::Pop()
+    {
+
+    TPrintQueueItem* firstItem = NULL;
+    
+    if( !iQueue.IsEmpty()  )
+        {
+        firstItem = iQueue.First();
+        iQueue.Remove( *firstItem  );
+        iQueueLen--;
+        }
+    
+    return( firstItem  );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintQueue
+
+    Method: Count
+
+    Description: Returns the queue size.
+    
+    Parameters: None
+
+    Return Values: TInt                             Count
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TInt CPrintQueue::Count()
+    {
+    
+    return( iQueueLen  );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TPrintQueueItem
+
+    Method: TPrintQueueItem
+
+    Description: Constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    Parameters  const TInt aPriority          :in:  Priority
+                const TStifInfoName& aText1       :in:  Description field
+                const TName& aText2           :in:  Text field
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TPrintQueueItem::TPrintQueueItem( const TInt aPriority,
+                                  const TStifInfoName& aText1,
+                                  const TName& aText2 )
+    {
+
+    iPriority = aPriority;
+    iData1 = aText1;
+    iData2 = aText2;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/TestExecutionThread.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2892 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestThreadContainer class implementation. These functions are 
+* called from the context of the test execution thread.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+#include <e32uid.h>
+#include <StifTestModule.h>
+#include "ThreadLogging.h"
+#include "TestEngineClient.h"
+#include <stifinternal/TestServerClient.h>
+#include "TestServer.h"
+#include "TestThreadContainer.h"
+#include "TestServerCommon.h"
+#include "TestServerModuleIf.h"
+#include "TestServerEvent.h"
+#include "TestThreadContainerRunner.h"
+#include <stifinternal/TestThreadContainerRunnerFactory.h>
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES
+
+// CONSTANTS
+
+// MACROS
+#ifdef THREADLOGGER
+#undef THREADLOGGER
+#endif
+#define THREADLOGGER iThreadLogger 
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: NewL
+
+    Description: Returns new CTestThreadContainer instance.
+
+    Parameters: None
+
+    Return Values: CTestThreadContainer*            New instance
+
+    Errors/Exceptions: Function leaves if memory allocation fails or
+                       CTestThreadContainer ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainer* CTestThreadContainer::NewL( 
+    CTestModuleContainer* aModuleContainer,
+    TThreadId aServerThreadId )
+    {
+
+    CTestThreadContainer* self = 
+        new ( ELeave ) CTestThreadContainer( aModuleContainer );
+    CleanupStack::PushL( self );
+    self->ConstructL( aServerThreadId );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: CTestThreadContainer*            New instance
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::ConstructL( TThreadId aServerThreadId )
+    {
+    
+    User::LeaveIfError( iServerThread.Open( aServerThreadId ) );
+    
+    iErrorPrintSem.SetHandle( ModuleContainer().ErrorPrintSemHandle() );
+    User::LeaveIfError( iErrorPrintSem.Duplicate( iServerThread ) );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: CTestThreadContainer
+
+    Description: Constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainer::CTestThreadContainer( 
+    CTestModuleContainer* aModuleContainer ):
+    iModuleContainer( aModuleContainer ),
+    iCheckResourceFlags( 0 )
+    {
+   
+    ModuleContainer().SetThreadContainer( this );
+    
+    StifMacroErrorInit(); // Initialization
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ~CTestThreadContainer
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainer::~CTestThreadContainer()
+    {
+
+    // Close mutexes
+    if ( iPrintMutex.Handle() != 0 ) iPrintMutex.Close();
+    if ( iEventMutex.Handle() != 0 ) iEventMutex.Close();
+    if ( iSndMutex.Handle() != 0 ) iSndMutex.Close();
+    if ( iRcvMutex.Handle() != 0 ) iRcvMutex.Close();
+    if ( iInterferenceMutex.Handle() != 0 ) iInterferenceMutex.Close();
+    if ( iMeasurementMutex.Handle() != 0 ) iMeasurementMutex.Close();
+    if ( iCommandMutex.Handle() != 0 ) iCommandMutex.Close();
+
+    // Mutex for testcomplete and cancel operations. Close duplicate mutex
+    if ( iTestThreadMutex.Handle() != 0 ) iTestThreadMutex.Close();
+
+    // Close semaphores
+    if ( iPrintSem.Handle() != 0 ) iPrintSem.Close();
+    if ( iErrorPrintSem.Handle() != 0 ) iErrorPrintSem.Close();
+    if ( iEventSem.Handle() != 0 ) iEventSem.Close();
+    if ( iSndSem.Handle() != 0 ) iSndSem.Close();
+    if ( iRcvSem.Handle() != 0 ) iRcvSem.Close();
+    if ( iInterferenceSem.Handle() != 0 ) iInterferenceSem.Close();
+    if ( iMeasurementSem.Handle() != 0 ) iMeasurementSem.Close();
+    //if ( iReceiverSem.Handle() != 0 ) iReceiverSem.Close();
+    if ( iCommandSem.Handle() != 0) iCommandSem.Close();
+    
+    iServerThread.Close();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: InitializeModule
+
+    Description: Initialize test module.
+
+    Function obtains pointer to the first exported function of the test module,
+    and calls that function to obtain an instance of CTestModuleBase derived
+    object. After that the "Init()"-method is called. If some operation fails,
+    module will be deleted and error code is returned.
+
+    This function is a static member function, which is intented to be called
+    from the context of the test module thread.
+
+    Parameters: RLibrary& aModule                 :in: Module to be loaded
+    
+    Return Values: TInt                                Error code from module
+                                                       or memory allocation.
+
+    Errors/Exceptions: None.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::InitializeModuleInThread ( RLibrary& aModule )
+    {        
+        
+    __TRACEI ( KInit, ( _L("Starting test module initialization") ) );
+    __TRACEI ( KInit, ( CStifLogger::EBold,  _L("Module name \"%S\""), 
+        &ModuleContainer().OperationName() ) );
+    ModuleContainer().OperationText() = _L("E32DLL");
+
+    TFileName moduleName;
+    TFileName tmpBuffer;
+
+    TInt r( KErrNone );
+    TFileName newNameBuffer;
+    TInt check = CheckModuleName( ModuleContainer().OperationName(), newNameBuffer );
+    if( check == KErrNone )
+        {
+        // Load the module(TestScripter)
+        r = aModule.Load( newNameBuffer );
+        }
+    else
+        {
+        // Load the module(Others)
+        RemoveOptionalIndex(ModuleContainer().OperationName(), newNameBuffer);
+        __TRACEI(KInit, (_L( "Valid module name is [%S] (extracted from [%S])"), &newNameBuffer, &ModuleContainer().OperationName()));
+        r = aModule.Load(newNameBuffer);
+        }
+    
+    if ( r != KErrNone )
+        {
+        __TRACEI (KError, ( CStifLogger::EError, _L("Can't initialize test module code = %d"), r));
+
+        // Set error codes
+        ModuleContainer().OperationErrorResult() = r;
+        return r;
+        }
+    else
+        {
+        // Print module name
+        moduleName = aModule.FileName();    
+        __TRACEI (KInit, (  _L("Loaded test module[%S]"), &moduleName ) );
+        }
+
+    
+    // Get pointer to first exported function
+    ModuleContainer().OperationText() = _L("1st EXPORTED function");
+    CTestInterfaceFactory libEntry;
+    libEntry = (CTestInterfaceFactory) aModule.Lookup(1);
+    if ( libEntry == NULL )
+        {
+        // New instance can't be created
+        __TRACEI (KError, ( CStifLogger::EError, _L("Can't initialize test module, NULL libEntry")));
+
+        // Set error codes
+        ModuleContainer().OperationErrorResult() = KErrNoMemory;
+        return KErrNoMemory;
+        }
+    else
+        {
+        __TRACEI ( KInit, ( _L("Pointer to 1st exported received")));
+        }
+
+    // initialize test module
+    __TRACEI ( KVerbose, (_L("Calling 1st exported at 0x%x"), (TUint32) libEntry ));
+    TRAPD ( err, iTestModule =  (*libEntry)() );
+
+     // Handle leave from test module
+    if ( err != KErrNone )
+        {
+        __TRACEI (KError, ( CStifLogger::EError, _L("Leave when calling 1st exported function, code %d"), err));
+        tmpBuffer = _L("Leave from test module 1st EXPORTED function");        
+        ErrorPrint( 1, tmpBuffer );        
+        delete iTestModule;
+        iTestModule = NULL;
+
+        // Set error codes
+        ModuleContainer().OperationErrorResult() = err;
+        return err;
+        }
+    else if ( iTestModule == NULL )     // Handle NULL from test module init
+        {
+        __TRACEI (KError, ( CStifLogger::EError, _L("NULL pointer received when constructing test module")));
+        tmpBuffer = _L("Test module 1st EXPORTED function returned NULL");        
+        ErrorPrint( 1, tmpBuffer );        
+        delete iTestModule;
+        iTestModule = NULL;
+
+        // Set error codes
+        ModuleContainer().OperationErrorResult() = KErrNoMemory;
+        return KErrNoMemory;
+        }
+    else
+        {
+        __TRACEI (KInit, (_L("Entrypoint successfully called, test module instance at 0x%x"), (TUint32)iTestModule ) );
+        }
+
+    // Verify version number.
+    ModuleContainer().OperationText() = _L("Version");
+    TVersion moduleAPIVersion(0,0,0);
+    TVersion myOldAPIVersion( KOldTestModuleAPIMajor, KOldTestModuleAPIMinor, KOldTestModuleAPIBuild );
+    TVersion myAPIVersion( KTestModuleAPIMajor, KTestModuleAPIMinor, KTestModuleAPIBuild );
+    TRAP ( err,  moduleAPIVersion = iTestModule->Version() );
+
+    if ( err != KErrNone ||  (( myOldAPIVersion.iMajor !=  moduleAPIVersion.iMajor ||
+                                myOldAPIVersion.iMinor !=  moduleAPIVersion.iMinor  )
+                                &&
+                              ( myAPIVersion.iMajor != moduleAPIVersion.iMajor ||
+                              	myAPIVersion.iMinor != moduleAPIVersion.iMinor ))
+        )
+        {
+        tmpBuffer = moduleAPIVersion.Name();
+        __TRACEI (KError, ( CStifLogger::EError, _L("Incorrect test module version. Module version %S"), &tmpBuffer ) );        
+        tmpBuffer = myOldAPIVersion.Name();
+        __TRACEI (KError, ( CStifLogger::EError, _L("Required version %S"), &tmpBuffer  ) );
+                
+        tmpBuffer.Format(_L("Invalid version in [%S]"), &moduleName );
+        ErrorPrint( 1, tmpBuffer );        
+
+         // Set error codes
+        ModuleContainer().OperationErrorResult() = KErrNotSupported;
+        return KErrNotSupported;
+        }
+
+    ModuleContainer().OperationText() = _L("InitL");
+    // Initialize test module
+    TInt initResult = KErrNone;
+    TRAP ( err, 
+        CTestModuleIf::NewL( NULL, iTestModule );
+        TFileName tmp = ModuleContainer().TestModuleIniFile();
+        initResult = iTestModule->InitL( tmp, ModuleContainer().OperationIntBuffer() );
+    );
+
+    // Handle leave from test module
+    if ( err != KErrNone )
+        {
+        __TRACEI (KError, ( CStifLogger::EError, _L("Leave when initializing test module code %d"), err));
+        tmpBuffer = _L("Leave from test module InitL");        
+        ErrorPrint( 1, tmpBuffer );   
+        ModuleContainer().OperationText() = _L("DESTRUCTOR");
+        delete iTestModule;
+        iTestModule = NULL;
+        ModuleContainer().OperationText() = _L("");
+
+        // Set error codes
+        ModuleContainer().OperationErrorResult() = err;
+        return err;
+        }      
+    else if ( initResult != KErrNone ) 
+        {     // Handle failed initialisation of test module
+        __TRACEI (KError, ( CStifLogger::EError, _L("Can't initialize test module, code %d"), initResult));
+        ModuleContainer().OperationText() = _L("DESTRUCTOR");
+        delete iTestModule;
+        iTestModule = NULL;
+        ModuleContainer().OperationText() = _L("");
+        
+        // Set error code
+        ModuleContainer().ModuleResult() = initResult;
+        return initResult;
+        }
+    ModuleContainer().OperationText() = _L("");
+
+    __TRACEI (KInit, ( CStifLogger::EBold, _L("Test module initialization done")));     
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: EnumerateInThread
+
+    Description: Enumerate test cases. Function calls GetTestCases method
+    from the test module.
+
+    This function is a static member function, which is intented to be called
+    from the context of the test module thread.
+        
+    Parameters: None
+    
+    Return Values: TInt                           Error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::EnumerateInThread()
+    {
+
+    TInt err = KErrNone;
+    __TRACEI ( KInit, ( CStifLogger::EBold, _L("Calling GetTestCasesL") ) );
+
+    if ( iCases == NULL )
+        {
+        iCases = new RPointerArray<TTestCaseInfo>;
+        if ( iCases == NULL )
+            {
+            ModuleContainer().OperationErrorResult() = KErrNoMemory;
+            __TRACEI ( KError, ( _L("Can't create pointer array for cases") ) );
+            return ModuleContainer().OperationErrorResult();
+            }
+        }
+
+    // Thread ID logging(For error situations) !!!!! ----------
+    /*
+    RThread t;
+    RDebug::Print(_L("XXXXXXXXXXXXXXXXXXXXXX CurrentThread=[%d]"), t.Id() );
+    t.Open( t.Id() );   
+    RDebug::Print(_L("XXXXXXXXXXXXXXXXXXXXXX Real id=[%d]"), t.Id() );
+    t.Close();
+    */
+    // --------------------------------------------------------
+
+    ModuleContainer().OperationText() = _L("GetTestCasesL");
+    TRAPD (r, err = iTestModule->GetTestCasesL( 
+                        ModuleContainer().OperationName(),
+                        *iCases ) );
+    ModuleContainer().OperationText() = _L("");
+
+    // Leave
+    if ( r != KErrNone )
+        {
+        __TRACEI ( KError, ( CStifLogger::ERed, _L("GetTestCasesL leave code %d"), r ) );
+        TName tmpBuffer = _L("Leave from test module GetTestCasesL");        
+        ErrorPrint( 1, tmpBuffer );        
+        FreeEnumerationDataInThread();
+
+        ModuleContainer().OperationErrorResult() = r;
+        return r;
+        }
+        
+    // Error originating from test module
+    if ( err != KErrNone )
+        {
+        __TRACEI ( KError, ( CStifLogger::ERed, _L("GetTestCasesL returned error %d"), err ) );
+        FreeEnumerationDataInThread();
+
+        ModuleContainer().ModuleResult() = err;
+        return err;
+        }
+
+    __TRACEI ( KInit, ( _L("GetTestCasesL successfully called") ) );
+
+    // All ok.
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: FreeEnumerationDataInThread
+
+    Description: Frees the enumeration data. This function is called, when
+    the enumeration data is read from execution thread heap to server thread
+    heap. If cases have not been enumerated function does nothing.
+    
+    Function is intented to be called from the context of the test module thread.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::FreeEnumerationDataInThread()
+    {
+
+    __TRACEI ( KInit, ( _L("Freeing test case array") ) );
+
+    if ( iCases )
+        {
+        iCases->ResetAndDestroy();
+        delete iCases;
+        iCases = NULL;
+        }
+    
+    __TRACEI ( KInit, ( _L("Freeing test case array done") ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ExecuteTestCaseInThread
+
+    Description: Execute test case. This function calls either RunTestCase or 
+    ExecuteOOMTestCase to execute and report the results.
+
+    This function is a static member function, which is intented to be called
+    from the context of the test module thread.
+
+    Parameters: None
+
+    Return Values: TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::ExecuteTestCaseInThread()
+    {        
+    TVersion moduleAPIVersion;
+    moduleAPIVersion = iTestModule->Version(); 
+
+    __TRACEI ( KInit, 
+        ( CStifLogger::EBold, _L("Executing test case file=[%S] case=%d"), 
+            &ModuleContainer().OperationName(), 
+            ModuleContainer().OperationIntBuffer() ) );
+
+    TInt r = KErrNone;
+    
+    // Thread handle
+    RThread thisRt;
+    r = DuplicateMutexHandles( thisRt );
+       
+    // Result from RunTestCase       
+    TTestResult caseResult; 
+    
+    // Execution result from RunTestCase
+    TInt err = KErrNone;
+
+    // Fill in initial values
+    TestExecution().FullResult().iCaseExecutionResultType = 
+        TFullTestResult::ECaseExecuted;
+    TestExecution().FullResult().iCaseExecutionResultCode = KErrNone;            
+    TestExecution().FullResult().iStartTime.HomeTime();
+    TestExecution().TestThreadFailure() = CTestExecution::ETestThreadOk;
+
+    // Set handle to test execution
+    TRAP( r, CTestModuleIf::NewL( this,
+                                  iTestModule ) );
+
+    ModuleContainer().OperationText() =_L("RunTestCaseL");
+    
+    // Do resource checks before starting test case
+    iCheckResourceFlags = 0;        
+    
+    TInt tmp;
+    TInt threadHandleCountBeforeTest;
+
+    // Request count check
+    TInt requestCountBeforeTest = thisRt.RequestCount();
+    // Handle count check, not checking process handles
+    thisRt.HandleCount( tmp, threadHandleCountBeforeTest );
+
+    // If handle ok, then execute test          
+    if( r == KErrNone )
+        {       
+        TInt testCaseNumber = ModuleContainer().OperationIntBuffer();
+
+        // Do the test
+        __TRACEI ( KInit, ( _L("About to call RunTestCaseL. If nothing in log \
+            after line \"Calling RunTestCaseL\", check testserver log file.") ) );        
+                    
+        TInt firstMemFailure = 0; 
+        TInt lastMemFailure = 0;        
+        // Store the OOM test type
+        CTestModuleBase::TOOMFailureType failureType;
+                
+        // Check if the current test case is supposed to be run using OOM
+        if( iTestModule->OOMTestQueryL( ModuleContainer().OperationName(), 
+                                        testCaseNumber, 
+                                        failureType,
+                                        firstMemFailure, 
+                                        lastMemFailure ) )
+            {
+            //  Run the test case in OOM conditions      
+            r = ExecuteOOMTestCase( testCaseNumber, 
+                                    firstMemFailure, 
+                                    lastMemFailure, 
+                                    err, 
+                                    caseResult );
+            }
+        else
+            {
+            // Run the test case the old way, without OOM testing           
+            __TRACEI ( KInit, ( _L("Calling RunTestCaseL - \
+                OOM condition is not set") ) );
+            TRAP( r, err = iTestModule->RunTestCaseL( 
+                                            testCaseNumber,
+                                            ModuleContainer().OperationName(),
+                                            caseResult ) );
+            }
+        }        
+     
+    // Do resource checks after test case execution
+    // Handle count check
+    TInt threadHandleCountAfterTest;
+    thisRt.HandleCount( tmp, threadHandleCountAfterTest );
+    // Request count check
+    TInt requestCountAfterTest = thisRt.RequestCount();           
+          
+    ModuleContainer().OperationText() =_L("");
+
+    // Store end time
+    TestExecution().FullResult().iEndTime.HomeTime();   
+    // Remove handle to testexecution 
+    TRAPD( rr, CTestModuleIf::NewL( NULL, iTestModule ) );
+    
+
+    if ( rr != KErrNone )
+        {        
+        __TRACEI ( KError, ( _L("Memory low in executionthread.") ) );        
+        // Do not actually handle error
+        }
+  
+    // Report test result. Parts of this will be overwritten if error
+    // is detected
+    TestExecution().FullResult().iTestResult = caseResult;
+
+    // Get target exit reasons
+    CTestModuleIf::TExitReason allowedExitReason;
+    TInt allowedExitCode = KErrNone;
+    ExitReason( allowedExitReason, allowedExitCode );
+    
+    TBool returnLeakCheckFail = EFalse;
+
+    // Check are STIF macros used
+    if( iTestMacroInfo.iIndication ) 
+        {
+        // STIF macros are used. Set description info, test case to
+        // ECaseExecuted state and case execution result code to KErrNone
+        // to get test case to failed category.
+        TName tmpResultDes;
+        __TRACEI ( KError, ( CStifLogger::ERed, _L("Leave from RunTestCaseL(STIF TF's macro is used)" ) ) );
+        // Set result description
+        tmpResultDes.Copy( _L( "FILE[") );
+        tmpResultDes.Append( iTestMacroInfo.iFileDes );
+        tmpResultDes.Append( _L( "] FUNCTION[" ) );
+        tmpResultDes.Append( iTestMacroInfo.iFunctionDes );
+        tmpResultDes.Append( _L( "] LINE[" ) );
+        tmpResultDes.AppendNum( iTestMacroInfo.iLine );
+        tmpResultDes.Append( _L( "]" ) );
+        // Other result information
+        TestExecution().FullResult().iTestResult.iResult =
+                                            iTestMacroInfo.iReceivedError;
+        TestExecution().FullResult().iTestResult.iResultDes = tmpResultDes;
+        TestExecution().FullResult().iCaseExecutionResultType = 
+                                            TFullTestResult::ECaseExecuted;
+        // Set category to failed cases
+        TestExecution().FullResult().iCaseExecutionResultCode = KErrNone;
+        StifMacroErrorInit(); // Initialization back to default
+        }
+    else if( r != KErrNone )
+        {   // Case has left, overwrite normal result description string
+        __TRACEI ( KError, ( CStifLogger::ERed, _L("Leave from RunTestCaseL, code %d"), r ) );
+        // Set result description
+        TName tmpResultDes = _L("Leave during case:");
+        // Check if there was already some description passed to result object
+        if(caseResult.iResultDes.Length() > 0)
+            {
+            tmpResultDes.Format(_L("Leave during case [%S]:"), &caseResult.iResultDes);
+            if(tmpResultDes.Length() > KStifMaxResultDes)
+                {
+                tmpResultDes.SetLength(KStifMaxResultDes);
+                }
+            }
+        // Other result information
+        TestExecution().FullResult().iTestResult.iResult = KErrGeneral;
+        TestExecution().FullResult().iTestResult.iResultDes = tmpResultDes;
+        TestExecution().FullResult().iCaseExecutionResultType = 
+            TFullTestResult::ECaseLeave;
+        TestExecution().FullResult().iCaseExecutionResultCode = r;
+        }    
+    else if ( err != KErrNone )
+        {   
+        // Case has returned error (e.g. case not found )       
+        __TRACEI ( KError, ( CStifLogger::ERed, _L("RunTestCaseL returned error %d"), err ) ); 
+        TestExecution().FullResult().iCaseExecutionResultType = 
+            TFullTestResult::ECaseErrorFromModule;
+        TestExecution().FullResult().iCaseExecutionResultCode = err;
+        }
+    else if ( allowedExitReason != CTestModuleIf::ENormal )
+        {
+        // Test is failed, because it should end to panic or exception.
+        __TRACEI ( KInit, ( _L("Case ended normally even if it should end to panic/exception") ) ); 
+        TestExecution().FullResult().iTestResult.iResult = KErrGeneral;
+        TestExecution().FullResult().iTestResult.iResultDes = 
+            _L("Case did not ended to panic/exception");
+        }
+    // If test case is passed, check memory leak, handles etc...    
+    else if( caseResult.iResult == KErrNone )
+        {
+        returnLeakCheckFail = ETrue;
+        }
+   
+   // Test case leak checks
+    // In EKA2 heap size cannot be measured because THeapWalk is no longer supported    
+    LeakChecksForTestCase( returnLeakCheckFail, 
+                           threadHandleCountBeforeTest,
+                           threadHandleCountAfterTest,
+                           requestCountBeforeTest,
+                           requestCountAfterTest );
+
+    // Close execution specific handles
+
+    iPrintMutex.Close();
+    iEventMutex.Close();
+    iSndMutex.Close();
+    iRcvMutex.Close();
+    iInterferenceMutex.Close();
+    iMeasurementMutex.Close();
+    iCommandMutex.Close();
+    
+    // The Wait operation is performed to let the message from TestServer 
+    // to TestEngine achieve TestEngine or TestCombiner.   
+    iCommandSem.Wait();
+    
+    // Note: iTestThreadMutex.iClose() mutex will be used later, close in destructor.
+    
+    iPrintSem.Close();
+    iEventSem.Close();
+    iSndSem.Close();
+    iRcvSem.Close();
+    iInterferenceSem.Close();
+    iMeasurementSem.Close();
+    iCommandSem.Close();
+
+    // Close thread handle 
+    thisRt.Close();
+
+    __TRACEI ( KVerbose, ( _L("ExecuteTestCase out") ) );
+
+    // continues from CTestModuleContainer::RunL
+        
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: DuplicateMutexHandles
+
+    Description: Duplicates mutex handles
+
+    Parameters: None
+
+    Return Values: TInt
+
+    Errors/Exceptions: Panic if duplication fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::DuplicateMutexHandles( RThread& aThread )
+    {
+    // For duplicating mutexes
+    iPrintMutex.SetHandle( TestExecution().PrintMutexHandle() );
+    iEventMutex.SetHandle( TestExecution().EventMutexHandle() );
+    iSndMutex.SetHandle( TestExecution().SndMutexHandle() );
+    iRcvMutex.SetHandle( TestExecution().RcvMutexHandle() );
+    iInterferenceMutex.SetHandle( TestExecution().InterferenceMutexHandle() );
+    iMeasurementMutex.SetHandle( TestExecution().MeasurementMutexHandle() );
+    iCommandMutex.SetHandle(TestExecution().CommandMutexHandle());
+
+    // Mutex for testcomplete and cancel operations. For duplicating mutex
+    iTestThreadMutex.SetHandle( TestExecution().TestThreadMutexHandle() );
+
+    // For duplicating semaphores
+    iPrintSem.SetHandle( TestExecution().PrintSemHandle() );
+    iEventSem.SetHandle( TestExecution().EventSemHandle() );
+    iSndSem.SetHandle( TestExecution().SndSemHandle() );
+    iRcvSem.SetHandle( TestExecution().RcvSemHandle() );
+    iInterferenceSem.SetHandle( TestExecution().InterferenceSemHandle() );
+    iMeasurementSem.SetHandle( TestExecution().MeasurementSemHandle() );
+    iCommandSem.SetHandle(TestExecution().CommandSemHandle());
+    
+    // Store thread id for later use
+    TestExecution().SetTestThread( aThread.Id() );
+    
+    // Duplicate handles from server thread
+    TRAPD( r,
+        User::LeaveIfError( iPrintMutex.Duplicate( iServerThread ) );
+        User::LeaveIfError( iEventMutex.Duplicate( iServerThread ) );
+        User::LeaveIfError( iSndMutex.Duplicate( iServerThread ) );
+        User::LeaveIfError( iRcvMutex.Duplicate( iServerThread ) );
+        User::LeaveIfError( iInterferenceMutex.Duplicate( iServerThread ) );
+        User::LeaveIfError( iMeasurementMutex.Duplicate( iServerThread ) );
+        User::LeaveIfError( iCommandMutex.Duplicate( iServerThread ) );
+        
+        User::LeaveIfError( iTestThreadMutex.Duplicate( iServerThread ) );
+
+        User::LeaveIfError( iPrintSem.Duplicate( iServerThread ) );
+        User::LeaveIfError( iEventSem.Duplicate( iServerThread ) );
+        User::LeaveIfError( iSndSem.Duplicate( iServerThread ) );
+        User::LeaveIfError( iRcvSem.Duplicate( iServerThread ) );
+        User::LeaveIfError( iInterferenceSem.Duplicate( iServerThread ) );
+        User::LeaveIfError( iMeasurementSem.Duplicate( iServerThread ) );
+        User::LeaveIfError( iCommandSem.Duplicate( iServerThread ) );
+        );
+
+    // Raise panic if duplications failed        
+    if( r != KErrNone )
+        {
+        Panic( EDuplicateFail );
+        }
+    
+    // Return the result, no error occurred
+    return KErrNone;            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ExecuteOOMTestCase
+
+    Description: Executes OOM test case
+
+    Parameters: None
+
+    Return Values: TInt
+
+    Errors/Exceptions: Panic if EOOMDisableLeakChecks is not set and test case
+    leaks memory.                       
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::ExecuteOOMTestCase( TInt aTestCaseNumber,
+                                               TInt aFirst, 
+                                               TInt aLast, 
+                                               TInt& aResult, 
+                                               TTestResult& caseResult )
+    {
+    TBool OOMwarning = EFalse;  
+    __TRACEI ( KInit, ( _L("CTestThreadContainer::ExecuteOOMTestCase") ) );            
+    __TRACEI ( KInit, ( _L("Executing test case #%d using OOM"), aTestCaseNumber ) );               
+    
+    // OOM test environment initialization
+    TRAPD( r, iTestModule->OOMTestInitializeL( 
+                                ModuleContainer().OperationName(),
+                                aTestCaseNumber ); );               
+    
+    for( TInt i=aFirst; i<aLast; i++ )
+        {   
+        // Fail the i:nth heap allocation
+        User::__DbgSetAllocFail( RHeap::EUser, RHeap::EFailNext, i  );
+        
+        //__TRACEI ( KInit, ( _L("Setting %d:nth heap allocation to fail"), i  ) );             
+                
+        // Intersection of iCheckResourceFlags and 
+        // EDisableMemoryLeakChecksInOOM to check if memory leak checks are to 
+        // be used with OOM testing.        
+        if( !( iCheckResourceFlags & CTestModuleIf::EOOMDisableLeakChecks ) )
+            {
+            User::__DbgMarkStart( RHeap::EUser );
+            }
+            
+        TRAP( r, aResult = iTestModule->RunTestCaseL( 
+                        aTestCaseNumber,
+                        ModuleContainer().OperationName(),
+                        caseResult ) );
+        
+        // Raise panic if test case leaks memory and EOOMDisableLeakChecks is not
+        // set        
+        if( !( iCheckResourceFlags & CTestModuleIf::EOOMDisableLeakChecks ) )
+            {
+            User::__DbgMarkEnd( RHeap::EUser, 0 );
+            }
+        
+        // If no error occurred, fake a memory error to make sure that this is
+        // the last test. If this last allocation goes wrong, it proves that 
+        // either the FAILNEXT() macro has reached its limit or that somewhere
+        // in the code some object TRAPped the OOM exception and did not leave.     
+        if( ( r != KErrNoMemory ) && ( aResult != KErrNoMemory  )
+            && ( caseResult.iResult != KErrNoMemory ) )
+            {
+            TInt* dummy = new TInt;
+            OOMwarning = ( dummy != NULL );
+            delete dummy;
+            }
+
+        // Cancel the simulated heap allocation failure
+        User::__DbgSetAllocFail( RHeap::EUser, RHeap::ENone, 1 );
+    
+        if( ( r != KErrNoMemory ) && !OOMwarning && ( aResult != KErrNoMemory )
+            && ( caseResult.iResult != KErrNoMemory ) )
+            {
+            // If we get here test was executed properly (= no memory error
+            // and no warning)
+            break;
+            }
+
+        if( OOMwarning )
+            {            
+            // It is possible that during testing some components TRAP the OOM
+            // exception and continue to run (do not leave) or they return an 
+            // error other than KErrNoMemory. These situations are making the
+            // OOM testing really difficult, so they should be detected and 
+            // make the tester aware.
+             
+            // Since each test case might have a specific oppinion on handling
+            // this situation, it is left up to the tester to handle it by 
+            // implementing the OOMHandleWarningL method. STIF will log a
+            // warning and call OOMHandleWarningL method.
+
+            // Print the OOM error message
+            __TRACEI ( KInit, ( _L("Possible trapped or non-leaving allocation in test case #%d"), i  ) );                          
+
+            iTestModule->OOMHandleWarningL( ModuleContainer().OperationName(), aTestCaseNumber, i );
+
+            // Clear the warning flag
+            OOMwarning = EFalse;
+            }
+        }
+        
+    // OOM test environment finalization                    
+    __TRACEI ( KInit, ( _L("Calling OOMTestFinalizeL") ) ); 
+    TRAPD( fres, iTestModule->OOMTestFinalizeL( 
+                                    ModuleContainer().OperationName(), 
+                                    aTestCaseNumber ); );
+    // Check the result
+    if( fres != KErrNone )
+        {
+        __TRACEI ( KInit, ( _L("OOMTestFinalizeL execution failed with error %d"), fres ) );                            
+        }
+                
+    return r;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: LeakChecksForTestCase
+
+    Description: Checks test case for memory, handle and request leaks
+
+    Parameters: None    
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::LeakChecksForTestCase( TBool aReturnLeakCheckFail,
+                                                  TInt aThreadHandleCountBeforeTest,
+                                                  TInt aThreadHandleCountAfterTest,
+                                                  TInt aRequestCountBeforeTest, 
+                                                  TInt aRequestCountAfterTest )
+                                                
+    {      
+    __TRACEI ( KInit, ( _L("CTestThreadContainer::LeakChecksForTestCase") ) );                          
+
+    // Note: Request leaks detection is disabled in UI components testing
+    if( !( iCheckResourceFlags & CTestModuleIf::ETestLeaksRequests ) && 
+             ( aRequestCountBeforeTest != aRequestCountAfterTest ) &&
+             ( !iModuleContainer->GetTestModule()->GetTestServer()->UiTesting()))
+        {
+        // Test is failed, because it should end to panic or exception.
+        __TRACEI ( KError, ( CStifLogger::ERed, 
+            _L("Asynchronous request leak from test module. Request count before:[%d] and after:[%d] test."),
+            aRequestCountBeforeTest, aRequestCountAfterTest ) );
+            
+        // Set failure status    
+        TestExecution().TestThreadFailure() |= CTestExecution::ETestRequestLeak;
+        if( aReturnLeakCheckFail )
+            {
+            aReturnLeakCheckFail = EFalse;   // return first fail   
+#ifndef STIF_DISABLE_LEAK_CHECK 
+            // Testcase set to failed when request leak occurred
+            TestExecution().FullResult().iTestResult.iResult = KErrGeneral;
+#endif
+            TestExecution().FullResult().iTestResult.iResultDes = 
+                _L("Asynchronous request leak from testmodule");
+            TestExecution().FullResult().iTestResult.iResultDes.
+                AppendNum( aRequestCountAfterTest );
+            }
+        }
+    // Note: Handle leaks detection is disabled in UI components testing
+    if( !( iCheckResourceFlags & CTestModuleIf::ETestLeaksHandles ) && 
+             ( aThreadHandleCountBeforeTest != aThreadHandleCountAfterTest ) &&
+             ( !iModuleContainer->GetTestModule()->GetTestServer()->UiTesting()) )
+        {
+        // Test is failed, because it should end to panic or exception.
+        __TRACEI ( KError, ( CStifLogger::ERed, 
+            _L("Thread handle leak from test module. Handle count before:[%d] and after:[%d] test."),
+            aThreadHandleCountBeforeTest, aThreadHandleCountAfterTest ) ); 
+            
+        // Set failure status
+        TestExecution().TestThreadFailure() |= CTestExecution::ETestHandleLeak;    
+        if( aReturnLeakCheckFail )
+            {
+            aReturnLeakCheckFail = EFalse;   // return first fail   
+#ifndef STIF_DISABLE_LEAK_CHECK 
+            // Testcase is set to failed yet when handle leak occurred
+            TestExecution().FullResult().iTestResult.iResult = KErrGeneral;
+#endif
+            TestExecution().FullResult().iTestResult.iResultDes = 
+                _L("Thread handle leak from testmodule");
+            TestExecution().FullResult().iTestResult.iResultDes.
+                AppendNum( aRequestCountAfterTest );
+            }
+        }       
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: DeleteTestModule
+
+    Description: Deletes a test module
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::DeleteTestModule()
+    {
+
+    __TRACEI ( KInit, ( _L("Deleting test module instance at 0x%x"), iTestModule ) );
+    // Delete the test module
+    ModuleContainer().OperationText() = _L("DESTRUCTOR");
+    TRAPD( r, delete iTestModule );
+    ModuleContainer().OperationText() = _L("");
+    iTestModule = NULL;
+
+    if ( r )
+        {
+        __TRACEI ( KError, ( _L("Leave when deleting test module, code %d"), r ) );
+        }
+
+    __TRACEI ( KInit, ( _L("Test module instance deleted") ) );
+
+    }
+    
+    /*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: TestCases
+
+    Description: Returns constant pointer to test case array
+
+    Parameters: None
+    
+    Return Values: const RPointerArray<TTestCaseInfo>*  Test cases
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+const RPointerArray<TTestCaseInfo>* CTestThreadContainer::TestCases() const
+    {
+    
+    return iCases;
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ErrorPrint
+
+    Description: Prints error
+
+    Parameters: const TInt aPriority :in: Priority
+                TPtrC aError: in: Error
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::ErrorPrint( const TInt aPriority, 
+                                       TPtrC aError )
+    {
+    
+    // Get access to print stuff
+    iErrorPrintSem.Wait();
+    
+    // Get status variable from server
+    TRequestStatus* status = 
+        ModuleContainer().GetRequest( CTestModuleContainer::ERqErrorPrint );
+    
+    if( status == NULL )
+        {
+        Panic( ENullRequest );
+        return;
+        }
+    
+    // Fill in progress
+    TErrorNotification& progress = ModuleContainer().ErrorNotification();
+    progress.iPriority = aPriority;
+    progress.iText = aError;
+    
+    // Complete action to server
+    iServerThread.RequestComplete( status, KErrNone );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: DoNotifyPrint
+
+    Description: If print notification available, notification is copied to
+                    client memory space and request is completed.
+                 Else new print queue item is created and appended to print 
+                    queue. If queue is full or memory can't be allocated,
+                    then message will be discarded.
+        
+    Parameters: const TInt aPriority  :       :in:  Priority
+                const TStifInfoName& aDes         :in:  Description
+                const TName& aBuffer          :in:  Value
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::DoNotifyPrint( const TInt aPriority,
+                                    const TStifInfoName& aDes,
+                                    const TName& aBuffer )
+    {    
+    // Get access to print stuff
+    iPrintSem.Wait();
+    
+    iPrintMutex.Wait(); // Take mutex to get access to server thread.
+                        // Between Wait and Signal is critical section and this
+                        // verifies that iPrintSem and RequestComplete is done
+                        // successfully.
+    
+    // Get status variable from server
+    TRequestStatus* status = 
+        TestExecution().GetRq( CTestExecution::ERqPrint );
+    
+    if( status == NULL )
+        {
+        iPrintMutex.Signal();
+        Panic( ENullRequest );
+        return;
+        }
+
+    if( *status != KRequestPending )
+        {
+        // CPrintHandler::DoCancel called before getting here, just return
+        iPrintMutex.Signal();
+        return;    
+        }
+    // Fill in progress
+    TTestProgress& progress = TestExecution().TestProgress();
+    progress.iPosition = aPriority;
+    progress.iDescription = aDes;
+    progress.iText = aBuffer;
+    
+    // Complete action to server
+    iServerThread.RequestComplete( status, KErrNone );
+
+    iPrintMutex.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: DoNotifyEvent
+
+    Description: Forward event request.
+        
+    Parameters: const TEventIf: in: Event definition
+                TRequestStatus* aStatus: in: TRequestStatus to complete 
+    
+    Return Values: None
+
+    Errors/Exceptions: Panics if event array can't be created
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::DoNotifyEvent( TEventIf& aEvent, 
+                                          TRequestStatus* aStatus )
+    {
+    
+    TInt ret = KErrNone;
+    
+    // Send event req
+    SetEventReq( TEventDef::EEventCmd, aEvent, aStatus );
+    
+    if( aStatus == NULL )
+        {
+        // Synchronous Event command used ->
+        // Block until completed with ECmdComplete from NotifyEvent
+        // Cannot be done before ERelEvent, 
+        // because Unset may be blocking the server  
+        User::WaitForRequest( iReqStatus ); 
+        
+        User::After( 1 );// workaround found for STIF 347 
+        
+        // Return result from engine 
+        ret = iReqStatus.Int();
+        
+        }    
+    
+    return ret;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: CancelEvent
+
+    Description: Cancels pending event request.
+        
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::CancelEvent( TEventIf& aEvent, 
+                                        TRequestStatus* aStatus )
+    {
+
+    __TRACEI( KMessage, ( _L( "CTestThreadContainer::CancelEvent(%d): %S [%p]" ), 
+            aEvent.Type(), &aEvent.Name(), aStatus ) );
+            
+    // Send event req
+    SetEventReq( TEventDef::EEventCmdCancel, aEvent, aStatus );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: SetExitReason
+
+    Description: Set exit reason
+        
+    Parameters: const TExitReason aExitReason in: Exit reason
+                const TInt aExitCode in: Exit code
+
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::SetExitReason( const CTestModuleIf::TExitReason aExitReason, 
+                                    const TInt aExitCode )
+    {
+    
+    TInt exitCode = aExitCode;
+    
+    if( ( aExitReason == CTestModuleIf::ENormal ) &&
+        ( aExitCode != KErrNone ) )
+        {
+        __TRACEI( KError, 
+            ( _L( "SetExitReason: Exit type normal uses always exit code 0 (given %d is not used)" ), 
+                exitCode ) );
+        exitCode = KErrNone;
+        }
+
+    ModuleContainer().AllowedExitReason() = aExitReason;
+    ModuleContainer().AllowedExitCode() = exitCode;              
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: SetBehavior
+
+    Description: Set test behaviour.
+        
+    Parameters:  const CTestModuleIf::TTestBehavior aType: in: behaviour type 
+                 TAny* aPtr: in: data
+
+    Return Values: Symbian OS error code.
+    
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::SetBehavior( const CTestModuleIf::TTestBehavior aType, 
+                                        TAny* /*aPtr*/ )
+    {
+    
+    if( aType & CTestModuleIf::ETestLeaksMem )
+        {
+        iCheckResourceFlags |= CTestModuleIf::ETestLeaksMem;
+        }
+    if( aType & CTestModuleIf::ETestLeaksRequests )
+        {
+        iCheckResourceFlags |= CTestModuleIf::ETestLeaksRequests;
+        } 
+    if( aType & CTestModuleIf::ETestLeaksHandles )
+        {
+        iCheckResourceFlags |= CTestModuleIf::ETestLeaksHandles;
+        }
+    // For OOM testing
+    if( aType & CTestModuleIf::EOOMDisableLeakChecks )
+        {
+        iCheckResourceFlags |= CTestModuleIf::EOOMDisableLeakChecks;
+        }                
+    if( !( aType & iCheckResourceFlags ) )
+        {
+        return KErrNotFound;
+        }
+        
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ExitReason
+
+    Description: Gets exit reason
+        
+    Parameters: TExitReason& aExitReason out: Exit reason
+                TInt& aExitCode out: Exit code
+
+    Return Values: None
+    
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::ExitReason( CTestModuleIf::TExitReason& aExitReason, 
+                                   TInt& aExitCode )
+    {
+
+    aExitReason = ModuleContainer().AllowedExitReason();
+    aExitCode = ModuleContainer().AllowedExitCode();
+          
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: SetEventReq 
+
+    Description: Sets asynchronous event request.
+        
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::SetEventReq( TEventDef::TEventCmdType aType, 
+                                        TEventIf& aEvent, 
+                                        TRequestStatus* aStatus )
+    {
+    // Get access to event stuff
+    iEventSem.Wait();
+
+    iEventMutex.Wait(); // Take mutex to get access to server thread.
+                        // Between Wait and Signal is critical section and this
+                        // verifies that iPrintSem and RequestComplete is done
+                        // successfully.
+    
+    // Get status variable from server
+    TRequestStatus* status = 
+        TestExecution().GetRq( CTestExecution::ERqEvent );
+    
+    if( status == NULL )
+        {
+        iEventMutex.Signal();
+        Panic( ENullRequest );
+        return;
+        }
+    if( *status != KRequestPending )
+        {
+        // CEventHandler::DoCancel called before getting here, just return
+        iEventMutex.Signal();
+        return;    
+        }
+    
+    // Fill in event on server thread
+    TEventDef& event = TestExecution().EventDef();
+    event.iType = aType;
+    event.iEvent.Copy( aEvent );
+
+    if( aStatus )
+        {
+        // Store TRequestStatus which is completed when next EEnable comes in
+        event.iStatus = aStatus;
+        } 
+    else
+        {
+        iReqStatus = KRequestPending;
+        event.iStatus = &iReqStatus;
+        }   
+
+    __TRACEI( KMessage ,(_L("SetReq Stat %d, %x"), this, 
+        aStatus ));
+    
+    // Complete action to server
+    iServerThread.RequestComplete( status, KErrNone );
+    
+    iEventMutex.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: DoRemoteReceive
+
+    Description: Enable remote receive and send.
+    
+    Parameters: 
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::DoRemoteReceive( TStifCommand aRemoteCommand,
+                                            TParams aParams,
+                                            TInt aLen,
+                                            TRequestStatus& aStatus )
+    {    
+    
+    switch( aRemoteCommand )
+        {
+        case EStifCmdSend:             // "Send"
+        case EStifCmdReboot:           // "Send"
+        case EStifCmdStoreState:       // "Send"
+        case EStifCmdGetStoredState:   // "Receive, this must be done with two phase"
+        case EStifCmdMeasurement:      // "Receive"
+            {
+            __TRACEI( KMessage, ( _L( "CTestThreadContainer::DoRemoteReceive Wait SndSem" ) ) );
+            
+            // Get access to sender 
+            // (for receive, used for securing access to shared memory)
+            iSndSem.Wait();
+
+            iSndMutex.Wait();   // Take mutex to get access to server thread.
+                                // Between Wait and Signal is critical section and this
+                                // verifies that iPrintSem and RequestComplete is done
+                                // successfully.
+
+            // Get status variable from server
+            TRequestStatus* status = 
+                TestExecution().GetRq( CTestExecution::ERqSnd );
+
+            if( status == NULL )
+                {
+                iSndMutex.Signal();
+                Panic( ENullRequest );
+                return;
+                }
+            if( *status != KRequestPending )
+                {
+                // CSndHandler::DoCancel called before getting here, just return
+                iSndMutex.Signal();
+                return;    
+                }                
+
+            // Fill in information
+            TCmdDef& aDef = TestExecution().SndInfo();
+            aDef.iCommand = aRemoteCommand;
+            aDef.iParam = aParams;
+            aDef.iLen = aLen;
+            aDef.iStatus = &aStatus;
+            
+            __TRACEI( KMessage ,
+                (_L("CTestThreadContainer::DoRemoteReceive Complete request 0x%x"),
+                    status ));
+            // Complete action to server
+            iServerThread.RequestComplete( status, KErrNone );  
+
+            iSndMutex.Signal();
+            }
+            break;
+        case EStifCmdReceive:          // "Receive"
+             {
+            __TRACEI( KMessage, ( _L( "CTestThreadContainer::DoRemoteReceive Wait RcvSem" ) ) );
+
+            // Get access to receive handler 
+            iRcvSem.Wait();
+
+            iRcvMutex.Wait();   // Take mutex to get access to server thread.
+                                // Between Wait and Signal is critical section and this
+                                // verifies that iPrintSem and RequestComplete is done
+                                // successfully.
+
+            // Get status variable from server
+            TRequestStatus* status = 
+                TestExecution().GetRq( CTestExecution::ERqRcv );
+
+            if( status == NULL )
+                {
+                iRcvMutex.Signal();
+                Panic( ENullRequest );
+                return;
+                }
+            if( *status != KRequestPending )
+                {
+                // CRcvHandler::DoCancel called before getting here, just return
+                iRcvMutex.Signal();
+                return;    
+                }                
+
+            // Fill in information
+            TCmdDef& aDef = TestExecution().RcvInfo();
+            aDef.iCommand = aRemoteCommand;
+            aDef.iParam = aParams;
+            aDef.iLen = aLen;
+            aDef.iStatus = &aStatus;
+            
+            __TRACEI( KMessage ,
+                (_L("CTestThreadContainer::DoRemoteReceive Complete request 0x%x"),
+                    status ));
+            __TRACEI( KMessage, ( _L( "CTestThreadContainer::DoRemoteReceive signal RcvSem" ) ) );
+            //iReceiverSem.Signal();
+
+            // Complete action to server
+            iServerThread.RequestComplete( status, KErrNone );  
+
+            iRcvMutex.Signal();
+            
+            }
+            break;
+
+        default:
+            TRequestStatus* rs = &aStatus;
+            User::RequestComplete( rs, KErrNotSupported );
+            break;
+        }
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: DoRemoteReceiveCancel
+
+    Description: Cancel DoRemoteReceive
+    
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::DoRemoteReceiveCancel()
+    {   
+           
+    // Get access to receive handler
+    iRcvSem.Wait();
+
+    iRcvMutex.Wait();   // Take mutex to get access to server thread.
+                        // Between Wait and Signal is critical section and this
+                        // verifies that iPrintSem and RequestComplete is done
+                        // successfully. 
+
+    // Get status variable from server
+    TRequestStatus* status = 
+        TestExecution().GetRq( CTestExecution::ERqRcv );
+
+    if( status == NULL )
+        {
+        iRcvMutex.Signal();
+        return KErrNotFound;
+        }
+        
+    if( *status != KRequestPending )
+        {
+        // CRcvHandler::DoCancel called before getting here, just return
+        iRcvMutex.Signal();
+        Panic( ENullRequest );
+        return KErrNone;    
+        }        
+
+    // Fill in information
+    TCmdDef& aDef = TestExecution().RcvInfo();
+    aDef.iCommand = EStifCmdReceiveCancel;
+    // Complete action to server
+    iServerThread.RequestComplete( status, KErrNone );  
+    
+    iRcvMutex.Signal();
+
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: TestComplete
+
+    Description: Complete test operation: Get test case, run test case,
+                 complete test case, etc.
+        
+    Parameters: TInt aCompletionCode: in: completion code.
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::TestComplete( TInt aCompletionCode )
+    {    
+    
+    // Get status variable from server
+    TRequestStatus* status = 
+        ModuleContainer().GetRequest( CTestModuleContainer::ERqTestCase );
+    
+    if( status == NULL )
+        {
+        Panic( ENullRequest );
+        return;
+        }
+        
+    // Complete action to server
+    if( iTestThreadMutex.Handle() == 0 )
+        {
+        // Actual test case is not started yet. Inititialization phase is ongoing.
+        // Before the completion check if the status was not already completed
+        // from other thread in CTestModuleContainer::DoCancel().
+        // For details see Jira STIF-564
+        if(*status == KRequestPending)
+            iServerThread.RequestComplete( status, aCompletionCode );
+        }
+    else
+        {
+        // Test case execution is started. Test is ongoing.
+        // Before the completion check if the status was not already completed
+        // from other thread in CTestModuleContainer::DoCancel().
+        // For details see Jira STIF-564
+        if(*status == KRequestPending)
+            {
+            iTestThreadMutex.Wait(); // Block that complete and cancel do not
+                                     // executed at the same time.
+            iServerThread.RequestComplete( status, aCompletionCode );
+            iTestThreadMutex.Signal();
+            }            
+        }
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: UIExecutionThread
+
+    Description: This is the test module execution thread "main" function".
+    All test module function calls are executed in context of this execution
+    thread.
+
+    When the thread is resumed first time, function goes to wait a semaphore.
+    Operations are initiated by setting operation and signaling the semaphore.
+    If operation is synchronous, then end of operation is signaled by using
+    OperationCompleted -Semaphore. When operation is done, function (and thread)
+    are going to wait OperationSemaphore.
+
+    Function exist either when operation does fatal error, or operation type
+    is "Exit". The thread function exist from it's main loop and the thread
+    will be terminated.
+
+    Parameters: TAny* aParams:                :in:  Pointer to CTestModuleContainer
+    
+    Return Values: TInt                        KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::UIExecutionThread( TAny* aParams )
+	{
+	
+    CTestModuleContainer* moduleContainer = 
+    	(CTestModuleContainer*) aParams;
+    
+    CTestModule* module = moduleContainer->GetTestModule();
+    CTestServer* testServer = module->GetTestServer();
+    CTestThreadContainerRunnerFactory* factory = testServer->GetTestThreadContainerRunnerFactory();    
+    
+    RThread server;
+    // Duplicate handles from server thread
+    TInt ret = server.Open( moduleContainer->ServerThreadId() );
+    if( ret != KErrNone )
+    	{
+    	Panic( EThreadHandleOpenFail );
+    	}
+    RSemaphore OperationStartSemaphore;
+    OperationStartSemaphore.SetHandle( 
+    		moduleContainer->OperationStartSemHandle() );
+    if( OperationStartSemaphore.Duplicate( server ) != KErrNone )
+        {
+        Panic( EDuplicateFail );
+        }        
+    RSemaphore OperationChangeSemaphore;
+    OperationChangeSemaphore.SetHandle( 
+    		moduleContainer->OperationChangeSemHandle() );
+    if( OperationChangeSemaphore.Duplicate( server ) != KErrNone )
+        {
+        Panic( EDuplicateFail );
+        }
+    server.Close();
+    
+    CTestThreadContainerRunner* runner = factory->CreateL();
+    
+    runner->Setup( moduleContainer );
+    
+    while ( runner->IsReusable() )
+        {
+        // Thread is going to suspend        
+        runner->CheckSignalFromSuspend();
+        
+        // Wait next operation
+        OperationStartSemaphore.Wait();
+
+        // Get operation semaphore
+        OperationChangeSemaphore.Wait();    
+    
+        // Run and wait active object
+        runner->RunOneIteration();
+        
+        OperationChangeSemaphore.Signal();        
+        }
+        
+    OperationStartSemaphore.Close();
+    OperationChangeSemaphore.Close();        
+        
+    runner->TeareDown();
+    
+    runner->Deque();
+    
+    factory->DeleteL( runner );    
+    
+    return KErrNone;    
+	}
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ExecutionThread
+
+    Description: This is the test module execution thread "main" function".
+    All test module function calls are executed in context of this execution
+    thread.
+
+    When the thread is resumed first time, function goes to wait a semaphore.
+    Operations are initiated by setting operation and signaling the semaphore.
+    If operation is synchronous, then end of operation is signaled by using
+    OperationCompleted -Semaphore. When operation is done, function (and thread)
+    are going to wait OperationSemaphore.
+
+    Function exist either when operation does fatal error, or operation type
+    is "Exit". The thread function exist from it's main loop and the thread
+    will be terminated.
+
+    Parameters: TAny* aParams:                :in:  Pointer to CTestModuleContainer
+    
+    Return Values: TInt                        KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::ExecutionThread( TAny* aParams )
+    {
+    TInt error( KErrNone );
+    
+    const TUint32 KAll = 0xFFFFFFFF;
+#ifndef __HIDE_IPC_V1__ // e.g. 7.0s, 8.0a
+    RThread currentThread;
+    currentThread.SetExceptionHandler( ExceptionHandler, KAll );
+#else // PlatSec used. Thread exception management is part of the User class.
+    User::SetExceptionHandler( ExceptionHandler, KAll );
+#endif // __HIDE_IPC_V1__
+
+     // Check parameters
+    __ASSERT_ALWAYS( aParams, Panic( EInvalidCTestThreadContainer ) );
+
+    CTestModuleContainer* moduleContainer = 
+        (CTestModuleContainer*) aParams;
+       
+    // Create cleanup stack
+    CTrapCleanup* tc = CTrapCleanup::New();
+    __ASSERT_ALWAYS( tc, Panic( ECreateTrapCleanup ) );
+
+    CTestThreadContainer* exec = NULL;    
+    TRAPD( err,
+        exec = CTestThreadContainer::NewL( moduleContainer, 
+                                           moduleContainer->ServerThreadId() );
+        );    
+    if( err != KErrNone )
+        {
+        Panic( ENullTestThreadContainer );
+        }
+
+    // Construct the logger
+    TName path = _L("C:\\logs\\testframework\\testserver\\");
+    TFileName name = _L("testserver_thread_");  
+    name.Append( moduleContainer->TestModuleName() );
+
+    // Create logger, in Wins use HTML in HW default logger
+    TLoggerSettings loggerSettings;
+
+    // Directory must create by hand if test server log wanted
+    loggerSettings.iCreateLogDirectories = EFalse;
+
+    loggerSettings.iOverwrite = ETrue;
+    loggerSettings.iTimeStamp = ETrue;
+    loggerSettings.iLineBreak = ETrue;
+    loggerSettings.iEventRanking = EFalse;
+    loggerSettings.iThreadId = EFalse;
+    loggerSettings.iHardwareFormat = CStifLogger::ETxt;
+#ifndef FORCE_STIF_INTERNAL_LOGGING_TO_RDEBUG
+    loggerSettings.iEmulatorFormat = CStifLogger::EHtml;
+    loggerSettings.iHardwareOutput = CStifLogger::EFile;
+    loggerSettings.iEmulatorOutput = CStifLogger::EFile;
+#else
+    RDebug::Print( _L( "STIF Test Server's thread logging forced to RDebug" ) );
+    loggerSettings.iEmulatorFormat = CStifLogger::ETxt;
+    loggerSettings.iHardwareOutput = CStifLogger::ERDebug;
+    loggerSettings.iEmulatorOutput = CStifLogger::ERDebug;
+#endif
+    loggerSettings.iUnicode = EFalse;
+    loggerSettings.iAddTestCaseTitle = EFalse;
+
+    TRAP ( error, exec->iThreadLogger = CStifLogger::NewL( path, name,
+                                                            loggerSettings ) );
+
+    RLibrary module;                    // Handle to test module library
+    TBool reusable = ETrue;             // Is test module reusable?
+    TBool initialized = EFalse;         // Is module initialized?
+    TBool signalFromSuspend = EFalse;   // Send signal from suspend state?
+
+    RThread server;
+    // Duplicate handles from server thread
+    TInt ret = server.Open( moduleContainer->ServerThreadId() );
+    if( ret != KErrNone )
+    	{
+    	Panic( EThreadHandleOpenFail );
+    	}
+    RSemaphore OperationStartSemaphore;
+    OperationStartSemaphore.SetHandle( 
+        exec->ModuleContainer().OperationStartSemHandle() );
+    if( OperationStartSemaphore.Duplicate( server ) != KErrNone )
+        {
+        Panic( EDuplicateFail );
+        }        
+    RSemaphore OperationChangeSemaphore;
+    OperationChangeSemaphore.SetHandle( 
+        exec->ModuleContainer().OperationChangeSemHandle() );
+    if( OperationChangeSemaphore.Duplicate( server ) != KErrNone )
+        {
+        Panic( EDuplicateFail );
+        }
+    server.Close();
+   
+    
+    ret = KErrNone;
+
+    // The test module thread will stay in this loop until it either
+    // dies or is exited nicely.
+    while ( reusable )
+        {
+        // Thread is going to suspend
+        
+        if ( signalFromSuspend )
+            {
+            signalFromSuspend = EFalse;
+            exec->TestComplete( ret );
+            }
+        ret = KErrNone;
+        
+        // Wait next operation
+        OperationStartSemaphore.Wait();
+
+        // Get operation semaphore
+        OperationChangeSemaphore.Wait();
+        switch ( moduleContainer->OperationType() )
+            {
+
+            // Test module initialisation
+            case CTestModuleContainer::EInitializeModule:
+                {
+                __ASSERT_ALWAYS ( !initialized,
+                                  Panic( EReInitializingTestModule ) );
+
+                // Initialize module
+                if ( exec->InitializeModuleInThread( module ) == KErrNone )
+                    {
+                    initialized = ETrue;
+                    }
+
+                signalFromSuspend = ETrue;
+                break;
+                }
+
+            // Test case enumeration
+            case CTestModuleContainer::EEnumerateInThread:
+                {
+                __ASSERT_ALWAYS ( initialized,
+                                  Panic( ETestModuleNotInitialized ) );
+                ret = exec->EnumerateInThread();
+
+                signalFromSuspend = ETrue;
+                break;
+                }
+
+            // Free test case enumeration data
+            case CTestModuleContainer::EFreeEnumerationData:
+                {
+                __ASSERT_ALWAYS ( initialized,
+                                  Panic( ETestModuleNotInitialized ) );
+                exec->FreeEnumerationDataInThread ();
+                
+                signalFromSuspend = ETrue;
+                break;
+                }
+
+            // Execute test case
+            case CTestModuleContainer::EExecuteTestInThread:
+                {
+                __ASSERT_ALWAYS ( initialized,
+                                  Panic( ETestModuleNotInitialized ) );
+                ret = exec->ExecuteTestCaseInThread ();
+
+                signalFromSuspend = ETrue;
+                break;
+                }
+
+            // Exiting (i.e test server is unloading)
+            case CTestModuleContainer::EExit:
+                {
+                reusable = EFalse;
+                break;
+                }
+
+            // Illegal state
+            default:
+                {
+                Panic( EInvalidTestModuleOperation );
+                }
+            }
+            OperationChangeSemaphore.Signal();
+        
+        }
+        
+    OperationStartSemaphore.Close();
+    OperationChangeSemaphore.Close();
+
+    exec->DeleteTestModule();
+
+    // Close handle to module. No function calls to test
+    // module are possible after this line.
+    module.Close();
+
+    // Delete logger    
+    delete exec->iThreadLogger;
+    exec->iThreadLogger = NULL;
+
+    // Delete clean-up stack.
+    delete tc;
+    tc = NULL;
+
+    // Operation completed ( = Exit completed )
+    exec->TestComplete( KErrNone );
+    
+    delete exec;
+    
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: Panic
+
+    Description: Panicing function for test thread.
+
+    Parameters: TPanicReason aReason: in: Reason code
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::Panic( TPanicReason aReason )
+    {
+    
+    RDebug::Print( _L("CTestThreadContainer::Panic %d"), aReason );
+    
+    User::Panic( _L("CTestThreadContainer::Panic"), aReason );
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ServerAlive
+
+    Description: Check that server is alive.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: Panics thread if server has died.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::IsServerAlive() const
+    {
+        
+    if( iServerThread.ExitType() != EExitPending ) 
+        {
+        // Server thread has died
+        __RDEBUG( ( _L( "Server died" ) ) );
+        Panic( EServerDied );
+        }
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: TestExecution
+
+    Description: Return CTestExecution handle to "parent" i.e. server.
+
+    Parameters: None
+    
+    Return Values: CTestExecution&
+
+    Errors/Exceptions: Panics thread if server has died.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestExecution& CTestThreadContainer::TestExecution() const
+    { 
+    
+    IsServerAlive();
+    CTestExecution* execution = iModuleContainer->TestExecution();
+    if( execution == NULL )
+        {
+        Panic( ENullExecution );
+        }
+    return *execution;
+    
+    };
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: GetTestCaseArguments
+
+    Description: Get test case arguments
+
+    Parameters: None
+    
+    Return Values: test case arguments
+
+    Errors/Exceptions: 
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestThreadContainer::GetTestCaseArguments() const
+    {
+    return TestExecution().GetTestCaseArguments();
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: TestExecution
+
+    Description: Return CTestExecution handle to "parent" i.e. server.
+
+    Parameters: None
+    
+    Return Values: CTestExecution&
+
+    Errors/Exceptions: Panics thread if server has died.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleContainer& CTestThreadContainer::ModuleContainer()
+    { 
+    
+    IsServerAlive();
+    return *iModuleContainer; 
+    
+    };
+ 
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: ExceptionHandler
+
+    Description: Test execution thread exception handler
+
+    Just kill thread. Undertaker handles rest.
+
+    Parameters: TExcType: in: Exception type
+    
+    Return Values: None
+
+    Errors/Exceptions: This function kills the thread where it is executed in.
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::ExceptionHandler ( TExcType aType )
+    {
+
+    // Kill the current thread, undertaker handles rest
+    RThread current;
+    current.Kill( aType );
+
+    // This line is never executed, because thread has been killed.
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: StifMacroErrorInit
+
+    Description: STIF TF's macro. Initialized TTestMacro.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::StifMacroErrorInit()
+    {
+    iTestMacroInfo.iIndication = EFalse;
+    iTestMacroInfo.iFileDes = KNullDesC;
+    iTestMacroInfo.iFunctionDes = KNullDesC;
+    iTestMacroInfo.iLine = 0;
+    iTestMacroInfo.iReceivedError = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: StifMacroError
+
+    Description: STIF TF's macros. Saves information for later use.
+
+    Parameters: TInt aMacroType: in: Macro type(0:TL, 1:T1L, 2:T2L, etc.)
+                TDesC& aFile: in: Modified file information.
+                TDesC& aFunction: in: Modified function information.
+                TInt aLine: in: Line information.
+                TInt aResult: in: Received result.
+                TInt aExpected1: in: Expected result from user.
+                TInt aExpected2: in: Expected result from user.
+                TInt aExpected3: in: Expected result from user.
+                TInt aExpected4: in: Expected result from user.
+                TInt aExpected5: in: Expected result from user.
+    
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::StifMacroError( TInt aMacroType,
+                                           const TText8* aFile,
+                                           const char* aFunction,
+                                           TInt aLine,
+                                           TInt aResult,
+                                           TInt aExpected1,
+                                           TInt aExpected2,
+                                           TInt aExpected3,
+                                           TInt aExpected4,
+                                           TInt aExpected5 )
+    {
+    TStifMacroDes file;
+    TStifMacroDes function;
+
+    // Modifies aFile and aFunction lengths if nesessarily.
+    // File and function maximun length is KStifMacroMax.
+    SetMacroInformation( KStifMacroMax, KStifMacroMax, 
+                            aFile, aFunction, file, function );
+
+    // Log more information to file and rdebug
+    switch( aMacroType )
+        {
+        case 0: // TL macro
+            {
+            __TRACEI( KError, ( CStifLogger::ERed, 
+                _L( "FAIL: STIF TF's macro. FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                &file, &function, aLine ) );
+            RDebug::Print( 
+                _L( "FAIL: STIF TF's macro. FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                &file, &function, aLine );
+            break;
+            }
+       case 1: // T1L macro
+            {
+           __TRACEI( KError, ( CStifLogger::ERed,
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, &file, &function, aLine ) );
+            RDebug::Print( 
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, &file, &function, aLine );
+            break;
+            }
+       case 2: // T2L macro
+            {
+            __TRACEI( KError, ( CStifLogger::ERed,
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, aExpected2, &file, &function, aLine ) );
+            RDebug::Print( 
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, aExpected2, &file, &function, aLine );
+            break;
+            }
+       case 3: // T3L macro
+            {
+            __TRACEI( KError, ( CStifLogger::ERed,
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, aExpected2, aExpected3, &file, &function, aLine ) );
+            RDebug::Print( 
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, aExpected2, aExpected3, &file, &function, aLine );
+            break;
+            }
+       case 4: // T4L macro
+            {
+            __TRACEI( KError, ( CStifLogger::ERed,
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, aExpected2, aExpected3, aExpected4, &file, &function, aLine ) );
+            RDebug::Print( 
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, aExpected2, aExpected3, aExpected4, &file, &function, aLine );
+            break;
+            }
+       case 5: // T5L macro
+            {
+            __TRACEI( KError, ( CStifLogger::ERed,
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, aExpected2, aExpected3, aExpected4, aExpected5, &file, &function, aLine ) );
+            RDebug::Print( 
+                _L( "FAIL: STIF TF's macro. RECEIVED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], EXPECTED[%d], FILE[%S], FUNCTION[%S], LINE[%d]" ),
+                aResult, aExpected1, aExpected2, aExpected3, aExpected4, aExpected5, &file, &function, aLine );
+            break;
+            }
+        default: // default, faulty handling
+            {
+            __TRACEI( KError, ( CStifLogger::EError,
+                _L( "CTestThreadContainer::StifMacroError(): Macro faulty handling(Macro type is incorrect)" ) ) );
+            RDebug::Print( 
+                _L( "ERROR: CTestThreadContainer::StifMacroError(): Macro faulty handling(Macro type is incorrect)" ) );
+            return KErrArgument; // Test case goes to crashed category
+            }        
+        }
+
+    // Modifies aFile and aFunction lengths if nesessarily.
+    // File maximun length is KStifMacroMaxFile.
+    // Function maximun length is KStifMacroMaxFunction.
+    SetMacroInformation( KStifMacroMaxFile, KStifMacroMaxFunction, 
+                            aFile, aFunction, file, function );
+
+    // Set information for later use(this information is
+    // limited and can be seen in UI)
+    iTestMacroInfo.iIndication = ETrue;
+    iTestMacroInfo.iFileDes = file;
+    iTestMacroInfo.iFunctionDes = function;
+    iTestMacroInfo.iLine = aLine;
+    if( aResult == KErrNone )
+        {
+        // aResult is KErrNone. TL macro is used or expected result(s) are/is
+        // negative value(s). Received error code is mapped to KErrArgument
+        // because this is erronous case.
+        iTestMacroInfo.iReceivedError = KErrArgument;
+        }
+    else
+        {
+        iTestMacroInfo.iReceivedError = aResult;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: SetMacroInformation
+
+    Description: Modifies aRecFile and aRecFunction lengths if nesessarily.
+
+    Parameters: TInt aMaxLength: in: Maximum length of file information.
+                TInt aMaxLength: in: Maximum length of function information.
+                const TText8* aRecFile: in: Received file information.
+                char* aRecFunction: in: Received function information.
+                TDes& aFile: inout: Modified file.
+                TDes& aFunction: inout: Modified function.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::SetMacroInformation( TInt aFileMaxLength,
+                                                TInt aFuntionMaxLength,
+                                                const TText8* aRecFile,
+                                                const char* aRecFunction,
+                                                TDes& aFile,
+                                                TDes& aFunction )
+    {
+    // Create 8 to 16
+    TPtrC8 buf_file;
+    buf_file.Set( aRecFile );
+    // File description length is limited. Extracts the rightmost part of the
+    // data.
+    aFile.Copy( buf_file.Right( aFileMaxLength ) );
+    aFile.LowerCase();
+
+    if( aRecFunction )
+        {
+        // Create 8 to 16
+        TPtrC8 buf_func;
+        buf_func.Set( (const unsigned char*)aRecFunction );
+        // Function description length is limited. Extracts the leftmost part
+        // of the data.
+        aFunction.Copy( buf_func.Left( aFuntionMaxLength ) );
+        aFunction.LowerCase();
+        }
+    else
+        {
+        // Function is not given(WINS)
+        aFunction.Copy( _L( "-" ) );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: AddInterferenceThread
+
+    Description: With this can be store information about test interference
+                 thread to client space.
+
+    Parameters: RThread aSTIFTestInterference: in: Thread information to store
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::AddInterferenceThread( 
+                                RThread aSTIFTestInterference )
+    {
+    // Get access to test interference stuff
+    iInterferenceSem.Wait();
+    
+    iInterferenceMutex.Wait();  // Take mutex to get access to server thread.
+                                // Between Wait and Signal is critical section
+                                // and this verifies that iInterferenceSem and
+                                // RequestComplete is done successfully.
+    
+    // Get status variable from server
+    TRequestStatus* status = 
+        TestExecution().GetRq( CTestExecution::ERqInterference );
+    
+    if( status == NULL )
+        {
+        iInterferenceMutex.Signal();
+        Panic( ENullRequest );
+        return KErrNone;
+        }
+
+    if( *status != KRequestPending )
+        {
+        // CInterferenceHandler::DoCancel called before getting here,
+        // just return
+        iInterferenceMutex.Signal();
+        return KErrNone;    
+        }
+
+    // Add thread to Array. Via array can handle test interference thread's
+    // kill in panic etc. cases
+    TTestInterference& testInterface = TestExecution().TestInterference();
+    testInterface.iThreadId = aSTIFTestInterference.Id();    
+    testInterface.iOperation = TTestInterference::EAppend;
+
+    // Complete action to server
+    iServerThread.RequestComplete( status, KErrNone );
+    // Goes to CInterferenceHandler::RunL()
+
+    iInterferenceMutex.Signal();
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: RemoveInterferenceThread
+
+    Description: With this can be remove information about test interference
+                 thread from client space.
+
+    Parameters:  RThread aSTIFTestInterference: in: Thread information to store
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::RemoveInterferenceThread( 
+                                RThread aSTIFTestInterference )
+    {
+    // Get access to test interference stuff
+    iInterferenceSem.Wait();
+    
+    iInterferenceMutex.Wait();  // Take mutex to get access to server thread.
+                                // Between Wait and Signal is critical section
+                                // and this verifies that iInterferenceSem and
+                                // RequestComplete is done successfully.
+    
+    // Get status variable from server
+    TRequestStatus* status = 
+        TestExecution().GetRq( CTestExecution::ERqInterference );
+    
+    if( status == NULL )
+        {
+        iInterferenceMutex.Signal();
+        Panic( ENullRequest );
+        return KErrNone;
+        }
+
+    if( *status != KRequestPending )
+        {
+        // CInterferenceHandler::DoCancel called before getting here, just return
+        iInterferenceMutex.Signal();
+        return KErrNone;    
+        }
+
+    // Add thread to Array. Via array can handle test interference thread's
+    // kill in panic etc. cases
+    TTestInterference& testInterface = TestExecution().TestInterference();
+    testInterface.iThreadId = aSTIFTestInterference.Id();    
+    testInterface.iOperation = TTestInterference::ERemove;
+
+    // Complete action to server
+    iServerThread.RequestComplete( status, KErrNone );
+    // Goes to CInterferenceHandler::RunL()
+
+    iInterferenceMutex.Signal();
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: HandleMeasurementProcess
+
+    Description: With this can be stored information about test measurement
+                 to TestServer space.
+
+    Parameters: CSTIFTestMeasurement::TMeasurement aSTIFMeasurementInfo: in:
+                Struct for measurement information.
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestThreadContainer::HandleMeasurementProcess( 
+            CSTIFTestMeasurement::TStifMeasurementStruct aSTIFMeasurementInfo )
+    {
+    // Get access to test measurement stuff
+
+    // This is syncronous operation and other request cannot executed at the
+    // same time. In this case iMeasurementSem is not signaled in StarL().
+    // So iMeasurementSem.Wait(); is not needed in this case.
+
+    iMeasurementMutex.Wait();   // Take mutex to get access to server thread.
+                                // Between Wait and Signal is critical section
+                                // and this verifies that iMeasurementSem and
+                                // RequestComplete is done successfully.
+
+    // Get status variable from server
+    TRequestStatus* status = 
+        TestExecution().GetRq( CTestExecution::ERqMeasurement );
+
+    if( status == NULL )
+        {
+        iMeasurementMutex.Signal();
+        Panic( ENullRequest );
+        return KErrNone;
+        }
+
+    if( *status != KRequestPending )
+        {
+        // CMeasurementHandler::DoCancel called before getting here,
+        // just return
+        iMeasurementMutex.Signal();
+        return KErrNone;
+        }
+
+    TTestMeasurement& testmeasurement = TestExecution().TestMeasurement();
+    testmeasurement.iMeasurementStruct = aSTIFMeasurementInfo;
+
+    // Complete action to server
+    iServerThread.RequestComplete( status, KErrNone );
+    // Goes to CMeasurementHandler::RunL()
+
+    // Make this synchronous and block until needed operations are done.
+    iMeasurementSem.Wait();
+    // This continue here when iMeasurementSem.Signal is said in 
+    // CMeasurementHandler::RunL(). So when measurement operations are done.
+
+    // Error code from measurement related operations
+    TInt ret( testmeasurement.iMeasurementStruct.iOperationResult );
+
+    iMeasurementMutex.Signal();
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: SetEventReq
+
+    Description: Sets asynchronous event request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::DoNotifyCommand(TCommand aCommand, const TDesC8& aParamsPckg)
+    {
+    // Get access to command stuff
+    iCommandSem.Wait();
+
+    iCommandMutex.Wait(); // Take mutex to get access to server thread.
+                          // Between Wait and Signal is critical section and this
+                          // verifies that iCommandSem and RequestComplete is done
+                          // successfully.
+
+    // Get status variable from server
+    TRequestStatus* status = TestExecution().GetRq(CTestExecution::ERqCommand);
+
+    if(status == NULL)
+        {
+        iCommandMutex.Signal();
+        Panic(ENullRequest);
+        return;
+        }
+    if(*status != KRequestPending)
+        {
+        iCommandMutex.Signal();
+        return;
+        }
+
+    // Fill in information
+    CCommandDef& aDef = TestExecution().CommandDef();
+    aDef.iCommand = aCommand;
+    aDef.iParamsPckg.Copy(aParamsPckg);
+
+    // Complete action to server
+    iServerThread.RequestComplete(status, KErrNone);
+
+    iCommandMutex.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: GetTestCaseTitleL
+
+    Description: Gets title of currently running test.
+
+    Parameters: aTestCaseTitle: OUT: test case title descriptor
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::GetTestCaseTitleL(TDes& aTestCaseTitle)
+    {
+    ModuleContainer().GetTestCaseTitleL(aTestCaseTitle); 
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: SetThreadLogger
+
+    Description: Sets thread logger.
+
+    Parameters: CStifLogger* aThreadLogger: in: Pointer to thread logger.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainer::SetThreadLogger( CStifLogger* aThreadLogger )
+	{
+	
+	iThreadLogger = aThreadLogger;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: SetThreadLogger
+
+    Description: Gets thread logger.
+
+    Parameters: None
+
+    Return Values: Pointer to CStifLogger. 
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CStifLogger* CTestThreadContainer::GetThreadLogger()
+	{
+	
+	return iThreadLogger;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: UITesting
+
+    Description: Gets information if testserver supports UI testing.
+
+    Parameters: None
+
+    Return Values: True if testserver supports UI testing, False if testserver
+    			   doesn't support UI testing. 
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TBool CTestThreadContainer::UITesting()
+	{
+	
+	return iModuleContainer->GetTestModule()->GetTestServer()->UiTesting();	
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestThreadContainer
+
+    Method: GetUiEnvProxy
+
+    Description: Gets UIEnvProxy.
+
+    Parameters: None
+
+    Return Values: Pointer to UIEnvProxy 
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CUiEnvProxy* CTestThreadContainer::GetUiEnvProxy()
+	{
+	
+	return iModuleContainer->GetTestModule()->GetTestServer()->GetUiEnvProxy();
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/TestModuleContainer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2364 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CTestModuleContainer class member functions. CTestModuleContainer 
+* class contains interface * to execute various functions in context 
+* of test execution thread.
+*
+* CTestModuleContainer is the owner of the test execution thread 
+* object and the owner of the test module instance.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+#include <e32uid.h>
+#include "TestEngineClient.h"
+#include <StifTestModule.h>
+#include <stifinternal/TestServerClient.h>
+#include "TestServer.h"
+#include "TestServerModuleIf.h"
+#include "TestServerCommon.h"
+#include "PrintQueue.h"
+#include "TestThreadContainer.h"
+//--PYTHON-- begin
+#include "StifPython.h"
+//--PYTHON-- end
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES
+
+// The test module execution thread function
+TInt ExecutionThread( TAny* aParams );
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+typedef TInt( *CTestInterfaceFactoryTestModule )( CTestModuleParam*&, TUint32& );
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: NewL
+
+    Description: Returns new CTestModuleContainer instance.
+
+    Parameters: const TDesC& aName: in: Module name
+                CTestModule* aSession: in: "Parent"
+                const TDesC& aConfig: in: Test case (config) file name.
+
+    Return Values: CTestModuleContainer* New instance
+
+    Errors/Exceptions: Function leaves if memory allocation fails or
+                       CTestModuleContainer ConstructL leaves.
+                       Panics if aSession is NULL.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleContainer* CTestModuleContainer::NewL( const TDesC& aName,
+                                                  CTestModule* aSession,
+                                                  const TDesC& aConfig )
+    {
+
+    __ASSERT_ALWAYS ( aSession, 
+                      CTestServer::PanicServer( ENullTestModule ) );
+
+    CTestModuleContainer* self = new ( ELeave ) CTestModuleContainer();
+    CleanupStack::PushL( self );
+    self->ConstructL( aName, aSession, aConfig );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Function creates the execution thread, creates exception
+    handler and the thread undertaker for it and then resumes the thread.
+
+    Parameters: const TDesC& aName: in: Module name
+                CTestModule* aSession: in: "Parent"
+                const TDesC& aConfig: in: Test case (config) file name.
+
+    Return Values: CTestModuleContainer* New instance
+
+    Errors/Exceptions: Function leaves if thread creation fails,
+                       memory allocation fails or undertaker creation leaves.
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::ConstructL( const TDesC& aName,
+                                       CTestModule* aSession,
+                                       const TDesC& aConfig )
+    {
+
+    RDebug::Print( aName );
+    
+    iNestedActiveScheduler = new (ELeave) CActiveSchedulerWait;
+    
+    iCTestModule = aSession;
+
+    // Create error print handler
+    iErrorPrintHandler = CErrorPrintHandler::NewL( *this );
+    User::LeaveIfError( iErrorPrintSem.CreateLocal( 0 ) );
+
+    // Construct unique thread name
+    const TInt KAddressLen = 8;
+    const TInt KMaxName = 50;  // Something smaller than max thread name
+    TInt len = aName.Length();
+    if ( KAddressLen + len > KMaxName )
+        {
+        len = KMaxName - KAddressLen;
+        }
+    
+    // Default heap and stack sizes that may configure by user.
+    TInt heapMinSize( KTestThreadMinHeap );
+    TInt heapMaxSize( KTestThreadMaxHeap );
+    TInt stackSize( KStackSize );
+
+    // Check is user give heap or stack sizes and verify sizes.
+    GetTestModuleParams( aName, aConfig, stackSize, heapMinSize, heapMaxSize );
+
+    // Create a new thread
+    TInt ret = KErrAlreadyExists;
+    for( TInt i = 0; ret == KErrAlreadyExists; i++ )
+        {
+        TName threadName = aName.Left( len );
+        threadName.AppendFormat( _L( "%x" ), ( TUint32 ) this );
+        threadName.AppendFormat( _L( "%x" ), i );
+        //RDebug::Print( threadName );
+
+		RDebug::Print(_L("CTestModuleContainer::ConstructL create thread=[%S] stackSize=(%d)"), &threadName, stackSize);
+
+		if ( iCTestModule->GetTestServer()->UiTesting() == false )
+			{
+	        ret = iThread.Create(
+	                    threadName,                 // name of thread
+	                    CTestThreadContainer::ExecutionThread,// thread function
+	                    stackSize,                  // Stack size
+	                    heapMinSize,                // Heap sizes
+	                    heapMaxSize,
+	                    this                        // Parameter to thread function
+	                    );
+			}
+		else
+			{
+	        ret = iThread.Create(
+                    threadName,                 // name of thread
+                    CTestThreadContainer::UIExecutionThread,// thread function
+                    stackSize,                  // Stack size
+                    heapMinSize,                // Heap sizes
+                    heapMaxSize,
+                    this                        // Parameter to thread function
+                    );
+			}
+
+        // If test execution thread exist try to create new one
+        if( ret == KErrAlreadyExists )
+            {
+            RDebug::Print( _L( "Thread[%S] allready exist, creating new one" ), &threadName );
+            __TRACE ( KInit, ( CStifLogger::ERed, _L( "Thread[%S] allready exist, creating new one" ), &threadName ) );
+            }
+
+        }
+
+    // If thread creation fails, leave here.
+    if( ret != KErrNone )
+        {
+        RDebug::Print( _L( "Execution thread creation fails with: [%d]" ), ret );
+        __TRACE ( KError, ( CStifLogger::ERed, _L( "Execution thread creation fails with: [%d]" ), ret ) );
+        User::Leave( ret );
+        }
+
+    // Doing nothing
+    // ChangeOperationNoError ( ESuspend, 0 );
+    // Thread suspends always first by default
+    
+    // Construct the undertaker to get notifications about the 
+    // thread death. 
+    // This must be trapped to allow to kill just created thread
+    // nicely without a mess in destructor.
+    TRAPD ( r, 
+        iUnderTaker = CUnderTaker::NewL ( this );
+        CActiveScheduler::Add( iUnderTaker );
+        iUnderTaker->StartL();
+        );    
+
+    // Can't create or start the undertaker. Kill the thread. 
+    // Undertaker will be deleted in destructor if needed.
+    if ( r != KErrNone )
+        {
+        iThread.Kill ( r );
+        iThread.Close();
+        User::Leave( r );
+        }
+
+    // Get server thread id ( i.e current thread id )
+    RThread tmpThread;
+    iServerThreadId = tmpThread.Id();
+    
+    // Resume the thread
+    iThread.Resume();                // Start the thread
+    iUpAndRunning = ETrue;           // Thread is created 
+
+    // Add "this" container to active scheduler
+    CActiveScheduler::Add ( this );
+
+    // Start error print handler
+    iErrorPrintHandler->StartL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: CTestModuleContainer
+
+    Description: Constructor.
+
+    Initialise semaphores.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CTestModuleContainer::CTestModuleContainer() :
+    CActive( CActive::EPriorityStandard ),
+    iOperationName ( 0, 0 ),
+    iIsPaused( EFalse )
+    {
+
+    // Create operation start semaphore
+    iOperationStartSemaphore.CreateLocal( 0 );
+
+    // Operation can be changed without first waiting.
+    iOperationChangeSemaphore.CreateLocal( 1 );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ~CTestModuleContainer
+
+    Description: Destructor
+
+    Delete the test execution thread, if it is up and running. Delete
+    undertaker and close handles.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestModuleContainer::~CTestModuleContainer()
+    {
+
+    __TRACE ( KThreadOperation, ( _L( "CTestModuleContainer::~CTestModuleContainer in" ) ) );
+
+    if ( iUpAndRunning )
+        {
+		if( iUnderTaker != NULL )
+			{
+			iUnderTaker->Cancel();
+			}
+
+        // Set the operation
+        ChangeOperationNoError ( EExit, 0 );
+
+        // Do operation
+        StartAndWaitOperation();
+
+        }
+    
+    delete iErrorPrintHandler;
+	iErrorPrintHandler = NULL;
+
+    // Delete heap descriptor
+    delete iModuleNameBuffer;
+    iModuleNameBuffer = NULL;
+
+    // Delete undertaker
+    delete iUnderTaker;
+    iUnderTaker = NULL;
+
+    // Close error semaphore
+    if ( iErrorPrintSem.Handle() != 0 ) iErrorPrintSem.Close();
+
+    // Close the semaphores
+    iOperationStartSemaphore.Close();
+    iOperationChangeSemaphore.Close();
+
+    // Close handle to thread
+    iThread.Close();
+
+    Cancel();
+
+    delete iNestedActiveScheduler;
+    iNestedActiveScheduler = NULL;
+
+    __TRACE ( KThreadOperation, ( _L( "CTestModuleContainer::~CTestModuleContainer out" ) ) );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: StartAndWaitOperation
+
+    Description: Signals operation and waits until operation is completed.
+
+    Function executes active scheduler locally to handle both request
+    completion from execution thread and thread undertaker operations.    
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::StartAndWaitOperation()
+    {
+
+    // Change undertaker mode to synchronous    
+    iUnderTaker->SetSynchronousMode( ETrue );
+
+    iStatus = KRequestPending;
+    // Get ready to handle operation completion
+    SetActive();
+
+    // Start operation
+    iOperationStartSemaphore.Signal();
+
+    // Start "nested" active scheduler "locally"
+    //CActiveScheduler::Start();
+    iNestedActiveScheduler->Start();
+
+    // Request completed or operation crashed, everything 
+    // is done in ModuleContainer's RunL function or in UnderTaker's RunL.
+
+    // Cancel the original request in case than it was the undertaker
+    // that stopped the active scheduler. Does not do anything if original
+    // request is already finished.
+    Cancel();
+    
+    // Undertaker back to "normal" mode
+    iUnderTaker->SetSynchronousMode ( EFalse );
+
+    return iModuleResult;
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: Initialise
+
+    Description: Initialise the test module
+
+    Initialisation is done in context of test execution thread.
+
+    Parameters: const TDesC& aName            :in:  Module name
+                TBool aFirstTime              :in:  First init?
+
+
+    Return Values: TInt                             Result from init
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::Initialize( const TFileName& aName,
+                                       TBool aFirstTime
+                                     )
+    {
+
+    __TRACE ( KInit, ( _L( "Initializing test module" ) ) );
+
+    // Set the operation
+    iErrorResult = ChangeOperation ( EInitializeModule, aName, aFirstTime );
+    iModuleResult = KErrNone;
+    
+    if ( iErrorResult == KErrNone )
+        {
+        // Wait until operation is completed
+        StartAndWaitOperation();
+        }
+    
+    if ( iErrorResult )
+        {
+        __TRACE ( KError, ( CStifLogger::ERed,  _L( "Initializing test module failed %d" ), iErrorResult ) );
+        }
+    else if ( iModuleResult )
+        {
+        __TRACE ( KError, ( CStifLogger::ERed, _L( "Initializing test module failed code from module = %d" ), iModuleResult ) );
+        } 
+    else
+        {
+        __TRACE ( KInit, ( CStifLogger::EBold, _L( "Test module initialization done" ) ) );
+        }
+
+    // Return result
+    return iModuleResult;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: EnumerateTestCases
+
+    Description: Enumerate test cases of the test module
+
+    Enumeration is done in context of test execution thread.
+
+    Parameters: const TDesC& aName            :in:  Configuration file
+
+    Return Values: TInt                             Result from enumeration
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::EnumerateTestCases( const TFileName& aName )
+    {
+
+    __TRACE ( KInit, ( CStifLogger::EBold, _L( "Enumerating test cases from [%S] (might be empty)" ), &aName ) );
+
+    // Set the operation
+    iErrorResult = ChangeOperation( EEnumerateInThread, aName, 0 );
+    iModuleResult = KErrNone;
+
+    if ( iErrorResult == KErrNone )
+        {
+        // Wait until operation is completed
+        StartAndWaitOperation();
+        }
+
+    if ( iErrorResult )
+        {
+        __TRACE ( KError, ( CStifLogger::ERed, _L( "Enumerating test cases failed %d" ), iErrorResult ) );
+        }
+    else if ( iModuleResult )
+        {
+        __TRACE ( KError, ( CStifLogger::ERed, _L( "Enumerating test cases failed, code from module = %d" ), iModuleResult ) );
+        } 
+    else
+        {
+        __TRACE ( KInit, ( _L( "Enumerating test cases done" ) ) );
+        }
+
+    // Return result
+    return iModuleResult;
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: FreeEnumerationData
+
+    Description: Frees the enumeration data
+
+    Memory deallocation is done in context of test execution thread.
+
+    Parameters: None
+
+    Return Values: TInt                             Result from operation
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+TInt CTestModuleContainer::FreeEnumerationData()
+    {
+
+    // Set the operation
+    ChangeOperationNoError( EFreeEnumerationData, 0 );
+    
+    // Do the operation
+    StartAndWaitOperation();
+
+    // Return result
+    return iModuleResult;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: RunTestCase
+
+    Description: Run a test case
+
+    Running a test case is done in context of test execution thread. This
+    function is asynchronous ( i.e test is not finished when this function
+    returns ).
+
+    Parameters: const TFileName& aName        :in:  Configuration file
+                TInt aCaseNumber              :in:  Case number
+                const RMessage                :in:  Handle to test msg.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::RunTestCase ( const TFileName& aName,
+                                         const TInt aCaseNumber,
+                                         const RMessage2& aMessage
+                                       )
+    {
+
+    __TRACE ( KInit, ( CStifLogger::EBold, _L( "Running test case [%S], case [%d]" ), &aName, aCaseNumber ) );
+
+    // Set the operation    
+    iErrorResult = ChangeOperation( EExecuteTestInThread, aName, aCaseNumber );
+
+    if ( iErrorResult != KErrNone )
+        {
+        aMessage.Complete ( iErrorResult );
+        return;
+        }    
+
+    // Set data
+    iMessage = aMessage;
+
+    iStatus = KRequestPending;
+    // Get ready to handle operation completion
+    SetActive();
+
+    // Do operation
+    iOperationStartSemaphore.Signal();    
+
+    // This is asynchronous operation, 
+    // do not wait until completed.    
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: SetExecutionSubSession
+
+    Description: Set execution subsession
+
+    Sets module container test execution subsession. Execution subsession
+    is changed when a module container is reused to run another 
+    test case.
+
+    Parameters: CTestExecution* aExecution    :in:  Subsession pointer
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::SetExecutionSubSession( CTestExecution* aExecution )
+    {
+
+    iCTestExecution = aExecution;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: PauseThread
+
+    Description: Pauses the thread
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::PauseThread()
+    {
+    
+    if( iThread.ExitType() != EExitPending )
+        {
+        // Thread is not alive anymore
+        return KErrDied;
+        }
+
+    if(iCTestExecution != NULL)
+    	{
+		RMutex printMutex;
+		printMutex.SetHandle( iCTestExecution->PrintMutexHandle() );
+		RMutex eventMutex;
+		eventMutex.SetHandle( iCTestExecution->EventMutexHandle() );
+		RMutex sndMutex;
+		sndMutex.SetHandle( iCTestExecution->SndMutexHandle() );
+		RMutex rcvMutex;
+		rcvMutex.SetHandle( iCTestExecution->RcvMutexHandle() );
+		
+		printMutex.Wait(); // wait that print operation is done
+		eventMutex.Wait(); // wait that event operation is done        
+		sndMutex.Wait(); // wait that and operation is done
+		rcvMutex.Wait(); // wait that event operation is done        
+			
+		iThread.Suspend();
+		
+		printMutex.Signal();
+		eventMutex.Signal();
+		sndMutex.Signal();
+		rcvMutex.Signal();
+    	}
+    else
+		{
+		__TRACE( KError,( _L( "STIF internal error - iCTestExecution is NULL in CTestModuleContainer::PauseThread" ) ) );
+		User::Panic(_L("NULL pointer exception"), KErrGeneral);
+		}
+    
+    iIsPaused = ETrue;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ResumeThread
+
+    Description: Resumes the thread
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::ResumeThread()
+    {
+
+    if( iThread.ExitType() != EExitPending )
+        {
+        // Thread is not alive anymore
+        return KErrDied;
+        }
+    
+    iThread.Resume();
+
+    // Pause() - Resume() operations done successfully. 
+    iIsPaused = EFalse;
+
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: KillThread
+
+    Description: Kills the thread
+
+    Parameters: const TInt aCode              :in:   Kill code
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::KillThread( const TInt aCode )
+    {
+
+    iUpAndRunning = EFalse;
+    iUnderTaker->Cancel();
+    
+    if(iCTestExecution != NULL)
+    	{
+		RMutex printMutex;
+		printMutex.SetHandle( iCTestExecution->PrintMutexHandle() );
+		RMutex eventMutex;
+		eventMutex.SetHandle( iCTestExecution->EventMutexHandle() );
+		RMutex sndMutex;
+		sndMutex.SetHandle( iCTestExecution->SndMutexHandle() );
+		RMutex rcvMutex;
+		rcvMutex.SetHandle( iCTestExecution->RcvMutexHandle() );
+		
+		printMutex.Wait(); // wait that print operation is done
+		eventMutex.Wait(); // wait that event operation is done        
+		sndMutex.Wait(); // wait that snd operation is done
+		rcvMutex.Wait(); // wait that event operation is done        
+			
+		iThread.Kill ( aCode );
+		
+		printMutex.Signal();
+		eventMutex.Signal();
+		sndMutex.Signal();
+		rcvMutex.Signal();
+    	}
+    else
+		{
+		__TRACE( KError,( _L( "STIF internal error - iCTestExecution is NULL in CTestModuleContainer::KillThread" ) ) );
+		User::Panic(_L("NULL pointer exception"), KErrGeneral);
+		}
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ChangeOperation
+
+    Description: Multithread safe way to change operation
+
+    Parameters: const TOperation aOperation   :in:  Operation type
+                const TFileName* aNameBuffer  :in:  Filename ( or NULL )
+                const TInt aInt               :in:  Operation specific int
+    
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::ChangeOperation( const TOperation aOperation,
+                                            const TFileName& aNameBuffer,
+                                            const TInt aInt )
+    {
+
+    TInt ret = KErrNone;
+
+    iOperationChangeSemaphore.Wait();
+
+    iErrorResult  = KErrNone;
+    iModuleResult = KErrNone;
+
+    TFileName newNameBuffer;
+    // Check is TestScripter
+    TInt check = CheckModuleName( aNameBuffer, newNameBuffer );
+    delete iModuleNameBuffer;
+	iModuleNameBuffer = NULL;
+    if( check == KErrNone )
+        {
+        // Construct heap buffer for configuration file
+        TRAP( ret, iModuleNameBuffer = HBufC::NewL( newNameBuffer.Length() ) );
+
+        if( ret == KErrNone )
+            {
+            iOperationName.Set ( iModuleNameBuffer->Des() );
+            iOperationName.Copy ( newNameBuffer );
+        
+            iOperationIntBuffer = aInt;
+            iOperationType = aOperation;
+            }
+        else
+            {
+            __TRACE ( KError, ( CStifLogger::ERed, _L( "CTestModuleContainer::ChangeOperation NoMemory" ) ) );
+            }   
+        }
+    else
+        {
+        // Construct heap buffer for configuration file
+        TRAP( ret, iModuleNameBuffer = HBufC::NewL( aNameBuffer.Length() ) );
+
+        if( ret == KErrNone )
+            {
+            iOperationName.Set ( iModuleNameBuffer->Des() );
+            iOperationName.Copy ( aNameBuffer );
+        
+            iOperationIntBuffer = aInt;
+            iOperationType = aOperation;
+            }
+        else
+            {
+            __TRACE ( KError, ( CStifLogger::ERed, _L( "CTestModuleContainer::ChangeOperation NoMemory" ) ) );
+            }
+        }
+
+    iOperationChangeSemaphore.Signal();
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ChangeOperationNoError
+
+    Description: Multithread safe way to change operation. This version
+    of function can't fail.
+
+    Parameters: const TOperation aOperation   :in:  Operation type
+                const TInt aInt               :in:  Operation specific int
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::ChangeOperationNoError( const TOperation aOperation,
+                                                   const TInt aInt
+                                                 )
+    {
+
+    iOperationChangeSemaphore.Wait();
+
+    iErrorResult  = KErrNone;
+    iModuleResult = KErrNone;
+    iOperationIntBuffer = aInt;
+    iOperationType = aOperation;
+    
+    iOperationChangeSemaphore.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: Operation
+
+    Description: Multithread safe way to obtain current operation.
+
+    Parameters: None
+
+    Return Values: TBool                            Operation
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+//@spe const CTestModuleContainer::TOperation CTestModuleContainer::Operation()
+CTestModuleContainer::TOperation CTestModuleContainer::Operation()
+    {
+    TOperation operation;
+    iOperationChangeSemaphore.Wait();
+    operation = iOperationType;
+    iOperationChangeSemaphore.Signal();
+
+    return operation;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ModuleResult
+
+    Description: Returns error code from test module
+
+    Parameters: None
+
+    Return Values: TInt                             Result code from module
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt& CTestModuleContainer::ModuleResult()
+    {
+
+    return iModuleResult;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: OperationErrorResult
+
+    Description: Returns error code from test module
+
+    Parameters: None
+
+    Return Values: TInt                             Result code from module
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt& CTestModuleContainer::OperationErrorResult()
+    {
+
+    return iModuleResult;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: TestModuleName
+
+    Description: Returns test module name.
+
+    Parameters: None
+
+    Return Values: const TDesC&: test module name
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestModuleContainer::TestModuleName()
+    {
+    
+    return iCTestModule->Name();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: TestModuleName
+
+    Description: Returns test module name.
+
+    Parameters: None
+
+    Return Values: const TDesC&: test module name
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestModuleContainer::TestModuleIniFile()
+    {
+    
+    return iCTestModule->IniName();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ModuleResult
+
+    Description: Returns constant pointer to test case array
+
+    Parameters: None
+    
+    Return Values: const RPointerArray<TTestCaseInfo>*  Test cases
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+const RPointerArray<TTestCaseInfo>* CTestModuleContainer::TestCases() const
+    {
+    
+    if( !iUpAndRunning )
+        {
+        return NULL;
+        }
+        
+    if( iThreadContainer == NULL )
+        {
+        CTestServer::PanicServer( ENullTestThreadContainer );
+        }
+    return iThreadContainer->TestCases();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: Complete
+
+    Description: Completes operation from any thread
+
+    Parameters: const TInt aCompletionCode :in:     Completion code
+    
+    Return Values: None
+
+    Errors/Exceptions: Function panics if server's thread can't be opened.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::Complete( const TInt aCompletionCode )
+    {
+
+    TRequestStatus* req = &iStatus;
+    User::RequestComplete( req, aCompletionCode );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: DoErrorPrint
+
+    Description: Handle error prints.
+        
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::DoErrorPrint()
+    {    
+    
+    iCTestModule->ErrorPrint( iErrorPrint.iPriority, iErrorPrint.iText );
+    
+    }
+ 
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: KillTestinterferenceThread
+
+    Description: Make sure that any of the test interference thread's won't
+                 stay to run if test case is crashed of test interference
+                 object is not deleted.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::KillTestinterferenceThread()
+    {
+    if (iCTestExecution != NULL)
+    	{
+    	iCTestExecution->KillTestinterferenceThread();
+    	}
+    else
+    	{
+    	__TRACE( KError,( _L( "STIF internal error - iCTestExecution is NULL in CTestModuleContainer::KillTestinterferenceThread" ) ) );
+    	User::Panic(_L("NULL pointer exception"), KErrGeneral);
+    	}
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: KillTestMeasurement
+
+    Description: Make sure that any of the test measurement process's won't
+                 stay to run if test case is crashed of test measurement object
+                 is not deleted.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::KillTestMeasurement()
+    {    
+    if (iCTestExecution != NULL)
+    	{
+    	iCTestExecution->KillTestMeasurement();
+    	}
+    else
+    	{
+    	__TRACE( KError,( _L( "STIF internal error - iCTestExecution is NULL in CTestModuleContainer::KillTestMeasurement" ) ) );
+    	User::Panic(_L("NULL pointer exception"), KErrGeneral);
+    	}
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: GetRequest
+
+    Description: Return status flags.
+        
+    Parameters: TRequestType aType: in: request type
+    
+    Return Values: TRequestStatus*: pointer to TRequestStatus
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TRequestStatus* CTestModuleContainer::GetRequest( TRequestType aType )
+    { 
+    
+    TRequestStatus* status = NULL;
+    
+    switch( aType )
+        {
+        case ERqTestCase:
+            status = &iStatus;
+            break;
+        case ERqErrorPrint:
+            status = &iErrorPrintHandler->iStatus;
+            break;
+        default: 
+            break;
+        }
+    
+    return status;
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: RunL
+
+    Description: Stops active scheduler when operation in another thread
+                 is completed.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::RunL()
+    {
+    
+    if( iOperationType == CTestModuleContainer::EExecuteTestInThread )
+        {
+        // Make sure that any of the test interference thread's won't stay
+        // to run.
+        KillTestinterferenceThread();
+
+        // Make sure that any of the test measurement process's won't stay
+        // to run.
+        KillTestMeasurement();
+
+        if(iCTestExecution == NULL)
+        	{
+        	__TRACE( KError,( _L( "STIF internal error - iCTestExecution is NULL in CTestModuleContainer::RunL" ) ) );
+        	User::Leave(KErrGeneral);
+        	}
+        else
+        	{
+			// Set the thread state
+			iCTestExecution->SetThreadState( CTestExecution::EFinished );
+	
+			 // If test print queue is empty, then complete request with KEof. If Queue
+			// is not empty, then do not complete. Queue will be emptied by UI.   
+			iCTestExecution->CompletePrintRequestIfQueueEmpty();
+	
+			// Event queue clean-up
+			iCTestExecution->CleanupEvents();
+			
+			// Complete the test request
+			iCTestExecution->CompleteTestExecution( iStatus.Int() );
+			
+			// Test case execution OK and test module thread's pause operation
+			// is not ongoing. Re-use old test module execution thread
+			if( iCTestExecution->TestThreadFailure() == CTestExecution::ETestThreadOk && !iIsPaused )
+				{
+				// Return this module to pool
+				__TRACE( KInit, ( _L("Freeing test module container at 0x%x"),  
+					(TUint32) this ) );
+				iCTestModule->FreeTestModule( this );
+				}
+			// Problems in test case execution. Delete this test module thread and
+			// start next test case in new test module thread.
+			else
+				{
+				if( iIsPaused )
+					{
+					// Test case is paused by user and this RunL is executed also.
+					// This RunL will make Resume() operation to fail because test
+					// case is finished. Next test case cannot complete and that is
+					// why next test case will start at the "clean table".
+					__TRACE( KInit, ( _L( "Delete test module container at 0x%x because test module thread is paused while test case is finished(Cannot Resume())" ), (TUint32) this ) );  
+					}
+				else
+					{
+					// delete test module thread if some thread problem has occurred 
+					__TRACE( KInit, ( _L("Delete test module container at 0x%x because of thread leak (0x%x)"),  
+						(TUint32) this,  iCTestExecution->TestThreadFailure() ) );
+					}
+				delete this;            
+				}
+        	}
+        }
+    else
+        {
+        // Synchronous operation is completed, stop "nested" active scheduler.
+        //CActiveScheduler::Stop();
+        iNestedActiveScheduler->AsyncStop();
+        // Execution continues from CTestModuleContainer::WaitOperation().
+        }
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: DoCancel
+
+    Description: Cancel asyncronous request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::DoCancel()
+    {
+
+    if ( iUpAndRunning == EFalse )
+        {
+        
+        // Before the completion check if the status was not already completed
+        // from other thread in CTestThreadContainer::TestComplete().
+        // For details see Jira STIF-564
+        if(iStatus == KRequestPending)
+            Complete ( KErrCancel ); 
+
+        }
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: RunError
+
+    Description: Handle errors. 
+
+    Because RunL does not leave, one should never come here. Just forward
+    error code and let framework panic the server in case of error.
+
+    Parameters: TInt aError:                  :in:  Error code
+
+    Return Values:  TInt                            Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::RunError( TInt aError )
+    {
+
+    __TRACE( KError,( _L( "CTestModuleContainer::RunError %d" ), aError ) );
+
+    return aError;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ReadParametersFromScriptFileL
+
+    Description: Read test class parameters from script file if parameter(s)
+                 are/is set(TestScripter and TestCombiner).
+
+    Parameters: const TDesC& aConfig: in: Test case (config) file name.
+                TUint32& aStackSize: inout: Stack size.
+                TUint32& aHeapMinSize: inout: Heap's minimum size.
+                TUint32& aHeapMaxSize: inout: Heap's maximum size.
+
+    Return Values: Symbian error code.
+
+    Errors/Exceptions: Leaves if User::LeaveIfError() leaves
+                       Leaves if User::LeaveIfNull() leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::ReadParametersFromScriptFileL( 
+                                                const TDesC& aConfig,
+                                                TInt& aStackSize,
+                                                TInt& aHeapMinSize,
+                                                TInt& aHeapMaxSize )
+    {
+    // __UHEAP_MARK;
+
+    RFs fileServer;
+    RFile file;
+    TInt ret( KErrNone );
+
+    User::LeaveIfError( fileServer.Connect() );
+    CleanupClosePushL( fileServer );
+    
+    __TRACE( KInit, ( _L( "ReadParametersFromScriptFile(): Open configfile [%S]" ), &aConfig ) );
+
+    TParse parse;
+    parse.Set( aConfig, NULL, NULL );
+
+    User::LeaveIfError( fileServer.SetSessionPath( parse.DriveAndPath() ) );
+
+    User::LeaveIfError( file.Open( fileServer, aConfig, EFileRead | EFileShareAny ) );
+    CleanupClosePushL( file );
+
+    TInt size( 0 );
+    User::LeaveIfError( file.Size( size ) );
+
+    const TInt tmpSize = KMaxName; // 128
+    TInt offset( 0 ); // Offset value to parts reading
+
+    // Indications for tags
+    TBool start_tag_found( EFalse );
+    TBool end_tag_found( EFalse );
+    // Offset values for start and end position parsing
+    TInt offset_start( 0 );
+    TInt offset_end( 0 );
+
+    /* Search is combined to section that include tags. After this create new
+    combined section that include second buffer data and new buffer data.
+    Section:     1) 1+2
+                 2) 2+1
+                 2) 1+2 etc. This should ensure that all data is search.
+    */
+
+    // Construct modifiable heap-based descriptor. tmp1 to CleanupStack
+    // This for first data buffer
+    HBufC8* tmp1 = HBufC8::NewLC( tmpSize );            // 128
+    TPtr8 buf1 = tmp1->Des();
+
+    // Construct modifiable heap-based descriptor. tmp2 to CleanupStack
+    // This for second data buffer
+    HBufC8* tmp2 = HBufC8::NewLC( tmpSize );            // 128
+    TPtr8 buf2 = tmp2->Des();
+
+    // Construct modifiable heap-based descriptor. tmp3 to CleanupStack
+    // This includes both first and second data buffers
+    HBufC* tmp3 = HBufC::NewLC( tmpSize + tmpSize );    // 256
+    TPtr currentSection = tmp3->Des();
+
+    // Construct modifiable heap-based descriptor. tmp4 to CleanupStack
+    // This is for changing 8 bit to 16 bit
+    HBufC* tmp4 = HBufC::NewLC( tmpSize );              // 128
+    TPtr to16bit = tmp4->Des();
+
+    ret = KErrNone;
+
+    // Read data to buffer 1
+    // tmp4, tmp3, tmp2 and tmp1 are in CleanupStack => Leave OK
+    // CleanupClosePushL is used to fileServer and file => Leave OK
+    User::LeaveIfError( file.Read( offset, buf1, tmpSize ) );
+
+    // For next buffer reading
+    offset += tmpSize;
+
+    // Read data to buffer 2
+    // tmp4, tmp3, tmp2 and tmp1 are in CleanupStack => Leave OK
+    // CleanupClosePushL is used to fileServer and file => Leave OK
+    User::LeaveIfError( file.Read( offset, buf2, tmpSize ) );
+
+    // 8 bit to 16. Create first combined buffer 1 and buffer 2 that
+    // is used for searching.
+    to16bit.Copy( buf1 );
+    currentSection.Copy( to16bit );
+    to16bit.Copy( buf2 );
+    currentSection.Append( to16bit );
+
+    // Check if small files to be parsed(e.g. settings + one short case).
+    TInt bigsize( 0 );
+    // Check if parsed section is smaller than 256
+    if( size <  ( tmpSize + tmpSize ) )
+        {
+        bigsize = size;
+        }
+    else
+        {
+        bigsize = tmpSize + tmpSize;    // 256
+        }
+
+    do
+        {
+        // Start the next buffer reading
+        offset += tmpSize;
+
+        // Search the start tag
+        ret = currentSection.Find( KStifSettingsStartTag );
+        if( ret != KErrNotFound )
+            {
+            // Succesfully search, take the start offset
+            ret = file.Seek( ESeekCurrent, offset_start );
+            if( ret == KErrNone )
+                {
+                start_tag_found = ETrue;
+                // Current section is end so offset to beging of the 
+                // combined section.
+                offset_start = ( offset_start - ( bigsize ) );
+                }
+            }
+        // Search the end tag
+        ret = currentSection.Find( KStifSettingsEndTag );
+        if( ret != KErrNotFound )
+            {
+            // Succesfully search, take the end offset
+            ret = file.Seek( ESeekCurrent, offset_end );
+            if( ret == KErrNone )
+                {
+                end_tag_found = ETrue;
+                }
+            }
+
+        // Both start and end tags are founded, start parsing sizes.
+        if( start_tag_found && end_tag_found )
+            {
+            TInt length = ( offset_end - offset_start );
+
+            // Construct modifiable heap-based descriptor.
+            // setting_buf to CleanupStack
+            HBufC8* setting_buf = HBufC8::NewLC( length );// 8 bit for reading
+            TPtr8 setting8 = setting_buf->Des();
+
+            // Construct modifiable heap-based descriptor.
+            // setting_buf2 to CleanupStack
+            HBufC* setting_buf2 = HBufC::NewLC( length );// 16 bit for parsing
+            TPtr setting16 = setting_buf2->Des();
+
+            // Read data from the founded STIF settings sections
+            ret = KErrNone;
+            // HBufCs are in CleanupStack => Leave OK
+            // CleanupClosePushL is used to fileServer and file => Leave OK
+            User::LeaveIfError( file.Read( offset_start, setting8, length ) );
+
+            // Section 8 bit to 16.
+            setting16.Copy( setting8 );
+
+            // Start create parser for parsing heap and stack sizes.
+            // NOTE: Comments are parsed away from the section.
+            CStifParser* parser = NULL;
+            User::LeaveIfNull( parser = CStifParser::NewL( setting16,
+                                        CStifParser::ECStyleComments  ) );
+            CleanupStack::PushL(parser);
+
+            CStifSectionParser* section = NULL;
+            User::LeaveIfNull( section = parser->SectionL( KStifSettingsStartTag,
+                                                   KStifSettingsEndTag ) );
+            CleanupStack::PushL(section);
+            TInt lineRet( KErrNone );
+            TInt integer( 0 );
+
+            // Try to get stack size
+            CStifItemParser* itemLine = NULL;
+            TRAPD( parse_ret, itemLine = section->GetItemLineL(
+                                                        KUserDefStackSize ) );
+            if ( parse_ret == KErrNone && itemLine != NULL )
+                {
+                lineRet = itemLine->GetInt( KUserDefStackSize, integer );
+                if ( lineRet == KErrNone )
+                    {
+                    aStackSize = integer;
+                    }
+                }
+            delete itemLine;
+            itemLine = NULL;
+
+            // Try to get minimum heap size
+            TRAP( parse_ret, itemLine = section->GetItemLineL(
+                                                        KUserDefMinHeap ) );
+            if ( parse_ret == KErrNone && itemLine != NULL )
+                {
+                lineRet = itemLine->GetInt( KUserDefMinHeap, integer );
+                if ( lineRet == KErrNone )
+                    {
+                    aHeapMinSize = integer;
+                    }
+                }
+            delete itemLine;
+            itemLine = NULL;
+
+            // Try to get maximum heap size
+            TRAP( parse_ret, itemLine = section->GetItemLineL(
+                                                        KUserDefMaxHeap ) );
+            if ( parse_ret == KErrNone && itemLine != NULL )
+                {
+                lineRet = itemLine->GetInt( KUserDefMaxHeap, integer );
+                if ( lineRet == KErrNone )
+                    {
+                    aHeapMaxSize = integer;
+                    }
+                }
+            delete itemLine;
+
+            CleanupStack::Pop(section);
+            CleanupStack::Pop(parser);
+
+            CleanupStack::PopAndDestroy( setting_buf2 );
+            CleanupStack::PopAndDestroy( setting_buf );
+
+            delete section;
+            delete parser;
+
+            break; // Stop the do branch
+            }
+
+        // Start to create new section for search
+
+        // 8 bit to 16. Last buffer to first
+        to16bit.Copy( buf2 );
+        currentSection.Copy( to16bit );
+
+        // Read new data to buffer 1
+        ret = KErrNone;
+        User::LeaveIfError( file.Read( offset, buf1, tmpSize ) );
+
+        // 8 bit to 16. Append
+        to16bit.Copy( buf1 );
+        currentSection.Append( to16bit );
+
+        // Copy first buffer data to buffer 2. This is added to first
+        // in section in next run
+        buf2.Copy( buf1 );
+
+        } while( offset < size );
+
+    CleanupStack::PopAndDestroy( tmp4 );
+    CleanupStack::PopAndDestroy( tmp3 );
+    CleanupStack::PopAndDestroy( tmp2 );
+    CleanupStack::PopAndDestroy( tmp1 );
+
+    CleanupStack::PopAndDestroy( &file );
+    CleanupStack::PopAndDestroy( &fileServer );
+    file.Close();
+    fileServer.Close();
+
+    //__UHEAP_MARKEND;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: ReadParametersFromTestModule
+
+    Description: Loads dynamically testmodule and calls SetRequirements()-
+                 method for test module parameter handling.
+
+    Parameters: const TDesC& aModuleName: in: Test module name
+                CTestModuleParam*& aTestModuleParam: inout: Object for handling
+                test module parameters.
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::ReadParametersFromTestModule(
+                                const TDesC& aModuleName,
+                                CTestModuleParam*& aTestModuleParam )
+    {
+    __TRACE( KInit, (  _L( "ReadParametersFromTestModule() [%S]" ), &aModuleName ) );
+    RLibrary testModule;
+    // Load the module
+    TPtrC dllName;
+    
+    // Remove optional index appended to module name
+    TFileName validModuleName;
+    RemoveOptionalIndex(aModuleName, validModuleName);
+    __TRACE(KInit, (_L( "Valid module name is [%S] (extracted from [%S])"), &validModuleName, &aModuleName));
+    dllName.Set(validModuleName);
+    
+    // Loading should work with and without '.dll' extension.
+    TInt r = testModule.Load( dllName );
+    if ( r != KErrNone )
+        {
+        __TRACE( KError, ( CStifLogger::EError, _L("Can't initialize test module[%S], code = %d"), &dllName, r ) );
+        return KErrNotFound;
+        }
+    else
+        {
+        // Print reset module name
+        __TRACE( KInit, (  _L("Loaded test module[%S]"), &dllName ) );
+        }
+
+    
+
+    CTestInterfaceFactoryTestModule libEntry = NULL;
+    
+#if defined( __ARMCC__ )
+        {
+        // In this environment the heap and stack feature may crash if
+        // test module not include a workaround for ARM RVCT(ARMv5) compiler
+        // error. For more information see STIF user guide.
+        __TRACE ( KInit, ( _L( "Workaround for ARM RVCT(ARMv5) compiler error should be included to TestModule." ) ) );
+        }
+#endif // #if defined(__ARMCC__)
+
+    // Get pointer to second exported function
+    // Verify that there is function
+    //CTestInterfaceFactoryTestModule libEntry;
+    libEntry = (CTestInterfaceFactoryTestModule) testModule.Lookup( 2 );
+    if ( libEntry == NULL )
+        {
+        // New instance can't be created
+        __TRACE( KInit, (_L( "Test module is old version and has not SetRequirements() feature." ) ) );
+        testModule.Close();
+        return KErrNotSupported;
+        }
+    else
+        {
+        __TRACE ( KInit, ( _L("Pointer to 2st exported received")));
+        }
+
+    // Calls dynamically loaded module's second method.
+    __TRACE ( KVerbose, (_L("Calling 2st exported at 0x%x"), (TUint32) libEntry ));
+    TUint32 check = 0;
+    TInt ret =  (*libEntry)( aTestModuleParam, check  );
+    if( check != KStifTestModuleParameterChanged  )
+        {
+        // Problems in def-file definitions. Test module is old wersion
+        // and has not SetRequirements feature.
+        RDebug::Print( ( _L( "STIF TF: Test module is old version and has not SetRequirements() feature." ) ) );
+        __TRACE( KInit, (_L( "Test module is old version and has not SetRequirements() feature." ) ) );
+        testModule.Close();
+        return KErrNotSupported;
+        }
+    if( ret != KErrNone )
+        {
+        __TRACE (KInit, (_L("ReadParametersFromTestModule; SetRequirements fails with error: %d"), ret ) );
+        testModule.Close();
+        return ret;
+        }
+
+    libEntry = NULL; 
+    testModule.Close(); // After close test module's pointer is not
+                        // valid anymore.
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: GetTestModuleParams
+
+    Description: Load test module dynamically. If loading is done succesfully
+                 then set test module's parameters according to version.
+                 Verify received parameters.
+
+    Parameters: const TDesC& aModuleName: in: Test module name.
+                const TDesC& aConfig: in: Test case (config) file name.
+                TInt& aStackSize: inout: Stack size.
+                TInt& aHeapMinSize: inout: Heap's minimum size.
+                TInt& aHeapMaxSize: inout: Heap's maximum size.
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModuleContainer::GetTestModuleParams( const TDesC& aModuleName,
+                                                const TDesC& aConfig,
+                                                TInt& aStackSize,
+                                                TInt& aHeapMinSize,
+                                                TInt& aHeapMaxSize )
+    {
+    TInt r( KErrNone );
+
+    // There is lower case despite what is initialization file given.
+    // Module name is without dll extension.
+    // Check is TestScripter or TestCombiner and test case (config) file
+    // name is given.
+    if( ( aModuleName.Find( KTestScripterName ) != KErrNotFound ||
+          aModuleName == _L( "testcombiner" ) ) && aConfig != KNullDesC )
+        {
+        TRAPD( ret, r = ReadParametersFromScriptFileL( aConfig, aStackSize,
+                                          aHeapMinSize, aHeapMaxSize ) );
+        if( r != KErrNone )
+            {
+            __TRACE( KInit, ( CStifLogger::ERed, _L( "Cannot set Test Class's stack or heap sizes, fail with error: %d" ), r ) );
+            __TRACE( KInit, ( _L( "Default sizes will be use(See KTestThreadMinHeap, KTestThreadMinHeap and KStackSize)" ) ) );
+            return r;
+            }
+        if( ret != KErrNone )
+            {
+            __TRACE( KInit, ( CStifLogger::ERed, _L( "Cannot set Test Class's stack or heap sizes, leaves with error: %d" ), r ) );
+            __TRACE( KInit, ( _L( "Default sizes will be use(See KTestThreadMinHeap, KTestThreadMinHeap and KStackSize)" ) ) );
+            return ret;
+            }
+        }
+    else
+        {
+        CTestModuleParam* testModuleParam = NULL;
+        //--PYTHON-- begin
+        if(aModuleName.Find(KPythonScripter) != KErrNotFound)
+            {
+			RDebug::Print(_L("CTestModuleContainer::GetTestModuleParams reading params for PythonScripter, aModuleName=[%S]"), &aModuleName);
+            TName n;
+            n.Copy(KPythonScripter);
+            r = ReadParametersFromTestModule( n, testModuleParam );
+            }
+        else
+        //--PYTHON-- end
+            r = ReadParametersFromTestModule( aModuleName, testModuleParam );
+
+        if( r != KErrNone )
+            {
+            __TRACE( KInit, ( _L( "Cannot set Test Module's stack or heap sizes, fails with: %d" ), r ) );
+            __TRACE( KInit, ( _L( "Default sizes will be use(See KTestThreadMinHeap, KTestThreadMinHeap and KStackSize)" ) ) );
+            delete testModuleParam;
+            return r;
+            }
+
+        if ( testModuleParam->Version() == 1 )
+            {
+            // Casting
+            CTestModuleParamVer01* paramVer01 = ( CTestModuleParamVer01* ) testModuleParam;
+            aStackSize = paramVer01->iTestThreadStackSize;
+            aHeapMinSize = paramVer01->iTestThreadMinHeap;
+            aHeapMaxSize = paramVer01->iTestThreadMaxHeap;
+            }
+
+        delete testModuleParam;
+        }
+
+    // Verify that sizes are valid. If problems are notices then use default 
+    // value
+
+    // 1) "The panic occurs when the value of the stack size is negative."
+    if( aStackSize < 0 )
+        {
+        RDebug::Print( ( _L("STIF TF: GetTestModuleParams() fails because value of the stack size is negative, default value is taken into use") ) );
+        __TRACE( KInit, ( CStifLogger::ERed, _L("STIF TF: GetTestModuleParams() fails because value of the stack size is negative, default value is taken into use" ) ) );
+        // Use default value
+        aStackSize = KStackSize;
+        }
+    
+    // 2) "The panic occurs if the minimum heap size specified is less
+    // than KMinHeapSize".
+    // KMinHeapSize: "Functions that require a new heap to be allocated will
+    // either panic, or will reset the required heap size to this value if a
+    // smaller heap size is specified".
+    if( aHeapMinSize < KMinHeapSize )
+        {
+        RDebug::Print( _L( "STIF TF: GetTestModuleParams() fails because test module minimum heap size is less than KMinHeapSize:[%d], default value is taken into use" ), KMinHeapSize );
+        __TRACE( KInit, ( CStifLogger::ERed, _L("STIF TF: GetTestModuleParams() fails because test module minimum heap size is less than KMinHeapSize:[%d], default value is taken into use"), KMinHeapSize ) );
+        // Use default value(Note: This is used for now on)
+        aHeapMinSize = KTestThreadMinHeap;
+        }
+
+    // 3) "The panic occurs if the minimum heap size specified is greater than
+    // the maximum size to which the heap can grow".
+    // Check this last !
+    if( aHeapMinSize > aHeapMaxSize )
+        {
+        RDebug::Print( ( _L("STIF TF: GetTestModuleParams() fails because the maximum heap size is specified less than minimum heap size, default values is taken into use" ) ) );
+        __TRACE( KInit, ( CStifLogger::ERed, _L( "STIF TF: GetTestModuleParams() fails because the maximum heap size is specified less than minimum heap size, default values is taken into use" ) ) );
+        // Use default values
+        aHeapMinSize = KTestThreadMinHeap;
+        aHeapMaxSize = KTestThreadMaxHeap;
+        }
+
+    __TRACE( KInit, ( _L( "[%S] uses:" ), &aModuleName ) );
+    __TRACE( KInit, ( _L( "Stack size: [%d]" ), aStackSize ) );
+    __TRACE( KInit, ( _L( "Minimum heap size: [%d]" ), aHeapMinSize ) );
+    __TRACE( KInit, ( _L( "Maximum heap size: [%d]" ), aHeapMaxSize ) );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: GetTestCaseTitleL
+
+    Description: Gets title of currently running test case.
+
+    Parameters: TDes& aTestCaseTitle: out: Test case title.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModuleContainer::GetTestCaseTitleL(TDes& aTestCaseTitle)
+    {
+    //currently run test case stored in the iOperationIntBuffer variable
+    iCTestModule->GetTestCaseTitleL( iOperationIntBuffer, 
+                                     iCTestExecution->GetConfigFileName(),
+                                    aTestCaseTitle);  
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModuleContainer
+
+    Method: GetTestModule
+
+    Description: Gets pointer to test module
+
+    Parameters: none
+
+    Return Values: CTestModule* : Pointer to test module
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestModule* CTestModuleContainer::GetTestModule()
+    {
+    
+    return iCTestModule;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CPrintHandler class member functions.
+    CErrorPrintHandler listens print notifications from test thread.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrintHandler
+
+    Method: NewL
+
+    Description: Constructs a new CErrorPrintHandler object.
+
+    Parameters: CTestExecution& aExecution: in: "Parent"
+
+    Return Values: CErrorPrintHandler*: New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CErrorPrintHandler* CErrorPrintHandler::NewL( CTestModuleContainer& aContainer )
+    {
+
+    CErrorPrintHandler* self = new( ELeave ) CErrorPrintHandler( aContainer );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrintHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CErrorPrintHandler::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrintHandler
+
+    Method: CErrorPrintHandler
+
+    Description: Constructor
+
+    Parameters: CTestModuleContainer& aExecution :in:   "Parent"
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CErrorPrintHandler::CErrorPrintHandler( CTestModuleContainer& aContainer ) :
+    CActive( CActive::EPriorityStandard ),
+    iContainer( aContainer )
+    {
+    
+    CActiveScheduler::Add ( this );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrintHandler
+
+    Method: ~CErrorPrintHandler
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CErrorPrintHandler::~CErrorPrintHandler()
+    {
+
+    Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrintHandler
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CErrorPrintHandler::StartL()
+    {
+    
+    __TRACE( KPrint, ( _L( "CErrorPrintHandler::StartL" ) ) );
+    
+    iStatus = KRequestPending;
+    SetActive();
+    
+    // Signal test thread
+    iContainer.iErrorPrintSem.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrintHandler
+
+    Method: RunL
+
+    Description: Handles thread death.
+    Function does:
+    1 ) Stops monitoring thread
+    1 ) Marks thread death
+    2 ) Completes ongoing requests
+    3 ) Cleans the memory
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CErrorPrintHandler::RunL()
+    {
+
+    __TRACE( KPrint, ( _L( "CErrorPrintHandler::RunL [%d]" ), iStatus.Int() ) );
+    
+    iContainer.DoErrorPrint();    
+    
+    // enable error print request
+    iContainer.iErrorPrintHandler->StartL();
+       
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrintHandler
+
+    Method: DoCancel
+
+    Description: Stops print notification listening.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CErrorPrintHandler::DoCancel()
+    {
+
+    __TRACE( KPrint, ( _L( "CErrorPrintHandler::DoCancel" ) ) );
+
+    // Signal test thread
+    iContainer.iErrorPrintSem.Wait();
+
+    TRequestStatus* status = &iStatus;    
+    User::RequestComplete( status, KErrCancel );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CErrorPrintHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError:                  :in:  Error code
+
+    Return Values:  TInt                            Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CErrorPrintHandler::RunError( TInt aError )
+    {
+    
+    __TRACE( KError,( _L( "CErrorPrintHandler::RunError" ) ) );
+
+    return aError;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: CheckModuleName
+
+    Description: Check is module TestScripter. Does parsing and returns new
+                 module name and error codes(Needed operations when creating
+                 server sessions to TestScripter).
+
+    Parameters: TFileName aModuleName: in: Module name for checking.
+                TFileName& aNewModuleName: inout: Parsed module name.
+
+    Return Values: KErrNone if TestScripter releated module.
+                   KErrNotFound if not TestScripter releated module.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CheckModuleName( TFileName aModuleName, TFileName& aNewModuleName )
+    {
+//--PYTHON-- old code has been replaced with the new one
+/*
+    // Check that length is greated than KTestScripterNameLength
+    if( aModuleName.Length() < KTestScripterNameLength )
+        {
+        return KErrNotFound;
+        }
+    // Check is TestScripter
+    TPtrC check( aModuleName.Mid( 0, KTestScripterNameLength ) );
+    TInt ret = check.Compare( KTestScripterName );
+    if( ret == KErrNone )
+        {
+        aNewModuleName.Copy( aModuleName.Mid( 0, KTestScripterNameLength ) );
+        }
+    else
+        {
+        return KErrNotFound;
+        }
+
+    return KErrNone;
+*/
+
+	// Check that length is greated than KTestScripterNameLength
+	if( aModuleName.Length() >= KTestScripterNameLength )
+		{
+		TPtrC check( aModuleName.Mid( 0, KTestScripterNameLength ) );
+		TInt ret = check.Compare( KTestScripterName );
+		if( ret == KErrNone )
+			{
+			aNewModuleName.Copy( aModuleName.Mid( 0, KTestScripterNameLength ) );
+			return KErrNone;
+			}
+		}
+
+	// Check that length is greated than KTestScripterNameLength
+	if( aModuleName.Length() >= KPythonScripterLength )
+		{
+		TPtrC check( aModuleName.Mid( 0, KPythonScripterLength ) );
+		TInt ret = check.Compare( KPythonScripter );
+		if( ret == KErrNone )
+			{
+			aNewModuleName.Copy( aModuleName.Mid( 0, KPythonScripterLength ) );
+			return KErrNone;
+			}
+		}
+
+    return KErrNotFound;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: RemoveOptionalIndex
+
+    Description: Remove optional index appended to module name.
+                 If it is found (@ char) then set new module name without it.
+                 This feature is used when iSeparateProcesses is set in
+                 TestEngine.
+
+    Parameters: TFileName aModuleName: in: Module name for checking.
+                TFileName& aNewModuleName: inout: Parsed module name.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void RemoveOptionalIndex(const TDesC& aModuleName, TDes& aNewModuleName)
+    {
+    //Copy module name to destination buffer
+    aNewModuleName.Copy(aModuleName);
+    
+    //Search for @ char (it means that some index has been appended)
+    TInt index = aNewModuleName.Find(_L("@"));
+    
+    //Remove index form name (if found)
+    if(index != KErrNotFound)
+        {
+        aNewModuleName.Delete(index, aNewModuleName.Length() - index);
+        }
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/TestServer.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,976 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CTestServer 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+#include "TestEngineClient.h"
+#include <StifTestModule.h>
+#include <stifinternal/TestServerClient.h>
+#include "TestServer.h"
+#include "TestServerCommon.h"
+#include <stifinternal/TestThreadContainerRunnerFactory.h>
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// Struct to pass parameters to server thread
+struct TThreadStartTestServer
+    {
+    TFileName  iName;         // Server name
+    RThread    iServerThread; // The server thread
+    RSemaphore iStarted;      // Startup syncronisation semaphore   
+    TBool      iInNewThread;  // Is thread running in new process?
+    TInt       iStartupResult;// Start-up result
+    TBool      iUiTesting;    // Is it testserver for UI testing
+    CTestThreadContainerRunnerFactory* iTestThreadContainerRunnerFactory; // Pointer to CTestThreadContainerRunner. Defined when
+																		  // iUiTesting is true
+    };
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: PanicServer
+
+    Description: Panics the server. 
+
+    Parameters: const TTestServerPanic aPanic: in: Panic code
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestServer::PanicServer( const TTestServerPanic aPanic )
+    {
+    
+#ifdef USE_LOGGER
+    // Check if logger is available, if so, use it.
+    CStifLogger* log = (CStifLogger*) Dll::Tls();
+    if ( log )
+        {
+        log->Log( CStifLogger::ERed, _L("TestServer.DLL Panic %d"), aPanic);
+        }
+#endif
+
+    RDebug::Print( _L( "CTestServer::PanicServer" ) );
+    _LIT( KTxtTestServer,"CTestServer" );
+    User::Panic( KTxtTestServer,aPanic );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: NewL
+
+    Description: Returns new CTestServer object
+
+    Parameters: const TFileName& aName: in: Server name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation, ConstructL or StartL leaves.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestServer* CTestServer::NewL( const TFileName& aName )
+    {
+
+    CTestServer* self = new( ELeave ) CTestServer();
+    CleanupStack::PushL( self );
+
+    // Construct the server
+    self->ConstructL( aName );
+
+    // Start the server
+    self->StartL( aName );
+
+    CleanupStack::Pop( self );
+
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: ConstructL
+
+    Description: Second level constructor. Obtains pointer to library
+    entrypoint.
+
+    Parameters: const TFileName& aName: in: Server name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if entrypoint can't be obtained.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestServer::ConstructL( const TFileName& aName )
+    {
+    // Construct heap buffer for configuration file
+    iModuleNameBuffer = HBufC::NewL( aName.Length() );
+    iModuleName.Set ( iModuleNameBuffer->Des() );
+    iModuleName.Copy ( aName );
+
+    iContainerIndex = CObjectConIx::NewL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: CTestServer
+
+    Description: Constructor.
+
+    Initialises non-zero member variables and base class with correct
+    priority.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestServer::CTestServer() : CServer2( CTestServer::ETestServerPriority ),
+                             iModuleName(0, 0),
+                             iSessionCount( 0 )
+    {
+    iFirstTime = ETrue;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: ~CTestServer
+
+    Description: Destructor
+    Frees memory.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestServer::~CTestServer()
+    {
+
+    delete iModuleNameBuffer;
+    iModuleNameBuffer = NULL;
+
+    delete iContainerIndex;
+    iContainerIndex = NULL;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: NewContainerL
+
+    Description: Returns new container. Used to store subsessions
+
+    Parameters: None
+
+    Return Values: CObjectCon* New object container
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CObjectCon* CTestServer::NewContainerL()
+    {
+     
+    CObjectCon* container = iContainerIndex->CreateL();
+
+    iSessionCount++;
+
+    return container;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: DeleteContainer
+
+    Description: Deletes a container.
+
+    Parameters: CObjectCon* aContainer: in: Container to be removed
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestServer::DeleteContainer( CObjectCon* aContainer )
+    {
+    iContainerIndex->Remove( aContainer );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: SessionClosed
+
+    Description: Inform Server that session is closed.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestServer::SessionClosed()
+    {
+    // Decrease session count
+    iSessionCount--;
+
+    // Check if last session is closed
+    if ( iSessionCount <= 0 )
+        {
+        // Stop the active scheduler
+        // Execution will continue in ThreadFunction()
+        CActiveScheduler::Stop();
+        }
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: NewSessionL
+
+    Description: Returns new session.
+    
+    Parameters: const TVersion &aVersion: in: Version required
+
+    Return Values: CSharableSession* New session
+
+    Errors/Exceptions: Leaves if invalid version or CTestModule construction
+                       leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CSession2* CTestServer::NewSessionL( const TVersion& aVersion,
+                                        const RMessage2& /*aMessage*/ ) const
+    {
+    // check version is ok
+    TVersion v( KTestServerMajorVersionNumber,
+                KTestServerMinorVersionNumber,
+                KTestServerBuildVersionNumber
+               );
+    if( !User::QueryVersionSupported( v,aVersion ) )
+        {
+        User::Leave( KErrNotSupported );
+        }
+
+    return CTestModule::NewL( ( CTestServer* ) this );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: ModuleName
+
+    Description: Returns module name
+
+    Parameters: None
+
+    Return Values: const TDesC&* Module name
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestServer::ModuleName() const
+    {
+    return iModuleName;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: FirstTime
+
+    Description: Is module already once initialised.
+
+    Parameters: None
+
+    Return Values: TBool Has module initialized?
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+//@spe const TBool CTestServer::FirstTime() const
+TBool CTestServer::FirstTime() const
+    {
+    return iFirstTime;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: ClearFirstTime
+
+    Description: Clear module first time flag. 
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestServer::ClearFirstTime()
+    {
+    iFirstTime = EFalse;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: ThreadFunction
+
+    Description: The thread function, where Test Server lives in
+    
+    Parameters: TAny* aStarted: in: Start-up information
+    
+    Return Values: TInt Result from test module
+
+    Errors/Exceptions: Clean-up stack can't be created because cannot
+                       leave, error checks are done locally.
+                       Panics if:
+                       invalid start-up information
+                       Test Server can't be started
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestServer::ThreadFunction( TAny* aStarted )
+    {
+
+    __UHEAP_MARK;
+
+    TInt error( KErrNone );
+
+    // Get start-up information
+    TThreadStartTestServer* startInfo = ( TThreadStartTestServer* ) aStarted;
+    __ASSERT_ALWAYS( startInfo,PanicServer( ENoStartupInformation ) );
+
+    // Create clean-up stack
+    CTrapCleanup* tc = CTrapCleanup::New();
+    __ASSERT_ALWAYS( tc, PanicServer(ECreateTrapCleanup));
+
+    // Construct the logger
+    TName path = _L("C:\\logs\\testframework\\testserver\\");
+    TFileName name = _L("testserver_");
+    name.Append ( startInfo->iName );
+
+    // Create logger, in Wins use HTML in HW default logger
+    TLoggerSettings loggerSettings;
+
+    // Directory must create by hand if test server log wanted
+    loggerSettings.iCreateLogDirectories = EFalse;
+
+    loggerSettings.iOverwrite = ETrue;
+    loggerSettings.iTimeStamp = ETrue;
+    loggerSettings.iLineBreak = ETrue;
+    loggerSettings.iEventRanking = EFalse;
+    loggerSettings.iThreadId = EFalse;
+    loggerSettings.iHardwareFormat = CStifLogger::ETxt;
+#ifndef FORCE_STIF_INTERNAL_LOGGING_TO_RDEBUG
+    loggerSettings.iEmulatorFormat = CStifLogger::EHtml;
+    loggerSettings.iHardwareOutput = CStifLogger::EFile;
+    loggerSettings.iEmulatorOutput = CStifLogger::EFile;
+#else
+    RDebug::Print( _L( "STIF Test Server logging forced to RDebug" ) );
+    loggerSettings.iEmulatorFormat = CStifLogger::ETxt;
+    loggerSettings.iHardwareOutput = CStifLogger::ERDebug;
+    loggerSettings.iEmulatorOutput = CStifLogger::ERDebug;
+#endif
+    loggerSettings.iUnicode = EFalse;
+    loggerSettings.iAddTestCaseTitle = EFalse;
+
+    CStifLogger* logger = NULL;
+    TRAP ( error, logger = CStifLogger::NewL( path, name, loggerSettings ) );
+
+    // Thread Local Storage is used for get pointer to logger.
+    Dll::SetTls ( logger );
+
+    __TRACE( KInit,( _L( "TestServer.DLL server starting" ) ) );
+    __TRACE( KInit,( CStifLogger::EBold, _L( "Loading module: %S"), &startInfo->iName ) );
+
+    RLibrary module;
+    TInt ret = KErrNone;
+
+    TFileName newNameBuffer;
+    TInt check = CheckModuleName( startInfo->iName, newNameBuffer );
+    if( check == KErrNone )
+        {
+        // Load the module(TestScripter)
+        ret = module.Load( newNameBuffer );
+        }
+    else
+        {
+        RemoveOptionalIndex(startInfo->iName, newNameBuffer);
+        __TRACE(KInit, (CStifLogger::EBold, _L( "Valid module name is [%S] (extracted from [%S])"), &newNameBuffer, &startInfo->iName));
+        // Load the module(Others)
+        ret = module.Load(newNameBuffer);
+        }
+
+    // If test module loading fails, do not start server
+    if( ret != KErrNone )
+        {
+         __TRACE( KError,( CStifLogger::ERed, _L( "Test module loading failed, code = %d" ), ret ) );
+         __TRACE( KError,( _L( "Check that module is compiled properly and stored to correct directory and all DLLs that it requires are available" ) ) );                  
+
+         // Error will be handled in StartNewServer
+        startInfo->iStartupResult = ret;
+        startInfo->iStarted.Signal();
+        if ( !startInfo->iInNewThread )
+            {
+            startInfo->iStarted.Close();
+            }
+        module.Close();
+        Dll::FreeTls();
+        // Delete logger
+        delete logger;
+        logger = NULL;
+        // Delete clean-up stack
+        delete tc;
+        tc = NULL;
+        __UHEAP_MARKEND;
+        return ret;
+        }
+    else
+        {
+        __TRACE( KInit,( _L( "Test module loaded correctly" ) ) );
+        }
+
+    // Verify that there is function
+    CTestInterfaceFactory libEntry = ( CTestInterfaceFactory ) module.Lookup( 1 );
+    if( libEntry == NULL )
+        {
+         // Error will be handled in StartNewServer
+        __TRACE( KError,( CStifLogger::ERed, _L( "Can't find entrypoint from test module" ) ) );
+
+        startInfo->iStartupResult = KErrNotFound;
+        startInfo->iStarted.Signal();
+        if ( !startInfo->iInNewThread )
+            {
+            startInfo->iStarted.Close();
+            }
+        module.Close();
+        Dll::FreeTls();
+        // Delete logger
+        delete logger;
+        logger = NULL;
+        // Delete clean-up stack
+        delete tc;
+        tc = NULL;
+        __UHEAP_MARKEND;
+        return KErrNotFound;
+        }
+
+    module.Close();
+
+    // Construct and install active scheduler
+    CActiveScheduler* scheduler = new CActiveScheduler;
+    __ASSERT_ALWAYS( scheduler, PanicServer( EMainSchedulerError ) );
+    CActiveScheduler::Install( scheduler );
+
+    // Construct server
+    CTestServer* server = NULL;
+    TRAPD( err, server = CTestServer::NewL( startInfo->iName ) );
+    __ASSERT_ALWAYS( !err, PanicServer( ESvrCreateServer ) );
+
+    server->iUiTesting = startInfo->iUiTesting;
+    server->iTestThreadContainerRunnerFactory = startInfo->iTestThreadContainerRunnerFactory;
+    
+    // Inform that we are up and running
+    startInfo->iStartupResult = KErrNone;
+    startInfo->iStarted.Signal();
+    if ( !startInfo->iInNewThread )
+        {
+        startInfo->iStarted.Close();
+        }
+
+    // Start handling requests
+    CActiveScheduler::Start();
+
+    // Execution continues from here after CActiveScheduler::Stop
+
+    __TRACE( KVerbose,( _L( "TestServer.DLL active scheduler stopped" ) ) );
+
+    // Delete the server
+    delete server;
+    server = NULL;
+    __TRACE( KVerbose,( _L( "TestServer.DLL server object deleted" ) ) );
+
+    delete scheduler;
+    scheduler = NULL;
+    __TRACE( KVerbose,( _L( "Active scheduler deleted" ) ) );
+
+    __TRACE ( KInit, (_L("TestServer.DLL ThreadFunction exiting, server closing")) );
+
+    Dll::FreeTls();
+    // Delete logger
+    delete logger;
+    logger = NULL;
+    // Delete clean-up stack
+    delete tc;
+    tc = NULL;
+
+    __UHEAP_MARKEND;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: GetServerThreadId
+
+    Description: Returns server thread id
+
+    Parameters: None
+
+    Return Values: TInt : thread id
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestServer::GetServerThreadId()
+    {
+    RThread thread; 
+    return thread.Id();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: GetTestThreadContainerRunnerFactory
+
+    Description: Returns server thread id
+
+    Parameters: None
+
+    Return Values: TInt : thread id
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainerRunnerFactory* CTestServer::GetTestThreadContainerRunnerFactory()
+	{
+	
+	return iTestThreadContainerRunnerFactory;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: UiTesting
+
+    Description: Gets information if testserver supports UI testing
+
+    Parameters: None
+
+    Return Values: True if testserver supports UI testing, False if not.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TBool CTestServer::UiTesting()
+	{
+	
+	return iUiTesting;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestServer
+
+    Method: GetUiEnvProxy
+
+    Description: Gets UIEnvProxy
+
+    Parameters: None
+
+    Return Values: Pointer to UIEnvProxy.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CUiEnvProxy* CTestServer::GetUiEnvProxy()
+	{
+	
+	return iTestThreadContainerRunnerFactory->GetUiEnvProxy();
+	}
+
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: StartNewServer
+
+    Description: Starts a new server. Server will be running its own
+    thread and this functions returns when server is up and running or
+    server start-up fails.
+
+    Parameters: const TFileName& aModuleFileName: in: Module name
+                TFileName& aServerName: in: Server name
+                const TBool aInNewThread: in: Is new thread
+                RSemaphore aSynchronisation: in: For synchronisation
+                TBool aUiTestingServer: in: Indicates if testserver should support UI testing
+                CTestThreadContainerRunnerFactory* aTestThreadContainerRunnerFactory: in: Pointer to runner factory
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt StartNewServer( const TFileName& aModuleFileName,
+                              TFileName& aServerName,
+                              const TBool aInNewThread,
+                              RSemaphore aSynchronisation,
+                              TBool aUiTestingServer,
+                              CTestThreadContainerRunnerFactory* aTestThreadContainerRunnerFactory
+                            )
+    {
+
+    __UHEAP_MARK;
+
+    //Check server not already started
+    TFindServer findServer( aModuleFileName );
+    TFullName name;
+    if( findServer.Next( name ) == KErrNone )
+        {   
+        // Server already started, nothing to do
+        aServerName = aModuleFileName;
+        __UHEAP_MARKEND;
+        return KErrAlreadyExists;
+        }
+
+    // Construct start-up information object
+    TThreadStartTestServer* startInfo = new TThreadStartTestServer();
+    if( startInfo == NULL )
+        {
+        __UHEAP_MARKEND;
+        return KErrNoMemory;
+        }
+
+    // Fill the start-up information
+    startInfo->iName = aModuleFileName;
+    startInfo->iStartupResult = KErrNone;
+    startInfo->iStarted = aSynchronisation;
+    startInfo->iInNewThread = aInNewThread;
+	startInfo->iUiTesting = aUiTestingServer;
+	startInfo->iTestThreadContainerRunnerFactory = aTestThreadContainerRunnerFactory;
+
+    // EKA1
+    if ( aInNewThread )
+        {
+        // Create thread    
+        TInt res = startInfo->iServerThread.Create( 
+            startInfo->iName ,                       // Name of thread
+            CTestServer::ThreadFunction,             // Thread function
+            KDefaultStackSize,                       // Stack size
+            KDefaultHeapSize,                        // Heap initial size
+            KMaxHeapSize,                            // Heap start max size
+            startInfo                                // Parameter to thread function
+            );
+
+        // If thread creation failed
+        if( res != KErrNone )
+            {
+            startInfo->iStarted.Close();             // Close semaphore
+            delete startInfo;
+            startInfo = NULL;
+            __UHEAP_MARKEND;
+            return res;
+            }
+
+         // Now start thread
+        startInfo->iServerThread.SetPriority( EPriorityMuchMore ); 
+        startInfo->iServerThread.Resume();
+
+        // Wait until the thread is started
+        startInfo->iStarted.Wait();
+
+        // Server is started( or it has returned error )
+    
+
+        }
+
+    // EKA2 and EKA1's HW
+    else
+        {
+        // Call directly thread function, this starts server and
+        // blocks this thread.
+        // Priority is default, not known reason why should be greater
+        // than default priority (Work over a year).
+        CTestServer::ThreadFunction( startInfo );
+        }
+
+    // Set server name
+    aServerName = aModuleFileName;
+
+    // Free memory
+    TInt r = startInfo->iStartupResult;
+    startInfo->iServerThread.Close();
+    startInfo->iStarted.Close();
+    delete startInfo;
+    startInfo = NULL;
+
+    __UHEAP_MARKEND;
+
+    // Return start-up result.
+    return r;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: StartNewServer
+
+    Description: Starts a new server. Server will be running its own
+    thread and this functions returns when server is up and running or
+    server start-up fails.
+
+    Parameters: const TFileName& aModuleFileName: in: Module name
+                TFileName& aServerName: in: Server name
+                const TBool aInNewThread: in: Is new thread
+                RSemaphore aSynchronisation: in: For synchronisation
+
+    Return Values: TInt: Symbian error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt StartNewServer( const TFileName& aModuleFileName,
+                              TFileName& aServerName,
+                              const TBool aInNewThread,
+                              RSemaphore aSynchronisation
+                            )
+	{
+	
+	return StartNewServer( aModuleFileName, aServerName, aInNewThread, aSynchronisation, false, NULL );
+	}
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: StartNewServer
+
+    Description: Starts a new server. Server will be running its own
+    thread and this functions returns when server is up and running or
+    server start-up fails.
+
+    Parameters: const TFileName& aName: in: Module name to be used
+                TFileName& aServerName: out: The name of the server
+
+    Return Values: TInt Error code / KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt StartNewServer( const TFileName& aModuleFileName,
+                              TFileName& aServerName
+                            )
+    {
+
+    __UHEAP_MARK;
+
+    RMutex startupMutex;
+    TInt ret( KErrNone );
+    // Global mutex already created(see CTestEngineServer::ThreadFunction).
+    // Open global mutex.
+    ret = startupMutex.OpenGlobal( KStifTestServerStartupMutex );
+    if( ret != KErrNone )
+        {
+        // Not able to open mutex
+        return ret;
+        }
+
+    startupMutex.Wait();
+
+    //Check server not already started
+    TFindServer findServer( aModuleFileName );
+    TFullName name;
+    if( findServer.Next( name ) == KErrNone )
+        {
+        // Server already started, nothing to do
+        aServerName = aModuleFileName;
+        
+        // release startupmutex
+        startupMutex.Signal();
+        startupMutex.Close();
+
+        __UHEAP_MARKEND;
+        return KErrAlreadyExists;
+        }
+
+    RSemaphore startupSemaphore;
+    startupSemaphore.CreateLocal( 0 );
+
+    // Start server in new thread
+    TInt r = StartNewServer ( aModuleFileName, aServerName, ETrue, startupSemaphore );
+
+    // startupSemaphore will be closed inside StartNewServer when start-up is done.
+
+    // release startupmutex
+    startupMutex.Signal();
+    startupMutex.Close();
+
+    __UHEAP_MARKEND;
+
+    // Return start-up result.
+    return r;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/TestServerClient.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1237 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of RTestServer, 
+* RTestModule and RTestExecution class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include <stifinternal/TestServerClient.h>
+#include "TestServerCommon.h"
+//--PYTHON-- begin
+#include "StifPython.h"
+//--PYTHON-- end
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestServer
+
+    Method: RTestServer
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C RTestServer::RTestServer()
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestServer
+
+    Method: Connect
+
+    Description: Connect method creates new RTestServer session.
+    RTestServer session is used to manage the test case execution.
+    
+    Parameters: const TFileName& aModuleName: in: Module to be loaded
+                const TDesC& aConfigFile: in: Test case(config) file
+                name(Used in TestScripter case for parsing STIF settings).
+
+    Return Values: TInt Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestServer::Connect( const TFileName& aModuleName,
+                                    const TDesC& aConfigFile
+                                    )
+    {
+    TFileName serverName;
+
+    TInt ret = KErrNone;
+
+    // Create global semaphore start-up. It will be indexed (if given name already exsists, index will be increased)
+    RSemaphore startSemaphore;
+    TName semaphoreName = _L("startupSemaphore");
+    semaphoreName.Append( aModuleName );
+    TInt x = 0;
+    RBuf semName;
+    ret = semName.Create(KMaxName);
+    if(ret != KErrNone)
+        {
+        RDebug::Print(_L("RTestServer::Connect() Could not create buffer for semaphore name [%d]"), ret);
+        return ret;
+        }
+    do
+        {
+        semName.Format(_L("%S%d"), &semaphoreName, x);
+        if (semName.Length() > KMaxKernelName)
+            {
+            // if the cfg file name is larger than maximum length of acceptable length of semaphore .
+            RDebug::Print(_L("Test Module name or Configuration File name is too long."));
+            
+            semName.Close();
+            return KErrBadName;
+            }
+        
+        ret = startSemaphore.CreateGlobal(semName, 0);
+        RDebug::Print(_L("RTestServer::Connect() Creating global semaphore [%S] with result [%d]"), &semName, ret);
+        if(ret != KErrAlreadyExists)
+            {
+            semaphoreName.Copy(semName);
+            break;
+            }
+        x++;
+        } while (ETrue);
+    semName.Close();
+    
+    if ( ret != KErrNone )
+        {
+        startSemaphore.Close();
+        return ret;
+        }
+
+    // By default start 'testserverstarter.exe'
+    TFileName pathAndExeModule;
+    if ( aModuleName.Find( _L( "testscripter_ui_" ) ) == 0 ) 
+    	{
+        pathAndExeModule.Copy( KDefaultUiExeName );    	
+    	}
+    else
+    	{
+        pathAndExeModule.Copy( KDefaultExeName );    	
+    	}
+
+    RProcess pr;
+
+    // Data to be passed to new process. It will contain module name and synchronization semaphore name separated with space.
+    // I.e. it will be: "mymodule startupSemaphore0"
+    RBuf data; 
+    ret = data.Create(KMaxFileName);
+    if(ret != KErrNone)
+        {
+        RDebug::Print(_L("RTestServer::Connect() Could not create buffer for data to be passed to process [%d]"), ret);
+        return ret;
+        }
+    data.Format(_L("%S %S"), &aModuleName, &semaphoreName);
+    RDebug::Print(_L("RTestServer::Connect() Data for new process prepared [%S]"), &data);
+    
+
+    // Indication is Create() operation needed
+    TBool doCreate( ETrue );
+
+    #ifdef __WINS__ // CodeWarrior(emulator)
+        // Create without path(Uses Symbian default path).
+        // Note: If TestScriter used then module name is format:
+        // testscripter_testcasefilename
+        
+        ret = pr.Create( aModuleName, data );
+        if( ret == KErrNone )
+            {
+            RDebug::Print(_L("RTestServer::Connect() Combination (1): Caps modifier [%S], Data [%S]"), &aModuleName, &data);
+            doCreate = EFalse;
+            }
+    #endif // __WINS__
+
+    if ( doCreate )
+        {
+        TInt find_ret( KErrNone );
+        TInt trapd_ret( KErrNone );
+        // Check is TestScripter and is caps modifíer name given
+        if( aModuleName.Find( KTestScripterName ) != KErrNotFound && aConfigFile != KNullDesC )
+            {
+            TInt ret_caps;
+            TFileName capsModifierName;
+            // In TestClass's test case (config) file can give name to caps
+            // modifier module.
+            ret_caps = GetCapsModifier( aConfigFile, capsModifierName );
+            if( ret_caps != KErrNone )
+                {
+                RDebug::Print( _L( "RTestServer::Connect() Caps modifier was not defined. Default modifier will be used" ) );
+                }
+            else
+                {
+                #ifdef __WINS__ // CodeWarrior(emulator)
+                    // Create without path(Uses Symbian default path)
+                    ret = pr.Create( capsModifierName, data );
+                    if( ret == KErrNone )
+                        {
+                        RDebug::Print( _L( "RTestServer::Connect() Combination (2): Caps modifier [%S], Data [%S]"), &capsModifierName, &data);
+                        doCreate = EFalse;
+                        }
+                #endif // __WINS__
+                if ( doCreate )
+                    {
+                    TRAP( trapd_ret, find_ret = FindExeL(
+                                    capsModifierName, pathAndExeModule ) );
+                    }
+                }
+            }
+        //--PYTHON-- begin
+        // If this is python module, use caps modifier
+        else if(aModuleName.Length() >= KPythonScripterLength && aModuleName.Mid(0, KPythonScripterLength).Compare(KPythonScripter) == 0)
+           {
+           pathAndExeModule.Copy(KPythonScripter);
+           }
+        //--PYTHON-- end
+        // Find exe from file system
+        else if( aModuleName != _L( "testcombiner" ) )
+           {
+           // Check if e.g. TestModule.exe is available
+           TRAP( trapd_ret, find_ret = FindExeL( aModuleName, pathAndExeModule  ) );
+           }
+
+        // Check FindExeL error codes
+        if( find_ret != KErrNone )
+			{
+			// Module was not found, using default exe: testserverstarter.exe
+			RDebug::Print( _L( "RTestServer::Connect() Correct caps modifier module not found, capabilities cannot set" ) );
+			if ( aModuleName.Find( _L( "testscripter_ui_" ) ) == 0 ) 
+				{
+				pathAndExeModule.Copy( KDefaultUiExeName );    	
+				}
+			else
+				{
+				pathAndExeModule.Copy( KDefaultExeName );    	
+				}           
+			}
+        if( trapd_ret != KErrNone )
+           {
+           // FindExeL fails
+           RDebug::Print( _L( "RTestServer::Connect() Caps modifier module searching fails with error: %d" ), trapd_ret );
+           startSemaphore.Close();
+           data.Close();
+           return trapd_ret;
+           }
+
+        }
+
+    if ( doCreate )
+        {
+        ret = pr.Create( pathAndExeModule, data );
+        RDebug::Print(
+            _L( "RTestServer::Connect() Combination (3): Caps modifier [%S], Data [%S], Result [%d]" ),
+            &pathAndExeModule, &data, ret );
+        }
+
+    data.Close();
+    
+    if ( ret != KErrNone )
+        {
+        startSemaphore.Close();  
+        return ret;
+        }
+
+    // Process created, continue start-up
+    pr.Resume();
+    pr.Close();
+
+    // Wait until server is started
+    startSemaphore.Wait();
+    startSemaphore.Close();     // Close semaphore
+
+    serverName = aModuleName;
+
+    // Server is up and running, connect to it    
+    ret = CreateSession( serverName, Version() );    
+    return ret;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestServer
+
+    Method: Version
+
+    Description: Return client side version.
+
+    Parameters: None
+
+    Return Values: TVersion: Version number
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TVersion RTestServer::Version() const
+    {
+
+    return( TVersion( KTestServerMajorVersionNumber,
+                       KTestServerMinorVersionNumber, 
+                       KTestServerBuildVersionNumber 
+                     ) );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestServer
+
+    Method: Close
+
+    Description: Closes the RTestServer session.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestServer::Close()
+    {
+
+    // Check that server is connected
+    if( Handle() != 0 )
+        {
+        TIpcArgs args( TIpcArgs::ENothing, TIpcArgs::ENothing, TIpcArgs::ENothing );
+        SendReceive( ETestServerCloseSession, args );
+        }
+
+    RSessionBase::Close();
+
+    }
+ /*
+-------------------------------------------------------------------------------
+
+    Class: RTestServer
+
+    Method: GetServerThreadId
+
+    Description: Get server thread id
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestServer::GetServerThreadId(TThreadId& aThreadId)
+    {
+
+    TInt ret(0);
+
+    // Check that server is connected
+    if( Handle() != 0 )
+        {
+        TThreadId id;
+        TPckg<TThreadId> threadIdPckg( id );
+        TIpcArgs args( &threadIdPckg, TIpcArgs::ENothing, TIpcArgs::ENothing );
+        ret = SendReceive( ETestServerGetServerThreadId, args );  
+        
+        aThreadId = threadIdPckg();        
+        }
+        
+    return ret;
+
+    }            
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestServer
+
+    Method: FindExeL
+
+    Description: Find exe(CapsModifier) from file system(Used in EKA2)
+
+    Parameters: TFileName aModuleName: in: Module name.
+                TFileName& aPathAndExeModule: inout: Module's exe(CapsModifier)
+                path information.
+
+    Return Values: TBool: Symbian error code: If exe(CapsModifier) is found
+                          return KErrNone else other error code will return.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TBool RTestServer::FindExeL( TFileName aModuleName,
+                                TFileName& aPathAndExeModule )
+    {
+    RFs fsSession;  // For the file session handling
+    RFile file;
+
+    // Connect to file server
+	User::LeaveIfError( fsSession.Connect() ); // Start session
+
+    TDriveList drivelist; 
+	User::LeaveIfError( fsSession.DriveList(drivelist) );
+	// A TDriveList (the list of available drives), is an array of 
+	// 26 bytes. Each byte with a non zero value signifies that the 
+	// corresponding drive is available.
+    TInt driveNumber; 
+	TChar driveLetter;
+    
+	for( driveNumber=EDriveA; driveNumber<=EDriveZ; driveNumber++ )
+		{
+		if( !drivelist[driveNumber] ) 
+			{
+			// If drive-list entry is zero, drive is not available
+			continue;
+			}
+        User::LeaveIfError(fsSession.DriveToChar(driveNumber,driveLetter));
+
+        aPathAndExeModule.Zero();
+        aPathAndExeModule.Append( driveLetter );
+
+        aPathAndExeModule.Append( _L(":\\sys\\bin\\") );
+
+        aPathAndExeModule.Append( aModuleName );
+        aPathAndExeModule.Append( _L( ".exe" ) );
+
+        TInt found( KErrNone );
+        found = file.Open( fsSession, aPathAndExeModule, EFileRead );
+        if( found == KErrNone )
+            {
+            // exe(capsmodifier module) is founded.
+            file.Close();
+            fsSession.Close();
+            return KErrNone;
+            }
+        }
+
+    // If exe not found use testserverstarter.exe but capabilities cannot
+    // set.
+    if ( aModuleName.Find( _L( "testscripter_ui_" ) ) == 0 ) 
+    	{
+        aPathAndExeModule.Copy( KDefaultUiExeName );    	
+    	}
+    else
+    	{
+        aPathAndExeModule.Copy( KDefaultExeName );    	
+    	}	
+    file.Close();
+    fsSession.Close();
+ 
+    return KErrNotFound;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestServer
+
+    Method: GetCapsModifierName
+
+    Description: Get caps modifier module name from TestScripter's test
+                 case(config) file.
+
+    Parameters: const TDesC& aConfigFile: in: TestScripter's test case(config)
+                file path and name.
+                TFileName& aCapsModifierName: inout: Parsed caps modifier name.
+
+    Return Values: TInt: Symbian error code: Return KErrNone if caps modifier
+                                             module name is successfully parsed
+                                             or given else other error code
+                                             will return.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt RTestServer::GetCapsModifier( const TDesC& aConfigFile,
+                                        TFileName& aCapsModifierName )
+    {
+    // Create parser
+    CStifParser* parser = NULL;
+    TRAPD( err, parser = CStifParser::NewL( _L(""), aConfigFile ) );
+    if( err != KErrNone )
+        {
+        return err;
+        }
+
+    CleanupStack::PushL( parser );
+
+    // Create section
+    CStifSectionParser* section = NULL;
+    TRAP( err, section = parser->SectionL( KStifSettingsStartTag,
+                                            KStifSettingsEndTag ) );
+    if( err != KErrNone || section == NULL)
+        {
+        CleanupStack::PopAndDestroy( parser );
+        return KErrNotFound;
+        }
+
+    CleanupStack::PushL( section );
+
+    // Create item
+    CStifItemParser* item = NULL;
+    TRAP( err, item = section->GetItemLineL( KCapsModifier ) );
+    if( err != KErrNone || item == NULL )
+        {
+        CleanupStack::PopAndDestroy( section );
+        CleanupStack::PopAndDestroy( parser );
+        return KErrNotFound;
+        }
+    CleanupStack::PushL( item );
+
+    // Get caps modifier module name
+    TPtrC capsModifierName;
+    err = item->GetString( KCapsModifier, capsModifierName );
+    if( err != KErrNone )
+        {
+        CleanupStack::PopAndDestroy( item );
+        CleanupStack::PopAndDestroy( section );
+        CleanupStack::PopAndDestroy( parser );
+        return err;
+        }
+
+    aCapsModifierName.Copy( capsModifierName );
+
+    // Remove optional '.EXE' from the name
+    aCapsModifierName.LowerCase();
+    TParse parse;
+    parse.Set( aCapsModifierName, NULL, NULL );
+
+    if ( parse.Ext() == _L(".exe") )
+        {
+        const TInt len = parse.Ext().Length();
+        aCapsModifierName.Delete ( aCapsModifierName.Length()-len, len );
+        }
+
+    CleanupStack::PopAndDestroy( item );
+    CleanupStack::PopAndDestroy( section );
+    CleanupStack::PopAndDestroy( parser );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: Open
+
+    Description: Create new subsession with the RTestServer server
+
+    Parameters: RTestServer& aServer          :inout: Server
+                TFileName& aIniFile           :in:    Initialization file
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestModule::Open( RTestServer& aServer,
+                                 TFileName& aIniFile
+                               )
+    {
+    TIpcArgs args( &aIniFile, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return CreateSubSession( aServer, ETestModuleCreateSubSession, args );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: Close
+
+    Description: Close a subsession
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestModule::Close()
+    {
+
+    RSubSessionBase::CloseSubSession( ETestModuleCloseSubSession );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: EnumerateTestCases
+
+    Description: Enumerates test cases
+
+    Parameters: TFileName aConfigFile         :in:  Configuration file name
+                TCaseSize& aCount             :out: Package for storing count
+                TRequestStatus& aStatus       :out: Status
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestModule::EnumerateTestCases( TDesC& aConfigFile,
+                                               TCaseSize& aCount,
+                                               TRequestStatus& aStatus
+                                             )
+    {
+    TIpcArgs args( &aConfigFile, &aCount, TIpcArgs::ENothing );
+    SendReceive( ETestModuleEnumerateTestCases, args, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: GetTestCases
+
+    Description: Get test cases
+
+    Parameters: CFixedFlatArray<TTestCaseInfo>& aTestCaseBuffer :Out:    Cases
+
+    Return Values: TInt                             Return value from operation
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestModule::GetTestCases( CFixedFlatArray<TTestCaseInfo>& aTestCaseBuffer )
+    {
+    TIpcArgs args( &aTestCaseBuffer.Des(), TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestModuleGetTestCases, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: ErrorNotification
+
+    Description: Request error notification
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestModule::ErrorNotification( TErrorNotificationPckg& aError,                                           
+                                              TRequestStatus& aStatus )
+    {
+    TIpcArgs args( &aError, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    SendReceive( ETestModuleErrorNotification, args, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: CancelAsyncRequest
+
+    Description: Cancel ongoing request
+
+    Parameters: TInt aReqToCancel             :in:  Request to be cancelled
+
+    Return Values: TInt                             Return value from operation
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestModule::CancelAsyncRequest( TInt aReqToCancel )
+    {
+    TIpcArgs args( aReqToCancel, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestModuleCancelAsyncRequest, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: Open
+
+    Description: create new subsession with the RTestModule
+
+    Parameters: RTestServer& aServer          :in:  Handle to server
+                const TInt aCaseNumber        :in:  Case number
+                const TFileName& aConfig      :in:  Configuration file
+
+    Return Values: TInt                             Return value from operation
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::Open( RTestServer& aServer,
+                                    const TInt aCaseNumber,
+                                    const TFileName& aConfig
+                                  )
+    {
+    TIpcArgs args( aCaseNumber, &aConfig, TIpcArgs::ENothing );
+    return CreateSubSession( aServer, ETestExecutionCreateSubSession, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: Close
+
+    Description: close a subsession
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestExecution::Close()
+    {
+
+    // Close subsession
+    RSubSessionBase::CloseSubSession( ETestExecutionCloseSubSession );
+
+    }
+
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: RunTestCase
+
+    Description: Runs a test case
+
+    Parameters: TFullTestResultPckg& aResult  :out: Case result
+                TRequestStatus& aStatus       :out: Request to be completed
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestExecution::RunTestCase( TFullTestResultPckg& aResult,
+                                           TRequestStatus& aStatus 
+                                         )
+    {
+    TIpcArgs args( &aResult, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    SendReceive( ETestExecutionRunTestCase, args, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: RunTestCase
+
+    Description: Runs a test case
+
+    Parameters: TFullTestResultPckg& aResult  :out: Case result
+                const TDesC& aTestCaseArgs: Test case arguments
+                TRequestStatus& aStatus       :out: Request to be completed
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C void RTestExecution::RunTestCase( TFullTestResultPckg& aResult,
+                                           const TDesC& aTestCaseArgs,
+                                           TRequestStatus& aStatus 
+                                         )
+    {
+    TIpcArgs args( &aResult, &aTestCaseArgs, TIpcArgs::ENothing );
+    SendReceive( ETestExecutionRunTestCase, args, aStatus );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: NotifyProgress
+
+    Description: Notify about test case progress, i.e test case prints.
+
+    Parameters: TTestProgressPckg& aProgress  :out: Print info
+                TRequestStatus& aStatus       :out: Request to be completed
+
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::NotifyProgress( TTestProgressPckg& aProgress,
+                                              TRequestStatus& aStatus 
+                                            )
+    {
+    TIpcArgs args( &aProgress, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    SendReceive( ETestExecutionNotifyProgress, args, aStatus );
+    return KErrNone;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: Pause
+
+    Description: Pauses a test case
+
+    Parameters: None
+
+    Return Values: TInt                             Return value from operation
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::Pause()
+    {
+    TIpcArgs args( TIpcArgs::ENothing, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestExecutionPause, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: Resume
+
+    Description: Resumes a test case
+
+    Parameters: None
+
+    Return Values: TInt                             Return value from operation
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::Resume()
+    {
+    TIpcArgs args( TIpcArgs::ENothing, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestExecutionResume, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: CancelAsyncRequest
+
+    Description: Cancels an asynchronous request.
+
+    Parameters: TInt aReqToCancel             :in:  Request to be cancelled.
+
+    Return Values: TInt                             Return value from operation
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::CancelAsyncRequest( TInt aReqToCancel )
+    {
+    TIpcArgs args( aReqToCancel, TIpcArgs::ENothing, TIpcArgs::ENothing );
+    return SendReceive( ETestExecutionCancelAsyncRequest, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: NotifyEvent
+
+    Description: NotifyEvent is used to receive event requests
+                 from the Test module.
+
+    Parameters: TEventIfPckg& aEvent          :inout:  Event package.
+                TRequestStatus& aStatus       :out:    Request to be completed
+                TInt aError                   :in:     Error from event system
+
+    Return Values: TInt                                Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::NotifyEvent( TEventIfPckg& aEvent,
+                                           TRequestStatus& aStatus,
+                                           TInt aError )
+    {
+    TIpcArgs args( &aEvent, aError, TIpcArgs::ENothing );
+    SendReceive( ETestExecutionNotifyEvent, args, aStatus );
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestModule
+
+    Method: NotifyRemoteCmd
+
+    Description: NotifyRemoteCmd is used to receive RemoteCmd requests
+                 from the Test module.
+
+    Parameters: TRemoteCmdPckg& aRemoteCommand: nout: Remote command's packege.
+                TRemoteCmdType aType: in: Remote type.
+                TRequestStatus& aStatus: inout: Request to be completed
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::NotifyRemoteCmd( TStifCommandPckg& aRemoteCommand,
+                                               TPckg<TInt>& aMsgSizePckg,
+                                               TRequestStatus& aStatus )
+    {
+// Construct message
+    TIpcArgs args( &aRemoteCommand, &aMsgSizePckg, TIpcArgs::ENothing );
+    SendReceive( ETestExecutionNotifyRemoteCmd, args, aStatus );
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: ReadRemoteCmdInfo
+
+    Description: ReadRemoteCmdInfo is used to receive RemoteCmd requests
+                 from the Test module.
+
+    Parameters: TDesC& aMsg :inout: message.
+                TRemoteCommand aType :in: Remote command's type
+                TInt aError: in: Symbian error code
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::ReadRemoteCmdInfo( TDes8& aMsg,
+                                                 TStifCommand aType,
+                                                 TInt aError )
+    {
+    TInt value = 0;
+    if( aError != KErrNone )
+        {
+        value = aError;
+        }
+    else
+        {
+        value = aMsg.Length();
+        }
+
+// Construct message
+    TIpcArgs args( &aMsg, aType, value );
+     // Synchronous method so return a value
+    return SendReceive( ETestExecutionReadRemoteCmdInfo, args );
+    }
+    
+#if 0
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: ReadRemoteCmdInfo
+
+    Description: ReadRemoteCmdInfo is used to receive RemoteCmd requests
+                 from the Test module.
+
+    Parameters: TRebootParamsPckg& aRemoteType :inout: Remote type.
+                TRemoteCommand aType :in: Remote command's type
+                TInt aError: in: Symbian error code
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::ReadRemoteCmdInfo( 
+                                            TRebootParamsPckg& aRemoteType,
+                                            TRemoteCommand aType,
+                                            TInt aError )
+    {
+// Construct message
+    TIpcArgs args( &aRemoteType, aType, aError );
+    // Synchronous method so return a value
+    return SendReceive( ETestExecutionReadRemoteCmdInfo, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: ReadRemoteCmdInfo
+
+    Description: ReadRemoteCmdInfo is used to receive RemoteCmd requests
+                 from the Test module.
+
+    Parameters: TRebootStateParamsPckg& aRemoteState :inout: Remote state.
+                TRemoteCommand aType :in: Remote command's type
+                TInt aError: in: Symbian error code
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::ReadRemoteCmdInfo( 
+                                        TRebootStateParamsPckg& aRemoteState,
+                                        TRemoteCommand aType,
+                                        TInt aError )
+    {
+    // Construct message
+    TIpcArgs args( &aRemoteState, aType, aError );
+    // Synchronous method so return a value
+    return SendReceive( ETestExecutionReadRemoteCmdInfo, args );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: ReadRemoteCmdInfo
+
+    Description: ReadRemoteCmdInfo is used to receive RemoteCmd requests
+                 from the Test module.
+
+    Parameters: TGetRebootStoredParamsPckg& aRemoteStoredState :inout: Stored
+                state.
+                TRemoteCommand aType :in: Remote command's type
+                TInt aError: in: Symbian error code
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::ReadRemoteCmdInfo( 
+                                TGetRebootStoredParamsPckg& aRemoteStoredState,
+                                TRemoteCommand aType,
+                                TInt aError )
+    {
+    // Construct message
+    TIpcArgs args( &aRemoteStoredState, aType, aError );
+    // Synchronous method so return a value
+    return SendReceive( ETestExecutionReadRemoteCmdInfo, args );
+    }
+#endif // 0
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: NotifyCommand
+
+    Description: NotifyCommand is used to receive command requests
+                 from the Test module. DEPRECATED !!
+                 Use NotifyCommand2 instead.
+
+    Parameters: aStifCommandPckg:     command
+                aParam1Pckg:          parameter of command
+                aTestCaseHandlePckg:  handle to test case
+                aStatus:              request status
+                aError:               error
+
+    Return Values: TInt               Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::NotifyCommand(TCommandPckg& /*aCommandPckg*/,
+                                            TBuf8<KMaxCommandParamsLength>& /*aParamsPckg*/,
+                                            TRequestStatus& /*aStatus*/,
+                                            TInt /*aError*/)
+    {
+    /*TIpcArgs args(&aCommandPckg, &aParamsPckg, TIpcArgs::ENothing);
+    SendReceive(ETestExecutionNotifyCommand, args, aStatus);
+    return KErrNone;*/
+    return KErrNotSupported;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: RTestExecution
+
+    Method: NotifyCommand2
+
+    Description: NotifyCommand is used to receive command requests
+                 from the Test module.
+
+    Parameters: aStifCommandPckg:     command
+                aParam1Pckg:          parameter of command
+                aTestCaseHandlePckg:  handle to test case
+                aStatus:              request status
+                aError:               error
+
+    Return Values: TInt               Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt RTestExecution::NotifyCommand2(TCommandPckg& aCommandPckg,
+                                            TDes8& aParamsPckg,
+                                            TRequestStatus& aStatus,
+                                            TInt /*aError*/)
+    {
+    TIpcArgs args(&aCommandPckg, &aParamsPckg, TIpcArgs::ENothing);
+    SendReceive(ETestExecutionNotifyCommand, args, aStatus);
+    return KErrNone;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/TestServerEvent.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,408 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: <This module contains the implementation of xxx 
+* class member functions...>
+*
+*/
+
+// INCLUDE FILES
+#include <e32svr.h>
+#include "TestServerEvent.h"
+#include "TestThreadContainer.h"
+#include "TestServerModuleIf.h"
+#include "Logging.h"
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: TEvent
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+    
+    <description of the functionality 
+    description continues and...
+    continues.>
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+		                     description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+TEvent::TEvent( TThreadId aTestThread ) :
+    TEventIf(),
+	iReq(NULL),
+	iThread( aTestThread ),
+	iEventPending(EFalse),
+	iExecution( NULL )
+	{
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: ~TEvent
+
+    Description: Destructor
+    
+    <description of the functionality 
+    description continues and...
+    continues.>
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+		                     description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/    
+TEvent::~TEvent()
+    {
+    // Removed this call, to be studied @js
+    //Release(); //safety
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: Set
+
+    Description: Set event.
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void TEvent::Set( TEventType aEventType )
+    {
+   	iEventPending = ETrue; 
+    iEventType = aEventType;
+    
+   	if( iReq )
+   		{ 
+   		CompletePendingWait( KErrNone );  
+  		if( iEventType == EIndication )
+			iEventPending = EFalse;    		
+    	} 
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: EventPending
+
+    Description: Check event status.
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+TBool TEvent::EventPending()
+	{
+	if( iEventPending )
+		{
+		// Indication events are signaled only once
+		if( iEventType == EIndication )
+			iEventPending = EFalse;
+		return ETrue;
+		}
+	return EFalse;
+	}        
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: WaitEventPending
+
+    Description: Check waiting status.
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+TBool TEvent::WaitEventPending()
+	{
+	if( iReq )
+	    {
+	    return ETrue;
+	    }
+	else
+	    {
+	    return EFalse;
+	    }
+	}        
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: SetWaitPending
+
+    Description: First phase of waiting.
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+TInt TEvent::SetWaitPending( TRequestStatus* aStatus )
+	{	       
+	if( aStatus )
+	    {
+	    iReq = aStatus;
+	    }
+	else
+	    {
+	    iReq = &iRequestStatus;
+	    }
+    __RDEBUG((_L("Set wait pending(%d) %x"), this, iReq ));
+
+    return KErrNone;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: CompletePendingWait
+
+    Description: Complete pending wait.
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void TEvent::CompletePendingWait( TInt aError )
+	{	       
+	_LIT( KTEvent, "TEvent" );
+	__ASSERT_ALWAYS( iReq, User::Panic( KTEvent, KErrGeneral ) );
+	
+	RThread rt;
+    if( rt.Open( iThread ) == KErrNone )
+        {
+        __RDEBUG( (_L("Complete wait(%d) %x"), this, iReq ) );
+        rt.RequestComplete( iReq, aError );
+	    } 
+    rt.Close();
+    iReq = NULL;
+    
+	}
+	
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: Wait
+
+    Description: Wait event.
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void TEvent::Wait()
+    { 
+
+    User::WaitForRequest( iRequestStatus );
+    // else Wait was already completed from other thread
+    EventPending();
+    } 
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: Release
+
+    Description: Release event. Completes conceivably pending unset.
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+void TEvent::Release()
+    { 
+    if( iReq )
+   		{
+   		// Wait is pending and we received Release, 
+   		// so we complete event with Cancel   
+   		CompletePendingWait( KErrCancel );
+   		iEventPending = ETrue;
+    	} 
+    	
+	if( iExecution )
+		{
+
+		iExecution->UnsetEvent( *this, iUnsetMessage );
+		iExecution = NULL;
+		
+		}
+		
+    } 
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: TEvent
+
+    Method: Unset
+
+    Description: Unset event. Unset blocks until Release is called 
+    			(i.e. iUnsetMessage is compeled from release).
+
+    Parameters:	<arg1>: <in/out/inout>: <accepted values>: <Description>
+    
+    Return Values: <value_1: Description
+		            value_n: Description line 1
+			                 description line 2>
+
+    Errors/Exceptions: <description how errors and exceptions are handled>
+
+    Status: Draft
+	
+-------------------------------------------------------------------------------
+*/
+TInt TEvent::Unset( const RMessage2& aMessage, CTestExecution* aExecution )
+    { 
+
+    if( iExecution )
+        {
+    	return KErrAlreadyExists;
+    	}
+
+    if( aExecution == NULL )
+        {
+    	return KErrArgument;
+    	}
+    
+    iExecution = aExecution;	
+    iUnsetMessage = aMessage;
+    
+    return KErrNone;
+    
+    } 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/TestThreadContainerRunner.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,627 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* CTestThreadContainerRunner class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include "TestThreadContainerRunner.h"
+#include "ThreadLogging.h"
+#include "TestThreadContainer.h"
+#include "TestServer.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: NewL
+
+     Description: NewL is first phase of two-phased constructor.
+
+     NewL is first phase of two-phased constructor.
+
+     Parameters: TThreadId aMainThreadId: in: Main thread id.
+     			 CActiveScheduler* aMainThreadActiveScheduler: in: Pointer to main thread active scheduler.
+     
+     Return Values: Pointer to new CTestThreadContainerRunner object.
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestThreadContainerRunner* CTestThreadContainerRunner::NewL( TThreadId aMainThreadId, 
+		CActiveScheduler* aMainThreadActiveScheduler )
+	{	
+	CTestThreadContainerRunner* self = new(ELeave) CTestThreadContainerRunner();
+	CleanupStack::PushL( self );
+	self->ConstructL( aMainThreadId, aMainThreadActiveScheduler );
+	CleanupStack::Pop( self );
+	
+	return self;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: CTestThreadContainerRunner
+
+     Description: Default constructor.
+
+	 Default constructor.
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainerRunner::CTestThreadContainerRunner()
+:CActive( EPriorityNormal )
+	{
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: ~CTestThreadContainerRunner
+
+     Description: Default destructor.
+
+	 Default destructor.
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainerRunner::~CTestThreadContainerRunner()
+	{
+	Cancel();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: ConstructL
+
+     Description: Second phase of two-phased constructor.
+
+	 Second phase of two-phased constructor.
+
+     Parameters: TThreadId aMainThreadId: in: Main thread id.
+     			 CActiveScheduler* aMainThreadActiveScheduler: in: Pointer to main thread active scheduler.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::ConstructL( TThreadId aMainThreadId, 
+		CActiveScheduler* aMainThreadActiveScheduler )
+	{
+	User::LeaveIfNull( aMainThreadActiveScheduler );
+	
+	iMainThreadId = aMainThreadId;
+
+	iMainThreadActiveScheduler = aMainThreadActiveScheduler;	
+	aMainThreadActiveScheduler->Add( this );
+	
+	iOperationOngoing.CreateLocal( 0 );
+	
+	iTestThreadContainer = NULL;
+	iCurrentOperation = ENone;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: Setup
+
+     Description: Emulates setup part of CTestThreadContainer::ExecutionThread method
+
+	 Setup is performed in main thread.
+
+     Parameters: CTestModuleContainer* aTestModuleContainer: in: Pointer to test CTestModuleContainer
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::Setup( CTestModuleContainer* aTestModuleContainer )
+	{	
+	iTestModuleContainer = aTestModuleContainer;
+	iCurrentOperation = ESetup;
+	SetActive();
+	CompleteRequest();
+	iOperationOngoing.Wait();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: RunOneIteration
+
+     Description: Emulates one iteration of while loop from CTestThreadContainer::ExecutionThread method
+
+	 Iterations is performed in main thread.
+
+     Parameters: None
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::RunOneIteration()
+	{	
+	iCurrentOperation = ERunOneIteration;
+	SetActive();
+	CompleteRequest();
+	iOperationOngoing.Wait();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: TeareDown
+
+     Description: Emulates teare down part of CTestThreadContainer::ExecutionThread method
+
+	 Teare down is performed in main thread.
+
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::TeareDown()
+	{	
+	iCurrentOperation = ETearDown;
+	SetActive();
+	CompleteRequest();
+	iOperationOngoing.Wait();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: CheckSignalFromSuspend
+
+     Description: Checks if operation change signal was signaled from suspend state.
+
+	 Main part of code is executed in main thread.
+
+     Parameters: None
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::CheckSignalFromSuspend()
+	{
+    if ( iSignalFromSuspend )
+        {
+        iSignalFromSuspend = EFalse;
+        iTestThreadContainer->TestComplete( iReturnCode );
+        }
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: IsReusable
+
+     Description: Checks if test thread is reusable.
+
+	 Checks if test thread is reusable.
+
+     Parameters: None
+     
+     Return Values: True if TestThreadContainer is reusable.
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TBool CTestThreadContainerRunner::IsReusable()
+	{
+	return iReusable;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: ExceptionHandler
+
+     Description: Test thread exception handler.
+
+	 Test thread exception handler.
+
+     Parameters: TExcType aType: in: Exception type.
+     
+     Return Values: None
+
+     Errors/Exceptions: None
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::ExceptionHandler ( TExcType aType )
+	{
+	// Kill the current thread, undertaker handles rest
+	RThread current;
+	current.Kill( aType );
+	
+	// This line is never executed, because thread has been killed.
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: RunL
+
+     Description: RunL derived from CActive handles the completed requests.
+
+	 RunL derived from CActive handles the completed requests.
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if one of the called method leavs.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::RunL()
+	{
+	switch( iCurrentOperation )
+		{
+		case ESetup:
+			{
+		    TInt error( KErrNone );
+		    
+		    const TUint32 KAll = 0xFFFFFFFF;
+		#ifndef __HIDE_IPC_V1__ // e.g. 7.0s, 8.0a
+		    RThread currentThread;
+		    currentThread.SetExceptionHandler( ExceptionHandler, KAll );
+		#else // PlatSec used. Thread exception management is part of the User class.
+		    User::SetExceptionHandler( ExceptionHandler, KAll );
+		#endif // __HIDE_IPC_V1__
+
+		    // Create cleanup stack
+//		    CTrapCleanup* tc = CTrapCleanup::New();
+//		    __ASSERT_ALWAYS( tc, Panic( ECreateTrapCleanup ) );
+
+		    iTestThreadContainer = NULL;    
+		    TRAPD( err,
+		    	iTestThreadContainer = CTestThreadContainer::NewL( iTestModuleContainer, 
+		    			iTestModuleContainer->ServerThreadId() );
+		        );    
+		    if( err != KErrNone )
+		        {
+		        Panic( ENullTestThreadContainer );
+		        }
+
+		    // Construct the logger
+		    TName path = _L("C:\\logs\\testframework\\testserver\\");
+		    TFileName name = _L("testserver_thread_");  
+		    name.Append( iTestModuleContainer->TestModuleName() );
+
+		    // Create logger, in Wins use HTML in HW default logger
+		    TLoggerSettings loggerSettings;
+
+		    // Directory must create by hand if test server log wanted
+		    loggerSettings.iCreateLogDirectories = EFalse;
+
+		    loggerSettings.iOverwrite = ETrue;
+		    loggerSettings.iTimeStamp = ETrue;
+		    loggerSettings.iLineBreak = ETrue;
+		    loggerSettings.iEventRanking = EFalse;
+		    loggerSettings.iThreadId = EFalse;
+		    loggerSettings.iHardwareFormat = CStifLogger::ETxt;
+		#ifndef FORCE_STIF_INTERNAL_LOGGING_TO_RDEBUG
+		    loggerSettings.iEmulatorFormat = CStifLogger::EHtml;
+		    loggerSettings.iHardwareOutput = CStifLogger::EFile;
+		    loggerSettings.iEmulatorOutput = CStifLogger::EFile;
+		#else
+		    RDebug::Print( _L( "STIF Test Server's thread logging forced to RDebug" ) );
+		    loggerSettings.iEmulatorFormat = CStifLogger::ETxt;
+		    loggerSettings.iHardwareOutput = CStifLogger::ERDebug;
+		    loggerSettings.iEmulatorOutput = CStifLogger::ERDebug;
+		#endif
+		    loggerSettings.iUnicode = EFalse;
+		    loggerSettings.iAddTestCaseTitle = EFalse;
+
+		    TRAP ( error, iTestThreadContainer->SetThreadLogger( CStifLogger::NewL( path, name,
+		                                                            loggerSettings ) ) );
+
+		    iReusable = ETrue;             // Is test module reusable?
+		    iInitialized = EFalse;         // Is module initialized?
+		    iSignalFromSuspend = EFalse;   // Send signal from suspend state?
+		    
+		    iReturnCode = KErrNone;			
+			}
+			break;
+		case ERunOneIteration:
+			{			
+	        iReturnCode = KErrNone;
+	        
+	        switch ( iTestModuleContainer->OperationType() )
+	            {
+	            // Test module initialisation
+	            case CTestModuleContainer::EInitializeModule:
+	                {
+	                __ASSERT_ALWAYS ( !iInitialized,
+	                                  Panic( EReInitializingTestModule ) );
+
+	                // Initialize module
+	                if ( iTestThreadContainer->InitializeModuleInThread( iModule ) == KErrNone )
+	                    {
+	                    iInitialized = ETrue;
+	                    }
+
+	                iSignalFromSuspend = ETrue;
+	                break;
+	                }
+
+	            // Test case enumeration
+	            case CTestModuleContainer::EEnumerateInThread:
+	                {
+	                __ASSERT_ALWAYS ( iInitialized,
+	                                  Panic( ETestModuleNotInitialized ) );
+	                iReturnCode = iTestThreadContainer->EnumerateInThread();
+
+	                iSignalFromSuspend = ETrue;
+	                break;
+	                }
+
+	            // Free test case enumeration data
+	            case CTestModuleContainer::EFreeEnumerationData:
+	                {
+	                __ASSERT_ALWAYS ( iInitialized,
+	                                  Panic( ETestModuleNotInitialized ) );
+	                iTestThreadContainer->FreeEnumerationDataInThread ();
+	                
+	                iSignalFromSuspend = ETrue;
+	                break;
+	                }
+
+	            // Execute test case
+	            case CTestModuleContainer::EExecuteTestInThread:
+	                {
+	                __ASSERT_ALWAYS ( iInitialized,
+	                                  Panic( ETestModuleNotInitialized ) );
+	                iReturnCode = iTestThreadContainer->ExecuteTestCaseInThread ();
+
+	                iSignalFromSuspend = ETrue;
+	                break;
+	                }
+
+	            // Exiting (i.e test server is unloading)
+	            case CTestModuleContainer::EExit:
+	                {
+	                iReusable = EFalse;
+	                break;
+	                }
+
+	            // Illegal state
+	            default:
+	                {
+	                Panic( EInvalidTestModuleOperation );
+	                }
+	            }
+			}
+			break;
+		case ETearDown:
+			{
+			iTestThreadContainer->DeleteTestModule();
+
+		    // Close handle to module. No function calls to test
+		    // module are possible after this line.
+			iModule.Close();
+
+		    // Delete logger    
+			CStifLogger* threadLogger = iTestThreadContainer->GetThreadLogger();
+			iTestThreadContainer->SetThreadLogger( NULL );
+			delete threadLogger;
+			threadLogger = NULL;
+
+		    // Delete clean-up stack.
+//		    delete tc;
+//		    tc = NULL;
+			
+		    // Operation completed ( = Exit completed )
+		    iTestThreadContainer->TestComplete( KErrNone );
+		    
+		    delete iTestThreadContainer;
+			}
+			break;
+		case ENone:
+			break;
+		}
+		
+	iCurrentOperation = ENone;
+	iOperationOngoing.Signal();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: Panic
+
+     Description: Raises panic.
+
+	 Raises panic.
+
+     Parameters: TInt aReason: in: Panic reason.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::Panic( TInt aReason )
+    {    
+    RDebug::Print( _L("CTestThreadContainer::Panic %d"), aReason );    
+    User::Panic( _L("CTestThreadContainer::Panic"), aReason );    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: DoCancel
+
+     Description: DoCancel derived from CActive handles the Cancel.
+
+	 DoCancel derived from CActive handles the Cancel.
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::DoCancel()
+	{
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunner
+
+     Method: CompleteRequest
+
+     Description: Complets current operation request.
+
+     Complets current operation request, what causes execution of RunL method 
+     in main thread of UITestServerStarter.
+
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunner::CompleteRequest()
+	{
+	iStatus = KRequestPending;
+	TRequestStatus* statusPtr = &iStatus;		            	
+	RThread mainThread;
+	User::LeaveIfError( mainThread.Open( iMainThreadId ) );
+	mainThread.RequestComplete( statusPtr, KErrNone );
+	mainThread.Close();	
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/TestThreadContainerRunnerFactory.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,368 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains the implementation of 
+* CTestthreadContainerRunnerFactory class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <stifinternal/TestThreadContainerRunnerFactory.h>
+#include "TestThreadContainerRunner.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: NewL
+
+     Description: NewL is first phase of two-phased constructor.
+
+	 NewL is first phase of two-phased constructor.
+
+     Parameters: TThreadId aThreadId: in: main thread id.
+     			 CActiveScheduler* aScheduler: in: Pointer to main thread active scheduler.
+     			 CUiEnvProxy* aUiEnvProxy: in: Pointer to UIEnvProxy.
+     
+     Return Values: Pointer to new CTestServerThreadStarter object.
+
+     Errors/Exceptions: Leaves if new or ConstructL leaves.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CTestThreadContainerRunnerFactory* 
+CTestThreadContainerRunnerFactory::NewL( TThreadId aThreadId, CActiveScheduler* aScheduler, CUiEnvProxy* aUiEnvProxy )
+	{
+	CTestThreadContainerRunnerFactory* self = 
+		new(ELeave)CTestThreadContainerRunnerFactory();
+	CleanupStack::PushL( self );
+	self->ConstructL( aThreadId, aScheduler, aUiEnvProxy );
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: CTestThreadContainerRunnerFactory
+
+     Description: Default constructor.
+
+	 Default constructor.
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainerRunnerFactory::CTestThreadContainerRunnerFactory()
+:CActive( EPriorityNormal ),
+iTestThreadContainerRunner( NULL ),
+iOperation( ENone )
+	{
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: ~CTestThreadContainerRunnerFactory
+
+     Description: Default destructor.
+
+	 Default destructor.
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainerRunnerFactory::~CTestThreadContainerRunnerFactory()
+	{
+	Cancel();
+	iOperationEndSemaphore.Close();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: ConstructL
+
+     Description: Second phase of two-phased constructor.
+
+	 Second phase of two-phased constructor.
+
+     Parameters: TThreadId aThreadId: in: main thread id.
+     			 CActiveScheduler* aScheduler: in: Pointer to main thread active scheduler.
+     			 CUiEnvProxy* aUiEnvProxy: in: Pointer to UIEnvProxy.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunnerFactory::ConstructL( TThreadId aThreadId, CActiveScheduler* aScheduler, CUiEnvProxy* aUiEnvProxy )
+	{
+	User::LeaveIfNull( aScheduler );
+	iThreadId = aThreadId;
+	iScheduler = aScheduler;
+	iUiEnvProxy = aUiEnvProxy;
+	
+	TInt ret = iOperationEndSemaphore.CreateLocal( 0 );
+	if ( ret != KErrNone )
+		{
+		User::Leave( ret );
+		}
+	
+	iScheduler->Add( this );
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: DeleteL
+
+     Description: Performs creation of CTestThreadContainerRunner object.
+
+	 Performs creation of CTestThreadContainerRunner object.
+
+     Parameters: CTestThreadContainerRunner* aTestThreadContainerRunner: in: Pointer to 
+     				CTestThreadContainerRunner object which needs to be deleted.
+     
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if one of the called method leavs.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestThreadContainerRunner* CTestThreadContainerRunnerFactory::CreateL()
+	{
+	if ( IsActive() )
+		{
+		User::Panic( _L( "E32USER-CBase" ), 42 );
+		}
+
+	iOperation = ECreate;
+	iStatus = KRequestPending;
+	
+	RThread thread;
+	TInt ret = thread.Open( iThreadId );
+	if ( ret != KErrNone )
+		{
+		User::Leave( ret );
+		}
+	
+	SetActive();
+	TRequestStatus* statusPtr = &iStatus;
+	thread.RequestComplete( statusPtr, KErrNone );
+	thread.Close();
+	iOperationEndSemaphore.Wait();
+
+	return iTestThreadContainerRunner;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: DeleteL
+
+     Description: Performs deletion of CTestThreadContainerRunner object.
+
+	 Performs deletion of CTestThreadContainerRunner object.
+
+     Parameters: CTestThreadContainerRunner* aTestThreadContainerRunner: in: Pointer to 
+     				CTestThreadContainerRunner object which needs to be deleted.
+     
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if one of the called method leavs.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunnerFactory::DeleteL( CTestThreadContainerRunner* aTestThreadContainerRunner )
+	{
+	if ( IsActive() )
+		{
+		User::Panic( _L( "E32USER-CBase" ), 42 );
+		}
+	
+	iOperation = EDelete;
+	iStatus = KRequestPending;
+	
+	RThread thread;
+	TInt ret = thread.Open( iThreadId );
+	if ( ret != KErrNone )
+		{
+		User::Leave( ret );
+		}
+	
+	iTestThreadContainerRunner = aTestThreadContainerRunner;
+	SetActive();
+	TRequestStatus* statusPtr = &iStatus;
+	thread.RequestComplete( statusPtr, KErrNone );
+	thread.Close();
+	iOperationEndSemaphore.Wait();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: RunL
+
+     Description: RunL derived from CActive handles the completed requests.
+
+	 RunL derived from CActive handles the completed requests.
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: Leaves if one of the called method leavs.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunnerFactory::RunL()
+	{
+	switch( iOperation )
+		{
+		case ECreate:
+			{
+			iTestThreadContainerRunner = CTestThreadContainerRunner::NewL( iThreadId, iScheduler );
+			}
+			break;
+		case EDelete:
+			{
+			delete iTestThreadContainerRunner;
+			iTestThreadContainerRunner = NULL;
+			}
+			break;
+		default:
+			{
+			User::Panic( _L("STIFInternalError"), KErrNotFound );
+			}			
+			break;
+		}
+	iOperation = ENone;
+	iOperationEndSemaphore.Signal();
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: DoCancel
+
+     Description: DoCancel derived from CActive handles the Cancel.
+
+	 DoCancel derived from CActive handles the Cancel.
+
+     Parameters: None.
+     
+     Return Values: None.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestThreadContainerRunnerFactory::DoCancel()
+	{	
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+     Class: CTestThreadContainerRunnerFactory
+
+     Method: GetUiEnvProxy
+
+     Description: Gets UIEnvProxy.
+
+     Parameters: None.
+     
+     Return Values: Pointer to UIEnvProxy.
+
+     Errors/Exceptions: None.
+
+     Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CUiEnvProxy* CTestThreadContainerRunnerFactory::GetUiEnvProxy()
+	{
+	return iUiEnvProxy;
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/Testexecution.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4821 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CTestExecution 
+* class member functions. CTestExecution class handles a test 
+* execution subsession specific operations.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+#include "TestEngineClient.h"
+#include "StifTFwIfProt.h"
+#include <stifinternal/TestServerClient.h>
+#include "TestServer.h"
+#include "TestServerModuleIf.h"
+#include "TestServerCommon.h"
+#include "PrintQueue.h"
+#include "TestServerEvent.h"
+#include "TestThreadContainer.h"
+#include "STIFMeasurement.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: NewL
+
+    Description: Returns new CTestExecution instance.
+
+    Parameters: CTestModule* aModuleSession   :in:  "Parent" module
+                TInt aCaseNumber              :in:  Test case number
+                const TFileName& aConfig      :in:  Configuration filename
+
+    Return Values: CTestExecution*                  New instance
+
+    Errors/Exceptions: Function leaves if memory allocation fails or
+                       CTestExecution construction leaves.
+                       Panics is aModuleSession is NULL.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestExecution* CTestExecution::NewL( CTestModule* aModuleSession,
+                                      TInt aCaseNumber, 
+                                      const TFileName& aConfig )
+    {
+
+    __ASSERT_ALWAYS ( aModuleSession, 
+                      CTestServer::PanicServer( ENullModuleSession ) );
+
+    CTestExecution* self=new( ELeave ) CTestExecution;
+    CleanupClosePushL( *self );
+    self->ConstructL( aModuleSession, aCaseNumber, aConfig );
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CTestExecution
+
+    Description: Constructor.
+    Initialises member variables whose default state is not zero or NULL.
+
+    Parameters:  None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CTestExecution::CTestExecution() : 
+    iConfig( 0, 0 ),
+    iTestThreadOpen( EFalse ),
+    iTestThreadFailure( ETestThreadOk )
+    {
+
+    iPrintNotifyAvailable = EFalse;
+    iThreadState = ENotStarted;
+    iRemoteSendAvailable = EFalse;
+    iRemoteReceiveAvailable = EFalse;
+    iEventNotifyAvailable = EFalse;
+    iCommandNotifyAvailable = EFalse;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: ~CTestExecution
+
+    Description: Destructor
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: Panics is threadmutex is taken.
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTestExecution::~CTestExecution()
+    {
+    // Thread must be stopped before CTestExecution can be deleted
+    if( iThreadState == EOnGoing ) 
+		{
+			if( iModuleContainer != NULL )
+				{
+				iModuleContainer->KillThread( KErrCancel );
+				}
+			delete iModuleContainer;
+			iModuleContainer = NULL;
+			CTestServer::PanicServer( EClosingWhileTestRunning );
+		}
+
+    delete iPrintHandler;
+    iPrintHandler = NULL;
+    delete iEventHandler;
+    iEventHandler = NULL;
+    delete iSndHandler;
+    iSndHandler = NULL;
+    delete iRcvHandler;
+    iRcvHandler = NULL;
+    delete iInterferenceHandler;
+    iInterferenceHandler = NULL;
+    delete iMeasurementHandler;
+    iMeasurementHandler = NULL;
+    delete iCommandHandler;
+    iCommandHandler = NULL;
+
+    // Test interference array(Needed cases when test interference thread is
+    // needed to Kill())
+    iSTIFTestInterferenceArray.Reset();
+    iSTIFTestInterferenceArray.Close();
+
+    // Reset test measurement array
+    iMeasurementHandlingArray.Reset();
+    iMeasurementHandlingArray.Close();
+
+    // iPrintQueue must be emptied here, because it items are allocated from server heap
+    delete iPrintQueue;
+    iPrintQueue = NULL;
+
+    // Delete name buffer
+    delete iConfigNameBuffer;
+    iConfigNameBuffer = NULL;
+
+    delete iTestCaseArgs;
+    iTestCaseArgs = NULL;
+        
+    iStateEvents.ResetAndDestroy();
+    iStateEvents.Close();
+
+    iEventArray.ResetAndDestroy();
+    iEventArray.Close();
+
+    // Close mutexes
+    if ( iPrintMutex.Handle() != 0 ) iPrintMutex.Close();
+    if ( iEventMutex.Handle() != 0 ) iEventMutex.Close();
+    if ( iSndMutex.Handle() != 0 ) iSndMutex.Close();
+    if ( iRcvMutex.Handle() != 0 ) iRcvMutex.Close();
+    if ( iInterferenceMutex.Handle() != 0 ) iInterferenceMutex.Close();
+    if ( iMeasurementMutex.Handle() != 0 ) iMeasurementMutex.Close();
+    if ( iCommandMutex.Handle() != 0 ) iCommandMutex.Close();
+
+    // Mutex for testcomplete and cancel operations. Close mutex
+    if ( iTestThreadMutex.Handle() != 0 ) iTestThreadMutex.Close();
+
+    // Close semaphores
+    if ( iPrintSem.Handle() != 0 ) iPrintSem.Close();
+    if ( iEventSem.Handle() != 0 ) iEventSem.Close();
+    if ( iSndSem.Handle() != 0 ) iSndSem.Close();
+    if ( iRcvSem.Handle() != 0 ) iRcvSem.Close();
+    if ( iInterferenceSem.Handle() != 0 ) iInterferenceSem.Close();
+    if ( iMeasurementSem.Handle() != 0 ) iMeasurementSem.Close();
+    //if ( iReceiverSem.Handle() != 0 ) iReceiverSem.Close();
+    if ( iCommandSem.Handle() != 0 ) iCommandSem.Close();
+    
+    iMessageQueue.Close();
+    
+    iTestThread.Close();
+
+    delete iCommandDef;
+    iCommandDef = NULL;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: ConstructL
+
+    Description: Second level constructor
+
+    Parameters: CTestModule* aModuleSession   :in:  "Parent" module
+                TInt aCaseNumber ::           :in:  Test case number
+                const TFileName& aConfig      :in:  Configuration filename
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::ConstructL( CTestModule *aModuleSession,
+                                 TInt aCaseNumber,
+                                 const TFileName& aConfig )
+    {
+
+    // Get the parameters
+    iModuleSession = aModuleSession;
+    iCaseNumber = aCaseNumber;
+
+    // Construct heap buffer for configuration file
+    iConfigNameBuffer = HBufC::NewL( aConfig.Length() );
+    iConfig.Set ( iConfigNameBuffer->Des() );
+    iConfig.Copy ( aConfig );
+
+    // Create mutexes
+    User::LeaveIfError( iPrintMutex.CreateLocal() );
+    User::LeaveIfError( iEventMutex.CreateLocal() );
+    User::LeaveIfError( iSndMutex.CreateLocal() );
+    User::LeaveIfError( iRcvMutex.CreateLocal() );
+    User::LeaveIfError( iInterferenceMutex.CreateLocal() );
+    User::LeaveIfError( iMeasurementMutex.CreateLocal() );
+    User::LeaveIfError( iCommandMutex.CreateLocal() );
+
+    // Mutex for testcomplete and cancel operations. Create mutex
+    User::LeaveIfError( iTestThreadMutex.CreateLocal() );
+
+    // Create semaphores
+    User::LeaveIfError( iPrintSem.CreateLocal( 0 ) );
+    User::LeaveIfError( iEventSem.CreateLocal( 0 ) );
+    User::LeaveIfError( iSndSem.CreateLocal( 0 ) );
+    User::LeaveIfError( iRcvSem.CreateLocal( 0 ) );
+    User::LeaveIfError( iInterferenceSem.CreateLocal( 0 ) );
+    User::LeaveIfError( iMeasurementSem.CreateLocal( 0 ) );
+    //User::LeaveIfError( iReceiverSem.CreateLocal( 0 ) );
+    User::LeaveIfError( iCommandSem.CreateLocal( 0 ) );
+
+    // Create handlers
+    iPrintHandler = CPrintHandler::NewL( *this );
+    iEventHandler = CEventHandler::NewL( *this );
+    iSndHandler  = CSndHandler::NewL( *this );
+    iRcvHandler  = CRcvHandler::NewL( *this );
+    iInterferenceHandler = CInterferenceHandler::NewL( *this );
+    iMeasurementHandler = CMeasurementHandler::NewL( *this );
+    iCommandHandler = CCommandHandler::NewL( *this );
+
+    // Create print queue
+    iPrintQueue = CPrintQueue::NewL();
+
+    // Start print handler   
+    iPrintHandler->StartL();
+    
+    // Start rcv handler
+    iRcvHandler->StartL();
+
+    // Start interference handler
+    iInterferenceHandler->StartL();
+
+    // Start measurement handler
+    iMeasurementHandler->StartL();
+
+    iCommandDef = CCommandDef::NewL();
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: RunTestCase
+
+    Description: Starts to execute test case in separate thread.
+
+    Parameters: const RMessage& aMessage  :in:      Message from client.
+
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::RunTestCase( const RMessage2& aMessage )
+    {
+
+    __TRACE ( KInit, ( _L( "CTestExecution::RunTestCase in" ) ) );
+
+    TInt ret = KErrNone;
+    
+    // Store message to be completed when case is finished
+    iTestExeMessage = aMessage;
+
+    iFullResult.iStartTime.HomeTime();
+
+    delete iTestCaseArgs;
+    iTestCaseArgs = NULL;
+    
+    TInt testCaseArgsLength = iTestExeMessage.GetDesLength( 1 );
+    if ( ( testCaseArgsLength != KErrArgument ) && ( testCaseArgsLength != KErrBadDescriptor ) )
+        {
+        iTestCaseArgs = HBufC::New( testCaseArgsLength );
+        if ( iTestCaseArgs == NULL )
+            {
+            _LIT(KRunError,"Can't allocate memory for test case arguments");
+            __TRACE ( KError, ( CStifLogger::ERed, KRunError() ) );
+            CompleteTestExecution( KErrNone,
+                                   TFullTestResult::ECaseException,
+                                   KErrNoMemory,
+                                   KErrGeneral,
+                                   KRunError );
+            return KErrNone;        
+            }
+            
+        TPtr testCaseArgsPtr( iTestCaseArgs->Des() );
+        TRAP( ret, iTestExeMessage.Read( 1, testCaseArgsPtr ) );
+        if ( ret != KErrNone )
+            {
+            _LIT(KRunError,"Can't read test case arguments");
+            __TRACE ( KError, ( CStifLogger::ERed, KRunError() ) );
+            CompleteTestExecution( KErrNone,
+                                   TFullTestResult::ECaseException,
+                                   ret,
+                                   KErrGeneral,
+                                   KRunError );
+            return KErrNone;
+            }
+        }
+
+    // Get a test module, which executes the test case.
+    // The test module will be freed either when the test case
+    // completes, or the test case is aborted.
+    ret = iModuleSession->GetTestModule( iModuleContainer, iConfig );
+    if ( ret != KErrNone || iModuleContainer == NULL )
+        {
+        _LIT(KRunError,"Can't get test module");
+        __TRACE ( KError, ( CStifLogger::ERed, KRunError() ) );
+        CompleteTestExecution( KErrNone,
+                               TFullTestResult::ECaseException,
+                               ret,
+                               KErrGeneral,
+                               KRunError );
+        return KErrNone;
+        }
+    
+
+    // Thread is created, so all thread specific operations are possible, 
+    // even if thread is not yet resumed, so mark thread to be "Running"
+    SetThreadState ( EOnGoing );
+
+    // Start the test
+    iModuleContainer->SetExecutionSubSession( this );
+    iModuleContainer->RunTestCase( iConfig, iCaseNumber, aMessage );
+
+    __TRACE ( KRunTestCase, ( _L( "CTestExecution::RunTestCase out. Case ongoing" ) ) );
+
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: NotifyPrint
+
+    Description: Handles print request from engine. If print queue is empty,
+                 message is stored to be used later when there is something to
+                 print, otherwise the first queue item is returned and request
+                 completes immediately.
+
+    Parameters: const RMessage& aMessage      :in:  Message from client.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::NotifyPrint( const RMessage2& aMessage )
+    {
+
+    __ASSERT_ALWAYS( iPrintNotifyAvailable == EFalse, 
+                     CTestServer::PanicServer( EPrintQueueBroken ) );
+
+    // Get first item from queue
+    TPrintQueueItem *item = iPrintQueue->Pop();
+
+    if ( item == NULL )
+        {
+
+        // If thread can't print anymore, and queue is empty, then 
+        // complete with Eof, because there will not be any new prints
+        if ( iThreadState == EFinished || iThreadState == ECancelled )
+            {
+            __TRACE ( KPrint, ( _L( "CTestExecution::NotifyPrint to finished thread" ) ) );
+            aMessage.Complete ( KErrEof );
+            }
+        else
+            {
+            // Print request available, do not complete request
+            iNotifyPrintMessage = aMessage;
+            iPrintNotifyAvailable = ETrue;
+            }
+
+        }
+    else
+        {
+        // Construct message
+        TTestProgress progress;
+        progress.iPosition = item->iPriority;
+        progress.iDescription = item->iData1;
+        progress.iText = item->iData2;
+
+        iNotifyPrintMessage = aMessage;
+        // Write message to client space and complete request
+        WritePrint( progress );
+
+        delete item; 
+        }
+
+
+    return KErrNone;
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: DoNotifyPrint
+
+    Description: If print notification available, notification is copied to
+                    client memory space and request is completed.
+                 Else new print queue item is created and appended to print 
+                    queue. If queue is full or memory can't be allocated,
+                    then message will be discarded.
+        
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::DoNotifyPrint()
+    {    
+
+    if ( iPrintNotifyAvailable )
+        {
+        // Write message to client space
+        WritePrint( iProgress );
+        }
+    else
+        {
+
+        TPrintQueueItem *item = 
+            new TPrintQueueItem( iProgress.iPosition, 
+                                 iProgress.iDescription, 
+                                 iProgress.iText );
+
+        if ( item != NULL )
+            {
+            // Item constructed ok, add it to queue
+            if ( iPrintQueue->Push( *item ) != KErrNone )
+                { 
+                // Queue is full, clean-up
+                delete item;
+                }
+            }
+        // else: Could not construct TPrintQueueItem, no free memory.
+        // drop printing            
+        }
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: DoNotifyInterference
+
+    Description: Handles Test Interference thread append and remove operations.
+        
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::DoNotifyInterference()
+    {    
+    // Information for this context => information is in this thread's heap and
+    // if CUndertaker::RunL is called then test interface thread can called
+    // with function call and kill() test interference thread
+
+    // Take information from struct given in 
+    // CTestThreadContainer::AddInterferenceThread or
+    // CTestThreadContainer::RemoveInterferenceThread
+    
+    RThread thread;
+    TInt ret = thread.Open ( iTestInterference.iThreadId );
+    if( ret != KErrNone )
+    	{
+    	RDebug::Print( _L("CTestExecution::DoNotifyInterference %d"), ret );
+        User::Panic( _L("CTestExecution::DoNotifyInterference"), ret );
+    	}
+    
+    if ( iTestInterference.iOperation == TTestInterference::EAppend )
+        {
+        iSTIFTestInterferenceArray.Append( thread );
+        }
+    else if (iTestInterference.iOperation == TTestInterference::ERemove )
+        {
+        // Remove thread from Array.Test interference thread is stopped and killed
+        // successfully
+        for( TInt i = 0; i < iSTIFTestInterferenceArray.Count(); i++ )
+            {
+            if( iSTIFTestInterferenceArray[i].Id() == thread.Id() )
+                {
+                iSTIFTestInterferenceArray.Remove( i );
+                break;
+                }
+            }
+        }
+    else
+        {
+        return;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: DoNotifyMeasurement
+
+    Description: Handles test measurement operations: NewL, Start and Stop.
+        
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::DoNotifyMeasurement()
+    {    
+    // Information for this context => information is in this thread's heap:
+    // From CUndertaker::RunL() or CTestModuleContainer::RunL() method can
+    // handle stop and clean operations if these operations are not done 
+    // before.
+    // Erronous cases(CUndertaker::RunL will be called) or when test case is
+    // executed(CTestModuleContainer::RunL() will be called) there can handle
+    // test measurement stop and clean operation. 
+
+    if( iTestMeasurement.iMeasurementStruct.iMeasurementOperation == 
+                                        CSTIFTestMeasurement::KMeasurementNew)
+        {
+        // Check that same measurement module don't try to create several times
+        // Only one measurement type per test is allowed
+        for( TInt i = 0; i < iMeasurementHandlingArray.Count(); i++ )
+            {
+            if( iMeasurementHandlingArray[i]->iMeasurementModulePtr->MeasurementType() ==
+                        iTestMeasurement.iMeasurementStruct.iMeasurementType )
+                {
+                return KErrAlreadyExists;
+                }
+            }
+
+        TMeasurementHandling* measurementHandling = NULL;
+        measurementHandling = new TMeasurementHandling();
+
+        TBuf<KStifMeasurementTypeLength> modulename;
+        if( iTestMeasurement.iMeasurementStruct.iMeasurementType == 1 )
+            {
+            modulename.Copy( KStifMeasurement01 );
+            }
+        else if( iTestMeasurement.iMeasurementStruct.iMeasurementType == 2 )
+            {
+            modulename.Copy( KStifMeasurement02 );
+            }
+        else if( iTestMeasurement.iMeasurementStruct.iMeasurementType == 3 )
+            {
+            modulename.Copy( KStifMeasurement03 );
+            }
+        else if( iTestMeasurement.iMeasurementStruct.iMeasurementType == 4 )
+            {
+            modulename.Copy( KStifMeasurement04 );
+            }
+        else if( iTestMeasurement.iMeasurementStruct.iMeasurementType == 5 )
+            {
+            modulename.Copy( KStifMeasurement05 );
+            }
+        else if( iTestMeasurement.iMeasurementStruct.iMeasurementType == 6 )
+            {
+            modulename.Copy( KStifMeasurementBappea );
+            }
+        else
+            {
+            __TRACE( KError, (  _L("CTestExecution::DoNotifyMeasurement(): unknown measurement type" ) ) );
+            return KErrArgument;
+            }
+
+        // Loading should work with and without '.dll' extension.
+        TInt r = measurementHandling->iMeasurementModule.Load( modulename );
+        if ( r != KErrNone )
+            {
+            __TRACE( KError, ( CStifLogger::EError, _L("Can't load test measurement module[%S], code = %d"),
+                &modulename, r ) );
+            delete measurementHandling;
+            return KErrNotFound;
+            }
+        else
+            {
+            //Print test measururement module name
+            __TRACE( KInit, (  _L("Loaded test measurement module[%S]"),
+                &modulename ) );
+            }
+
+        // Get pointer to first exported function
+        // Verify that there is function
+        measurementHandling->iMeasurementLibEntry = (CTestMeasurementFactory) measurementHandling->iMeasurementModule.Lookup( 1 );
+        if ( measurementHandling->iMeasurementLibEntry == NULL )
+            {
+            // New instance can't be created
+            __TRACE( KInit, (_L( "Test measurement module instance cannot create." ) ) );
+            measurementHandling->iMeasurementModule.Close();
+            delete measurementHandling;
+            return KErrNotFound;
+            }
+        else
+            {
+            __TRACE ( KInit, ( _L("Pointer to 1st exported received")));
+            }
+
+        CSTIFTestMeasurementImplementation* measurement;
+        measurement = NULL;
+
+        // initialize test measurement module
+        __TRACE ( KVerbose, (_L("Calling 1st exported at 0x%x"), (TUint32) measurementHandling->iMeasurementLibEntry ));
+        TRAPD ( err, measurement = (*measurementHandling->iMeasurementLibEntry)( 
+                            iTestMeasurement.iMeasurementStruct.iConfigurationInfo, iTestMeasurement.iMeasurementStruct.iMeasurementType ) );
+
+         // Handle leave from test module
+        if ( err != KErrNone )
+            {
+            __TRACE (KError, ( CStifLogger::EError, _L( "Leave when calling 1st exported function, code %d"), err ) );
+            delete measurementHandling;
+            return err;
+            }
+        else if ( measurementHandling->iMeasurementLibEntry == NULL )     // Handle NULL from test measurement
+            {
+            __TRACE (KError, ( CStifLogger::EError, _L( "NULL pointer received when constructing test measurement module" ) ) );
+            delete measurementHandling;
+            // Set error codes
+            return KErrNoMemory;
+            }
+        else
+            {
+            measurementHandling->iMeasurementModulePtr = measurement;
+            __TRACE (KInit, (_L("Entrypoint successfully called, Measurement module instance at 0x%x"),
+                (TUint32)measurementHandling->iMeasurementLibEntry ) );
+            }
+        iMeasurementHandlingArray.Append( measurementHandling );
+        } // End of NewL operations
+
+    else if( iTestMeasurement.iMeasurementStruct.iMeasurementOperation == 
+                                        CSTIFTestMeasurement::KMeasurementStart)
+        {
+        for( TInt i = 0; i < iMeasurementHandlingArray.Count(); i++ )
+            {
+            if( iMeasurementHandlingArray[i]->iMeasurementModulePtr->MeasurementType() == iTestMeasurement.iMeasurementStruct.iMeasurementType )
+                {
+                return iMeasurementHandlingArray[i]->iMeasurementModulePtr->Start();
+                }
+            }
+
+        }
+    else if( iTestMeasurement.iMeasurementStruct.iMeasurementOperation == 
+                                        CSTIFTestMeasurement::KMeasurementStop)
+        {
+        for( TInt i = 0; i < iMeasurementHandlingArray.Count(); i++ )
+            {
+            if( iMeasurementHandlingArray[i]->iMeasurementModulePtr->MeasurementType() == iTestMeasurement.iMeasurementStruct.iMeasurementType )
+                {
+                TInt stop_ret = iMeasurementHandlingArray[i]->iMeasurementModulePtr->Stop();
+                delete iMeasurementHandlingArray[i];
+                iMeasurementHandlingArray.Remove(i);
+                return stop_ret;
+                }
+            }
+        }
+    else 
+        {
+        __TRACE (KError, ( CStifLogger::EError, _L("CTestExecution::DoNotifyMeasurement(): Not supported operation") ) );
+        return KErrNotSupported;
+        }
+    
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: WritePrint
+
+    Description: Writes print notification to client memory space.                 
+        
+    Parameters: const TInt aPriority          :in:  Priority
+                const TStifInfoName& aDes         :in:  Description
+                const TName& aBuffer          :in:  Value
+    
+    Return Values: TInt                             Return value from message write
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::WritePrint( TTestProgress& aProgress )
+    {
+
+    TTestProgressPckg progressPckg( aProgress );
+ 
+    // Write message to client space    
+    TRAPD( res, iNotifyPrintMessage.WriteL( 0, progressPckg ) );
+
+    iPrintNotifyAvailable = EFalse;
+
+    // Complete request with possible error code
+    iNotifyPrintMessage.Complete( res );
+
+    return res;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: NotifyEvent
+
+    Description: Handles event request from engine. 
+
+    ESetEvent and EUnsetEvent change event status. EEnable enables 
+    event notify.
+
+    Parameters: const RMessage& aMessage      :in:  Message from client.
+                    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::NotifyEvent( const RMessage2& aMessage )
+    {   
+
+    TEventIf event;
+    TEventIfPckg eventPckg( event );
+    
+    TRAPD( res, aMessage.ReadL( 0, eventPckg ) );
+
+    if( res != KErrNone )
+        {
+        __TRACE( KError, ( _L( "CTestExecution::NotifyEvent: ReadL failed" ) ));
+        return res;
+        }
+    
+    switch( event.Type() )
+        {
+        case TEventIf::ESetEvent: 
+            {
+            TInt ind = 0;
+            TInt count = iEventArray.Count();
+            for( ind=0; ind < count; ind++ )
+                {
+                if( iEventArray[ind]->Name() == event.Name() )
+                    {
+                    __TRACE( KMessage, ( _L( "CTestExecution::NotifyEvent(%d): SetEvent %S ( count %i )" ), 
+                        this, &event.Name(), count ) );
+                    TEventIf::TEventType etype = TEventIf::EIndication;
+                    // To get state events working with testcombiner
+                    if( ( event.EventType() == TEventIf::EState ) ||                            
+                        ( iEventArray[ind]->EventType() == TEventIf::EState ) )
+                        {
+                        etype = TEventIf::EState;
+                        }
+                    iEventArray[ind]->Set( etype );
+                    }
+                }
+            }
+            break;
+        case TEventIf::EUnsetEvent:
+            { 
+            return UnsetEvent( event, aMessage );
+            }
+        case TEventIf::EEnable:
+            {
+            // Store event message
+            iNotifyEventMessage = aMessage;
+            iEventNotifyAvailable = ETrue;
+            TInt errorFromPreviousCmd =  aMessage.Int1();
+
+            __TRACE( KMessage, ( _L( "CTestExecution::NotifyEvent: enable (%d) notify %d" ), 
+                errorFromPreviousCmd, this ) );
+
+            // Complete previous Event command
+            CompleteEvent( errorFromPreviousCmd );    
+            iEventHandler->StartL();
+            
+            // iNotifyEventMessage is completed from DoNotifyEvent
+            return KErrNone; 
+            }
+        
+        default:
+            __TRACE( KError, ( _L( "CTestExecution::NotifyEvent: Unknown command %i" ), 
+                event.Type() ));
+            return KErrArgument;
+        }
+
+    __TRACE( KMessage, ( _L( "CTestExecution::NotifyEvent(%d): Done" ), this ) );
+
+    aMessage.Complete( KErrNone );
+    //User::After(1000); //Stif-95 This pause is needed to let Info::TestFrameworkEngine thread
+                       //get some processor time and run exactly at this moment (by calling
+                       //CTestEventController::EventCallBack). When Stif is focused on the screen,
+                       //there is no problem if this line is absent, however when another
+                       //application (like screen saver) is focused this is required.
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: DoNotifyEvent
+
+    Description: Forward event request.
+        
+    Parameters: None
+   
+    Return Values: None
+
+    Errors/Exceptions: Panics if event array can't be created
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::DoNotifyEvent()
+    {
+    
+    TInt ret = KErrNone;
+        
+    switch( iEventDef.iEvent.Type() )
+        {
+        case TEventIf::EReqEvent:
+            {
+            __TRACE( KMessage, 
+                ( _L( "CTestExecution::DoNotifyEvent(%d): ReqEvent %S" ), 
+                    this, &iEventDef.iEvent.Name() ) );
+            ret = RequestEvent( iEventDef.iEvent );
+            // If error, return error, 
+            // otherwise proceed with sending information to engine
+            if( ret != KErrNone )
+                {
+                iEventHandler->StartL();
+                return ret;
+                }
+            }
+            break;
+        case TEventIf::EWaitEvent:
+        case TEventIf::ESetWaitPending:
+            {
+            __TRACE( KMessage, 
+                ( _L( "CTestExecution::DoNotifyEvent(%d): WaitEvent %S" ), 
+                    this, &iEventDef.iEvent.Name() ) );
+            // We return from here, i.e. nothing is sent to engine
+            ret = WaitEvent( iEventDef.iEvent, iEventDef.iStatus );
+            iEventHandler->StartL();
+            return ret;
+            }
+        // Add state events to internal array  
+        case TEventIf::ESetEvent: 
+        case TEventIf::EUnsetEvent:
+            {
+            __TRACE( KMessage, 
+                ( _L( "CTestExecution::DoNotifyEvent(%d): Set/UnsetEvent %S" ), 
+                    this, &iEventDef.iEvent.Name() ) );
+            EventStateChange( iEventDef.iEvent );
+            }
+            break;
+        case TEventIf::ERelEvent:
+            // This is handled later
+            __TRACE( KMessage, 
+                ( _L( "CTestExecution::DoNotifyEvent(%d): RelEvent %S" ), 
+                    this, &iEventDef.iEvent.Name() ) );
+            break;
+        default:
+            iEventHandler->StartL();
+            return KErrArgument;
+        }
+    
+    // Construct message
+    TEventIfPckg eventPckg( iEventDef.iEvent );
+
+    // Write message to client space
+    TRAPD( res, iNotifyEventMessage.WriteL( 0, eventPckg ) );
+
+    if( res != KErrNone )
+        {
+        __TRACE( KError, ( _L( "CTestExecution::DoNotifyEvent: WriteL failed" ) ) );
+        ret = res;
+        }
+    // Complete request
+    // Complete with WriteL result
+    // MUST be done before ERelEvent
+    iEventNotifyAvailable = EFalse;
+    iNotifyEventMessage.Complete( res );
+    User::After(1000); //Stif-95 This pause is needed to let Info::TestFrameworkEngine thread
+                       //get some processor time and run exactly at this moment (by calling
+                       //CTestEventNotifier::RunL). When Stif is focused on the screen,
+                       //there is no problem if this line is absent, however when another
+                       //application (like screen saver) is focused this is required.
+
+    if( iEventDef.iEvent.Type() == TEventIf::ERelEvent )
+        {
+        ret = ReleaseEvent( iEventDef.iEvent );
+        if( ret != KErrNone )
+            {
+            // If error, return immediately
+            return ret;
+            }
+        }
+
+    __TRACE( KMessage, ( _L( "CTestExecution::DoNotifyEvent(%d): Done" ), this ) );
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: RequestEvent
+
+    Description: Handles TestModule event requests. 
+        
+    Parameters: const TEventIf& aEvent: in: Event requested  
+    
+    Return Values: TInt: Success/Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/    
+TInt CTestExecution::RequestEvent( TEventIf& aEvent )
+    {
+
+    // Requested events are added to iEventArray
+    // There can be multiple simultaneous requests for the same event                    
+    TEvent* event = new TEvent( iTestThreadId );    
+    if( !event )
+        {
+        return KErrNoMemory;
+        }
+    event->Copy( aEvent );
+    if( iEventArray.Append( event ) != KErrNone )
+        {
+        delete event;
+        return KErrNoMemory;
+        }
+        
+    __TRACE( KMessage,( _L( "CTestExecution::DoNotifyEvent: Req added %S ( count %i )" ), 
+         &aEvent.Name(), iEventArray.Count() ));
+    
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: WaitEvent
+
+    Description: Handles TestModule event waits. Waiting is implemented here 
+                and completed in NotifyEvent    
+
+        
+    Parameters: const TEventIf& aEvent: in: Event wait  
+    
+    Return Values: TInt: Success/Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/    
+TInt CTestExecution::WaitEvent( TEventIf& aEvent, TRequestStatus* aStatus )
+    {
+      
+    // Get first "free" event entry from requested events
+    TInt ind = 0;
+    TInt count = iEventArray.Count();
+    TEvent* event = NULL;
+    for( ind=0; ind < count; ind++ )
+        {
+        if( ( iEventArray[ind]->Name() == aEvent.Name() ) &&
+            ( iEventArray[ind]->WaitEventPending() == EFalse ) )
+            {
+            // Found event with correct name and one that is still free
+            // i.e. nobody is waiting for it.
+            event = iEventArray[ind];
+            if( aEvent.Type() == TEventIf::EWaitEvent )
+                {
+                // For EWaitEvent we complete immediately if event is pending
+                if( event->EventPending() )
+                    {
+                    // Event was already pending, so we may return immediately
+                    if( aStatus )
+                        {
+                        TestThreadRequestComplete( aStatus, KErrNone );
+                        }
+                    return KErrNone;           
+                    }
+                }
+            }
+        }
+    if( event == NULL )
+        {
+        // Event is not in the iEventArray, 
+        // so event is not currently requested
+        return KErrNotFound;
+        }
+        
+    __TRACE( KMessage,( _L( "CTestExecution::DoNotifyEvent: Waiting %S ( count %i )" ), 
+        &aEvent.Name(), count ));
+    
+    // Event is not pending so we have to wait for it
+    // Set wait pending            
+    TInt ret = event->SetWaitPending( aStatus );
+    // event cannot be freed by the test module, 
+    // because it is waiting the event, 
+
+    if( ( aStatus == NULL ) &&
+        ( ret == KErrNone ) &&
+        ( aEvent.Type() == TEventIf::EWaitEvent ) ) 
+        {
+        // This is synchronous wait
+        // Go waiting, completed from set event            
+        event->Wait();
+        }
+
+    return ret;
+    
+    } 
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: ReleaseEvent
+
+    Description: Handles TestModule event releases. 
+        
+    Parameters: const TEventIf& aEvent: in: Event released  
+    
+    Return Values: TInt: Success/Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/   
+TInt CTestExecution::ReleaseEvent( TEventIf& aEvent )
+    {
+    
+    // Get last event entry from requested events
+    TInt ind = 0;
+    TInt freeFound = 0;
+    TInt eventIndex = 0;
+    TInt count = iEventArray.Count();
+    for( ind=0; ind < count; ind++ )
+        {
+        if( iEventArray[ind]->Name() == aEvent.Name() )
+            {
+            if( iEventArray[ind]->WaitEventPending() == EFalse )
+                {
+                freeFound++;
+                eventIndex = ind;
+                }
+            }
+        }
+
+    if( freeFound == 0 )
+        {
+        return KErrNotFound;
+        }
+    __TRACE( KMessage,( 
+        _L( "CTestExecution::DoNotifyEvent: Release event %S ( count %i )" ), 
+            &aEvent.Name(), iEventArray.Count() ));
+
+    TEvent* event = iEventArray[eventIndex];
+    iEventArray.Remove( eventIndex );
+    // Release and free event entry
+    event->Release(); 
+
+    // Delete used event entry
+    delete event;
+    
+    return KErrNone;
+}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: UnsetEvent
+
+    Description: Handles TestModule event unsets. 
+        
+    Parameters: const TEventIf& aEvent: in: Event unset  
+    
+    Return Values: TInt: Success/Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::UnsetEvent( TEventIf& aEvent, const RMessage2& aMessage )
+    {
+    
+    TInt ret = KErrNone;
+    TInt ind = 0;
+    TInt count = iEventArray.Count();
+    TBool activeEventReq = EFalse;
+    for( ind=0; ind < count; ind++ )
+        {
+        if( iEventArray[ind]->Name() == aEvent.Name() )
+            {
+             __TRACE( KMessage, ( 
+                _L( "CTestExecution::NotifyEvent(%d): UnsetEvent %S ( count %i )" ), 
+                this, &aEvent.Name(), count ) );
+                
+            ret = iEventArray[ind]->Unset( aMessage, this );
+            if( ret == KErrNone )
+                {
+                activeEventReq = ETrue;
+                }
+            break;
+            }
+        }
+    if( activeEventReq )
+        {
+        // Unset is completed by release   
+        return KErrNone;
+        }
+        
+    // No pending requests or error from unset
+    aMessage.Complete( ret );
+    
+    return KErrNone;
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: EventStateChange
+
+    Description: Handles event setting and unsetting. Saves status of
+                state events to enable unsetting of set state events when 
+                killing the testcase abnormally.
+        
+    Parameters: const TEventIf& aEvent: in: Event set/unset  
+    
+    Return Values: TInt: Success/Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/   
+TInt CTestExecution::EventStateChange( TEventIf& aEvent )
+    {
+    
+    TInt ret = KErrNotFound;
+    if( aEvent.EventType() == TEventIf::EState )
+        {
+        
+        TInt count = iStateEvents.Count();
+        TInt index = 0;
+        for(; index < count; index++ )   
+            {
+            TPtrC name = *(iStateEvents[index]);
+            if( name == aEvent.Name() )
+                {
+                break;
+                }
+            } 
+            
+                
+        if( aEvent.Type() == TEventIf::ESetEvent )
+            {
+            if( index < count )
+                {
+                ret = KErrAlreadyExists;
+                }
+            else
+                {
+                // add event to iStateEvents
+                HBufC* name = aEvent.Name().Alloc();
+                if( name == NULL )
+                    {
+                    ret = KErrNoMemory;
+                    }
+                else if( iStateEvents.Append( name ) != KErrNone )
+                    {
+                    delete name;
+                    ret = KErrNoMemory;
+                    }
+                else
+                    {
+                    ret = KErrNone;
+                    }
+                }                
+            }
+        else if( aEvent.Type() == TEventIf::EUnsetEvent )
+            {
+            if( index == count )
+                {
+                ret = KErrNotFound;
+                }
+            else
+                {
+                ret = KErrNone;
+                delete iStateEvents[index];
+                iStateEvents.Remove( index );
+                }
+            }
+        }
+    
+    return ret;
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelEvent
+
+    Description: Cancels pending event request.
+        
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::CancelEvent()
+    {
+    
+    TInt ret = KErrNotFound;
+
+    __TRACE( KMessage, ( _L( "CTestThreadContainer::CancelEvent(%d): %S [%p]" ), 
+            iEventDef.iEvent.Type(), &iEventDef.iEvent.Name(), iEventDef.iStatus ) );
+
+    switch( iEventDef.iEvent.Type() )
+        {
+        case TEventIf::EReqEvent:
+        case TEventIf::ERelEvent:
+        case TEventIf::ESetEvent:
+        case TEventIf::EUnsetEvent:   
+            CompleteEvent( KErrCancel );  
+            break;
+        case TEventIf::EWaitEvent:
+        case TEventIf::ESetWaitPending:
+            {
+            // Get waited event entry from requested events
+            TInt ind = 0;
+            TInt count = iEventArray.Count();
+            for( ind=0; ind < count; ind++ )
+                {
+                if( ( iEventArray[ind]->Name() == iEventDef.iEvent.Name() ) &&
+                    ( iEventArray[ind]->WaitEventPending() != EFalse ) &&
+                    ( iEventArray[ind]->RequestStatus() == iEventDef.iStatus ) )
+                    {
+                    TEvent* event = iEventArray[ind];
+                    // Found event with correct name and one that is waited.
+                    event->CompletePendingWait( KErrCancel ); 
+                    ret = KErrNone;
+                    break;
+                    }
+                }
+            if( ret != KErrNone )
+                {
+                // Request has been already completed, not handled 
+                // by ActiveScheduler yet.
+                // DoCancel will do the job, don't worry.
+                __TRACE( KError, ( _L( "CTestThreadContainer::CancelEvent(%d): %S, not found 2" ), 
+                    iEventDef.iEvent.Type(), &iEventDef.iEvent.Name() ) ); 
+                }
+            }
+            break;
+        default:
+            CTestServer::PanicServer( EUnknownEventCmd );
+            break;
+        }
+        
+    // Synchonize
+    iEventHandler->StartL();
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: NotifyRemoteCmd
+
+    Description: Handles the first phase of the RemoteCmd request from engine.
+
+    Parameters: const RMessage& aMessage: in: Message from client.
+                    
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::NotifyRemoteCmd( const RMessage2& aMessage )
+    {   
+
+    // Store RemoteCmd message
+    // and the length buffer address
+    iNotifyRemoteCmdMessage = aMessage;
+    iRemoteSendAvailable = ETrue;
+    iSndHandler->StartL();
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: DoRemoteReceive
+
+    Description: Enable remote receive.
+    
+    Parameters: None 
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::DoRemoteReceive()
+    {    
+
+    switch( iRcvCmdDef.iCommand )
+        {
+        case EStifCmdReceive:          // "Receive"
+            {
+            // @js If there's pointer in array, we'll send it down
+            if(iMessageQueue.Count() > 0)
+                {
+                HBufC8 * buf =  iMessageQueue[0];
+                iRcvCmdDef.iParam.aRemoteMsgRef->Copy( iMessageQueue[0]->Des() );
+                iMessageQueue.Remove(0);
+                delete buf; 
+                __TRACE( KMessage, 
+                        (_L("CTestExecution::ReadRemoteCmdInfo: complete receive 0x%x"), 
+                            iRcvCmdDef.iStatus ));
+                       
+                 // calls the TestCombiner's CRemoteReceiver::RunL()
+                 TestThreadRequestComplete( iRcvCmdDef.iStatus, KErrNone );
+                }
+            else
+                {
+                iRemoteReceiveAvailable = ETrue;            
+                }
+
+            break;
+            }
+        case EStifCmdReceiveCancel:
+            if( iRemoteReceiveAvailable )
+                {
+                iRemoteReceiveAvailable = EFalse;
+                TestThreadRequestComplete( iRcvCmdDef.iStatus, KErrCancel );
+                }                
+            break;
+        default:
+            CTestServer::PanicServer( EUnknownRemoteCmd );
+            break;
+        }
+    // Signal test thread
+    iRcvHandler->StartL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: DoRemoteSend
+
+    Description: Send remote messages.
+    
+    Parameters: None 
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::DoRemoteSend()
+    {  
+    switch( iCmdDef.iCommand )
+        {  
+        case EStifCmdSend:             // "Send"
+        case EStifCmdReboot:           // "Send"
+        case EStifCmdStoreState:       // "Send"
+        case EStifCmdGetStoredState:   // "Receive, this must be done with two phase"
+        case EStifCmdMeasurement:      // "Receive, this must be done with two phase"
+            {
+            if( iRemoteSendAvailable )
+                {
+                TInt ret = KErrNone;
+                TPckg<TStifCommand> remoteCommandPckg( iCmdDef.iCommand );
+
+                // Start first phase of the writing message to client space
+                TRAP( ret, 
+                    iNotifyRemoteCmdMessage.WriteL( 0, remoteCommandPckg ) );
+
+                if( ret != KErrNone )
+                    {
+                    __TRACE( KError, ( _L( "CTestExecution::DoRemoteSend: WriteL failed" ) ) );
+                    }
+                TPckg<TInt> lenPckg( iCmdDef.iLen );
+
+                TRAP( ret, 
+                    iNotifyRemoteCmdMessage.WriteL( 1, lenPckg ) );
+
+                if( ret != KErrNone )
+                    {
+                    __TRACE( KError, ( _L( "CTestExecution::DoRemoteSend: WriteL failed" ) ) );
+                    }
+
+                // Complete request
+                // Complete with WriteL result
+                // CTestRemoteCmdNotifier::RunL() will called
+                iRemoteSendAvailable = EFalse;
+                iNotifyRemoteCmdMessage.Complete( ret );
+                break;
+                }
+            }
+            TestThreadRequestComplete( iCmdDef.iStatus, KErrNotSupported );
+            break;
+        default:
+            CTestServer::PanicServer( EUnknownRemoteCmd );
+            break;
+        }
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: ReadRemoteCmdInfo
+
+    Description: Handles the second phase of the RemoteCmd request from engine.
+
+    Parameters: const RMessage& aMessage: in: Message from client.
+                    
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::ReadRemoteCmdInfo( const RMessage2& aMessage )
+    {   
+    
+    TInt ret( KErrNone );
+    TInt completeSend = EFalse;
+    TInt returnedErrorCode = KErrNone;
+    TInt len = 0;
+    TInt value( aMessage.Int2() );
+    if( value < 0 )
+        {
+        returnedErrorCode = value;
+        }
+    else
+        {
+        len = value;
+        }
+  
+    switch( aMessage.Int1() )
+        {
+        case EStifCmdReceive:              // "Receive"
+            {
+
+                if( len <= 0 )
+                    {
+                    __TRACE( KError, 
+                        (_L("CTestExecution::ReadRemoteCmdInfo: empty message")));
+                    ret = KErrGeneral;
+                    break;
+                    }
+                if( iRcvCmdDef.iParam.aRemoteMsgRef->MaxLength() < len )
+                    {
+                    __TRACE( KError, 
+                        (_L("CTestExecution::ReadRemoteCmdInfo: message overflow")));
+                    ret = KErrGeneral;
+                    break;
+                    }
+
+                HBufC8* buf = HBufC8::New( len );
+                if( buf == NULL )
+                    { 
+                    ret = KErrNoMemory;
+                    break;
+                    }
+                TPtr8 tmp = buf->Des();
+                // Read message from client space
+                TRAP( ret, aMessage.ReadL( 0, tmp ) );
+
+                
+                if( ret != KErrNone )
+                    {
+                    __TRACE( KError, 
+                        (_L("CTestExecution::ReadRemoteCmdInfo: ReadL failed")));
+                    break;
+                    }
+                    
+                if( iRemoteReceiveAvailable )
+                // @js Checking moved here
+                    {                                   
+                    iRcvCmdDef.iParam.aRemoteMsgRef->Copy( buf->Des() );
+                    delete buf;
+                
+                    __TRACE( KMessage, 
+                        (_L("CTestExecution::ReadRemoteCmdInfo: complete receive 0x%x"), 
+                            iRcvCmdDef.iStatus ));
+                    // calls the TestCombiner's CRemoteReceiver::RunL()
+                    TestThreadRequestComplete( iRcvCmdDef.iStatus, ret );
+                    
+                    iRemoteReceiveAvailable = EFalse;
+                    }
+                else
+                // @js Adding buf to RPointerArray, handling it in DoRemoteReceive function
+                    {
+                   iMessageQueue.Append( buf );
+                    } 
+                
+            break;
+            }
+        case EStifCmdSend:                 // "Send"
+            {
+            HBufC8* buf = HBufC8::New( iCmdDef.iParam.aRemoteMsgConstRef->Length() );
+            if( buf == NULL )
+                { 
+                ret = KErrNoMemory;
+                break;
+                }
+            TPtr8 tmp = buf->Des();
+            tmp.Copy( *iCmdDef.iParam.aRemoteMsgConstRef );
+            // Second phase of the writing. Write information to the Engine.
+            TRAP( ret, aMessage.WriteL( 0, tmp ) );
+
+            delete buf;
+            
+            if( ret != KErrNone )
+                {
+                __TRACE( KError, ( _L( "CTestExecution::ReadRemoteCmdInfo: WriteL failed" ) ) );
+                }
+            completeSend = ETrue;
+            break;
+            }
+        case EStifCmdReboot:               // "Send"
+            {
+            TRebootParamsPckg remoteTypePckg( *iCmdDef.iParam.aRebootType );
+
+            // Second phase of the writing. Write information to the Engine.
+            TRAP( ret, aMessage.WriteL( 0, remoteTypePckg ) );
+
+            if( ret != KErrNone )
+                {
+                __TRACE( KError, ( _L( "CTestExecution::ReadRemoteCmdInfo: WriteL failed" ) ) );
+                }
+            // Because Reboot must block...Don't complete, so now we wait for
+            // ever phone booting operation !!!!!
+            break;
+            }
+        case EStifCmdStoreState:          // "Send"
+            {
+            TRebootStateParamsPckg remoteStatePckg( *iCmdDef.iParam.aRebootState );
+
+            // Second phase of the writing. Write information to the Engine.
+            TRAP( ret, aMessage.WriteL( 0, remoteStatePckg ) );
+
+            if( ret != KErrNone )
+                {
+                __TRACE( KError, ( _L( "CTestExecution::ReadRemoteCmdInfo: WriteL failed" ) ) );
+                }
+            // Completed from EStifCmdRebootProceed
+            break;
+            }
+        case EStifCmdMeasurement:   // "Receive"
+            {
+            TGetMeasurementOptions getMeasurementOptions;
+            TGetMeasurementOptionsPckg measurementParamsPckg( getMeasurementOptions );
+
+            // Read message from client space
+            TRAP( ret, aMessage.ReadL( 0, measurementParamsPckg ) );
+
+            if( ret != KErrNone )
+                {
+                __TRACE( KError, ( _L( "CTestExecution::ReadRemoteCmdInfo: ReadL failed" ) ) );
+                }
+            iCmdDef.iParam.aMeasurementOption->iOptions = getMeasurementOptions.iOptions;
+
+            completeSend = ETrue;
+            break;
+            }
+        case EStifCmdGetStoredState:   // "Receive"
+            {
+            TGetRebootStoredParams getRebootStoredParams;
+            TGetRebootStoredParamsPckg rebootStoredParamsPckg( getRebootStoredParams );
+
+            // Read message from client space
+            TRAP( ret, aMessage.ReadL( 0, rebootStoredParamsPckg ) );
+
+            if( ret != KErrNone )
+                {
+                __TRACE( KError, ( _L( "CTestExecution::ReadRemoteCmdInfo: ReadL failed" ) ) );
+                }
+            iCmdDef.iParam.aRebootStoredRef->iCode = getRebootStoredParams.aCode;
+            iCmdDef.iParam.aRebootStoredRef->iName = getRebootStoredParams.aName;
+
+            completeSend = ETrue;
+            break;
+            }
+        case EStifCmdRebootProceed:          
+            {
+            completeSend = ETrue; // Complete EStifCmdStoreState
+            }
+            break;
+        default:
+            {
+            iModuleSession->PanicClient( EUnknownRemoteCmd, aMessage );
+            break;
+            }
+        }
+    // Complete request with ret
+    aMessage.Complete( ret ); 
+
+    if( completeSend )
+        {
+        // Calls the TestCombiner's CRemoteReceiver::RunL() and
+        // returns error code to test module.
+        TestThreadRequestComplete( iCmdDef.iStatus, returnedErrorCode );
+        }
+        
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: Pause
+
+    Description: Pauses a test case
+
+    Only ongoing tests can be paused. If test is not ongoing, then
+    function does nothing.
+
+    Parameters: const RMessage& aMessage      :in:  Message from client.
+    
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::Pause( const RMessage2& aMessage )
+    {
+
+    __TRACE ( KThreadOperation, ( _L( "CTestExecution::Pause" ) ) );
+
+    TInt completionCode = KErrNone;
+
+    // Note that it is allowed to suspend already suspended thread, so
+    // there is no need for states to verify that thread is really in
+    // resumed state.
+    switch ( iThreadState )
+        {
+        case EOnGoing:
+            completionCode = iModuleContainer->PauseThread();
+            break;
+
+        case ENotStarted:
+            completionCode = KErrNotReady;
+            break;
+
+        case EFinished:
+        case ECancelled:
+            completionCode = KErrCompletion;
+            break;
+
+        default:
+            CTestServer::PanicServer( EInvalidThreadState );
+            break;
+        }
+
+
+    // Complete the request
+    aMessage.Complete( completionCode );
+
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: Resume
+
+    Description: Resumes a test case. If test is not ongoing,
+    then do not resume.
+
+    Parameters: const RMessage& aMessage      :in:  Message from client.
+    
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::Resume( const RMessage2& aMessage )
+    {
+
+    __TRACE ( KThreadOperation, ( _L( "CTestExecution::Resume" ) ) );
+
+    TInt completionCode = KErrNone;
+
+    // Note that it is allowed to resume already resumed thread, so
+    // there is no need for states to verify that thread is really in
+    // suspended state.
+    switch ( iThreadState )
+        {
+        case EOnGoing:
+            completionCode = iModuleContainer->ResumeThread();
+            break;
+
+        case ENotStarted:
+            completionCode = KErrNotReady;
+            break;
+
+        case EFinished:
+        case ECancelled:
+            completionCode = KErrCompletion;
+            break;
+
+        default:
+            CTestServer::PanicServer( EInvalidThreadState );
+            break;
+        }
+
+
+    // Complete the request
+    aMessage.Complete( completionCode );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CloseTestExecution
+
+    Description: Closes Test Execution subsession
+
+    Parameters: const RMessage& aMessage      :in:  Message from client.
+    
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CloseTestExecution( const RMessage2& aMessage )
+    {
+
+    // Cancel test request
+    CancelTestRequest();
+
+    // Cancel print request
+    CancelPrintRequest();
+    
+    // Cancel event request
+    CancelEventRequest();
+
+    // Delete this subsession
+    const TUint subsession = aMessage.Int3();
+    iModuleSession->DeleteTestExecution( subsession, aMessage );
+
+    // Complete the request
+    aMessage.Complete( KErrNone );
+
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelPrintRequest
+
+    Description: Cancel print request. Completes ongoing print request
+    with KErrCancel.
+
+    Parameters: None
+    
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CancelPrintRequest()
+    {
+
+    if ( iPrintNotifyAvailable )
+        {
+        iPrintHandler->Cancel();
+        
+        iPrintNotifyAvailable = EFalse;
+        iNotifyPrintMessage.Complete ( KErrCancel );
+        //@spe iPrintNotifyAvailable = EFalse;
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelEventRequest
+
+    Description: Cancel event request. Completes ongoing event request
+    with KErrCancel.
+
+    Parameters: None
+    
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CancelEventRequest()
+    {
+    iEventHandler->Cancel();
+
+    if( iEventNotifyAvailable )
+        {
+        // Cancel request
+        iEventNotifyAvailable = EFalse;
+        iNotifyEventMessage.Complete ( KErrCancel );
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelInterferenceRequest
+
+    Description: Cancel print request. Completes ongoing print request
+    with KErrCancel.
+
+    Parameters: None
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CancelInterferenceRequest()
+    {
+
+    if ( iInterferenceNotifyAvailable )
+        {
+        iInterferenceHandler->Cancel();
+        
+        iInterferenceNotifyAvailable = EFalse;
+        iNotifyInterferenceMessage.Complete ( KErrCancel );
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelRemoteCmdRequest
+
+    Description: Cancel RemoteCmd request. Completes ongoing RemoteCmd request
+        with KErrCancel.
+
+    Parameters: None
+    
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CancelRemoteCmdRequest()
+    {
+    iSndHandler->Cancel();
+
+    // Cancel request
+    if( iRemoteSendAvailable )
+        {
+        iRemoteSendAvailable = EFalse;
+        iNotifyRemoteCmdMessage.Complete ( KErrCancel );
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: NotifyCommand
+
+    Description: Handles the first phase of the Command request from engine.
+
+    Parameters: const RMessage& aMessage: in: Message from client.
+
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::NotifyCommand( const RMessage2& aMessage )
+    {
+    iNotifyCommandMessage = aMessage;
+    iCommandNotifyAvailable = ETrue;
+    iCommandHandler->StartL();
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelCommandRequest
+
+    Description: Cancel Command request. Completes ongoing Command request
+        with KErrCancel.
+
+    Parameters: None
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CancelCommandRequest()
+    {
+    iCommandHandler->Cancel();
+
+    // Cancel request
+    if(iCommandNotifyAvailable)
+        {
+        iCommandNotifyAvailable = EFalse;
+        iNotifyCommandMessage.Complete(KErrCancel);
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: GetTestCaseArguments
+
+    Description: Get test case arguments
+
+    Parameters: None
+
+    Return Values: Test case arguments
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestExecution::GetTestCaseArguments() const
+    {
+    if ( iTestCaseArgs != NULL )
+        {
+        return *iTestCaseArgs;
+        }
+    return KNullDesC;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelTestRequest
+
+    Description: Cancel test execution request.
+    If thread is not in OnGoing state, function does not do anything.
+
+    Otherwise following operations are done:
+    1 ) Obtain access to both  PrintMutex and EventMutex to make sure that
+       thread can't be accessing print queue or events.
+    2 ) Kill the thread
+    3 ) Complete original "RunTestCase" request with KErrCancel
+    4 ) If print queue is empty, complete print request
+    5 ) Give up mutexes
+    6 ) Delete module container
+
+    Parameters: None
+    
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CancelTestRequest()
+    {
+    // This mutex block and make sure that cancel operation is done succesfully
+    // and test case e.g. cannot complete at the same time. Get mutex.
+    iTestThreadMutex.Wait();
+
+    // iModuleContainer is an active object, check is active.
+    if ( iModuleContainer == NULL || ( iModuleContainer != NULL && !iModuleContainer->IsActive() ) )
+        {
+        // Test case is already ready, return.
+        iTestThreadMutex.Signal();
+        return KErrNone;
+        }
+
+    if ( iThreadState == EOnGoing )
+        {
+        // Print mutex access is required to make sure that the dying thread
+        // does not have access to print queue. Same is true for event queue.
+
+        // NOTE: iEventArrayMutex is now taken, so the ongoing thread
+        // can't set any events so queue will be empty.
+        iPrintHandler->Cancel();
+        iEventHandler->Cancel();
+        iInterferenceHandler->Cancel();
+        iCommandHandler->Cancel();
+
+        // Kill the thread
+        iModuleContainer->KillThread( KErrCancel );
+
+        // Complete the test execution request
+        CompleteTestExecution( KErrCancel, TFullTestResult::ECaseCancelled, 
+                               KErrCancel, KErrCancel, _L( "Cancelled" ) );
+        iThreadState = ECancelled;
+
+       
+        /**        
+        * Removed, because may block in certain situations. Implemented now in
+        * TestCombiner instead.
+        // Unset all pending state events, 
+        // because we have killed the testcase abnormally
+        // UnsetStateEvents();
+        */
+        
+        // Complete print request if queue is empty
+        CompletePrintRequestIfQueueEmpty();
+        
+        // Delete the module containter
+        delete iModuleContainer;
+        iModuleContainer = NULL;
+        }
+        
+    // Relinquish mutex.
+    iTestThreadMutex.Signal();
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelRequestL
+
+    Description: Cancel asynchronous request
+
+    Parameters: const RMessage& aMessage      :in:  Message from client.
+    
+    Return Values: TInt                             Error code from CancelXXX-
+                                                    function
+
+    Errors/Exceptions: Function panics the client, if invalid message
+                       received.
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CancelRequestL( const RMessage2& aMessage )
+    {
+    TInt r = KErrNone;
+
+    switch ( aMessage.Int0() )
+        {
+        case ETestExecutionRunTestCase:
+            {
+            r = CancelTestRequest();
+            break;
+            }
+        case ETestExecutionNotifyProgress:
+            {
+            r = CancelPrintRequest();
+            break;
+            }
+        case ETestExecutionNotifyEvent:
+            {
+            r = CancelEventRequest();
+            break;
+            }
+        case ETestExecutionNotifyRemoteCmd:
+            {
+            r = CancelRemoteCmdRequest();
+            break;
+            }
+        case ETestExecutionNotifyCommand:
+            {
+            r = CancelCommandRequest();
+            break;
+            }
+        default:
+            iModuleSession->PanicClient( EInvalidRequestCancel, aMessage );
+            break;
+        }
+
+    aMessage.Complete( r );
+
+    return r;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: SetThreadState
+
+    Description: A multithread safe thread state modification function
+
+    Parameters: const TTestState aState       :in:  New state
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::SetThreadState( const TTestState aState )
+    {
+
+    iThreadState = aState;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: Complete event
+
+    Description: Completes pending event request. Must be 
+        called with iEventSem taken.
+        
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::CompleteEvent( TInt aError )
+    {
+    if( iEventDef.iStatus )
+        {
+        __TRACE( KMessage,(_L("Comp Stat %d, %x (error %d)"), 
+            this, iEventDef.iStatus, aError));
+        TestThreadRequestComplete( iEventDef.iStatus, aError );
+        
+        iEventDef.iStatus = NULL;
+        
+        }
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CompletePrintRequestIfQueueEmpty
+
+    Description: Completes print request if queue is empty.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::CompletePrintRequestIfQueueEmpty()
+    {
+
+    if ( iPrintNotifyAvailable &&  iPrintQueue->Count() == 0 )
+        {
+        iNotifyPrintMessage.Complete ( KErrEof );
+        iPrintNotifyAvailable = EFalse;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CleanupEvents
+
+    Description: Cleanups Events.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::CleanupEvents()
+    {
+    
+    iEventArray.ResetAndDestroy();
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: GetRq
+
+    Description: Get request pointers.
+
+    Parameters: None
+
+    Return Values: TRequestStatus*
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TRequestStatus* CTestExecution::GetRq( TRequestType aType )
+    {
+
+    TRequestStatus* status = NULL;
+
+    switch( aType )
+        {
+        case ERqPrint:
+            status = &iPrintHandler->iStatus;
+            break;
+        case ERqEvent:
+            status = &iEventHandler->iStatus;
+            break;
+        case ERqSnd:
+            status = &iSndHandler->iStatus;
+            break;
+        case ERqRcv:
+            status = &iRcvHandler->iStatus;
+            break;
+        case ERqInterference:
+            status = &iInterferenceHandler->iStatus;
+            break;
+        case ERqMeasurement:
+            status = &iMeasurementHandler->iStatus;
+            break;
+        case ERqCommand:
+            status = &iCommandHandler->iStatus;
+            break;
+        default:
+            break;
+        }
+
+    return status;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CompleteTestExecution
+
+    Description: Completes test execution
+
+    Parameters: const TInt aCompletionCode    :in:  Request completion code
+                const TInt aCaseExecutionCode  in:  Case execution code
+                const TFullTestResult::TCaseExecutionResult aCaseExecutionType,
+                const TInt aCaseResult        :in:  Case result
+                const TDesC& aText            :in:  Completion text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::CompleteTestExecution( const TInt aCompletionCode,
+    const TFullTestResult::TCaseExecutionResult aCaseExecutionType,
+    const TInt aCaseExecutionCode,
+    const TInt aCaseResult,
+    const TDesC& aText )
+    {
+    
+    TInt completionCode = aCompletionCode;
+    
+    if( iModuleContainer != NULL )
+        {
+        // Fill the description
+        iFullResult.iEndTime.HomeTime();
+        iFullResult.iCaseExecutionResultType = aCaseExecutionType;
+        iFullResult.iCaseExecutionResultCode = aCaseExecutionCode;
+        iFullResult.iTestResult.iResult = aCaseResult;
+        iFullResult.iTestResult.iResultDes = aText;
+        CompleteTestExecution( aCompletionCode );
+        return;
+        }
+    else
+        {   
+        completionCode = KErrGeneral;
+        __TRACE ( KError, ( CStifLogger::ERed, 
+            _L("CTestExecution::CompleteTestExecution: ModuleContainer NULL") ) );
+        }
+
+    iTestExeMessage.Complete ( completionCode );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CompleteTestExecution
+
+    Description: Completes test execution
+
+    Parameters: const TInt aCompletionCode: in: completion code
+                TFullTestResult&: in: test case result
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::CompleteTestExecution( const TInt aCompletionCode )
+    {
+    
+    TInt completionCode = aCompletionCode;
+    
+    TFullTestResultPckg fullResultPckg( iFullResult );
+    TRAPD( res, iTestExeMessage.WriteL( 0, fullResultPckg ) );
+    if ( res != KErrNone )
+        {
+        completionCode = res;
+        }
+
+    iTestExeMessage.Complete ( completionCode );
+    
+    // @js Now it returns completionCode, used to return res
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: UnsetStateEvents
+
+    Description: Unsets all state events. Must be done if testcase is exited 
+                abnormally (i.e. aborted by the user).
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::UnsetStateEvents()
+    {
+
+
+    // Unset all state events that are set currently
+    TInt count = iStateEvents.Count();
+    TEventIf event;
+    for( TInt i = 0; i < count; i++ )   
+        {
+        TPtrC name = *(iStateEvents[i]);
+        event.Set( TEventIf::EUnsetEvent, name, TEventIf::EState );
+        
+        // Construct message
+        TEventIfPckg eventPckg( event );
+
+        // Write message to client space
+        TRAPD( res, iNotifyEventMessage.WriteL( 0, eventPckg ) );
+
+        // Complete with WriteL result
+        iEventNotifyAvailable = EFalse;
+        iNotifyEventMessage.Complete( res );
+        if( res != KErrNone )
+            {
+            __TRACE( KError,( _L( "CTestExecution::UnsetStateEvents: WriteL failed" ) ));
+            break;
+            } 
+        }
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: TestThreadRequestComplete
+
+    Description: Complete test thread request.
+
+    Parameters: None
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestExecution::TestThreadRequestComplete( TRequestStatus* aStatus, 
+                                                TInt aCode)
+    {                                        
+    
+    if( iThreadState != EOnGoing )
+        {
+        __TRACE( KError,
+            ( _L( "CTestExecution::TestThreadRequestComplete: test thread killed" ) ));
+        return;
+        }
+
+    if( iTestThreadOpen == EFalse )
+        {        
+        if( iTestThread.Open( iTestThreadId ) != KErrNone )
+            {
+            __TRACE( KError,
+                ( _L( "CTestExecution::TestThreadRequestComplete: test thread cannot be opened" ) ));
+            return;
+            }
+        iTestThreadOpen = ETrue;
+        }
+    if( iTestThread.ExitType() != EExitPending ) 
+        {
+        // test thread has died
+        __TRACE( KError,
+            ( _L( "CTestExecution::TestThreadRequestComplete: test thread has died" ) ));
+        return;
+        }    
+     
+    iTestThread.RequestComplete( aStatus, aCode );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: CancelTestExecution
+
+    Description: Cancels test(s) execution in special cases e.g. timeout,
+                 exit etc.
+
+    Parameters: None
+    
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::CancelTestExecution()
+    {
+    TInt ret( KErrNone );
+    ret = CancelTestRequest();
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: KillTestinterferenceThread
+
+    Description: Make sure that any of the test interference thread's won't
+                 stay to run if test case is crashed of test interference
+                 object is not deleted.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::KillTestinterferenceThread()
+    {
+    for( TInt i = 0; i < iSTIFTestInterferenceArray.Count(); i++ )
+        {
+        RDebug::Print( 
+            _L( "Test interference's thread[%x] killed by STIF" ), (TInt)iSTIFTestInterferenceArray[i].Id() );
+        __TRACE( KInit,
+            ( _L( "Test interference's thread[%x] killed by STIF" ), (TInt)iSTIFTestInterferenceArray[i].Id() ) );
+        iSTIFTestInterferenceArray[i].Kill( KErrCancel );
+        //iSTIFTestInterferenceArray.Remove( i );
+        }
+
+    iSTIFTestInterferenceArray.Reset();
+    iSTIFTestInterferenceArray.Close();
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: DoNotifyCommand
+
+    Description: Completes command message.
+
+    Parameters: None.
+
+    Return Values: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::DoNotifyCommand()
+    {
+    if(!iCommandNotifyAvailable)
+    	{
+    	__TRACE(KPrint, (_L("CTestExecution::DoNotifyCommand(): unable to complete notification")))
+    	return KErrNone;
+    	}
+
+    TInt ret = KErrNone;
+
+    switch(iCommandDef->iCommand)
+        {
+        case EStopExecution:
+            {
+            //Unpack received parameters
+            TStopExecutionCommandParams par;
+            TStopExecutionCommandParamsPckg parPack(par);
+            parPack.Copy(iCommandDef->iParamsPckg);
+
+            //Set test case handle
+            par.iTestCaseHandle = iNotifyCommandMessage.Int3();
+
+            __TRACE(KPrint, (_L("CTestExecution::DoNotifyCommand(): command [%d] type [%d] code [%d] test handle [%d]"), TInt(iCommandDef->iCommand), TInt(par.iType), TInt(par.iCode), par.iTestCaseHandle));
+            iCommandDef->iParamsPckg.Copy(parPack);
+            break;
+            }
+        case ESendTestModuleVersion:
+        	{
+        	TSendTestModuleVesionCommandParams par;
+        	TSendTestModuleVesionCommandParamsPckg parPack(par);
+        	parPack.Copy(iCommandDef->iParamsPckg);
+        	
+        	__TRACE(KPrint, (_L("CTestExecution::DoNotifyCommand(): command ESendTestModuleVersion")));
+        	break;
+        	}
+        default:
+            __TRACE(KError, (_L("CTestExecution::DoNotifyCommand(): Unknown command [%d]"), TInt(iCommandDef->iCommand)));
+            return KErrNotFound;
+        }
+    // Construct message
+    TPckg<TCommand> commandPckg(iCommandDef->iCommand);
+
+    // Start first phase of the writing message to client space
+    TRAP(ret, iNotifyCommandMessage.WriteL(0, commandPckg));
+    if(ret != KErrNone)
+       {
+       __TRACE(KError, (_L( "CTestExecution::DoNotifyCommand(): WriteL failed (0)")));
+       }
+
+    TRAP(ret, iNotifyCommandMessage.WriteL(1, iCommandDef->iParamsPckg));
+    if(ret != KErrNone)
+       {
+       __TRACE(KError, (_L( "CTestExecution::DoNotifyCommand(): WriteL failed (1)")));
+       }
+
+    // Complete request with WriteL result
+    iCommandNotifyAvailable = EFalse;
+    iNotifyCommandMessage.Complete(ret);
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestExecution
+
+    Method: KillTestMeasurement
+
+    Description: Make sure that any of the test measurement operations won't
+                 stay to run if test case is crashed or test measurement object
+                 is not stopped by user.
+
+    Parameters: None
+
+    Return Values: TInt: Symbian OS error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestExecution::KillTestMeasurement()
+    {
+    for( TInt i = 0; i < iMeasurementHandlingArray.Count(); i++ )
+        {
+        iMeasurementHandlingArray[i]->iMeasurementModulePtr->Stop();
+        }
+
+    iMeasurementHandlingArray.ResetAndDestroy();
+    iMeasurementHandlingArray.Close();
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CPrintHandler class member functions.
+    CPrintHandler listens print notifications from test thread.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintHandler
+
+    Method: NewL
+
+    Description: Constructs a new CPrintHandler object.
+
+    Parameters: CTestExecution& aExecution: in: "Parent"
+
+    Return Values: CPrintHandler*: New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CPrintHandler* CPrintHandler::NewL( CTestExecution& aExecution )
+    {
+
+    CPrintHandler* self = new( ELeave ) CPrintHandler( aExecution );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CPrintHandler::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintHandler
+
+    Method: CPrintHandler
+
+    Description: Constructor
+
+    Parameters: CTestModuleContainer& aExecution :in:   "Parent"
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CPrintHandler::CPrintHandler( CTestExecution& aExecution ) :
+    CActive( CActive::EPriorityStandard ),
+    iExecution( aExecution )
+    {
+    
+    CActiveScheduler::Add ( this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintHandler
+
+    Method: ~CPrintHandler
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CPrintHandler::~CPrintHandler()
+    {
+
+    Cancel();
+
+    }
+
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintHandler
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CPrintHandler::StartL()
+    {
+    
+    __TRACE( KPrint, ( _L( "CPrintHandler::StartL" ) ) );
+    
+    if( IsActive() ) 
+        {
+        CTestServer::PanicServer( EAlreadyActive );
+        }
+
+    iStatus = KRequestPending;
+    SetActive();
+    
+    // Signal test thread
+    iExecution.iPrintSem.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintHandler
+
+    Method: RunL
+
+    Description: Handles thread death.
+    Function does:
+    1 ) Stops monitoring thread
+    1 ) Marks thread death
+    2 ) Completes ongoing requests
+    3 ) Cleans the memory
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CPrintHandler::RunL()
+    {
+
+    __TRACE( KPrint, ( _L( "CPrintHandler::RunL [%d]" ), iStatus.Int() ) );
+    
+    iExecution.DoNotifyPrint();
+    
+    // enable print request
+    //@speiExecution.iPrintHandler->StartL();
+    StartL();
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintHandler
+
+    Method: DoCancel
+
+    Description: Stops print notification listening.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CPrintHandler::DoCancel()
+    {
+
+    __TRACE( KPrint, ( _L( "CPrintHandler::DoCancel" ) ) );
+
+    iExecution.iPrintMutex.Wait();  // Take mutex and check test case print
+                                    // operation. If pending take print semaphore
+                                    // and complete
+    if( iStatus == KRequestPending )
+        {
+        // Signal test thread
+        // @remove iExecution.iPrintSem.Wait();
+    
+        TRequestStatus* status = &iStatus;    
+        User::RequestComplete( status, KErrCancel );        
+        }
+
+    iExecution.iPrintMutex.Signal();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CPrintHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError:                  :in:  Error code
+
+    Return Values:  TInt                            Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CPrintHandler::RunError( TInt aError )
+    {
+    
+    __TRACE( KError,( _L( "CPrintHandler::RunError" ) ) );
+
+    return aError;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CEventHandler class member functions.
+    CEventHandler listens print notifications from test thread.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CEventHandler
+
+    Method: NewL
+
+    Description: Constructs a new CEventHandler object.
+
+    Parameters: CTestExecution& aExecution: in: "Parent"
+
+    Return Values: CEventHandler*: New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CEventHandler* CEventHandler::NewL( CTestExecution& aExecution )
+    {
+
+    CEventHandler* self = new( ELeave ) CEventHandler( aExecution );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CEventHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CEventHandler::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CEventHandler
+
+    Method: CEventHandler
+
+    Description: Constructor
+
+    Parameters: CTestModuleContainer& aExecution :in:   "Parent"
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CEventHandler::CEventHandler( CTestExecution& aExecution ) :
+    CActive( CActive::EPriorityStandard ),
+    iExecution( aExecution )
+    {
+    
+    CActiveScheduler::Add ( this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CEventHandler
+
+    Method: ~CEventHandler
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CEventHandler::~CEventHandler()
+    {
+
+    Cancel();
+
+    }
+
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CEventHandler
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CEventHandler::StartL()
+    {
+    
+    __TRACE( KPrint, ( _L( "CEventHandler::StartL" ) ) );
+
+    if( IsActive() ) 
+        {
+        CTestServer::PanicServer( EAlreadyActive );
+        }
+    
+    iStatus = KRequestPending;
+    SetActive();
+    
+    // Signal test thread
+    iExecution.iEventSem.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CEventHandler
+
+    Method: RunL
+
+    Description: Handles thread death.
+    Function does:
+    1 ) Stops monitoring thread
+    1 ) Marks thread death
+    2 ) Completes ongoing requests
+    3 ) Cleans the memory
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CEventHandler::RunL()
+    {
+
+    __TRACE( KPrint, ( _L( "CEventHandler::RunL [%d]" ), iStatus.Int() ) );
+
+    switch( iExecution.EventDef().iType )
+        {
+        case TEventDef::EEventCmd:
+            iExecution.DoNotifyEvent();
+            break;
+        case TEventDef::EEventCmdCancel:
+            iExecution.CancelEvent();
+            break;
+        default:
+            CTestServer::PanicServer( EUnknownEventCmd );
+            break;  
+        }
+         
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CEventHandler
+
+    Method: DoCancel
+
+    Description: Stops print notification listening.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CEventHandler::DoCancel()
+    {
+
+    __TRACE( KPrint, ( _L( "CEventHandler::DoCancel" ) ) );
+    
+    iExecution.iEventMutex.Wait();  // Take mutex and check test case event
+                                    // operation. If pending take event
+                                    // semaphore and complete
+    if( iStatus == KRequestPending )
+        {
+        // Signal test thread
+        // @remove iExecution.iEventSem.Wait();
+
+        TRequestStatus* status = &iStatus;    
+        User::RequestComplete( status, KErrCancel );
+
+        }
+
+    iExecution.iEventMutex.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CEventHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError:                  :in:  Error code
+
+    Return Values:  TInt                            Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CEventHandler::RunError( TInt aError )
+    {
+    
+    __TRACE( KError,( _L( "CEventHandler::RunError" ) ) );
+
+    return aError;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CSndHandler class member functions.
+    CSndHandler listens print notifications from test thread.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSndHandler
+
+    Method: NewL
+
+    Description: Constructs a new CSndHandler object.
+
+    Parameters: CTestExecution& aExecution: in: "Parent"
+
+    Return Values: CSndHandler*: New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CSndHandler* CSndHandler::NewL( CTestExecution& aExecution )
+    {
+
+    CSndHandler* self = new( ELeave ) CSndHandler( aExecution );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSndHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CSndHandler::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSndHandler
+
+    Method: CSndHandler
+
+    Description: Constructor
+
+    Parameters: CTestModuleContainer& aExecution :in:   "Parent"
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CSndHandler::CSndHandler( CTestExecution& aExecution ) :
+    CActive( CActive::EPriorityStandard ),
+    iExecution( aExecution )
+    {
+    
+    CActiveScheduler::Add ( this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSndHandler
+
+    Method: ~CSndHandler
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CSndHandler::~CSndHandler()
+    {
+
+    Cancel();
+
+    }
+
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSndHandler
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CSndHandler::StartL()
+    {
+    
+    __TRACE( KPrint, ( _L( "CSndHandler::StartL" ) ) );
+
+    if( IsActive() ) 
+        {
+        CTestServer::PanicServer( EAlreadyActive );
+        }
+    
+    iStatus = KRequestPending;
+    SetActive();
+    
+    // Signal test thread
+    iExecution.iSndSem.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSndHandler
+
+    Method: RunL
+
+    Description: Handles thread death.
+    Function does:
+    1 ) Stops monitoring thread
+    1 ) Marks thread death
+    2 ) Completes ongoing requests
+    3 ) Cleans the memory
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CSndHandler::RunL()
+    {
+
+    __TRACE( KPrint, ( _L( "CSndHandler::RunL [%d]" ), iStatus.Int() ) );
+    
+    iExecution.DoRemoteSend();
+       
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSndHandler
+
+    Method: DoCancel
+
+    Description: Stops print notification listening.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CSndHandler::DoCancel()
+    {
+
+    __TRACE( KPrint, ( _L( "CSndHandler::DoCancel" ) ) );
+
+    iExecution.iSndMutex.Wait();  // Take mutex and check test case send
+                                  // operation. If pending take send
+                                  // semaphore and complete
+    if( iStatus == KRequestPending )
+        {
+        // Signal test thread
+        // @remove iExecution.iSndSem.Wait();
+
+        TRequestStatus* status = &iStatus;    
+        User::RequestComplete( status, KErrCancel );
+
+        }
+
+    iExecution.iSndMutex.Signal();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CSndHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError:                  :in:  Error code
+
+    Return Values:  TInt                            Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CSndHandler::RunError( TInt aError )
+    {
+    
+    __TRACE( KError,( _L( "CSndHandler::RunError" ) ) );
+
+    return aError;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CSndHandler class member functions.
+    CRcvHandler listens print notifications from test thread.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRcvHandler
+
+    Method: NewL
+
+    Description: Constructs a new CRcvHandler object.
+
+    Parameters: CTestExecution& aExecution: in: "Parent"
+
+    Return Values: CRcvHandler*: New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CRcvHandler* CRcvHandler::NewL( CTestExecution& aExecution )
+    {
+
+    CRcvHandler* self = new( ELeave ) CRcvHandler( aExecution );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRcvHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CRcvHandler::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRcvHandler
+
+    Method: CRcvHandler
+
+    Description: Constructor
+
+    Parameters: CTestModuleContainer& aExecution :in:   "Parent"
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRcvHandler::CRcvHandler( CTestExecution& aExecution ) :
+    CActive( CActive::EPriorityStandard ),
+    iExecution( aExecution )
+    {
+    
+    CActiveScheduler::Add ( this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRcvHandler
+
+    Method: ~CRcvHandler
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CRcvHandler::~CRcvHandler()
+    {
+
+    Cancel();
+
+    }
+
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRcvHandler
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CRcvHandler::StartL()
+    {
+    
+    __TRACE( KPrint, ( _L( "CRcvHandler::StartL" ) ) );
+    
+    if( IsActive() ) 
+        {
+        CTestServer::PanicServer( EAlreadyActive );
+        }
+    iStatus = KRequestPending;
+    SetActive();
+    
+    // Signal test thread
+    iExecution.iRcvSem.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRcvHandler
+
+    Method: RunL
+
+    Description: Handles thread death.
+    Function does:
+    1 ) Stops monitoring thread
+    1 ) Marks thread death
+    2 ) Completes ongoing requests
+    3 ) Cleans the memory
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CRcvHandler::RunL()
+    {
+
+    __TRACE( KPrint, ( _L( "CRcvHandler::RunL [%d]" ), iStatus.Int() ) );
+    
+    iExecution.DoRemoteReceive();
+       
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRcvHandler
+
+    Method: DoCancel
+
+    Description: Stops print notification listening.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CRcvHandler::DoCancel()
+    {
+
+    __TRACE( KPrint, ( _L( "CRcvHandler::DoCancel" ) ) );
+
+    iExecution.iRcvMutex.Wait();  // Take mutex and check test case receive
+                                  // operation. If pending take reveive
+                                  // semaphore and complete
+    if( iStatus == KRequestPending )
+        {
+        // Signal test thread
+        // @remove iExecution.iRcvSem.Wait();
+
+        TRequestStatus* status = &iStatus;    
+        User::RequestComplete( status, KErrCancel );
+        }
+        
+    iExecution.iRcvMutex.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CRcvHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError:                  :in:  Error code
+
+    Return Values:  TInt                            Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CRcvHandler::RunError( TInt aError )
+    {
+    
+    __TRACE( KError,( _L( "CRcvHandler::RunError" ) ) );
+
+    return aError;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CTestInterferenceHandler class 
+    member functions. CTestInterferenceHandler listens print notifications from
+    test thread.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CInterferenceHandler
+
+    Method: NewL
+
+    Description: Constructs a new CInterferenceHandler object.
+
+    Parameters: CTestExecution& aExecution: in: "Parent"
+
+    Return Values: CInterferenceHandler*: New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CInterferenceHandler* CInterferenceHandler::NewL( 
+                                                CTestExecution& aExecution )
+    {
+    CInterferenceHandler* self = 
+                        new( ELeave ) CInterferenceHandler( aExecution );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CInterferenceHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CInterferenceHandler::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CInterferenceHandler
+
+    Method: CInterferenceHandler
+
+    Description: Constructor
+
+    Parameters: CTestModuleContainer& aExecution :in: "Parent"
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CInterferenceHandler::CInterferenceHandler( CTestExecution& aExecution ) :
+    CActive( CActive::EPriorityStandard ),
+    iExecution( aExecution )
+    {
+    CActiveScheduler::Add ( this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CInterferenceHandler
+
+    Method: ~CInterferenceHandler
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CInterferenceHandler::~CInterferenceHandler()
+    {
+    Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CInterferenceHandler
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CInterferenceHandler::StartL()
+    {
+    __TRACE( KPrint, ( _L( "CInterferenceHandler::StartL" ) ) );
+    
+    if( IsActive() ) 
+        {
+        CTestServer::PanicServer( EAlreadyActive );
+        }
+
+    iStatus = KRequestPending;
+    SetActive();
+    
+    // Signal test thread, Notify test thread that operation is done.
+    iExecution.iInterferenceSem.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CInterferenceHandler
+
+    Method: RunL
+
+    Description: Handles thread death.
+    Function does:
+    1 ) Stops monitoring thread
+    1 ) Marks thread death
+    2 ) Completes ongoing requests
+    3 ) Cleans the memory
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CInterferenceHandler::RunL()
+    {
+    __TRACE( KPrint, ( _L( "CInterferenceHandler::RunL [%d]" ), iStatus.Int() ) );
+    
+    iExecution.DoNotifyInterference();
+    
+    StartL();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CInterferenceHandler
+
+    Method: DoCancel
+
+    Description: Stops interference notification listening.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CInterferenceHandler::DoCancel()
+    {
+    __TRACE( KPrint, ( _L( "CInterferenceHandler::DoCancel" ) ) );
+
+    iExecution.iInterferenceMutex.Wait();   // Take mutex and check test
+                                            // interference operation. If
+                                            // pending take interference
+                                            // semaphore and complete
+    if( iStatus == KRequestPending )
+        {
+    
+        TRequestStatus* status = &iStatus;    
+        User::RequestComplete( status, KErrCancel );
+        }
+
+    iExecution.iInterferenceMutex.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CInterferenceHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError: in: Error code
+
+    Return Values:  TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CInterferenceHandler::RunError( TInt aError )
+    {
+    __TRACE( KError,( _L( "CTestInterferenceHandler::RunError" ) ) );
+
+    return aError;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CMeasurementHandler class 
+    member functions. CMeasurementHandler handles test measurement operations
+    that comes from test execution side to TestServer side.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMeasurementHandler
+
+    Method: NewL
+
+    Description: Constructs a new CMeasurementHandler object.
+
+    Parameters: CTestExecution& aExecution: in: Pointer to test execution side.
+
+    Return Values: CMeasurementHandler*: New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CMeasurementHandler* CMeasurementHandler::NewL( CTestExecution& aExecution )
+    {
+    CMeasurementHandler* self = 
+                        new( ELeave ) CMeasurementHandler( aExecution );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMeasurementHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CMeasurementHandler::ConstructL()
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMeasurementHandler
+
+    Method: CMeasurementHandler
+
+    Description: Constructor
+
+    Parameters: CTestModuleContainer& aExecution :in: Pointer to test
+                execution side.
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CMeasurementHandler::CMeasurementHandler( CTestExecution& aExecution ) :
+    CActive( CActive::EPriorityStandard ),
+    iExecution( aExecution )
+    {
+    CActiveScheduler::Add ( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMeasurementHandler
+
+    Method: ~CMeasurementHandler
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CMeasurementHandler::~CMeasurementHandler()
+    {
+    Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMeasurementHandler
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: TInt: Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CMeasurementHandler::StartL()
+    {
+    __TRACE( KPrint, ( _L( "CMeasurementHandler::StartL" ) ) );
+
+    if( IsActive() ) 
+        {
+        CTestServer::PanicServer( EAlreadyActive );
+        }
+
+    iStatus = KRequestPending;
+    SetActive();
+
+    // Do not Signal here because synchronous operations will be executed and we
+    // don't want to signal at first time: iExecution.iMeasurementSem.Signal();
+    // Signal() operation will be handled in RunL in this case.
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMeasurementHandler
+
+    Method: RunL
+
+    Description: Derived from CActive, handles test measurement execution.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CMeasurementHandler::RunL()
+    {
+    __TRACE( KPrint, ( _L( "CMeasurementHandler::RunL [%d]" ), iStatus.Int() ) );
+    
+    TInt ret( 0 );
+    ret = iExecution.DoNotifyMeasurement();
+
+    // ret value is copied to struct so it can be handled later.
+    iExecution.iTestMeasurement.iMeasurementStruct.iOperationResult = ret;
+    
+    // SetActive again
+    StartL();
+
+    // TestServer side operations are done, Signal that operation is done.
+    iExecution.iMeasurementSem.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMeasurementHandler
+
+    Method: DoCancel
+
+    Description: Stops measurement notification listening.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+void CMeasurementHandler::DoCancel()
+    {
+    __TRACE( KPrint, ( _L( "CMeasurementHandler::DoCancel" ) ) );
+
+    iExecution.iMeasurementMutex.Wait();    // Take mutex and check test
+                                            // measurement operation. If
+                                            // pending take measurement
+                                            // semaphore and complete
+    if( iStatus == KRequestPending )
+        {
+    
+        TRequestStatus* status = &iStatus;    
+        User::RequestComplete( status, KErrCancel );
+        }
+
+    iExecution.iMeasurementMutex.Signal();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMeasurementHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError: in: Error code
+
+    Return Values:  TInt: Error code
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CMeasurementHandler::RunError( TInt aError )
+    {
+    __TRACE( KError,( 
+        _L( "CMeasurementHandler::RunError with error: %d" ), aError ) );
+
+    return aError;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CCommandHandler class member functions.
+    CCommandHandler listens command notifications from test thread.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandHandler
+
+    Method: NewL
+
+    Description: Constructs a new CCommandHandler object.
+
+    Parameters: CTestExecution& aExecution: in: "Parent"
+
+    Return Values: CCommandHandler*: New object
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CCommandHandler* CCommandHandler::NewL(CTestExecution& aExecution)
+    {
+    CCommandHandler* self = new (ELeave) CCommandHandler(aExecution);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandHandler
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CCommandHandler::ConstructL()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandHandler
+
+    Method: CCommandHandler
+
+    Description: Constructor
+
+    Parameters: CTestExecution& aExecution :in:   "Parent"
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CCommandHandler::CCommandHandler(CTestExecution& aExecution):
+    CActive(CActive::EPriorityStandard),
+    iExecution(aExecution)
+    {
+    CActiveScheduler::Add (this);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandHandler
+
+    Method: ~CCommandHandler
+
+    Description: Destructor.
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CCommandHandler::~CCommandHandler()
+    {
+    Cancel();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandHandler
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CCommandHandler::StartL()
+    {
+    __TRACE(KPrint, (_L( "CCommandHandler::StartL" )));
+
+    if(IsActive())
+        {
+        CTestServer::PanicServer(EAlreadyActive);
+        }
+    iStatus = KRequestPending;
+    SetActive();
+
+    // Signal test thread
+    iExecution.iCommandSem.Signal();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandHandler
+
+    Method: RunL
+
+    Description:
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CCommandHandler::RunL()
+    {
+    __TRACE(KPrint, (_L( "CCommandHandler::RunL [%d]"), iStatus.Int()));
+
+    iExecution.DoNotifyCommand();
+//    StartL();
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandHandler
+
+    Method: DoCancel
+
+    Description: Stops command notification listening.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+
+void CCommandHandler::DoCancel()
+    {
+    __TRACE(KPrint, (_L("CCommandHandler::DoCancel")));
+
+    iExecution.iCommandMutex.Wait();  // Take mutex and check test case receive
+                                      // operation. If pending take reveive
+                                      // semaphore and complete
+    if(iStatus == KRequestPending)
+        {
+        TRequestStatus* status = &iStatus;
+        User::RequestComplete(status, KErrCancel);
+        }
+
+    iExecution.iCommandMutex.Signal();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandHandler
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here.
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError:                  :in:  Error code
+
+    Return Values:  TInt                            Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CCommandHandler::RunError(TInt aError)
+    {
+    __TRACE(KError, (_L("CCommandHandler::RunError")));
+
+    return aError;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandDef
+
+    Method: CCommandDef
+
+    Description: private constructor
+
+    Return Values:  void
+
+-------------------------------------------------------------------------------
+*/
+
+CCommandDef::CCommandDef()
+	{
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandDef
+
+    Method: ConstructL
+
+    Description: Second phase constructor
+
+    Return Values:  void
+
+-------------------------------------------------------------------------------
+*/
+
+void CCommandDef::ConstructL()
+	{
+
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandDef
+
+    Method: NewL
+
+    Description: First phase constructor
+
+    Return Values:  void
+
+-------------------------------------------------------------------------------
+*/
+
+CCommandDef* CCommandDef::NewL()
+	{
+	CCommandDef* self = new(ELeave) CCommandDef;
+	CleanupStack::PushL(self);
+	self->ConstructL();
+	CleanupStack::Pop(self);
+	return self;
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCommandDef
+
+    Method: ~CCommandDef
+
+    Description: destructor
+
+-------------------------------------------------------------------------------
+*/
+
+CCommandDef::~CCommandDef()
+	{
+
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/Testserversession.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1673 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CTestServer 
+* class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+#include "TestEngineClient.h"
+#include <StifTestModule.h>
+#include <stifinternal/TestServerClient.h>
+#include "TestServer.h"
+#include "TestServerCommon.h"
+#include "TestServerModuleIf.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+// Struct to pass parameters to server thread
+struct TThreadStartTestServerSession
+    {
+    RThread    iServerThread; // The server thread
+    RSemaphore iStarted;      // Startup syncronisation semaphore   
+    TInt       iStartupResult;// Start-up result
+    };
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: NewL
+
+    Description: Create new test cases list    
+
+    Parameters: const TDesC& aConfigFileName :in:  Config file name
+
+    Return Values: CTestCasesList* Pointer to new test cases list
+
+    Errors/Exceptions: Leaves if memory allocation fails or ConstructL leaves.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCasesList* CTestCasesList::NewL( const TDesC& aConfigFileName )
+    {    
+    CTestCasesList* self = new(ELeave)CTestCasesList;
+    CleanupStack::PushL( self );
+    self->ConstructL( aConfigFileName );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: ~CTestCasesList
+
+    Description: Destructor    
+
+    Parameters: 
+
+    Return Values: 
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCasesList::~CTestCasesList()
+    {
+    delete iConfigFileName;
+    iConfigFileName = NULL;
+    iTestCases.ResetAndDestroy();
+    iTestCases.Close();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: AppendTestCaseL
+
+    Description: Appends test case.
+
+    Parameters: const TDesC& aTestCaseTitle  in: Test case title
+
+    Return Values: 
+
+    Errors/Exceptions: Leaves if memory allocation fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCasesList::AppendTestCaseL( const TDesC& aTestCaseTitle )
+    {
+    HBufC* testCaseTitle = aTestCaseTitle.AllocL();
+    CleanupStack::PushL( testCaseTitle );
+    iTestCases.AppendL( testCaseTitle );
+    CleanupStack::Pop( testCaseTitle );
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: GetTestCaseTitleL
+
+    Description: Returns specified test case title  
+
+    Parameters: TInt aIndex: in: Requested test case index. 
+
+    Return Values: Test case title.
+
+    Errors/Exceptions: Leaves if test case index is invalid
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestCasesList::GetTestCaseTitleL( TInt aIndex ) const
+    {    
+    if ( ( aIndex < 0 ) || ( aIndex >= iTestCases.Count() ) )
+        {
+        User::Leave( KErrNotFound );
+        }
+    return *iTestCases[ aIndex ];
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: GetConfigFileName
+
+    Description: Returns config file name  
+
+    Parameters: 
+
+    Return Values: Config file name.
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestCasesList::GetConfigFileName() const
+    {    
+    return *iConfigFileName;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: Count
+
+    Description: Returns count of test cases.    
+
+    Parameters: 
+
+    Return Values: Test cases count.
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestCasesList::Count() const
+    {
+    return iTestCases.Count();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: ResetAndDestroy
+
+    Description: Resets list of test cases.    
+
+    Parameters: 
+
+    Return Values: 
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCasesList::ResetAndDestroy()
+    {    
+    iTestCases.ResetAndDestroy();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: ~CTestCasesList
+
+    Description: Destructor    
+
+    Parameters: 
+
+    Return Values: 
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestCasesList::CTestCasesList()
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestCasesList
+
+    Method: ~CTestCasesList
+
+    Description: Destructor    
+
+    Parameters: 
+
+    Return Values: 
+
+    Errors/Exceptions: 
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestCasesList::ConstructL( const TDesC& aConfigFileName )
+    {
+    iConfigFileName = aConfigFileName.AllocL();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: NewL
+
+    Description: Create new Test Module    
+
+    Parameters: RThread& aClient              :in:  Handle to client
+                CTestServer* aServer          :in:  Pointer to server
+
+    Return Values: CTestModule*                     Pointer to new test module
+
+    Errors/Exceptions: Leaves if memory allocation fails or ConstructL leaves.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModule* CTestModule::NewL( CTestServer* aServer )
+    {
+
+    CTestModule* self=new( ELeave ) CTestModule();
+    CleanupStack::PushL( self );
+    self->ConstructL( aServer );
+    CleanupStack::Pop();
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: CTestModule
+
+    Description: Constructor.
+    Initialise base class.
+
+    Parameters: RThread& aClient              :in:  Handle to client
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CTestModule::CTestModule() :
+    CSession2(),
+    iIni(0, 0)
+    {
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: ~CTestModule
+
+    Description: Destructor.
+    Deallocate memory and close handles.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CTestModule::~CTestModule()
+    {
+
+    __TRACE( KVerbose, ( _L( "Closing test module" ) ) );
+        
+    // Free test case related data. No error checking here, because if freeing
+    // fails, then nothing can be done in destructor.
+    FreeCaseData();
+
+    // Delete all test module instances.
+    // Cleanup all RTestExecution has been opened by client but not properly
+    // closed for example if timeout occurs and client died. This almost do
+    // same than CloseSession() in "if( iTestExecutionHandle )" branch.
+    if( iTestExecutionHandle )
+        {
+        TInt handle = 0;
+        CObject* theObj = NULL;
+        TInt count = iTestExecutionHandle->Count();
+
+        for( TInt i = 0 ; i < count; i++ )
+            {
+            // Get pointer to CTestExecution
+            theObj=iTestExecutionHandle->operator[]( i );
+            if( theObj )
+                {
+                handle=iTestExecutionHandle->At( theObj );
+
+                CTestExecution* testcase = (CTestExecution*) theObj;
+                // Cancels test(s) execution(timeout, exit, etc)
+                // For example TestCombiner is timeouted => TestCombiner's
+                // TestServer+TestModule(s) should cancel also.
+                testcase->CancelTestExecution();
+                // CTestExecution will panic if test case is ongoing!!! This
+                // should be stopped, client should handless this.
+                iTestExecutionHandle->Remove( handle );
+                }
+            }
+
+        delete iTestExecutionHandle;
+        iTestExecutionHandle = NULL;
+
+        }
+
+    // Delete all FREE Test Module instances.
+    if( iTestModuleInstances )
+        {
+        iTestModuleInstances->ResetAndDestroy();
+        delete iTestModuleInstances;
+        iTestModuleInstances = NULL;
+        }
+
+    // Delete ini file heap buffer
+    delete iIniBuffer;
+    iIniBuffer = NULL;
+
+    // Delete array of test case titles
+    iTestCaseTitlesMap.ResetAndDestroy();
+    iTestCaseTitlesMap.Close();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+    
+    Parameters: CTestServer* aServer          :in:  Server
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if:
+                       base class CreateL leaves
+                       Object index creation fails
+                       Object container creation fails
+                       Pointer array construction fails                       
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModule::ConstructL( CTestServer* aServer )
+    {
+
+	__TRACE( KVerbose, ( _L( "CTestModule::ConstructL - constructing server session" ) ) );
+
+    // second-phase construct base class
+    //CSession2::CreateL( /* *aServer */ );
+    iTestServer = aServer;
+
+    // create new object index
+    iTestExecutionHandle = CObjectIx::NewL();
+
+    // Initialize the object container using the object
+    // container index in the server.
+    iContainer = iTestServer->NewContainerL();
+
+    iTestModuleInstances = new( ELeave ) RPointerArray<CTestModuleContainer>;
+
+	__TRACE( KError, ( _L( "CTestModule::ConstructL - constructing server session done" ) ) );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: CountResources
+
+    Description: Resource counting
+
+    Parameters: None
+
+    Return Values: TInt                             Resource count
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::CountResources()
+    {
+
+    return iResourceCount;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: NumResources
+
+    Description: Get resources, writes to Message()
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Panic client if result can't be written to descriptor.
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModule::NumResources( const RMessage2& aMessage )
+    {
+
+    TPckgBuf<TInt> countPckg( iResourceCount );
+
+    TRAPD( r, aMessage.WriteL( 0, countPckg ) );
+    if( r !=KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: PanicClient
+
+    Description: Panic clients.
+
+    Parameters: TInt aPanic                   :in:  Panic code
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CTestModule::PanicClient( const TInt aPanic, const RMessage2& aMessage ) const
+    {
+
+    __TRACE( KError,( _L( "CTestModule::PanicClient code = %d" ), aPanic ) );
+
+    _LIT( KTxtTestModule,"CTestModule" );
+
+    aMessage.Panic( KTxtTestModule, aPanic );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: CloseSession
+
+    Description: Close session
+
+    Parameters: None
+
+    Return Values: TInt: Symbian error code.
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::CloseSession( const RMessage2& aMessage )
+    {
+
+    __TRACE( KMessage,( _L( "CTestModule::CloseSession in" ) ) );
+
+    // Delete all unclosed subsession handle before closing session.
+    // Remove iTestExecutionHandle contents. iTestExecutionHandle countains
+    // CTestExecution that handles test case have been created.
+    if( iTestExecutionHandle )
+        {
+        TInt handle = 0;
+        CObject* theObj = NULL;
+        TInt count = iTestExecutionHandle->Count();        
+        for ( TInt i = count - 1; i >= 0; i-- )
+            {
+            theObj=iTestExecutionHandle->operator[]( i );
+            if( theObj )
+                {
+                handle=iTestExecutionHandle->At( theObj );
+                // CTestExecution will panic if test case is ongoing!!! This
+                // should be stopped, client should handle this.
+                iTestExecutionHandle->Remove( handle );
+                }
+            }
+
+        delete iTestExecutionHandle;
+        iTestExecutionHandle = NULL;
+        }
+
+    // Deletion must be done here, because the "CloseSession" message is 
+    // completed before execution continues from CActiveScheduler::Start 
+    // location, and the main thread can continue execution 
+    // and therefore shutdown itself and all threads in that process.
+    
+    // Delete the object container
+    iTestServer->DeleteContainer( iContainer );
+
+    // Free test case related data
+    TInt r = FreeCaseData();
+
+    // Delete all FREE Test Module instances
+    iTestModuleInstances->ResetAndDestroy();
+    delete iTestModuleInstances;
+    iTestModuleInstances = NULL;
+
+     // Inform server that session is closed
+    iTestServer->SessionClosed();
+
+	// Check for avoiding multiple complete, see CTestModule::ServiceL()
+    if( r != KErrNone )
+        {
+		// In error cases do not complete, just return
+        __TRACE( KMessage,( _L( "CTestModule::CloseSession out (1)" ) ) );
+        return r;
+        }
+
+    aMessage.Complete( KErrNone );
+
+    // After active scheduler shutdown is done, execution continues from
+    // CTestServer::ThreadFunction()
+
+    __TRACE( KMessage,( _L( "CTestModule::CloseSession out (2)" ) ) );
+    return r;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: ServiceL
+
+    Description: Trap harness for dispatcher
+
+    Parameters: const RMessage& aMessage  :inout:   Message
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModule::ServiceL( const RMessage2& aMessage )
+    {
+
+    // NOTE! HW testing slows down dramatically if adds commants here
+
+    //__TRACE( KMessage,( _L( "CTestModule::ServiceL in" ) ) );
+
+    TInt r = KErrNone;
+    TRAPD( ret, r = DispatchMessageL( aMessage ) );
+
+    if ( ret != KErrNone )
+        {
+        // Complete message on leaving cases with leave code.
+        __TRACE( KError, ( CStifLogger::ERed, _L( "CTestModule::DispatchMessageL leaved" ) ) );
+        aMessage.Complete( ret );
+        }
+
+    // Complete message with error code originating from message handling
+    // function.
+    if ( r != KErrNone )
+        {
+        __TRACE( KError, ( CStifLogger::ERed, _L( "CTestModule::DispatchMessageL returned error" ) ) );
+        aMessage.Complete( r );
+        }
+
+     // __TRACE( KMessage,( _L( "CTestModule::ServiceL out" ) ) );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: DispatchMessageL
+
+    Description: Dispatch message, calls corresponding function to do it.
+
+    Parameters: const RMessage& aMessage  :inout:   Message to be handled
+
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: Leaves if operation handling function leaves
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::DispatchMessageL( const RMessage2& aMessage )
+    {
+
+    __TRACE( KMessage,( _L( "CTestModule::DispatchMessageL %d" ),
+        aMessage.Function()  ) );
+    switch( aMessage.Function() )
+    {
+    // Session specific
+    case ETestServerCloseSession:                // Close whole session
+        {
+		__TRACE( KError ,( _L( "Closing test module session" ) ) );
+        return CloseSession( aMessage );
+        }
+    case ETestServerGetServerThreadId:           // Get Server ThreadId
+        {
+		__TRACE( KError ,( _L( "Return server thread id" ) ) );
+        return GetServerThreadIdL( aMessage );
+        }
+
+    case ETestModuleCreateSubSession :           // Create new test module subsession
+        {
+		__TRACE( KError,( _L( "Creating test module session" ) ) );
+        return CreateModuleSessionL( aMessage );
+        }
+
+    case ETestModuleCloseSubSession:             // Close module subsession
+        {
+        // Nothing to do.
+        aMessage.Complete( KErrNone );
+        return KErrNone;
+        }
+
+    case ETestExecutionCreateSubSession:         // Create new test execution subsession
+        {
+        return NewTestExecutionL( aMessage );
+        }
+ 
+    case ETestModuleEnumerateTestCases:          // Enumerate test cases
+        {
+		__TRACE( KError,( _L( "Enumerating test cases" ) ) );
+        return EnumerateTestCasesL( aMessage );
+        }
+        
+    case ETestModuleGetTestCases:                // Get test cases
+        {
+        return GetTestCasesL( aMessage );
+        }
+
+    case ETestModuleErrorNotification:           // Request error notification
+        {
+        return HandleErrorNotificationL( aMessage );
+        }
+
+    case ETestModuleCancelAsyncRequest:
+        {
+        return CancelAsyncRequestL( aMessage );
+        }
+  
+    // Subsession specific
+    case ETestExecutionRunTestCase:              // Run test case
+        {
+		__TRACE( KInit,( _L( "Running test case" ) ) );
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->RunTestCase( aMessage );
+        }
+        
+    case ETestExecutionNotifyProgress:           // Test case prints
+        {
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->NotifyPrint( aMessage );
+        }
+
+    case ETestExecutionNotifyEvent:              // Event notifications
+        {
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->NotifyEvent( aMessage );
+        }
+        
+    case ETestExecutionNotifyRemoteCmd:          // RemoteCmd notifications
+        {
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->NotifyRemoteCmd( aMessage );
+        }
+    case ETestExecutionReadRemoteCmdInfo:          // RemoteCmd reading
+        {
+        //CTestExecution* testCase=CaseFromHandle( aMessage.Int3() );
+        //return testCase->NotifyRemoteCmd( aMessage );
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->ReadRemoteCmdInfo( aMessage );
+        }
+
+
+    case ETestExecutionResume:                   // Resume case execution
+        {
+		__TRACE( KVerbose,( _L( "Resuming test execution" ) ) );
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->Resume( aMessage );
+        }
+        
+    case ETestExecutionPause:                    // Pause case execution
+        {
+		__TRACE( KVerbose,( _L( "Pausing test execution" ) ) );
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->Pause( aMessage );
+        }
+            
+    case ETestExecutionCloseSubSession:          // Close execution subsession
+        {
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->CloseTestExecution( aMessage );
+        }
+
+    case ETestExecutionCancelAsyncRequest:       // Cancel async request
+        {
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->CancelRequestL( aMessage );
+        }
+    case ETestExecutionNotifyCommand:            // Command notifications
+        {
+        CTestExecution* testCase=CaseFromHandle( aMessage.Int3(), aMessage );
+        return testCase->NotifyCommand( aMessage );
+        }
+
+    default:                                     // Invalid request
+        {
+        PanicClient( EBadRequest, aMessage );
+        return KErrNotSupported;
+        }
+    }
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: EnumerateTestCases
+
+    Description: Enumerates test cases and returns test case count by writing
+    result to client side package.
+
+    Function obtains a TestModule and calls EnumerateTestCases from it.
+    Test module will be released when calling GetTestCases function.
+
+    Parameters: const RMessage& aMessage  :inout:   Message to be handled
+
+    Return Values: TInt                             Operation result
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::EnumerateTestCasesL( const RMessage2& aMessage )
+    {
+
+    __TRACE( KMessage,( _L( "CTestModule::EnumerateTestCasesL in" ) ) );
+ 
+    // Get data from message
+    TFileName config;
+    TRAPD( res, aMessage.ReadL( 0, config ) );
+    if(res == KErrDied)
+        {
+        RDebug::Print(_L("CTestModule::EnumerateTestCasesL() Reading from RMessage ended with KErrDied. Client is not alive anymore and this request will be ignored"));
+        return res;
+        }
+    else if( res != KErrNone )
+        {
+        RDebug::Print(_L("CTestModule::EnumerateTestCasesL() #1 Panic client with [%d], res=[%d]"), EBadDescriptor, res);
+        PanicClient( EBadDescriptor, aMessage );
+        return res;
+        }
+
+    // Free old case data
+    User::LeaveIfError( FreeCaseData() );
+
+    // Get test cases from the test module
+    User::LeaveIfError( GetTestModule( iEnumerateModule, config ) );
+
+    // Enumerate test cases
+    iEnumerateModule->EnumerateTestCases( config );
+
+    // Something fatal?
+    TInt r = iEnumerateModule->OperationErrorResult();
+    if(  r != KErrNone )
+        {
+        // Enumeration module have crashed.
+        delete iEnumerateModule;
+        iEnumerateModule = NULL;
+
+        return r;
+        }
+
+    // Error from module?
+    if( iEnumerateModule->ModuleResult() != KErrNone )
+        {
+        return iEnumerateModule->ModuleResult();
+        }
+
+    // Write count to Ptr1()
+    const RPointerArray<TTestCaseInfo>* testCases = iEnumerateModule->TestCases();
+    
+    if( testCases == NULL )
+        {
+        User::Leave( KErrGeneral );
+        }
+    
+    CTestCasesList* testCasesList = NULL;
+    for ( TInt i = 0; i < iTestCaseTitlesMap.Count(); i++ )
+        {
+        if ( iTestCaseTitlesMap[ i ]->GetConfigFileName() == config )
+            {
+            testCasesList = iTestCaseTitlesMap[ i ];
+            break;
+            }
+        }
+    if ( testCasesList == NULL )
+        {
+        testCasesList = CTestCasesList::NewL( config );
+        CleanupStack::PushL( testCasesList );
+        iTestCaseTitlesMap.AppendL( testCasesList );
+        CleanupStack::Pop( testCasesList );
+        }
+    
+    // Store titles (for further use, i.e. when asked for title from the interface via CTestModuleIf->CTestThreadContainer->CTestModuleContainer)
+    testCasesList->ResetAndDestroy();
+    TInt i;
+    for(i = 0; i < testCases->Count(); i++)
+        {
+        //Handle situation when test cases are enumerated not as 0-based (testscripter, ...)
+        if(i == 0 && (*testCases)[i]->iCaseNumber > 0)
+            {
+            testCasesList->AppendTestCaseL( KNullDesC );
+            }
+        testCasesList->AppendTestCaseL( (*testCases)[i]->iTitle );
+        }
+    
+    TPckgBuf<TInt> countPckg( testCases->Count() );
+    TRAP( res, aMessage.WriteL( 1, countPckg ) );
+    if(res == KErrDied)
+        {
+        RDebug::Print(_L("CTestModule::EnumerateTestCasesL() Writing to RMessage ended with KErrDied. Client is not alive anymore and this request will be ignored"));
+        return res;
+        }
+    else if( res != KErrNone )
+        {
+        RDebug::Print(_L("CTestModule::EnumerateTestCasesL() #2 Panic client with [%d], res=[%d], config=[%S]"), EBadDescriptor, res, &config);
+        PanicClient( EBadDescriptor, aMessage );
+        return res;
+        }
+
+    // All ok, complete message
+    aMessage.Complete( KErrNone );
+
+    __TRACE( KMessage,( _L( "CTestModule::EnumerateTestCasesL out" ) ) );
+    
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: GetTestCasesL
+
+    Description: Get test cases. Enumerate test cases must be called before
+    calling this function.
+
+    Function releases the test module reserved by EnumerateTestCase().
+
+    Parameters: const RMessage& aMessage  :inout:   Message to be handled
+
+    Return Values: TInt                             Operation result
+
+    Errors/Exceptions: Leaves if cases have not been enumerated.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::GetTestCasesL( const RMessage2& aMessage )
+    {
+
+    __TRACE( KMessage,( _L( "CTestModule::GetTestCasesL in" ) ) );
+
+    // Leave if cases have not been enumerated.
+    //User::LeaveIfNull(( TAny* ) iEnumerateModule->TestCases() );
+    if( ( TAny* ) iEnumerateModule->TestCases() == NULL )
+        {
+        User::Leave( KErrGeneral );
+        }
+
+    const TInt len = sizeof( TTestCaseInfo );
+    
+    // Get cases
+    const RPointerArray<TTestCaseInfo>& cases = *iEnumerateModule->TestCases();
+
+    // Get number of cases
+    const TInt Kcount = cases.Count();
+
+    // Loop through case and copy then to client's descriptor.
+    for( TInt i = 0; i < Kcount; i++ )
+        {
+
+        // Construct package for source data
+        TTestCaseInfoPckg tmpPackage( *cases[i] );
+
+        // Write to correct location
+        aMessage.WriteL( 0, tmpPackage, i *len );
+
+        }
+
+    // Free case data and the test module
+    User::LeaveIfError( FreeCaseData() );
+
+    // Finished
+    aMessage.Complete( KErrNone );
+
+    __TRACE( KMessage,( _L( "CTestModule::GetTestCasesL out" ) ) );
+
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: HandleErrorNotification
+
+    Description: Request error notification.
+
+    Parameters: const RMessage& aMessage  :inout:   Message to be handled
+
+    Return Values: TInt                             Operation result
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::HandleErrorNotificationL( const RMessage2& aMessage )
+    {
+    
+    iErrorMessage = aMessage;
+    iErrorMessageAvailable = ETrue;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: GetServerThreadId
+
+    Description: Request server state notification.
+
+    Parameters: const RMessage& aMessage :inout: Message to be handled
+
+    Return Values: TInt Operation result
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::GetServerThreadIdL( const RMessage2& aMessage )
+    {
+      
+    TInt id( iTestServer->GetServerThreadId() );
+   
+    TPckg<TThreadId> threadIdPckg( id );
+   
+    TRAPD( res, aMessage.WriteL( 0, threadIdPckg ) );
+    
+      // Finished
+    aMessage.Complete( res );
+    
+    return KErrNone;
+
+    }      
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: CancelAsyncRequest
+
+    Description: Cancels asynchronous request
+
+    Parameters: const RMessage& aMessage  :inout:   Message to be handled
+
+    Return Values: TInt                             Operation result
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::CancelAsyncRequestL( const RMessage2& aMessage )
+    {
+    
+    switch ( aMessage.Int0() )
+        {
+        case ETestModuleErrorNotification:
+            {
+            if ( iErrorMessageAvailable )
+                {
+                iErrorMessage.Complete ( KErrCancel );
+                iErrorMessageAvailable = EFalse;
+                }
+            aMessage.Complete ( KErrNone );
+            break;
+            }
+
+        default:
+            {
+            PanicClient( EInvalidRequestCancel, aMessage );
+            break;
+            }
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: ErrorPrint
+
+    Description: Prints error
+
+    Parameters: const TInt aPriority :in: Priority
+                TPtrC aError: in: Error
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModule::ErrorPrint( const TInt aPriority, 
+                              TPtrC aError )
+    {
+
+    if ( iErrorMessageAvailable )
+        {        
+        TErrorNotification error;
+        TErrorNotificationPckg errorPckg ( error );
+
+        error.iModule = _L("TestServer");
+        error.iPriority = aPriority;
+        error.iText = aError;
+
+        TRAPD( r, iErrorMessage.WriteL( 0, errorPckg ) );
+        
+        // Do not handle errors
+        iErrorMessageAvailable = EFalse;
+        iErrorMessage.Complete( r );
+
+        }
+    else
+        {
+        RDebug::Print (_L("Error message lost %d [%S]"), aPriority, &aError );
+        }
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: FreeCaseData
+
+    Description: Frees the test case data and test module that is used in
+    enumeration.
+
+    Parameters: None
+
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::FreeCaseData()
+    {
+
+    __TRACE( KMessage,( _L( "CTestModule::FreeCaseData in" ) ) );
+ 
+    TInt r = KErrNone;
+
+    if( iEnumerateModule )
+        {
+        
+        // Deallocate testcase memory
+        iEnumerateModule->FreeEnumerationData();
+
+        // Free the module
+        r = FreeTestModule( iEnumerateModule );
+
+        iEnumerateModule = NULL;
+
+        }
+
+    __TRACE( KMessage,( _L( "CTestModule::FreeCaseData out" ) ) );
+
+    return r;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: CreateModuleSessionL
+
+    Description: Creates a new module session.
+    Just take the initialisation file name from message.
+
+    Parameters: const RMessage& aMessage  :inout:   Message to be handled
+
+    Return Values: TInt                             Operation result
+
+    Errors/Exceptions: Leaves if memory allocation fails
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::CreateModuleSessionL( const RMessage2& aMessage )
+    {
+
+    __TRACE( KMessage,( _L( "CTestModule::CreateModuleSession in" ) ) );
+
+    // Take parameters
+    TFileName ini;
+    TRAPD( res, aMessage.ReadL( 0, ini ) );
+    if( res != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        return res;
+        }
+
+    // Construct heap buffer for initialization file name
+    iIniBuffer = HBufC::NewL( ini.Length() );
+    iIni.Set ( iIniBuffer->Des() );
+    iIni.Copy ( ini );
+
+    aMessage.Complete( KErrNone );
+
+    __TRACE( KMessage,( _L( "CTestModule::CreateModuleSession out" ) ) );
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: NewTestExecutionL
+
+    Description: Create new test execution subsession
+    
+    Parameters: const RMessage& aMessage  :inout:   Message to be handled
+    
+    Return Values: TInt                             Operation result
+
+    Errors/Exceptions: Function leaves if object can't be created or
+                       it can't be added to container.
+                       Function panics client if message contains invalid
+                       descriptor.
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::NewTestExecutionL( const RMessage2& aMessage )
+    {
+
+    __TRACE( KMessage,( _L( "CTestModule::NewTestExecutionL in" ) ) );
+
+    // Get data from message
+    TInt caseNumber = aMessage.Int0();
+    TFileName config;
+    
+    TRAPD( res, aMessage.ReadL( 1, config ) );
+    if( res != KErrNone )
+        {
+        PanicClient( EBadDescriptor, aMessage );
+        return res;
+        }
+
+    // Make new object
+    CTestExecution* execution=CTestExecution::NewL( this, caseNumber, config );
+
+    // add object to object container to generate unique id
+    iContainer->AddL( execution );
+
+    // add object to object index; this returns a unique handle so we can get it again
+    TInt handle=iTestExecutionHandle->AddL( execution );
+
+    // write the handle to client
+    TPckg<TInt> handlePckg( handle );
+    TRAP( res, aMessage.WriteL( 3, handlePckg ) );
+    if( res != KErrNone )
+        {
+        iTestExecutionHandle->Remove( handle );
+        PanicClient( EBadDescriptor, aMessage );
+        return res;
+        }
+
+    // notch up another resource
+    iResourceCount++;
+
+    // Complete message
+    aMessage.Complete( KErrNone );
+
+    __TRACE( KMessage,( _L( "CTestModule::NewTestExecutionL out" ) ) );
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: DeleteTestExecution
+
+    Description: Deletes Test Execution by handle
+
+    Parameters: const TUint aHandle           :in:  Handle
+
+    Return Values: None
+
+    Errors/Exceptions: Panics client if invalid handle
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CTestModule::DeleteTestExecution( const TUint aHandle, const RMessage2& aMessage )
+    {
+
+    // Verify that handle is valid
+    CaseFromHandle( aHandle, aMessage );
+
+    // Remove object
+    iTestExecutionHandle->Remove( aHandle );
+
+    // Decrement resource count.
+    iResourceCount--;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: CaseFromHandle
+
+    Description: Return subsession from handle
+
+    Parameters: const TUint aHandle           :in:  Handle
+
+    Return Values: CTestExecution*                  Test Execution object
+
+    Errors/Exceptions: Function panics client if invalid handle.
+
+    Status: Approved
+    
+-------------------------------------------------------------------------------
+*/
+CTestExecution* CTestModule::CaseFromHandle( const TUint aHandle, const RMessage2& aMessage ) const
+    {
+
+    CTestExecution* testcase =( CTestExecution* ) iTestExecutionHandle->At( aHandle );
+
+    if( testcase == NULL )
+        {
+        PanicClient( EBadSubsessionHandle, aMessage );
+        }
+
+    return testcase;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: GetTestModule
+
+    Description: Gets a CTestModuleBase*. If there is a free entry
+    in the free list, then it is returned. Otherwise a new one is created.
+
+    Parameters: CTestModuleContainer*& aContainer: out: container pointer.
+                const TDesC& aConfig: in: Test case (config) file name.
+
+    Return Values: Symbian OS error code
+    
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::GetTestModule( CTestModuleContainer*& aContainer,
+                                    const TDesC& aConfig )
+    {
+    TInt ret = KErrNone;
+
+    if( iTestModuleInstances->Count() )
+        {
+        // Return an existing one        
+        aContainer =( *iTestModuleInstances )[0];
+        iTestModuleInstances->Remove( 0 );
+		__TRACE( KInit,( _L( "Reusing old test module container instance at 0x%x" ), (TUint32) aContainer ) );
+        }
+    else
+        {
+        // Create a new one    
+        __TRACE( KInit,( _L( "Creating new test module instance" ) ) );
+        TRAPD( err, aContainer = CTestModuleContainer::NewL( 
+                                                iTestServer->ModuleName(),
+                                                this,
+                                                aConfig ) );
+
+        // If module can't be created, then return NULL.
+        if( err )
+            {
+            __TRACE( KError,( _L( "Can't create new test module container instance" ) ) );
+            aContainer = NULL;
+            ret = err;
+            }
+		else
+			{
+			__TRACE( KInit,( _L( "Test module instance container created" ) ) );
+			}
+
+        if( aContainer )
+            {
+
+            // Initialise module
+            aContainer->Initialize( iTestServer->ModuleName(), iTestServer->FirstTime() );
+
+            if( aContainer->OperationErrorResult() != KErrNone )
+                {
+                // Can't initialise module, delete it
+                __TRACE( KError,( CStifLogger::ERed, _L( "Operation error, can't initialize test module container instance" ) ) );
+                ret = aContainer->OperationErrorResult();                    
+                delete aContainer;
+                aContainer = NULL;
+                }
+            else if( aContainer->ModuleResult() != KErrNone )
+                {
+                // Can't initialise module, delete it
+                __TRACE( KError,( CStifLogger::ERed, _L( "Module error, can't initialize test module container instance" ) ) );
+                ret = aContainer->ModuleResult();
+                delete aContainer;
+                aContainer = NULL;
+                }
+            else
+                {
+                // Module initialised properly, clear the first time flag.
+                iTestServer->ClearFirstTime();
+				__TRACE( KInit,( _L( "Test module container initialized at 0x%x" ), (TUint32) aContainer ) );
+                }
+            }
+        }
+
+    return ret;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: FreeTestModule
+
+    Description:Frees a CTestModuleContainer. This function can be called
+    from the context of the test execution thread.
+    
+    Parameters: CTestModuleContainer* aModule :in:  Module to be freed
+    
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CTestModule::FreeTestModule( CTestModuleContainer* aModule )
+    {
+  
+    // Free the module
+    TInt r = iTestModuleInstances->Append( aModule );
+    if( r != KErrNone )
+        {
+        delete aModule;
+        aModule = NULL;
+        }
+
+    return r;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: IniName
+
+    Returns the initialisation file name
+    
+    Parameters: None
+    
+    Return Values: const TDesC&                     Initialisation file name
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+const TDesC& CTestModule::IniName() const
+    {
+
+    return iIni;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: Name
+
+    Returns the module name
+    
+    Parameters: None
+    
+    Return Values: const TDesC&                     Initialisation file name
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+const TDesC& CTestModule::Name() const
+    {
+
+    return iTestServer->ModuleName();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: GetTestCaseTitleL
+
+    Gets title of currently running test case
+    
+    Parameters: None
+    
+    Return Values: TInt aTestCaseNumber: in: index of currently running test case
+                   TDes& aTestCaseTitle: out: test case title
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CTestModule::GetTestCaseTitleL(TInt aTestCaseNumber, const TDesC& aConfigFile,TDes& aTestCaseTitle)
+    {
+    CTestCasesList* testCasesList = NULL;
+    for ( TInt i = 0; i < iTestCaseTitlesMap.Count(); i++ )
+        {
+        if ( iTestCaseTitlesMap[ i ]->GetConfigFileName() == aConfigFile )
+            {
+            testCasesList = iTestCaseTitlesMap[ i ];
+            break;
+            }
+        }
+    if ( testCasesList == NULL )
+        {
+        User::Leave( KErrNotFound );
+        }
+    
+    RDebug::Print(_L("Trying to get test case title from module. Index=%d, count=%d"), aTestCaseNumber, testCasesList->Count() );
+    
+    aTestCaseTitle.Copy( testCasesList->GetTestCaseTitleL( aTestCaseNumber ) );
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestModule
+
+    Method: GetTestServer
+
+    Gets pointer to TestServer
+    
+    Parameters: None
+    
+    Return Values: CTestServer : pointer to TestServer
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CTestServer* CTestModule::GetTestServer()
+    {
+    return iTestServer;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServer/src/Testundertaker.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,492 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CUnderTaker 
+* class member functions. CUnderTaker is a class, which listens 
+* on Test Execution Thread death, and if that thread dies, then 
+* UnderTaker aborts the ongoing test execution request.
+*
+*/
+
+// INCLUDE FILES
+#include <e32std.h>
+#include <e32svr.h>
+#include "TestEngineClient.h"
+#include <StifTestModule.h>
+#include <stifinternal/TestServerClient.h>
+#include "TestServer.h"
+#include "TestServerModuleIf.h"
+#include "TestServerCommon.h"
+#include "PrintQueue.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: NewL
+
+    Description: Constructs a new CUnderTaker object.
+
+    Parameters: CTestModuleContainer* aContainer :in:   "Parent"
+
+    Return Values: CUnderTaker*                         New undertaker
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves.
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+CUnderTaker* CUnderTaker::NewL( CTestModuleContainer* aContainer )
+    {
+
+    CUnderTaker* self = new( ELeave ) CUnderTaker();
+    CleanupStack::PushL( self );
+    self->ConstructL( aContainer );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CTestModuleContainer* aExecution :in:   "Parent"
+
+    Return Values: None
+
+    Errors/Exceptions: Panics if aContainer is NULL
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CUnderTaker::ConstructL( CTestModuleContainer* aContainer )
+    {
+
+    __ASSERT_ALWAYS( aContainer, 
+                     CTestServer::PanicServer( ENullTestModuleContainer ) );
+
+    iModuleContainer = aContainer;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: CUnderTaker
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CUnderTaker::CUnderTaker() :
+    CActive( CActive::EPriorityHigh+1 )
+    {
+
+    // By default in asynchronous mode
+    iSynchronousMode = EFalse;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: ~CUnderTaker
+
+    Description: Destructor. 
+    Cancels active request.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CUnderTaker::~CUnderTaker()
+    {
+
+    Cancel();
+
+    }
+
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: StartL
+
+    Description: Starts to monitor thread.
+
+    Parameters: None
+
+    Return Values: TInt                             Always KErrNone
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+TInt CUnderTaker::StartL()
+    {
+    
+    SetActive();
+    iModuleContainer->iThread.Logon( iStatus );
+    iCancelNeeded = ETrue;
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: RunL
+
+    Description: Handles thread death.
+    Function does:
+    1 ) Stops monitoring thread
+    1 ) Marks thread death
+    2 ) Completes ongoing requests
+    3 ) Cleans the memory
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CUnderTaker::RunL()
+    {
+
+    // Make sure that any of the test interference thread's won't stay to run.
+    iModuleContainer->KillTestinterferenceThread();
+
+    // Make sure that any of the test measurement's process won't stay to run.
+    iModuleContainer->KillTestMeasurement();
+
+    // Get the exit category
+    TName exitCategory = _L( "Crash reason:" );
+    exitCategory.Append( iModuleContainer->iThread.ExitCategory() );
+    TInt exitReason = iModuleContainer->iThread.ExitReason();
+    TFullTestResult::TCaseExecutionResult exitType = TFullTestResult::ECaseException;
+    if( iModuleContainer->iThread.ExitType() == EExitPanic )
+        {
+        exitType = TFullTestResult::ECasePanic;
+        }    
+
+    // it is not running anymore..
+    iModuleContainer->iUpAndRunning = EFalse;
+
+    // Do not monitor anymore.
+    iModuleContainer->iThread.LogonCancel( iStatus );
+    iCancelNeeded = EFalse;
+
+    __TRACE( KError,( CStifLogger::ERed, _L( "Execution thread crashed, exitReason = %d" ), exitReason ) );
+    __TRACE( KError,( CStifLogger::ERed, exitCategory ) );    
+
+    if ( iSynchronousMode )
+        {        
+
+        // Synchronous request was running. Complete that 
+          // operation.
+        __TRACE( KVerbose,( _L( "CUnderTaker::RunL Crash during synchronous operation" ) ) );
+        iModuleContainer->iErrorResult = KErrDied;
+        iModuleContainer->Cancel();
+        iModuleContainer->iUpAndRunning = EFalse;
+
+        // Print notification
+        TName operationText = _L("Test module died when calling:");
+        operationText.Append( iModuleContainer->iOperationText );
+
+        // Print to log file        
+        __TRACE( KError,( CStifLogger::ERed, operationText ) );
+        // Print to UI
+        iModuleContainer->iCTestModule->ErrorPrint ( 1, operationText );        
+
+        // Stop active scheduler.
+        CActiveScheduler::Stop();
+
+        // Execution continues from CTestModuleContainer::StartAndWaitOperation.
+
+        }
+    else
+        {// Test case was running, 
+
+        __TRACE( KError,( _L( "Test case execution aborted" ) ) );
+        __TRACE( KVerbose,( _L( "CUnderTaker::Run crash during test execution" ) ) );      
+
+        TInt caseResult = KErrGeneral;
+        
+        // Check if case have any special panic or exception codes that are "passed"
+        if ( iModuleContainer->iAllowedExitReason != 
+             CTestModuleIf::ENormal )            
+            {
+                
+            if ( iModuleContainer->iAllowedExitReason == 
+                 CTestModuleIf::EPanic &&
+                 exitType == TFullTestResult::ECasePanic &&
+                 iModuleContainer->iAllowedExitCode == exitReason )
+                {
+                exitType = TFullTestResult::ECaseExecuted;
+                caseResult = KErrNone;
+                exitCategory = _L("Allowed case panic");
+                
+                __TRACE( KError,( _L( "Test case execution panic, setting to OK" ) ) );
+                }
+
+            if ( iModuleContainer->iAllowedExitReason == 
+                 CTestModuleIf::EException &&
+                 exitType == TFullTestResult::ECaseException &&
+                 iModuleContainer->iAllowedExitCode == exitReason )
+                {
+                exitType = TFullTestResult::ECaseExecuted;
+                caseResult = KErrNone;
+                exitCategory = _L("Allowed case exception");
+
+                __TRACE( KError,( _L( "Test case execution exception, setting to OK" ) ) );
+                }
+            
+            
+            }
+
+        // This was asynchronous request, and nobody is waiting for it
+        // completion in server, so all clean-up must be done here
+
+        // Forget iTestThreadContainer pointer, memory is freed because test thread
+        // is destroyed   
+        // This is needed to prevent from accessing memory from thread that is destroyed.
+        // Do this only if test is been executed.
+        iModuleContainer->iThreadContainer = NULL;
+
+        if (iModuleContainer->iCTestExecution != NULL)
+        	{
+			// Execution thread have been killed
+			iModuleContainer->iCTestExecution->SetThreadState( CTestExecution::ECancelled );
+	
+			
+			// Cancel the request
+			iModuleContainer->iCTestExecution->CompleteTestExecution( KErrNone,
+																	  exitType,
+																	  exitReason,
+																	  caseResult,
+																	  exitCategory );
+	
+			// If the print queue is empty, and there is active print
+			// request, then cancel that request. 
+			// NOTE: Case queue not empty AND request waiting AND
+			//       thread terminated can't happen due iPrintMutex
+			iModuleContainer->iCTestExecution->CompletePrintRequestIfQueueEmpty();
+        	}
+        else
+        	{
+        	__TRACE( KError,( _L( "STIF internal error - iCTestExecution is NULL in CUnderTaker::RunL." ) ) );
+        	User::Leave(KErrGeneral);
+        	}
+        // Free the memory
+        // Remove undertaker from module container to make sure that
+        // it does not delete this.
+        iModuleContainer->iUnderTaker = NULL;
+        delete iModuleContainer;
+        iModuleContainer = NULL;
+
+        // Suicide. "Parent", i.e iModuleContainer has already died
+        // and no-one have pointer to this active object, so die.
+        delete this;
+
+        }
+       
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: DoCancel
+
+    Description: Stops thread monitoring
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+
+void CUnderTaker::DoCancel()
+    {
+
+    if( iCancelNeeded && iModuleContainer )
+        {
+        iModuleContainer->iThread.LogonCancel( iStatus );
+        }
+    else
+        {
+        // Note that iModuleContainer can be NULL if iCancelNeeded is EFalse
+        __ASSERT_ALWAYS( iModuleContainer, 
+                         CTestServer::PanicServer( ENullTestModuleContainer ) );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: RunError
+
+    Description: Handle errors. RunL function does not leave, so one should
+    never come here. 
+
+    Print trace and let framework handle error( i.e to do Panic )
+
+    Parameters: TInt aError:                  :in:  Error code
+
+    Return Values:  TInt                            Error code
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TInt CUnderTaker::RunError( TInt aError )
+    {
+    __TRACE( KError,( _L( "CUnderTaker::RunError" ) ) );
+
+    return aError;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: Completed
+
+    Description: Is request completed
+
+    Parameters: None
+
+    Return Values:  TBool                           Completed?
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CUnderTaker::Completed()
+    {
+
+    if( iStatus == KRequestPending )
+        {
+        return EFalse;
+        }
+    else
+        {
+        return ETrue;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CUnderTaker
+
+    Method: SetSynchronousMode
+
+    Description: Set or unsets local processing mode
+
+    Parameters: const TBool aMode             :in:  Mode
+
+    Return Values:  None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+void CUnderTaker::SetSynchronousMode( const TBool aMode )
+    {
+
+    iSynchronousMode = aMode;
+   
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServerStarter/group/TestServerStarter.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestServerStarter 
+* module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          TestServerStarter.exe
+TARGETTYPE      exe
+
+CAPABILITY	ALL -TCB
+VENDORID 	0x101FB657
+SECUREID        0x102073E4
+
+/* Include paths */
+USERINCLUDE     ../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+/* Source files */
+SOURCEPATH      ../src
+
+SOURCE          TestServerStarter.cpp
+
+/* Used libraries */
+LIBRARY         euser.lib
+LIBRARY         stiftestserver.lib
+
+/* Test Server requires large stack */
+EPOCSTACKSIZE   40960
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServerStarter/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for Test Framework's Console UI.
+*/
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	TestServerStarter.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TestServerStarter/src/TestServerStarter.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains TestServerStarter implementation.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32svr.h>
+#include <stifinternal/TestServerClient.h>
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: E32Main
+
+    Description: 
+
+    Parameters: None
+
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+GLDEF_C TInt E32Main()
+    {
+
+    RDebug::Print(_L("STIF: New process starting"));
+
+    // Get module name from command line
+	const TInt length = User::CommandLineLength();
+
+    HBufC* cmdLine = HBufC::New( length );
+    
+    if ( cmdLine == NULL )
+        {
+        return KErrNoMemory;
+        }
+
+    TPtr moduleName = cmdLine->Des();
+
+	User::CommandLine( moduleName );
+
+    RDebug::Print(_L("STIF: Received data [%S]"), &moduleName);
+
+    // Extract semaphore name passed in data
+    TInt index = moduleName.Find(_L(" "));
+    RDebug::Print(_L("STIF: Space separator found at position [%d]"), index);
+    TPtrC semaphoreName = moduleName.Mid(index + 1);
+    moduleName = moduleName.Left(index);
+
+    RDebug::Print(_L("STIF: Extracted module name [%S] and sempahore name [%S]"), &moduleName, &semaphoreName);
+
+    // Open start-up synchronization semaphore
+    RSemaphore startup;
+    RDebug::Print(_L(" Openingstart-up semaphore"));
+    //TName semaphoreName = _L("startupSemaphore");
+    //semaphoreName.Append( moduleName );
+    
+    TInt res = startup.OpenGlobal(semaphoreName);
+    RDebug::Print(_L("Opening result %d"), res);    
+
+
+    TFileName serverName;
+    TInt r = StartNewServer ( moduleName, serverName, EFalse, startup);    
+
+    if ( r ==   KErrAlreadyExists )
+        {        
+        // Ok, server was already started
+        RDebug::Print(_L("Server already started, signaling semaphore and existing"));
+        startup.Signal();        
+
+        delete cmdLine;
+
+        return KErrNone;
+        }
+    else
+        {       
+        RDebug::Print(_L("Server is finished, code %d"), r);
+        }
+
+    delete cmdLine;
+    
+    return r;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TouchConsoleUI/group/TouchConsoleUI.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's Consoleui app.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          TouchConsoleUI.exe
+TARGETTYPE      exe
+UID			 0 0x2002C347
+CAPABILITY	AllFiles CommDD
+//VENDORID 	0x101FB657
+//SECUREID    0x102073DA
+
+USERINCLUDE     ../inc
+USERINCLUDE     ../../inc
+USERINCLUDE     ../../StifTFwIf/inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+/* Source files */
+SOURCEPATH      ../src
+
+SOURCE          ConsoleUI.cpp
+SOURCE          ConsoleMenus.cpp
+SOURCE          ConsoleNotify.cpp
+
+/* Used libraries */
+LIBRARY         euser.lib
+LIBRARY		efsrv.lib
+LIBRARY         stiftestinterface.lib
+LIBRARY         stiftfwif.lib
+LIBRARY     	  stiftestengine.lib
+LIBRARY         econs.lib
+LIBRARY         hal.lib
+
+// In case of large amount of test cases, bigger heap size is required. 
+// Heap sizes can be changed using EPOCHEAPSIZE statement, where the first
+// parameter is heap's minimum size and the latter the maximum size.
+EPOCHEAPSIZE    0x10000 0x300000
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TouchConsoleUI/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for STIF Test Framework's Console UI.
+*/
+
+PRJ_PLATFORMS
+// Specify the platforms your component needs to be built for here.
+// If not specified all platforms can be built.
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+PRJ_TESTEXPORTS
+
+PRJ_MMPFILES
+
+	TouchConsoleUI.mmp
+
+PRJ_TESTMMPFILES
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TouchConsoleUI/inc/CallBack.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,211 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CCallBack 
+* class.
+*
+*/
+
+#ifndef CALLBACK_H
+#define CALLBACK_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Simple class for callbacks.
+
+class CCallBack 
+    :public CAsyncCallBack
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * C++ constructor.
+        */
+        CCallBack( TInt aPriority ):CAsyncCallBack( aPriority ) {}
+
+        /**
+        * C++ constructor.
+        */
+        CCallBack( TCallBack& aCallBack, TInt aPriority ):
+            CAsyncCallBack( aCallBack, aPriority ) {}
+    
+    public: // New functions
+        /**
+        * Return reference to TRequestStatus member.
+        */
+        TRequestStatus& Status(){ return iStatus; }
+
+        /**
+        * Set CCallBack active.
+        */
+        void SetActive()
+            { 
+            iStatus = KRequestPending; 
+            CActive::SetActive(); 
+            };
+    
+    public: // Functions from base classes
+   
+        /**
+        *
+        */
+        void RunL(){ iCallBack.CallBack(); }
+
+    protected:  // New functions
+        
+    protected:  // Functions from base classes
+        
+    private:
+
+	public:     // Data
+    
+	protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+
+template <class T>
+class CActiveCallback 
+        :public CActive
+    {
+    public: // Enumerations
+
+        /**
+        * Callback function type definitions
+        */
+       typedef void (T::* TestFunction)();    
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * C++ constructor.
+        */
+        CActiveCallback ( T* aClass, TestFunction aFunction ) : CActive (EPriorityStandard)
+            {
+            iMethod = aFunction;
+            iClass = aClass;
+            iCompleted = EFalse;
+            }
+    
+    public: // New functions
+        /**
+        * Return reference to TRequestStatus member.
+        */
+        TRequestStatus& Status(){ return iStatus; }
+
+        /**
+        * Set active object to active and return reference to TRequestStatus member
+        */
+        TRequestStatus& Activate()
+            {        
+            iCompleted = EFalse;
+            SetActive();
+            return iStatus;
+            }
+
+        /**
+        * Is callback completed?
+        */
+        TBool isCompleted()
+            {
+            return iCompleted;
+            }
+    
+    public: // Functions from base classes
+   
+        /**
+        * Call the callback
+        */
+        void RunL()
+            {
+            iCompleted = ETrue;
+            if ( iMethod != NULL )
+                {
+                (iClass->*iMethod) ();
+                }        
+            }
+
+        /**
+        * Just forward errors to framework
+        */
+        TInt RunError ( TInt aError )
+            {
+            return aError;
+            }
+
+        /**
+        * Cancel is not supported.
+        */
+        void DoCancel ()
+            {  
+            }
+
+    protected:  // New functions
+        
+    protected:  // Functions from base classes
+        
+    private:
+
+
+
+	public:     // Data
+    
+	protected:  // Data
+
+    private:    // Data
+        TestFunction iMethod;           // Pointer to method to be called
+        T* iClass;                      // Pointer to calls to be called
+        TBool iCompleted;               // Is callback completed?
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // CALLBACK_H  
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TouchConsoleUI/inc/ConsoleMenus.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1903 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CMenu 
+* derived classes.
+*
+*/
+
+
+#ifndef CONSOLE_MENUS_H
+#define CONSOLE_MENUS_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <stifinternal/UIStoreIf.h>
+#include <stifinternal/UIStoreContainer.h>
+#include <stifinternal/UIEngineContainer.h>
+
+#include "CallBack.h"
+
+// CONSTANTS
+const TInt KMenuOverhead = 4;
+
+// Numeric key ascii code values for ConsoleUI's menu
+const TInt KMyKeyDownAsciiCode = 56; // Ascii code for number '8'
+const TInt KMyKeyLeftAsciiCode = 52; // Ascii code for number '4'
+const TInt KMyKeyRightAsciiCode = 54; // Ascii code for number '6'
+const TInt KMyKeyUpAsciiCode = 50;  // Ascii code for number '2'
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CMenu;
+class CConsoleMain;
+class CCaseOperationMenu;
+class CCaseExecutionView;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Main menu
+class CMenu
+        :public CBase
+    {
+    public:  // Enumerations
+        enum TUpdateType
+            {
+            EMenuPrint,
+            EMenuRefresh,
+            };
+
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMenu* NewL( CConsoleMain* aConsole,
+                            CMenu* aParent,
+                            const TDesC& aName);
+
+       /**
+        * Destructor of CConsoleMain.
+        */
+        virtual ~CMenu();
+
+    public: // New functions
+    
+        /** 
+        * Return menu name
+        */
+        virtual const TDesC& Name() const;
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Set parent menu
+        */
+        virtual void SetParent ( CMenu* aMenu );
+
+        /** 
+        * Print line
+        */
+        virtual void Print( const TDesC& aPrint);
+
+        /** 
+        * Multi line print
+        */
+        virtual void PrintMulti( const TDesC& aPrint );
+
+        /** 
+        * Add item to menu
+        */
+        virtual void AddItemL ( CMenu* aItem );
+        
+        /** 
+        * Signals test completion
+        */
+        virtual void SignalL ( CStartedTestCase* /*aContainer*/ ){};
+		
+        /** 
+        * Update display from timer
+        */
+		virtual void TimerUpdate();
+		
+		/**
+		* Append text before original text.
+		*/
+		virtual void AppendBefore(  TInt aLineNum, TDes& aLine );
+		
+		/**
+		* Get menu type.
+		*/
+		inline TInt Type(){ return iType; };
+		
+		/**
+		* Map KeyCode 
+		*/
+		void MapKeyCode(TKeyCode &aSelection);
+
+		/**
+		 * Recalculates visible menu elements.
+		 */
+		void Recalculate( TInt aItemCount );
+		
+    public: // Functions from base classes
+        // None
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None    
+
+        /** 
+        * C++ default constructor.
+        */
+        CMenu();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         const TDesC& aHeader = KNullDesC);
+    
+    private:   // Functions from base classes
+        // None
+
+    public:   // Data
+        // None
+
+    protected:  // Data    
+    
+        //CConsoleBase*           iConsole;      // Pointer to console
+        RConsole*           iConsole;      // Pointer to console
+        CConsoleMain*           iMain;         // Pointer to main console
+        CMenu*                  iParent;       // Pointer to parent menu
+        TName                   iName;         // Menu name
+    	TName					iHeader;	   // Used to display STIF version information
+
+        RPointerArray<CMenu>    iItems;        // Menu items
+
+        TInt                    iPosOnScreen;  // Position on display
+        TInt                    iFirst;        // First displayed item
+        TInt                    iLast;         // Last displayed item
+        TInt                    iItemCount;    // Last Item
+        TSize                   iSize;         // Display size
+        TInt                    iScreenSize;   // "Work area" size
+		TInt                    iDirection;    // Scrolling direction
+		TInt                    iStart;        // Scrolling position
+		TInt                    iPrevPos;      // Previous position in scrolling
+
+        // Menu type (which updates must cause console update) 
+        // Flags from CUIStoreIf::TUpdateFlags 
+        TInt                    iType;
+        
+        // Update type set from PrintMenuL
+		TUpdateType             iUpdateType;
+		
+    private:    // Data
+        // None
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+
+// CONSTANTS
+_LIT( KSelectMenuTxt, "Select module to load, if using ini or test case file use testframework.ini" );
+
+// DESCRIPTION
+// Filename query menu
+class CFileNameQueryView 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CFileNameQueryView* NewL( CConsoleMain* aConsole, 
+                                         CMenu* aParent, 
+                                         const TDesC& aName);
+
+        ~CFileNameQueryView();
+        
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+        
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+    protected:  // New functions
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent, 
+                         const TDesC& aName );
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+    public:   // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // List of module names
+        RPointerArray<TDesC>    iTestModuleNames;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KAddMenuTxt,  "Add test module" );
+_LIT( KLoadMenuTxt,  "Load all test modules" );
+
+// DESCRIPTION
+// Module list menu
+class CModuleListView 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TModuleListMenu
+            {
+            EAddMenuTxtItem,
+            ELoadMenuTxtItem,
+            };
+            
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CModuleListView* NewL( CConsoleMain* aConsole,
+                                      CMenu* aParent,
+                                      const TDesC& aName );
+
+       /**
+        * Destructor
+        */
+        ~CModuleListView();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+        
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, 
+                                TBool& aContinue );
+ 
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+        
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CMenu*                     iModuleAdd;
+
+    public:     // Friend classes
+         // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// Test case starting menu
+class CCaseStartMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCaseStartMenu* NewL( CConsoleMain* aConsole, 
+                                     CMenu* aParent, 
+                                     const TDesC& aName,
+                                     TBool aShowOutput = EFalse);
+
+        /**
+        * Destructor.
+        */
+		~CCaseStartMenu();
+
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, 
+                                TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         TBool aShowOutput = EFalse);
+
+    private:
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // Test case array
+        RRefArray<CTestInfo> iTestCases;
+
+    private:    // Data
+        // Show output automaticly after test case is started
+        TBool iShowOutput;
+        
+        // Map table. Translates indexes from filtered to all loaded from module  
+        RArray<TInt> iMapFilteredToAll;
+        
+        // Keeps filter name converted to lower case
+        TFileName iFilterLowerCase;
+        
+        // Keeps title of test case converted to lower case
+        TFileName iTitleLowerCase;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KChangeAll, "Change all");
+_LIT( KCancelSet, "Cancel set execution" );
+
+// Test set creation menu
+class CMultipleBaseMenu 
+    :public CCaseStartMenu
+  
+    {
+    public:  // Enumerations
+         enum TMenuIndex
+		    {  
+		    EChangeAll = 0,
+		    ECancelSet = 0,
+		    };
+        enum TRunType
+            {
+            ERunSequential,
+            ERunParallel,
+            ERunRepeatSequential,
+            };
+		    
+    protected: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMultipleBaseMenu* NewL( CConsoleMain* aConsole, 
+                                        CMenu* aParent, 
+                                        const TDesC& aName);
+        
+        /**
+        * Destructor.
+        */
+		~CMultipleBaseMenu();
+
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+		/** 
+        * Signals test completion
+        */
+        virtual void SignalL ( CStartedTestCase* aContainer );
+        
+        /** 
+        * Append text before line print.
+        */
+        virtual void AppendBefore( TInt aLineNum, TDes& aLine );
+        
+    protected:  // New functions
+
+        //inline void SetRunType( TRunType aRunType )
+        //    { iRunType = aRunType; };
+            
+        /**
+        * Update iTestCases();
+        */ 
+        virtual TInt UpdateTestCases();
+        TBool CheckIfAnyCaseIsSelected(TInt aCount);
+                      
+    protected:  // Functions from base classes
+
+        /**
+        * Constructor.
+        */
+		CMultipleBaseMenu();
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+       
+    public:     // Data
+
+    protected:  // Data
+		RArray<TBool>       iSetState;
+		TInt                iCurrentRunPos;
+		TBool               iSetFinished;
+		CStartedTestCase*   iOngoingCaseContainer;
+		TRunType            iRunType;
+				
+		// Number of items in "static" menu (including derived classes)
+		TInt                iMenuTotCount;
+
+    private:    // Data
+		// Number of items in "static" menu of this class
+		// (excluding derived classes)  
+		TInt                iMenuCount;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// CONSTANTS
+_LIT( KRunSequentially, "Run selection sequentially");
+_LIT( KRunParallel, "Run selection parallel");
+_LIT( KRepeatRunSequentially, "Repeat run selection sequentially");
+
+_LIT( KSelectFromTo, "Select all between already selected"); 
+
+// Test set creation menu
+class CMultipleCaseMenu 
+    :public CMultipleBaseMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TMultipleMenuIndex
+		    {  
+		    ERunSelection = 0,
+		    ERunSelectionParaller = 1,
+		    ERepeatRunSelection = 2,
+		    ESelectFromTo = 3,
+		    };
+		    
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMultipleCaseMenu* NewL( CConsoleMain* aConsole, 
+                                        CMenu* aParent, 
+                                        const TDesC& aName);
+        
+        /**
+        * Destructor.
+        */
+		~CMultipleCaseMenu();
+
+    public: // New functions
+       /**
+       * Start running.
+       */
+       virtual void StartRunningL( TRunType aRunType, 
+                                   const TDesC& aModule = KNullDesC, 
+                                   const TDesC& aTestCaseFile = KNullDesC );
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+    
+        /**
+        * Constructor.
+        */
+		CMultipleCaseMenu();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+       
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Number of items in "static" menu of this class
+		// (excluding derived classes)  
+		TInt                iMenuItemsCount;
+		
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+// CONSTANTS
+_LIT( KExitTxt,     "Exit" );
+
+// DESCRIPTION
+// The main menu class
+class CMainMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMainMenu* NewL( CConsoleMain* aConsole, 
+                                CMenu* aParent, 
+                                const TDesC& aName,
+                                const TDesC& aHeader );
+
+        /**
+        * Destructor
+        */
+        ~CMainMenu();
+
+    public: // New functions
+        /**
+        * Creates CaseOperationMenu and CaseExecutionView.
+        * Used when after test case starting its output view needs to be shown.
+        */
+        CMenu* CreateOutputViewL(CMenu* aParent);
+
+    public: // Functions from base classes    
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         const TDesC& aHeader );
+
+    private:
+
+    public:   //Data
+
+    protected:  // Data
+
+    private:    // Data
+        // Menu representing output view, used to show it after test case is started
+        CCaseExecutionView* iOutputView;
+
+        // Operation menu used to show output view after test case is started
+        CCaseOperationMenu* iOperationMenu;
+		
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+
+// DESCRIPTION
+// The case list (passed/failed/...) menu class
+class CCaseMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCaseMenu* NewL( CConsoleMain* aConsole, 
+                                CMenu* aParent, 
+                                const TDesC& aName, 
+                                TInt aType );
+
+        /**
+        * Destructor
+        */
+        ~CCaseMenu();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes    
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+        
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+        /**
+        * Append text before original text.
+        */
+        virtual void AppendBefore(TInt aLineNum, TDes& aLine);
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent, 
+                         const TDesC& aName, 
+                         TInt aType );
+
+    private:    // Data
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        CCaseOperationMenu*             iCaseOperationMenu;    // Submenu
+        RRefArray<CStartedTestCase>     iTestCases;
+
+    private:    // Data
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KOutputViewDes,   "View Output");
+_LIT( KPauseCaseDes,    "Pause");
+_LIT( KResumeCaseDes,   "Resume");
+_LIT( KAbortCaseDes,    "Abort case");
+_LIT( KRestartCaseDes,  "Restart");
+
+// DESCRIPTION
+// Case specific operations, like pause, abort etc.
+class CCaseOperationMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TCaseOperationMenu
+            {
+            ERestartCase,
+            EOutputView,
+            EPauseResume,
+            EAbortCase,   
+            };
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCaseOperationMenu* NewL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName, 
+                            const CStartedTestCase* aCaseContainer );
+        
+        /**
+        * Destructor.
+        */
+        ~CCaseOperationMenu();
+        
+    public: // New functions
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         const CStartedTestCase* aCaseContainer );
+
+    private:    // Functions from base classes
+        // None
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Case container
+        const CStartedTestCase* iCaseContainer; 
+        // Execution view                       
+        CCaseExecutionView*     iView;
+        
+    public:     // Friend classes
+        // None        
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+
+class CCaseExecutionView 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CCaseExecutionView* NewL( CConsoleMain* aConsole, 
+                                         CMenu* aParent, 
+                                         const TDesC& aName, 
+                                         const CStartedTestCase* aCase);
+
+         /**
+        * Destructor.
+        */
+        ~CCaseExecutionView();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+        
+        /**
+        * Get current testcase info.
+        */ 
+        inline const CStartedTestCase* TestCase(){ return iCase; };
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName,
+                         const CStartedTestCase* aCase );
+
+    private:   // Functions from base classes
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        const CStartedTestCase* iCase;
+
+        /**
+        * Indicates current selected line.
+        */
+        TInt                    iLine;
+        /**
+        * Indicates will line show.
+        */
+        TBool                   iShowLine;
+        /**
+        * Line to be show.
+        */
+        HBufC*                  iLineTextBuf;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CMenu notifier class shows dialogs in UI.
+class CMenuNotifier
+        :public CBase
+    {
+    public:  // Enumerations
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMenuNotifier* NewL( const TDesC& aError, 
+                                    CConsoleMain* aMain );
+
+       /**
+        * Destructor of CConsoleMain.
+        */
+        virtual ~CMenuNotifier();
+
+    public: // New functions  
+            
+    public: // Functions from base classes
+        // None
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None    
+
+        /** 
+        * C++ default constructor.
+        */
+        CMenuNotifier( CConsoleMain* aMain );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aError );
+    
+    private:   // Functions from base classes
+        // None
+
+    private:   // New functions
+        /** 
+        * C++ default constructor.
+        */
+        void Run1();	
+
+    public:   // Data
+        // None
+
+    protected:  // Data      
+
+    private:    // Data
+        CActiveCallback <CMenuNotifier> iCallBack1;
+        CActiveCallback <CMenuNotifier> iCallBack2;
+        RTimer iTimer;
+        CConsoleBase* iConsole;
+        CConsoleMain* iMain;        
+        TInt iCompletionCode; 
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CMenu dialog class shows dialogs in UI and waits for keypress.
+class CMenuDialog
+    :public CBase
+    {
+    public:  // Enumerations
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CMenuDialog* NewL( CConsoleMain* aMain, 
+                                  const TDesC& aMessage, 
+                                  const TDesC& aInstruction,
+                                  TInt aTimeInSecs );
+
+       /**
+        * Destructor.
+        */
+        virtual ~CMenuDialog();
+
+    public: // New functions  
+            
+    public: // Functions from base classes
+        
+        TInt WaitForKeypress( TKeyCode& aKeyCode, 
+                              TRequestStatus& aStatus  );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None    
+
+        /** 
+        * C++ default constructor.
+        */
+        CMenuDialog( CConsoleMain* aMain );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aMessage, 
+                         const TDesC& aInstruction, 
+                         TInt aTimeInSecs );
+    
+    private:   // Functions from base classes
+        // None
+
+    private:   // New functions
+        /**
+        * Handle completions.
+        */
+        void Run1();	
+
+    public:   // Data
+        // None
+
+    protected:  // Data      
+
+    private:    // Data
+        // Backpointer
+        CConsoleMain* iMain;        
+        CConsoleBase* iConsole;
+
+        // Timer support
+        CActiveCallback <CMenuDialog> iCallBack1;
+        RTimer iTimer;
+        
+        // Reading
+        CActiveCallback <CMenuDialog> iCallBack2;
+        
+        // For reading keys        
+        TRequestStatus* iStatus;
+        TKeyCode*     iKeyCode;
+    
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KTestSetMenu,     "CTestSetMenu" );
+
+_LIT( KDefaultSetName,  "ConsoleUI.set" );
+
+_LIT( KSetCreate,       "Create test set" );
+_LIT( KSetLoad,         "Load test set" );
+
+_LIT( KSetShow,         "Show started test sets" );
+_LIT( KSetUnload,       "Unload test set" );
+_LIT( KSetRemove,       "Remove test set" );
+_LIT( KSetCaseAdd,      "Add test case to test set" );
+_LIT( KSetCaseRemove,   "Remove test case from test set" );
+_LIT( KSetSave,         "Save test set" );
+
+_LIT( KSetStartSeq,     "Start sequential test set execution" );
+_LIT( KSetStartPar,     "Start parallel test set execution" );
+//_LIT( KSetStartRep,     "Start repeating test set execution" );
+
+_LIT( KSetStartSeqNotRun, "Start sequentially not started tests" );
+
+// DESCRIPTION
+// Test set menu
+class CTestSetMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        
+    private: // Enumerations
+        
+        enum TCreateMenu
+            {
+            ESetCreate,
+            ESetLoad,    
+            };
+            
+        enum TEditMenu
+            {
+            ESetShow,
+ 
+            ESetStartSeq,
+            ESetStartPar,
+            //ESetStartRep,
+
+            ESetUnload, 
+            ESetRemove,
+            ESetSave,
+            ESetCaseAdd,
+            ESetCaseRemove,
+            
+            ESetStartSeqNotRun,
+            
+
+            ESetLAST //This entry must remain LAST in this menu
+            };
+            
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetMenu* NewL( CConsoleMain* aConsole,
+                                   CMenu* aParent,
+                                   const TDesC& aName );
+
+       /**
+        * Destructor
+        */
+        ~CTestSetMenu();
+
+    public: // New functions
+        /**
+        * Set test set file name.
+        */
+        void SetTestSetFileName( const TFileName& aTestSetFileName ); 
+        
+        /**
+        * Set test set state created.
+        */
+        void SetCreated(){ iTestSetCreated = ETrue; };
+         
+    public: // Functions from base classes
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+        
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, 
+                                TBool& aContinue );
+ 
+        /** 
+        * Prints the menu
+        */
+        virtual void PrintMenuL( TUpdateType  aType );
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+        /**
+        * Constructor
+        */
+        CTestSetMenu();
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        TBool               iTestSetCreated;
+        TFileName           iTestSetName;
+        
+        CMenu*              iSubMenu;
+        
+    public:     // Friend classes
+         // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+    // CONSTANTS
+    _LIT( KTestSetChoice,     "CTestSetChoiceMenu" );
+    _LIT( KSetSelect,       "Select Test Set" );
+
+
+    // DESCRIPTION
+    // Test set choice menu
+    class CTestSetChoiceMenu 
+        :public CMenu
+
+        {
+        public:  // Enumerations
+            
+        private: // Enumerations
+            
+            
+                
+        public:  // Constructors and destructor
+
+            /**
+            * NewL is first phase of two-phased constructor.
+            */
+            static CTestSetChoiceMenu* NewL( CConsoleMain* aConsole,
+                                       CMenu* aParent,
+                                       const TDesC& aName );
+
+           /**
+            * Destructor
+            */
+            ~CTestSetChoiceMenu();
+
+        public: // New functions
+             
+        public: // Functions from base classes
+
+            /** 
+            * Return item texts.
+            */
+           virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+            
+            /** 
+            * Process keypresses on this menu
+            */
+            virtual CMenu* SelectL( TKeyCode aSelectLion, 
+                                    TBool& aContinue );
+     
+            /** 
+            * Prints the menu
+            */
+            virtual void PrintMenuL( TUpdateType  aType );
+            
+        protected:  // New functions
+
+        protected:  // Functions from base classes
+            /**
+            * Constructor
+            */
+            CTestSetChoiceMenu();
+           
+            /**
+            * By default Symbian OS constructor is private.
+            */
+            void ConstructL( CConsoleMain* aConsole, 
+                             CMenu* aParent,
+                             const TDesC& aName );
+
+        private:
+
+        public:   //Data
+            // None
+
+        protected:  // Data
+            // None
+
+        private:    // Data
+            TFileName           iTestSetName;
+            RPointerArray<HBufC> iFileList;
+            
+        public:     // Friend classes
+             // None
+
+        protected:  // Friend classes
+            // None
+
+        private:    // Friend classes
+            // None
+
+        };
+    
+// CONSTANTS
+_LIT( KAddSelected, "Add selected cases");
+
+// Test set case add menu
+class CTestSetAddCaseMenu 
+    :public CMultipleBaseMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TTestSetAddCaseMenuIndex
+		    {  
+		    EAddSelected = 0,
+		    };
+		    
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetAddCaseMenu* NewL( CConsoleMain* aConsole, 
+                                         CMenu* aParent, 
+                                         const TDesC& aName,
+                                         TDesC& aTestSetName );
+        
+        /**
+        * Destructor.
+        */
+		~CTestSetAddCaseMenu();
+
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+    
+        /**
+        * Constructor.
+        */
+		CTestSetAddCaseMenu( TDesC& aTestSetName );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+       
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Number of items in "static" menu of this class
+		// (excluding derived classes)  
+		TInt    iMenuItemsCount;
+		
+        TPtrC   iTestSetName;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KRemoveSelected, "Remove selected cases");
+
+// Test set case add menu
+class CTestSetRemoveCaseMenu 
+    :public CMultipleBaseMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TTestSetRemoveCaseMenuIndex
+		    {  
+		    ERemoveSelected = 0,
+		    };
+		    
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetRemoveCaseMenu* NewL( CConsoleMain* aConsole, 
+                                             CMenu* aParent, 
+                                             const TDesC& aName,
+                                             TDesC& aTestSetName );
+        
+        /**
+        * Destructor.
+        */
+		~CTestSetRemoveCaseMenu();
+
+    public: // New functions
+       // None
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+        
+        /**
+        * Update iTestCases;
+        */ 
+        virtual TInt UpdateTestCases();
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+    
+        /**
+        * Constructor.
+        */
+		CTestSetRemoveCaseMenu( TDesC& aTestSetName );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole,
+                         CMenu* aParent,
+                         const TDesC& aName );
+
+    private:
+       
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Number of items in "static" menu of this class
+		// (excluding derived classes)  
+		TInt        iMenuItemsCount;
+		
+        TPtrC       iTestSetName;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };    
+
+// DESCRIPTION
+// The case list (passed/failed/...) menu class
+class CTestSetCaseMenu  
+    :public CCaseMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetCaseMenu* NewL( CConsoleMain* aConsole, 
+                                       CMenu* aParent, 
+                                       const TDesC& aName,
+                                       CStartedTestSet& aTestSet );
+
+        /**
+        * Destructor
+        */
+        ~CTestSetCaseMenu();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes    
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+        /** 
+        * Prints the menu
+        */
+        void AppendBefore( TInt aLineNum, TDes& aLine );
+        
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );     
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+       
+
+    private:    // Data
+    
+        CTestSetCaseMenu( CStartedTestSet& aTestSet );
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent, 
+                         const TDesC& aName );
+    public:     // Data
+        // None
+
+    protected:  // Data
+
+    private:    // Data
+        CStartedTestSet& iTestSet;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// CONSTANTS
+_LIT( KCancelTestSet, "Cancel test set");
+        
+// DESCRIPTION
+// Started test sets (passed/failed/...) menu class
+class CStartedTestSetMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        // None
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CStartedTestSetMenu* NewL( CConsoleMain* aConsole, 
+                                          CMenu* aParent, 
+                                          const TDesC& aName );
+
+        /**
+        * Destructor
+        */
+        ~CStartedTestSetMenu();
+
+    public: // New functions
+        // None
+
+    public: // Functions from base classes    
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL( TKeyCode aSelectLion, TBool& aContinue );
+        
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts( RRefArray<TDesC>& aArray );
+
+
+        /** 
+        * Prints the menu
+        */
+        void AppendBefore( TInt aLineNum, TDes& aLine );
+        
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+       
+
+    private:    // Data
+    
+        CStartedTestSetMenu();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aConsole, 
+                         CMenu* aParent, 
+                         const TDesC& aName );
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CTestSetCaseMenu*           iCaseMenu;    // Submenu
+        RRefArray<CStartedTestSet>  iTestSets;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// Menu which shows available filters for test case titles
+class CFilterMenu 
+    :public CMenu
+  
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CFilterMenu* NewL(CConsoleMain* aConsole, 
+                                 CMenu* aParent, 
+                                 const TDesC& aName);
+
+        /**
+        * Destructor.
+        */
+        ~CFilterMenu();
+
+    public: // New functions
+        /**
+        * Set test case menu, so it can be shown when user selects filter
+        */
+        void SetTestCaseMenu(CMenu* aTestCaseMenu);
+
+    public: // Functions from base classes
+
+        /** 
+        * Process keypresses on this menu
+        */
+        virtual CMenu* SelectL(TKeyCode aSelectLion, 
+                               TBool& aContinue);
+
+        /** 
+        * Return item texts.
+        */
+        virtual TInt ItemTexts(RRefArray<TDesC>& aArray);
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        /** 
+        * C++ default constructor.
+        */
+        CFilterMenu();
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL(CConsoleMain* aConsole,
+                        CMenu* aParent,
+                        const TDesC& aName);
+
+    private:    // Functions
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+        
+    private:    // Data
+        /**
+        * Test case menu. It will be shown when user selects filter.
+        */
+        CMenu *iTestCaseMenu;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+   
+#endif // CONSOLE_MENUS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TouchConsoleUI/inc/ConsoleUI.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,446 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the ConsoleUI.
+*
+*/
+
+#ifndef CONSOLE_UI_H
+#define CONSOLE_UI_H
+
+
+//  INCLUDE
+#include <e32std.h>
+#include <e32base.h>
+#include <e32twin.h>
+
+#include <stifinternal/UIStoreIf.h>
+#include <stifinternal/UIStore.h>
+#include <stifinternal/UIEngine.h>
+
+#include "CallBack.h"
+
+#include "TestModuleInfo.h"
+
+#include "ConsoleMenus.h"
+
+// CONSTANTS
+const TInt KMaxLineLength = 80;            // Longest supported line length
+const TInt KScrollPeriod = 300000;		   // Scrolling speed
+
+// MACROS
+
+// DATA TYPES
+
+// Case state
+// Menu update type
+enum TConsoleUIPanic
+    {
+    EInvalidCaseCompletion,
+    };
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CMenu;
+class CConsoleMain;
+class CConsoleReader;
+class CMenuDialog;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CModule contains a test module data
+
+class CScrollerTimer
+        :public CActive
+    {
+    public:  // Enumerations
+        // None
+
+    private: // Enumerations
+        
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CScrollerTimer* NewL( CConsoleMain* aMain );
+
+        /**
+        * Destructor of CModule.
+        */
+        ~CScrollerTimer();
+
+    public: // New functions
+
+		/** 
+        * StartL
+        */
+		void StartL();
+
+		/** 
+        * RunL
+        */
+		void RunL();
+
+		/** 
+        * DoCancel
+        */
+		void DoCancel();
+
+		/** 
+        * RunError
+        */
+		TInt RunError ( TInt aError );
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CScrollerTimer();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CConsoleMain* aMain );
+
+    public:   //Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CConsoleMain*     iMain;            // Pointer to main console
+		RTimer            iTimer;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+// DESCRIPTION
+// Console UI main class
+class CConsoleMain
+        :public CUIStoreIf
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        enum TStartCasesOnStart
+            {
+            EStartCaseNo = 0,
+            EStartSingleCase,
+            EStartCasesSeq,
+            EStartCasesPar,
+            };
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CConsoleMain* NewL();
+
+        /**
+        * Start
+        */
+        TInt StartL();
+
+        /**
+        * Destructor of CConsoleMain.
+        */
+        ~CConsoleMain();
+
+
+    public: // New functions
+    
+    
+        /**
+        * Receives output update notification from CUIStore.
+        */
+        void Update( CStartedTestCase* aTestCase, 
+                     TInt aFlags );
+                                                                      
+        /**
+        * Function is called when test framework prints error.
+        */
+        void Error( TErrorNotification& aError );
+        
+        /**
+        * Function is called when testframework 
+        * wants to print a popup window.
+        */
+        TInt PopupMsg( const TDesC& aLine1, 
+                       const TDesC& aLine2, 
+                       TInt aTimeInSecs );
+        
+        /**
+        * Function is called when testframework 
+        * wants to print a popup window and 
+        * get the key pressed.
+        */
+        TInt PopupMsg( const TDesC& aLine1, 
+                       const TDesC& aLine2, 
+                       TInt aTimeInSecs,
+                       TKeyCode& aKey,
+                       TRequestStatus& aStatus );
+
+        /**
+        * Close instance.
+        */
+        void Close( TInt aHandle );
+                
+        /**
+        * Console UI panic function
+        */
+        static void Panic( TConsoleUIPanic aPanic );
+
+        /**
+        * Return pointer to console
+        */
+        
+        RConsole* GetConsole();
+
+        /**
+        * Called from timer to perform scrolling
+        */
+        void TimerUpdate();
+                
+        /**
+        * Process keystokes.
+        */
+        void KeyPressed();
+        
+        TKeyCode mapKey();
+
+        /**
+         * Displays no memory error message and closes ConsoleUI
+         */
+        void ExitWithNoMemoryErrorMessage();
+        
+        /**
+         * Returns MainMenu of console
+         */
+        CMainMenu* GetMainMenu();
+        
+        /**
+         * Get filter array for reading purpose
+         */
+        const RPointerArray<TDesC>& GetFilterArray(void) const;
+        
+        /**
+         * Set info about which index filter is used
+         */
+        void SetFilterIndex(TInt aFilterIndex);
+
+        /**
+         * Get info about which index filter is used
+         */
+        TInt GetFilterIndex(void);
+        
+    public: // Functions from base classes
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CConsoleMain();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+
+        /**
+        * Print error from ConsoleUI.
+        */  
+        void UiError( const TDesC& aInfo );
+        
+        /**
+        * Process command line parameters.
+        */
+        void ProcessCommandlineL( TFileName& aIniFile );
+
+        /**
+        * Parse and search for module info and fill list of modules.
+        */
+        void ParseTestModulesL(CStifParser* aParser, CTestModuleList* aModuleList, const TDesC& aSectionStart, const TDesC& aSectionEnd);
+        
+    public:   //Data
+        RPointerArray<CMenuDialog> iDialogs;
+        
+        TConsoleKey key; 
+        
+    protected:  // Data
+        // None
+
+    private:    // Data
+        //CConsoleBase*       iConsole;       // Pointer to console
+        RConsole iConsole; // Pointer to console
+        TBool 				rConsoleCreated;
+
+        CMenu*              iMainMenu;      // Root menu
+        CMenu*              iCurrentMenu;   // Current menu
+
+        CScrollerTimer*     iScroller;
+        
+        CConsoleReader*     iReader;        // Console reader                   
+    
+        // For starting runnning multiple cases upon start
+        TStartCasesOnStart  iStartCases;
+        HBufC*              iTestModule;
+        HBufC*              iTestModuleIni;
+        HBufC*              iTestCaseFile;
+        TInt                iTestCaseNum;
+        HBufC*              iTestSetName;
+
+        // List of found modules (included from module given in parameters)
+        CTestModuleList*    iModuleList;
+        
+        // List of filters (for test cases title)
+        RPointerArray<TDesC> iFilters;
+        
+        // Chosen filter index
+        TInt iChosenFilterIndex;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+    
+// DESCRIPTION
+// Read keystrokes from console
+class CConsoleReader
+    :public CActive
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CConsoleReader* NewL( CConsoleMain* aMain, 
+                                     //CConsoleBase* aConsole );
+                                     RConsole* aConsole );
+
+        /**
+        * Start
+        */
+        void StartL();
+
+        /**
+        * Destructor of CConsoleReader.
+        */
+        ~CConsoleReader();
+
+
+    public: // New functions
+
+    public: // Functions from base classes
+
+        /**
+        * RunL derived from CActive handles the completed requests.
+        */
+        void RunL();
+
+        /**
+        * DoCancel derived from CActive handles the Cancel
+        */
+        void DoCancel();
+        /**
+        * RunError derived from CActive handles errors from active object
+        */        
+        virtual TInt RunError(TInt aError);
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CConsoleReader( CConsoleMain* aMain, 
+                        //CConsoleBase* iConsole );
+                        RConsole* iConsole );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public:   //Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        //CConsoleBase*   iConsole;   // Pointer to console
+        RConsole*   iConsole;   // Pointer to console
+        CConsoleMain*   iMain;      // Backpointer
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif // CONSOLEUI_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TouchConsoleUI/src/ConsoleNotify.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,480 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CMenuNotifier 
+* and CMenuDialog class implementations.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+#include <f32file.h>
+#include "ConsoleUI.h"
+#include "ConsoleMenus.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+const TInt KDefaultTime = 2;
+
+// MACROS
+#ifndef __WINS__
+  #define GETPTR &
+#else
+  #define GETPTR
+#endif
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+   
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuNotifier
+
+    Method: NewL
+
+    Description: Constructs new menu notifier
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenuNotifier* CMenuNotifier::NewL( const TDesC& aError, CConsoleMain* aMain )
+    {
+
+    CMenuNotifier* self = new ( ELeave ) CMenuNotifier( aMain );
+    CleanupStack::PushL( self );
+    self->ConstructL( aError );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuNotifier
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenuNotifier::ConstructL( const TDesC& aError )
+    {
+    
+    //TSize size = iMain->GetConsole()->ScreenSize();
+    TSize size;
+    iMain->GetConsole()->Size(size);
+    
+    size.iWidth = Min( size.iWidth - KMenuOverhead, 
+                       aError.Length() );
+    size.iHeight = aError.Length()/size.iWidth + 2;
+    
+    iConsole = Console::NewL( _L("Error note"), size );
+    
+    iConsole->Printf( _L("Error:") );    
+    iConsole->Printf( aError ); 
+    iConsole->Printf( _L("\n") );
+    iConsole->Printf( _L("Press any key") );
+
+    iTimer.CreateLocal();
+
+    CActiveScheduler::Add ( &iCallBack1 );
+    CActiveScheduler::Add ( &iCallBack2 );
+
+    // Get timer
+    iTimer.After( iCallBack1.Activate(), 10000000 );
+
+    // Poll keypresses
+    iConsole->Read ( iCallBack2.Activate() );        
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuNotifier
+
+    Method: CMenuNotifier
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+#pragma warning( disable : 4355 )       // Incomplete this usage
+CMenuNotifier::CMenuNotifier( CConsoleMain* aMain ): 
+    iCallBack1 ( this, GETPTR CMenuNotifier::Run1 ),
+    iCallBack2 ( this, GETPTR CMenuNotifier::Run1 ),
+    iMain( aMain )          
+    {
+    }
+#pragma warning( default : 4355 )
+
+/*
+-------------------------------------------------------------------------------
+e
+    Class: CMenuNotifier
+
+    Method: ~CMenuNotifier
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CMenuNotifier::~CMenuNotifier()
+    {
+
+    delete iConsole;    
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuNotifier
+
+    Method: Run1
+
+    Description: Callback function. Closes dialog
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenuNotifier::Run1()
+    {
+
+    if ( iCallBack1.isCompleted() && iCallBack2.isCompleted() )
+        {
+        // Both callback have been done, delete this object
+        delete this;
+        return;
+        }
+    else
+        {
+        // One callback finished, stop listening anything else
+        iConsole->ReadCancel();
+        iTimer.Cancel();
+        }
+    }  
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: NewL
+
+    Description: Constructs new menu dialog
+
+    Parameters: const TDesC& aMessage: in: Message to dialog
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenuDialog* CMenuDialog::NewL( CConsoleMain* aMain,
+                                const TDesC& aLine1, 
+                                const TDesC& aLine2, 
+                                TInt aTimeInSecs )
+    {
+
+    CMenuDialog* self = new ( ELeave ) CMenuDialog( aMain );
+    CleanupStack::PushL( self );
+    self->ConstructL( aLine1, aLine2, aTimeInSecs );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: const TDesC& aMessage: in: Message to dialog
+    
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenuDialog::ConstructL( const TDesC& aLine1, 
+                              const TDesC& aLine2, 
+                              TInt aTimeInSecs )
+    {
+    
+    //TSize size = iMain->GetConsole()->ScreenSize();
+    TSize size;
+    iMain->GetConsole()->Size(size);
+    
+    size.iWidth = Min( size.iWidth - KMenuOverhead, 
+                       Max( aLine1.Length(), aLine2.Length() ) );
+    size.iHeight = aLine1.Length()/size.iWidth + aLine2.Length()/size.iWidth + 2;
+    
+    iConsole = Console::NewL( _L("Info"), size );
+    
+    if( aLine1.Length() > 0 )
+        {
+        iConsole->Printf( aLine1 );
+        }
+    if( aLine2.Length() > 0 )
+        {
+        iConsole->Printf( _L("\n") );
+        iConsole->Printf( aLine2 );
+        }
+    
+    if( aTimeInSecs == 0 )
+        {
+        aTimeInSecs = KDefaultTime;
+        }
+    iTimer.CreateLocal();
+
+    CActiveScheduler::Add ( &iCallBack1 );
+    // Get timer
+    iTimer.After( iCallBack1.Activate(), aTimeInSecs*1000*1000 );
+           
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: CMenuDialog
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+#pragma warning( disable : 4355 )       // Incomplete this usage
+CMenuDialog::CMenuDialog( CConsoleMain* aMain ):  
+    iMain( aMain ),      
+    iCallBack1 ( this, GETPTR CMenuDialog::Run1 ), 
+    iCallBack2 ( this, GETPTR CMenuDialog::Run1 )
+    {
+    }
+#pragma warning( default : 4355 )
+
+/*
+-------------------------------------------------------------------------------
+e
+    Class: CMenuDialog
+
+    Method: ~CMenuDialog
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CMenuDialog::~CMenuDialog()
+    {
+ 
+    if( iCallBack1.IsActive() )
+        {
+        iTimer.Cancel();
+        iTimer.Close();
+        iCallBack1.Cancel();
+        }
+        
+    if( iCallBack2.IsActive() )
+        {
+        User::RequestComplete( iStatus, KErrCancel );
+		if( iConsole != NULL )
+			{
+			iConsole->ReadCancel();    
+			}
+        iCallBack2.Cancel();
+        }
+        
+    delete iConsole;    
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: Run1
+
+    Description: Callback function. Closes dialog
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenuDialog::Run1()
+    {
+
+    if ( iCallBack2.isCompleted() )
+        {            
+        *iKeyCode = iConsole->KeyCode();
+    
+        User::RequestComplete( iStatus, iCallBack2.Status().Int() );
+        }
+        
+    TInt index = iMain->iDialogs.Find( this );
+    if( index >= 0 )
+        {
+        iMain->iDialogs.Remove( index );
+        }
+    // Timeout, delete this object
+    delete this;
+    return;
+
+    }  
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenuDialog
+
+    Method: WaitForKeypress
+
+    Description: Wait for keypress
+
+    Parameters: None
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CMenuDialog::WaitForKeypress( TKeyCode& aKeyCode, 
+                                   TRequestStatus& aStatus )
+    {
+    
+    aStatus = KRequestPending;
+    iKeyCode = &aKeyCode;
+    iStatus = &aStatus;
+    
+    CActiveScheduler::Add ( &iCallBack2 );
+     
+    // Poll keypresses
+    iConsole->Read( iCallBack2.Activate() );        
+
+    return KErrNone;
+    
+    }  
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TouchConsoleUI/src/ConsoleUI.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,2282 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of CConsoleMain 
+* and CModule class member functions.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+#include <f32file.h>
+#include <hal.h>
+#include <hal_data.h>
+
+
+
+#include <stifinternal/UIStoreIf.h>
+
+#include "ConsoleUI.h"
+#include "ConsoleMenus.h"
+
+#include "StifTestInterface.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+_LIT(KNameTxt,"STIF");
+_LIT( KConsoleMain, "CConsoleMain" );
+
+// Commandline params
+_LIT( KTestModule,      "-testmodule" );
+_LIT( KTestModuleIni,   "-testmoduleini" );
+_LIT( KTestCaseFile,    "-testcasefile" );
+_LIT( KTestSet,         "-testset" );
+_LIT( KTestRun,         "-run" );
+_LIT( KTestRunAll,      "all" );
+_LIT( KTestRunSeq,      "sequential" );
+_LIT( KTestRunPar,      "parallel" );
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+LOCAL_C void MainL();
+
+
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// None
+
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: NewL
+
+    Description: Construct the console main class
+
+    Parameters: None
+
+    Return Values: CConsoleMain*                    New object
+
+    Errors/Exceptions: Leaves if memory allocation fails or
+                       ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleMain* CConsoleMain::NewL( )
+    {
+
+    CConsoleMain* self = new ( ELeave ) CConsoleMain();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Construct the console
+    Construct module and case containers
+    Retrieve command line parameters
+    Connect to test engine
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation fails or fileserver or
+                       test engine can't be connected.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::ConstructL( )
+    {
+    _LIT( KEnableMaximised,  "+Maximised" );
+    //_LIT( KDisableMaximised, "-Maximised" );
+    _LIT( KEnableInform,     "+Inform" );
+    //_LIT( KDisableInform,    "-Inform" );
+    _LIT( KEnableRaw,        "+Raw" );
+    //_LIT( KDisableRaw,       "-Raw" );
+    _LIT( KEnablePointer,    "+Pointer" );
+    //_LIT( KDisablePointer,   "-Pointer" );
+    //_LIT( KDescription,   "-Pointer" );
+    
+    CUIStoreIf::ConstructL();
+
+    rConsoleCreated = false;
+    // Construct the console
+    //iConsole = Console::NewL( KNameTxt,
+    //                         TSize( KConsFullScreen, KConsFullScreen ) );
+ 
+    TInt ret = iConsole.Create(); 
+    
+    if(ret != KErrNone)
+    	{
+    	RDebug::Print(_L("Could not create console, err = (%d)"), ret);
+    	User::Leave(ret);
+    	}
+    
+    rConsoleCreated = true;
+    
+    ret = iConsole.Init(KNameTxt, TSize( KConsFullScreen, KConsFullScreen ));
+    if(ret != KErrNone)
+    	{
+    	RDebug::Print(_L("Could not initialize console, err = (%d)"), ret);
+    	User::Leave(ret);
+    	}
+    
+    ret = iConsole.Control( KEnableMaximised );
+    if(ret != KErrNone)
+    	{
+    	RDebug::Print(_L("Could not initialize console controls(+Maximised), err = (%d)"), ret);
+    	User::Leave(ret);
+    	}
+    ret = iConsole.Control( KEnableInform );
+    if(ret != KErrNone)
+        	{
+        	RDebug::Print(_L("Could not initialize console controls(+Inform), err = (%d)"), ret);
+        	User::Leave(ret);
+        	}
+    ret = iConsole.Control( KEnablePointer );
+    if(ret != KErrNone)
+        	{
+        	RDebug::Print(_L("Could not initialize console controls(+Pointer), err = (%d)"), ret);
+        	User::Leave(ret);
+        	}
+    ret = iConsole.Control( KEnableRaw );
+    if(ret != KErrNone)
+        	{
+        	RDebug::Print(_L("Could not initialize console controls(+Raw), err = (%d)"), ret);
+        	User::Leave(ret);
+        	}
+    
+    
+
+    RDebug::Print(_L("Creating module list object"));
+    TRAPD(err, iModuleList = CTestModuleList::NewL(NULL));
+    if(err != KErrNone)
+        {
+        RDebug::Print(_L("Could not create module list (%d)"), err);
+        UiError(_L("Could not create module list (err)"));
+        User::Leave(err);
+        }
+    if(!iModuleList)
+        {
+        RDebug::Print(_L("Could not create module list (NULL)"));
+        UiError(_L("Could not create module list (NULL)"));
+        User::Leave(KErrGeneral);
+        }
+
+    // Get command line parameters
+    TFileName iniFile; // TestFramework initialization file
+                    
+    ProcessCommandlineL( iniFile );
+
+    if(iTestModule)
+        {
+        // Add to module list info about module taken from command line
+        RDebug::Print(_L("Adding command line module to list"));
+        TName moduleName;
+        moduleName.Copy(iTestModule->Des());
+        moduleName.LowerCase();
+        err = iModuleList->AddTestModule(moduleName);
+        if(err != KErrNone && err != KErrAlreadyExists)
+            {
+            RDebug::Print(_L("Could not add module to list of modules (%d)"), err);
+            UiError(_L("Could not add module to list of modules (err)"));
+            User::Leave(err);
+            }
+
+        //Get added module
+        CTestModuleInfo* moduleInfo = iModuleList->GetModule(moduleName);
+        if(!moduleInfo)
+            {
+            RDebug::Print(_L("Could not add get module info from list"));
+            UiError(_L("Could not add get module info from list"));
+            User::Leave(KErrGeneral);
+            }
+
+        //Add ini file if given
+        if(iTestModuleIni && iTestModuleIni->Length() > 0)
+            {
+            TFileName filename;
+            filename.Copy(iTestModuleIni->Des());
+            filename.LowerCase();
+            moduleInfo->SetIniFile(filename);
+            }
+
+        //Add config file if given
+        if(iTestCaseFile && iTestCaseFile->Length() > 0)
+            {
+            TFileName filename;
+            filename.Copy(iTestCaseFile->Des());
+            filename.LowerCase();
+            moduleInfo->AddCfgFile(filename);
+            }
+
+        //Now check all config files if there are included modules
+        _LIT(KIncludeModuleStart, "[New_Include_Module]");
+        _LIT(KIncludeModuleEnd, "[End_Include_Module]");
+
+        RDebug::Print(_L("Start parsing included modules"));
+        CTestCaseFileInfo* finfo = iModuleList->GetUncheckedCfgFile();
+        while(finfo)
+            {
+            TFileName fname;
+            finfo->GetCfgFileName(fname);
+
+            RDebug::Print(_L("Checking file: '%S'"), &fname);
+            finfo->SetChecked();
+
+            CStifParser* parser = NULL;
+ 
+            TRAP(err, parser = CStifParser::NewL(_L(""), fname));
+            if(err != KErrNone)
+                {
+                RDebug::Print(_L("Could not create parser to read content of config file (%d)"), err);
+                UiError(_L("Could not create parser to read content of config file (err)"));
+                User::Leave(err);
+                }
+            CleanupStack::PushL(parser);
+
+            ParseTestModulesL(parser, iModuleList, KIncludeModuleStart, KIncludeModuleEnd);
+
+            CleanupStack::PopAndDestroy(parser);
+            finfo = iModuleList->GetUncheckedCfgFile();
+            }
+        RDebug::Print(_L("End parsing included modules"));
+        }
+
+    //iConsole->Printf(_L("\nTest Framework starting\n"));
+    iConsole.Write(_L("\nTest Framework starting\n"));
+
+    // CUIStore open
+    User::LeaveIfError( UIStore().Open( iniFile ) );
+    
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: CConsoleMain
+
+    Description: Constructor.
+    Initialize non-zero member variables.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleMain::CConsoleMain( ):iStartCases( EStartCaseNo )
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ~CConsoleMain
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleMain::~CConsoleMain( )
+    {	
+
+    iDialogs.ResetAndDestroy();
+    iDialogs.Close();
+ 
+    // CUIStore close
+    UIStore().Close();
+    
+    delete iReader;
+    iReader = NULL;
+    
+	delete iScroller;
+	iScroller = NULL;
+    
+    //delete iConsole;
+    //iConsole = NULL;
+	if(rConsoleCreated){
+		iConsole.Destroy();
+	}
+    delete iMainMenu;
+    iMainMenu = NULL;
+
+    delete iTestModule;
+    iTestModule = 0;
+    
+    delete iTestModuleIni;
+    iTestModuleIni = 0;
+    
+    delete iTestCaseFile;
+    iTestCaseFile = 0;
+    
+    delete iTestSetName;
+    iTestSetName = 0;
+
+    delete iModuleList;
+    iModuleList = 0;
+    
+    iFilters.ResetAndDestroy();
+    iFilters.Close();
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ProcessCommandlineL
+
+    Description: Process commandline parameters.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves on error.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::ProcessCommandlineL( TFileName& aIniFile )
+    {
+
+	User me;
+    TInt lineLength = me.CommandLineLength();
+    HBufC* lineBuf = HBufC::NewLC( lineLength );
+    TPtr line( lineBuf->Des() );
+    TBool firstTime = ETrue;
+    TInt offset = 0;
+    TPtrC param;
+    TChar c;
+    
+    me.CommandLine( line );
+    TLex lex( line );
+    
+    while( offset < lineLength )
+        {    
+        // Get first charecter of the parameter
+        lex.SkipSpace();
+        c = lex.Peek();
+        if( c == 0 )
+            {
+            // End of line
+            break;
+            }
+        
+        // Get the whole parameter 
+        param.Set( lex.NextToken() );
+        if( firstTime )
+            {
+            // Filebrowser workaround. It gives the exe name as command line param
+            // verify that it is not the same as the executable name
+            //@spe TFileName exePath = me.FileName();
+			TFileName exePath = RProcess().FileName();
+            if ( param == exePath )
+                {
+                // Discard command line parameters when using filebrowser
+                break;
+                }
+
+            firstTime = EFalse;
+            }
+        // Check if -param option
+        if( c == '-' )
+            {
+            // This is option
+            if( param == KTestModule )
+                {
+                // Get test module name
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test module name not given"));
+                    break;
+                    }
+                if( param.Length() > KMaxName )
+                    {
+                    UiError( _L("Test module name too long"));
+                    break;
+                    }
+                iTestModule = param.AllocL();
+                }
+            else if( param == KTestModuleIni )
+                {
+                // Get test module initialization file
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test module initialization file name not given"));
+                    break;
+                    }
+                if( param.Length() > KMaxFileName )
+                    {
+                    UiError( _L("Test module initialization file name too long"));
+                    break;
+                    }
+                TFileName tmpTestModuleIni( param );
+                TStifUtil::CorrectFilePathL( tmpTestModuleIni );
+                iTestModuleIni = tmpTestModuleIni.AllocL();
+                }
+            else if( param == KTestCaseFile )
+                {
+                // Get test case file name
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test case file name not given"));
+                    break;
+                    }
+                if( param.Length() > KMaxFileName )
+                    {
+                    UiError( _L("Test case file name too long"));
+                    break;
+                    }
+                TFileName tmpTestCaseFile( param );
+                TStifUtil::CorrectFilePathL( tmpTestCaseFile );
+                iTestCaseFile = tmpTestCaseFile.AllocL();
+                }
+            else if( param == KTestSet )
+                {
+                // Get test set name
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test set name not given"));
+                    break;
+                    }
+                if( param.Length() > KMaxFileName )
+                    {
+                    UiError( _L("Test set name too long"));
+                    
+                    break;
+                    }
+                iTestSetName = param.AllocL();
+                }
+            else if( param == KTestRun )
+                {
+                if( iStartCases )
+                    {
+                    UiError( _L("Only one -run option allowed") );
+                    // Do not start anything
+                    iStartCases = EStartCaseNo;
+                    break;
+                    }
+                // Get run type
+                lex.Mark();
+                param.Set( lex.NextToken() );
+                if( param.Length() == 0 )
+                    {
+                    UiError( _L("Test set name not given"));
+                    break;
+                    }
+                if( ( param == KTestRunAll ) ||
+                    ( param == KTestRunSeq ) )
+                    {
+                    iStartCases = EStartCasesSeq;
+                    }
+                else if( param == KTestRunPar )
+                    {
+                    iStartCases = EStartCasesPar;
+                    }
+                else
+                    {
+                    lex.UnGetToMark();
+                    lex.SkipSpace();
+                    if( lex.Val( iTestCaseNum ) != KErrNone )
+                        { 
+                        UiError( _L("Unknown run type given, valid values are all/sequential/parallel/test case number"));
+                        }
+                    else
+                        {
+                        iStartCases = EStartSingleCase;
+                        }    
+                    break;
+                    }
+                }            
+            }
+        else 
+            {
+            // This is Test Framework ini file
+            aIniFile = param;
+            TStifUtil::CorrectFilePathL( aIniFile );
+            // ini file is last option
+            break;
+            }
+        
+        }
+      
+    CleanupStack::PopAndDestroy( lineBuf );
+
+    }
+    
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: Panic
+
+    Description: Console UI panic function
+
+    Parameters: TInt
+
+    Return Values: 
+
+    Errors/Exceptions: Does not return.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::Panic(TConsoleUIPanic aPanic )
+    {
+        
+    User::Panic (_L("STIF TestFramework Console UI panic"), aPanic );
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: StartL
+
+    Description: Construct menu objects and start the menu handling
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions:
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CConsoleMain::StartL()
+    {
+    
+    // Construct keystroke reader
+    iReader           = CConsoleReader::NewL( this, &iConsole );
+
+    // Construct the main menu
+    TInt majorV;
+    TInt minorV;
+    TInt buildV;
+    TBuf<30> relDate;
+    TStifUtil::STIFVersion(majorV, minorV, buildV, relDate);
+    
+    TBuf<128> version;
+    version.Format(_L("STIF v%d.%d.%d - "), majorV, minorV, buildV);
+    version.Append(relDate);
+    version.Append(_L("\n"));
+    iMainMenu = CMainMenu::NewL( this, NULL, _L("Main menu"), version );
+
+    // Add the case menu
+    CMenu* caseMenu   = CMenu::NewL( this, iMainMenu, _L("Case menu") );
+    iMainMenu->AddItemL ( caseMenu );
+
+    // Add the module menu
+    CMenu* moduleMenu = CModuleListView::NewL( this, iMainMenu, _L("Module menu") );
+    iMainMenu->AddItemL ( moduleMenu );
+
+    // Add test set menu
+    CTestSetMenu* testSetMenu = CTestSetMenu::NewL( this, iMainMenu, _L("Test set menu") );
+    iMainMenu->AddItemL ( testSetMenu );
+ 
+    // Construct the case menus
+    CMenu* casestart  = NULL;
+    CMenu* casestartshow  = NULL;
+    
+    // Load filters
+    UIStore().ReadFiltersL(iFilters);
+    
+    // If there are no filters defined, then construct menu without filter's menu
+    if(iFilters.Count() == 0)
+        {
+        casestart = CCaseStartMenu::NewL(this, caseMenu, _L("Start new case"));
+        caseMenu->AddItemL(casestart);
+    CMenu* casestartshow  = NULL;
+        casestartshow = CCaseStartMenu::NewL(this, caseMenu, _L("Start & show output"), ETrue);
+        caseMenu->AddItemL(casestartshow);
+        }
+    else // if there are filters defined, create also filter's menu
+        {
+        CFilterMenu* filtercasestart = NULL;
+        CFilterMenu* filtercasestartshow = NULL;
+        
+        filtercasestart = CFilterMenu::NewL(this, caseMenu, _L("Start new case (filter)"));
+        caseMenu->AddItemL(filtercasestart);
+        casestart = CCaseStartMenu::NewL(this, caseMenu, _L("Start new case"));
+        filtercasestart->SetTestCaseMenu(casestart);
+        
+        filtercasestartshow = CFilterMenu::NewL(this, caseMenu, _L("Start & show output (filter)"));
+        caseMenu->AddItemL(filtercasestartshow);
+        casestartshow = CCaseStartMenu::NewL(this, caseMenu, _L("Start & show output"), ETrue);
+        filtercasestartshow->SetTestCaseMenu(casestartshow);
+        }
+
+	CMultipleCaseMenu* multicasestart =
+	    CMultipleCaseMenu::NewL (this, caseMenu, _L("Run multiple tests") );
+    caseMenu->AddItemL( multicasestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Ongoing cases"), 
+        CUIStoreIf::EStatusRunning );
+    caseMenu->AddItemL( casestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Executed cases"), 
+        CUIStoreIf::EStatusExecuted );
+    caseMenu->AddItemL( casestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Passed cases"), 
+        CUIStoreIf::EStatusPassed );
+    caseMenu->AddItemL( casestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Failed cases"), 
+        CUIStoreIf::EStatusFailed );
+    caseMenu->AddItemL( casestart );
+    casestart = CCaseMenu::NewL ( this, caseMenu, _L("Aborted/Crashed cases"), 
+        ( CUIStoreIf::EStatusAborted | CUIStoreIf::EStatusCrashed) );
+    caseMenu->AddItemL( casestart );
+    //Add "test set choice" menu
+    CTestSetChoiceMenu* testChoiceMenu = CTestSetChoiceMenu::NewL( this, testSetMenu, _L("Load test set") );
+ 	testSetMenu->AddItemL( testChoiceMenu );
+
+    // Start stuff according to command line parameters
+    if( iTestSetName )
+        { 
+        // Set test set name
+        testSetMenu->SetTestSetFileName( iTestSetName->Des() );
+        
+        // Load test set
+        if( UIStore().LoadTestSet( iTestSetName->Des() ) != KErrNone )
+ 	       {
+           UiError( _L("Test set loading failed"));
+           }
+        else 
+           {
+           // Inform test set menu that set is loaded
+           testSetMenu->SetCreated();
+    
+            // Check if test set should be started
+    	    if( ( iStartCases == EStartCasesPar ) || 
+    	    	( iStartCases == EStartCasesSeq ))         	
+            	{
+            
+	            // Check set starting type
+    	    	CStartedTestSet::TSetType setType = 
+       	        CStartedTestSet::ESetSequential;
+       	        
+                if( iStartCases == EStartCasesPar )
+                    {
+                    setType = 
+                        CStartedTestSet::ESetParallel;
+                    }
+                    
+                // Start test set
+                RRefArray<CTestSetInfo> setInfos;
+                TInt ret = UIStore().TestSets( setInfos );
+                if( (  ret != KErrNone ) ||
+                    ( setInfos.Count() != 1 ) )
+                    {
+                    // Should never ever happen
+                    User::Panic( KConsoleMain, KErrGeneral );
+                    }
+                
+                const CTestSetInfo& set = setInfos[0];
+                setInfos.Reset();
+                setInfos.Close();
+                
+                TInt index;
+                ret = UIStore().StartTestSet( set, index, setType );
+                if( ret != KErrNone )
+                    {
+                    UiError( _L("Test set starting failed") );
+                    }
+                } 
+            }
+        delete iTestSetName;
+        iTestSetName = 0;     
+        }
+    if( iTestModule )
+        {
+        TPtrC module( iTestModule->Des() ); 
+
+        // Add all test modules and config files
+        RDebug::Print(_L("Start creating test modules"));
+        CTestModuleInfo* moduleInfo = NULL;
+        TInt i;
+        TInt modCnt = iModuleList->Count();
+        TInt ret;
+
+        for(i = 0; i < modCnt; i++)
+            {
+            RDebug::Print(_L("Processing module"));
+            // Get module
+            moduleInfo = iModuleList->GetModule(i);
+            if(!moduleInfo)
+                {
+                RDebug::Print(_L("Could not get module info at index %d"), i);
+                continue;
+                }
+
+            // Get module name
+            TName moduleName;
+            moduleInfo->GetModuleName(moduleName);
+            RDebug::Print(_L("module name: '%S'"), &moduleName);
+
+            // Get ini file, if exists
+            TFileName ini;
+            moduleInfo->GetIniFileName(ini);
+            if(ini.Length() == 0)
+                {
+                RDebug::Print(_L("ini file not found"));
+                }
+            else
+                {
+                RDebug::Print(_L("ini file: '%S'"), &ini);
+                }
+
+            // Create test module
+            RDebug::Print(_L("Adding module to UI store"));
+            ret = UIStore().AddTestModule(moduleName, ini);
+            if(ret != KErrNone && ret != KErrAlreadyExists)
+                {
+                RDebug::Print(_L("Test module adding failed (%d)"), ret);
+                UiError(_L("Test module adding failed"));
+                continue;
+                }
+
+            //Add test case files
+            TInt cfgCnt = moduleInfo->CountCfgFiles();
+            TInt j;
+            TFileName cfgFile;
+            for(j = 0; j < cfgCnt; j++)
+                {
+                moduleInfo->GetCfgFileName(j, cfgFile);
+                if(cfgFile.Length() > 0)
+                    {
+                    RDebug::Print(_L("config file: '%S'"), &cfgFile);
+
+                    ret = UIStore().AddTestCaseFile(moduleName, cfgFile);
+                    if(ret != KErrNone)
+                        {
+                        // Log error
+                        RDebug::Print(_L("Test case file adding failed (%d)"), ret);
+                        UiError(_L("Test case file adding failed"));
+                        continue;
+                        }
+                    }
+                else
+                    {
+                    RDebug::Print(_L("Got empty cfg file"));
+                    }
+                }
+            if(cfgCnt == 0)
+                {
+                RDebug::Print(_L("cfg file not found"));
+                }
+
+            RDebug::Print(_L("Module '%S' processed correctly"), &moduleName);
+            }
+
+        RDebug::Print(_L("End creating test modules"));
+
+        if( ( iStartCases == EStartCasesPar ) ||
+            ( iStartCases == EStartCasesSeq ) )
+            {
+            // Start running
+            CMultipleBaseMenu::TRunType runType = 
+                CMultipleBaseMenu::ERunSequential;
+            if( iStartCases == EStartCasesPar )
+                {
+                runType = CMultipleBaseMenu::ERunParallel;
+                }
+            TRAPD( err,
+                //multicasestart->StartRunningL( runType, module, file );
+                multicasestart->StartRunningL(runType, KNullDesC, KNullDesC);
+                );
+            if( err != KErrNone )
+                {
+                UiError( _L("Stating test cases failed") );
+                }
+            }
+        else if( iStartCases == EStartSingleCase )
+            {
+            // Get test case
+            RRefArray<CTestInfo> testCases;
+            //ret = UIStore().TestCases( testCases, module, file );
+            ret = UIStore().TestCases(testCases, KNullDesC, KNullDesC);
+            if( ret == KErrNone )
+                {
+                if( ( iTestCaseNum < 0 ) ||
+                    ( iTestCaseNum >= testCases.Count() ) )
+                    {
+                    ret = KErrNotFound;
+                    }
+                else
+                    {         
+                    TInt index;           
+                    // Start single test case
+                    ret = UIStore().StartTestCase( testCases[iTestCaseNum], index );
+                    }                                       
+                }
+            testCases.Reset();       
+            testCases.Close();
+            if( ret != KErrNone )
+                {
+                UiError( _L("Starting test case failed"));        
+                }
+            }
+
+        delete iTestCaseFile;
+        iTestCaseFile = 0;
+        delete iTestModuleIni;
+        iTestModuleIni = 0;
+        delete iTestModule;
+        iTestModule = 0;
+        }
+        
+    iStartCases = EStartCaseNo;
+    
+    // Load testcase if some stored 
+    UIStore().LoadSavedTestCases();
+           
+	iScroller = CScrollerTimer::NewL ( this );
+	iScroller->StartL();	
+
+    // Print the main menu
+    iCurrentMenu = iMainMenu;
+    iCurrentMenu->PrintMenuL( CMenu::EMenuPrint );
+
+    // Start to process keyboard events
+    iReader->StartL();
+    
+    return KErrNone;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: KeyPressed
+
+    Description: Process keyboard events. Print new menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if SelectL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::KeyPressed()
+    {
+
+    TBool cont = ETrue;
+
+    // Read the key
+   // TKeyCode key = iConsole->KeyCode();
+    
+    TKeyCode key = mapKey();
+    if(key == EKeyNull)
+    	{
+    	iReader->StartL();
+    	return;
+    	}
+//    TKeyCode key = EKeyDownArrow; //TODO
+    CMenu* tmp = iCurrentMenu;
+
+    // Let the menu handle the key press
+    TRAPD( err, 
+        iCurrentMenu = iCurrentMenu->SelectL( key, cont );
+        );
+    if( err != KErrNone )
+        {
+        User::InfoPrint( 
+            _L("Processing keystroke failed") );  
+        }
+            
+    if ( iCurrentMenu == NULL )
+        {
+        iCurrentMenu = tmp;
+        }
+
+   // If "not-exit" key pressed, continue
+    if ( cont )
+        {
+
+        // Either only update old menu or new menu.
+        if ( tmp == iCurrentMenu )
+            {
+            TRAP( err, iCurrentMenu->PrintMenuL( CMenu::EMenuRefresh ); );
+            }
+        else
+            {
+            TRAP( err, iCurrentMenu->PrintMenuL( CMenu::EMenuPrint ); )
+            }
+        
+        if( err != KErrNone )
+            {
+            if ( err == KErrNoMemory )
+            	{            	
+            	ExitWithNoMemoryErrorMessage();                
+            	}
+            else
+            	{
+	            User::InfoPrint( 
+	                _L("Printing menu failed") );
+            	}
+            }
+
+        // Enable keystrokes
+        iReader->StartL();
+
+        }
+    else
+        {
+        // "Exit", stop scheduler and exit
+        CActiveScheduler::Stop();
+        }
+
+    }
+
+
+TKeyCode CConsoleMain::mapKey()
+	{
+	TInt event   = key.Type();
+	TInt keyCode = key.Code();
+	
+	if( event == TRawEvent::EButton1Down )
+		{
+		TInt ret;
+		//displayXPixels contains X of screen resolution
+		TInt displayXPixels;    
+		//retrieve EDisplayXPixels value of this phone
+		ret = HAL::Get( HALData::EDisplayXPixels, displayXPixels );
+		 
+		//displayYPixelscontains Y of screen resolution
+		TInt displayYPixels;    
+		//retrieve EDisplayYPixels value of this phone
+		ret =HAL::Get( HALData::EDisplayYPixels, displayYPixels );
+		
+		if(ret != KErrNone)
+			{
+			UiError( _L("Unable to get screen resolution"));
+			}
+		
+	//if(keyCode ==EKeyEnter )
+		TPoint currPos = key.MousePos();	
+		if(currPos.iY < ((displayYPixels/2)-(displayYPixels*0.3)) && currPos.iX < (displayXPixels -(displayXPixels*0.2)) && currPos.iX >(displayXPixels*0.3) )
+			{
+			return EKeyUpArrow;
+			}
+		else if(currPos.iY > (displayYPixels/2+(displayYPixels*0.3))&& currPos.iX < (displayXPixels -(displayXPixels*0.2)) && currPos.iX >(displayXPixels*0.3))
+			{
+			return EKeyDownArrow;
+			}
+		if(currPos.iX < ((displayXPixels/2)-(displayXPixels*0.3)) && currPos.iY < (displayYPixels -(displayYPixels*0.2)) && currPos.iY >(displayYPixels*0.3) )
+			{
+			return EKeyLeftArrow;
+			}
+		else if(currPos.iX > (displayXPixels/2+(displayXPixels*0.3))&& currPos.iY < (displayYPixels -(displayYPixels*0.2)) && currPos.iY >(displayYPixels*0.3))
+			{
+			return EKeyRightArrow;
+			}
+		
+		
+		}
+	else if (event == TRawEvent::EKeyDown)
+		{
+		 switch (keyCode) 
+			{
+			case 16:
+				return EKeyUpArrow;
+			case 17:
+				return EKeyDownArrow;
+			case 15:
+				return EKeyRightArrow;
+			case 14:
+				return EKeyLeftArrow;
+			case 851971:
+				return EKeyEnter;
+			case 4:
+				return EKeyEscape;
+				
+			// Additional keys
+			case 180: 
+				return EKeyHome;
+							
+			default:
+				return EKeyNull;
+
+			}
+		}
+	return EKeyNull;
+	}
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ExitWithNoMemoryErrorMessage
+
+    Description: Displays no memory error message and closes ConsoleUI
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::ExitWithNoMemoryErrorMessage()
+	{
+    // "Exit", stop scheduler and exit
+    CActiveScheduler::Stop();
+
+    _LIT( KErrorTitle, "Error:\n" );
+    _LIT( KErrorMessage, "Test cases execution have been stopped. ConsoleUI does not have enough memory to store information about executed test cases.  Results of executed test cases can be found in TestReport file. ConsoleUI will be closed now." );
+    _LIT( KErrorPressAnyKey, "\n\nPress any key" );
+    
+//    TSize size = GetConsole()->ScreenSize();
+    TSize size;
+    GetConsole()->Size(size);
+    size.iWidth = Min( size.iWidth - KMenuOverhead, 
+                       KErrorMessage().Length() );
+    size.iHeight = ( KErrorTitle().Length() + KErrorMessage().Length() + 
+    				 KErrorPressAnyKey().Length() ) / size.iWidth + 3;
+    
+    CConsoleBase* console = NULL;
+    TRAPD( err, console = Console::NewL( _L("Error note"), size ) );
+    if ( err != KErrNone )
+    	{
+    	// We can't create console, exit without displaying error message
+    	return;
+    	}
+    
+    console->Printf( KErrorTitle );    
+    console->Printf( KErrorMessage ); 
+    console->Printf( KErrorPressAnyKey );
+        
+    console->Getch();
+    
+    delete console;    
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: UiError
+
+    Description: Function is called when UI hit an error.
+    
+    Parameters: const TDesC& aInfo: in: information
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+void CConsoleMain::UiError( const TDesC& aInfo )
+    {
+    
+    // Error note deletes itself when it completes
+    CMenuNotifier::NewL( aInfo, this );
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: Update
+
+    Description: Receives output update notification from CUIStore.
+    
+    Parameters: CStartedTestCase* aTestCase: in: Test case information
+                TInt aFlags: in: Update reason flags
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::Update( CStartedTestCase* aTestCase, TInt aFlags )
+    {
+    
+   	TInt err( KErrNone );
+    
+    // First check if some menu should be signaled 
+    if( ( aFlags & CUIStoreIf::EStatusExecuted ) &&
+        ( aTestCase->iBackPtr ) )
+        {
+        CMenu* menu = ( CMenu* )aTestCase->iBackPtr;
+        TRAP( err, 
+            menu->SignalL( aTestCase ); 
+            );            
+        }
+
+    // Update console if needed
+    if( iCurrentMenu && ( iCurrentMenu->Type() & aFlags ) )
+        {
+        if( aFlags & CUIStoreIf::EPrintUpdate )
+            {
+            CCaseExecutionView* view = 
+                ( CCaseExecutionView* )iCurrentMenu;
+            if( view->TestCase() == aTestCase )
+                {
+                TRAP( err, iCurrentMenu->PrintMenuL( CMenu::EMenuRefresh ) );
+                }
+            }
+        else
+            {
+            TRAP( err, iCurrentMenu->PrintMenuL( CMenu::EMenuRefresh ); )
+            }
+        }
+    
+    	if ( err != KErrNone )
+    		{
+    		if ( err == KErrNoMemory )
+    			{
+    			ExitWithNoMemoryErrorMessage();
+    			}
+    		}
+    
+    }
+                                                              
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: Error
+
+    Description: Function is called when test framework prints error.
+    
+    Parameters: TErrorNotification& aError: in: Error description
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+void CConsoleMain::Error( TErrorNotification& aError )
+    {
+    
+    // Error note deletes itself when it completes
+    CMenuNotifier::NewL( aError.iText, this );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: PopupMsg
+
+    Description: Function is called when testframework 
+        wants to print a popup window.
+    
+    Parameters: TDesC& aMsg: in: message
+                
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+TInt CConsoleMain::PopupMsg( const TDesC& aLine1, 
+                             const TDesC& aLine2, 
+                             TInt aTimeInSecs )
+    {
+    
+    TInt ret = KErrNone;
+    
+    CMenuDialog* dialog = NULL;
+
+    TRAP( ret, dialog = CMenuDialog::NewL( this, aLine1, aLine2, aTimeInSecs ); );
+
+    if( ret == KErrNone )
+        {
+        iDialogs.Append( dialog ); 
+        return (TInt)dialog;
+        }
+
+    return ret;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: PopupMsg
+
+    Description: Function is called when testframework 
+        wants to print a popup window.
+    
+    Parameters: TDesC& aMsg: in: message
+                
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+TInt CConsoleMain::PopupMsg( const TDesC& aLine1, 
+                             const TDesC& aLine2, 
+                             TInt aTimeInSecs,
+                             TKeyCode& aKey,
+                             TRequestStatus& aStatus )
+    {
+    
+    TInt ret = PopupMsg( aLine1, aLine2, aTimeInSecs );
+    if( ret < 0 )
+        {
+        return ret;
+        }    
+        
+    CMenuDialog* dialog = (CMenuDialog*) ret; 
+    ret = dialog->WaitForKeypress( aKey, aStatus );
+
+    return (TInt) dialog;
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: Close
+
+    Description: Close instance.
+    
+    Parameters: TInt aHandle: in: handle to open instance.                
+
+    Return Values: Symbian OS error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::Close( TInt aHandle )
+    {
+    
+    if( aHandle < 0 )
+        {
+        return;
+        }
+    CMenuDialog* dialog = (CMenuDialog*) aHandle;
+    TInt index = iDialogs.Find( dialog );
+    if( index >= 0 )
+        {
+        delete dialog;
+        iDialogs.Remove( index );
+        }
+        
+    }
+           
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: GetConsole
+
+    Description: Returns the console
+
+    Parameters: None
+
+    Return Values: CConsoleBase*                    Console
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+//CConsoleBase* CConsoleMain::GetConsole()
+RConsole* CConsoleMain::GetConsole()
+    {
+
+    return &iConsole;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: TimerUpdate
+
+    Description: Updates current menu from timer
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::TimerUpdate()
+    {
+
+	iCurrentMenu->TimerUpdate();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: ParseTestModulesL
+
+    Description: Parse and search for module info and fill list of modules.
+
+    Parameters: CStifParser*     aParser:       in: CStifParser object
+                CTestModuleList* aModuleList:   in: list of modules
+                TPtrC&           aSectionStart: in: descriptor with start of section string
+                TPTrC&           aSectionEnd:   in: descriptor with end of section string
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if some of called leaving methods leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::ParseTestModulesL(CStifParser* aParser, CTestModuleList* aModuleList, const TDesC& aSectionStart, const TDesC& aSectionEnd)
+    {
+    //First let's find all modules given in Stif's ini file and store that info in CTestModuleList object
+    CStifSectionParser* sectionParser = NULL;
+    CStifItemParser* item = NULL;
+
+    sectionParser = aParser->SectionL(aSectionStart, aSectionEnd);
+
+    while(sectionParser)
+        {
+        RDebug::Print(_L("Found '%S' and '%S' sections"), &aSectionStart, &aSectionEnd);
+        CleanupStack::PushL(sectionParser);
+        RDebug::Print(_L("Starting to read module information"));
+
+        // Get name of module
+        _LIT(KModuleName, "ModuleName=");
+        item = sectionParser->GetItemLineL(KModuleName);
+        CleanupStack::PushL(item);
+        if(!item)
+            {
+            CleanupStack::PopAndDestroy(item);
+            UiError(_L("Line not found from module section"));
+            User::Leave(KErrGeneral);
+            }
+        else
+            {
+            RDebug::Print(_L("'%S' found"), &KModuleName);
+            }
+
+        TPtrC name;
+        TName moduleName;
+        TInt ret(KErrNone);
+        ret = item->GetString(KModuleName, name);
+        if(ret != KErrNone)
+            {
+            CleanupStack::PopAndDestroy(item);
+            RDebug::Print(_L("Module name parsing left with error (%d)"), ret);
+            UiError(_L("Module name parsing left with error (err)"));
+            User::Leave(ret);
+            }
+        else
+            {
+            RDebug::Print(_L("Module '%S' found from ini-file"), &name);
+            moduleName.Copy(name);
+            moduleName.LowerCase();
+            ret = aModuleList->AddTestModule(moduleName);
+            if(ret != KErrNone && ret != KErrAlreadyExists)
+                {
+                RDebug::Print(_L("Could not add module to list of modules (%d)"), ret);
+                UiError(_L("Could not add module to list of modules (err)"));
+                User::Leave(ret);
+                }
+            }
+        CleanupStack::PopAndDestroy(item);
+
+        //Get pointer to added module
+        CTestModuleInfo* moduleInfo = aModuleList->GetModule(moduleName);
+        if(!moduleInfo)
+            {
+                RDebug::Print(_L("Could not add get module info from list"));
+                UiError(_L("Could not add get module info from list"));
+                User::Leave(KErrNotFound);
+            }
+
+        // Get ini file, if it exists
+        RDebug::Print(_L("Start parsing ini file"));
+        _LIT(KIniFile, "IniFile=");
+        item = sectionParser->GetItemLineL(KIniFile);
+        if(item)
+            {
+            RDebug::Print(_L("'%S' found"), &KIniFile);
+            CleanupStack::PushL(item);
+            TPtrC iniFile;
+            ret = item->GetString(KIniFile, iniFile);
+            if(ret == KErrNone)
+                {
+                RDebug::Print(_L("Initialization file '%S' found, file can be empty"), &iniFile);
+                TFileName filename;
+                filename.Copy(iniFile);
+				TStifUtil::CorrectFilePathL(filename);
+                filename.LowerCase();
+                moduleInfo->SetIniFile(filename);
+                }
+            else
+                {
+                RDebug::Print(_L("Initialization file not found"));
+                }
+            CleanupStack::PopAndDestroy(item);
+            }
+        else
+            {
+            RDebug::Print(_L("'%S' not found"), &KIniFile);
+            }
+
+        // Get config (testcase) file
+        RDebug::Print(_L("Start parsing cfg files"));
+        TPtrC cfgTag;
+        for(TInt i = 0; i < 2; i++)
+            {
+            //Set tag for config files
+            if(i == 0)
+                {
+                cfgTag.Set(_L("ConfigFile="));
+                }
+                else
+                {
+                cfgTag.Set(_L("TestCaseFile="));
+                }
+            //Read data
+            item = sectionParser->GetItemLineL(cfgTag);
+            while(item)
+                {
+                CleanupStack::PushL(item);
+                RDebug::Print(_L("Item '%S' found"), &cfgTag);
+                TPtrC cfgFile;
+                ret = item->GetString(cfgTag, cfgFile);
+                if(ret == KErrNone)
+                    {
+                    RDebug::Print(_L("Configuration file '%S' found"), &cfgFile);
+                    TFileName ifile;
+                    ifile.Copy(cfgFile);
+					TStifUtil::CorrectFilePathL(ifile);
+                    ifile.LowerCase();
+                    moduleInfo->AddCfgFile(ifile);
+                    }
+                else
+                    {
+                    RDebug::Print(_L("Configuration file not found"));
+                    }
+                CleanupStack::PopAndDestroy(item);
+                item = sectionParser->GetNextItemLineL(cfgTag);
+                }
+            }
+
+        RDebug::Print(_L("Module '%S' information read correctly"), &moduleName);
+
+        // Get next section
+        CleanupStack::PopAndDestroy(sectionParser);
+        sectionParser = aParser->NextSectionL(aSectionStart, aSectionEnd);
+        }
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: GetMainMenu
+
+    Description: Return main menu of console.
+
+    Parameters: None
+
+    Return Values: CMainMenu*  pointer to main menu
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+CMainMenu* CConsoleMain::GetMainMenu()
+    {
+    return dynamic_cast<CMainMenu*>(iMainMenu);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: GetFilterArray
+
+    Description: Get filter array for reading purposes
+
+    Parameters: None
+
+    Return Values: const RPointerArray<TDesC>&  array with filters
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+const RPointerArray<TDesC>& CConsoleMain::GetFilterArray(void) const
+    {
+    return iFilters;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: SetFilterIndex
+
+    Description: Set info about which index filter is used
+
+    Parameters: TInt aFilterIndex: filter index selected by user
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleMain::SetFilterIndex(TInt aFilterIndex)
+    {
+    iChosenFilterIndex = aFilterIndex;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleMain
+
+    Method: GetFilterIndex
+
+    Description: Get info about which index filter is used
+
+    Parameters: None
+
+    Return Values: TInt: filter index selected by user
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+TInt CConsoleMain::GetFilterIndex(void)
+    {
+    return iChosenFilterIndex;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: NewL
+
+    Description: Construct a new CScrollerTimer object
+
+    Parameters: CConsoleMain*             :in:      Pointer to main console               
+
+    Return Values: CScrollerTimer*                         New CScrollerTimer object
+
+    Errors/Exceptions: Leaves if memory allocation or ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CScrollerTimer* CScrollerTimer::NewL( CConsoleMain* aMain )
+    {
+
+    CScrollerTimer* self = new ( ELeave ) CScrollerTimer();
+    CleanupStack::PushL( self );
+    self->ConstructL( aMain );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: ConstructL
+
+    Description: Second level constructor
+
+    Parameters: CConsoleMain*             :in:      Pointer to main console
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CScrollerTimer::ConstructL( CConsoleMain* aMain )
+    {
+
+    // Store module information
+    iMain = aMain;
+	iTimer.CreateLocal();
+
+	CActiveScheduler::Add ( this );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: CScrollerTimer
+
+    Description: Constructor.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CScrollerTimer::CScrollerTimer() : CActive (CActive::EPriorityStandard)
+    {
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: ~CScrollerTimer
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CScrollerTimer::~CScrollerTimer( )
+    {
+
+	Cancel();
+	iTimer.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: StartL
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CScrollerTimer::StartL( )
+    {
+
+	SetActive();
+	iTimer.After ( iStatus, KScrollPeriod );	
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: RunL
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CScrollerTimer::RunL( )
+    {
+
+	iMain->TimerUpdate();
+
+	// Restart request
+	SetActive();
+	iTimer.After ( iStatus, KScrollPeriod );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: DoCancel
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CScrollerTimer::DoCancel( )
+    {
+
+	iTimer.Cancel();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CScrollerTimer
+
+    Method: RunError
+
+    Description: None
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+TInt CScrollerTimer::RunError( TInt aError)
+    {
+    if ( aError == KErrNoMemory )
+    	{
+    	iMain->ExitWithNoMemoryErrorMessage();
+    	}
+  
+	return aError;
+    }    
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This module contains implementation of CConsoleReader class.
+
+-------------------------------------------------------------------------------
+*/
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: NewL
+
+    Description: Construct the console main class
+
+    Parameters: CConsoleMain* aMain: in: Pointer to main console
+                CConsoleBase* aConsole: in: Console pointer
+
+    Return Values: CConsoleReader*                    New object
+
+    Errors/Exceptions: Leaves if memory allocation fails or
+                       ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleReader* CConsoleReader::NewL( CConsoleMain* aMain, 
+                                      //CConsoleBase* aConsole )
+                                      RConsole* aConsole )
+    {
+
+    CConsoleReader* self = 
+        new ( ELeave ) CConsoleReader( aMain, aConsole );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: 
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleReader::ConstructL( )
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: CConsoleReader
+
+    Description: Constructor.
+
+    Parameters: CConsoleMain* aMain: in: Pointer to main console
+                CConsoleBase* aConsole: in: Console pointer
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleReader::CConsoleReader( CConsoleMain* aMain, 
+                                //CConsoleBase* aConsole ): 
+                                RConsole* aConsole ): 
+    CActive( EPriorityStandard )
+    {
+    
+    iMain = aMain;
+    iConsole = aConsole;
+    
+    CActiveScheduler::Add( this );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: ~CConsoleReader
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CConsoleReader::~CConsoleReader( )
+    {	
+    
+    Cancel();    
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: StartL
+
+    Description: Construct menu objects and start the menu handling
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions:
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleReader::StartL( )
+    {
+
+    // Start to process keyboard events
+    SetActive();
+    //iConsole->Read(iStatus);
+    iConsole->Read(iMain->key, iStatus);
+
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: RunError
+
+    Description: None
+
+    Parameters: TInt aError
+
+    Return Values: Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/    
+TInt CConsoleReader::RunError(TInt aError)
+    {
+    return aError;
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: RunL
+
+    Description: Process keyboard events. Print new menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if SelectL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleReader::RunL()
+    {
+
+    iMain->KeyPressed();
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CConsoleReader
+
+    Method: DoCancel
+
+    Description: Cancel request
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CConsoleReader::DoCancel()
+    {
+    
+    iConsole->ReadCancel();
+    
+    }
+
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: MainL
+
+    Description: The main function that can leave.
+    Create the CMainConsole object and create, initialise and 
+    start active scheduler.
+
+    When active scheduler is stopped, clean up memory and exit.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation or CConsoleMain construction
+                       leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+LOCAL_C void MainL()
+    {
+
+    // Construct and install active scheduler
+    CActiveScheduler* scheduler=new ( ELeave ) CActiveScheduler;
+    CleanupStack::PushL( scheduler );
+    CActiveScheduler::Install( scheduler );
+
+    // Construct the console
+    CConsoleMain* mainConsole = CConsoleMain::NewL();
+    CleanupStack::PushL( mainConsole );
+
+    // Start the console
+    mainConsole->StartL();
+
+    // Start handling requests
+    CActiveScheduler::Start();
+    // Execution continues from here after CActiveScheduler::Stop()
+
+    // Clean-up
+    CleanupStack::PopAndDestroy( mainConsole );
+    CleanupStack::PopAndDestroy( scheduler );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: E32Main
+
+    Description: The main function. Execution starts from here.
+    Create clean-up stack and trap the MainL function which does the
+    real work.
+
+    Parameters: None
+
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+GLDEF_C TInt E32Main()
+    {
+
+    __UHEAP_MARK;
+
+    // Get clean-up stack
+    CTrapCleanup* cleanup=CTrapCleanup::New();
+
+    // Call the main function
+    TRAPD( error, MainL() );
+
+    // Clean-up
+    delete cleanup; 
+    cleanup = NULL;
+
+    __UHEAP_MARKEND;
+
+    return error;
+
+    }
+
+#if defined(__WINS__)
+/*
+-------------------------------------------------------------------------------
+
+    Class: -
+
+    Method: WinsMain
+
+    Description: The WinsMain function.
+
+    Parameters: None
+
+    Return Values: TInt                             Error code
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C TInt WinsMain()
+	{
+	E32Main();
+	return KErrNone;
+	}
+
+#endif // __WINS__
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/TouchConsoleUI/src/Consolemenus.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,5696 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This module contains implementation of 
+* CMenu-derived classes.
+*
+*/
+
+// INCLUDE FILES
+#include <e32base.h>
+#include <e32cons.h>
+#include <e32svr.h>
+
+#include <f32file.h>
+#include <stifinternal/UIEngineContainer.h>
+
+#include "ConsoleUI.h"
+#include "ConsoleMenus.h"
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+LOCAL_C void LimitedAppend( TDes& aOriginal, const TDesC& aAppend);
+
+// FORWARD DECLARATIONS
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+LOCAL_C void LimitedAppend( TDes& aOriginal, const TDesC& aAppend)
+    {
+
+    TInt spaceLeft = aOriginal.MaxLength() - aOriginal.Length();
+    
+    if (spaceLeft > aAppend.Length())
+        {
+        aOriginal.Append ( aAppend );
+        }
+    else
+        {       
+        aOriginal.Append ( aAppend.Left ( spaceLeft ) );
+        }
+
+    }
+
+// None
+
+// ================= MEMBER FUNCTIONS =========================================
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMenu::NewL( CConsoleMain* aConsole,
+                    CMenu* aParent,
+                    const TDesC& aName
+                  )
+    {
+
+    CMenu* self = new ( ELeave ) CMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+				const TDesC& aHeader	  :in:		Text containing STIF version info
+				
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::ConstructL( CConsoleMain* aConsole,
+                        CMenu* aParent,
+                        const TDesC& aName,
+                        const TDesC& aHeader
+                      )
+    {
+ 
+    // Store the parameters
+    iMain = aConsole;
+    iConsole = aConsole->GetConsole();
+    iParent = aParent;
+    iName = aName;
+    iHeader = aHeader;
+
+    // Get display size
+    const TInt KOverHead = 5;
+    //iSize = iConsole->ScreenSize();
+    iConsole->ScreenSize(iSize);
+    iScreenSize = iSize.iHeight - KOverHead;   // Size available for menus
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: CMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu::CMenu()
+    {
+    iDirection = 1;
+    iPrevPos  = -1;     // Invalid starting value
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: ~CMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CMenu::~CMenu()
+    {
+    
+    iItems.ResetAndDestroy();
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: TimerUpdate
+
+    Description: TimerUpdate
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenu::TimerUpdate()
+    {    
+
+    RRefArray<TDesC> texts;
+    User::LeaveIfError( ItemTexts( texts ) );
+    
+    TInt count = texts.Count();
+    // If list is empty, do not scroll.
+    if ( count < 1 )
+        {
+        texts.Close();
+        return;
+        }
+    
+    // Recalculate visible part of menu
+    Recalculate( count );
+
+    // If menu selection is updated, then restart scrolling
+    if (iPrevPos != iFirst + iPosOnScreen)
+        {
+        iPrevPos = iFirst + iPosOnScreen;
+        iStart = 0;
+        iDirection = 1;
+        }
+
+
+    // If menu item have not been changed after last timer, then
+    // start scrolling  
+    const TDesC& name = texts[ iFirst + iPosOnScreen ]; 
+    if ( name.Length() > ( iSize.iWidth - KMenuOverhead ) )
+        {
+
+        //TInt y = iConsole->WhereY();
+        //TInt x = iConsole->WhereX();
+        TPoint cp;
+        iConsole->CursorPos(cp);
+        TInt y = cp.iY;
+        TInt x = cp.iX;
+        
+        TBuf<80> iTmp;              
+
+        iStart = iStart + iDirection;
+
+        // "Right end"
+        if ( iStart + iSize.iWidth > name.Length() + KMenuOverhead )
+            {
+            iStart--;
+            iDirection = -1;
+            }
+        
+        // "Left end"
+        if ( iStart == -1 )
+            {
+            iStart++;
+            iDirection = 1;
+            }
+        
+        if( iStart > name.Length() )
+            {
+            iStart = 0;
+            }
+
+        iTmp=_L(" *");
+        LimitedAppend( iTmp, name.Mid ( iStart ) );
+            
+        //iConsole->SetPos( 0, iPosOnScreen+1);
+        TPoint p(0, iPosOnScreen+1);
+        iConsole->SetCursorPosAbs( p);       
+        //iConsole->Printf ( iTmp.Left( iSize.iWidth -2 )  );
+        iConsole->Write ( iTmp.Left( iSize.iWidth -2 )  );
+
+        //iConsole->SetPos(x,y);
+        p.SetXY(x,y);
+        iConsole->SetCursorPosAbs(p);
+        }
+    texts.Close();
+
+    }
+    
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number 
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenu::AppendBefore( TInt aLineNum, TDes& aLine )
+    {
+    
+    if( ( aLine.MaxLength() - aLine.Length() ) < 2 )
+        {
+        return;
+        }        
+    
+    // If printing active line, print the marker
+    if ( aLineNum == iPosOnScreen + iFirst )
+        {
+        aLine.Append( _L(" *") );
+        }
+    else
+        {
+        aLine.Append( _L("  ") );
+        }
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenu::PrintMenuL( TUpdateType aType )
+    {
+
+    iUpdateType = aType;
+    
+    TBuf<KMaxLineLength> line;
+
+    // Clear display
+    iConsole->ClearScreen();
+    
+    //Print STIF version information, only when defined (i.e. in main menu)
+    if(iHeader != _L(""))
+    	Print(iHeader);
+
+    // Print menu title
+    Print( Name() );
+            
+    RRefArray<TDesC> texts;
+    User::LeaveIfError( ItemTexts( texts ) );
+    
+    // Recalculate visible part of menu
+    Recalculate( texts.Count() );
+    
+    // Print items
+    for ( TInt i = iFirst; i <= iLast; i++ )
+        {
+        line.Zero();
+        
+        // Append text before line
+        AppendBefore( i, line );
+
+        // Get the menu line
+        LimitedAppend ( line, texts[i] );
+
+        // Print the line
+        Print(line);
+
+        }
+    texts.Close();
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Either updates position in
+    menu or returns new menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    switch ( (TInt) aSelection )
+    {
+
+    // Exit
+    case EKeyEscape:
+        aContinue = EFalse;
+        return this;
+    // SelectL item
+    case EKeyEnter:
+    case EKeyRightArrow:
+        return iItems[iPosOnScreen];
+
+    // Going back
+    case EKeyLeftArrow:
+        return iParent;
+
+    // Go down
+    case EKeyDownArrow:
+        {
+        if ( iFirst + iPosOnScreen == iItemCount - 1 )
+            {
+            // If end of the list, go to beginning
+            iPosOnScreen = 0;
+            iFirst = 0;
+            iLast = iScreenSize;
+            if ( iLast > iItemCount - 1 )
+            	{
+            	iLast = iItemCount - 1;
+            	}
+            }
+        else 
+            {
+            if ( iPosOnScreen == iScreenSize )
+                {
+                iLast++;
+                iFirst++;
+                }
+            else
+                {
+                // Going down "in-screen", no need to update items
+                iPosOnScreen++;
+                }
+            }
+        break;
+        }
+        
+    // Go Up
+    case EKeyUpArrow:
+        {
+        if ( iFirst + iPosOnScreen == 0 )
+            {
+            // If in the beginning of the list
+
+            if(iItemCount > 0)
+                {
+                iLast = iItemCount - 1;
+                iFirst = iLast - iScreenSize;
+                if ( iFirst < 0 )
+                	{
+                	iFirst = 0;            	
+                	}
+                iPosOnScreen = iLast - iFirst;
+                }
+            }
+        else if ( iPosOnScreen == 0 )
+            {
+            iLast--;
+            iFirst--;
+            }
+        else
+            {
+            iPosOnScreen--;
+            }
+        
+        break;
+        }
+
+    // Additional keys
+    case EKeyHome:
+    case '3':
+        iPosOnScreen = 0;
+        iFirst = 0;
+        iLast = iScreenSize;
+
+        if ( iLast > iItemCount - 1 )
+            {
+            iLast = iItemCount - 1;
+            }
+        break;
+
+    case EKeyEnd:
+    case '9':
+        iLast = iItemCount - 1;
+        iFirst = iLast - iScreenSize;
+
+        if ( iFirst < 0 )
+            {
+            iFirst = 0;
+            }
+        iPosOnScreen = iLast - iFirst;        
+        break;
+
+    case EKeyPageUp:
+    case '1':
+
+        iFirst = iFirst - iScreenSize;
+        iLast = iLast - iScreenSize;
+
+        if ( iFirst < 0 )
+            {
+            iFirst = 0;
+            iPosOnScreen = 0;           
+            iLast = iScreenSize;
+            if ( iLast > iItemCount - 1 )
+                {
+                iLast = iItemCount - 1;
+                }
+            }
+        break;
+
+    case EKeyPageDown:
+    case '7':
+        iFirst = iFirst + iScreenSize;
+        iLast = iLast + iScreenSize;
+
+        // Going too far
+        if ( iLast > iItemCount - 1 )
+            {
+            iLast = iItemCount - 1;
+            iFirst = iLast - iScreenSize;
+            if ( iFirst < 0 )
+                {
+                iFirst = 0;
+                }
+            }
+        iPosOnScreen = iLast - iFirst;
+        break;
+    default:  // Bypass the keypress
+        break;
+    }
+
+    // Continue normally and keep in the same menu
+    aContinue = ETrue;
+    return this;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    TInt count = iItems.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aArray.Append( iItems[i]->Name() ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    return KErrNone;
+
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: SetParent
+
+    Description: Sets menu parent menu.
+
+    Parameters: CMenu* aMenu              :in:      Menu parent
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::SetParent ( CMenu* aMenu )
+    {
+
+    iParent = aMenu;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: Print
+
+    Description: Prints one line text and changes to next line. If line is
+    too long, overhead is not printed..
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMenu::Print( const TDesC& aPrint )
+    {
+    
+    //iConsole->Printf ( aPrint.Left( iSize.iWidth - KMenuOverhead ) );
+    iConsole->Write ( aPrint.Left( iSize.iWidth - KMenuOverhead ) );
+    //iConsole->Printf(_L("\n"));
+    iConsole->Write(_L("\r\n"));
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: PrintMulti
+
+    Description: Prints text. If line is too long, it will be continued to
+    following lines.
+
+    Parameters: const TDesC& aPrint       :in:      Text to print
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::PrintMulti( const TDesC& aPrint )
+    {
+
+    // Get current line
+    const TInt KMenuOverHead = 2;
+    //TInt y = iConsole->WhereY();
+    TPoint cp;
+    iConsole->CursorPos(cp);
+    TInt y = cp.iY;
+
+
+    const TInt KLineLen =iSize.iWidth -4;
+    TBuf<KMaxLineLength+1> oneLine;
+
+    // Loop through the line
+    for (TInt i = 0; i < aPrint.Length(); i++)
+        {
+        oneLine.Append( aPrint[i] );
+
+        // Print one line
+        if (oneLine.Length() == KLineLen )
+            {
+            oneLine.Append (_L("\r\n"));
+            //iConsole->Printf(oneLine);
+            iConsole->Write(oneLine);
+            oneLine=_L("");
+            y++;
+            }
+    
+        // Prevent display scrolling
+        if ( y == iScreenSize + KMenuOverHead )
+            {
+            oneLine=_L("");
+            break;
+            }
+        }
+
+    // Print last part if required
+    if ( oneLine.Length() != 0 )
+        {
+        oneLine.Append (_L("\r\n"));
+        //iConsole->Printf(oneLine);
+        iConsole->Write(oneLine);
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: AddItem
+
+    Description: Add new item to menu
+
+    Parameters: CMenu* aMenu              :in:      Menu to be added
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if can't add item to menu
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::AddItemL( CMenu* aMenu )
+    {
+
+    User::LeaveIfError ( iItems.Append (aMenu) );
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: Name
+
+    Description: Returns menu name
+
+    Parameters: None
+
+    Return Values: const TDesC&                     Menu name
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+const TDesC& CMenu::Name( ) const
+    {
+
+    return iName;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: MapKeyCode
+
+    Description: Maps numeric keycodes to proper TKeyCode values
+
+    Parameters: TKeyCode 
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+
+void CMenu::MapKeyCode(TKeyCode &aSelection)
+    {
+    
+    TInt asciiCode = (TInt) aSelection;
+    
+    // Handling numeric keys 2,4,6 and 8
+    
+    if(asciiCode == KMyKeyUpAsciiCode)
+        {
+        aSelection = EKeyUpArrow;
+        }
+        
+    if(asciiCode == KMyKeyLeftAsciiCode)
+        {
+        aSelection = EKeyLeftArrow;
+        }
+
+    if(asciiCode == KMyKeyRightAsciiCode)
+        {
+        aSelection = EKeyEnter;
+        }
+
+    if(asciiCode == KMyKeyDownAsciiCode)
+        {
+        aSelection = EKeyDownArrow;
+        }
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: Recalculate
+
+    Description: Recalculates visible menu elements
+
+    Parameters: TInt aItemCount    :in:      Menu items count
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CMenu::Recalculate( TInt aItemCount )
+	{    
+    TInt oldItemCount = iItemCount;
+     
+    iItemCount = aItemCount;
+ 
+    // If first time in menu, update start and end positions
+    if ( ( iFirst == 0 ) && ( iLast == 0 ) || (iItemCount == 0)) //if there are no items, update start and end positions too
+    	{
+    	if ( iItemCount - 1 > iScreenSize  )
+    		{
+    		iLast = iScreenSize;
+    		}
+    	else
+    		{
+    		iLast = iItemCount - 1;
+    		}
+    	iPosOnScreen = 0;
+    	}
+    // New menu entry added, update last visible element if needed
+    else if ( oldItemCount < iItemCount )
+    	{
+    	if ( iFirst + iScreenSize < iItemCount )
+    		{
+    		iLast = iFirst + iScreenSize;
+    		}
+    	else
+    		{
+    		iLast = iItemCount - 1;
+    		}
+    	}
+    // Menu entry removed, update last visible element if needed
+    else if ( oldItemCount > iItemCount )
+    	{
+    	if ( iFirst + iScreenSize < iItemCount )
+    		{
+    		iLast = iFirst + iScreenSize;
+    		}
+    	else if ( iFirst > iItemCount - 1 )
+    		{
+    		iFirst = iItemCount - 1 - iScreenSize;
+    		if ( iFirst < 0 )
+    			{
+    			iFirst = 0;
+    			}
+    		iLast = iItemCount - 1;
+    		iPosOnScreen = iFirst - iLast;
+    		}
+    	else
+    		{
+    		iLast = iItemCount - 1;
+    		}
+    	
+    	if ( iFirst + iPosOnScreen > iLast )
+    		{
+    		iPosOnScreen = iLast - iFirst;
+    		}
+    	}	
+	}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CFileNameQueryView* CFileNameQueryView::NewL( CConsoleMain* aConsole,
+                                              CMenu* aParent,
+                                              const TDesC& aName )
+    {
+
+    CFileNameQueryView* self = new ( ELeave ) CFileNameQueryView();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CFileNameQueryView::ConstructL( CConsoleMain* aConsole, 
+                                     CMenu* aParent, 
+                                     const TDesC& aName 
+                                    )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: ~CFileNameQueryView
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CFileNameQueryView::~CFileNameQueryView()
+    {
+
+    iTestModuleNames.ResetAndDestroy();
+    iTestModuleNames.Close();
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: ItemText
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CFileNameQueryView::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    iTestModuleNames.ResetAndDestroy();    
+    
+    // Add loaded module names to menu
+    TInt ret = iMain->UIStore().ListAllModules( iTestModuleNames );
+
+    if( ret != KErrNone )
+        {                 
+        return ret;
+        }
+        
+    TInt count = iTestModuleNames.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aArray.Append( *iTestModuleNames[i] ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    return KErrNone; 
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFileNameQueryView
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Just return the parent menu
+
+    Parameters: TKeyCode aSelection       :in:      Not used
+                TBool& aContinue          :out:     Has user pressed "Quit"?
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CFileNameQueryView::SelectL( TKeyCode aSelection, 
+                                    TBool& aContinue )
+    {  
+    
+    MapKeyCode(aSelection);
+
+    if (aSelection == EKeyEnter || aSelection == EKeyRightArrow )
+        {
+        if( iPosOnScreen < iTestModuleNames.Count() )
+            {
+            TInt ret = 
+                iMain->UIStore().AddTestModule( *iTestModuleNames[iPosOnScreen] );
+            if( ret != KErrNone )
+                {
+                TErrorNotification error;
+                error.iModule.Copy( _L("ConsoleUI") );
+                error.iText.Copy( _L("Failed to load test module ") );
+                error.iText.Append( *iTestModuleNames[iPosOnScreen] );
+                error.iText.Append( _L(" error "));
+                error.iText.AppendNum( ret );
+                iMain->Error( error );
+                }
+            return iParent;
+            }
+        else
+            {
+            return this;
+            }
+        }  
+
+    return CMenu::SelectL( aSelection, aContinue );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                const TDesC& aHeader	  :in:		Text containing STIF version information
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMainMenu* CMainMenu::NewL( CConsoleMain* aConsole,
+                            CMenu* aParent,
+                            const TDesC& aName,
+                            const TDesC& aHeader)
+    {
+
+    CMainMenu* self = new ( ELeave ) CMainMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aHeader );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMainMenu
+
+    Method: ~CMainMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMainMenu::~CMainMenu()
+    {
+    delete iOutputView;
+    iOutputView = NULL;
+    delete iOperationMenu;
+    iOperationMenu = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text. Add "Exit" to normal SelectLion
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMainMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    TInt ret = CMenu::ItemTexts( aArray );
+    if ( ret != KErrNone )
+    	{
+    	return ret;
+    	}
+    // Add Exit to last one in menu
+    if( aArray.Append( KExitTxt ) != KErrNone )
+        {
+        return KErrNoMemory;
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                const TDesC& aHeader	  :in:		Text containing STIF version information
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMainMenu::ConstructL( CConsoleMain* aConsole, 
+                            CMenu* aParent,
+                            const TDesC& aName,
+                            const TDesC& aHeader
+                          )
+    {
+    CMenu::ConstructL( aConsole, aParent, aName, aHeader);
+    iOutputView = NULL;
+    iOperationMenu = NULL;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle SelectLion in this
+    method, other keys are handles in CMenu class.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMainMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    // If SelectLion == "exit" and right or enter
+    if (aSelection == EKeyEnter || aSelection == EKeyRightArrow )
+        {
+        if ( iPosOnScreen == iItemCount-1 )
+            {
+            // Exit
+            aContinue = EFalse;
+            return this;
+            }
+        }
+
+    // Normal menu handling
+    CMenu* tmp = CMenu::SelectL(aSelection, aContinue);
+    return tmp;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMainMenu
+
+    Method: CreateOutputViewL
+
+    Description: Creates test case output view.
+
+    Parameters: CMenu* aParent: parent menu for case operation menu
+
+    Return Values: CMenu*        New menu
+
+    Errors/Exceptions: Leaves is CCaseExecutionView menu leaves during creation
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMainMenu::CreateOutputViewL(CMenu* aParent)
+    {
+    // Get test cases that have been run
+    RRefArray<CStartedTestCase> startedTestCases;
+    CleanupClosePushL(startedTestCases);
+    CMenu* res = NULL;
+
+    startedTestCases.Reset();
+    if(iMain->UIStore().StartedTestCases(startedTestCases, CUIStoreIf::EStatusAll) == KErrNone)
+        {                 
+        TInt count = startedTestCases.Count();
+        if(count > 0)
+            {
+            // Create menu with execution info
+            const CStartedTestCase* caseContainer = &startedTestCases[count - 1];
+            delete iOutputView;
+            iOutputView = NULL;
+            delete iOperationMenu;
+            iOperationMenu = NULL;
+
+            iOperationMenu = CCaseOperationMenu::NewL(iMain,
+                                                      aParent, //back to parent menu
+                                                      caseContainer->TestInfo().TestCaseTitle(),
+                                                      caseContainer
+                                                     );
+
+            iOutputView = CCaseExecutionView::NewL(iMain,
+                                                   iOperationMenu, //back to Case Operation Menu
+                                                   caseContainer->TestInfo().TestCaseTitle(),
+                                                   caseContainer
+                                                  );
+            res = iOutputView;
+            }
+        }
+        
+    CleanupStack::PopAndDestroy(&startedTestCases);
+    return res;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CModuleListView* CModuleListView::NewL( CConsoleMain* aConsole,
+                                        CMenu* aParent,
+                                        const TDesC& aName )
+    {    
+
+    CModuleListView* self = new ( ELeave ) CModuleListView();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: ~CModuleListView
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CModuleListView::~CModuleListView()
+    {
+    delete iModuleAdd;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: ConstructL
+
+    Description: Second level constructor. 
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if module can't be appended to list
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CModuleListView::ConstructL( CConsoleMain* aConsole,
+                                  CMenu* aParent,
+                                  const TDesC& aName
+                                 )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+   
+    // Construct module menu
+    iModuleAdd  = CFileNameQueryView::NewL ( iMain, this, KSelectMenuTxt );    
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: ItemText
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CModuleListView::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    // Add also "Add module" text
+    if( aArray.Append( KAddMenuTxt ) != KErrNone )
+        {
+        return KErrNoMemory;
+        }
+    if( aArray.Append( KLoadMenuTxt ) != KErrNone )
+        {
+        return KErrNoMemory;
+        } 
+        
+    return KErrNone; 
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CModuleListView
+
+    Method: PrintMenuL
+
+    Description: Prints the menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CModuleListView::PrintMenuL( TUpdateType aType )
+    {
+    
+    // Get module names
+    RRefArray<TDesC> modules;
+    TInt ret = iMain->UIStore().Modules( modules );
+
+    CMenu::PrintMenuL( aType );
+    
+    // Add loaded module names to menu
+    if( ret != KErrNone )
+        {
+        modules.Reset();
+        modules.Close();
+        return;
+        }
+        
+    TBuf<KMaxLineLength> line;
+    TInt count = modules.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        line = _L("    ");
+        LimitedAppend ( line, modules[i] );
+
+        // Print the line
+        Print(line);
+        }
+    modules.Reset();
+    modules.Close();
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CModuleListView
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle right arrow and enter
+                 here, others in parent menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CModuleListView::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+    
+    MapKeyCode(aSelection);
+
+    if( ( aSelection == EKeyRightArrow ||
+            aSelection == EKeyEnter ) )
+        {
+        if( iPosOnScreen == EAddMenuTxtItem )
+            {
+            return iModuleAdd;
+            }
+        else if( iPosOnScreen == ELoadMenuTxtItem )
+            {
+            iMain->UIStore().LoadAllModules();
+            return this;
+            }
+        else 
+            {
+            return this;
+            }
+        }
+
+    return CMenu::SelectL( aSelection, aContinue );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseStartMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TBool aShowOutput         :in:      Show output after test case is run
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseStartMenu* CCaseStartMenu::NewL( CConsoleMain* aConsole,
+                                      CMenu* aParent,
+                                      const TDesC& aName,
+                                      TBool aShowOutput)
+    {
+
+    CCaseStartMenu* self = new ( ELeave ) CCaseStartMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aShowOutput );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseStartMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseStartMenu::ConstructL( CConsoleMain* aConsole,
+                                 CMenu* aParent,
+                                 const TDesC& aName,
+                                 TBool aShowOutput
+                               )
+    {
+
+    iShowOutput = aShowOutput;
+    CMenu::ConstructL( aConsole, aParent, aName);
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CCaseStartMenu
+
+    Method: ~CCaseStartMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseStartMenu::~CCaseStartMenu()
+    {
+    iTestCases.Close();
+
+    iMapFilteredToAll.Reset();
+    iMapFilteredToAll.Close();
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseStartMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CCaseStartMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+    iTestCases.Reset();
+    TInt ret = iMain->UIStore().TestCases( iTestCases );
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    const RPointerArray<TDesC> &filters = iMain->GetFilterArray();
+    const TInt filterindex = iMain->GetFilterIndex(); 
+    iMapFilteredToAll.Reset();
+    
+    TInt count = iTestCases.Count();
+    for( TInt i = 0; i < count; i++ )
+        {
+        //If user has chosen filter, let's apply it
+        if(filterindex > 0) //skip the first filter which always is "No filter"
+            {
+            //Check whether test title is matching the applied filter
+            iTitleLowerCase.Copy(iTestCases[i].TestCaseTitle());
+            iTitleLowerCase.LowerCase();
+            iFilterLowerCase.Copy(*filters[filterindex]);
+            iFilterLowerCase.LowerCase();
+
+            if(iTitleLowerCase.Match(iFilterLowerCase) != KErrNotFound)
+                {
+                ret = aArray.Append(iTestCases[i].TestCaseTitle());
+                if(ret != KErrNone)
+                    {
+                    return ret;
+                    }
+                ret = iMapFilteredToAll.Append(i);
+                if(ret != KErrNone)
+                    {
+                    return ret;
+                    }                
+                }
+            }
+        else
+            {
+            ret = aArray.Append( iTestCases[i].TestCaseTitle() );
+            if(ret != KErrNone)
+                {
+                return ret;
+                }
+            ret = iMapFilteredToAll.Append(i);
+            if(ret != KErrNone)
+                {
+                return ret;
+                }                
+            }
+        }
+        
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseStartMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CCaseStartMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    switch ( aSelection )
+        {
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            // Start the case
+            if ( (iFirst + iPosOnScreen) < iMapFilteredToAll.Count() ) //changed from iTestCases to iMapFilteredToAll, because first table keeps info about all test cases, and second one about filtered cases
+                {
+                TInt index;
+                User::LeaveIfError( 
+                    iMain->UIStore().StartTestCase( 
+                        iTestCases[iMapFilteredToAll[iFirst + iPosOnScreen]], index ) );
+                // Create output screen (menu) if needed
+                if(iShowOutput)
+                    {
+                    CMenu* m = iMain->GetMainMenu()->CreateOutputViewL(iParent);
+                    if(m)
+                        return m;
+                    }
+                return iParent;
+                }
+            else
+                {
+                return this;
+                }
+            }
+
+        default:
+            return CMenu::SelectL( aSelection, aContinue);
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleBaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleBaseMenu* CMultipleBaseMenu::NewL( CConsoleMain* aConsole,
+                                            CMenu* aParent,
+                                            const TDesC& aName )
+    {
+
+    CMultipleBaseMenu* self = new ( ELeave ) CMultipleBaseMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleBaseMenu
+
+    Method: CMultipleBaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleBaseMenu::CMultipleBaseMenu(): 
+    iSetFinished( ETrue ),
+    iRunType( ERunSequential ),
+    iMenuTotCount( 0 ),
+    iMenuCount( 0 )
+    {
+    
+    iMenuCount = EChangeAll + 1;
+    iMenuTotCount = iMenuCount;
+    
+    }   
+    
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleBaseMenu
+
+    Method: ~CMultipleBaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleBaseMenu::~CMultipleBaseMenu()
+    {
+    
+    iSetState.Close();
+    
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMultipleBaseMenu::ConstructL( CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName 
+                             )
+    {
+
+    CCaseStartMenu::ConstructL( aConsole, aParent, aName );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMultipleBaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+    if ( iSetFinished )
+        {
+        if( aArray.Append( KChangeAll ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        
+        if( iUpdateType ==  EMenuPrint )
+            {   
+            TInt ret = UpdateTestCases();
+            if( ret != KErrNone )
+                {                 
+                return ret;
+                }
+            }
+        TInt count = iTestCases.Count();
+        for( TInt j=0; j<count; j++ )
+            {
+            if( aArray.Append( iTestCases[j].TestCaseTitle() ) 
+                != KErrNone )
+                {
+                return KErrNoMemory;
+                }
+            if( aArray.Count() > iSetState.Count())
+                {
+                // Appends iSetState only if aArray's size is bigger @js
+                if( iSetState.Append(EFalse) != KErrNone )
+                    {
+                    return KErrNoMemory;
+                    }
+                }
+            }
+        }
+    else
+        {
+        if( aArray.Append( KCancelSet ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMultipleBaseMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number 
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CMultipleBaseMenu::AppendBefore( TInt aLineNum, TDes& aLine )
+    {
+    
+    CMenu::AppendBefore( aLineNum, aLine );
+    if( ( aLine.MaxLength() - aLine.Length() ) < 2 )
+        {
+        return;
+        }        
+    
+    if( aLineNum >= iMenuTotCount )
+        {
+        if ( iSetState[ aLineNum - iMenuTotCount ] )
+            {
+            aLine.Append(_L("S "));
+            }
+        else
+            {
+            aLine.Append(_L("  "));
+            }
+        }
+   
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMultipleBaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    if ( iSetFinished )
+        {
+
+        if ( ( aSelection == EKeyEnter  ) || ( aSelection == EKeyRightArrow ) )
+            {
+            // CMultipleBaseMenu relative position 
+            TInt pos = iFirst + iPosOnScreen - iMenuTotCount + iMenuCount;
+            if( pos  == EChangeAll )
+                {
+                TInt count = iTestCases.Count();    
+
+                // Change all                                       
+                for (TInt i = 0; i < count; i++)
+                    {
+                    iSetState[i] = !iSetState[i];
+                    }
+
+                return this;
+                }
+            else
+                {
+                // Normal item, change state...
+                iSetState[ iFirst + iPosOnScreen - iMenuTotCount ] = 
+                    !iSetState[ iFirst + iPosOnScreen - iMenuTotCount ];
+                return this;
+                }            
+            
+            }
+
+		return CMenu::SelectL( aSelection, aContinue );
+        }
+    else
+        {
+
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {
+                if ( iOngoingCaseContainer != NULL )
+                    {
+                    iOngoingCaseContainer->UIEngineContainer().CancelTest();
+                    }
+                iSetFinished = ETrue;
+                iFirst = 0;
+                iLast = 0;
+                return this;
+                }
+            default:
+                return CMenu::SelectL( aSelection, aContinue );
+            }
+
+
+
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: CheckIfAnyCaseIsSelected
+
+    Description: Checks if any of testcases was selected in multiple selection menu
+
+    Parameters: TInt aCount number of testcases in multiple selection menu
+
+    Return Values: ETrue if any testcase was selected, EFalse if none of testcases was selected
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+TBool CMultipleBaseMenu::CheckIfAnyCaseIsSelected(TInt aCount)
+{
+	TInt currentPos = 0;
+	for(; currentPos<aCount; currentPos++)	
+	{
+		//if any of testcases was selected then return true
+		if (iSetState[currentPos])
+			return ETrue;
+	}
+	//if none of testcases was selected then return false
+	return EFalse;
+}
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: SignalL
+
+    Description: Handle test case starts
+
+    Parameters: CStartedTestCase* aContainer: in: CStartedTestCase container
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+void CMultipleBaseMenu::SignalL( CStartedTestCase* /*aContainer*/ )
+    {
+
+    TInt count = iTestCases.Count();
+    
+    TBool started = EFalse;
+    TInt index;
+    TInt err = KErrNone;
+
+    // Counter to prevent infinite loop when cases can't be started at all
+    // when running cases in repeat mode.
+    TInt casesChecked = 0;
+
+    // If cases are not aborted or not in last case and at least one test
+    // case was selected, start a new one
+    if ( !iSetFinished && iCurrentRunPos != count && CheckIfAnyCaseIsSelected(count) )
+        {
+        // Search next case from set and execute it.
+        while( iCurrentRunPos < count )
+            {
+            if ( iSetState[iCurrentRunPos] )
+                {       
+                err = iMain->UIStore().StartTestCase( 
+                    iTestCases[ iCurrentRunPos ], 
+                    index );
+
+                iCurrentRunPos++;
+                casesChecked++;
+
+                // Go to start of list, if running cases in repeat mode. 
+                // In other modes, just get out from the main loop
+                if( ( iRunType == ERunRepeatSequential ) &&
+                    ( iCurrentRunPos >= count ) )
+                    {
+                    // Restart from first one on next time.
+                    iCurrentRunPos = 0;
+                    }
+
+                // Handle out of memory error separately, because there is
+                // always new test case result display constructed when
+                // starting case => Starting more new cases uses more memory
+                // and it will not work, so stop starting new cases.
+                if( err == KErrNoMemory )
+                    {
+                    iSetFinished = ETrue;
+                    break;
+                    }
+
+                // Get pointer to ongoing case in case that user wants to
+                // cancel it.
+                iOngoingCaseContainer = 
+                    &iMain->UIStore().StartedTestCaseL( index );
+
+                // Store pointer to this object to allow 
+                // SignalL call when test case is completed
+                iOngoingCaseContainer->iBackPtr = (TAny*)this;
+
+                if( err != KErrNone )
+                    {
+                    TFullTestResult result;  
+                    result.iTestResult.iResult = err;
+                    result.iTestResult.iResultDes.Copy( 
+                                            _L("Failed to start testcase") );
+                    // Prevent infinite loop in case, where
+                    // ERunRepeatSequential and ALL cases fail to start.
+                    if ( iRunType == ERunRepeatSequential && 
+                                            casesChecked == count )
+                        {
+                        // In this state, started = EFalse so final check
+                        // stops running
+                        break;
+                        }
+                    }
+                else if( ( iRunType == ERunSequential ) ||
+                         ( iRunType == ERunRepeatSequential ) )
+                    {
+                    started = ETrue;
+                    break;
+                    }
+                }
+            else 
+                {
+                iCurrentRunPos++;
+                casesChecked++;
+
+                // Go to start of list, if running cases in repeat mode. 
+                // In other modes, just get out from the main loop
+                if( ( iRunType == ERunRepeatSequential ) &&
+                    ( iCurrentRunPos >= count ) )
+                    {
+                    // Restart from first one
+                    iCurrentRunPos = 0;
+                    }
+                }
+            }
+        }
+
+    if ( err == KErrNoMemory )
+    	{
+    	iMain->ExitWithNoMemoryErrorMessage();
+    	}
+    
+    // If nothing was selected, then mark set as finished. 
+    // Or running cases at same time, so all have been started.
+    if ( started == EFalse )
+        {
+        iFirst = 0;
+        iLast = 0;
+        iSetFinished = ETrue;
+        iCurrentRunPos = 0;
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleBaseMenu
+
+    Method: UpdateTestCases
+
+    Description: 
+
+    Parameters: 
+
+    Return Values: 
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMultipleBaseMenu::UpdateTestCases()
+    {
+
+    // Update test cases
+    iTestCases.Reset();
+    iSetState.Reset();
+    return iMain->UIStore().TestCases( iTestCases );
+            
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleCaseMenu* CMultipleCaseMenu::NewL( CConsoleMain* aConsole,
+                                            CMenu* aParent,
+                                            const TDesC& aName )
+    {
+
+    CMultipleCaseMenu* self = new ( ELeave ) CMultipleCaseMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleCaseMenu
+
+    Method: CMultipleCaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleCaseMenu::CMultipleCaseMenu()    
+    {
+    
+    iMenuItemsCount = ERepeatRunSelection + 1;
+    iMenuItemsCount++; //Select all between already selected
+    iMenuTotCount += iMenuItemsCount;
+    
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    CMultipleCaseMenu
+
+    Method: ~CMultipleCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMultipleCaseMenu::~CMultipleCaseMenu()
+    {
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMultipleCaseMenu::ConstructL( CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName 
+                             )
+    {
+
+    CCaseStartMenu::ConstructL( aConsole, aParent, aName );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleCaseMenu
+
+    Method: StartRunningL
+
+    Description: Start running multiple cases.
+
+    Parameters: TRunType aRunType: in: Running type
+                const TDesC& aModule: in: module name 
+                const TDesC& aTestCaseFile: in: test case file name 
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves on error
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CMultipleCaseMenu::StartRunningL( TRunType aRunType, 
+                                       const TDesC& aModule, 
+                                       const TDesC& aTestCaseFile )
+    {
+    
+    // Update test cases
+    iTestCases.Reset();
+    iSetState.Reset();
+    User::LeaveIfError( 
+        iMain->UIStore().TestCases( iTestCases, aModule, aTestCaseFile ) );
+    
+    // Select all for running
+    TInt count = iTestCases.Count();
+    for( TInt j=0; j<count; j++ )
+        {
+        User::LeaveIfError( iSetState.Append(ETrue) );
+        }
+        
+    // Start running
+    iCurrentRunPos = 0;
+    iSetFinished = EFalse;
+    iRunType = aRunType;
+    SignalL ( NULL );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CMultipleCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+    if ( iSetFinished )
+        {
+        if( aArray.Append( KRunSequentially ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if( aArray.Append( KRunParallel ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if( aArray.Append( KRepeatRunSequentially ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if(aArray.Append(KSelectFromTo) != KErrNone)
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    TInt ret = CMultipleBaseMenu::ItemTexts(aArray);
+    if(ret != KErrNone)
+        {
+        return ret;
+        }
+    
+    return KErrNone;    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMultipleCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CMultipleCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    if ( iSetFinished )
+        {
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {
+
+                if ( iFirst + iPosOnScreen == ERunSelection )
+                    {
+                    // Start the first one
+                    iCurrentRunPos = 0;
+                    iSetFinished = EFalse;
+                    iRunType = ERunSequential;
+                    SignalL ( NULL );
+
+                    return iParent;
+                    }
+                else if ( iFirst + iPosOnScreen == ERunSelectionParaller )
+                    {
+                    // Start the first one
+                    iCurrentRunPos = 0;
+                    iSetFinished = EFalse;
+                    iRunType = ERunParallel;
+                    SignalL ( NULL );
+
+                    return iParent;
+                    }
+                else if ( iFirst + iPosOnScreen == ERepeatRunSelection )
+                    {
+                    // Start the first one
+                    iCurrentRunPos = 0;
+                    iSetFinished = EFalse;
+                    iRunType = ERunRepeatSequential;
+                    SignalL ( NULL );
+
+                    return iParent;
+                    }
+                else if(iFirst + iPosOnScreen == ESelectFromTo)
+                    {
+                    TInt count = iTestCases.Count();
+                    TInt indexFirst = count;
+                    TInt indexLast = count - 1;
+                    TInt i;
+                    
+                    // Find first test case which is set
+                    for(i = 0; i < count; i++)
+                        {
+                        if(iSetState[i])
+                            {
+                            indexFirst = i;
+                            break;
+                            }
+                        }
+                    
+                    // Find last test case which is set
+                    if(indexFirst < count)
+                        {
+                        for(i = count - 1; i > indexFirst; i--)
+                            {
+                            if(iSetState[i])
+                                {
+                                indexLast = i;
+                                break;
+                                }
+                            }
+                        
+                        // Set test cases between first and last
+                        for(i = indexFirst; i <= indexLast; i++)
+                            {
+                            iSetState[i] = ETrue;
+                            }
+                        }
+
+                    return this;
+                    }
+                }
+                break;
+            default:
+                break;
+            }
+        }   
+        
+    return CMultipleBaseMenu::SelectL( aSelection, aContinue );
+        
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseMenu* CCaseMenu::NewL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName, 
+                            TInt aType )
+    {
+
+    CCaseMenu* self = new ( ELeave ) CCaseMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aType );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if memory allocation fails
+                       Leaves if CCaseOperation menu NewL leaves
+                       Leaves if UpcateCaseListL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseMenu::ConstructL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName, 
+                            TInt aType
+                          )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+    iType = aType;
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: ~CCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CCaseMenu::~CCaseMenu()
+    {
+
+    delete iCaseOperationMenu;
+    iCaseOperationMenu = 0;
+    
+    iTestCases.Close();
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    iTestCases.Reset();
+    
+    TInt ret = iMain->UIStore().StartedTestCases( iTestCases, iType );
+    if ( ret != KErrNone )
+    	{
+    	return ret;
+    	}
+
+    TInt count = iTestCases.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aArray.Append( iTestCases[i].TestInfo().TestCaseTitle() ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CCaseMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseMenu::AppendBefore(TInt aLineNum, TDes& aLine)
+    {
+    CMenu::AppendBefore(aLineNum, aLine);
+
+    //START of --Add number to the test case title--
+    //First check how much space we need
+    TInt additionalSpace = 0;
+    TInt currentCount = aLineNum + 1;
+
+    if(currentCount >= 10000) additionalSpace = 10; //f.e. "10157521. "
+    else if(currentCount >= 1000) additionalSpace = 6; //f.e. "1157. "
+    else if(currentCount >= 100) additionalSpace = 5; //f.e. "101. "
+    else if(currentCount >= 10) additionalSpace = 4; //f.e. "15. "
+    else additionalSpace = 3; //f.e. "1. "
+
+ //Create descriptor, add content to it, and finally append to line
+    TBuf<20> num;
+
+    if(iTestCases[aLineNum].Status() == CUIStoreIf::EStatusRunning )
+ 	   {
+    if( iTestCases[aLineNum].UIEngineContainer().State() == CUIEngineContainer::EPaused)
+     	{
+     	  //If not enough space, return
+     	if((aLine.MaxLength() - aLine.Length()) < additionalSpace + 4)
+     	     {
+     	     return;
+     	     }
+     		num.Format(_L("%d.(P) "), currentCount);
+     	}
+     else
+     	{
+        //If not enough space, return
+     	if((aLine.MaxLength() - aLine.Length()) < additionalSpace)
+     		{
+     	  	return;
+     	     }     		  			
+     	num.Format(_L("%d."), currentCount);
+     	}
+ 	   }
+    aLine.Append(num);
+    }
+    //END of --Add number to test case title--
+    
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle Enter and Right Arrow
+    here, other will be handled in CMenu::SelectL
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    switch (aSelection)
+        {
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            if ( iFirst + iPosOnScreen < iTestCases.Count() )
+                {
+                delete iCaseOperationMenu;
+                iCaseOperationMenu = 0;
+                iCaseOperationMenu = CCaseOperationMenu::NewL( 
+                    iMain, 
+                    this, 
+                    iTestCases[iFirst + iPosOnScreen].TestInfo().TestCaseTitle(), 
+                    &iTestCases[iFirst + iPosOnScreen] );   
+
+                return iCaseOperationMenu;
+                }
+            }
+            return this;
+        default:
+            // Let the parent class handle rest
+            return CMenu::SelectL(aSelection, aContinue);
+        }
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseOperationMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                CStartedTestCase* aCaseContainer:in: Case container
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseOperationMenu* CCaseOperationMenu::NewL( CConsoleMain* aConsole,
+                                 CMenu* aParent,
+                                 const TDesC& aName,
+                                 const CStartedTestCase* aCaseContainer
+                               )
+    {
+
+    CCaseOperationMenu* self = new ( ELeave ) CCaseOperationMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aCaseContainer );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseOperationMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                CStartedTestCase* aCaseContainer:in: Case container
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseOperationMenu::ConstructL( CConsoleMain* aConsole,
+                                     CMenu* aParent,
+                                     const TDesC& aName,
+                                     const CStartedTestCase* aCaseContainer
+                                   )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName); 
+    iCaseContainer = aCaseContainer;
+    
+    // Indicate that this menu contains prints, update when needed
+    iType = CUIStoreIf::EStatusExecuted;
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CMenu
+
+    Method: ~CMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CCaseOperationMenu::~CCaseOperationMenu()
+    {
+    delete iView;
+    iView = 0;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseOperationMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CCaseOperationMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    if( iCaseContainer->Status() & CUIStoreIf::EStatusRunning )
+        {
+        if( aArray.Append( KOutputViewDes ) != KErrNone )
+            {
+            return KErrNoMemory; 
+            }
+                
+        // Set resume/pause text
+        if( iCaseContainer->UIEngineContainer().State() == 
+            CUIEngineContainer::EPaused )
+            {
+            if( aArray.Append( KResumeCaseDes ) != KErrNone )
+                {
+                return KErrNoMemory; 
+                }
+            }
+        else
+            {
+            if( aArray.Append( KPauseCaseDes ) != KErrNone )
+                {
+                return KErrNoMemory; 
+                }
+            }
+        if( aArray.Append( KAbortCaseDes ) != KErrNone )
+            {
+            return KErrNoMemory; 
+            }
+        }
+    else
+        {
+        if(aArray.Append(KRestartCaseDes) != KErrNone)
+            {
+            return KErrNoMemory; 
+            }
+        if( aArray.Append( KOutputViewDes ) != KErrNone )
+            {
+            return KErrNoMemory; 
+            }
+        }
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu and test case specific information after that.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if FormatL leaves
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CCaseOperationMenu::PrintMenuL( TUpdateType  aType )
+    {
+
+    // Print menu
+    CMenu::PrintMenuL( aType );
+    
+    // Print the result description + result code
+    // If case is finished, print also result string
+    TInt state = iCaseContainer->Status();
+    if  ( ! ( state & CUIStoreIf::EStatusRunning ) )
+        {        
+
+        TName resultLine;
+        
+        Print (_L(""));
+        resultLine.Append(_L("Result info: ") );
+
+        if( state & CUIStoreIf::EStatusPassed )
+            {
+            resultLine.Append( _L("Passed" ) );
+            } 
+        else if( state & CUIStoreIf::EStatusFailed )
+            {
+            resultLine.Append( _L("Failed" ) );
+            } 
+        else if( state & CUIStoreIf::EStatusAborted )
+            {
+            resultLine.Append( _L("Aborted" ) );
+            } 
+        else if( state & CUIStoreIf::EStatusCrashed )
+            {
+            resultLine.Append( _L("Crashed" ) );
+            }
+        PrintMulti( resultLine );
+        resultLine.Zero();             
+
+        // Print test results
+        if( !( ( state & CUIStoreIf::EStatusAborted ) || 
+               ( state & CUIStoreIf::EStatusCrashed ) || 
+               ( state & CUIStoreIf::EStatusPassed ) ) )
+            {
+
+            resultLine.Format(_L("Result code %d"), 
+                iCaseContainer->Result().iTestResult.iResult );
+            PrintMulti ( resultLine );            
+            }
+
+        if( iCaseContainer->Result().iCaseExecutionResultType == 
+            TFullTestResult::ECaseErrorFromModule )
+            {
+            PrintMulti ( _L("Error from RunTestCase():"));
+            }
+
+        // Print result descriptor if that is available
+        const TDesC& des = iCaseContainer->Result().iTestResult.iResultDes;
+        if ( des.Length() >0 )
+            {
+            PrintMulti(des);
+            }
+
+        // Print abort code if that is available
+        if( ( state & CUIStoreIf::EStatusAborted ) ||
+            ( state & CUIStoreIf::EStatusCrashed ) )
+            {
+            // Print abort type, if that is available
+            TFullTestResult::TCaseExecutionResult res = 
+                iCaseContainer->Result().iCaseExecutionResultType;
+            
+            if ( res == TFullTestResult::ECaseLeave ||
+                 res == TFullTestResult::ECasePanic ||
+                 res == TFullTestResult::ECaseException || 
+                 res == TFullTestResult::ECaseErrorFromModule ||
+                 res == TFullTestResult::ECaseSuicided )
+                {
+                TInt code = iCaseContainer->Result().iCaseExecutionResultCode;
+                resultLine.Format(_L("Code %d (0x%x)"), code, code );
+                PrintMulti ( resultLine );
+                }
+            }
+
+        // Print start and end times
+        const TInt KTimeFieldLength = 30;
+        TBuf<KTimeFieldLength> time;
+        _LIT(KDateString,"%-B%:0%J%:1%T%:2%S%.%*C4%:3%+B");
+
+        resultLine = _L("Started:");
+        iCaseContainer->Result().iStartTime.FormatL(time,KDateString);
+        resultLine.Append(time);
+        PrintMulti (resultLine);
+
+        resultLine = _L("Completed:");
+        iCaseContainer->Result().iEndTime.FormatL(time,KDateString);
+        
+        resultLine.Append(time);
+        PrintMulti (resultLine);
+
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseOperationMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle Enter and right arrow
+    here, others are handled in parent menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CCaseOperationMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {   
+
+    MapKeyCode(aSelection);
+    
+    if (aSelection == EKeyEnter || aSelection == EKeyRightArrow )
+        {        
+        // restartOptionModifier is used because when test case is running
+        // restart option is not available (and visible) and that's why
+        // we need to modify switch by 1.
+        // When test case is finished, restart option becomes available
+        // and is put at the first place.
+        TInt restartOptionModifier = 0;
+        if(iCaseContainer->Status() & CUIStoreIf::EStatusRunning)
+            restartOptionModifier = 1;
+        
+        switch (iPosOnScreen + iFirst + restartOptionModifier)
+        {
+        case ERestartCase:
+            {
+            TInt index;
+            User::LeaveIfError(iMain->UIStore().StartTestCase(iCaseContainer->TestInfo(), index));
+            // Create output screen
+            CMenu* m = iMain->GetMainMenu()->CreateOutputViewL(iParent);
+            return m;
+            }
+        case EOutputView:
+            {
+            delete iView;
+            iView = 0;
+            iView = CCaseExecutionView::NewL( 
+                iMain, 
+                this, 
+                iCaseContainer->TestInfo().TestCaseTitle(), 
+                iCaseContainer );
+
+            return iView;
+            }
+
+        case EPauseResume:
+
+            if( iCaseContainer->UIEngineContainer().State() == 
+                CUIEngineContainer::ERunning )
+                {    
+                // Pausing a running case
+                iCaseContainer->UIEngineContainer().PauseTest();
+
+                }
+            else if( iCaseContainer->UIEngineContainer().State() == 
+                     CUIEngineContainer::EPaused )
+                {
+                // Resuming a paused case
+                iCaseContainer->UIEngineContainer().ResumeTest();
+
+                }
+            // No other possibilities
+            return this;
+
+        case EAbortCase:
+            iCaseContainer->UIEngineContainer().CancelTest();
+            break;
+
+        }
+        
+        return this;
+        }
+    else
+        {
+        return CMenu::SelectL(aSelection, aContinue);
+        }
+        
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseExecutionView
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                CStartedTestCase* aCase :in:      Case container
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseExecutionView* CCaseExecutionView::NewL( CConsoleMain* aConsole,
+                                              CMenu* aParent,
+                                              const TDesC& aName,
+                                              const CStartedTestCase* aCase )
+    {
+
+    CCaseExecutionView* self = new ( ELeave ) CCaseExecutionView();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName, aCase );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseExecutionView
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                CStartedTestCase* aCase :in:      Case container
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseExecutionView::ConstructL( CConsoleMain* aConsole,
+                                     CMenu* aParent,
+                                     const TDesC& aName,
+                                     const CStartedTestCase* aCase
+                                    )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName );
+
+    iCase = aCase;
+    
+    // Indicate that this menu contains prints, update when needed
+    iType = CUIStoreIf::EPrintUpdate;
+
+    iLine = 0;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CCaseExecutionView
+
+    Method: ~CCaseExecutionView
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CCaseExecutionView::~CCaseExecutionView()
+    {
+    delete iLineTextBuf;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu. Show the test status and the test case
+    print statements.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CCaseExecutionView::PrintMenuL( TUpdateType  /*aType*/ )
+    {
+    
+    if( iShowLine )
+        {
+        // User want to see whole line 
+        iConsole->ClearScreen();
+        this->PrintMulti( iLineTextBuf->Des() );
+        return;
+        }
+
+    // Print the status
+    TName tmp;
+    TInt state = iCase->Status();
+    if( state & CUIStoreIf::EStatusRunning )
+        {
+        if( iCase->UIEngineContainer().State() == 
+            CUIEngineContainer::EPaused )
+            {
+            tmp = _L("Paused");
+            }
+        else
+            {
+            tmp = _L("Running");
+            }
+        }
+    else if( state & CUIStoreIf::EStatusPassed )
+        {
+        tmp = _L("Passed");
+        }
+    else if( state & CUIStoreIf::EStatusFailed )
+        {
+        tmp = _L("Failed");
+        }
+    else if( state & CUIStoreIf::EStatusAborted )
+        {
+        tmp = _L("Aborted");
+        }
+    else if( state & CUIStoreIf::EStatusCrashed )
+        {
+        tmp = _L("Aborted");
+        }
+    else
+        {
+        tmp = _L("Unknown");
+        }
+    
+    // Clear screen.
+    iConsole->ClearScreen();
+    TBuf<KMaxLineLength> line;
+
+    line.Append(_L(" : "));
+    LimitedAppend(line, iCase->TestInfo().TestCaseTitle() );
+    Print( line );
+
+    const RPointerArray<CTestProgress>& prints = iCase->PrintArray();
+
+    Recalculate( prints.Count() );
+
+    // Print the print statements.
+    for ( TInt i = iFirst; i <= iLast; i++ )
+        {
+        line.Zero();
+        if( iLine == i )
+            {
+            line = _L( "*" ); // For indicating current line
+            }
+        line.Append( prints[i]->iDescription );
+        line.Append(_L(" : "));
+        LimitedAppend(line, prints[i]->iText );
+
+        // Print the line
+        TSize screenSize;
+        //screenSize = iConsole->ScreenSize();
+        iConsole->Size(screenSize);
+        Print ( line.Left(screenSize.iWidth ) );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseExecutionView
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Either updates position in
+    menu or returns new menu.
+
+    Parameters: TKeyCode aSelection: in: Key
+                TBool& aContinue: out: Has user pressed "Quit"
+
+    Return Values: CMenu* New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CCaseExecutionView::SelectL( TKeyCode aSelection, TBool& /*aContinue*/ )
+    {
+    iShowLine = EFalse;
+    MapKeyCode(aSelection);
+
+    // Take prints
+    const RPointerArray<CTestProgress>& prints = iCase->PrintArray();
+
+    switch( aSelection  )
+        {        
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            // Check that not out of range(too many EKeyUpArrow or EKeyDownArrow)
+            if( iLine >= prints.Count() || iLine < 0)
+                {
+                // do nothing
+                break;
+                }
+            TInt extra = 3; // ' : '
+            TInt length( 0 );
+            length = length + prints[iLine]->iDescription.Length();
+            length = length + prints[iLine]->iText.Length();
+            // Selected print line in seperate(operation will do in
+            // CCaseExecutionView::PrintMenuL() method )
+            delete iLineTextBuf;
+			iLineTextBuf = NULL;
+            TRAPD( ret, iLineTextBuf = HBufC::NewL( length + extra ) );
+            if( ret != KErrNone )
+                {
+                User::InfoPrint( _L("Line show failed, maybe out of memory!!!") );
+                break;
+                }
+            TPtr ptr = iLineTextBuf->Des();
+            ptr.Copy( prints[iLine]->iDescription );
+            ptr.Append( _L( " : " ) );
+            ptr.Append( prints[iLine]->iText );
+            iShowLine = ETrue;
+            break;
+            }
+        case EKeyLeftArrow:
+            {
+            return iParent;
+            }
+		// Go down
+		case EKeyDownArrow:
+			{
+			if ( iFirst + iPosOnScreen == iItemCount - 1 )
+				{
+				// If end of the list, go to beginning
+				iPosOnScreen = 0;
+				iFirst = 0;
+				iLast = iScreenSize;
+				if ( iLast > iItemCount - 1 )
+					{
+					iLast = iItemCount - 1;
+					}
+				iLine = 0;
+				}
+			else 
+				{
+				if ( iPosOnScreen == iScreenSize )
+					{
+					iLast++;
+					iFirst++;
+					}
+				else
+					{
+					// Going down "in-screen", no need to update items
+					iPosOnScreen++;
+					}
+				iLine++;
+				}			
+			break;
+			}
+			
+		// Go Up
+		case EKeyUpArrow:
+			{
+			if ( iFirst + iPosOnScreen == 0 )
+				{
+				// If in the beginning of the list
+
+				iLast = iItemCount - 1;
+				iFirst = iLast - iScreenSize;
+				if ( iFirst < 0 )
+					{
+					iFirst = 0;            	
+					}
+				iPosOnScreen = iLast - iFirst;
+				iLine = iItemCount - 1;
+				}
+			else 
+				{
+				if ( iPosOnScreen == 0 )
+					{
+					iLast--;
+					iFirst--;
+					}
+				else
+					{
+					iPosOnScreen--;
+					}
+				iLine--;
+			}
+			break;
+			}
+		// Additional keys
+		case EKeyHome:
+		case '3':
+			iPosOnScreen = 0;
+			iLine = 0;
+			iFirst = 0;
+			iLast = iScreenSize;
+
+			if ( iLast > iItemCount - 1 )
+				{
+				iLast = iItemCount - 1;
+				}
+			break;
+
+		case EKeyEnd:
+		case '9':
+			iLast = iItemCount - 1;
+			iFirst = iLast - iScreenSize;
+			iLine = iItemCount - 1;
+			
+			if ( iFirst < 0 )
+				{
+				iFirst = 0;
+				}
+			iPosOnScreen = iLast - iFirst;        
+			break;
+
+		case EKeyPageUp:
+		case '1':
+			iFirst = iFirst - iScreenSize;
+			iLast = iLast - iScreenSize;
+
+			if ( iFirst < 0 )
+				{
+				iFirst = 0;
+				iLast = iScreenSize;
+				if ( iLast > iItemCount - 1 )
+					{
+					iLast = iItemCount - 1;
+					}
+				iPosOnScreen = 0;
+				}
+			
+			iLine = iLine - iScreenSize;
+			if ( iLine < 0 )
+				{
+				iLine = 0;
+				}
+			break;
+
+		case EKeyPageDown:
+		case '7':
+			iFirst = iFirst + iScreenSize;
+			iLast = iLast + iScreenSize;
+
+			// Going too far
+			if ( iLast > iItemCount - 1 )
+				{
+				iLast = iItemCount - 1;
+				iFirst = iLast - iScreenSize;
+				if ( iFirst < 0 )
+					{
+					iFirst = 0;
+					}
+				iPosOnScreen = iLast - iFirst;
+				}
+
+			iLine = iLine + iScreenSize;
+			if ( iLine > iItemCount - 1 )
+				{
+				iLine = iItemCount - 1;
+				}
+			break;
+        default:
+            {
+            break;
+            }
+        }
+    
+    return this;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetMenu* CTestSetMenu::NewL( CConsoleMain* aConsole,
+                                        CMenu* aParent,
+                                        const TDesC& aName )
+    {    
+
+    CTestSetMenu* self = new ( ELeave ) CTestSetMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+       
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: CTestSetMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetMenu::CTestSetMenu():
+    iTestSetCreated( EFalse )
+    {
+    
+    iTestSetName.Copy( KDefaultSetName );    
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: ~CTestSetMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestSetMenu::~CTestSetMenu()
+    {
+    
+    delete iSubMenu;
+    iSubMenu = 0;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor. 
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if module can't be appended to list
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetMenu::ConstructL( CConsoleMain* aConsole,
+                                  CMenu* aParent,
+                                  const TDesC& aName
+                                 )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+   
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: SetTestSetName
+
+    Description: Set test set name.
+
+    Parameters: const TFileName& aTestSetName: in: Test set name
+
+    Return Values: None
+    
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetMenu::SetTestSetFileName( const TFileName& aTestSetName )
+    {
+    
+    iTestSetName.Copy( aTestSetName );    
+    
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    if( !iTestSetCreated )
+        {
+        if( aArray.Append( KSetCreate ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if( aArray.Append( KSetLoad ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }        
+        }
+    else
+        {
+        if( aArray.Append( KSetShow ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetStartSeq ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetStartPar ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        if( aArray.Append( KSetUnload ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                        			
+        if( aArray.Append( KSetRemove ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetSave ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetCaseAdd ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetCaseRemove ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        if( aArray.Append( KSetStartSeqNotRun ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }                
+        }
+        
+    return KErrNone; 
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CTestSetMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestSetMenu::PrintMenuL( TUpdateType aType )
+    {
+    
+    if( iTestSetCreated )
+        {
+        RRefArray<CTestSetInfo> setInfos;
+        TInt ret = iMain->UIStore().TestSets( setInfos );
+
+        CMenu::PrintMenuL( aType );
+
+        if( (  ret != KErrNone ) ||
+            ( setInfos.Count() != 1 ) )
+            {
+            // Should never ever happen
+            User::Panic( KTestSetMenu, KErrGeneral );
+            return;
+            }
+        const CTestSetInfo& set = setInfos[0];
+        setInfos.Reset();
+        setInfos.Close();
+        
+        const RRefArray<const CTestInfo> testCases = set.TestCases();
+        
+        TBuf<KMaxLineLength> line;
+        TInt count = testCases.Count();
+        for(TInt i = 0; i < count && i + ESetLAST <= iScreenSize; i++)
+            {
+            line = _L("    ");
+            LimitedAppend ( line, testCases[i].TestCaseTitle() );
+
+            // Print the line
+            Print(line);
+            }
+        }
+    else
+        {
+        CMenu::PrintMenuL( aType );
+        }    
+    
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle right arrow and enter
+                 here, others in parent menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+    
+    MapKeyCode(aSelection);    
+    
+    if( ( aSelection != EKeyRightArrow ) &&
+        ( aSelection != EKeyEnter ) )
+        {
+        return CMenu::SelectL( aSelection, aContinue );
+        }            
+    
+    TInt ret = KErrNone;        
+    if( !iTestSetCreated )
+        {
+        switch( iPosOnScreen )
+            {
+            case ESetCreate:
+                ret = iMain->UIStore().CreateTestSet( iTestSetName );
+                if( ret != KErrNone )
+                    {
+                    User::InfoPrint( _L("Test set creation failed") );
+                    }
+                break;
+            case ESetLoad: 
+            	return iItems[0];
+            } 
+        if( ret == KErrNone )
+            {
+            iTestSetCreated = ETrue;
+            }      
+        }
+    else
+        {
+        CStartedTestSet::TSetType setType = CStartedTestSet::ESetSequential;
+        switch( iPosOnScreen )
+            {
+            case ESetShow:   
+            // Add the test sets menu
+                delete iSubMenu;
+                iSubMenu = 0;
+                iSubMenu = CStartedTestSetMenu::NewL( iMain, 
+                                        this, 
+                                        _L("Started test sets menu"));
+                return iSubMenu;
+            case ESetUnload:
+                ret = iMain->UIStore().UnloadTestSet( iTestSetName );
+                if( ret != KErrNone )
+                    {
+                    User::InfoPrint( _L("Test set unload failed") );
+                    }
+                iTestSetCreated = EFalse;                  
+                break;
+            case ESetRemove: 
+                ret = iMain->UIStore().RemoveTestSet( iTestSetName );
+                if( ret != KErrNone )
+                    {
+                    User::InfoPrint( _L("Test set remove failed") );
+                    }
+                iTestSetCreated = EFalse;  
+                break;
+            case ESetCaseAdd:   
+                delete iSubMenu;
+                iSubMenu = 0;
+                iSubMenu = CTestSetAddCaseMenu::NewL( 
+                                iMain, 
+                                this, 
+                                _L("Add test cases to test set"),
+                                iTestSetName );
+                                
+                return iSubMenu;
+            case ESetCaseRemove: 
+                delete iSubMenu;
+                iSubMenu = 0;
+                iSubMenu =  CTestSetRemoveCaseMenu::NewL( 
+                                iMain, 
+                                this, 
+                                _L("Remove test cases from test set"),
+                                iTestSetName );
+                                
+                                
+                return iSubMenu;  
+            case ESetSave: 
+                ret = iMain->UIStore().SaveTestSet2( iTestSetName );
+                if( ret != KErrNone )
+                    {
+                    User::InfoPrint( _L("Test set saving failed") );
+                    }   
+                break;
+  
+  			default:          
+//            case ESetStartPar:   
+//                setType = CStartedTestSet::ESetParallel;
+//            case ESetStartSeq: 
+            //case ESetStartRep: 
+            	if( iPosOnScreen == ESetStartPar )
+                  {
+	            		setType = CStartedTestSet::ESetParallel;
+                  }
+              if( iPosOnScreen == ESetStartSeq || iPosOnScreen == ESetStartSeqNotRun)
+	                {
+	                RRefArray<CTestSetInfo> setInfos;
+	                ret = iMain->UIStore().TestSets( setInfos );
+	                if( (  ret != KErrNone ) ||
+	                    ( setInfos.Count() != 1 ) )
+	                    {
+	                    // Should never ever happen
+	                    User::Panic( KTestSetMenu, KErrGeneral );
+	                    }
+	                const CTestSetInfo& set = setInfos[0];
+	                setInfos.Reset();
+	                setInfos.Close();
+	                
+	                TInt index;
+	                ret = KErrGeneral;
+	                if(iPosOnScreen == ESetStartSeq)
+	                    {
+                        ret = iMain->UIStore().StartTestSet(set, index, setType);
+                        }
+                    else if(iPosOnScreen == ESetStartSeqNotRun)
+                        {
+	                    ret = iMain->UIStore().StartTestSet(set, index, setType, ETrue);
+	                    }
+	                if( ret != KErrNone )
+	                    {
+	                    User::InfoPrint( _L("Test set starting failed") );
+	                    }                 
+	                }    
+                break;
+            }
+        }
+        
+    return this;
+
+    }
+/**
+-------------------------------------------------------------------------------
+
+Class: CTestSetChoiceMenu
+
+Method: NewL
+
+Description: Constructs new menu.
+
+Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+            CMenu* aParent            :in:      Parent menu
+            const TDesC& aName        :in:      Menu name
+
+Return Values: CMenu*                           New menu
+
+Errors/Exceptions: Leaves if memory allocation fails
+                   Leaves if ConstructL leaves.
+
+Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetChoiceMenu* CTestSetChoiceMenu::NewL( CConsoleMain* aConsole,
+                                    CMenu* aParent,
+                                    const TDesC& aName )
+{    
+
+	CTestSetChoiceMenu* self = new ( ELeave ) CTestSetChoiceMenu();
+	CleanupStack::PushL( self );
+	self->ConstructL( aConsole, aParent, aName );
+	CleanupStack::Pop( self );
+	return self;
+
+}
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: CTestSetChoiceMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetChoiceMenu::CTestSetChoiceMenu()
+    
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: ~CTestSetChoiceMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestSetChoiceMenu::~CTestSetChoiceMenu()
+    {
+    
+    
+
+    iFileList.ResetAndDestroy();
+    iFileList.Close();
+
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor. 
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if module can't be appended to list
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetChoiceMenu::ConstructL( CConsoleMain* aConsole,
+                                  CMenu* aParent,
+                                  const TDesC& aName
+                                 )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text.
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetChoiceMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+   TInt ret = iMain->UIStore().GetTestSetsList( aArray );
+   TRAPD( err,
+	//Assign aArray to iFileList, it is used in LoadTestSet
+   for( TInt i=0 ; i < aArray.Count(); i++)
+	  {
+	  iFileList.AppendL(aArray[i].AllocL());
+	  }
+     ); // TRAPD
+   return err;       
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CTestSetChoiceMenu
+
+    Method: PrintMenuL
+
+    Description: Prints the menu
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestSetChoiceMenu::PrintMenuL( TUpdateType aType )
+    {
+    
+    iUpdateType = aType;
+    
+    TBuf<KMaxLineLength> line;
+    
+    // Clear display
+    iConsole->ClearScreen();
+
+    // Print menu title
+    Print( Name() );
+    
+    RRefArray<TDesC> texts;
+    if(  iMain->UIStore().GetTestSetsList( texts ) != KErrNone )
+        {
+        return;
+        }
+    
+    TInt oldItemCount = iItemCount;
+     
+    iItemCount = texts.Count();
+
+    // If first time in menu, update start and end positions
+    if( (iFirst == iLast) ||        // First time here..
+        ( iLast >= iItemCount ) ||
+        ( oldItemCount != iItemCount ) )      // Menu size changed
+        {
+        iLast = iItemCount - 1;
+        iPosOnScreen = 0;
+
+        // If "overflow", then adjust the end
+        if (iLast > iScreenSize )
+            {
+            iLast = iScreenSize;
+            }
+        }
+    
+    // Print items
+    for ( TInt i = iFirst; i <= iLast; i++ )
+        {
+        line.Zero();
+        
+        // Append text before line
+        AppendBefore( i, line );
+
+        // Get the menu line
+        LimitedAppend ( line, texts[i] );
+
+        // Print the line
+        Print(line);
+
+        }
+    texts.Close();
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetChoiceMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle right arrow and enter
+                 here, others in parent menu.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetChoiceMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+    
+    //return CMenu::SelectL( aSelection, aContinue );    
+    //return iParent;
+	    MapKeyCode(aSelection);
+	    TInt ret = 0;
+    
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {           
+                if(iPosOnScreen < iFileList.Count())
+                    {
+                
+                    ret = iMain->UIStore().LoadTestSet( iFileList.operator [](iPosOnScreen)->Des() );
+                    if (ret == KErrNone)
+                        {
+                        ((CTestSetMenu*)iParent)->SetCreated();
+                        ((CTestSetMenu*)iParent)->SetTestSetFileName(iFileList.operator [](iPosOnScreen)->Des());
+                        }
+                    return iParent;
+                    }
+                else
+                    {
+                    return this;
+                    }
+                }
+            default:
+                break;
+            }
+            
+    return CMenu::SelectL( aSelection, aContinue );    
+
+    }
+
+
+
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetAddCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetAddCaseMenu* CTestSetAddCaseMenu::NewL( CConsoleMain* aConsole,
+                                            CMenu* aParent,
+                                            const TDesC& aName,
+                                            TDesC& aTestSetName )
+    {
+
+    CTestSetAddCaseMenu* self = 
+        new ( ELeave ) CTestSetAddCaseMenu( aTestSetName );
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetAddCaseMenu
+
+    Method: CTestSetAddCaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetAddCaseMenu::CTestSetAddCaseMenu( TDesC& aTestSetName ):
+    iTestSetName( aTestSetName )    
+    {
+    
+    iMenuItemsCount = EAddSelected + 1;
+    iMenuTotCount += iMenuItemsCount;
+    
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetAddCaseMenu
+
+    Method: ~CTestSetAddCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetAddCaseMenu::~CTestSetAddCaseMenu()
+    {
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetAddCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetAddCaseMenu::ConstructL( CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName )
+    {
+
+    CCaseStartMenu::ConstructL( aConsole, aParent, aName );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetAddCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetAddCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    if ( iSetFinished )
+        {
+        if( aArray.Append( KAddSelected ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    return CMultipleBaseMenu::ItemTexts( aArray );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetAddCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetAddCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    if ( iSetFinished )
+        {
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {
+
+                if ( iFirst + iPosOnScreen == EAddSelected )
+                    {
+                    TInt count = iTestCases.Count();    
+                    for( TInt i=0; i<count; i++ )
+                        {
+                        if ( iSetState[i] )
+                            {
+                            TInt ret = 
+                                iMain->UIStore().AddToTestSet( iTestSetName,
+                                                               iTestCases[i] );
+                            if( ret != KErrNone )
+                                {
+                                User::InfoPrint( _L("Test case adding failed") );
+                                }   
+                            }
+                        } 
+                    return iParent;
+                    }               
+                }
+                break;
+            default:
+                break;
+            }
+        }   
+        
+    return CMultipleBaseMenu::SelectL( aSelection, aContinue );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetAddCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetRemoveCaseMenu* CTestSetRemoveCaseMenu::NewL( CConsoleMain* aConsole,
+                                            CMenu* aParent,
+                                            const TDesC& aName,
+                                            TDesC& aTestSetName )
+    {
+
+    CTestSetRemoveCaseMenu* self = 
+        new ( ELeave ) CTestSetRemoveCaseMenu( aTestSetName );
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetRemoveCaseMenu
+
+    Method: CTestSetRemoveCaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetRemoveCaseMenu::CTestSetRemoveCaseMenu( TDesC& aTestSetName ):
+    iTestSetName( aTestSetName )    
+    {
+    
+    iMenuItemsCount = ERemoveSelected + 1;
+    iMenuTotCount += iMenuItemsCount;
+    
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    CTestSetRemoveCaseMenu
+
+    Method: ~CTestSetRemoveCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetRemoveCaseMenu::~CTestSetRemoveCaseMenu()
+    {
+    }   
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetRemoveCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetRemoveCaseMenu::ConstructL( CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName )
+    {
+
+    CCaseStartMenu::ConstructL( aConsole, aParent, aName );
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetRemoveCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetRemoveCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+
+    if ( iSetFinished )
+        {
+        if( aArray.Append( KRemoveSelected ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    return CMultipleBaseMenu::ItemTexts( aArray );
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetRemoveCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetRemoveCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    if ( iSetFinished )
+        {
+        switch ( aSelection )
+            {
+            case EKeyEnter:
+            case EKeyRightArrow:
+                {
+
+                if ( iFirst + iPosOnScreen == ERemoveSelected )
+                    {
+                    TInt count = iTestCases.Count();    
+                    for( TInt i=0; i<count; i++ )
+                        {
+                        if ( iSetState[i] )
+                            {
+                            TInt ret = 
+                                iMain->UIStore().RemoveFromTestSet( iTestSetName,
+                                                                    iTestCases[i] );
+                            if( ret != KErrNone )
+                                {
+                                User::InfoPrint( _L("Test case adding failed") );
+                                }   
+                            }
+                        } 
+                    return iParent;
+                    }               
+                }
+                break;
+            default:
+                break;
+            }
+        }   
+        
+    return CMultipleBaseMenu::SelectL( aSelection, aContinue );
+        
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetRemoveCaseMenu
+
+    Method: UpdateTestCases
+
+    Description: 
+
+    Parameters: 
+
+    Return Values: 
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetRemoveCaseMenu::UpdateTestCases()
+    {
+    
+    TRAPD( err,
+        const CTestSetInfo& set = iMain->UIStore().TestSetL( iTestSetName );                
+        const RRefArray<const CTestInfo>& testCases = set.TestCases();
+
+        // Update test cases
+        iTestCases.Reset();
+        iSetState.Reset();
+        
+        TInt count = testCases.Count();
+        for( TInt i=0; i<count; i++ )
+            {
+            err = iTestCases.Append( testCases[i] );
+            if( err != KErrNone )
+                {
+                break;
+                }
+            }
+
+        ); // TRAPD
+                
+    return err;
+                
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestSetMenu* CStartedTestSetMenu::NewL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName )
+    {
+
+    CStartedTestSetMenu* self = new ( ELeave ) CStartedTestSetMenu();
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: CStartedTestSetMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CStartedTestSetMenu::CStartedTestSetMenu()
+    {
+    iType = CUIStoreIf::ESetAll;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if memory allocation fails
+                       Leaves if CCaseOperation menu NewL leaves
+                       Leaves if UpcateCaseListL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CStartedTestSetMenu::ConstructL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName )
+    {
+
+    CMenu::ConstructL( aConsole, aParent, aName);
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: ~CStartedTestSetMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CStartedTestSetMenu::~CStartedTestSetMenu()
+    {
+
+    delete iCaseMenu;
+    iCaseMenu = 0;
+    
+    iTestSets.Reset();
+    iTestSets.Close();
+
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CStartedTestSetMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    iTestSets.Reset();
+    
+    TInt ret = iMain->UIStore().StartedTestSets( iTestSets, iType );
+    if ( ret != KErrNone )
+    	{
+    	return ret;
+    	}
+
+    TInt count = iTestSets.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( aArray.Append( iTestSets[i].TestSetInfo().Name() ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CStartedTestSetMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number 
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CStartedTestSetMenu::AppendBefore( TInt aLineNum, TDes& aLine )
+    {
+    
+    CMenu::AppendBefore( aLineNum, aLine );
+    
+    if( ( aLine.MaxLength() - aLine.Length() ) < 2 )
+        {
+        return;
+        }        
+    if( iTestSets[aLineNum].Status() & CUIStoreIf::ESetRunning )
+        {
+        aLine.Append( _L("O ") );
+        }
+    else if( iTestSets[aLineNum].Status() & CUIStoreIf::ESetPassed )
+        {
+        aLine.Append( _L("P ") );
+        }    
+    else if( iTestSets[aLineNum].Status() & CUIStoreIf::ESetFailed )
+        {
+        aLine.Append( _L("F ") );
+        }    
+            
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStartedTestSetMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle Enter and Right Arrow
+    here, other will be handled in CMenu::SelectL
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CStartedTestSetMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+
+    MapKeyCode(aSelection);
+    
+    switch (aSelection)
+        {
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            if ( iFirst + iPosOnScreen < iTestSets.Count() )
+                {
+                delete iCaseMenu;
+                iCaseMenu = 0;
+                iCaseMenu = CTestSetCaseMenu::NewL( 
+                    iMain, 
+                    this, 
+                    iTestSets[iFirst + iPosOnScreen].TestSetInfo().Name(), 
+                    iTestSets[iFirst + iPosOnScreen] ); 
+
+                return iCaseMenu;
+                }
+            }
+            return this;
+        default:
+            break;
+        }   
+        
+    // Let the parent class handle rest
+    return CMenu::SelectL(aSelection, aContinue);
+    
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetCaseMenu* CTestSetCaseMenu::NewL( CConsoleMain* aConsole, 
+                                          CMenu* aParent, 
+                                          const TDesC& aName,
+                                          CStartedTestSet& aTestSet  )
+    {
+
+    CTestSetCaseMenu* self = new ( ELeave ) CTestSetCaseMenu( aTestSet );
+    CleanupStack::PushL( self );
+    self->ConstructL( aConsole, aParent, aName );
+    CleanupStack::Pop( self );
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: CTestSetCaseMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CTestSetCaseMenu::CTestSetCaseMenu( CStartedTestSet& aTestSet ):
+    iTestSet( aTestSet )
+    {
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+                TCaseState aType          :in:      Case state
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if parent class ConstructL leaves
+                       Leaves if memory allocation fails
+                       Leaves if CCaseOperation menu NewL leaves
+                       Leaves if UpcateCaseListL leaves
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CTestSetCaseMenu::ConstructL( CConsoleMain* aConsole, 
+                            CMenu* aParent, 
+                            const TDesC& aName )
+    {
+
+    CCaseMenu::ConstructL( aConsole, aParent, aName, 
+                           CUIStoreIf::EStatusAll );
+
+    }
+
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: ~CTestSetCaseMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+CTestSetCaseMenu::~CTestSetCaseMenu()
+    {
+    }
+
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CTestSetCaseMenu::ItemTexts( RRefArray<TDesC>& aArray )
+    {
+    
+    if ( iTestSet.Status() & CUIStoreIf::ESetRunning )
+        {
+        if( aArray.Append( KCancelTestSet ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }
+        }
+    
+    const RRefArray<CStartedTestCase>& testCases = iTestSet.TestCases();
+        
+    iTestCases.Reset();
+    
+    TInt count = testCases.Count();
+    for( TInt i=0; i<count; i++ )
+        {
+        if( iTestCases.Append( testCases[i] ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }  
+        if( aArray.Append( testCases[i].TestInfo().TestCaseTitle() ) != KErrNone )
+            {
+            return KErrNoMemory;
+            }   
+        }
+
+    return KErrNone;
+    
+    }
+
+/*
+-------------------------------------------------------------------------------
+    Class: CTestSetCaseMenu
+
+    Method: AppendBefore
+
+    Description: Append text before line.
+
+    Parameters: TInt aLine: in: line number 
+                TDes& aLine: in: line text
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+    
+-------------------------------------------------------------------------------
+*/
+void CTestSetCaseMenu::AppendBefore( TInt aLineNum, TDes& aLine )
+    {
+    
+    CMenu::AppendBefore( aLineNum, aLine );
+   
+    TInt testCaseNum = aLineNum; 
+    if( iTestSet.Status() & CUIStoreIf::ESetRunning ) 
+        {
+        if( aLineNum == 0 )
+            {
+            // "Cancel test set" row
+            return;
+            }
+        testCaseNum--;
+        }
+        
+    if( ( aLine.MaxLength() - aLine.Length() ) < 2 )
+        {
+        return;
+        }        
+    
+   if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusRunning )
+        {
+        aLine.Append( _L("O ") );
+        }
+    else if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusPassed )
+        {
+        aLine.Append( _L("P ") );
+        }
+    else if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusFailed )
+        {
+        aLine.Append( _L("F ") );
+        }
+    else if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusAborted )
+        {
+        aLine.Append( _L("A ") );
+        }
+    else if( iTestCases[testCaseNum].Status() & CUIStoreIf::EStatusCrashed )
+        {
+        aLine.Append( _L("C ") );
+        }
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CTestSetCaseMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CTestSetCaseMenu::SelectL( TKeyCode aSelection, TBool& aContinue )
+    {
+    
+    MapKeyCode(aSelection);
+
+    if( ( aSelection == EKeyEnter ) || ( aSelection == EKeyRightArrow ) )
+        {
+        TInt pos = iFirst + iPosOnScreen; 
+        if( iTestSet.Status() & CUIStoreIf::ESetRunning )
+            {
+            pos--;
+            }               
+        if( pos == -1 )
+            {
+            User::LeaveIfError( 
+                iMain->UIStore().AbortTestSet( iTestSet ) );
+            return iParent;             
+            }
+        else if( pos < iTestCases.Count() )
+            {
+            delete iCaseOperationMenu;
+            iCaseOperationMenu = 0;
+            iCaseOperationMenu = CCaseOperationMenu::NewL( 
+                iMain, 
+                this, 
+                iTestCases[pos].TestInfo().TestCaseTitle(), 
+                &iTestCases[pos] ); 
+
+            return iCaseOperationMenu;
+            }
+        }
+
+        // Let the parent class handle rest
+    return CMenu::SelectL(aSelection, aContinue);
+    }
+        
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: NewL
+
+    Description: Constructs new menu.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: Leaves if memory allocation fails
+                       Leaves if ConstructL leaves.
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CFilterMenu* CFilterMenu::NewL(CConsoleMain* aConsole,
+                               CMenu* aParent,
+                               const TDesC& aName)
+    {
+    CFilterMenu* self = new (ELeave) CFilterMenu();
+    CleanupStack::PushL(self);
+    self->ConstructL(aConsole, aParent, aName);
+    CleanupStack::Pop(self);
+    return self;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: ConstructL
+
+    Description: Second level constructor.
+
+    Parameters: CConsoleMain* aConsole    :in:      Pointer to main console
+                CMenu* aParent            :in:      Parent menu
+                const TDesC& aName        :in:      Menu name
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CFilterMenu::ConstructL(CConsoleMain* aConsole,
+                             CMenu* aParent,
+                             const TDesC& aName
+                            )
+    {
+    CMenu::ConstructL(aConsole, aParent, aName);
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    CFilterMenu
+
+    Method: CFilterMenu
+
+    Description: Constructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CFilterMenu::CFilterMenu()
+    {
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    CFilterMenu
+
+    Method: ~CFilterMenu
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CFilterMenu::~CFilterMenu()
+    {
+    delete iTestCaseMenu;
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: ItemText
+
+    Description: Returns menu item text
+
+    Parameters: const TInt                :in:      Menu index
+
+    Return Values: const TDesC&                     Menu line text
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+TInt CFilterMenu::ItemTexts(RRefArray<TDesC>& aArray)
+    {
+    const RPointerArray<TDesC> &filters = iMain->GetFilterArray();
+    TInt ret;
+    
+    TInt count = filters.Count();
+    for(TInt i = 0; i < count; i++)
+        {    
+        ret = aArray.Append(*filters[i]);
+        if(ret != KErrNone)
+            {
+            return ret;
+            }
+        }
+        
+    return KErrNone;
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: SelectL
+
+    Description: Process keypresses in menu. Handle enter and right arrow here,
+    others in CMenu::SelectL.
+
+    Parameters: TKeyCode aSelection       :in:      Key
+                TBool& aContinue          :out:     Has user pressed "Quit"
+
+    Return Values: CMenu*                           New menu
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+CMenu* CFilterMenu::SelectL(TKeyCode aSelection, TBool& aContinue)
+    {
+    const RPointerArray<TDesC> &filters = iMain->GetFilterArray();
+    
+    MapKeyCode(aSelection);
+    
+    switch ( aSelection )
+        {
+        case EKeyEnter:
+        case EKeyRightArrow:
+            {
+            // Start the case
+            if((iFirst + iPosOnScreen) < filters.Count())
+                {
+                // Show test cases menu
+                iMain->SetFilterIndex(iFirst + iPosOnScreen);
+                if(iTestCaseMenu)
+                    {
+                    return iTestCaseMenu;
+                    }
+                else
+                    {
+                    RDebug::Print(_L("STIF: CFilterMenu::SelectL: test case menu is not set, however it should be"));
+                    return this;
+                    }
+                }
+            else
+                {
+                return this;
+                }
+            }
+
+        default:
+            return CMenu::SelectL( aSelection, aContinue);
+        }
+    }
+    
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFilterMenu
+
+    Method: SetTestCaseMenu
+
+    Description: Set pointer to test case menu, so it can be shown when user
+                 selects filter.
+                 This menu will be deleted along with the filter menu.
+
+    Parameters: CMenu* aTestCaseMenu      :in:      test case menu
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Draft
+
+-------------------------------------------------------------------------------
+*/
+void CFilterMenu::SetTestCaseMenu(CMenu* aTestCaseMenu)
+    {
+    if(iTestCaseMenu)
+        {
+        RDebug::Print(_L("STIF: CFilterMenu::SetTestCaseMenu: test case menu is already set!"));
+        delete iTestCaseMenu;
+        iTestCaseMenu = NULL;
+        }
+    iTestCaseMenu = aTestCaseMenu;
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/envpatcher/EnvPatcher.pl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,544 @@
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+# 
+# Description:
+# Environment Patcher - Patches older S60 SDKs for supporting
+# tricks in newer platforms
+#
+
+
+require v5.6.1;	
+
+use File::Copy;
+use strict;
+
+# check amount of commandline options is valid
+if (@ARGV != 1)
+{
+    print "Usage: EnvPatcher <EPOCROOT>\n";
+    exit 1;
+}
+
+
+# get epocroot and convert, convert \ -> /
+(my $epocroot = $ARGV[0]) =~ s{\\}{/}g;
+
+# remove any trailing forward slashes
+$epocroot =~ s/\/$//;
+
+
+# create variables for paths
+my $e32toolsdir = $epocroot."/epoc32/tools";
+my $e32includedir = $epocroot."/epoc32/include";
+my $e32includeoemdir = $e32includedir."/oem";
+my $platformpathspath = $e32includedir."/platform_paths.hrh";
+my $domainplatformpathspath = $e32includedir."/domain/osextensions/platform_paths.hrh";
+my $mmppmpath = $e32toolsdir."/mmp.pm";
+my $pathutlpmpath = $e32toolsdir."/pathutl.pm";
+my $prepfilepmpath = $e32toolsdir."/prepfile.pm";
+
+# variables for hacked content
+my $dependshack = "\t\t\tif (/^DEPENDS\$/o) {\r\n\t\t\t\tnext LINE;  # Ignore DEPENDS keyword, not needed by ABLD\r\n\t\t\t}\r\n";
+my $smpsafehack = "\t\tif (/^SMPSAFE\$/o) {\r\n\t\t\tnext LINE;  # Ignore SMPSAFE keyword, not needed by older environments\r\n\t\t}\r\n";
+my $forwardslashhack = "\t\t# EnvPatcher forwardslash hack begins\r\n\t\t\$_=~s{/}{\\\\}g;   # convert all forward slashes to backslashes\r\n\t\t# EnvPatcher forwardslash hack ends\r\n\r\n";
+my $coreibyexportsupport = "\r\n// Following definition is used for exporting tools and stubs IBY files to\r\n// Core image.\r\n#define CORE_IBY_EXPORT_PATH(path,exported)  /epoc32/rom/include/##exported\r\n";
+
+
+# check epoc32\tools exists
+unless (-d $e32toolsdir)
+{
+    print "$e32toolsdir not found, please check valid epocroot has been given!\n";
+    exit 1;
+}
+
+# check epoc32\include exists
+unless (-d $e32includedir)
+{
+    print "$e32includedir not found, please check valid epocroot has been given!\n";
+    exit 1;
+}
+
+
+# create epoc32\include\oem if it does not exist
+unless (-d $e32includeoemdir)
+{
+    mkdir $e32includeoemdir or die;
+    print "Missing directory $e32includeoemdir created succesfully.\n";
+}
+
+
+# check if epoc32\include\domain\osextensions\platform_paths.hrh exists
+if (-e $domainplatformpathspath)
+{
+    # show an error if the file does not have any platform macros
+    unless (string_exists_in_file($domainplatformpathspath, "OS_LAYER_SYSTEMINCLUDE"))
+    {
+        print "ERROR: $domainplatformpathspath does not have SF macros.\n";
+        print "Please check your environment, if you have S60 3.2 OEM or newer, please get the latest version!\n";
+        exit 2;
+    }
+}
+
+
+# check if epoc32\include\platform_paths.hrh exists
+if (-e $platformpathspath)
+{
+    print "$platformpathspath already exists, not checking it.\n";    
+}
+else
+{
+    # create the file missing file
+    create_default_platform_paths_hrh();
+    print "Missing file $platformpathspath created succesfully.\n";    
+}
+
+
+# check if CORE_IBY_EXPORT_PATH macro exist in the platform_paths.hrh
+unless (string_exists_in_file($platformpathspath, "CORE_IBY_EXPORT_PATH"))
+{
+    # read content of the platform_paths.hrh
+    my @filecontent = read_file_to_array($platformpathspath);  
+
+    my $match_found = 0;
+    my $i = 0;
+    my $match_found_pos = 0;
+    
+    # find the position where the include guards start (this should be a safe position)
+    foreach (@filecontent)
+    {
+        if ($_ =~ /#define PLATFORM_PATHS_HRH/)
+        {
+            $match_found = 1;
+            $match_found_pos = $i;
+            last;
+        } 
+
+        $i++;
+    }
+    
+    if ($match_found)
+    {
+        # insert the patched content to the file
+        splice(@filecontent, $match_found_pos+1, 0, $coreibyexportsupport);
+        
+        # write the modified array to the file
+        write_file_from_array($platformpathspath, @filecontent);
+    
+        print "Platform_paths.hrh updated to support CORE_IBY_EXPORT_PATH macro.\n";
+    }
+    else
+    {
+        print "WARNING: $platformpathspath is corrupted or not supported!\n";    
+    }
+}
+ 
+    
+# check if epoc32\tools\mmp.pm exists
+if (-e $mmppmpath)
+{
+    # check if DEPENDS keyword already exists in the file
+    if (string_exists_in_file($mmppmpath, "DEPENDS"))
+    {
+        print "The SDK can already handle DEPENDS keyword in a MMP file.\n";        
+    }
+    else
+    {
+        # read content of the mmp.pm file
+        my @filecontent = read_file_to_array($mmppmpath);
+        
+        my $match_found = 0;
+        my $i = 0;
+        my $match_found_pos = 0;
+        
+        # loop through the array to find the correct place
+        foreach (@filecontent)
+        {
+            if ($_ =~ /Unrecognised Resource Keyword/)
+            {
+                $match_found = 1;
+                $match_found_pos = $i;
+                last;
+            } 
+
+            $i++;
+        }
+        
+        if ($match_found)
+        {
+            # insert the patched content to the file
+            splice(@filecontent, $match_found_pos-1, 0, $dependshack);
+            
+            # write the modified array to the file
+            write_file_from_array($mmppmpath, @filecontent);
+        
+            print "Mmp.pm patched with DEPENDS keyword hack.\n";
+        }
+        else
+        {
+            print "ERROR: Unable to find correct place from $mmppmpath for patching!\n";
+            print "Your SDK environment probably is not supported by this script!\n";
+            exit(2);    
+        }
+    }
+
+    # check if SMPSAFE keyword already exists in the file
+    if (string_exists_in_file($mmppmpath, "SMPSAFE"))
+    {
+        print "The SDK can already handle SMPSAFE keyword in a MMP file.\n";        
+    }
+    else
+    {
+        # read content of the mmp.pm file
+        my @filecontent = read_file_to_array($mmppmpath);
+        
+        my $match_found = 0;
+        my $i = 0;
+        my $match_found_pos = 0;
+        
+        # loop through the array to find the correct place
+        foreach (@filecontent)
+        {
+            if ($_ =~ /Unrecognised Keyword/)
+            {
+                $match_found = 1;
+                $match_found_pos = $i;
+                last;
+            } 
+
+            $i++;
+        }
+        
+        if ($match_found)
+        {
+            # insert the patched content to the file
+            splice(@filecontent, $match_found_pos, 0, $smpsafehack);
+            
+            # write the modified array to the file
+            write_file_from_array($mmppmpath, @filecontent);
+        
+            print "Mmp.pm patched with SMPSAFE keyword hack.\n";
+        }
+        else
+        {
+            print "ERROR: Unable to find correct place from $mmppmpath for patching!\n";
+            print "Your SDK environment probably is not supported by this script!\n";
+            exit(2);    
+        }
+    }
+}
+else
+{
+    print "WARNING: $mmppmpath not found, this environment is not supported!\n";
+}
+
+
+# check if epoc32\tools\pathutl.pm exists
+if (-e $pathutlpmpath)
+{
+    # check if "sub Path_Norm" already exists in the pathutil.pm file
+    # if it does not exists, then we need to patch prepfile.pm
+    if (string_exists_in_file($pathutlpmpath, "sub Path_Norm"))
+    {
+        print "The SDK is non Symbian OS 9.1, no need to add forward slash hack.\n";        
+    }
+    else
+    {
+        # check if prepfile.pm has already been patched
+        if (string_exists_in_file($prepfilepmpath, "EnvPatcher forwardslash hack"))
+        {        
+            print "The SDK has already been patched with forwardslash hack.\n";         
+        }
+        else
+        {    
+            # read content of the prepfile.pm file
+            my @filecontent = read_file_to_array($prepfilepmpath);  
+    
+            my $match_found = 0;
+            my $i = 0;
+            my $match_found_pos = 0;
+            
+            # loop through the array to find the correct place
+            foreach (@filecontent)
+            {
+                if ($_ =~ /# skip blank lines/)
+                {
+                    $match_found = 1;
+                    $match_found_pos = $i;
+                    last;
+                } 
+    
+                $i++;
+            }
+            
+            if ($match_found)
+            {
+                # insert the patched content to the file
+                splice(@filecontent, $match_found_pos+6, 0, $forwardslashhack);
+                
+                # write the modified array to the file
+                write_file_from_array($prepfilepmpath, @filecontent);
+            
+                print "Prepfile.pm patched with forward slash hack.\n";
+            }
+            else
+            {
+                print "ERROR: Unable to find correct place from $prepfilepmpath for patching!\n";
+                print "Your SDK environment probably is not supported by this script!\n";
+                exit(2);    
+            }
+        }
+    }    
+}
+else
+{
+    print "WARNING: $pathutlpmpath not found, this environment is not supported!\n";
+}
+ 
+ 
+ 
+# checks if string exists in the file    
+sub string_exists_in_file
+{
+    my $filepath = $_[0];
+    my $findstring = $_[1];
+    my $match_found = 0;     
+
+    open(FILE, "<", $filepath) or die "Failed to open $filepath for reading!";
+
+    # loop through the file for occurances
+    while (<FILE>)
+    {
+        if ($_ =~ /$findstring/)
+        {
+            $match_found = 1;
+            last;
+        } 
+    }
+
+    close FILE;
+    
+    return $match_found;
+}
+
+
+# reads lines from a file to an array    
+sub read_file_to_array
+{
+    my $filepath = $_[0];
+
+    open(FILE, "<", $filepath) or die "Failed to open $filepath for reading!";
+    my @data = <FILE>;
+    close FILE;
+    
+    return(@data);
+}
+
+
+# writes lines from an array to a file
+sub write_file_from_array
+{
+    my ($filepath, @data) = @_;
+    
+    # take a backup of the file
+    copy ($filepath, $filepath."EnvPatcher") or die "Cannot take backup of $filepath to $filepath.EnvPatcher";
+        
+    open(FILE, ">", $filepath) or die "Failed to open $filepath for writing!";
+
+    # write the array to file
+    foreach my $line (@data)
+    {
+        print FILE "$line";
+    }
+
+    close FILE;
+}
+
+sub create_default_platform_paths_hrh
+{
+    # the file does not exist, so create the missing file
+    open(FILE, ">", $platformpathspath) or die "Failed to open $platformpathspath for writing!\n";
+    
+    print FILE <<ENDOFTHEFILE;
+#ifndef PLATFORM_PATHS_HRH
+#define PLATFORM_PATHS_HRH
+
+/**
+* ---------------------------------------
+* Location, where the applications layer specific public headers should be exported
+* See usage on top of this hrh-file.
+* ---------------------------------------
+*/
+#define APP_LAYER_SDK_EXPORT_PATH(exported) /epoc32/include/##exported
+#define APP_LAYER_PUBLIC_EXPORT_PATH(exported) /epoc32/include/##exported
+
+/**
+* ---------------------------------------
+* Location, where the applications layer specific platform headers should be exported
+* See usage on top of this hrh-file.
+* ---------------------------------------
+*/
+#define APP_LAYER_DOMAIN_EXPORT_PATH(exported) /epoc32/include/##exported
+#define APP_LAYER_PLATFORM_EXPORT_PATH(exported) /epoc32/include/##exported
+
+/**
+* ---------------------------------------
+* Location, where the middleware layer specific public headers should be exported
+* See usage on top of this hrh-file.
+* ---------------------------------------
+*/
+#define MW_LAYER_SDK_EXPORT_PATH(exported) /epoc32/include/##exported
+#define MW_LAYER_PUBLIC_EXPORT_PATH(exported) /epoc32/include/##exported
+
+/**
+* ---------------------------------------
+* Location, where the middleware layer specific platform headers should be exported
+* ---------------------------------------
+*/
+#define MW_LAYER_DOMAIN_EXPORT_PATH(exported) /epoc32/include/##exported
+#define MW_LAYER_PLATFORM_EXPORT_PATH(exported) /epoc32/include/##exported
+
+/**
+* ---------------------------------------
+* Location, where the os layer specific public headers should be exported
+* ---------------------------------------
+*/
+#define  OSEXT_LAYER_SDK_EXPORT_PATH(exported) /epoc32/include/##exported
+#define  OS_LAYER_PUBLIC_EXPORT_PATH(exported) /epoc32/include/##exported
+
+/**
+* ---------------------------------------
+* Location, where the os specific platform headers should be exported
+* ---------------------------------------
+*/
+#define OSEXT_LAYER_DOMAIN_EXPORT_PATH(exported) /epoc32/include/##exported
+#define OS_LAYER_PLATFORM_EXPORT_PATH(exported) /epoc32/include/##exported
+
+/**
+* ---------------------------------------
+* Location, where the  cenrep excel sheets should be exported
+* Deprecated: should no longer be used. Kept for compability.
+* ---------------------------------------
+*/
+#define CENREP_XLS_EXPORT_PATH(exported) /epoc32/tools/cenrep/data/src/##exported
+
+/**
+* This define statements defines the SYSTEMINCLUDE-line, which is intended to be 
+* used in the mmp-files that are part of the applications-layer. It includes all 
+* the needed directories from the /epoc32/include, that are valid ones for the 
+* application-layer components. 
+*
+* Applications layer is the last one in the list, since most likely the most of 
+* the headers come from middleware or os-layer  => thus they are first.
+*/
+#define APP_LAYER_SYSTEMINCLUDE SYSTEMINCLUDE /epoc32/include /epoc32/include/oem
+ 
+/**
+* This define statements defines the SYSTEMINCLUDE-line, which is intended to be
+* used in the mmp-files that are part of the middleware-layer. It includes all 
+* the needed directories from the /epoc32/include, that are valid ones for the 
+* middleware-layer components. 
+*/
+#define MW_LAYER_SYSTEMINCLUDE SYSTEMINCLUDE /epoc32/include /epoc32/include/oem
+
+/**
+* This define statements defines the SYSTEMINCLUDE-line, which is intended to be
+* used in the mmp-files that are part of the  osextensions-layer. It includes all
+* the needed directories from the /epoc32/include, that are valid ones for the
+* os-layer components. 
+*/
+#define OS_LAYER_SYSTEMINCLUDE SYSTEMINCLUDE /epoc32/include /epoc32/include/oem
+
+
+// Below statement is Deprecated and the OS_LAYER_SYSTEMINCLUDE-macro has to be
+// used.
+#define OSEXT_LAYER_SYSTEMINCLUDE OS_LAYER_SYSTEMINCLUDE
+
+/**
+* This define statements defines the SYSTEMINCLUDE-line, which is intended to be
+* used in the mmp-files that are part of the os-layer. This is intended 
+* to be only used by those components which need to use in their mmp-file either
+* kern_ext.mmh or nkern_ext.mmh. Reason is that those
+* 2 files already contain the /epoc32/include  as system include path.
+* 
+*/
+#define OS_LAYER_KERNEL_SYSTEMINCLUDE SYSTEMINCLUDE /epoc32/include/oem
+
+
+// Below statement is Deprecated and the OS_LAYER_KERNEL_SYSTEMINCLUDE-macro 
+// has to be used.
+#define OSEXT_LAYER_KERNEL_SYSTEMINCLUDE OS_LAYER_KERNEL_SYSTEMINCLUDE
+
+/**
+****************************************************************************
+* Definitions that also define the paths to the layer specific source directories.
+****************************************************************************
+*/
+/**
+* The below 3 macros define the paths to the layer-specific source dirs.
+* See usage on top of this hrh-file, these are used the same way as 
+* for instance the OS_LAYER_DOMAIN_EXPORT_PATH
+* Deprecated: is not allowed to be using in Symbian Foundation
+*/
+#define APP_LAYER_SOURCE_PATH(rest)    /s60/app/##rest
+#define MW_LAYER_SOURCE_PATH(rest)     /s60/mw/##rest
+#define OSEXT_LAYER_SOURCE_PATH(rest)  /s60/osext/##rest
+
+/**
+****************************************************************************
+* Definitions to export IBY files to different folders where they will be taken 
+* to ROM image
+****************************************************************************
+*/
+// Following definition is used for exporting tools and stubs IBY files to 
+// Core image.
+#define CORE_IBY_EXPORT_PATH(path,exported)  /epoc32/rom/include/##exported
+
+/**
+* ---------------------------------------
+* Macros for Configuration tool migration. 
+* The below macros define the location under epoc32, where the confml 
+* (Configuration Markup Language) and crml (Central Repository Markup Language) 
+* files should be exported.
+* ---------------------------------------
+*/
+#define CONFML_EXPORT_PATH(file,category)           /epoc32/rom/config/confml_data/##category##/##file
+#define CRML_EXPORT_PATH(file,category)             /epoc32/rom/config/confml_data/##category##/##file
+#define GCFML_EXPORT_PATH(file,category)            /epoc32/rom/config/confml_data/##category##/##file
+#define CONFML_CONFIG_EXPORT_PATH(file,category)    /epoc32/rom/config/confml_data/##category##/config/##file
+
+#define APP_LAYER_CONFML(exported) 	                CONFML_EXPORT_PATH(exported,s60)
+#define APP_LAYER_CRML(exported)                    CRML_EXPORT_PATH(exported,s60)
+#define APP_LAYER_GCFML(exported)                   GCFML_EXPORT_PATH(exported,s60)
+#define APP_LAYER_CONFML_CONFIG(exported)           CONFML_CONFIG_EXPORT_PATH(exported,s60)
+                                                    
+#define MW_LAYER_CONFML(exported)                   CONFML_EXPORT_PATH(exported,s60)
+#define MW_LAYER_CRML(exported)                     CRML_EXPORT_PATH(exported,s60)
+#define MW_LAYER_GCFML(exported)                    GCFML_EXPORT_PATH(exported,s60)
+#define MW_LAYER_CONFML_CONFIG(exported)            CONFML_CONFIG_EXPORT_PATH(exported,s60)
+       
+// Deprecate: Use the OS_LAYER_* macros instead of OSEXT_LAYER_*                                             
+#define OSEXT_LAYER_CONFML(exported)                CONFML_EXPORT_PATH(exported,s60)
+#define OSEXT_LAYER_CRML(exported)                  CRML_EXPORT_PATH(exported,s60)
+#define OSEXT_LAYER_GCFML(exported)                 GCFML_EXPORT_PATH(exported,s60)
+#define OSEXT_LAYER_CONFML_CONFIG(exported)         CONFML_CONFIG_EXPORT_PATH(exported,s60)
+#define OS_LAYER_CONFML(exported)                   CONFML_EXPORT_PATH(exported,s60)
+#define OS_LAYER_CRML(exported)                     CRML_EXPORT_PATH(exported,s60)
+#define OS_LAYER_GCFML(exported)                    GCFML_EXPORT_PATH(exported,s60)
+#define OS_LAYER_CONFML_CONFIG(exported)            CONFML_CONFIG_EXPORT_PATH(exported,s60)
+
+#endif  // end of PLATFORM_PATHS_HRH
+
+ENDOFTHEFILE
+
+    close FILE;    
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/envpatcher/ReadMe.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+Environment Patcher v1.0.1
+==========================
+
+Updated: 12th November 2009
+
+
+Introduction:
+-------------
+This tool can be used to patch your S60 SDK environment so that the tricks and
+macros introduced in the latest SDKs can be used in a public SDK and older
+OEM releases.
+
+This tool can perform the following tasks:
+- Adds support for forward slashes in paths in bld.inf/.mmp files in S60 3.0 
+- Removes an unncessary warning about DEPENDS and SMPSAFE resource keywords in
+  an .mmp file
+- Creates a missing epoc32\include\platform_paths.hrh file for supporting
+  platform macros introduced since S60 3.2 OEM and Symbian Foundation releases
+- Modifies epoc32\include\platform_paths.hrh for missing macros   
+- Creates a missing epoc32\include\oem directory to suppress a possible warning
+
+
+Usage:
+------
+EnvPatcher.pl <EPOCROOT>
+
+Where EPOCROOT is the path to the root of the SDK, for example:
+  EnvPatcher.pl c:\Symbian\9.1\S60_3rd_MR
+  EnvPatcher.pl z:\
+
+
+Requirements:
+-------------
+- S60 SDK (public or OEM), version 3.0 or newer
+- Perl 5.6.1 or newer
+
+
+
+
+Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+All rights reserved.
+
+This component and the accompanying materials are made available
+under the terms of "Eclipse Public License v1.0"
+which accompanies this distribution, and is available
+at the URL "http://www.eclipse.org/legal/epl-v10.html".
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/STIFTestMeasurementStub/Bmarm/STIFTESTMEASUREMENTSTUBU.DEF	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	LibEntryL__FRC7TDesC16Q220CSTIFTestMeasurement20TSTIFMeasurementType @ 1 NONAME R3UNUSED ; LibEntryL(TDesC16 const &, CSTIFTestMeasurement::TSTIFMeasurementType)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/STIFTestMeasurementStub/Bwins/STIFTestMeasurementStubu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	?LibEntryL@@YAPAVCSTIFTestMeasurementImplementation@@ABVTDesC16@@W4TSTIFMeasurementType@CSTIFTestMeasurement@@@Z @ 1 NONAME ; class CSTIFTestMeasurementImplementation * __cdecl LibEntryL(class TDesC16 const &,enum CSTIFTestMeasurement::TSTIFMeasurementType)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/STIFTestMeasurementStub/eabi/STIFTestMeasurementStubu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,3 @@
+EXPORTS
+	_Z9LibEntryLRK7TDesC16N20CSTIFTestMeasurement20TSTIFMeasurementTypeE @ 1 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/STIFTestMeasurementStub/group/STIFTestMeasurementStub.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,72 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's TestMeasurement 
+* stub module.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET          STIFTestMeasurementStub.dll
+TARGETTYPE      dll
+UID             0x1000008D 0x101FB3E7
+
+
+CAPABILITY      ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+//TARGETPATH      ?target_path
+DEFFILE         STIFTestMeasurementStub.def
+
+USERINCLUDE     ../inc 
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          STIFTestMeasurementStub.cpp
+
+//RESOURCE        resource_file
+//RESOURCE        resource_file2
+
+LIBRARY         euser.lib
+
+LANG            SC
+
+/*
+START WINS      
+?wins_specific_information
+END
+
+START MARM
+?marm_specific_information
+END
+*/
+// Other possible keywords:
+ 
+// DOCUMENT     ?file, that is not compiled, but added to MSVC project workspace (i.e. release notes)
+/*
+START BITMAP ?target
+TARGETPATH   ?emulated_path_on_target_machine
+HEADER
+SOURCE       ?color_depth ?source_bitmap
+END
+*/
+// DEFFILE ?filename
+// AIF ?filename// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/STIFTestMeasurementStub/group/STIFTestMeasurementStub_DoxyFile.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,238 @@
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+#
+# Contributors:
+# 
+# Description:
+#
+#
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+PROJECT_NAME           = STIFTestMeasurementStub
+PROJECT_NUMBER         = 
+OUTPUT_DIRECTORY       = w:\STIFTestMeasurementStub\
+CREATE_SUBDIRS         = NO
+OUTPUT_LANGUAGE        = English
+USE_WINDOWS_ENCODING   = YES
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       = 
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = NO
+STRIP_FROM_PATH        = 
+STRIP_FROM_INC_PATH    = 
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = NO
+MULTILINE_CPP_IS_BRIEF = NO
+DETAILS_AT_TOP         = NO
+INHERIT_DOCS           = YES
+DISTRIBUTE_GROUP_DOC   = NO
+TAB_SIZE               = 8
+ALIASES                = 
+OPTIMIZE_OUTPUT_FOR_C  = YES
+OPTIMIZE_OUTPUT_JAVA   = NO
+SUBGROUPING            = YES
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = YES
+EXTRACT_PRIVATE        = NO
+EXTRACT_STATIC         = NO
+EXTRACT_LOCAL_CLASSES  = NO
+EXTRACT_LOCAL_METHODS  = NO
+HIDE_UNDOC_MEMBERS     = NO
+HIDE_UNDOC_CLASSES     = NO
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = YES
+CASE_SENSE_NAMES       = YES
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_BY_SCOPE_NAME     = NO
+GENERATE_TODOLIST      = NO
+GENERATE_TESTLIST      = NO
+GENERATE_BUGLIST       = NO
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       = 
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_DIRECTORIES       = YES
+FILE_VERSION_FILTER    = 
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           = 
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  = w:\STIFTestMeasurementStub\
+FILE_PATTERNS          = *.h \
+                         *.rh \
+                         *.hrh
+RECURSIVE              = YES
+EXCLUDE                = 
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       = 
+EXAMPLE_PATH           = 
+EXAMPLE_PATTERNS       = 
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             = 
+INPUT_FILTER           = 
+FILTER_PATTERNS        = 
+FILTER_SOURCE_FILES    = NO
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = NO
+INLINE_SOURCES         = NO
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = YES
+REFERENCES_RELATION    = YES
+VERBATIM_HEADERS       = YES
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = NO
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          = 
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = NO
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            = 
+HTML_FOOTER            = 
+HTML_STYLESHEET        = 
+HTML_ALIGN_MEMBERS     = YES
+GENERATE_HTMLHELP      = YES
+CHM_FILE               = 
+HHC_LOCATION           = 
+GENERATE_CHI           = NO
+BINARY_TOC             = YES
+TOC_EXPAND             = YES
+DISABLE_INDEX          = YES
+ENUM_VALUES_PER_LINE   = 4
+GENERATE_TREEVIEW      = YES
+TREEVIEW_WIDTH         = 250
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = NO
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4wide
+EXTRA_PACKAGES         = 
+LATEX_HEADER           = 
+PDF_HYPERLINKS         = NO
+USE_PDFLATEX           = NO
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = YES
+RTF_OUTPUT             = Doc
+COMPACT_RTF            = YES
+RTF_HYPERLINKS         = YES
+RTF_STYLESHEET_FILE    = 
+RTF_EXTENSIONS_FILE    = 
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_SCHEMA             = 
+XML_DTD                = 
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX = 
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor   
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = YES
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           = 
+INCLUDE_FILE_PATTERNS  = 
+PREDEFINED             = NONSHARABLE_CLASS
+EXPAND_AS_DEFINED      = 
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references   
+#---------------------------------------------------------------------------
+TAGFILES               = 
+GENERATE_TAGFILE       = 
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool   
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = YES
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = NO
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+TEMPLATE_RELATIONS     = YES
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+DOT_PATH               = 
+DOTFILE_DIRS           = 
+MAX_DOT_GRAPH_WIDTH    = 1024
+MAX_DOT_GRAPH_HEIGHT   = 1024
+MAX_DOT_GRAPH_DEPTH    = 0
+DOT_TRANSPARENT        = NO
+DOT_MULTI_TARGETS      = NO
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to the search engine   
+#---------------------------------------------------------------------------
+SEARCHENGINE           = NO
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/STIFTestMeasurementStub/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+PRJ_PLATFORMS
+
+	DEFAULT
+
+PRJ_TESTEXPORTS
+
+PRJ_EXPORTS
+
+PRJ_TESTMMPFILES
+
+PRJ_MMPFILES
+
+	STIFTestMeasurementStub.mmp
+
+//  End of File
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/STIFTestMeasurementStub/inc/STIFTestMeasurementStub.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,156 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIF measurement stub module declaration
+*
+*/
+
+#ifndef STIFTESTMEASUREMENTSTUB_H
+#define STIFTESTMEASUREMENTSTUB_H
+
+// INCLUDES
+#include <f32file.h>
+#include <StifTestInterface.h>
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// FUNCTION PROTOTYPES
+//?type ?function_name(?arg_list);
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// DATA TYPES
+//enum ?declaration
+//typedef ?declaration
+//extern ?data_type;
+
+// CLASS DECLARATION
+
+/**
+*  This a CSTIFTestMeasurementStub stub class for Test Measurement Module
+*  Pluging.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS( CSTIFTestMeasurementStub ) : 
+                                public CSTIFTestMeasurementImplementation
+    {
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CSTIFTestMeasurementStub* NewL( 
+                const TDesC& aConfigurationInfo,
+                CSTIFTestMeasurement::TSTIFMeasurementType aMeasurementType );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CSTIFTestMeasurementStub();
+
+    public: // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * From CSTIFTestMeasurementStub Start
+        * @since ?Series60_version
+        * @return Symbian OS error code
+        */
+        virtual TInt Start();
+
+        /**
+        * From CSTIFTestMeasurementStub Start
+        * @since ?Series60_version
+        * @return Symbian OS error code
+        */
+        virtual TInt Stop();
+
+        /**
+        * From CSTIFTestMeasurementStub Start
+        * @since ?Series60_version
+        * @return CSTIFTestMeasurement::TSTIFMeasurementType
+        */
+        virtual CSTIFTestMeasurement::TSTIFMeasurementType MeasurementType();
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CSTIFTestMeasurementStub(
+            CSTIFTestMeasurement::TSTIFMeasurementType aMeasurementType );
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL( const TDesC& aConfigurationInfo );
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+
+        // Test Measurement module type
+        CSTIFTestMeasurement::TSTIFMeasurementType iMeasurementType;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+#endif      // STIFTESTMEASUREMENTSTUB_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/STIFTestMeasurementStub/src/STIFTestMeasurementStub.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,182 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains testmeasurementstub declaration.
+*
+*/
+
+// INCLUDE FILES
+#include "STIFTestMeasurementStub.h"
+
+// EXTERNAL DATA STRUCTURES
+//extern  ?external_data;
+
+// EXTERNAL FUNCTION PROTOTYPES  
+//extern ?external_function( ?arg_type,?arg_type );
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// LOCAL CONSTANTS AND MACROS
+//const ?type ?constant_var = ?constant;
+//#define ?macro_name ?macro_def
+
+// MODULE DATA STRUCTURES
+//enum ?declaration
+//typedef ?declaration
+
+// LOCAL FUNCTION PROTOTYPES
+//?type ?function_name( ?arg_type, ?arg_type );
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// ============================= LOCAL FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// ?function_name ?description.
+// ?description
+// Returns: ?value_1: ?description
+//          ?value_n: ?description_line1
+//                    ?description_line2
+// -----------------------------------------------------------------------------
+//
+/*
+?type ?function_name(
+    ?arg_type arg,  // ?description
+    ?arg_type arg)  // ?description
+    {
+
+    ?code  // ?comment
+
+    // ?comment
+    ?code
+    }
+*/
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// CSTIFTestMeasurementStub::CSTIFTestMeasurementStub
+// C++ default constructor can NOT contain any code, that
+// might leave.
+// -----------------------------------------------------------------------------
+//
+CSTIFTestMeasurementStub::CSTIFTestMeasurementStub( 
+            CSTIFTestMeasurement::TSTIFMeasurementType aMeasurementType ):
+    iMeasurementType( aMeasurementType )
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSTIFTestMeasurementStub::ConstructL
+// Symbian 2nd phase constructor can leave.
+// -----------------------------------------------------------------------------
+//
+void CSTIFTestMeasurementStub::ConstructL( const TDesC& aConfigurationInfo )
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSTIFTestMeasurementStub::NewL
+// Two-phased constructor.
+// -----------------------------------------------------------------------------
+//
+CSTIFTestMeasurementStub* CSTIFTestMeasurementStub::NewL(
+                    const TDesC& aConfigurationInfo,
+                    CSTIFTestMeasurement::TSTIFMeasurementType aMeasurementType )
+    {
+    CSTIFTestMeasurementStub* self = new (ELeave) CSTIFTestMeasurementStub( 
+                                                            aMeasurementType );
+
+    CleanupStack::PushL( self );
+    self->ConstructL( aConfigurationInfo );
+    CleanupStack::Pop();
+
+    return self;
+
+    }
+
+// Destructor
+// -----------------------------------------------------------------------------
+// CSTIFTestMeasurementStub::~CSTIFTestMeasurementStub
+// Destructor.
+// -----------------------------------------------------------------------------
+//
+CSTIFTestMeasurementStub::~CSTIFTestMeasurementStub()
+    {
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSTIFTestMeasurementStub::Start
+// Starts test measurement
+// Returns Symbian error code
+// -----------------------------------------------------------------------------
+//
+TInt CSTIFTestMeasurementStub::Start( )
+    {
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSTIFTestMeasurementStub::Stop
+// Stops test measurement
+// Returns Symbian error code
+// -----------------------------------------------------------------------------
+//
+TInt CSTIFTestMeasurementStub::Stop( )
+    {
+    return KErrNone;
+
+    }
+
+// -----------------------------------------------------------------------------
+// CSTIFTestMeasurementStub::MeasurementType
+// 
+// Returns measurement module's type
+// -----------------------------------------------------------------------------
+//
+CSTIFTestMeasurement::TSTIFMeasurementType CSTIFTestMeasurementStub::MeasurementType( )
+    {
+    return iMeasurementType;
+
+    }
+
+// ========================== OTHER EXPORTED FUNCTIONS =========================
+
+// -----------------------------------------------------------------------------
+// LibEntryL is a polymorphic Dll entry point
+// Returns: CSTIFTestMeasurementImplementation*: Pointer to STIF Test 
+// Measurement Module
+// object
+// -----------------------------------------------------------------------------
+//
+EXPORT_C CSTIFTestMeasurementImplementation* LibEntryL( 
+                const TDesC& aConfigurationInfo,
+                CSTIFTestMeasurement::TSTIFMeasurementType aMeasurementType )
+    {
+    CSTIFTestMeasurementImplementation* measurement;
+    measurement = CSTIFTestMeasurementStub::NewL( 
+                                        aConfigurationInfo, aMeasurementType );
+    return measurement;
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/StifHWResetStub/BMARM/STIFHWRESETSTUBU.DEF	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	LibEntryL__Fv @ 1 NONAME R3UNUSED ; LibEntryL(void)
+	NewL__16CStifHWResetStub @ 2 NONAME R3UNUSED ; CStifHWResetStub::NewL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/StifHWResetStub/BWINS/StifHWResetStubu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	?LibEntryL@@YAPAVCStifHWResetStub@@XZ @ 1 NONAME ; class CStifHWResetStub * __cdecl LibEntryL(void)
+	?NewL@CStifHWResetStub@@SAPAV1@XZ @ 2 NONAME ; public: static class CStifHWResetStub * __cdecl CStifHWResetStub::NewL(void)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/StifHWResetStub/eabi/StifHWResetStubu.def	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,4 @@
+EXPORTS
+	_Z9LibEntryLv @ 1 NONAME
+	_ZN16CStifHWResetStub4NewLEv @ 2 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/StifHWResetStub/group/StifHWResetStub.mmp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: MMP file for STIF Test Framework's StifHWResetStub.
+*
+*/
+
+#include <platform_paths.hrh>
+
+SMPSAFE
+
+TARGET      StifHWResetStub.dll
+TARGETTYPE  dll
+DEFFILE     StifHWResetStub.def
+
+CAPABILITY	ALL -TCB
+/* Remove comments and replace 0x00000000 with correct vendor id */
+// VENDORID     0x00000000
+/* Remove comments and replace 0x00000000 with correct secure id */
+// SECUREID     0x00000000
+
+LIBRARY     euser.lib
+LIBRARY     stiftestinterface.lib
+
+USERINCLUDE     ../inc 
+USERINCLUDE     ../../../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+SOURCEPATH      ../src
+
+SOURCE          StifHWResetStub.cpp
+
+// First UID is DLL UID, Second UID is STIF Test Framework UID
+UID             0x1000008D 0x101FB3E7
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/StifHWResetStub/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	Build information for STIF Test Framework's StifHWResetStub.
+*/
+
+
+PRJ_PLATFORMS
+
+	DEFAULT
+
+PRJ_EXPORTS
+
+
+PRJ_TESTEXPORTS
+
+
+PRJ_MMPFILES
+	
+	StifHWResetStub.mmp
+
+PRJ_TESTMMPFILES
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/StifHWResetStub/inc/StifHWResetStub.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,130 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of 
+* CStifHWResetStub of STIF TestFramework.
+*
+*/
+
+#ifndef STIFHWRESETSTUB_H
+#define STIFHWRESETSTUB_H
+
+// INCLUDES
+#include <StifHWReset.h>
+#include <StifLogger.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+// None
+
+// DESCRIPTION
+// Implements common reset module for STIF TestFramework. According to this DLL
+// template can be implemented licensee specific reset module.
+NONSHARABLE_CLASS(CStifHWResetStub) 
+        :public CStifHWReset
+    {
+    public:     // Enumerations
+    	// None
+
+    private:    // Enumerations
+    	// None
+
+    public:     // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CStifHWResetStub* NewL();
+        
+        /**
+        * Destructor.
+        */
+        ~CStifHWResetStub();
+
+    public:     // New functions
+        
+        /**
+        * Does reset according to reset type.
+        */
+        TInt DoReset( CTestModuleIf::TRebootType aResetType );
+        
+    public:     // Functions from base classes
+    	// None
+       
+    protected:  // New functions
+    	// None
+    	
+    protected:  // Functions from base classes
+        // None
+    	
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CStifHWResetStub();
+
+        /**
+        * Symbian OS constructor.
+        */
+        void ConstructL();        
+
+        /**
+        * Kills process. Example method.
+        */
+        TInt KillProcess();
+
+        /**
+        * General reset. Example method.
+        */
+        TInt GeneralReset();
+
+	public:     // Data
+	    // None
+
+	protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Logger instance
+        CStifLogger*            iLogger;
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+    	
+    };
+
+#endif // STIFHWRESETSTUB_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/examples/StifHWResetStub/src/StifHWResetStub.cpp	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,325 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: Implements common reset module for STIF 
+* TestFramework. According to this DLL template can be implemented 
+* licensee specific reset module.
+*
+*/
+
+// INCLUDE FILES
+#include "StifHWResetStub.h"
+
+// EXTERNAL DATA STRUCTURES
+// None
+
+// EXTERNAL FUNCTION PROTOTYPES  
+// None
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// LOCAL CONSTANTS AND MACROS
+// None
+
+// MODULE DATA STRUCTURES
+// None
+
+// LOCAL FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// ==================== LOCAL FUNCTIONS =======================================
+
+// ================= MEMBER FUNCTIONS =========================================
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifHWResetStub
+
+    Method: CStifHWResetStub
+
+    Description: Default constructor.
+    
+    Parameters:    None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+CStifHWResetStub::CStifHWResetStub()
+    {
+    // None
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifHWResetStub
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor. Nothing to do.
+
+    Parameters:    None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+    
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+void CStifHWResetStub::ConstructL()
+    {
+    // Create Logger
+    iLogger = CStifLogger::NewL( _L( "C:\\logs\\testframework\\testengine\\"),
+                                    _L( "StifHWResetStub" ),
+                                        CStifLogger::ETxt,
+                                        CStifLogger::EFile,
+                                        EFalse, // Append
+                                        ETrue,
+                                        ETrue,
+                                        EFalse,
+                                        EFalse );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifHWResetStub
+
+    Method: NewL
+
+    Description: Two-phased constructor. Constructs new CStifHWResetStub
+                 instance and returns pointer to it.
+        
+    Parameters: None
+
+    Return Values: CStifHWResetStub*: new object.
+
+    Errors/Exceptions: Leaves if memory allocation fails or ConstructL leaves.
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifHWResetStub* CStifHWResetStub::NewL()
+    {
+    // Construct new CStifHWResetStub instance.
+    CStifHWResetStub* self = new ( ELeave ) CStifHWResetStub();    
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop();
+
+    return self;
+  
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifHWResetStub
+
+    Method: ~CStifHWResetStub
+
+    Description: Destructor.
+    
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/    
+CStifHWResetStub::~CStifHWResetStub()
+    {
+    delete iLogger;
+    iLogger = NULL;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifHWResetStub
+
+    Method: DoReset
+
+    Description: Does reset according to reset type.
+    
+    Parameters: CTestModuleIf::TRebootType aResetType: in: Reset type
+
+    Return Values: TInt: Symbian OS error
+
+    Errors/Exceptions: Error code returned if reset method returns an error.
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/    
+TInt CStifHWResetStub::DoReset( CTestModuleIf::TRebootType aResetType )
+    {
+    iLogger->Log( _L( "CStifHWResetStub::DoReset(), reset type: %d" ), aResetType );
+    TInt ret( KErrNone );
+
+    switch( aResetType )
+        {
+        case CTestModuleIf::EDefaultReset:
+            {
+            ret = KillProcess(); // For an example
+            break;
+            }
+        case CTestModuleIf::EDeviceReset0:
+            {
+            ret = KillProcess(); // For an example
+            break;
+            }
+        case CTestModuleIf::EDeviceReset1:
+            {
+            ret = KillProcess(); // For an example
+            break;
+            }
+        case CTestModuleIf::EDeviceReset2:
+            {
+            ret = GeneralReset(); // Do nothing, for an example
+            break;
+            }
+        case CTestModuleIf::EDeviceReset3:
+            {
+            ret = GeneralReset(); // Do nothing, for an example
+            break;
+            }
+        case CTestModuleIf::EDeviceReset4:
+            {
+            ret = GeneralReset(); // Do nothing, for an example
+            break;
+            }
+        case CTestModuleIf::EDeviceReset5:
+            {
+            ret = GeneralReset(); // Do nothing, for an example
+            break;
+            }
+        default:
+            {
+            return KErrArgument;
+            }
+        }
+
+    return ret;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifHWResetStub
+
+    Method: KillProcess
+
+    Description: Kills process
+    
+    Parameters: None
+
+    Return Values: TInt: Symbian OS error
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/    
+TInt CStifHWResetStub::KillProcess()
+    {
+    iLogger->Log( _L( "KillProcess()" ) );
+    // Do process kill if MTC messages not allowed
+    RProcess thisProcess;
+    thisProcess.Kill( KErrNone );
+    thisProcess.Close();
+
+    return KErrNone;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CStifHWResetStub
+
+    Method: GeneralReset
+
+    Description: General reset for example.
+    
+    Parameters: None
+
+    Return Values: TInt: Symbian OS error
+
+    Errors/Exceptions: None
+
+    Status: Proposal
+    
+-------------------------------------------------------------------------------
+*/    
+TInt CStifHWResetStub::GeneralReset()
+    {
+    // Lisencee specific reset
+    iLogger->Log( _L( "GeneralReset()" ) );
+    return KErrNone;
+
+    }
+
+// ================= OTHER EXPORTED FUNCTIONS =================================
+
+/*
+-------------------------------------------------------------------------------
+   
+    Function: LibEntryL
+
+    Description: Polymorphic Dll Entry Point
+    
+    Test framework calls this function to obtain new instance of test module
+    class. 
+
+    Parameters:    None
+    
+    Return Values: CStifHWResetStub* Pointer to CStifHWResetStub instance
+    
+    Errors/Exceptions: Leaves if CStifHWResetStub::NewL leaves
+    
+    Status: Proposal
+
+-------------------------------------------------------------------------------
+*/
+EXPORT_C CStifHWResetStub* LibEntryL()
+    {
+    return CStifHWResetStub::NewL();
+
+    }
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/group/ReleaseNote.txt	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,63 @@
+========================================================================
+RELEASE NOTE FOR STIF - STIF_201024 (7.3.35)
+SUPPORTING SERIES 60 3.0 ->
+========================================================================
+
+Product Description:
+====================
+STIF is a test harness for testing Symbian & S60 non-UI components.
+This widely used test framework can be used for both test case implementation and test cases execution.
+
+Features :
+=========
+- Test module implements test cases
+- Error and exception handling
+- Concurrent test case execution
+- Test Module Template Wizard (createtestmodule.BAT)
+- Memory leak detection
+- File parsing with STIF Parser
+- Logging facilities for test modules with STIF Logger
+- Scripted test cases with Test Scripter
+- Test case synchronization with STIF Event System
+- Test case combining with Test Combiner
+- Write once, test everywhere, e.g. test cases made during the development phase can be used in system testing, automatic release testing, etc.
+- Easy to use
+- Multiple test cases can be executed concurrently.
+- All execution errors and exceptions are handled properly and reported to tester.
+- Excellent support for test automation.
+- Symbian OS 9.1 features supported (Platform Security)
+- Releases bi-weekly
+- Heap and stack configuring
+- OOM test support
+- Test Interference support
+- S60\Symbian UI component test case implementation support
+
+
+Enhancements:
+=============
+N/A
+
+
+New Features:
+=============
+S60\Symbian UI component test case implementation support 
+
+
+System Requirements:
+====================
+Basic Requirements:
+- S60/Symbian OS development environment installed
+
+
+Compatibility Issues:
+=====================
+N/A
+
+Known Issues:
+===========
+If problems with compilation appears (missing platform_paths.hrh file error message), 
+please use EnvPatcher.pl script from stif/envpatcher folder to fix environment. 
+
+
+Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+All rights reserved.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/group/TestFramework.ini	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,217 @@
+#
+# This is STIF initialization file
+# Comment lines start with '#'-character.
+# See STIF TestFramework users guide.doc for instructions
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+# Set following test engine settings:
+#	- Set Test Reporting mode. TestReportMode's possible values are:
+#		+ 'Summary': Summary of the tested test cases.
+#		+ 'Environment': Hardware and software info.
+#		+ 'TestCases': Test case report.
+#		+ 'FullReport': Set of all above ones.
+#		+ Example 'TestReportMode= Summary TestCases'
+#
+# 	- CreateTestReport setting controls report creation mode
+#		+ YES, Test report will created.
+#		+ NO, No Test report.
+#
+# 	- File path indicates the base path of the test report.
+# 	- File name indicates the name of the test report.
+#
+# 	- File format indicates the type of the test report.
+#		+ TXT, Test report file will be txt type, for example 'TestReport.txt'.
+#		+ HTML, Test report will be html type, for example 'TestReport.html'.
+#   + XML, Test report will be xml type, for example 'TestReport.xml'.
+#          Note, that xml format is available only when output is set to FILE.
+#
+# 	- File output indicates output source of the test report.
+#		+ FILE, Test report logging to file.
+#		+ RDEBUG, Test report logging to using rdebug.
+#
+# 	- File Creation Mode indicates test report overwriting if file exist.
+#		+ OVERWRITE, Overwrites if the Test report file exist.
+#		+ APPEND, Continue logging after the old Test report information if
+#                 report exist.
+# 	- Sets a device reset module's dll name(Reboot).
+#		+ If Nokia specific reset module is not available or it is not correct one
+#		  StifHWResetStub module may use as a template for user specific reset
+#		  module.
+# 	- Sets STIF test measurement disable options. e.g. pluging1 and pluging2 disablation
+#		DisableMeasurement= stifmeasurementplugin01 stifmeasurementplugin02
+#
+
+[Engine_Defaults]
+
+TestReportMode= FullReport    # Possible values are: 'Empty', 'Summary', 'Environment',
+                              #                      'TestCases' or 'FullReport'
+
+CreateTestReport= YES         # Possible values: YES or NO
+
+TestReportFilePath= C:\LOGS\TestFramework\
+TestReportFileName= TestReport
+
+TestReportFormat= TXT         # Possible values: TXT, HTML or XML
+TestReportOutput= FILE        # Possible values: FILE or RDEBUG
+TestReportFileCreationMode= OVERWRITE # Possible values: OVERWRITE or APPEND
+
+DeviceResetDllName= StifResetForNokia.dll # e.g. 'StifHWResetStub.dll' for user specific reseting
+
+DisableMeasurement= stifmeasurementdisablenone  # Possible values are:
+              # 'stifmeasurementdisablenone', 'stifmeasurementdisableall'
+              # 'stifmeasurementplugin01', 'stifmeasurementplugin02',
+              # 'stifmeasurementplugin03', 'stifmeasurementplugin04',
+              # 'stifmeasurementplugin05' or 'stifbappeaprofiler'
+
+Timeout= 0                    # Default timeout value for each test case. In milliseconds
+#UITestingSupport= YES        # Possible values: YES or NO
+#SeparateProcesses= YES       # Possible values: YES or NO (default: NO)
+[End_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+# Module configurations start
+# Modules are added between module tags
+# tags. Module name is specified after ModuleName= tag, like
+# ModuleName= XXXXXXXXX
+# Modules might have initialisation file, specified as
+# IniFile= c:\testframework\YYYYYY
+# Modules might have several configuration files, like
+# TestCaseFile= c:\testframework\NormalCases.txt
+# TestCaseFile= c:\testframework\SmokeCases.txt
+# TestCaseFile= c:\testframework\ManualCases.txt
+
+# (TestCaseFile is synonym for old term ConfigFile)
+
+# Following case specifies demo module settings. Demo module
+# does not read any settings from file, so tags 
+# IniFile and TestCaseFile are not used.
+# In the simplest case it is enough to specify only the
+# name of the test module when adding new test module
+
+[New_Module]
+ModuleName= demomodule
+[End_Module]
+
+
+# Load testmoduleXXX, optionally with initialization file and/or test case files
+#[New_Module]
+#ModuleName= testmodulexxx
+
+#TestModuleXXX used initialization file
+#IniFile= c:\testframework\init.txt
+
+#TestModuleXXX used configuration file(s)
+#TestCaseFile= c:\testframework\testcases1.cfg
+#TestCaseFile= c:\testframework\testcases2.cfg
+#TestCaseFile= c:\testframework\manualtestcases.cfg
+
+#[End_Module]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+# Set STIF logging overwrite parameters for Logger.
+# 	Hardware and emulator environment logging path and styles can
+# 	be configured from here to overwrite the Logger's implemented values.
+#	
+#	Settings description:
+#	- Indicates option for creation log directory/directories. If log directory/directories
+#         is/are not created by user they will make by software.
+#		+ YES, Create log directory/directories if not allready exist.
+#		+ NO, Log directory/directories not created. Only created one is used.
+#
+#	- Overwrite emulator path setting.
+#		+ Example: If 'EmulatorBasePath= C:\LOGS\TestFramework\' and in code is defined 
+#		           Logger's path 'D:\\LOGS\\Module\\' with those definition the path
+#		           will be 'C:\LOGS\TestFramework\LOGS\Module\'
+#
+#	- Overwrite emulator's logging format.
+#		+ TXT, Log file(s) will be txt type(s), for example 'Module.txt'.
+#		+ HTML, Log file(s) will be html type(s), for example 'Module.html'.
+#
+#	- Overwrited emulator logging output source.
+#		+ FILE, Logging to file(s).
+#		+ RDEBUG, Logging to using rdebug(s).
+#
+#	- Overwrite hardware path setting (Same description as above in emulator path).
+#	- Overwrite hardware's logging format(Same description as above in emulator format).
+#	- Overwrite hardware's logging output source(Same description as above in emulator output).
+#
+#	- File Creation Mode indicates file overwriting if file exist.
+#		+ OVERWRITE, Overwrites if file(s) exist.
+#		+ APPEND, Continue logging after the old logging information if file(s) exist.
+#
+#	- Will thread id include to the log filename.
+#		+ YES, Thread id to log file(s) name, Example filename 'Module_b9.txt'.
+#		+ NO, No thread id to log file(s), Example filename 'Module.txt'.
+#
+#	- Will time stamps include the to log file.
+#		+ YES, Time stamp added to each line in log file(s). Time stamp is 
+#                 for example'12.Nov.2003 115958    LOGGING INFO'
+#		+ NO, No time stamp(s).
+#
+#	- Will line breaks include to the log file.
+#		+ YES, Each logging event includes line break and next log event is in own line.
+#		+ NO, No line break(s).
+#
+#	- Will event ranking include to the log file.
+#		+ YES, Event ranking number added to each line in log file(s). Ranking number
+#                 depends on environment's tics, for example(includes time stamp also)
+#                 '012   12.Nov.2003 115958    LOGGING INFO'
+#		+ NO, No event ranking.
+#
+#	- Will write log file in unicode format.
+#		+ YES, Log file will be written in unicode format
+#		+ NO, Log will be written as normal, not unicode, file.
+#
+
+[Logger_Defaults]
+
+#NOTE: If you want to set Logger using next setting(s) remove comment(s)'#'
+#NOTE: TestEngine and TestServer logging settings cannot change here
+
+#CreateLogDirectories= YES    # Possible values: YES or NO
+
+#EmulatorBasePath= C:\LOGS\TestFramework\
+#EmulatorFormat= HTML         # Possible values: TXT or HTML
+#EmulatorOutput= FILE         # Possible values: FILE or RDEBUG
+
+#HardwareBasePath= D:\LOGS\TestFramework\
+#HardwareFormat= HTML         # Possible values: TXT or HTML
+#HardwareOutput= FILE         # Possible values: FILE or RDEBUG
+
+#FileCreationMode= OVERWRITE  # Possible values: OVERWRITE or APPEND
+
+#ThreadIdToLogFile= YES       # Possible values: YES or NO
+#WithTimeStamp= YES           # Possible values: YES or NO
+#WithLineBreak= YES           # Possible values: YES or NO
+#WithEventRanking= YES        # Possible values: YES or NO
+
+#FileUnicode= YES             # Possible values: YES or NO
+#AddTestCaseTitle= YES        # Possible values: YES or NO
+[End_Logger_Defaults]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+
+
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+# Set filters to be used by ConsoleUI.
+# 	If you want to use filter with ConsoleUI, simply remove comments
+# 	from section below and provide valid filter entries.
+#   Each filter line has to start with "filter= " keyword.
+#   Filter can contain special wildcard characters:
+#     *  which stands for none or any literal;
+#     ?  which stands for single character.
+#   Filters are not case-sensitive.
+
+#[Filters]
+#filter= *math*
+#filter= *radio*
+#[End_Filters]
+# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
+
+# End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,89 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*	bld.inf Toplevel build information for STIF Test Framework
+*/
+
+#include <platform_paths.hrh>
+
+
+PRJ_PLATFORMS
+
+	DEFAULT
+
+
+PRJ_EXPORTS
+
+	TestFramework.ini +/wins/c/TestFramework/TestFramework.ini
+	TestFramework.ini +/winscw/c/TestFramework/TestFramework.ini
+	TestFramework.ini +/data/z/system/data/TestFramework.ini
+	
+	// This is added in order to export iby files automaticly in 5.0 env
+	../rom/Stif.iby     CORE_IBY_EXPORT_PATH(tools,Stif.iby) 
+	
+	../rom/Stif_rom.iby CORE_IBY_EXPORT_PATH(tools/rom,Stif_rom.iby)
+	
+	:zip ../TestModuleTemplates/TestModuleTemplates.zip +/tools/s60rndtools/stif
+	
+PRJ_TESTEXPORTS
+	
+PRJ_MMPFILES	
+
+	// Stif API
+	#include "../stif_plat/group/bld.inf"
+
+	// Test Interface
+	#include "../TestInterface/group/bld.inf"
+	
+	// Test Server
+	#include "../TestServer/group/bld.inf"
+	
+	// Test Engine
+	#include "../TestEngine/group/bld.inf"
+	
+	// Test Server Starter
+	#include "../TestServerStarter/group/bld.inf"
+	
+	// StifTFwIf
+	#include "../StifTFwIf/group/bld.inf"
+	
+	// Console UI
+	#include "../ConsoleUI/group/bld.inf"
+
+	// Test Combiner
+	#include "../TestCombiner/group/bld.inf"
+	
+	// Demomodule
+	#include "../DemoModule/group/bld.inf"
+	
+	// ATS logger
+	#include "../ATSLogger/group/bld.inf"
+	
+	// ATS interface
+	#include "../ATSInterface/group/bld.inf"
+	
+	// Test Scripter
+	#include "../TestScripter/group/bld.inf"
+	
+	// SU Event
+	#include "../SUEvent/group/bld.inf"
+	
+	#if defined(__S60_)
+		// StifKernelTestClassBase
+		#include "../StifKernelTestClassBase/group/bld.inf"
+	#endif // __S60_
+
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/STIFConfiguration.mmh	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+#ifndef STIFCONFIGURATION_MMH
+#define STIFCONFIGURATION_MMH
+
+// MMP's header file for macro definitions.
+
+/**
+* STIF's TestEngine and TestServer logs to c:\logs\testframework\testengine
+* and c:\logs\testframework\testserver directories. These logging can be changed
+* to log RDebug with next macro. If uncommenting this macro STIFTestFramework
+* reallyclean and compile is needed (from \STIFTestFramework\group\bld.inf).
+*/
+//MACRO FORCE_STIF_INTERNAL_LOGGING_TO_RDEBUG
+
+
+#endif      // STIFCONFIGURATION_MMH
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/STIFMeasurement.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,67 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: StifMeasurement plugin names declaration
+*
+*/
+
+#ifndef STIF_MEASUREMENT_H
+#define STIF_MEASUREMENT_H
+
+// INCLUDES
+#include <e32base.h>
+
+// Maximum length of measurement types(see literals below)
+const TInt KStifMeasurementTypeLength = 30; 
+
+/**
+* Literals for measurement types.
+*/
+_LIT( KStifMeasurementEnableAll, "stifmeasurementenableall" );
+_LIT( KStifMeasurementDisableAll, "stifmeasurementdisableall" );
+_LIT( KStifMeasurement01, "stifmeasurementplugin01" );
+_LIT( KStifMeasurement02, "stifmeasurementplugin02" );
+_LIT( KStifMeasurement03, "stifmeasurementplugin03" );
+_LIT( KStifMeasurement04, "stifmeasurementplugin04" );
+_LIT( KStifMeasurement05, "stifmeasurementplugin05" );
+_LIT( KStifMeasurementBappea, "stifbappeaprofiler" );
+// Next is used in testframework.ini file
+_LIT( KStifMeasurementDisableNone, "stifmeasurementdisablenone" );
+
+
+// Measurement module types definition(used in keyword's parameters)
+_LIT( KParamMeasurement01, "measurementplugin01" );
+_LIT( KParamMeasurement02, "measurementplugin02" );
+_LIT( KParamMeasurement03, "measurementplugin03" );
+_LIT( KParamMeasurement04, "measurementplugin04" );
+_LIT( KParamMeasurement05, "measurementplugin05" );
+_LIT( KParamMeasurementBappea, "stifbappeaprofiler" );
+
+/**
+* Enumeration for measurement disable and enable.
+*/
+enum TDisableMeasurement
+    {
+    EDisableAll     = 0xFFFFFFFF,   // Disable all measurement, 1111
+    EEnableAll      = ~EDisableAll, // This allowes all measurements, 0000
+    EMeasurement01  = 1<<0,         // User specific measurement
+    EMeasurement02  = 1<<1,         // User specific measurement
+    EMeasurement03  = 1<<2,         // User specific measurement
+    EMeasurement04  = 1<<3,         // User specific measurement
+    EMeasurement05  = 1<<4,         // User specific measurement
+    EBappea         = 1<<25,        // Disable bappea measurement
+    };
+
+#endif // STIF_MEASUREMENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/StifKernelTestClass.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: Kernel test class for STIF Test Framework TestScripter
+*
+*/
+
+
+#ifndef STIFKERNELTESTCLASS_H
+#define STIFKERNELTESTCLASS_H
+
+// INCLUDES
+
+#include <e32cmn.h>
+
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+typedef TBuf8<0x80>  TMethodResultDes;
+typedef TBuf8<0x20>  TMethodName;
+typedef TBuf8<0x100> TMethodParams;
+
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+class TStifRunMethodInfo
+    {
+    public:
+        TStifRunMethodInfo() : 
+            iResult( 0 )
+            {
+            iMethodName.Zero();
+            iMethodParams.Zero();
+            iMethodResultDes.Zero();
+            }
+    
+    public:
+        TMethodName         iMethodName;
+        TMethodParams       iMethodParams;
+        TMethodResultDes    iMethodResultDes;
+        TInt                iResult;
+        
+    };
+
+// CLASS DECLARATION
+
+/**
+*  RStifKernelTestClass kernel test class for STIF Test Framework TestScripter.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class RStifKernelTestClass : public RBusLogicalChannel
+    {
+    public:
+        // Synchronous operations
+        enum TStifKernelTCOperation
+            { 
+            ERunMethod = 1,                       
+            };
+    
+        // Version number
+        enum TStifKernelTCVersion
+            {
+            EMajorVersionNumber=1,
+            EMinorVersionNumber=0,
+            EBuildVersionNumber=1
+            };
+
+    public: // Interface functions
+
+          // Open
+          inline TInt Open( const TVersion& aVer, const TDesC& aDriverName );
+
+          // Return required version
+          inline TVersion VersionRequired() const;
+          
+          // Run specific method
+          
+        
+          inline TInt RunMethod( const TDesC8&  aMethodName,
+                                 const TDesC8&  aParams,
+                                 TInt&          aResult,
+                                 TDes8&         aResultDes );
+ 
+    };
+    
+// Include inline function implementations
+#include "StifKernelTestClass.inl"
+
+#endif      // STIFKERNELTESTCLASS_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/StifKernelTestClass.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,79 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+
+#ifndef STIFKERNELTESTCLASS_INL
+#define STIFKERNELTESTCLASS_INL
+
+// ============================ MEMBER FUNCTIONS ===============================
+
+// -----------------------------------------------------------------------------
+// RStifKernelTestClass::Open
+// Open driver.
+// -----------------------------------------------------------------------------
+//
+TInt RStifKernelTestClass::Open( const TVersion& aVer, const TDesC& aDriverName )
+    {       
+    return DoCreate( aDriverName, aVer, KNullUnit, NULL, NULL );    
+    }
+
+// -----------------------------------------------------------------------------
+// RStifKernelTestClass::VersionRequired
+// Get version info.
+// -----------------------------------------------------------------------------
+//
+TVersion RStifKernelTestClass::VersionRequired() const
+    {
+    return TVersion( EMajorVersionNumber, EMinorVersionNumber, EBuildVersionNumber );
+    }
+    
+// -----------------------------------------------------------------------------
+// RStifKernelTestClass::RunMethod
+// DoControl call to the kernel side for test case execution
+// -----------------------------------------------------------------------------
+//
+                                    
+TInt RStifKernelTestClass::RunMethod( const TDesC8&  aMethodName,
+                                      const TDesC8&  aMethodParams,
+                                      TInt&          aResult,
+                                      TDes8&         aResultDes )                                   
+    {      
+    TStifRunMethodInfo methodInfo;
+    if( ( aMethodName.Length() > methodInfo.iMethodName.MaxLength() ) ||
+        ( aMethodParams.Length() > methodInfo.iMethodParams.MaxLength() ) ) 
+        {
+        return KErrArgument;
+        }
+    methodInfo.iMethodName.Copy( aMethodName );
+    methodInfo.iMethodParams.Copy( aMethodParams );
+    
+    TPckg<TStifRunMethodInfo> methodInfoPckg( methodInfo );
+    TInt ret = DoControl( ERunMethod, ( TAny* )&methodInfoPckg );
+    
+    if( ret != KErrNone )
+        {
+        return ret;
+        }
+    
+    aResult = methodInfo.iResult;
+    aResultDes.Copy( methodInfo.iMethodResultDes.Left( aResultDes.MaxLength() ) );
+    return KErrNone;
+    }
+
+#endif      // STIFKERNELTESTCLASS_INL
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/StifPython.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header of additional functions 
+* needed for Python support and used in PythonScripter, TestEngine 
+* and TestCombiner.
+*
+*/
+
+#ifndef STIFPYTHON_H
+#define STIFPYTHON_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+_LIT(KPythonScripter, "pythonscripter");
+const TInt KPythonScripterLength = 14;
+
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+// None
+
+#endif        // STIFPYTHON_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/StifTFw.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,190 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CStifTFw.
+*
+*/
+
+#ifndef STIF_TFW_H
+#define STIF_TFW_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifLogger.h>
+#include <StifTestInterface.h>
+#include <stifinternal/UIEngine.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CUIEngineContainer;
+class CUIEngineEvent;
+class CStifTFwIf;
+
+// CLASS DECLARATION
+
+// CStifTFw is the sub class of STIF Test Framework Interface
+class CStifTFw
+    :public CUIIf
+    {
+    public: // Enumerations
+
+    protected: // Enumerations
+        
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+         /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CStifTFw* NewL( CStifTFwIf* aStifTFwIf );
+
+        /**
+        * Destructor.
+        */
+        virtual ~CStifTFw();
+        
+    public: 
+
+    protected: // Functions that can be called from derived class
+
+    protected: // Functions that the derived class may implement.
+ 
+    private:
+
+        /**
+        * Constructor.
+        */
+        CStifTFw( CStifTFwIf* aStifTFwIf );
+
+        /**
+        * Second phase constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Test case executed.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C void TestExecuted( CUIEngineContainer* aContainer, 
+                                    TFullTestResult& aFullTestResult );
+        /**
+        * Progress information from Test case execution.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt PrintProg ( CUIEngineContainer* aContainer,
+                                  TTestProgress& aProgress );
+
+        /**
+        * Forward message to ATS.
+        */                            
+        IMPORT_C TInt RemoteMsg( CUIEngineContainer* aContainer,
+                                 const TDesC& /*aMessage*/ );
+                                 
+        /**
+        * Forward reboot indication to ATS.
+        */                            
+        IMPORT_C TInt GoingToReboot( CUIEngineContainer* aContainer,
+                                     TRequestStatus& aStatus );
+ 
+        /**
+        * Initialize logger from UI engine.
+        */
+        void InitializeLogger( CStifLogger* aLogger ){ iLogger = aLogger; }
+
+        /**
+        * Remote ATS call
+        */
+        TInt AtsRemote( CStifTFwIfProt& aReq, CStifTFwIfProt& aResp );
+
+        /**
+        * Remote ATS run call
+        */
+        TInt AtsRemoteRun( CStifTFwIfProt& aReq, CStifTFwIfProt& aResp );
+
+        /**
+        * Remote ATS test control call
+        */
+        TInt AtsRemoteTestCtl( CStifTFwIfProt& aReq, CStifTFwIfProt& aResp );
+
+        /**
+        * Remote ATS event system control call
+        */
+        TInt AtsRemoteEventCtl( CStifTFwIfProt& aReq, CStifTFwIfProt& aResp );
+        
+        /**
+        * Delete data in class
+        */
+        void DeleteData();
+
+        /**
+        * Enumerates test cases from given module and finds test case index by title
+        */
+        TInt GetCaseNumByTitle(TDesC& aModule, TDesC& aTestCaseFile, TDesC& aTitle, TInt& aCaseNum);
+
+    public: // Data
+        /**
+        * Logger created by UI engine.
+        */ 
+        CStifLogger* iLogger;
+        
+    protected: // Data
+        
+    private: // Data
+        /**
+        * Pointer to UI engine.
+        */ 
+        CUIEngine* iUIEngine;
+        
+        /**
+        * Pointer to CStifTfwIf
+        */ 
+        CStifTFwIf* iStifTFwIf;
+
+        // Execute test case table
+        RPointerArray<CUIEngineContainer>      iTestExecutionTable;
+
+        // Remote execute test case table
+        RPointerArray<CUIEngineContainer>      iTestRemoteExecutionTable;
+
+        // Remote execute test case table
+        RPointerArray<CUIEngineEvent>          iEventArray;
+        
+        // Array of master identifiers that have reserved the slave
+        RArray<TUint32>                        iMasterArray;
+
+    public: // Friend classes
+        // None
+        
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        friend class CStifTFwIf;
+
+    };
+
+#endif      // STIF_TFW_H 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/TestModuleInfo.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,292 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CTestModuleInfo class. The class was created to keep module names, 
+* ini files and test case configuration files.
+*
+*/
+
+#ifndef TESTMODULEINFO_H
+#define TESTMODULEINFO_H
+
+//  INCLUDES
+#include <e32base.h>
+#include <StifLogger.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Class with information about configuration (test case) file.
+class CTestCaseFileInfo
+    :public CBase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * NewL.
+        */
+        static CTestCaseFileInfo* NewL(TDesC& aCfgFileName, CStifLogger* aLogger);
+
+        /**
+        * C++ destructor.
+        */
+        virtual ~CTestCaseFileInfo();
+
+    private: // Constructors and destructor
+        /**
+        * C++ constructor.
+        */
+        CTestCaseFileInfo();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL(TDesC& aCfgFileName, CStifLogger* aLogger);
+
+    public: // New functions
+        /**
+        * Set configuration file as already checked.
+        */
+        IMPORT_C void SetChecked(void);
+
+        /**
+        * Return if config file has been checked.
+        */
+        TBool IsChecked(void);
+
+        /**
+        * Get module name.
+        */
+        IMPORT_C TInt GetCfgFileName(TDes& aCfgFileName);
+
+    protected:  // New functions
+
+    private:    // New functions
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+        //Config file name
+        HBufC* iCfgFileName;
+
+        //Was checked
+        TBool iChecked;
+
+        // Logger instance
+        CStifLogger* iLogger;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+    };
+
+// DESCRIPTION
+// Class with information about test modules.
+class CTestModuleInfo
+    :public CBase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * NewL.
+        */
+        static CTestModuleInfo* NewL(TDesC& aModuleName, CStifLogger* aLogger);
+
+        /**
+        * C++ destructor.
+        */
+        virtual ~CTestModuleInfo();
+
+    private: // Constructors and destructor
+        /**
+        * C++ constructor.
+        */
+        CTestModuleInfo();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL(TDesC& aModuleName, CStifLogger* aLogger);
+
+    public: // New functions
+        /**
+        * Set initialization file name.
+        */
+        IMPORT_C TInt SetIniFile(TDesC& aIniFileName);
+
+        /**
+        * Add configuration (test case) file name to array.
+        */
+        IMPORT_C TInt AddCfgFile(TDesC& aCfgFileName);
+
+        /**
+        * Get number of test case files.
+        */
+        IMPORT_C TInt CountCfgFiles(void);
+
+        /**
+        * Get module name.
+        */
+        IMPORT_C TInt GetModuleName(TDes& aModuleName);
+
+        /**
+        * Get ini file.
+        */
+        IMPORT_C TInt GetIniFileName(TDes& aIniFileName);
+
+        /**
+        * Get cfg file.
+        */
+        IMPORT_C TInt GetCfgFileName(TInt aIndex, TDes& aCfgFileName);
+
+        /**
+        * Get first unchecked config file.
+        */
+        CTestCaseFileInfo* GetUncheckedCfgFile(void);
+
+    protected:  // New functions
+
+    private:    // New functions
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+        //Module name
+        HBufC* iModuleName;
+
+        //Initialization file
+        HBufC* iIniFileName;
+
+        //Array of cfg files
+        RPointerArray<CTestCaseFileInfo> iCfgFiles;
+
+        // Logger instance
+        CStifLogger* iLogger;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+    };
+
+// DESCRIPTION
+// Class with list of test modules.
+class CTestModuleList
+    :public CBase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        /**
+        * NewL.
+        */
+        IMPORT_C static CTestModuleList* NewL(CStifLogger* aLogger);
+
+        /**
+        * C++ destructor.
+        */
+        IMPORT_C virtual ~CTestModuleList();
+
+    private: // Constructors and destructor
+        /**
+        * C++ constructor.
+        */
+        CTestModuleList();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL(CStifLogger* aLogger);
+
+    public: // New functions
+        /**
+        * Add test module to list.
+        */
+        IMPORT_C TInt AddTestModule(TDesC& aModuleName);
+
+        /**
+        * Get number of test modules.
+        */
+        IMPORT_C TInt Count(void);
+
+        /**
+        * Get module.
+        */
+        IMPORT_C CTestModuleInfo* GetModule(TDesC& aModuleName);
+
+        /**
+        * Get module.
+        */
+        IMPORT_C CTestModuleInfo* GetModule(TInt aIndex);
+
+        /**
+        * Get first unchecked test case file (module: testscripter and testcombiner).
+        */
+        IMPORT_C CTestCaseFileInfo* GetUncheckedCfgFile(void);
+
+    protected:  // New functions
+
+    private:    // New functions
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+        //Array of test modules
+        RPointerArray<CTestModuleInfo> iTestModules;
+
+        // Logger instance
+        CStifLogger* iLogger;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+    };
+
+#endif      // TESTMODULEINFO_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/TestServerModuleIf.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,693 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CTestExecution.
+*
+*/
+
+#ifndef TEST_SERVER_MODULE_IF_H
+#define TEST_SERVER_MODULE_IF_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifTestModule.h>
+#include <StifTestInterface.h>
+#include "StifTFwIfProt.h"
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+typedef CSTIFTestMeasurementImplementation*( 
+        *CTestMeasurementFactory )( const TDesC&,
+                                    CSTIFTestMeasurement::TSTIFMeasurementType );
+
+// FORWARD DECLARATIONS
+class TEvent;
+class CTestModule;
+class CTestModuleContainer;
+class CPrintQueue;
+class CPrintHandler;
+class CEventHandler;
+class CSndHandler;
+class CRcvHandler;
+class CErrorPrintHandler;
+class CInterferenceHandler;
+class CMeasurementHandler;
+class CCommandHandler;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TCmdDef represents remote command
+class TCmdDef
+    {
+    public:
+        TStifCommand    iCommand;
+        TParams         iParam;
+        TInt            iLen;
+        TRequestStatus* iStatus;
+    };
+
+// TCommandDef represents command
+class TCommandDef
+    {
+    public:
+        TCommand                       iCommand;
+        TBuf8<KMaxCommandParamsLength2> iParamsPckg;
+    };
+    
+// DESCRIPTION
+// CCommandDef represents command
+class CCommandDef : public CBase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+        
+    public:  // Constructors and destructor
+    		static CCommandDef* NewL();
+        	~CCommandDef();
+
+    private:  // Constructors and destructor
+    		CCommandDef();
+        	void ConstructL();
+
+    public: // New functions
+          
+    public: // Functions from base classes
+        
+    protected:  // New functions
+        
+    protected:  // Functions from base classes
+        
+    private:
+        
+    public:		//Data
+            TCommand iCommand;
+            TBuf8<KMaxCommandParamsLength2> iParamsPckg;
+        
+    protected:  // Data
+        
+    private:    // Data
+        
+    public:     // Friend classes
+        
+    protected:  // Friend classes
+        
+    private:    // Friend classes
+        
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TCmdDef represents remote command
+class TEventDef
+    {
+    public:
+        enum TEventCmdType
+            {
+            EEventCmd,
+            EEventCmdCancel,
+            };
+    // Added constructor to TEventDef @js
+        TEventDef():iStatus(NULL){};
+            
+    public:
+        TEventCmdType   iType;
+        TEventIf        iEvent;
+        TRequestStatus* iStatus;
+    };
+
+// DESCRIPTION
+// TTestInterference represents remote command
+class TTestInterference 
+    {
+    public:
+        enum TOperation
+            {
+            EAppend,
+            ERemove,
+            };
+    public:
+        TTestInterference(){};
+    public:
+        // Thread id.
+        TUint iThreadId;
+        // Is operations append or remove.
+        TOperation iOperation;
+    };
+
+// DESCRIPTION
+// TTestMeasurement contains measurement related information
+// transfering between TestInterface and TestServer.
+class TTestMeasurement 
+    {
+    public:
+        TTestMeasurement(){};
+    public:
+        // Struct for information.
+        CSTIFTestMeasurement::TStifMeasurementStruct iMeasurementStruct;
+
+    };
+
+// DESCRIPTION
+// TMeasurementHandling keeps information for measurement module
+// dynamic loading, types, etc.
+class TMeasurementHandling 
+    {
+    public:
+        TMeasurementHandling() : iMeasurement( NULL ),
+                                 iMeasurementModulePtr( NULL ){};
+
+        ~TMeasurementHandling()
+            { 
+            delete iMeasurement;
+            delete iMeasurementModulePtr;
+            // After close test measurement's pointer is not valid anymore.
+            if ( iMeasurementModule.Handle() )
+                { 
+                iMeasurementModule.Close(); 
+                }
+            };
+    public:
+        RLibrary iMeasurementModule;
+        CTestMeasurementFactory iMeasurementLibEntry;
+        CSTIFTestMeasurementImplementation* iMeasurement;
+        CSTIFTestMeasurement::TSTIFMeasurementType iMeasurementType;
+        CSTIFTestMeasurementImplementation* iMeasurementModulePtr;
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestExecution represents a subsession object in the CTestServer.
+// A session may own any number of CTestExecution objects
+class CTestExecution
+        :public CObject
+    {
+
+    public: // Enumerations
+        enum TTestState
+            {
+            ENotStarted,
+            EOnGoing,
+            EFinished,
+            ECancelled,
+            };
+        
+        enum TRequestType
+            {
+            ERqPrint,
+            ERqEvent,
+            ERqSnd,
+            ERqRcv,
+            ERqInterference,
+            ERqMeasurement,
+            ERqCommand,
+            };
+
+        enum TTestThreadFailure
+            {
+            ETestThreadOk       = 0,
+            ETestMemLeak        = 0x00000001,
+            ETestRequestLeak    = 0x00000002,
+            ETestHandleLeak     = 0x00000004,
+            };
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestExecution* NewL( CTestModule* aModuleSession, 
+                                     TInt aCaseNumber, 
+                                     const TFileName& aConfig
+                                   );
+
+        /**
+        * Destructor
+        */
+        virtual ~CTestExecution();
+
+    public: // New functions
+
+        /**
+        * Close Test Execution
+        */
+        TInt CloseTestExecution( const RMessage2& aMessage );
+
+        /**
+        * Run a test case
+        */
+        TInt RunTestCase( const RMessage2& aMessage );
+
+        /**
+        * Sets a print notification
+        */
+        TInt NotifyPrint( const RMessage2& aMessage );
+
+        /**
+        * Sets a event notification
+        */
+        TInt NotifyEvent( const RMessage2& aMessage );
+
+        /**
+        * Sets a RemoteCmd notification
+        */
+        TInt NotifyRemoteCmd( const RMessage2& aMessage );
+
+        /**
+        * Reads a RemoteCmd notification
+        */
+        TInt ReadRemoteCmdInfo( const RMessage2& aMessage );
+
+        /**
+        * Resumes a paused test case
+        */
+        TInt Resume( const RMessage2& aMessage );
+
+        /**
+        * Pauses ongoing test case
+        */
+        TInt Pause( const RMessage2& aMessage );
+
+
+        /**
+        * Cancels asynchronous request
+        */
+        TInt CancelRequestL( const RMessage2& aMessage );
+
+
+        /**
+        * Completes a print request. 
+        */
+        void DoNotifyPrint();
+
+        /**
+        * Completes a interference request. 
+        */
+        void DoNotifyInterference();
+
+        /**
+        * Completes a measurement request. 
+        */
+        TInt DoNotifyMeasurement();
+
+        /**
+        * Completes a print request. 
+        */
+        void DoErrorPrint();
+
+        /**
+        * Enables remote command receiving. 
+        */
+        void DoRemoteReceive();
+
+        /**
+        * Sends remote commands. 
+        */
+        void DoRemoteSend();
+        
+        /**
+        * Completes a event request. 
+        */
+        TInt DoNotifyEvent();
+
+        /**
+        * Completes a event cancel request. 
+        */
+        void CancelEvent();
+        
+        /** 
+        * Set thread State. 
+        * This function can be called from test execution thread.
+        */
+        void SetThreadState( const TTestState aState );
+        
+        /**
+        * Completes print request if print queue is empty
+        */
+        void CompletePrintRequestIfQueueEmpty();
+
+        /**
+        * Completes print request if print queue is empty
+        */
+        void CleanupEvents();
+
+        /**
+        * Completes test execution
+        */
+        void CompleteTestExecution( const TInt aCompletionCode, 
+                                    const TFullTestResult::TCaseExecutionResult aCaseExecutionType,
+                                    const TInt aCaseExecutionCode,
+                                    const TInt aCaseResult,
+                                    const TDesC& aText );
+
+        /**
+        * Unsets all pending state events.
+        */
+        void UnsetStateEvents();
+
+        /**
+        * Completes test execution
+        */
+        void CompleteTestExecution( const TInt aCompletionCode );
+        
+        /**
+        * Current thread state.
+        */
+        TTestState ThreadState(){ return iThreadState; }
+
+        /**
+        * Cancels test(s) execution in special cases e.g. timeout, exit etc.
+        */
+        TInt CancelTestExecution();
+
+        /**
+        * Make sure that any of the test interference thread's won't stay
+        * to run if test case is crashed of test interference object is not
+        * deleted.
+        */
+        TInt KillTestinterferenceThread();
+
+        /**
+        * Make sure that any of the test measurement process's won't stay
+        * to run if test case is crashed of test measurement object is not
+        * deleted.
+        */
+        TInt KillTestMeasurement();
+
+        /**
+        * Executes command for ongoing test case.
+        * Created to allow test case to kill itself.
+        */
+        TInt NotifyCommand(const RMessage2& aMessage);
+
+        /**
+        * Completes a command request.
+        * Created to allow test case to kill itself.
+        */
+        TInt DoNotifyCommand();
+
+        /**
+        * Cancels command request.
+        * Created to allow test case to kill itself.
+        */
+        TInt CancelCommandRequest();
+
+        /**
+         * Get test case arguments.
+         */
+        const TDesC& GetTestCaseArguments() const;
+
+    public: // Functions that are called from test thread
+
+        /**
+        * Get mutex handles.
+        */
+        TInt EventMutexHandle(){ return iEventMutex.Handle(); };
+        TInt SndMutexHandle(){ return iSndMutex.Handle(); };
+        TInt RcvMutexHandle(){ return iRcvMutex.Handle(); };
+        TInt PrintMutexHandle(){ return iPrintMutex.Handle(); };
+        TInt InterferenceMutexHandle(){ return iInterferenceMutex.Handle(); };
+        TInt MeasurementMutexHandle(){ return iMeasurementMutex.Handle(); };
+        TInt CommandMutexHandle(){ return iCommandMutex.Handle(); };
+
+        /**
+        * Get semaphore handles.
+        */
+        TInt EventSemHandle(){ return iEventSem.Handle(); };
+        TInt SndSemHandle(){ return iSndSem.Handle(); };
+        TInt RcvSemHandle(){ return iRcvSem.Handle(); };
+        //TInt ReceiverSemHandle(){ return iReceiverSem.Handle(); };
+        TInt PrintSemHandle(){ return iPrintSem.Handle(); };
+        TInt InterferenceSemHandle(){ return iInterferenceSem.Handle(); };
+        TInt MeasurementSemHandle(){ return iMeasurementSem.Handle(); };
+        TInt CommandSemHandle(){ return iCommandSem.Handle(); };
+
+        /**
+        * Set execution test thread id.
+        */ 
+        void SetTestThread( TThreadId aThreadId ){ iTestThreadId = aThreadId; };
+
+        /**
+        * Access to "shared" memory.
+        */
+        TFullTestResult& FullResult(){ return iFullResult; };
+        TTestProgress& TestProgress(){ return iProgress; };
+        TEventDef& EventDef(){ return iEventDef; };
+        TCmdDef& SndInfo(){ return iCmdDef; };
+        TCmdDef& RcvInfo(){ return iRcvCmdDef; };
+        TInt& TestThreadFailure(){ return iTestThreadFailure; };
+        TTestInterference& TestInterference(){ return iTestInterference; };
+        TTestMeasurement& TestMeasurement(){ return iTestMeasurement; };
+        CCommandDef& CommandDef(){ return *iCommandDef; };
+
+        /**
+        * Get specific TRequestStatus variable.
+        */
+        TRequestStatus* GetRq( TRequestType aType );
+
+        /**
+        * Get mutex handle.
+        * This mutex meaning is to make sure that test complete and test
+        * case cancel operations are not executed at the same time.
+        */
+        TInt TestThreadMutexHandle() { return iTestThreadMutex.Handle(); };
+
+        const TDesC& GetConfigFileName() const { return iConfig; }
+    public: // Functions from base classes
+        // None
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CTestExecution(); 
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CTestModule* aModuleSession,
+                         TInt aCaseNumber,
+                         const TFileName& aConfig );
+
+        /**
+        * Cancels print request.
+        */
+        TInt CancelPrintRequest();
+
+        /**
+        * Cancels test interference request.
+        */
+        TInt CancelInterferenceRequest();
+
+        /**
+        * Cancels test execution request
+        */
+        TInt CancelTestRequest();
+
+        /**
+        * Cancel event request.
+        */
+        TInt CancelEventRequest();
+
+        /**
+        * Cancel event request.
+        */
+        TInt CancelRemoteCmdRequest();
+
+        /**
+        * Writes a print notification to client memory space.
+        */
+        TInt WritePrint( TTestProgress& aProgress );
+
+        /**
+        * Complete event TRequestStatus if pending. 
+        */
+        void CompleteEvent( TInt aError );
+
+        /**
+        * Handle event unsets. 
+        */
+        TInt UnsetEvent( TEventIf& aEvent, const RMessage2& aMessage );
+
+        /**
+        * Handle event request. 
+        */
+        TInt RequestEvent( TEventIf& aEvent );
+
+        /**
+        * Wait event request. 
+        */
+        TInt WaitEvent( TEventIf& aEvent, TRequestStatus* aStatus );
+
+        /**
+        * Handle event releases. 
+        */
+        TInt ReleaseEvent( TEventIf& aEvent );
+
+        /**
+        * Handle state events. 
+        */
+        TInt EventStateChange( TEventIf& aEvent );
+
+        /**
+        * Complete request in test thread.
+        */
+        void TestThreadRequestComplete( TRequestStatus* aStatus, TInt aCode );
+
+    public:     // Data
+        // None
+    protected:  // Data
+        // None
+
+    private:    // Data
+
+        // Pointers to things around
+        CTestModule* iModuleSession;             // Session owning us
+        CTestModuleContainer* iModuleContainer;  // Container used to execute this case
+
+        // Test execution related members
+        TInt iCaseNumber;                        // Case to be executed
+        TPtr iConfig;                            // Configuration file name
+        HBufC* iConfigNameBuffer;                // HBuffer for configuration file;
+        HBufC* iTestCaseArgs;                    // HBuffer for test case arguments
+		
+        RMessage2 iTestExeMessage;               // Test execution message
+        TTestState iThreadState;                 // Thread state
+
+        // Print related members
+        RMutex          iPrintMutex;             // For iPrintSem semaphore handling
+        RSemaphore      iPrintSem;               // Synchonize print queue access
+        CPrintQueue*    iPrintQueue;             // Print queue
+        RMessage2 iNotifyPrintMessage;           // Print notification message
+        TBool iPrintNotifyAvailable;             // Is print notification available?
+
+        // Event related members
+        RMessage2 iNotifyEventMessage;           // Event nofitication message
+        TBool           iEventNotifyAvailable;   // Is event notification available?
+        RMutex          iEventMutex;             // For iEventSem semaphore handling
+        RSemaphore      iEventSem;               // Signal event request availability
+        TEventDef       iEventDef;
+
+        // Remote command protocol related stuff
+        RMessage2       iNotifyRemoteCmdMessage;// RemoteCmd notication message
+        TBool           iRemoteSendAvailable;    // Is RemoteSend available
+        RMutex          iSndMutex;               // For iSndSem semaphore handling
+        RSemaphore      iSndSem;                 // Signal RemoteCmd request availability
+        TThreadId       iTestThreadId;           // Thread id for receiver 
+        RThread         iTestThread;
+        TBool           iTestThreadOpen;
+        TBool           iRemoteReceiveAvailable; // Is RemoteReceive available
+        RMutex          iRcvMutex;               // For iRcvSem semaphore handling
+        RSemaphore      iRcvSem;                 // Signal RemoteCmd request availability
+        //RSemaphore      iReceiverSem;            // Signal testmodule request availability
+        RPointerArray<HBufC8> iMessageQueue;
+        
+        TCmdDef         iCmdDef;
+        TCmdDef         iRcvCmdDef;  
+        TTestProgress   iProgress;
+                
+
+        // Result with timestamp information
+        TFullTestResult iFullResult;    
+        TInt            iTestThreadFailure;         
+        
+        // Event array        
+        RPointerArray<TEvent>           iEventArray; 
+        // State event array
+        RPointerArray<TDesC>            iStateEvents;  
+        
+        // Event handlers
+        CPrintHandler*          iPrintHandler;
+        CEventHandler*          iEventHandler;
+        CSndHandler*            iSndHandler;
+        CRcvHandler*            iRcvHandler;
+        CInterferenceHandler*   iInterferenceHandler;
+        CMeasurementHandler*    iMeasurementHandler;
+        CCommandHandler*        iCommandHandler;
+        
+        // Test Interface related members
+        RMutex          iInterferenceMutex; // For iInterferenceMutex semaphore handling
+        RSemaphore      iInterferenceSem;   // Synchronize interference queue access
+        TBool           iInterferenceNotifyAvailable; // Is interference notification
+                                                      //available?
+        // Test measurement related members
+        RMutex          iMeasurementMutex;  // For iMeasurementMutex semaphore handling
+        RSemaphore      iMeasurementSem;    // Synchronize measurement queue access
+        TBool           iMeasurementNotifyAvailable; // Is measurement notification
+                                                      //available?
+        RMessage2 iNotifyInterferenceMessage; // Interference notification message
+
+        TTestInterference   iTestInterference; // Struct for information
+        // Array for handling test interference thread's kill in
+        // panic etc. cases
+        RArray<RThread>  iSTIFTestInterferenceArray;
+
+        RMessage2 iNotifyMeasurementMessage; // Measurement notification message
+
+        // Struct for information
+        TTestMeasurement   iTestMeasurement;
+        // Array for handling measurement
+        RPointerArray<TMeasurementHandling>  iMeasurementHandlingArray;
+
+        // This mutex meaning is to make sure that test complete and test
+        // case cancel operations are not executed at the same time.
+        RMutex          iTestThreadMutex; 
+
+        // Command related members
+        CCommandDef*     iCommandDef;             // Command definition (content)
+        RMessage2       iNotifyCommandMessage;   // Command nofitication message
+        TBool           iCommandNotifyAvailable; // Is command notification available?
+        RMutex          iCommandMutex;           // For iCommandSem semaphore handling
+        RSemaphore      iCommandSem;             // Signal command request availability
+        
+    public:     // Friend classes
+        // None
+        
+    protected:  // Friend classes
+        // None
+    	
+    private:    // Friend classes
+        friend class CUnderTaker;
+        friend class CPrintHandler;
+        friend class CEventHandler;
+        friend class CSndHandler;
+        friend class CRcvHandler;
+        friend class TEvent;
+        friend class CInterferenceHandler;
+        friend class CMeasurementHandler;
+        friend class CCommandHandler;
+    };
+
+#endif // TEST_SERVER_MODULE_IF_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/TestThreadContainer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,447 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CTestServer.
+*
+*/
+
+#ifndef TEST_THREAD_CONTAINER_H
+#define TEST_THREAD_CONTAINER_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifLogger.h>
+#include <StifTestModule.h>
+#include <StifTestInterface.h>
+#include "TestServerModuleIf.h"
+
+// CONSTANTS
+const TInt KStifMacroMax = 128;         // Maximum description length for
+                                        // STIF TF's macro cases
+const TInt KStifMacroMaxFile = 50;      // Maximum test result description
+                                        // length for STIF TF's macro cases
+const TInt KStifMacroMaxFunction = 30;  // Maximum test result description
+                                        // length for STIF TF's macro cases
+
+typedef TBuf<KStifMacroMax> TStifMacroDes;
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CUiEnvProxy;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestThreadContainer is a class, which contains the test execution thread
+// and interface functions to do operations in that thread context.
+class CTestThreadContainer 
+       :public CBase 
+    {
+
+    public: // Enumerations
+
+    private: // Enumerations
+        enum TPanicReason
+            {
+            EUnknownEventCmd,
+            EInvalidCTestThreadContainer,
+            ECreateTrapCleanup,
+            ENullTestThreadContainer,
+            EReInitializingTestModule,
+            ETestModuleNotInitialized,
+            EInvalidTestModuleOperation,
+            ENullRequest,            
+            EDuplicateFail,
+            EServerDied,
+            ENullExecution,
+            EThreadHandleOpenFail,
+            };
+
+    public: // Structured classes
+
+        /**
+        * For STIF TF's macro information
+        */
+        struct TTestMacro
+            {
+            TBool   iIndication;
+            TName   iFileDes;
+            TName   iFunctionDes;
+            TInt    iLine;
+            TInt    iReceivedError;
+            };
+
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestThreadContainer* NewL( 
+            CTestModuleContainer* aModuleContainer,
+            TThreadId aServerThreadId );
+
+        /**
+        * Destructor of CTestThreadContainer.
+        */
+        virtual ~CTestThreadContainer();
+
+
+    public: // New functions
+    
+        /**
+        * Test case execution thread thread function
+        */
+        static TInt ExecutionThread( TAny* aParams );        
+
+        /**
+         * UI Test case execution thread thread function
+         */
+         static TInt UIExecutionThread( TAny* aParams );        
+        
+        /**
+        * Returns pointer to test cases
+        */
+        const RPointerArray<TTestCaseInfo>* TestCases() const;
+        
+        /**
+        * Completes a print request. 
+        * This function is called from test execution thread.
+        */
+        virtual void DoNotifyPrint( const TInt aPriority, 
+                                    const TStifInfoName& aDes, 
+                                    const TName& aBuffer
+                                    );
+
+        /**
+        * Enables remote command receiving. 
+        * This function is called from test execution thread.
+        */
+        virtual void DoRemoteReceive( TStifCommand aRemoteCommand,
+                                      TParams aParams,
+                                      TInt aLen,
+                                      TRequestStatus& aStatus );
+        
+        /**
+        * Cancel remote command receiving. 
+        * This function is called from test execution thread.
+        */
+        virtual TInt DoRemoteReceiveCancel();
+
+        /**
+        * Completes a event request. 
+        * This function is called from test execution thread.
+        */
+        virtual TInt DoNotifyEvent( TEventIf& aEvent,
+                                    TRequestStatus* aStatus = NULL );
+                                    
+        /**
+        * Cancels pending asynchronous event request. 
+        * This function is called from test execution thread.
+        */
+        virtual void CancelEvent( TEventIf& aEvent, 
+                                  TRequestStatus* aStatus );
+                          
+        /**
+        * Set exit reason.
+        */
+        virtual void SetExitReason( const CTestModuleIf::TExitReason aExitReason, 
+                                    const TInt aExitCode );
+                                    
+        /**
+        * Set test behavior.
+        */
+        virtual TInt SetBehavior( const CTestModuleIf::TTestBehavior aType, 
+                                  TAny* aPtr );
+
+        /**
+        * Get exit reason.
+        */
+        virtual void ExitReason (  CTestModuleIf::TExitReason& aExitReason, 
+                                   TInt& aExitCode );
+
+        /**
+        * STIF TF's macro. Initialized TTestMacro.
+        */
+        virtual void StifMacroErrorInit();
+
+        /**
+        * STIF TF's(TL, T1L, T2L, etc )macro. Saves information for later use.
+        */ 
+        virtual TInt StifMacroError( TInt aMacroType,
+                                     const TText8* aFile,
+                                     const char* aFunction,
+                                     TInt aLine,
+                                     TInt aResult,
+                                     TInt aExpected1,
+                                     TInt aExpected2,
+                                     TInt aExpected3,
+                                     TInt aExpected4,
+                                     TInt aExpected5 );
+
+        /**
+        * With this can be store information about test interference
+        * thread to client space.
+        */ 
+        virtual TInt AddInterferenceThread( RThread aSTIFTestInterference );
+
+        /**
+        * With this can be remove information about test interference
+        * thread from client space.
+        */ 
+        virtual TInt RemoveInterferenceThread( RThread aSTIFTestInterference );
+
+        /**
+        * With this can be stored information about test measurement
+        * to TestServer space.
+        */ 
+        virtual TInt HandleMeasurementProcess(
+                    CSTIFTestMeasurement::TStifMeasurementStruct aSTIFMeasurementInfo );
+
+        /**
+        * Completes a command request.
+        * This function is called from test execution thread.
+        */
+        virtual void DoNotifyCommand(TCommand aCommand, const TDesC8& aParamsPckg);
+
+        /**
+         * Get test case execution arguments
+         */
+        virtual const TDesC& GetTestCaseArguments() const;        
+        
+        
+        /**
+        * Obtain title of currently running test case.
+        */
+        virtual void GetTestCaseTitleL(TDes& aTestCaseTitle);        
+
+        /**
+         * Sets thread logger.
+         */
+        void SetThreadLogger( CStifLogger* aThreadLogger );
+        
+        /**
+         * Gets thread logger.
+         */
+        CStifLogger* GetThreadLogger();
+        
+        /**
+         * Gets information if testserver supports UI testing.
+         */
+        IMPORT_C TBool UITesting();
+                
+        /**
+         * Gets UIEnvProxy.
+         */
+        IMPORT_C CUiEnvProxy* GetUiEnvProxy();
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    private:  // New functions
+
+        /**
+        * Function that initialise module in execution thread context.
+        */
+        TInt InitializeModuleInThread( RLibrary& aModule );
+
+        /**
+        * Function that enumerates test cases in execution thread context.
+        */
+        TInt EnumerateInThread();
+
+        /**
+        * Function that frees the enumeration data in execution thread context.
+        */
+        void FreeEnumerationDataInThread();
+
+        /**
+        * Function that executes test case in execution thread context.
+        */
+        TInt ExecuteTestCaseInThread();
+
+        
+        /**
+        * Complete testcase.
+        */
+        void TestComplete( TInt aCompletionCode );
+        
+        /**
+        * Delete a test module instance
+        */
+        void DeleteTestModule();
+        
+        /**
+        * Store TRequestStatus.
+        */
+        void SetEventReq(  TEventDef::TEventCmdType aType, 
+                           TEventIf& aEvent, 
+                           TRequestStatus* aStatus );
+
+        /**
+        * Destroys the event queue. 
+        * This function is called from test execution thread.
+        */
+        void DestroyEventQueue();
+        
+        /**
+        * Error print.
+        */
+        void ErrorPrint( const TInt aPriority, TPtrC aError );
+
+        /**
+        * Panicing function for test thread.
+        */ 
+        static void Panic( TPanicReason aReason );
+     
+        /**
+        * Check that server is alive.
+        */ 
+        void IsServerAlive() const;
+
+        /**
+        * Exception handler
+        */
+        static void ExceptionHandler( TExcType );
+
+         /**
+        * Modifies aRecFile and aRecFunction lenghts if nesessarily.
+        */ 
+        void SetMacroInformation( TInt aFileMaxLength,
+                                  TInt aFuntionMaxLength,
+                                  const TText8* aRecFile,
+                                  const char* aRecFunction,
+                                  TDes& aFile,
+                                  TDes& aFunction );
+        /**
+        * Duplicates mutexes
+        */                                 
+        TInt DuplicateMutexHandles( RThread& aThread );
+        
+        /**
+        * Executes test case using OOM simulation
+        */       
+        TInt ExecuteOOMTestCase( TInt aTestCaseNumber,                
+                                 TInt aFirst, 
+                                 TInt aLast, 
+                                 TInt& aResult, 
+                                 TTestResult& caseResult );
+        /**
+        * Leak checks for test case
+        */       
+
+        void LeakChecksForTestCase( TBool aReturnLeakCheckFail,
+                            TInt aThreadHandleCountBeforeTest,
+                            TInt aThreadHandleCountAfterTest,
+                            TInt aRequestCountBeforeTest, 
+                            TInt aRequestCountAfterTest );                           
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TThreadId aServerThreadId );
+
+        /** 
+        * C++ default constructor.
+        */
+        CTestThreadContainer( CTestModuleContainer* aModuleContainer );                              
+
+        /**
+         * Get module container.
+         */
+        CTestModuleContainer& ModuleContainer();        
+
+        /**
+        * Handles to parent.
+        */
+        CTestExecution& TestExecution() const;
+        
+    public:     // Data
+        
+    protected:  // Data
+        // None
+
+    private:    // Data     
+        // Pointers to server 
+        CTestModuleContainer*           iModuleContainer;
+        
+        // Pointer to test module
+        CTestModuleBase*                iTestModule;            
+        
+        // Test cases
+        RPointerArray<TTestCaseInfo>*   iCases;    
+        
+        // Resource checking
+        TUint                           iCheckResourceFlags;
+
+        // Internal if none provoded from testmodule        
+        TRequestStatus                  iReqStatus;
+
+         // StifLogger used in test module thread
+        CStifLogger* iThreadLogger;             
+        
+        // Handles to server
+        RThread     iServerThread;
+
+        // Mutexes, duplicated handles
+        RMutex  iPrintMutex;                // For iPrintSem semaphore handling
+        //RMutex  iErrorPrintMutex;         // For iErrorPrintSem semaphore handling
+        RMutex  iEventMutex;                // For iEventSem semaphore handling
+        RMutex  iSndMutex;                  // For iSndSem semaphore handling
+        RMutex  iRcvMutex;                  // For iRcvSem semaphore handling
+        RMutex  iInterferenceMutex;         // For iInterferenceSem semaphore handling
+        RMutex  iMeasurementMutex;          // For iMeasurementSem semaphore handling
+        RMutex  iCommandMutex;              // For iCommandSem semaphore handling
+        
+        // Mutex, duplicated handle. This mutex meaning is to make sure that
+        // test complete and test case cancel operations are not executed at
+        // the same time.
+        RMutex          iTestThreadMutex;                 
+                
+        // Semaphores, duplicated handles
+        RSemaphore  iPrintSem;          // Signal print request availability
+        RSemaphore  iErrorPrintSem;     // Signal error request availability
+        RSemaphore  iEventSem;          // Signal event request availability
+        RSemaphore  iSndSem;            // Signal Send request availability
+        RSemaphore  iRcvSem;            // Signal Receive request availability
+        RSemaphore  iInterferenceSem;   // Synchronize test interference access
+        RSemaphore  iMeasurementSem;    // Synchronize test measurement access
+        RSemaphore  iCommandSem;        // Signal command request availability
+
+        // Macro information
+        TTestMacro  iTestMacroInfo;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+    	friend class CTestThreadContainerRunner;
+    };
+
+#endif // TEST_THREAD_CONTAINER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/inc/version.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,31 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIF version declaration
+*
+*/
+
+#ifndef VERSION_H_
+#define VERSION_H_
+
+#define STIF_MAJOR_VERSION 7
+#define STIF_MINOR_VERSION 3
+#define STIF_BUILD_VERSION 35
+
+#define STIF_REL_DATE "15th June 2010"
+
+#define TO_UNICODE(text) _L(text) 
+
+#endif /*VERSION_H_*/
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/rom/STIFTestFramework.iby	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIFTestFramework.iby file specifies needed 
+* components for ROM image
+*
+*/
+
+#ifndef __STIF_TEST_FRAMEWORK_IBY__
+#define __STIF_TEST_FRAMEWORK_IBY__
+ 
+   #include <Stif.iby>
+
+#endif
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/rom/Stif.iby	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: Stif.iby file specifies needed components for ROM image
+*
+*/
+
+#ifndef __STIF_IBY__
+#define __STIF_IBY__
+
+file=ABI_DIR\BUILD_DIR\stiftestengine.dll            SHARED_LIB_DIR\stiftestengine.dll
+file=ABI_DIR\BUILD_DIR\stiftestserver.dll            SHARED_LIB_DIR\stiftestserver.dll
+file=ABI_DIR\BUILD_DIR\stiftestinterface.dll         SHARED_LIB_DIR\stiftestinterface.dll
+file=ABI_DIR\BUILD_DIR\consoleui.exe                 SHARED_LIB_DIR\consoleui.exe
+file=ABI_DIR\BUILD_DIR\testcombiner.dll              SHARED_LIB_DIR\testcombiner.dll
+file=ABI_DIR\BUILD_DIR\TestServerStarter.exe         SHARED_LIB_DIR\TestServerStarter.exe
+file=ABI_DIR\BUILD_DIR\demomodule.dll                SHARED_LIB_DIR\demomodule.dll
+file=ABI_DIR\BUILD_DIR\atsinterface.exe              SHARED_LIB_DIR\atsinterface.exe
+file=ABI_DIR\BUILD_DIR\atslogger.dll                 SHARED_LIB_DIR\atslogger.dll
+file=ABI_DIR\BUILD_DIR\testscripter.dll              SHARED_LIB_DIR\testscripter.dll
+file=ABI_DIR\BUILD_DIR\stiftfwif.dll                 SHARED_LIB_DIR\stiftfwif.dll
+file=ABI_DIR\BUILD_DIR\suevent.dll                   SHARED_LIB_DIR\suevent.dll
+
+// Touchconsoleui is a component that allows to work with touch screen devices in console mode.
+// It should be use only swith environments that do not supports S60 graphical user interface
+
+//file=ABI_DIR\BUILD_DIR\touchconsoleui.exe            SHARED_LIB_DIR\touchconsoleui.exe
+
+data=\epoc32\data\z\system\data\TestFramework.ini    testframework\TestFramework.ini
+
+
+#if defined(__S60_)
+// Note: before creating image, copy Stif_31_Stub.sis from \stif\sis\ to \epoc32\data\Z\system\install\
+data=ZSYSTEM\install\Stif_31_Stub.sis    System\Install\Stif_31_Stub.sis
+#endif
+
+
+// For STIF UI support use Stifui.iby:
+
+#endif
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/rom/Stif_rom.iby	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,27 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: Stif.iby file specifies needed components for ROM image
+*
+*/
+
+#ifndef __STIF_ROM_IBY__
+#define __STIF_ROM_IBY__
+
+#if defined(__S60_)
+// For kernel testing support, uncomment the following line
+device[VARID]=ABI_DIR\BUILD_DIR\StifKernelTestClassBase.dll  SHARED_LIB_DIR\StifKernelTestClassBase.dll
+#endif
+
+#endif
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/sis/Stif.pkg	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,80 @@
+;
+; Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+; All rights reserved.
+; This component and the accompanying materials are made available
+; under the terms of "Eclipse Public License v1.0"
+; which accompanies this distribution, and is available
+; at the URL "http://www.eclipse.org/legal/epl-v10.html".
+;
+; Initial Contributors:
+; Nokia Corporation - initial contribution.
+;
+; Contributors:
+; 
+; Description:
+;
+;	Installation file for STIF
+;
+
+; Languages
+&EN
+
+; Package header,uid is the 2nd uid of TestServer 0x101FB3E0
+#{"STIF"},(0x101FB3E0),1,1,0,TYPE=SA
+
+; Series60 product id for S60 3.0
+[0x101F7961], 0, 0, 0, {"Series60ProductID"}
+
+; Localised Vendor name
+%{"Nokia"}
+
+; Unique Vendor name
+:"Nokia"
+
+; Logo
+; None
+
+; Package signature - Optional
+; None
+
+; Start of Package body
+
+; Condition blocks
+; None
+
+; Options list
+; None
+
+; Install files
+
+
+  "\epoc32\release\armv5\udeb\consoleui.exe"   -   "!:\Sys\Bin\consoleui.exe"
+  "\epoc32\release\armv5\udeb\atsinterface.exe"   -   "!:\Sys\Bin\atsinterface.exe"
+  "\epoc32\release\armv5\udeb\stiftestengine.dll"   -   "!:\Sys\Bin\stiftestengine.dll"
+  "\epoc32\release\armv5\udeb\stiftestserver.dll"   -   "!:\Sys\Bin\stiftestserver.dll"
+  "\epoc32\release\armv5\udeb\stiftestinterface.dll"   -   "!:\Sys\Bin\stiftestinterface.dll"
+  "\epoc32\release\armv5\udeb\testcombiner.dll"   -   "!:\Sys\Bin\testcombiner.dll"
+  "\epoc32\release\armv5\udeb\testserverstarter.exe"   -   "!:\Sys\Bin\testserverstarter.exe"
+  "\epoc32\release\armv5\udeb\demomodule.dll"   -   "!:\Sys\Bin\demomodule.dll"
+  "\epoc32\release\armv5\udeb\testscripter.dll"   -   "!:\Sys\Bin\testscripter.dll"
+  "\epoc32\release\armv5\udeb\stiftfwif.dll"   -   "!:\Sys\Bin\stiftfwif.dll"
+  "\epoc32\release\armv5\udeb\atslogger.dll"   -   "!:\Sys\Bin\atslogger.dll"
+  "\epoc32\release\armv5\udeb\suevent.dll"   -   "!:\Sys\Bin\suevent.dll"
+  
+  ;// For kernel testing support, uncomment the following line
+  ; "\epoc32\release\armv5\udeb\stifkerneltestclassbase.dll"   -   "!:\Sys\Bin\stifkerneltestclassbase.dll"
+
+  "\epoc32\data\z\system\data\TestFramework.ini"-"C:\TestFramework\TestFramework.ini"
+  
+   ;// For STIF UI, use Stifui.pkg
+
+; Embedded SIS 
+; None
+
+; End of Package body
+
+; PKG dependencies
+; None
+
+; PKG capabilities
+; None
\ No newline at end of file
Binary file stif/sis/Stif_31.sis has changed
Binary file stif/sis/Stif_31_Stub.SIS has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/group/bld.inf	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: Build information for STIF API.
+*
+*/
+
+#include <platform_paths.hrh>
+
+
+PRJ_EXPORTS
+../inc/UIStoreIf.h                          OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/UIStoreIf.h)
+../inc/UIStoreContainer.h                   OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/UIStoreContainer.h)
+../inc/UIStore.h                            OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/UIStore.h)
+../inc/UIEngineContainer.h                  OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/UIEngineContainer.h)
+../inc/UIEngine.h                           OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/UIEngine.h)
+../inc/RRefArray.h                          OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/RRefArray.h)
+// ------- files for uitestserverstarter  -------
+../inc/TestServerClient.h                   OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/TestServerClient.h)
+../inc/UiEnvProxy.h                         OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/UiEnvProxy.h)
+../inc/TestThreadContainerRunnerFactory.h   OS_LAYER_PLATFORM_EXPORT_PATH(stifinternal/TestThreadContainerRunnerFactory.h)
+// ------- other files  -------
+../inc/atslogger.h                          OS_LAYER_PLATFORM_EXPORT_PATH(atslogger.h)
+../inc/StifKernelTestClassBase.h            OS_LAYER_PLATFORM_EXPORT_PATH(StifKernelTestClassBase.h) 
+../inc/StifTFwIf.h                          OS_LAYER_PLATFORM_EXPORT_PATH(StifTFwIf.h)
+../inc/StifLogger.h                         OS_LAYER_PLATFORM_EXPORT_PATH(StifLogger.h)
+../inc/StifParser.h                         OS_LAYER_PLATFORM_EXPORT_PATH(StifParser.h)
+../inc/StifSectionParser.h                  OS_LAYER_PLATFORM_EXPORT_PATH(StifSectionParser.h)
+../inc/StifItemParser.h                     OS_LAYER_PLATFORM_EXPORT_PATH(StifItemParser.h)
+../inc/StifTestInterface.h                  OS_LAYER_PLATFORM_EXPORT_PATH(StifTestInterface.h)
+../inc/StifTestModule.h                     OS_LAYER_PLATFORM_EXPORT_PATH(StifTestModule.h)
+../inc/StifTestEventInterface.h             OS_LAYER_PLATFORM_EXPORT_PATH(StifTestEventInterface.h)
+../inc/TestScripterInternal.h               OS_LAYER_PLATFORM_EXPORT_PATH(TestScripterInternal.h)
+../inc/StifHWReset.h                        OS_LAYER_PLATFORM_EXPORT_PATH(StifHWReset.h)
+../inc/StifTestInterference.h               OS_LAYER_PLATFORM_EXPORT_PATH(StifTestInterference.h)
+../inc/StifCommand.h                        OS_LAYER_PLATFORM_EXPORT_PATH(StifCommand.h)
+../inc/SettingServerClient.h                OS_LAYER_PLATFORM_EXPORT_PATH(SettingServerClient.h)
+../inc/TestEngineClient.h                   OS_LAYER_PLATFORM_EXPORT_PATH(TestEngineClient.h)
+../inc/TestEngineClient.inl                 OS_LAYER_PLATFORM_EXPORT_PATH(TestEngineClient.inl)
+../inc/StifTFwIfProt.h                      OS_LAYER_PLATFORM_EXPORT_PATH(StifTFwIfProt.h)
+../inc/NormalHardcodedAssert.h              OS_LAYER_PLATFORM_EXPORT_PATH(NormalHardcodedAssert.h)
+../inc/TestclassAssert.h                    OS_LAYER_PLATFORM_EXPORT_PATH(TestclassAssert.h)
+../inc/StifUnitUtils.inl                    OS_LAYER_PLATFORM_EXPORT_PATH(StifUnitUtils.inl)
+../inc/StifUnitMacros.h                     OS_LAYER_PLATFORM_EXPORT_PATH(StifUnitMacros.h)
+../inc/StifUnitGeneric.h                    OS_LAYER_PLATFORM_EXPORT_PATH(StifUnitGeneric.h)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/NormalHardcodedAssert.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,246 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the STIF 
+* normal and hardcoded modules assert macros.
+*
+*/
+
+
+#ifndef NormalHardcodedAssert_MACROS_H
+#define NormalHardcodedAssert_MACROS_H
+
+_LIT( KAssertFailedEquals, "AssertEquals Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotEquals, "AssertNotEquals Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNull, "AssertNull Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotNull, "AssertNotNull Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedSame, "AssertSame Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotSame, "AssertNotSame Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedTrue, "AssertTrue Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedFalse, "AssertFalse Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotLeaves, "AssertNotLeaves Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedLeaves, "AssertLeaves Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedLeavesWith, "AssertLeavesWith Failed [F:%s][L:%d]" );
+
+
+#ifdef _UNICODE
+	#define __STIF_WIDEN2(x) L ## x
+	#define __STIF_WIDEN(x) __STIF_WIDEN2(x)
+	#define __STIF_DBG_FILE__ __STIF_WIDEN(__FILE__)
+#else
+	#define __STIF_DBG_FILE__ __FILE__
+#endif
+
+
+// Logs to the STIF log file AND to the RDebug
+#define STIF_LOG( aMessage ) \
+    iLog->Log( _L( aMessage ) ); RDebug::Print( _L( aMessage ) );
+
+		
+/*********************************************************************************
+ * Assert Macros
+ *********************************************************************************/
+#define __STIF_ASSERT_SHARED( aFunction, aMessage ) \
+	if(!aFunction) \
+		{ \
+		iLog->Log( aMessage, __STIF_DBG_FILE__, __LINE__ );\
+		aResult.SetResult( KErrGeneral, _L("Testcase failed"));\
+		return KErrNone;\
+		}
+
+#define __STIF_ASSERT_SHARED_DESC( aFunction, aMessage, aDesc ) \
+	if(!aFunction) \
+		{ \
+		iLog->Log( aMessage, __STIF_DBG_FILE__, __LINE__ );\
+		aResult.SetResult( KErrGeneral, aDesc );\
+		return KErrNone;\
+		} \
+	else \
+		{ \
+		aResult.SetResult( KErrNone, aDesc ); \
+		}
+		
+		
+
+#define STIF_ASSERT_EQUALS( aExpected, aActual ) \
+	__STIF_ASSERT_SHARED( AssertEquals( aExpected, aActual ) , KAssertFailedEquals );
+
+#define STIF_ASSERT_EQUALS_DESC( aExpected, aActual, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( AssertEquals( aExpected, aActual ) , KAssertFailedEquals, aDescription ); 
+
+#define STIF_ASSERT_NOT_EQUALS( aExpected, aActual ) \
+	__STIF_ASSERT_SHARED( !AssertEquals( aExpected, aActual ) , KAssertFailedNotEquals );
+
+#define STIF_ASSERT_NOT_EQUALS_DESC( aExpected, aActual, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( !AssertEquals( aExpected, aActual ) , KAssertFailedNotEquals, aDescription );
+
+#define STIF_ASSERT_NULL( aPtr ) \
+	__STIF_ASSERT_SHARED( AssertNull( aPtr ), KAssertFailedNull );
+
+#define STIF_ASSERT_NULL_DESC( aPtr, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( AssertNull( aPtr ), KAssertFailedNull, aDescription );
+
+#define STIF_ASSERT_NOT_NULL( aPtr ) \
+	__STIF_ASSERT_SHARED( !AssertNull( aPtr ), KAssertFailedNotNull );
+
+#define STIF_ASSERT_NOT_NULL_DESC( aPtr, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( !AssertNull( aPtr ), KAssertFailedNotNull, aDescription );
+
+#define STIF_ASSERT_SAME( aExpectedPtr, aActualPtr ) \
+	__STIF_ASSERT_SHARED( AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedSame );
+
+#define STIF_ASSERT_SAME_DESC( aExpectedPtr, aActualPtr, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedSame, aDescription );
+
+#define STIF_ASSERT_NOT_SAME( aExpectedPtr, aActualPtr) \
+	__STIF_ASSERT_SHARED( !AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedNotSame );
+
+#define STIF_ASSERT_NOT_SAME_DESC( aExpectedPtr, aActualPtr, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( !AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedNotSame, aDescription );
+
+#define STIF_ASSERT_TRUE( aCondition ) \
+	__STIF_ASSERT_SHARED( AssertTrue( aCondition ), KAssertFailedTrue );
+
+#define STIF_ASSERT_TRUE_DESC( aCondition, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( AssertTrue( aCondition ), KAssertFailedTrue, aDescription );
+
+#define STIF_ASSERT_FALSE( aCondition ) \
+	__STIF_ASSERT_SHARED( !AssertTrue( aCondition ), KAssertFailedFalse );
+
+#define STIF_ASSERT_FALSE_DESC( aCondition, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( !AssertTrue( aCondition), KAssertFailedFalse, aDescription );
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_NOT_LEAVES( aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( AssertEquals( __leaveValue, KErrNone ), KAssertFailedNotLeaves ); \
+    }
+
+#define STIF_ASSERT_NOT_LEAVES_DESC( aStatement, aDescription ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_DESC( AssertEquals( __leaveValue, KErrNone ), KAssertFailedNotLeaves, aDescription ); \
+    }    
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_LEAVES( aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( !AssertEquals( __leaveValue, KErrNone ), KAssertFailedLeaves ); \
+    }
+
+#define STIF_ASSERT_LEAVES_DESC( aStatement, aDescription ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_DESC( !AssertEquals( __leaveValue, KErrNone ), KAssertFailedLeaves, aDescription ); \
+    }   
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_LEAVES_WITH( aLeaveCode, aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( AssertEquals( __leaveValue, aLeaveCode ), KAssertFailedLeaves ); \
+    }
+
+#define STIF_ASSERT_LEAVES_WITH_DESC( aLeaveCode, aStatement, aDescription ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_DESC( AssertEquals( __leaveValue, aLeaveCode ), KAssertFailedLeaves, aDescription ); \
+    }
+
+#define STIF_ASSERT_PANIC( aPanicCode, aStatement ) \
+	{ \
+	TestModuleIf().SetExitReason( CTestModuleIf::EPanic, aPanicCode ); \
+	aStatement; \
+	}
+
+#define STIF_ASSERT_PANIC_DESC( aPanicCode, aStatement, aDescription ) \
+	{ \
+	TestModuleIf().SetExitReason( CTestModuleIf::EPanic, aPanicCode ); \
+	aResult.SetResult(KErrNone, aDescription); \
+	aStatement; \
+	}
+
+template <class T>
+inline TBool AssertEquals(const T& aExpected, const T& aActual)
+/**
+ * AssertEquals
+ *
+ *
+ * @param aExpected - Expected result
+ * @param aActual - Actual result
+ * @return - True if equal
+ */
+	{
+	if( aExpected==aActual )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+template <class T>
+inline TBool AssertNull(const T* aPtr)
+/**
+ * AssertNull
+ *
+ *
+ * @param aPtr - Pointer
+ * @return - True if NULL
+ */
+	{
+	if( aPtr==NULL )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+template <class T>
+inline TBool AssertSame(const T* aExpectedPtr, const T* aActualPtr)
+/**
+ * AssertSame
+ *
+ *
+ * @param aExpectedPtr - Expected pointer
+ * @param aActualPtr - Actual pointer
+ * @return - True if equal
+ */
+	{
+	if( aExpectedPtr==aActualPtr )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+inline TBool AssertTrue(const TBool& aCondition)
+/**
+ * AssertTrue
+ *
+ *
+ * @param aCondition - Condition
+ * @return - True if aCondition is true
+ */
+	{
+	if( !aCondition )
+		{
+		return EFalse;
+		}
+	return ETrue;
+	}
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/RRefArray.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the STIF util
+* class RRefArray.
+*
+*/
+
+#ifndef RREFARRAY_H
+#define RREFARRAY_H
+
+// INCLUDES
+#include <e32std.h>
+
+// CLASS DECLARATION
+/**
+* Array class for references.
+*/
+template <class T>
+class RRefArray
+    :public RPointerArrayBase
+    {
+    public:
+        inline RRefArray():RPointerArrayBase(){};
+    	inline void Close(){ RPointerArrayBase::Close(); };
+    	inline TInt Count() const{ return RPointerArrayBase::Count(); };
+    	inline T const& operator[](TInt anIndex) const 
+    	    { return *( ( T* ) At(anIndex)); };
+    	inline T& operator[](TInt anIndex) 
+    	    { return *( ( T* ) At(anIndex)); };
+    	inline TInt Append( T const& anEntry )
+    	    { return RPointerArrayBase::Append(( TAny*) &anEntry); };
+    	inline TInt Insert( T const& anEntry, TInt aPos )
+    	    { return RPointerArrayBase::Insert(( TAny*) &anEntry, aPos ); };
+    	inline void Remove( TInt anIndex ) 
+    	    { RPointerArrayBase::Remove( anIndex ); };
+    	inline void Reset(){ RPointerArrayBase::Reset(); };
+    private:
+        RArray<TAny*> iArray;
+    };
+
+
+#endif // RREFARRAY_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/SettingServerClient.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* RSettingServer
+*
+*/
+
+#ifndef SETTING_SERVER_CLIENT_H
+#define SETTING_SERVER_CLIENT_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+#include <TestEngineClient.h>
+
+
+// CONSTANTS
+
+// The server version.
+// A version must be specified when creating a session with the server.
+const TUint KSettingServerMajorVersionNumber=0;
+const TUint KSettingServerMinorVersionNumber=1;
+const TUint KSettingServerVersionNumber=1;
+
+// MACROS
+
+// DATA TYPES
+// Opcodes used in message passing between client and server
+enum TSettingServerRequests
+    {
+    // RSettingServer requests
+    ESettingServerCloseSession,
+
+    // RLoggerSetting requests
+    EReadLoggerSettingsFromIniFile,
+    EGetLoggerSettings,
+
+    // IniFile information requests
+    ESetIniFileInformation,
+
+    // e.g. SetAttribute requests
+    ESetNewIniFileSetting,
+    
+    // Engine
+    EGetEngineSettings,
+    EStoreEngineSettings,
+    };
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// RSettingServer is a client class of Setting server
+// The connect function starts the server, if it not already running.
+
+class RSettingServer
+        :public RSessionBase 
+    {
+    public: // Enumerations
+        // None
+
+    private: // Enumerations
+        // None
+
+    public:  // Constructors and destructor
+        
+        /**
+        * Constructor.
+        */
+        IMPORT_C RSettingServer();
+
+        /**
+        * Closes the RSettingServer session.
+        */
+        IMPORT_C void Close();
+
+    public: // New functions
+        
+        /**
+        * Connect method creates new RSettingServer session 
+        */
+        IMPORT_C TInt Connect();
+
+        /**
+        * Version returns the client side version number from the RSettingServer.
+        */
+        IMPORT_C TVersion Version() const;
+
+        /**
+        * Set initialization filename and path settings to Setting server.
+        */
+        IMPORT_C TInt SetIniFileInformation( const TFileName& aIniFile );
+
+        /**
+        * Read Logger setting from initialization file. Mainly use from
+        * TestEngine side.
+        */
+        IMPORT_C TInt ReadLoggerSettingsFromIniFile( 
+                                        TLoggerSettings& aLoggerSettings );
+
+        /**
+        * Get Logger settings. Mainly use from Logger side.
+        */
+        IMPORT_C TInt GetLoggerSettings( TLoggerSettings& aLoggerSettings );
+
+        /**
+        * Set new initialization file setting(e.g. SetAttribute).
+        */
+        IMPORT_C TInt SetNewIniFileSetting( TName& aNewIniFileSetting );
+        
+        /**
+        * Get TestEngine settings
+        */
+        IMPORT_C TInt GetEngineSettings(TEngineSettings& aEngineSettings);
+
+        /**
+        * Set TestEngine settings
+        */
+        IMPORT_C TInt StoreEngineSettings(TEngineSettings& aEngineSettings);
+
+    public:     // Functions from base classes
+        // None
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:    // Functions from base classes
+        // None
+
+    public:     // Data
+        // None
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // None
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif // SETTING_SERVER_CLIENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifCommand.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,80 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the type definitions used by 
+* command feature (i.e. StopExecution).
+*
+*/
+
+#ifndef STIF_COMMAND_H
+#define STIF_COMMAND_H
+
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS 
+const TInt KMaxCommandParamsLength = 50;	// DEPRECATED use KMaxCommandParamsLength2 instead
+const TInt KMaxCommandParamsLength2 = 600;
+
+// MACROS
+
+// FUNCTION PROTOTYPES
+
+// DATA TYPES
+
+// This enum type lists all possible commands sent from test case to test engine
+enum TCommand
+    {
+    EStopExecution,
+    ESendTestModuleVersion,
+    };
+
+typedef TPckg<TCommand> TCommandPckg;
+
+// This enum type lists all possible ways of how to run StopExecution command
+enum TStopExecutionType
+    {
+    EOk,
+    EFail,
+    EAbort,
+    };
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+
+// CLASS DECLARATION
+struct TStopExecutionCommandParams
+    {
+    TInt               iTestCaseHandle;
+    TStopExecutionType iType;
+    TInt               iCode;
+    };
+
+typedef TPckg<TStopExecutionCommandParams> TStopExecutionCommandParamsPckg;
+
+
+struct TSendTestModuleVesionCommandParams
+	{
+	TFileName iTestModuleName;
+	TInt iMajor;
+	TInt iMinor;
+	TInt iBuild;
+	};
+
+typedef TPckg<TSendTestModuleVesionCommandParams> TSendTestModuleVesionCommandParamsPckg;
+
+#endif //STIF_COMMAND_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifHWReset.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,117 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of CStifHWReset 
+* of STIF TestFramework.
+*
+*/
+
+#ifndef STIFHWRESET_H
+#define STIFHWRESET_H
+
+// INCLUDES
+#include <e32base.h>
+#include <e32std.h>
+
+#include "StifTestModule.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// This is class which can be inherited from own code to perform a
+// reset to the system.
+// This is used when calling dynamic loaded dll from STIF TestFramework.
+class CStifHWReset
+        :public CBase
+    {
+    public:     // Enumerations
+
+        // Different reset types. Possibility to do different king of reset.
+/*        enum TResetType
+            {
+            EResetType0,
+            EResetType1,
+            EResetType2,
+            EResetType3,
+            EResetType4,
+            EResetType5
+            };
+*/
+    public:     // Enumerations
+    	// None
+
+    private:    // Enumerations
+    	// None
+
+    public:     // Constructors and destructor
+    	// None
+
+    public:     // New functions
+        
+        /**
+        * Defines reset type and forwards information to reset module.
+        * This method is pure virtual and it is mandatory to implement it
+        * to specific reset module.
+        */
+        virtual TInt DoReset( CTestModuleIf::TRebootType aResetType ) = 0;
+        
+    public:     // Functions from base classes
+        // None
+
+    protected:  // New functions
+    	// None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+        // None
+
+	public:     // Data
+	    // None
+
+	protected:  // Data
+        // None
+
+    private:    // Data
+        // None
+
+    public:     // Friend classes
+        // None
+    	
+    protected:  // Friend classes
+        // None
+    	
+    private:    // Friend classes
+        // None
+    	
+    };
+
+#endif // STIFHWRESET_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifItemParser.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,290 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CStifItemParser.
+*
+*/
+
+#ifndef STIF_ITEM_PARSER_H
+#define STIF_ITEM_PARSER_H
+
+//  INCLUDES
+#include <f32file.h>
+#include <e32std.h>
+#include <e32base.h>
+
+// CONSTANTS
+const TInt KMaxTag = 256; // A tag maximum length
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CStifItemParser is a STIF Test Framework StifParser class.
+// Class contains a configuration file parsing operations.
+
+class CStifItemParser
+        :public CBase
+    {
+    public:     // Enumerations
+
+        // Parsing type can be given when parsing string(GetString and
+        // GetNextString). This enumeration indicates parsing type.
+        // ENormalParsing:
+        //      - Indicates normal parsing without any modifications to
+        //        parsed information
+        // EQuoteStyleParsing:
+        //      - Indicates special parsing. This style of parsing gives to
+        //        quote(" ") characters special meaning.
+        //      - Information between quotes is handled as a one string. Quotes
+        //        not included to information.
+        enum TParsingType
+            {
+            ENormalParsing,     // Mode on(Default)
+            EQuoteStyleParsing, // Mode off
+            };
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CStifItemParser* NewL( TPtrC aSection,
+                                                TInt aStartPos,
+                                                TInt aLength );
+
+        /**
+        * Destructor.
+        */
+        ~CStifItemParser();
+
+    public:     // New functions
+
+        /**
+        * Get a string with a tag.
+        * Returns an error code and a reference to the parsed string.
+         *If start tag is empty the first string will be parsed and returned.
+        */
+        IMPORT_C TInt GetString( const TDesC& aTag, TPtrC& aString );
+
+        /**
+        * Get next string.
+        * Returns an error code and a reference to the parsed string.
+        * GetString or GetInt or GetChar must be called before call
+        * GetNextString method.
+        */
+        IMPORT_C TInt GetNextString( TPtrC& aString );
+
+        /**
+        * Get next string with a tag.
+        * Returns an error code and a reference to the parsed string.
+        * If start tag is empty the next string will be parsed and returned.
+        * GetString or GetInt or GetChar must be called before call
+        * GetNextString method.
+        */
+        IMPORT_C TInt GetNextString( const TDesC& aTag, TPtrC& aString );
+
+        /**
+        * Get a integer(TInt) with a tag.
+        * Returns an error code and a reference to the parsed integer.
+        * If start tag is empty the first integer will be parsed and returned.
+        */
+        IMPORT_C TInt GetInt( const TDesC& aTag, TInt& aInteger );
+
+        /**
+        * Get next integer(TInt).
+        * Returns an error code and a reference to the parsed integer.
+        * GetString or GetInt or GetChar must be called before call
+        * GetNextInt method.
+        */
+        IMPORT_C TInt GetNextInt( TInt& aInteger );
+
+        /**
+        * Get next integer(TInt) with a tag.
+        * Returns an error code and a reference to the parsed integer.
+        * If start tag is empty the next integer will be parsed and returned.
+        * GetString or GetInt or GetChar must be called before call
+        * GetNextInt method.
+        */
+        IMPORT_C TInt GetNextInt( const TDesC& aTag, TInt& aInteger );
+
+        /**
+        * Get a integer(TUint) with a tag.
+        * Returns an error code and a reference to the parsed integer.
+        * If start tag is empty the first integer will be parsed and returned.
+        * With TRadix parameter can convert a number into different
+        * presentation(EBinary, EOctal, EDecimal and EHex).
+        */
+        IMPORT_C TInt GetInt( const TDesC& aTag,
+                                TUint& aInteger,
+                                TRadix aRadix = EDecimal );
+
+        /**
+        * Get next integer(TUint).
+        * Returns an error code and a reference to the parsed integer.
+        * GetString or GetInt or GetChar must be called before call
+        * GetNextInt method.
+        * With TRadix parameter can convert a number into different
+        * presentation(EBinary, EOctal, EDecimal and EHex).
+        */
+        IMPORT_C TInt GetNextInt( TUint& aInteger,
+                                    TRadix aRadix = EDecimal );
+
+        /**
+        * Get next integer(TUint) with a tag.
+        * Returns an error code and a reference to the parsed integer.
+        * If start tag is empty the next integer will be parsed and returned.
+        * GetString or GetInt or GetChar must be called before call
+        * GetNextInt method.
+        * With TRadix parameter can convert a number into different
+        * presentation(EBinary, EOctal, EDecimal and EHex).
+        */
+        IMPORT_C TInt GetNextInt( const TDesC& aTag,
+                                    TUint& aInteger,
+                                    TRadix aRadix = EDecimal );
+
+        /**
+        * Get a character with a tag.
+        * Returns an error code and a reference to the parsed character.
+        * If start tag is empty the first character will be parsed and
+        * returned.
+        */
+        IMPORT_C TInt GetChar( const TDesC& aTag, TChar& aCharacter );
+
+        /**
+        * Get next character.
+        * Returns an error code and a reference to the parsed character.
+        * GetString or GetInt or GetChar must be called before call
+        * GetNextChar method.
+        */
+        IMPORT_C TInt GetNextChar( TChar& aCharacter );
+
+        /**
+        * Get next character with a tag.
+        * Returns an error code and a reference to the parsed character.
+        * If start tag is empty the next character will be parsed and returned.
+        * GetString or GetInt or GetChar must be called before call
+        * GetNextChar method.
+        */
+        IMPORT_C TInt GetNextChar( const TDesC& aTag, TChar& aCharacter );
+
+        
+        /**
+        * Get remaining strings.
+        * Returns an error code and a reference to the remainder of the 
+        * parsed line.
+        * Note: This method does not support the quote(TParsingType) feature,
+        * only GetString and GetNextString methods include support.
+        */
+        IMPORT_C TInt Remainder( TPtrC& aString );
+        
+        /**
+        * Parsing type can be given when parsing string(GetString and
+        * GetNextString). See TParsingType enumeration for more
+        * inforamtion.
+        */
+        IMPORT_C TInt SetParsingType( CStifItemParser::TParsingType aType );
+        
+        /**
+        * Get current parsing type. Please see TParsingType enumeration for
+        * more inforamtion.
+        */
+        IMPORT_C CStifItemParser::TParsingType ParsingType();
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CStifItemParser( TPtrC aSection,
+                            TInt aStartPos,
+                            TInt aLength );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Generig start and end position parser for given data.
+        * Returns an error code.
+        */
+        TInt ParseStartAndEndPos( TPtrC aSection,
+                                    const TDesC& aStartTag,
+                                    TInt& aStartPos,
+                                    TInt& aEndPos,
+                                    TInt& aLength,
+                                    TInt& aExtraEndPos );
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+        /**
+        * Parsed section with GetItemLineL() or GetNextItemLineL() method.
+        */
+        TPtrC                           iItemLineSection;
+
+        /**
+        * Indicates position where start the parsing.
+        */
+        TInt                            iItemSkipAndMarkPos;
+
+        /**
+        * Indicator is GetString(), GetInt() or GetChar() called.
+        */
+        TBool                           iGetMethodsIndicator;
+
+        /**
+        * Parsing type indicator for GetString and GetNextString use.
+        */
+        CStifItemParser::TParsingType   iParsingType;
+
+    public:     // Friend classes
+
+        /**
+        * For testing operations to get length information.
+        */
+        friend class CTestParser;
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // STIF_ITEM_PARSER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifKernelTestClassBase.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,149 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the STIF 
+* kernel testclass declaration
+*
+*/
+
+#ifndef STIFKERNELTESTCLASSBASE_H
+#define STIFKERNELTESTCLASSBASE_H
+
+//  INCLUDES
+#include <kernel.h>    
+
+
+// CONSTANTS
+
+// MACROS
+
+
+// In EKA2 kernel only 8bit descriptors are allowed, because of that C++'s 
+// L makro cannot be used.
+
+// ENTRY macro is modified and now it stores data as 8bit descriptor.
+// In EKA2 kernel TText is 8bit descriptor.
+
+#define ENTRY(A,B) \
+	{ (TText*) A, (StifTestFunction) &B }
+
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class DStifKernelTestClassBase;
+
+// DATA TYPES
+typedef TInt (DStifKernelTestClassBase::* StifTestFunction)( const TDesC& );    
+
+// CLASS DECLARATION
+
+/**
+*  An internal structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TStifFunctionInfo
+    {
+    public:            
+        const TText*           iFunctionName;
+        StifTestFunction       iMethod;    
+    };
+    
+// CLASS DECLARATION
+
+/**
+* DStifKernelTestClassBaseDriver is the device driver factory that will
+* instantiate the physical channel, which is the actual
+* physical driver.
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class DStifKernelTestClassBaseDriver : public DLogicalDevice
+    {
+
+    public:
+        IMPORT_C DStifKernelTestClassBaseDriver( const TDesC& aName );
+        IMPORT_C virtual ~DStifKernelTestClassBaseDriver();
+
+        IMPORT_C virtual TInt Install();
+        IMPORT_C virtual void GetCaps(TDes8 &aDes) const;
+
+        virtual TInt Create(DLogicalChannelBase*& aChannel)=0;
+  
+    private:
+        TName   iName;
+    
+    };
+
+
+// CLASS DECLARATION
+
+/**
+*  DStifKernelTestClassBase is a base class for kernel test class 
+*  for STIF Test Framework TestScripter.
+*  ?other_description_lines
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class DStifKernelTestClassBase : public DLogicalChannel
+    {
+
+    public:
+        IMPORT_C DStifKernelTestClassBase( DLogicalDevice* aDevice );
+        IMPORT_C virtual ~DStifKernelTestClassBase();
+        
+    public:     
+        /**
+        * Runs a script line. Derived class must implement
+        */
+        virtual TInt RunMethodL( const TDesC& aMethod, const TDesC& aParams ) = 0;  
+        
+        /**
+        * Called from destructor. Derived class may implement.
+        */
+        virtual void Delete(){};  
+        
+        // Processes a message for this logical channel
+        IMPORT_C virtual void HandleMsg( TMessageBase* aMsg );
+    protected: // Derived class uses
+        
+        // Internal fuction to run specified method.              
+        IMPORT_C virtual TInt RunInternalL( 
+                        const TStifFunctionInfo* const aFunctions, 
+                        TInt aCount, 
+                        const TDesC& aMethod, 
+                        const TDesC& aParams );
+
+    private: 
+
+        // No need to export DoControl in EKA2, because it is called
+        // from HandleMsg
+        TInt DoControl( TInt aFunction,TAny* a1,TAny* a2 );
+     
+        // Asynchronous command are not supported
+        void DoCancel( TInt ){};
+                  
+    private:
+     
+        DThread*         iThread;                
+     
+    };
+
+#endif      // STIFKERNELTESTCLASSBASE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifLogger.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,409 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CStifLogger.
+*
+*/
+
+#ifndef STIFLOGGER_H
+#define STIFLOGGER_H
+
+//  INCLUDES
+#include <e32base.h>
+
+// If using older STIF TF than STIF200414 there is no this definition.
+// If is need to combile e.g. testmodule with older STIF TF there may use
+// in the testmodule this flag to indicating which enum definition is used.
+// Example:
+//          #ifdef __NEW_LOGGER_ENUMS_DEFS__
+//              logger->Log( CStifLogger::ERed, _L( "Logged text" ) );
+//          #else
+//              logger->Log( ERed, _L( "Logged text" ) );
+//          #endif
+#define __NEW_LOGGER_ENUMS_DEFS__
+
+// Maximum length of the data. Must be over 26 because HTML page initializing.
+// Can be only max 254 length because rdebug prints max 256 length text and
+// that includes line break(+2 character)
+const TInt KMaxLogData = 254;
+
+// This is for making partitions of the rdebug( minus 3 is for ' ->')
+const TInt KMaxRDebug = KMaxLogData - 3;
+
+// Maximum count of file type plus dot e.g. ".txt"
+const TInt KMaxFileType = 10;
+
+// Maximum length of the date and time logging
+// Includes date, time, spaces(5) and end of line(2):
+// e.g. "'06.Nov.2003 15:12:18.123    '...logged data...'  '"
+const TInt KMaxTimeStamp = 30;
+
+// MACROS
+// None
+
+// DATA TYPES
+
+// For 16 bit data size definition.
+typedef TBuf<KMaxLogData> TLogInfo;
+
+// For 8 bit data size definition.
+typedef TBuf8<KMaxLogData> TLogInfo8;
+
+// For file type size definition.
+typedef TBuf<KMaxFileType> TFileType;
+
+// For time stamp size definition.
+typedef TBuf8<KMaxTimeStamp> TStifLoggerTimeStamp;
+
+// For time stamp size definition.
+typedef TBuf<KMaxTimeStamp> TStifLoggerTimeStamp8;
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class COutput;
+
+// Structs are defined at the end of this file.
+struct TOverwritedSettings;
+struct TLoggerSettings;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CStifLogger is a STIF Test Framework StifLogger class.
+// Class contains a file logging operations.
+
+class CStifLogger 
+        :public CBase
+    {
+    public:     // Enumerations
+
+        // Different StifLogger presentations types.
+        enum TLoggerType
+            {
+            ETxt,       // txt file logging
+            EData,      // data file logging(e.g. web page downloading )
+            EHtml       // html file logging
+            };
+
+        // Different StifLogger output modules.
+        enum TOutput
+            {
+            EFile,      // File logging
+            ERDebug     // RDebug logging
+            };
+
+        // Different style forms for text.
+        enum TStyle
+            {
+            ENoStyle    = 0x00000,  // No style parameter
+            EBold       = 0x00001,  // Bold
+            ECursive    = 0x00002,  // Cursive
+            EUnderline  = 0x00004,  // Underline
+            EBlue       = 0x00008,  // Blue
+            EGreen      = 0x00010,  // Green
+            ERed        = 0x00020,  // Red
+            EImportant  = 0x00040,  // Important (Line will starts a 'IMPORTANT' text)
+            EWarning    = 0x00080,  // Warning (Line will starts a 'WARNING' text)
+            EError      = 0x00100   // Error (Line will starts a 'ERROR' text)
+            };
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CStifLogger* NewL( const TDesC& aTestPath,
+                                            const TDesC& aTestFile,
+                                            // Default logger type is .txt
+                                            TLoggerType aLoggerType = ETxt,
+                                            // By default output is file
+                                            TOutput aOutput = EFile,
+                                            // By default overwrite is used
+                                            TBool aOverWrite = ETrue,
+                                            // By default time stamp is used
+                                            TBool aWithTimeStamp = ETrue,
+                                            // By default line break is used
+                                            TBool aWithLineBreak = ETrue,
+                                            // By default even ranking is not
+                                            // used
+                                            TBool aWithEventRanking = EFalse,
+                                            // By default thread id is added
+                                            // after the log file
+                                            TBool aThreadIdToLogFile = ETrue,
+                                            // By default log directory will
+                                            // not create
+                                            TBool aCreateLogDir = EFalse,
+                                            // Static logger implementation is
+                                            // not yet permanent, may change 
+                                            TInt aStaticBufferSize = 0,
+                                            // By default files are not written
+                                            // in unicode format
+                                            TBool aUnicode = EFalse );
+        /**
+        * Destructor.
+        */
+        virtual ~CStifLogger();
+
+    public:     // New functions
+
+        /**
+        * C++ default constructor.
+        */
+        CStifLogger();
+
+        /**
+        * Log a 16 bit information to some storage e.g. text file.
+        */
+        IMPORT_C TInt Log( const TDesC& aLogInfo );
+
+        /**
+        * Log a 8 bit information to some storage e.g. text file.
+        */
+        IMPORT_C TInt Log( const TDesC8& aLogInfo );
+
+        /**
+        * Log a 16 bit information to some storage e.g. text file. There is
+        * also parameter to styling text information e.g. text color.
+        */
+        IMPORT_C TInt Log( TInt aStyle, const TDesC& aLogInfo );
+
+        /**
+        * Log a 8 bit information to some storage e.g. text file. There is
+        * also parameter to styling text information e.g. text color.
+        */
+        IMPORT_C TInt Log( TInt aStyle, const TDesC8& aLogInfo );
+
+        /**
+        * Log a 16 bit information to some storage e.g. text file. In this log
+        * method may set several parameters.
+        */
+        IMPORT_C TInt Log( TRefByValue<const TDesC> aLogInfo,... );
+
+        /**
+        * Log a 8 bit information to some storage e.g. text file. In this log
+        * method may set several parameters.
+        */
+        IMPORT_C TInt Log( TRefByValue<const TDesC8> aLogInfo,... );
+
+        /**
+        * Log a 16 bit information to some storage e.g. text file. There is
+        * also parameter to styling text information e.g. text color.
+        */
+        IMPORT_C TInt Log( TInt aStyle,
+            TRefByValue<const TDesC> aLogInfo,... );
+
+        /**
+        * Log a 8 bit information to some storage e.g. text file. There is
+        * also parameter to styling text information e.g. text color.
+        */
+        IMPORT_C TInt Log( TInt aStyle,
+            TRefByValue<const TDesC8> aLogInfo,... );
+
+        /**
+        * Log a 16 bit delimiter. Default char is '#' and default
+        * repeat count is 60.
+        * This will be used if parameters are not given when calling
+        * this method.
+        */
+        IMPORT_C TInt WriteDelimiter( const TDesC& aDelimiter = _L( "#"),
+                                        TInt aCount = 60 );
+
+        /**
+        * Log a 8 bit delimiter. 8 bit delimiter includes no default values.
+        * Delimiter may be '#' or 'XO' etc.
+        */
+        IMPORT_C TInt WriteDelimiter( const TDesC8& aDelimiter, TInt aCount );
+
+        /**
+        * Used when is need to save file or data to storage e.g. web page.
+        * 16 bit.
+        */
+        IMPORT_C TInt SaveData( TDesC& aData );
+
+        /**
+        * Used when is need to save file or data to storage e.g. web page.
+        * 8 bit.
+        */
+        IMPORT_C TInt SaveData( TDesC8& aData );
+        
+        /**
+        * Get creation result.
+        */
+        IMPORT_C TInt CreationResult();
+
+        /**
+        * Get output type. Valid only if CreationResult returns KErrNone.
+        */
+        IMPORT_C TOutput OutputType();
+
+        /**
+        * Pure virtual. Send style information and data to the output module.
+        * 16 bit.
+        */
+        virtual TInt Send( TInt /*aStyle*/, const TDesC& /*aData*/ ) = 0;
+
+        /**
+        * Pure virtual. Send style information and data to the output module.
+        * 8 bit.
+        */
+        virtual TInt Send( TInt /*aStyle*/, const TDesC8& /*aData*/ ) = 0;
+
+        /**
+        * Log 16 bit _LIT information to some storage e.g. text file.
+        */
+        template<TInt S> TInt Log( const TLitC<S>& aLogInfo )
+            { 
+            return Send( ENoStyle, (TDesC&)aLogInfo );
+            };
+
+        /**
+        * Log 8 bit _LIT information to some storage e.g. text file.
+        */
+        template<TInt S> TInt Log( const TLitC8<S>& aLogInfo )
+            { 
+            return Send( ENoStyle, (TDesC8&)aLogInfo );
+            };
+
+        /**
+        * Log 16 bit _LIT information to some storage e.g. text file. There is
+        * also parameter to styling text information e.g. text color.
+        */
+        template<TInt S> TInt Log( TInt aStyle, const TLitC<S>& aLogInfo )
+            { 
+            return Send( aStyle, (TDesC&)aLogInfo );
+            };
+
+        /**
+        * Log 8 bit _LIT information to some storage e.g. text file.  There is
+        * also parameter to styling text information e.g. text color.
+        */
+        template<TInt S> TInt Log( TInt aStyle, const TLitC8<S>& aLogInfo )
+            { 
+            return Send( aStyle, (TDesC8&)aLogInfo );
+            };
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+        /**
+        * Two-phased constructor. TestEngine's and TestServer's are friend.
+        * For TestEngine's and TestServer's StifLogger creation.
+        */
+        IMPORT_C static CStifLogger* NewL( const TDesC& aTestPath,
+                                            const TDesC& aTestFile,
+                                            TLoggerSettings& aLoggerSettings );
+
+    protected:  // Functions from base classes
+
+        /**
+        * Local CStifLogger's method for StifLogger settings overwriting.
+        */
+        static void OverwriteLoggerSettings( TLoggerSettings& aLoggerSettings,
+                                                TName& aTestPath,
+                                                TName& aTestFile,
+                                                TLoggerType& aLoggerType,
+                                                TOutput& aOutput,
+                                                TBool& aOverWrite,
+                                                TBool& aWithTimeStamp,
+                                                TBool& aWithLineBreak,
+                                                TBool& aWithEventRanking,
+                                                TBool& aThreadIdToLogFile,
+                                                TBool& aCreateLogDir,
+                                                TBool& aUnicode );
+
+    private:
+
+    public:     // Data
+
+    protected:  // Data
+        /**
+        * Output object.
+        */
+        COutput*    iOutput;
+        
+    private:    // Data
+
+    public:     // Friend classes
+        
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+        // TestEngine classes
+        friend class CTestEngineServer;
+        friend class CTestReport;
+        friend class CTestCaseController;
+        friend class CTestEngine;
+
+        // TestServer classes
+        friend class CTestModuleContainer;
+        friend class CTestServer;
+        friend class CTestThreadContainer;
+        friend class CTestThreadContainerRunner;
+
+        // UIEngine classes
+        friend class CUIEngine;
+
+        // SettingServer classes
+        friend class CSettingServer;
+
+    };
+
+// Struct to indicate StifLogger's settings overwriting
+struct TOverwritedSettings
+    {
+    TBool               iCreateLogDir;
+    TBool               iPath;
+    TBool               iHwPath;
+    TBool               iFormat;
+    TBool               iHwFormat;
+    TBool               iOutput;
+    TBool               iHwOutput;
+    TBool               iOverwrite;
+    TBool               iTimeStamp;
+    TBool               iLineBreak;
+    TBool               iEventRanking;
+    TBool               iThreadId;
+    TBool               iUnicode;
+    TBool               iAddTestCaseTitle;
+    };
+
+// Struct to StifLogger overwrite settings
+struct TLoggerSettings
+    {
+    TBool                       iCreateLogDirectories;
+    TName                       iEmulatorPath;
+    CStifLogger::TLoggerType    iEmulatorFormat;
+    CStifLogger::TOutput        iEmulatorOutput;
+    TName                       iHardwarePath;
+    CStifLogger::TLoggerType    iHardwareFormat;
+    CStifLogger::TOutput        iHardwareOutput;
+    TBool                       iOverwrite;
+    TBool                       iTimeStamp;
+    TBool                       iLineBreak;
+    TBool                       iEventRanking;
+    TBool                       iThreadId;
+    TBool                       iUnicode;
+    TBool                       iAddTestCaseTitle;
+    TOverwritedSettings         iIsDefined;
+    };
+
+#endif      // STIFLOGGER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifParser.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,246 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CStifParser.
+*
+*/
+
+#ifndef STIF_PARSER_H
+#define STIF_PARSER_H
+
+//  INCLUDES
+#include <f32file.h>
+#include <e32std.h>
+#include <e32base.h>
+#include "StifSectionParser.h"
+#include "StifItemParser.h"
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CStifSectionParser;
+class CStifFileParser;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CStifParser is a STIF Test Framework StifParser class.
+// Class contains a configuration file parsing operations.
+
+class CStifParser
+        :public CBase
+    {
+    public:     // Enumerations
+
+        // Indication which type of comments are in use
+        enum TCommentType
+            {
+            ENoComments,        // No comments type given, parse all
+            ECStyleComments,    // C-style comments( // and /*...*/ ) are
+                                // removed
+            };
+
+    private:    // Enumerations
+
+        // Indication which mode of parsing are in use
+        enum TParsingMode
+            {
+            EFileParsing,       // Indication for file parsing.
+            EBufferParsing,     // Indication for buffer parsing.
+            };
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * Creating parser with path and file information. For default all
+        * information will be parsed(ENoComments).
+        */
+        IMPORT_C static CStifParser* NewL( const TDesC& aPath, 
+                                            const TDesC& aConfig,
+                                            TCommentType = ENoComments);
+
+        /**
+        * Two-phased constructor.
+        * Creating parser with buffer information. For default all
+        * information will be parsed(ENoComments).
+        */
+        IMPORT_C static CStifParser* NewL( const TDesC& aBuffer, 
+                                            TCommentType = ENoComments );
+
+        /**
+        * Destructor.
+        */
+        IMPORT_C ~CStifParser();
+
+    public:     // New functions
+
+        /**
+        * Open and read configuration source and parses a required section.
+        * If start tag is empty the parsing starts beging of the configuration
+        * file.
+        * If end tag is empty the parsing goes end of configuration file.
+        * This method starts always from beginning of configuration file and
+        * parses first section if aSeeked parameters is not given.
+        * If configuration file includes several sections with both start and
+        * end tags so aSeeked parameter seeks the required section. The aSeeked
+        * parameters indicates section that will be parsed.
+        */
+        IMPORT_C CStifSectionParser* SectionL( const TDesC& aStartTag,
+                                                const TDesC& aEndTag,
+                                                TInt aSeeked = 1 );
+
+        /**
+        * Open and read configuration source and parses a required section.
+        * If start tag is empty the parsing starts beging of the configuration
+        * file.
+        * If end tag is empty the parsing goes end of configuration file.
+        * This method will parse next section after the earlier section if
+        * aSeeked parameter is not given.
+        * If configuration file includes several sections with both start and
+        * end tags so aSeeked parameter seeks the required section. The aSeeked
+        * parameters indicates section that will be parsed.
+        */
+        IMPORT_C CStifSectionParser* NextSectionL( const TDesC& aStartTag,
+                                                    const TDesC& aEndTag,
+                                                    TInt aSeeked = 1 );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CStifParser( TCommentType aCommentType );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aPath,
+                         const TDesC& aConfig,
+                         const TDesC& aContent = KNullDesC );
+
+        /**
+        * Convert a section without comments.
+        */
+        void ParseCommentsOff( TPtr& aBuf );
+
+        //
+        // Handles special marks.( '\/\/', '\/\*' and '*/\/' ). This
+        // is used when ECStyleComments comment type is used. 
+        //
+        void HandleSpecialMarks( TPtr& aBuf );
+
+        /**
+        * Open and read configuration source and parses a required section.
+        * If start tag is empty the parsing starts beging of the configuration
+        * file.
+        * If end tag is empty the parsing goes end of configuration file.
+        * This method will parse next section after the earlier section if
+        * aSeeked parameter is not given.
+        * If configuration file includes several sections with both start and
+        * end tags so aSeeked parameter seeks the required section. The aSeeked
+        * parameters indicates section that will be parsed.
+        */
+		CStifSectionParser *NextSectionMemoryL( const TDesC& aStartTag,
+                                              	const TDesC& aEndTag,
+                                                TInt aSeeked );
+
+        /**
+        * Open and read configuration source and parses a required section.
+        * If start tag is empty the parsing starts beging of the configuration
+        * file.
+        * If end tag is empty the parsing goes end of configuration file.
+        * This method will parse next section after the earlier section if
+        * aSeeked parameter is not given.
+        * If configuration file includes several sections with both start and
+        * end tags so aSeeked parameter seeks the required section. The aSeeked
+        * parameters indicates section that will be parsed.
+        */
+		CStifSectionParser *NextSectionFileL( const TDesC& aStartTag,
+                                              const TDesC& aEndTag,
+                                              TInt aSeeked );
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+        /**
+        * For file opening.
+        */
+        RFs         iFileServer;
+
+        /**
+        * For file opening.
+        */
+        RFile       iFile;
+
+        /**
+        * Indicates position where we are currently.
+        */
+        TInt        iOffset;
+
+        /**
+        * Comment type's indication.
+        */
+        TCommentType iCommentType;
+
+        /**
+        * Indication which mode of parsing are in use.
+        */
+        TParsingMode iParsingMode;
+
+        /**
+        * For buffer parsing.
+        */
+        HBufC*       iBufferTmp;
+        TPtr         iBuffer;
+
+        /**
+        * Flag indicating if file is unicode.
+        */
+        TBool        iIsUnicode;
+
+        /**
+        * Pointer to file parser.
+        */
+		CStifFileParser* iFileParser;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // STIF_PARSER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifSectionParser.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,286 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CStifSectionParser.
+*
+*/
+
+#ifndef STIF_SECTION_PARSER_H
+#define STIF_SECTION_PARSER_H
+
+// INCLUDES
+#include <f32file.h>
+#include <e32std.h>
+#include <e32base.h>
+#include "StifItemParser.h"
+
+// CONSTANTS
+// Indicates is tag included in returned value.
+enum TTagToReturnValue
+    {
+    ETag,   // Return value includes the tag
+    ENoTag  // Return value include no tag
+    };
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CStifItemParser;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CStifSectionParser is a STIF Test Framework StifParser class.
+// Class contains a configuration file parsing operations.
+
+class CStifSectionParser 
+        :public CBase
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        static CStifSectionParser* NewL( const TInt aLength );
+
+        /**
+        * Destructor.
+        */
+        ~CStifSectionParser();
+
+    public:     // New functions
+        
+        /**
+        * Parses a line for items parsing with a tag.
+        * Returns a CStifItemParser object.
+        * If start tag is empty the parsing starts beging of the section.
+        * TTagToReturnValue indicates will also the aTag value (if exist)
+        * include to the returned object(For default the tag will be added).
+        */
+        IMPORT_C CStifItemParser* GetItemLineL( const TDesC& aTag,
+                                TTagToReturnValue aTagIndicator = ETag );
+
+        /**
+        * Parses a next line for items parsing.
+        * Returns a CStifItemParser object.
+        */
+        IMPORT_C CStifItemParser* GetNextItemLineL();
+
+        /**
+        * Parses a next line for items parsing with a tag.
+        * Returns a CStifItemParser object.
+        * If start tag is empty the parsing starts beging of the section.
+        * TTagToReturnValue indicates will also the aTag value (if exist)
+        * include to the returned object(For default the tag will be added).
+        */
+        IMPORT_C CStifItemParser* GetNextItemLineL( const TDesC& aTag,
+                                TTagToReturnValue aTagIndicator = ETag );
+
+        /**
+        * Parses a sub sections from the main section with a start and with
+        * a end tag.
+        * Returns a CStifSectionParser object.
+        * If start tag is empty the parsing starts beging of the section.
+        * If end tag is empty the parsing goes end of section.
+        * This method will parse next subsection after the earlier subsection
+        * if aSeeked parameter is not given.
+        * If configuration file includes several subsections with both start
+        * and end tags so aSeeked parameter seeks the required subsection. The
+        * aSeeked parameters indicates subsection that will be parsed.
+        */
+        IMPORT_C CStifSectionParser* SubSectionL( const TDesC& aStartTag,
+                                                    const TDesC& aEndTag,
+                                                    TInt aSeeked = 1 );
+
+        /**
+        * Parses a next subsections from the main section with a start and with
+        * a end tag.
+        * Returns a CStifSectionParser object.
+        * If start tag is empty the parsing starts beging of the section.
+        * If end tag is empty the parsing goes end of section.
+        * This method will parse next subsection after the earlier subsection
+        * if aSeeked parameter is not given.
+        * If configuration file includes several subsections with both start
+        * and end tags so aSeeked parameter seeks the required subsection. The
+        * aSeeked parameters indicates subsection that will be parsed.
+        */        
+        IMPORT_C CStifSectionParser* NextSubSectionL( const TDesC& aStartTag,
+                                                const TDesC& aEndTag,
+                                                TInt aSeeked = 1 );
+
+        /**
+        * Get a line from section with a tag.
+        * Returns an error code and a reference to the parsed line.
+        * If start tag is empty the parsing starts beging of the section.
+        * TTagToReturnValue indicates will also the aTag value(if exist)
+        * include to the aLine reference(For default the tag will be added).
+        */
+        IMPORT_C TInt GetLine( const TDesC& aTag, TPtrC& aLine, 
+                                TTagToReturnValue aTagIndicator = ETag );
+
+        /**
+        * Get next line.
+        * Returns an error code and a reference to the parsed line.
+        */
+        IMPORT_C TInt GetNextLine( TPtrC& aLine );
+
+        /**
+        * Get next line with tag.
+        * Returns an error code and a reference to the parsed line.
+        * If start tag is empty the parsing starts beging of the section.
+        * TTagToReturnValue indicates will also the aTag value(if exist)
+        * include to the aLine reference(For default the tag will be added).
+        */
+        IMPORT_C TInt GetNextLine( const TDesC& aTag, TPtrC& aLine,
+                                TTagToReturnValue aTagIndicator = ETag );
+
+        /**
+        * Get current position.
+        * Returns current parsing position, which
+        * can be used as parameter for SetPosition afterwards to go back
+        * to old parsing position.
+        */
+        IMPORT_C TInt GetPosition();
+        
+        /**
+        * Set position.
+        * Returns a Symbian OS error code. aPos indicates the position to 
+        * which section parser should go.  
+        * SetPosition can be used to set parsing position, e.g. to rewind 
+        * back to some old position retrieved with GetPosition.
+        */
+        IMPORT_C TInt SetPosition( TInt aPos );        
+        
+        /**
+        * Create a section.
+        */
+        void SetData( TPtr aData,
+                        TInt aStartPos, 
+                        TInt aLength );
+
+        /**
+        * Returns a current section.
+        */
+        const TPtrC Des();
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CStifSectionParser( const TInt aLength );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+        /**
+        * Generic start and end position parser for given data.
+        * Returns an error code.
+        */
+        TInt ParseStartAndEndPos(   TPtrC aSection,
+                                    const TDesC& aStartTag,
+                                    TTagToReturnValue aTagIndicator,
+                                    TInt& aStartPos,
+                                    TInt& aEndPos,
+                                    TInt& aLength );
+                                    
+        /**
+        * Generic search for end-of-line.
+        * Returns position before linefeed and 
+        * lex is posotioned to the beginning of next line.
+        */
+        TInt GotoEndOfLine( TLex& lex );                            
+
+        /**
+        * Substracts line from the begining of selected text.
+        */
+        TPtrC SubstractLine( const TPtrC& aText );
+		
+		/**
+		* Searches for selected tag in a text.
+		*/		
+        TInt FindTag( const TDesC& aText, const TDesC& aTag, TInt& aStartPos, TInt& aEndPos );
+        
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+        /**
+        * Parsed section with SectionL() or SubSectionL() method.
+        */
+        TPtr                iSection;
+
+        /**
+        * Section length definitions.
+        */
+        HBufC*              iHBufferSection;
+
+        /**
+        * Section length
+        */
+        TInt                iLength;
+
+        /**
+        * Indicates position where start the parsing.
+        */
+        TInt                iSkipAndMarkPos;
+
+        /**
+        * For line and item line parsing. Indicator is GetLine() or
+        * GetItemLineL() method used.
+        */
+        TBool               iLineIndicator;
+
+        /**
+        * Indicates position where we are currently(subsection).
+        */
+        TInt                iSubOffset;
+
+    public:     // Friend classes
+
+        /**
+        * For testing operations to get length information.
+        */
+        friend class CTestParser;
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#endif      // STIF_SECTION_PARSER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifTFwIf.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,279 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CStifTFwIf.
+*
+*/
+
+#ifndef STIF_TFW_IF_H
+#define STIF_TFW_IF_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifTestModule.h>
+#include <StifTestInterface.h>
+
+
+// CONSTANTS
+// None
+
+// MACROS
+// Hardcoded deviceid used if DevId function is not overridden
+const TUint16 KDefaultDevId = 0x0001;
+
+// DATA TYPES
+    
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CStifTFw;
+
+// CLASS DECLARATION
+// Information of test case
+class CTestInfo
+    :public CBase
+    {
+    public:
+        IMPORT_C static CTestInfo* NewL();
+        ~CTestInfo();
+        
+    public:
+        const TDesC& ModuleName () const { return iModuleName; };
+        TInt SetModuleName ( const TDesC& aModuleName );
+        const TDesC& TestCaseTitle() const { return iTitle; };
+        TInt SetTestCaseTitle ( const TDesC& aTitle );
+        const TDesC& TestCaseFile() const { return iTestCaseFile; };
+        TInt SetTestCaseFile ( const TDesC& aTestCaseFile );
+        TInt TestCaseNum() const { return iCaseNumber; };
+        void SetTestCaseNumber ( TInt aTestCaseNumber )
+                                { iCaseNumber = aTestCaseNumber; };
+        TInt Priority() const { return iPriority; };
+        void SetPriority ( TInt aPriority )
+                                { iPriority = aPriority; };
+        TTimeIntervalMicroSeconds Timeout() const { return iTimeout; };
+        void SetTimeout ( const TTimeIntervalMicroSeconds& aTimeout )
+                                { iTimeout = aTimeout; };
+        TInt ExpectedResult() const { return iExpectedResult; };
+        void CopyL( const CTestInfo& aTestInfo );
+        TBool operator==(const CTestInfo& aTestInfo) const;
+                                    
+    private:
+        CTestInfo();
+        void ConstructL();
+        CTestInfo( const CTestInfo& /*aTestInfo*/ ){};
+        CTestInfo& operator= ( const CTestInfo& );
+        
+    private:
+        TInt iCaseNumber;
+        TInt iExpectedResult;
+        TTimeIntervalMicroSeconds iTimeout;
+        TInt iPriority; 
+        TPtrC iModuleName;
+        HBufC* iModuleNameBuf;
+        TPtrC iTitle;
+        HBufC* iTitleBuf;
+        TPtrC iTestCaseFile;
+        HBufC* iTestCaseFileBuf;
+    
+    };
+    
+// CLASS DECLARATION
+
+// CStifTFwIf is the main class of STIF Test Framework Interface
+class CStifTFwIf 
+    :public CBase 
+    {
+    public: // Enumerations
+
+    protected: // Enumerations
+        
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        
+        /**
+        * Destructor.
+        */
+        virtual IMPORT_C ~CStifTFwIf();
+
+    protected: // Functions that can be called from derived class
+
+        /**
+        * Used to open TestFramework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt Open( TDesC& aTestFrameworkIni = (TDesC&) KNullDesC() );
+
+        /**
+        * Used to close TestFramework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt Close();
+
+        /**
+        * Used to set attributes for test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt SetAttribute( TAttribute aAttribute,
+                                    const TDesC& aValue );
+
+        /**
+        * Receive message from ATS.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt AtsReceive( const TDesC& aMessage );
+
+        /**
+        * Used to add test module to test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt AddTestModule( TDesC& aModuleName, 
+                            TDesC& aIniFile = (TDesC&) KNullDesC() );
+
+        /**
+        * Used to remove test module to test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt RemoveTestModule( TDesC& aModuleName );
+
+        /**
+        * Used to add test case file for test module.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt AddTestCaseFile( TDesC& aModuleName,
+                              TDesC& aCaseFile );
+
+        /**
+        * Used to remove test case file from test module.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt RemoveTestCaseFile( TDesC& aModuleName,
+                                 TDesC& aCaseFile );
+
+        /**
+        * Get testcases from test modules. Returns test case information 
+        * in aTestinfo.
+        * Test module name and test case file can be used to limit the 
+        * set of test cases returned.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt GetTestCases( RPointerArray<CTestInfo>& aTestInfo,
+                           TDesC& aTestModule = (TDesC&) KNullDesC(),
+                           TDesC& aTestCaseFile = (TDesC&) KNullDesC() );
+
+        /**
+        * Start selected test case identified with CTestInfo.
+        * Return TestId, which is handle used in subsequent 
+        * test case execution control.
+        *
+        * Returns Symbian OS error code.
+        */
+
+        IMPORT_C TInt StartTestCase( TInt& aTestId,
+                            const CTestInfo& aTestInfo );
+
+        /**
+        * Cancel test case execution. TestCompleted() will be called 
+        * with aTestExecutionResult set to KErrCancel.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt CancelTestCase( TInt aTestId );
+
+        /**
+        * Pause test case execution.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt PauseTestCase( TInt aTestId );
+
+        /**
+        * Resume test case execution.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt ResumeTestCase( TInt aTestId );
+
+        /**
+        * C++ default constructor.
+        */
+        IMPORT_C CStifTFwIf();
+
+    protected: // Functions that the derived class may implement.
+
+        /**
+        * Function is called when test execution is finished 
+        * with information of test case, result of test case execution 
+        * and test case result.
+        */
+        virtual void TestCompleted( TInt aTestId,
+                                    TInt aTestExecutionResult,
+                                    TTestResult& aTestResult )=0;
+
+        /**
+        * Function is called when test case prints.
+        */
+        virtual void Print( TInt /*aTestId*/,
+                            TTestProgress& /*iProgress*/ ){};
+
+        /**
+        * Send message to ATS.
+        */                            
+        virtual void AtsSend( const TDesC& /*aMessage*/ ){};
+     
+        /**
+        * Get device identifier, should be overridden to make them 
+        * unique among slaves. 
+        * Returns default value for every slave otherwise.
+        */
+        virtual TUint16 DevId(){ return KDefaultDevId; };      
+        
+        /**
+        * Reboot indication. 
+        * After this function returns, reboot is done
+        * by test module or STIF TF.
+        */                            
+        virtual void GoingToDoReset(){};  
+        
+    private:
+
+    public: // Data
+    
+    protected: // Data
+        
+    private: // Data
+        
+        CStifTFw*   iStifTFw;
+
+    public: // Friend classes
+        
+    protected: // Friend classes
+
+    private: // Friend classes
+        friend class CStifTFw;
+    };
+
+#endif      // STIF_TFW_IF_H 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifTFwIfProt.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,422 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CStifTFwIfProt.
+*
+*/
+
+#ifndef STIF_TFW_IF_PROT_H 
+#define STIF_TFW_IF_PROT_H 
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifTestEventInterface.h>
+#include <StifParser.h>
+
+// CONSTANTS
+// Protocol identifier length
+const TInt KProtocolIdLength=8;
+// Default allocation size for message created with CreateL
+const TInt KDefaultMsgSize=0x200;
+// Maximum length for value added to type-value parameter
+const TInt KMaxValueLength=12;
+
+// MACROS
+// Macros for identifier manipulation
+#define DEVID(x) ((TUint16)( ( 0xffff0000 & ((TUint32)(x)) ) >> 16 ))
+#define TESTID(x) ((TUint16)( 0x0000ffff & ((TUint32)(x)) ))
+#define SETID(d,t) ((TUint32)(( ( 0x0000ffff & ((TUint32)(d)) ) << 16 )|( 0x0000ffff & ((TUint32)(t)) )))
+#define GETDEVID(x) ((TUint32)( 0xffff0000 & ((TUint32)(x)) ))
+
+// DATA TYPES
+typedef TPtrC (*KeywordFunc)( TInt aKeyword );
+// typedef TBuf<KDefaultMessageSize> TRemoteProtMsg;
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+
+// CStifTFwIfProt is the control protocol interface
+class CStifTFwIfProt
+        :public CBase
+    {
+    public: // Enumerations
+
+        // Message type
+        enum TMsgType
+            {
+            EMsgReserve,
+            EMsgRelease,
+            EMsgRemote,
+            EMsgResponse,
+            };
+            
+        // Command types
+        enum TCmdType
+            {
+            ECmdRun,
+            ECmdPause,
+            ECmdResume,
+            ECmdCancel,
+            ECmdRequest,
+            ECmdRelease,
+            ECmdSendReceive,
+            ECmdSetEvent,
+            ECmdUnsetEvent,
+            
+            ECmdUnknown,
+            };
+            
+        // Remote device type
+        enum TRemoteType
+            {
+            ERemotePhone,
+            //ERemoteCallBox, ...
+            
+            ERemoteUnknown,
+            };
+            
+        // Run parameters
+        enum TRunParams
+            {
+            ERunModule,
+            ERunInifile,
+            ERunTestcasefile,
+            ERunTestcasenum,                        
+            ERunTitle,
+            };
+            
+        // Response parameters
+        enum TRespParam
+            {
+            ERespResult,
+            };
+     
+        // Run status
+        enum TRunStatus
+            {
+            ERunStarted,
+            ERunError,
+            ERunReady,
+            };
+            
+        // Run status parameters
+        enum TRunStatusParams
+            {
+            ERunResult,
+            ERunCategory,
+            };
+            
+        // Execution result category
+        enum TResultCategory
+            {
+            EResultNormal = 0,
+            EResultPanic,
+            EResultException,
+            EResultTimeout,
+            EResultLeave,
+            };
+            
+        // Event status
+        enum TEventStatus
+            {
+            EEventActive,
+            EEventSet,
+            EEventError,
+            }; 
+            
+        // Event status
+        enum TEventStatusParams
+            {
+            EEventResult,
+            EEventType,
+            };           
+                                    
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+       
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CStifTFwIfProt* NewL();
+        
+        /**
+        * Destructor.
+        */
+        IMPORT_C virtual ~CStifTFwIfProt();
+
+    public: // New functions
+    
+        /*
+        * Get message handle
+        */ 
+        virtual const TDesC& Message(){ return iMessage; };
+        
+        /**
+        * Set message.
+        */
+        IMPORT_C TInt SetL( const TDesC& aMessage );
+
+        /**
+        * Create message.
+        */
+        IMPORT_C void CreateL( TInt aLength = KDefaultMsgSize );
+        
+        /**
+        * Append string to message.
+        */
+        IMPORT_C TInt Append( const TDesC& aStr );
+        
+        /**
+        * Append hexadecimal protocol identifier to message.
+        */
+        IMPORT_C TInt AppendId( TUint32 aId );
+
+        /**
+        * Append keyword string to message.
+        */
+        IMPORT_C TInt Append( KeywordFunc aFunc, TInt aKeyword );
+
+        /**
+        * Append keyword type-value string to message.
+        */
+        IMPORT_C TInt Append( KeywordFunc aFunc, TInt aKeyword, TInt aValue );
+        
+        /**
+        * Append keyword type-value string to message.
+        */
+        IMPORT_C TInt Append( KeywordFunc aFunc, 
+                              TInt aKeyword, 
+                              const TDesC& aStr );
+        
+        /**
+        * Append keyword type-value string to message.
+        */
+        IMPORT_C TInt Append( KeywordFunc aFunc, 
+                              TInt aKeyword, 
+                              KeywordFunc aValueFunc, 
+                              TInt aValue );
+        
+        /**
+        * Get protocol source identifier.
+        */
+        IMPORT_C TUint32 SrcId();
+
+        /**
+        * Get protocol source device identifier.
+        */
+        IMPORT_C TUint16 SrcDevId();
+
+        /**
+        * Get protocol source test identifier.
+        */
+        IMPORT_C TUint16 SrcTestId();
+
+        /**
+        * Get protocol destination identifier.
+        */
+        IMPORT_C TUint32 DstId();
+        
+        /**
+        * Get protocol destination device identifier.
+        */
+        IMPORT_C TUint16 DstDevId();
+        
+        /**
+        * Get protocol destination test identifier.
+        */
+        IMPORT_C TUint16 DstTestId();
+        
+        /**
+        * Set protocol source identifier.
+        */
+        IMPORT_C TInt SetSrcId( TUint32 aSrcId );
+            
+        /**
+        * Set protocol destination identifier.
+        */
+        IMPORT_C TInt SetDstId( TUint32 aDstId );
+
+        /**
+        * Set message type.
+        */
+        IMPORT_C TInt SetMsgType( TMsgType aMsgType );
+        
+        /**
+        * Set response type.
+        */
+        IMPORT_C TInt SetRespType( TMsgType aRespType );
+
+        /**
+        * Set message type.
+        */
+        IMPORT_C TInt SetCmdType( TCmdType aCmdType );
+
+        /*
+        * String containers.
+        */
+        IMPORT_C static TPtrC MsgType( TInt aKeyword );
+        
+        IMPORT_C static TPtrC CmdType( TInt aKeyword );
+        
+        IMPORT_C static TPtrC RemoteType( TInt aKeyword );
+
+        IMPORT_C static TPtrC RunParams( TInt aKeyword );
+
+        IMPORT_C static TPtrC RunStatus( TInt aKeyword );
+
+        IMPORT_C static TPtrC RunStatusParams( TInt aKeyword );
+
+        IMPORT_C static TPtrC ResultCategory( TInt aKeyword );
+
+        IMPORT_C static TPtrC EventStatus( TInt aKeyword );
+
+        IMPORT_C static TPtrC EventStatusParams( TInt aKeyword );
+
+        IMPORT_C static TPtrC EventType( TInt aKeyword );
+        
+        IMPORT_C static TPtrC RespParam( TInt aKeyword );
+        
+    public: // Functions from base classes
+
+        /**
+        * From <base_class member_description.
+        */
+        //<type member_function( type arg1 );>
+        
+    protected:  // New functions
+        
+        /**
+        * <member_description.>
+        */
+        //<type member_function( type arg1 );>
+
+    protected:  // Functions from base classes
+        
+        /**
+        * From <base_class member_description>
+        */
+        //<type member_function();>
+
+    private:
+        /**
+        * C++ default constructor.
+        */
+        CStifTFwIfProt();
+        
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+        
+        /**
+        * Parsing functions.
+        */
+        TInt ParseMessageL();
+        
+        void ParseHeaderL();
+        
+        void ParseReserveL();
+        
+        void ParseRemoteL();
+
+        void ParseResponseL();     
+        
+        void ParseCmdResponseL();   
+
+        static TInt Parse( TDesC& aKeyword, KeywordFunc aFunc );
+        
+        static TInt ParseOptArg( const TDesC& aOptArg, TPtrC& aArg, TPtrC& aVal );
+        
+	public:   //Data
+	    // Message type
+        TMsgType            iMsgType;
+        // Remote type
+        TRemoteType         iRemoteType;
+        // Response request type
+        TMsgType            iRespType;
+        // Remote command type (valid only if TMsgType is EMsgRemote)
+        TCmdType            iCmdType;
+        TPtrC               iCmdDes;
+        
+        // Run parameters (valid only if run command)
+        // Test module name
+        TPtrC               iModule;
+        // Test module initialization file
+        TPtrC               iIniFile;
+        // Test module initialization file
+        TPtrC               iTestCaseFile;
+        // Test case number
+        TInt                iTestCaseNumber;
+        // Test case title
+        TPtrC               iTitle;
+        
+        // Event parameters
+        // Event name
+        TPtrC               iEventName;
+      
+        // Result from request or command
+        TInt            iResult;
+
+        // Response status 
+        union 
+            {
+            TRunStatus      iRunStatus;
+            TEventStatus    iEventStatus;
+            };
+        // Result category
+        TResultCategory     iResultCategory;
+        // Event response parameters
+        // Event type
+        TEventIf::TEventType    iEventType;
+    
+	protected:  // Data
+        //<data_declaration;>
+
+    private:    // Data
+        // Message buffer
+        HBufC*              iMessageBuf;
+        // Message ptr
+        TPtr                iMessage;     
+        
+        // Message parser
+        CStifItemParser*    iItem;
+        
+        // SrcId
+        TInt32              iSrcId;
+        // DstId
+        TInt32              iDstId;
+        
+    public:     // Friend classes
+        //<friend_class_declaration;>
+
+    protected:  // Friend classes
+        //<friend_class_declaration;>
+
+    private:    // Friend classes
+        //<friend_class_declaration;>
+        
+    };
+
+#endif      // STIF_TFW_IF_PROT_H 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifTestEventInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,184 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the event 
+* interface.
+*
+*/
+
+#ifndef TESTEVENTINTERFACE_H
+#define TESTEVENTINTERFACE_H
+
+//  INCLUDES
+#include <e32std.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Interface class for the event system.
+class TEventIf
+    {
+    public: // Enumerations
+        /**
+        * Event request types.
+        */
+        enum TReqType
+            {
+            // The following can be used by the test module
+            EReqEvent = 1,
+            EWaitEvent,
+            ERelEvent,
+            ESetEvent,
+            EUnsetEvent,
+            
+            // The rest are special
+            // Not used by the test module
+            EEnable,
+            ESetWaitPending,
+            ECmdError,
+            ECancelWait,
+            };
+        
+        /**
+        * Event types.
+        */
+        enum TEventType
+            {
+            EIndication,
+            EState,
+            };
+            
+    private: // Enumerations
+        
+    public:  // Constructors and destructor
+
+        /**
+        * C++ constructor with params.
+        */
+        TEventIf( TReqType aType = EEnable, 
+                  const TName& aName = KNullDesC(), 
+                  TEventType aEventType = EIndication ) 
+            { iType = aType; iName = aName; iEventType = aEventType; }
+
+    public: // New functions
+        
+        /**
+        * Get request type.
+        */        
+        inline TReqType Type() const { return iType; }
+         
+        /**
+        * Get event name.
+        */        
+        inline const TName& Name() const { return iName; } 
+        
+        /**
+        * Get event type.
+        */        
+        inline TEventType EventType() const { return iEventType; } 
+        
+        /**
+        * Set request type.
+        */        
+        inline void SetType( TReqType aType ){ iType = aType; } 
+        
+        /**
+        * Set event name.
+        */        
+        inline void SetName( const TName& aName ){ iName = aName; }
+        
+        /**
+        * Set event to state event.
+        */        
+        inline void SetEventType( TEventType aEventType )
+            { iEventType = aEventType; }
+        
+        /**
+        * Set request type and event name.
+        */        
+        inline void Set( TReqType aType, const TName& aName )
+            { iType = aType; iName = aName; } 
+        
+        /**
+        * Set request type, event name and event type.
+        */        
+        inline void Set( TReqType aType, 
+                         const TName& aName, 
+                         TEventType aEventType )
+            { iType = aType; iName = aName; iEventType = aEventType; } 
+        
+        /**
+        * Copy data from existing TEventIf (or derived class).
+        */
+        inline void Copy( const TEventIf& aEvent) 
+            { iType = aEvent.iType; 
+            iName = aEvent.iName; 
+            iEventType = aEvent.iEventType; } 
+          
+    public: // Functions from base classes
+        
+    protected:  // New functions
+        
+    protected:  // Functions from base classes
+        
+    private:
+        
+    public:   //Data
+        
+    protected:  // Data
+        /**
+        * Request type.
+        */
+        TReqType iType; 
+        
+        /**
+        * Event name (must be unique).
+        */
+        TName iName;     
+        
+        /**
+        * Event type.
+        */
+        TEventType iEventType;
+        
+    private:    // Data
+        
+    public:     // Friend classes
+        
+    protected:  // Friend classes
+        
+    private:    // Friend classes
+        
+    };
+    
+// Packaged TEventIf
+typedef TPckg<TEventIf> TEventIfPckg;
+ 
+#endif      // TESTEVENTINTERFACE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifTestInterface.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,355 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* TestInterface.
+*
+*/
+
+#ifndef TEST_INTERFACE_H
+#define TEST_INTERFACE_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifTestModule.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+
+// This defines drive letters that is available in STIF TF.
+//@spe IMPORT_C const TChar StifDriveLetters( TInt aDriveNumber, TInt& aCount );
+
+// This works and used only in EKA2 environment and used from STIF
+// TestFramework internally.
+// Executable module uses defined capabilities(PlatSec's Capability model)
+// to start session. Function for starting the TestServer and
+// Testmodule/TestClass.
+IMPORT_C TInt StartSession();
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+const TInt KMaxStifInfoName = 0x10; 
+typedef TBuf<KMaxStifInfoName> TStifInfoName;
+
+// DESCRIPTION
+// TTestInfo defines the information for test case and Test Module.
+class TTestInfo 
+    {
+    public:
+        IMPORT_C TTestInfo();
+    public:
+        // The name of Test Module.
+        TName iModuleName;
+        // Test case info for test case execution.
+        TTestCaseInfo iTestCaseInfo;
+        // Config file to be used.
+        TFileName iConfig;
+    };
+    
+// Packaged TTestInfo
+typedef TPckg<TTestInfo> TTestInfoPckg;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TFullTestResult defines the full test case result information.
+class TFullTestResult
+    {
+    public:
+        IMPORT_C TFullTestResult();
+
+        enum TCaseExecutionResult
+        {
+            ECaseOngoing,
+            ECaseExecuted,
+            ECaseCancelled,
+            ECaseErrorFromModule,
+            ECaseLeave,
+            ECasePanic,
+            ECaseException,
+            ECaseTimeout,
+            ECaseSuicided,
+        };
+
+    public:
+        // Test case result.
+        TTestResult iTestResult;
+        // Timestamp when test case was started.
+        TTime iStartTime;
+        // Timestamp when test case was ended.
+        TTime iEndTime;
+        
+        // Test result type
+        TCaseExecutionResult iCaseExecutionResultType;      
+        // Test result code
+        TInt iCaseExecutionResultCode;
+    };
+
+// Packaged TFullTestResult
+typedef TPckg<TFullTestResult> TFullTestResultPckg;
+
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TTestProgress defines the progress information from Test Module.
+class TTestProgress 
+    {
+    public:
+        IMPORT_C TTestProgress();
+    public:
+        // "Priority" of the progress information.
+        TInt iPosition;
+        // Description of the data to be printed.
+        TStifInfoName iDescription;
+        // The actual progress information.
+        TName iText;
+    };
+
+// Packaged TTestProgress
+typedef TPckg<TTestProgress> TTestProgressPckg;
+
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TErrorNotification defines the error notifications
+class TErrorNotification 
+    {
+    public:
+        IMPORT_C TErrorNotification();
+    public:
+        // Error priority
+        TInt iPriority;
+        // Module reporting error
+        TStifInfoName iModule;
+        // The actual error information.
+        TName iText;
+    };
+
+// Attributes that can be changed with SetAttribute
+enum TAttribute
+    {
+    ELogPath,           // Log file path
+    ERebootPath,        // Reboot path definition
+    ERebootFilename,    // Reboot filename definition
+    EStifMeasurementOn,  // STIF's Measurement enable
+    EStifMeasurementOff // STIF's Measurement disable
+    };
+    
+// Packaged TErrorNotification
+typedef TPckg<TErrorNotification> TErrorNotificationPckg;
+
+// Different STIF internal commands.
+enum TStifCommand
+    {
+    EStifCmdReceive,
+    EStifCmdSend,
+    EStifCmdReboot,
+    EStifCmdStoreState,
+    EStifCmdGetStoredState,
+    EStifCmdRebootProceed,
+    EStifCmdReceiveCancel,
+    EStifCmdMeasurement,
+    };
+typedef TPckg<TStifCommand> TStifCommandPckg;
+
+// Class for Reboot parameter
+class TRebootParams
+    {
+    public:
+        CTestModuleIf::TRebootType aType;
+    };
+
+// Class for Reboot state parameters
+class TRebootStateParams
+    {
+    public:
+        TInt aCode;
+        TName aName;
+    };
+
+// Class for Reboot stored parameters
+class TGetRebootStoredParams
+    {
+    public:
+        TInt aCode;
+        TName aName;
+    };
+
+// Class for Reboot stored parameters(references)
+class TGetRebootStoredParamsRef
+    {
+    public:
+        TGetRebootStoredParamsRef( 
+            TInt& aCode, TName& aName ):iCode(aCode),iName(aName){};
+    public:
+        TInt& iCode;
+        TName& iName;
+    };
+
+// Class for measurement stored parameters
+class TGetMeasurementOptions
+    {
+    public:
+        TInt iOptions;
+    };
+
+// Class for measurement stored parameters(options)
+class TGetMeasurementOptionsRef
+    {
+    public:
+        TGetMeasurementOptionsRef( TInt& aOptions ): iOptions(aOptions){};
+    public:
+        TInt& iOptions;
+    };
+
+// This class offer generic attribute for passing client-server interface
+union TParams
+    {
+    TDes*                       aRemoteMsgRef;
+    const TDesC*                aRemoteMsgConstRef;
+    TRebootParams*              aRebootType;
+    TRebootStateParams*         aRebootState;
+    TGetRebootStoredParamsRef*  aRebootStoredRef;
+    TGetMeasurementOptionsRef*  aMeasurementOption;
+    };
+
+// Packaged TRebootParams
+typedef TPckg<TRebootParams> TRebootParamsPckg;
+
+// Packaged TRebootStateParams
+typedef TPckg<TRebootStateParams> TRebootStateParamsPckg;
+
+// Packaged TGetRebootStoredParams
+typedef TPckg<TGetRebootStoredParams> TGetRebootStoredParamsPckg;
+
+// Packaged TGetMeasurementParams
+typedef TPckg<TGetMeasurementOptions> TGetMeasurementOptionsPckg;
+
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Base class for test measurement modules. Measurement modules implements
+// measurerement operations.
+NONSHARABLE_CLASS( CSTIFTestMeasurementImplementation ) : public CBase
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+    public: // New functions
+
+        /**
+        * Pure virtual measurement start command.
+        * Start method's implementation is in measurement module.
+        */
+        virtual TInt Start( ) = 0;
+
+        /**
+        * Pure virtual measurement stop command.
+        * Stop method's implementation is in measurement module.
+        */
+        virtual TInt Stop( ) = 0;
+
+       /**
+        * Pure virtual measurement stop command.
+        * Stop method's implementation is in measurement module.
+        */
+        virtual CSTIFTestMeasurement::TSTIFMeasurementType MeasurementType() = 0;
+
+
+    public: // Functions from base classes
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+
+    public: //Data
+
+    protected: // Data
+
+    private: // Data
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+
+    };
+
+// STIF utility class
+class TStifUtil
+	{
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+    public: // New functions    
+		/**
+		 * Checks if file path contains drive letter. If not file is serched
+		 * on all drives and first hit is added to file name.
+		 */
+    	IMPORT_C static void CorrectFilePathL( TDes& aFilePath );
+    	
+    	/**
+    	 * Method used by both STIF and STIF UI to retrieve version of STIF  
+    	 */
+    	IMPORT_C static void STIFVersion(TInt& aMajorV, TInt& aMinorV, TInt& aBuildV, TDes& aRelDate);
+    
+    public: // Functions from base classes
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+
+    public: //Data
+
+    protected: // Data
+
+    private: // Data
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+	
+	};
+    
+    
+#endif // TEST_INTERFACE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifTestInterference.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,221 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the STIF test
+* interference module.
+*
+*/
+
+#ifndef STIFTESTINTERFERENCE_H
+#define STIFTESTINTERFERENCE_H
+
+// INCLUDES
+#include "StifTestModule.h"
+#include <StifLogger.h>
+#include <e32std.h>
+#include <e32base.h>
+#include <e32svr.h>
+
+// CONSTANTS
+//const ?type ?constant_var = ?constant;
+
+// MACROS
+//#define ?macro ?macro_def
+
+// DATA TYPES
+//enum ?declaration
+//typedef ?declaration
+//extern ?data_type;
+
+// FUNCTION PROTOTYPES
+//?type ?function_name(?arg_list);
+
+// FORWARD DECLARATIONS
+//class ?FORWARD_CLASSNAME;
+
+// CLASS DECLARATION
+
+/**
+*  This a MSTIFTestInterference class.
+*  MSTIFTestInterference is an interface class. Purpose is to 
+*  avoid multi heritance in subclasses.
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+NONSHARABLE_CLASS( MSTIFTestInterference )
+    {
+    public:     // Enumerations 
+
+    // Way of using test interference
+    enum TStifTestInterferenceCategory
+        {
+        EActiveObject,      // Test interference using active object
+        EThread,            // Test interference using thread
+        };
+
+    // Type of the test interference
+    enum TStifTestInterferenceType
+        {
+        ENone,                    // No test interference
+        ECpuLoad,                 // with CPU load
+        EFileSystemReadC,         // with file system load, read from C-drive
+        EFileSystemReadD,         // with file system load, read from D-drive
+        EFileSystemReadE,         // with file system load, read from E-drive
+        EFileSystemReadZ,         // with file system load, read from Z-drive
+        EFileSystemWriteC,        // with file system load, write from C-drive
+        EFileSystemWriteD,        // with file system load, write from D-drive
+        EFileSystemWriteE,        // with file system load, write from E-drive
+        EFileSystemFillAndEmptyC, // with file system load, fill and empty from
+                                  // C-drive
+        EFileSystemFillAndEmptyD, // with file system load, fill and empty from
+                                  // D-drive
+        EFileSystemFillAndEmptyE, // with file system load, fill and empty from
+                                  // E-drive
+
+        ENoneMicroSeconds,                    // No test interference
+        ECpuLoadMicroSeconds,                 // with CPU load
+        EFileSystemReadCMicroSeconds,         // with file system load, read from C-drive
+        EFileSystemReadDMicroSeconds,         // with file system load, read from D-drive
+        EFileSystemReadEMicroSeconds,         // with file system load, read from E-drive
+        EFileSystemReadZMicroSeconds,         // with file system load, read from Z-drive
+        EFileSystemWriteCMicroSeconds,        // with file system load, write from C-drive
+        EFileSystemWriteDMicroSeconds,        // with file system load, write from D-drive
+        EFileSystemWriteEMicroSeconds,        // with file system load, write from E-drive
+        EFileSystemFillAndEmptyCMicroSeconds, // with file system load, fill and empty from
+                                  			  // C-drive
+        EFileSystemFillAndEmptyDMicroSeconds, // with file system load, fill and empty from
+                                  			  // D-drive
+        EFileSystemFillAndEmptyEMicroSeconds  // with file system load, fill and empty from
+                                  			  // E-drive
+        };
+
+    public:  // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        * @param: aTestModuleBase: CTestModuleBase object for get test
+                  interference handle to STIF's side(Used if test case panic so
+                  test interference thread can be kill by STIF). 
+        * @param: aCategory: Test interference category
+        * @return: MSTIFTestInterference object
+        */
+        IMPORT_C static MSTIFTestInterference* NewL( 
+                                CTestModuleBase* aTestModuleBase,
+                                TStifTestInterferenceCategory aCategory );
+
+        /**
+        * Destructor.
+        */
+        virtual ~MSTIFTestInterference();
+
+    public: // New functions
+
+        /**
+        * StartL method starts test interference.
+        * @param: aType: Test interference type. 
+        * @param: aIdleTime: Test interference idle time.
+        * @param: aActiveTime: Test interference active time.
+        * @return: Symbian error code.
+        */
+        virtual TInt StartL( TStifTestInterferenceType aType,
+                            TInt aIdleTime,
+                            TInt aActiveTime ) = 0;
+
+        /**
+        * Stop method stops test interference.
+        */
+        virtual TInt Stop() = 0;
+
+        /**
+        * Sets thread or active object priority. This should use before
+        * test interference is started otherwise error code will return.
+        *
+        * Thread priority can set during interference executions time. User
+        * should be sure that given value is acceptable, otherwise SetPriority
+        * panics.
+        *
+        * @param: aPriority: New priority for active object or thread
+        * @return: Symbian error code.
+        */
+        virtual TInt SetPriority( TInt aPriority ) = 0;
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        // Prohibit copy constructor if not deriving from CBase.
+        // ?classname( const ?classname& );
+        // Prohibit assigment operator if not deriving from CBase.
+        // ?classname& operator=( const ?classname& );
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+#endif      // STIFTESTINTERFERENCE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifTestModule.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,1217 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CTestModuleBase and CTestModuleIf classes. Test Module inherits 
+* the CTestModuleBase and uses the CTestModuleIf for printing 
+* to user interface and event system control.
+*
+* The initialization of this interface must be done from the Test Module Server with:
+* 	CTestModuleXXX *mod = new CTestModuleXXX;
+* 	RThread thread;
+* 	CTestModuleIf::NewL( this, (CTestModuleBase*) mod, thread.Id() );
+* 
+* CTestModuleIf is deleted by destructor of the CTestModuleBase. 
+*
+*/
+
+#ifndef TESTMODULE_H
+#define TESTMODULE_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include "StifCommand.h"
+
+// CONSTANTS
+
+// Define Old Test Module API version - API that doesn't support version of test module
+const TInt KOldTestModuleAPIMajor = 1;
+const TInt KOldTestModuleAPIMinor = 1;
+const TInt KOldTestModuleAPIBuild = 0;
+
+// Define Test Module API version
+const TInt KTestModuleAPIMajor = 1;
+const TInt KTestModuleAPIMinor = 2;
+const TInt KTestModuleAPIBuild = 0;
+const TInt KStifMaxResultDes = 128; // Maximum test result description length
+
+// Max array value for STIF macros allow result.
+const TInt KSTIFMacroResultArraySize = 10;
+
+// Test module def-file check when setting parameters.
+const TUint32 KStifTestModuleParameterChanged = 0xdeadbeef;
+
+// MACROS
+// Test result description. Maximum length is 128 characters.
+typedef TBuf<KStifMaxResultDes> TResultDes;
+
+// Macro for boolean.
+#ifdef TL
+    #pragma message( "============================================================" )
+    #pragma message( " TL macro is already defined, now using STIF TF's TL macro" )
+    #pragma message( "============================================================" )
+#undef TL
+#endif
+// Macro for integer and one expected result.
+#ifdef T1L
+    #pragma message( "==============================================================" )
+    #pragma message( " T1L macro is already defined, now using STIF TF's T1L macro" )
+    #pragma message( "==============================================================" )
+#undef T1L
+#endif
+// Macro for integer and two expected result.
+#ifdef T2L
+    #pragma message( "==============================================================" )
+    #pragma message( " T2L macro is already defined, now using STIF TF's T2L macro" )
+    #pragma message( "==============================================================" )
+#undef T2L
+#endif
+// Macro for integer and three expected result.
+#ifdef T3L
+    #pragma message( "==============================================================" )
+    #pragma message( " T3L macro is already defined, now using STIF TF's T3L macro" )
+    #pragma message( "==============================================================" )
+#undef T3L
+#endif
+// Macro for integer and four expected result.
+#ifdef T4L
+    #pragma message( "==============================================================" )
+    #pragma message( " T4L macro is already defined, now using STIF TF's T4L macro" )
+    #pragma message( "==============================================================" )
+#undef T4L
+#endif
+// Macro for integer and five expected result.
+#ifdef T5L
+    #pragma message( "==============================================================" )
+    #pragma message( " T5L macro is already defined, now using STIF TF's T5L macro" )
+    #pragma message( "==============================================================" )
+#undef T5L
+#endif
+
+// Macro for boolean. Recommended use with TestScripter's test class.
+#ifdef TAL
+    #pragma message( "==============================================================" )
+    #pragma message( " TAL macro is already defined, now using STIF TF's TAL macro" )
+    #pragma message( "==============================================================" )
+#undef TAL
+#endif
+// Macro for integer and one expected result. Recommended use with TestScripter's test
+// class.
+#ifdef TA1L
+    #pragma message( "================================================================" )
+    #pragma message( " TA1L macro is already defined, now using STIF TF's TA1L macro" )
+    #pragma message( "================================================================" )
+#undef TA1L
+#endif
+// Macro for integer and two expected result. Recommended use with TestScripter's test
+// class.
+#ifdef TA2L
+    #pragma message( "================================================================" )
+    #pragma message( " TA2L macro is already defined, now using STIF TF's TA2L macro" )
+    #pragma message( "================================================================" )
+#undef TA2L
+#endif
+// Macro for integer and three expected result. Recommended use with TestScripter's test
+// class.
+#ifdef TA3L
+    #pragma message( "================================================================" )
+    #pragma message( " TA3L macro is already defined, now using STIF TF's TA3L macro" )
+    #pragma message( "================================================================" )
+#undef TA3L
+#endif
+// Macro for integer and four expected result. Recommended use with TestScripter's test
+// class.
+#ifdef TA4L
+    #pragma message( "================================================================" )
+    #pragma message( " TA4L macro is already defined, now using STIF TF's TA4L macro" )
+    #pragma message( "================================================================" )
+#undef TA4L
+#endif
+// Macro for integer and five expected result. Recommended use with TestScripter's test
+// class.
+#ifdef TA5L
+    #pragma message( "================================================================" )
+    #pragma message( " TA5L macro is already defined, now using STIF TF's TA5L macro" )
+    #pragma message( "================================================================" )
+#undef TA5L
+#endif
+
+
+//  TL ========================================================================
+//  Macro for verify boolean value.
+//  Example for use, 1: TL( Open() == KErrNone );
+//                   1: TL( VerifyString1() == VerifyString2() );
+//                   2: TL( 6 <= 8 );
+//  ===========================================================================
+    #define TL( aIsTrue )\
+        if( (!(aIsTrue)) )\
+        { TestModuleIf().StifMacroError( (0), (TText8*)__FILE__, __FUNCTION__, __LINE__ );\
+        User::Leave( KErrArgument ); };
+
+//  T1L =======================================================================
+//  Macro for verify integer value from the expected 1 value.
+//  Example: T1L( Open(), KErrNone );
+//  ===========================================================================
+    #define T1L( aResult, aExpected1 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) ) )\
+            { TestModuleIf().StifMacroError(\
+                (1), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), (aExpected1) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+//  T2L =======================================================================
+//  Macro for verify integer value from the expected 1 and 2 values.
+//  Example for use: T1L( Open(), KErrNone, KErrAlreadyExists );
+//  ===========================================================================
+    #define T2L( aResult, aExpected1, aExpected2 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) && (result) != (aExpected2) ) )\
+            { TestModuleIf().StifMacroError(\
+                (2), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), (aExpected1), (aExpected2) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+//  T3L =======================================================================
+//  Macro for verify integer value from the expected 1, 2 and 3 values.
+//  Example for use: T1L( Open(), KErrNone, KErrAlreadyExists, KErrDiskFull );
+//  ===========================================================================
+    #define T3L( aResult, aExpected1, aExpected2, aExpected3 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) && (result) != (aExpected2) && (result) != (aExpected3) ) )\
+            { TestModuleIf().StifMacroError(\
+                (3), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), (aExpected1), (aExpected2), (aExpected3) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+//  T4L =======================================================================
+//  Macro for verify integer value from the expected 1, 2, 3 and 4 values.
+//  Example for use:
+//  T1L( Open(), KErrNone, KErrAlreadyExists, KErrDiskFull, KErrDisconnected );
+//  ===========================================================================
+    #define T4L( aResult, aExpected1, aExpected2, aExpected3, aExpected4 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) && \
+              (result) != (aExpected2) && \
+              (result) != (aExpected3) && \
+              (result) != (aExpected4) ) )\
+            { TestModuleIf().StifMacroError(\
+                (4), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), \
+                (aExpected1), (aExpected2), (aExpected3), (aExpected4) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+//  T5L =======================================================================
+//  Macro for verify integer value from the expected 1, 2, 3, 4 and 5 values.
+//  Example for use:
+//  T1L( Open(), KErrNone, KErrDied, KErrInUse, KErrDisconnected, KErrAbort );
+//  ===========================================================================
+    #define T5L( aResult, aExpected1, aExpected2, aExpected3, aExpected4, aExpected5 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) && \
+              (result) != (aExpected2) && \
+              (result) != (aExpected3) && \
+              (result) != (aExpected4) && \
+              (result) != (aExpected5) ) )\
+            { TestModuleIf().StifMacroError(\
+                (5), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), \
+                (aExpected1), (aExpected2), (aExpected3), (aExpected4), (aExpected5) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+
+//  TAL ========================================================================
+//  Macro for verify boolean value. 
+//  Recommended use with TestScripter's test class. Allowed result can be defined
+//  with 'allownextresult' and 'allowerrorcodes' keywords.
+//  Example for use, 1: TL( Open() == KErrNone );
+//                   1: TL( VerifyString1() == VerifyString2() );
+//                   2: TL( 6 <= 8 );
+//  =============================================================================
+    #define TAL( aIsTrue )\
+        if( ( !(aIsTrue) ) && TestModuleIf().CheckAllowResult( 0 /* = EFalse*/ ) )\
+            { TestModuleIf().StifMacroError( (0), (TText8*)__FILE__, __FUNCTION__, __LINE__ );\
+            User::Leave( KErrArgument ); };
+
+//  TA1L =======================================================================
+//  Macro for verify integer value from the expected 1 value. 
+//  Recommended use with TestScripter's test class. Allowed result can be defined
+//  with 'allownextresult' and 'allowerrorcodes' keywords.
+//  Example: T1L( Open(), KErrNone );
+//  =============================================================================
+    #define TA1L( aResult, aExpected1 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) ) && \
+               TestModuleIf().CheckAllowResult( result ) ) \
+            { TestModuleIf().StifMacroError(\
+                (1), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), (aExpected1) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+//  TA2L =======================================================================
+//  Macro for verify integer value from the expected 1 and 2 values.
+//  Recommended use with TestScripter's test class. Allowed result can be defined
+//  with 'allownextresult' and 'allowerrorcodes' keywords.
+//  Example for use: T1L( Open(), KErrNone, KErrAlreadyExists );
+//  =============================================================================
+    #define TA2L( aResult, aExpected1, aExpected2 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) && (result) != (aExpected2) ) && \
+               TestModuleIf().CheckAllowResult( result ) ) \
+            { TestModuleIf().StifMacroError(\
+                (2), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), (aExpected1), (aExpected2) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+//  TA3L =======================================================================
+//  Macro for verify integer value from the expected 1, 2 and 3 values. 
+//  Recommended use with TestScripter's test class. Allowed result can be defined
+//  with 'allownextresult' and 'allowerrorcodes' keywords.
+//  Example for use: T1L( Open(), KErrNone, KErrAlreadyExists, KErrDiskFull );
+//  =============================================================================
+    #define TA3L( aResult, aExpected1, aExpected2, aExpected3 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) && (result) != (aExpected2) && (result) != (aExpected3) ) && \
+              TestModuleIf().CheckAllowResult( result ) )\
+            { TestModuleIf().StifMacroError(\
+                (3), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), (aExpected1), (aExpected2), (aExpected3) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+//  TA4L =======================================================================
+//  Macro for verify integer value from the expected 1, 2, 3 and 4 values.
+//  Recommended use with TestScripter's test class. Allowed result can be defined
+//  with 'allownextresult' and 'allowerrorcodes' keywords.
+//  Example for use:
+//  T1L( Open(), KErrNone, KErrAlreadyExists, KErrDiskFull, KErrDisconnected );
+//  =============================================================================
+    #define TA4L( aResult, aExpected1, aExpected2, aExpected3, aExpected4 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) && \
+              (result) != (aExpected2) && \
+              (result) != (aExpected3) && \
+              (result) != (aExpected4) ) && \
+               TestModuleIf().CheckAllowResult( result ) ) \
+            { TestModuleIf().StifMacroError(\
+                (4), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), \
+                (aExpected1), (aExpected2), (aExpected3), (aExpected4) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+//  TA5L =======================================================================
+//  Macro for verify integer value from the expected 1, 2, 3, 4 and 5 values.
+//  Recommended use with TestScripter's test class. Allowed result can be defined
+//  with 'allownextresult' and 'allowerrorcodes' keywords.
+//  Example for use:
+//  T1L( Open(), KErrNone, KErrDied, KErrInUse, KErrDisconnected, KErrAbort );
+//  =============================================================================
+    #define TA5L( aResult, aExpected1, aExpected2, aExpected3, aExpected4, aExpected5 )\
+        {\
+        TInt result = aResult;\
+        if( ( (result) != (aExpected1) && \
+              (result) != (aExpected2) && \
+              (result) != (aExpected3) && \
+              (result) != (aExpected4) && \
+              (result) != (aExpected5) ) && \
+               TestModuleIf().CheckAllowResult( result ) ) \
+            { TestModuleIf().StifMacroError(\
+                (5), (TText8*)__FILE__, __FUNCTION__, __LINE__, (result), \
+                (aExpected1), (aExpected2), (aExpected3), (aExpected4), (aExpected5) );\
+            User::Leave( KErrArgument ); };\
+        };
+
+
+// Workaround for ARM RVCT compiler error. This added because if some
+// environment do not include this definition.
+#if !defined (NONSHARABLE_CLASS)
+#define NONSHARABLE_CLASS(x) class x
+#endif
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CTestModuleBase;
+class TEventIf;
+class CTestThreadContainer;
+class MSTIFTestInterference;
+class CSTIFTestMeasurement;
+class CSTIFTestMeasurementImplementation;
+class CUiEnvProxy;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Base class for test case measurement . User can start measurement operations
+// via this class.
+NONSHARABLE_CLASS( CSTIFTestMeasurement )
+        :public CBase 
+    {
+    public: // Enumerations
+
+        /**
+        * Enumeration for different measurement types.
+        */
+        enum TSTIFMeasurementType
+            {
+            KStifMeasurementEnableAll,
+            KStifMeasurementPlugin01,
+            KStifMeasurementPlugin02,
+            KStifMeasurementPlugin03,
+            KStifMeasurementPlugin04,
+            KStifMeasurementPlugin05,
+            KStifMeasurementBappeaProfiler,
+            KStifMeasurementDisableAll,
+            };
+
+        /**
+        * Enumeration for different measurement operations.
+        */
+        enum TSTIFMeasurementOperation
+            {
+            KMeasurementNew,
+            KMeasurementStart,
+            KMeasurementStop,
+            };
+
+        /**
+        * Struct for measurement.
+        */
+        struct TStifMeasurementStruct
+            {
+            TSTIFMeasurementType        iMeasurementType;
+            TFileName                   iConfigurationInfo;
+            TSTIFMeasurementOperation   iMeasurementOperation;
+            TInt                        iOperationResult;
+            CTestModuleBase*            iPointerToMeasurementModule;
+            };
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor. Intializes test measurement module.
+        */
+        IMPORT_C static CSTIFTestMeasurement* NewL( 
+                                            CTestModuleBase* aTestModuleBase,
+                                            TSTIFMeasurementType aType,
+                                            const TDesC& aConfigurationInfo );
+
+    public: // New functions
+
+        /**
+        * Start commant for test measurement module.
+        * Returns Symbian error code.
+        */
+        IMPORT_C TInt Start();
+
+        /**
+        * Stop command for test measurement module.
+        * Returns Symbian error code.
+        */
+        IMPORT_C TInt Stop();
+
+    public: // Functions from base classes
+
+        /**
+        * Destructor 
+        */
+        virtual ~CSTIFTestMeasurement();
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CSTIFTestMeasurement( CTestModuleBase* aTestModuleBase );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( TSTIFMeasurementType aType,
+                         const TDesC& aConfigurationInfo );
+
+    public: //Data
+
+    protected: // Data
+
+    private: // Data
+
+        // Pointer to STIF side
+        CTestModuleBase*        iTestModuleBase;
+
+        // Stuct that includes measurement related information
+        TStifMeasurementStruct  iMeasurementStruct;
+
+        // Indicates is measurement disable
+        TInt                    iMeasurementOption;
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+        friend class CTestModuleBase;
+
+    };
+
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TTestResult defines the test case result information.
+class TTestResult 
+    {
+    public:
+
+        /**
+        * Default constructor of TTestResult.
+        */
+        IMPORT_C TTestResult();
+
+        /**
+        * Sets result and result description of the test case.
+        */
+        IMPORT_C void SetResult( TInt aResultCode, const TDesC& aResultDes );
+
+    public:
+
+        // Test case result as Symbian OS error code.
+        TInt iResult;
+        // Descriptive test case result.
+        TResultDes iResultDes;
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// TTestCaseInfo defines the information for test case execution.
+class TTestCaseInfo
+    {
+    public:
+        // Default test case priority values
+        enum TPriority
+            {    
+            EPriorityLow = -100,
+            EPriorityNormal = 0,
+            EPriorityHigh = 100,
+            };
+
+    public:
+
+        /**
+        * Default constructor of TTestCaseInfo.
+        */
+        IMPORT_C TTestCaseInfo();
+
+    public:
+
+        // Test case number.
+        TInt iCaseNumber;
+        // Test case title.
+        TName iTitle;
+        // Test Case Timeout ( 0 == No timeout )
+        TTimeIntervalMicroSeconds iTimeout; 
+        // Test case priority
+        TInt iPriority;
+
+    };
+// Packaged TTestCaseInfo
+typedef TPckg<TTestCaseInfo> TTestCaseInfoPckg;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestModuleIf provides interface for Test Module to perform 
+// printing to user interface and to control event system.
+class CTestModuleIf
+        :public CBase 
+    {
+    public: // Enumerations
+
+        // Possible test case exit reasons.
+        enum TExitReason
+            {    
+            // Case will exit normally AND return test case result.
+            ENormal,          
+            // Case is expected to panic.
+            EPanic,           
+            // Case will end to exception.
+            EException,
+            };
+
+        enum TRebootType
+            {
+            EDefaultReset = 0,  // Do not change the value
+            EKernelReset,
+
+            EDeviceReset0 = 100,
+            EDeviceReset1,
+            EDeviceReset2,
+            EDeviceReset3,
+            EDeviceReset4,
+            EDeviceReset5
+            };
+
+        enum TTestBehavior
+            {
+            ETestLeaksMem       = 0x00000001,
+            ETestLeaksRequests  = 0x00000002,
+            ETestLeaksHandles   = 0x00000004,
+            EOOMDisableLeakChecks = 0x00000008,
+            };
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CTestModuleIf* NewL( CTestThreadContainer* aExecutionSession, 
+                                             CTestModuleBase* aTestModule );
+
+    public: // New functions
+
+        /**
+        * Printf is used to provide different information up to the UI 
+        * that can be then printed e.g. to the Console Screen. 
+        * The definition of data to be printed is copied to aDefinition. 
+        * The aPriority tells how important information is returned. 
+        * The priority can be used in the UI to decide if the information 
+        * received from the Test Module will be discarded or not in 
+        * the different performance situations. The priority is also 
+        * used in the Test Module server and in the Test Engine to queue 
+        * the Printf responses.
+        * This method is implemented in Test Module Server and the Test Module 
+        * can call it to provide printable information to the UI.
+        */
+        IMPORT_C void Printf( const TInt aPriority, 
+                              const TDesC& aDefinition, 
+                              TRefByValue<const TDesC> aFmt,... );
+
+        /**
+        * Event function is used to control and use the event system. 
+        * TEvent &aEvent encapsulates the request type and 
+        * the event name, see StifTestEventInterface.h for more information.
+        * This method is implemented in Test Module Server and the Test Module 
+        * can call it to control the event system.
+        */
+        IMPORT_C TInt Event( TEventIf& aEvent );
+
+        /**
+        * Asynchronous overload function for the previous. Only one 
+        * asynchronous Event call can be active concurrently. Second 
+        * concurrent call will block until first one is completed.
+        */
+        IMPORT_C void Event( TEventIf& aEvent, TRequestStatus& aStatus );
+
+        /**
+        * Cancel asynchronous event command. 
+        */
+        IMPORT_C TInt CancelEvent( TEventIf& aEvent,
+                                   TRequestStatus* aStatus );
+
+        /**
+        * SetExitReason function is used to set different crash reasons to
+        * acceptable test case result. 
+        * Only one exit reason can be set at time. When function is called
+        * again, previous exit reason is removed and new one is set to
+        * acceptable exit reason.
+        *
+        * Function is typically used to accept test case panics as "passed"
+        * test cases.
+        * 
+        * Test case that panics or gets exception is set to passed 
+        * if aExitReason parameter matches with exit reason and 
+        * aExitCode matches with panic code or exception type.
+        */
+        IMPORT_C void SetExitReason( const CTestModuleIf::TExitReason aExitReason, 
+                                     const TInt aExitCode );
+
+
+        /**
+        * RemoteSend function is used send remote control protocol messages.
+        */
+        IMPORT_C TInt RemoteSend( const TDesC& aRemoteMsg );
+
+        /**
+        * RemoteReceive function is used receive remote 
+        * control protocol messages.
+        */
+        IMPORT_C void RemoteReceive( TDes& aRemoteMsg, 
+                                     TRequestStatus& aStatus );
+
+        /**
+        * RemoteReceiveCancel function is used cancel 
+        * pending RemoteReceive.
+        */
+        IMPORT_C void RemoteReceiveCancel();
+
+        /**
+        * Reboot device, StoreState MUST have been called.
+        */
+        IMPORT_C TInt Reboot( TInt aType = EDefaultReset );
+
+        /**
+        * Store state before reboot. MUST be called before calling Reboot().
+        */
+        IMPORT_C TInt StoreState( TInt aCode, TName& aName );
+
+        /**
+        * Get state after reboot (stored with StoreState).
+        */
+        IMPORT_C TInt GetStoredState( TInt& aCode, TName& aName );
+
+        /**
+        * Set test case behavior, e.g. allow memory leak, handle leak etc.
+        */
+        IMPORT_C TInt SetBehavior( TTestBehavior aType, TAny* aPtr=NULL );
+
+        /**
+        * This can be called from test module but it is recommended to use
+        * TL, T1L, T2L or T3L macro instead of this method.
+        * For more information see macro definitions above on this file.
+        */ 
+        IMPORT_C TInt StifMacroError( TInt aMacroType,
+                                      const TText8* aFile,
+                                      const char* aFunction,
+                                      TInt aLine,
+                                      TInt aResult = 0,
+                                      TInt aExpected1 = 0,
+                                      TInt aExpected2 = 0,
+                                      TInt aExpected3 = 0,
+                                      TInt aExpected4 = 0,
+                                      TInt aExpected5 = 0 );
+
+        /**
+        * Add thread handle to Array. Via array can handle test interference
+        * thread's kill in panic etc. cases
+        */ 
+        TInt AddInterferenceThread( RThread aSTIFTestInterference );
+
+        /**
+        * Remove thread handle from Array.Test interference thread is stopped
+        * and killed successfully
+        */ 
+        TInt RemoveInterferenceThread( RThread aSTIFTestInterference );
+
+        /**
+        * With this can be stored information about test measurement
+        * to TestServer space.
+        */ 
+        TInt HandleMeasurementProcess( CSTIFTestMeasurement::TStifMeasurementStruct aSTIFMeasurementInfo );
+
+        /**
+        * Get measurement option(s) given from initialization file etc.
+        */
+        IMPORT_C TInt GetMeasurementOptions( TInt& aOptions );
+
+        /**
+        * Use with TAL, TA1L, TA2L, TA3L, TA4L and TA5L macros to allow
+        * results.
+        * Set test case allow result given by user. In TestScripter cases allow
+        * result can set by 'allownextresult' or 'allowerrorcodes' keywords. In
+        * Normal and Hardcoded test modules allow result can be set with this
+        * method, reset should be done with ResetAllowResult method.
+        */
+        IMPORT_C TInt SetAllowResult( TInt aResult );
+
+        /**
+        * This is mainly used by STIF's TAL-TA5L macros internally.
+        * Check is macros result allowed result.
+        */
+        IMPORT_C TInt CheckAllowResult( TInt aResult );
+
+        /**
+        * Use with TAL, TA1L, TA2L, TA3L, TA4L and TA5L macros to reset allowed
+        * results.
+        * Reset allow result(s) given with SetAllowResult. In TestScripter
+        * cases this will be called automatically by STIF. Normal and Hardcoded
+        * cases this should be called by user.
+        */
+        IMPORT_C TInt ResetAllowResult();
+
+        /**
+        * StopExecution function is used to stop the execution of test case.
+        */
+        IMPORT_C TInt StopExecution(TStopExecutionType aType, TInt aCode = KErrNone);
+
+        /**
+         * SendTestModuleVersion method is used to pass version of test module
+         * to test engine
+         */
+        IMPORT_C TInt SendTestModuleVersion(TVersion aVersion, TFileName aModuleName);
+        
+        /**
+         * SendTestModuleVersion method is used to pass version of test module
+         * to test engine. This version with 3 parameters were added because version with
+         * 2 parameters has arguments passed by value which is incorrect. So the third argument
+         * was added only to overload the method and enable test modules using "old" version
+         * (with 2 parameters) to work. Only this version (with three parameters) should be used.
+         */
+        IMPORT_C TInt SendTestModuleVersion(TVersion& aVersion, const TDesC& aModuleName, TBool aNewVersion);
+
+        /**
+        * Command function is used to send command to test engine.
+        * It was created to provide possibility to kill test case by itself.
+        */
+        TInt Command(TCommand aCommand, const TDesC8& aParamsPckg);
+
+        /**
+         * Get test case execution arguments
+         */
+        IMPORT_C const TDesC& GetTestCaseArguments() const;        
+
+        /**
+        * GetTestCaseTitleL function is used to obtain test case title.
+        */
+        IMPORT_C void GetTestCaseTitleL(TDes& aTestCaseTitle);
+
+        /**
+        * Checks if testserver supports UI testing
+        */
+		IMPORT_C TBool UITesting();
+
+        /**
+        * Gets UIEnvProxy
+        */
+		IMPORT_C CUiEnvProxy* GetUiEnvProxy();
+
+    public: // Functions from base classes
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        CTestModuleIf( CTestThreadContainer* aTestExecution );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( CTestModuleBase* aTestModule );
+
+        /**
+        * Destructor is also private. 
+        * ONLY friend CTestModuleBase can delete CTestModuleIf.
+        */
+        ~CTestModuleIf();
+
+        /**
+        * Check that server is alive.
+        */ 
+        TBool IsServerAlive();
+
+    public: //Data
+
+    protected: // Data
+
+    private: // Data
+        CTestThreadContainer* iTestExecution;
+
+        // Indicates is reboot operation ready to start.
+        TBool iIsRebootReady;
+
+        // Indicated StoreState() method's call times.
+        TInt iStoreStateCounter;
+
+        // Test case allowed results. Array is a static one for avoid dynamic
+        // allocations.
+        TInt iTestCaseResults[KSTIFMacroResultArraySize]; 
+        // Test case allowed results count. This is used with
+        // iTestCaseResults array.
+        TInt iAllowTestCaseResultsCount; 
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+        friend class CTestModuleBase;
+
+    };
+
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Base class for test module parameters. According to parameters may
+// configure test module. e.g. heap and stack configuring.
+class CTestModuleParam : public CBase 
+    {
+
+    public: // Enumerations
+
+        /**
+        * Evolution version for test module parameters.
+        **/
+        enum TParameterVersio
+            {
+            EVersio1 = 1, // For heap and stack configuring.
+            EVersio2 = 2, // For future needs.
+            EVersio3 = 3, // For future needs.
+            EVersio4 = 4, // For future needs.
+            EVersio5 = 5, // For future needs.
+
+            };
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        //IMPORT_C static CTestModuleParam* NewL();
+
+        /**
+        *
+        */
+        //IMPORT_C ~CTestModuleParam();
+
+    public: // New functions
+
+        /**
+        * 
+        */
+        virtual TInt Version() = 0;
+
+    public: // Functions from base classes
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        //CTestModuleParam();
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        //void ConstructL();
+
+    public: //Data
+
+    protected: // Data
+
+    private: // Data
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestModuleParamVer01 implements evolution version 1 for test module's 
+// heap and stack configuring.
+class CTestModuleParamVer01 : public CTestModuleParam
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public: // Constructors and destructor
+
+        /**
+        * Two-phased constructor.
+        */
+        IMPORT_C static CTestModuleParamVer01* NewL();
+        //IMPORT_C CTestModuleParamVer01* NewL();
+
+        /**
+        * C++ default constructor.
+        */
+        CTestModuleParamVer01();
+
+        /**
+        * Destructor.
+        */
+        IMPORT_C ~CTestModuleParamVer01(); 
+
+    private: // Constructors and destructor
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+
+    public: // New functions
+
+        /**
+        *
+        */
+        inline TInt Version() { return iVersio; };
+
+    public: // Functions from base classes
+        
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+
+    public: // Data
+
+        /**
+        * Test thread stack size defined by user.
+        **/
+        TInt iTestThreadStackSize;
+
+        /**
+        * Test thread heap minimum size defined by user.
+        **/
+        TInt iTestThreadMinHeap;
+
+        /**
+        * Test thread heap maximum size defined by user.
+        **/
+        TInt iTestThreadMaxHeap;
+
+    protected: // Data
+
+    private: // Data
+
+        /**
+        *
+        **/
+        TInt iVersio;
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+
+    };
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Test Module inherits the CTestModuleBase class that is used to provide 
+// simple interface between Test Engine and Test Module. CTestModuleBase 
+// consists of pure virtual methods that the Test Module shall implement 
+// and virtual methods that the Test Module should implement.
+class CTestModuleBase
+        :public CBase
+    {
+    public: // Enumerations
+    
+        // For OOM execution
+        enum TOOMFailureType 
+            {    
+            EFailNext
+            };
+    private: // Enumerations
+
+    public: // Version query.
+
+        /**
+        * Returns the API version which this test module complies.
+        * Test Framework uses this function to verify that loaded module
+        * can be used in current framework release.
+        *
+        * Note that this function must always be the very first function
+        * that is defined in CTestModuleBase.
+        */
+        virtual inline TVersion Version()
+                                 { return TVersion ( KTestModuleAPIMajor,
+                                                     KTestModuleAPIMinor,
+                                                     KTestModuleAPIBuild); }
+
+    public: // Constructors and destructor
+
+        /**
+        * C++ default constructor.
+        */
+        CTestModuleBase(): iTestModuleIf(0) {};
+
+        /**
+        * Destructor.
+        */
+        virtual ~CTestModuleBase(){ delete iTestModuleIf; }; 
+
+    public: // New functions
+
+        /**
+        * InitL is used to initialize the Test Module. The Test Modules may 
+        * use the initialization file to read parameters for Test Module 
+        * initialization but they can also have their own configure file or 
+        * some other routine to initialize themselves.
+        * This method is virtual and it is not mandatory to implement it 
+        * to Test Module.
+        */
+        virtual TInt InitL( TFileName& /* aIniFile */,
+                           TBool /* aFirstTime */ )
+            { return KErrNone; };
+
+        /**
+        * Test cases are inquired from the Test Module by calling 
+        * GetTestCasesL. Test cases may be read from the testcase file 
+        * specified by aTestCaseFile or they can be e.g. hardcoded to testmodule. 
+        * If the Test Module does not use testcase files for test case 
+        * definition it does not use aTestCaseFile parameter. Test cases are 
+        * appended to RPointerArray<TTestCaseInfo> that is a list 
+        * consisting of several TTestCaseInfo objects.
+        * The STIF Test Framework will be the owner of the objects stored to 
+        * RPointerArray after the GetTestCasesL has appended them to the list
+        * and it does the memory deallocation.
+        * This method is pure virtual and the Test Module must implement it.
+        */
+        virtual TInt GetTestCasesL( const TFileName& aTestCaseFile, 
+            RPointerArray<TTestCaseInfo>& aTestCases ) = 0;
+
+        /**
+        * RunTestCaseL is used to run an individual test case specified 
+        * by aCaseNumber and aTestCaseFile (optional). 
+        * This method is synchronous and test case result is returned as 
+        * reference parameter aResult value. 
+        * The function shall return KErrNone if case is started succesfully.
+        * If test case is not available (i.e invalid testcase file or
+        * or case number), then function shall return KErrNotFound. In other 
+        * error situations another Symbian error code is returned.                
+        * This method is pure virtual and the Test Module must implement it. 
+        */
+        virtual TInt RunTestCaseL( const TInt aCaseNumber, 
+                                  const TFileName& aTestCaseFile,
+                                  TTestResult& aResult ) = 0;
+
+        /**
+        * TestModuleIf returns the handle to the CTestModuleIf interface. 
+        * This is an utility function that can be used if the upper layer 
+        * interface is needed to be used.
+        * This method must not be called from the constructor of Test Module 
+        * that derives the CTestModuleBase.
+        */
+        inline CTestModuleIf& TestModuleIf(){ return *iTestModuleIf; };
+
+        /**
+        * Used to perform the test environment setup for a particular OOM test 
+        * case. The Test Modules may use the initialization file to read parameters 
+        * for Test Module initialization but they can also have their own 
+        * configure file or some other routine to initialize themselves.
+        *
+        * This method is virtual and will be implemented if test case is to be
+        * executed using OOM conditions.
+        */
+        virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */, 
+                                         const TInt /* aCaseNumber */ ) {};
+
+        /**
+        * Used to perform the test environment cleanup for a particular OOM 
+        * test case.
+        *         
+        * This method is virtual and will be implemented if test case is to be
+        * executed using OOM conditions.
+        */
+        virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */, 
+                                       const TInt /* aCaseNumber */ ) {};
+
+        /**
+        * Used to check if a particular Test Case should be run in OOM 
+        * conditions and which memory allocations should fail.
+        * Method returns ETrue if test is should run in OOM conditions, EFalse 
+        * otherwise. 
+        *
+        * This method is virtual and will be implemented if test case is to be
+        * executed using OOM conditions.
+        */
+        virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */, 
+                                     const TInt /* aCaseNumber */, 
+                                     TOOMFailureType& aFailureType, 
+                                     TInt& /* aFirstMemFailure */, 
+                                     TInt& /* aLastMemFailure */ ) 
+            { 
+            aFailureType = EFailNext;
+            return EFalse; 
+            };
+
+        /**
+        * Used in OOM testing only. Provides a way to the derived TestModule to
+        * handle warnings related to non-leaving or TRAPped allocations.
+        * 
+        * In some cases the allocation should be skipped, either due to problems
+        * in the OS code or components used by the code being tested, or even
+        * inside the tested components which are implemented this way on purpose
+        * (by design), so it is important to give the tester a way to bypass
+        * allocation failures.
+        *
+        * This method is virtual and will be implemented if test case is to be
+        * executed using OOM conditions.
+        */
+        virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
+                                        const TInt /* aCaseNumber */, 
+                                        TInt& /* aFailNextValue */) {};
+
+    public: // Functions from base classes
+
+    protected: // New functions
+
+    protected: // Functions from base classes
+
+    private:
+
+    public: // Data
+
+    protected: // Data
+
+    private: // Data
+        CTestModuleIf* iTestModuleIf;
+
+    public: // Friend classes
+
+    protected: // Friend classes
+
+    private: // Friend classes
+        friend class CTestModuleIf;
+        friend class CTestModuleParam;
+        friend class MSTIFTestInterference;
+        friend class CSTIFInterferenceThread;
+        friend class CSTIFTestMeasurement;
+
+    };
+
+#endif      // TESTMODULE_H  
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifUnitGeneric.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,474 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIFUnit module declaration
+*
+*/
+
+#ifndef StifUnitGeneric_H
+#define StifUnitGeneric_H
+
+// INCLUDES
+#include <e32svr.h>
+//#include "StifTestModule.h"
+#include <StifTestInterface.h>
+#include <StifLogger.h>
+#include <StifUnitMacros.h>
+
+// INCLUDES FROM CASES FILE
+#define STIF_UNIT_INCLUDE_SECTION
+#include STIF_UNIT_TEST_CASES
+#undef STIF_UNIT_INCLUDE_SECTION
+
+// FORWARD DECLARATIONS
+class STIF_UNIT_MODULE_CLASS_NAME;
+
+// DATA TYPES
+// A typedef for function that does the actual testing,
+// function is a type 
+// TInt STIF_UNIT_MODULE_CLASS_NAME::<NameOfFunction> ( TTestResult& aResult )
+typedef TInt (STIF_UNIT_MODULE_CLASS_NAME::* TestFunction)(TTestResult&);
+
+// CLASS DECLARATION
+/**
+*  An internal structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TCaseInfoInternal
+    {
+    public:
+        const TText*    iCaseName;
+        TestFunction    iMethod;
+        TBool           iIsOOMTest;
+        TInt            iFirstMemoryAllocation;
+        TInt            iLastMemoryAllocation;
+    };
+
+// CLASS DECLARATION
+/**
+*  A structure containing a test case name and
+*  the pointer to function doing the test
+*
+*  @lib ?library
+*  @since ?Series60_version
+*/
+class TCaseInfo
+    {
+    public:
+        TPtrC iCaseName;
+        TestFunction iMethod;
+        TBool           iIsOOMTest;
+        TInt            iFirstMemoryAllocation;
+        TInt            iLastMemoryAllocation;
+
+    TCaseInfo( const TText* a ) : iCaseName( (TText*) a )
+        {
+        };
+
+    };
+
+// CLASS DECLARATION
+/**
+*  STIFUnit class (name of the class is changed by real module name).
+*/
+NONSHARABLE_CLASS(STIF_UNIT_MODULE_CLASS_NAME) : public CTestModuleBase
+    {
+    public:  //Enums
+        
+    public:  // Constructors and destructor
+
+
+        /**
+        * Two-phased constructor.
+        */
+        static STIF_UNIT_MODULE_CLASS_NAME* NewL()
+            {
+            STIF_UNIT_MODULE_CLASS_NAME* self = new (ELeave) STIF_UNIT_MODULE_CLASS_NAME;
+
+            CleanupStack::PushL( self );
+            self->ConstructL();
+            CleanupStack::Pop();
+
+            return self;
+            }
+
+        /**
+        * Destructor.
+        */
+        virtual ~STIF_UNIT_MODULE_CLASS_NAME()
+            {
+            delete iLog;
+            }
+
+
+    public: // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    public: // Functions from base classes
+
+        /**
+        * From CTestModuleBase InitL is used to initialize the 
+        *       STIFUnit module. It is called once for every instance of 
+        *       TestModuleUnit after its creation.
+        * @param aIniFile Initialization file for the test module (optional)
+        * @param aFirstTime Flag is true when InitL is executed for first 
+        *               created instance of STIFUnit module.
+        * @return Symbian OS error code
+        */
+        TInt InitL( TFileName& /*aIniFile*/, TBool /*aFirstTime*/ )
+            {
+            return KErrNone;
+            }
+
+        /**
+        * From CTestModuleBase GetTestCasesL is used to inquiry test cases 
+        *   from STIFUnit module. 
+        * @since ?Series60_version
+        * @param aTestCaseFile Test case file (optional)
+        * @param aTestCases  Array of TestCases returned to test framework
+        * @return Symbian OS error code
+        */
+        TInt GetTestCasesL( const TFileName& /*aTestCaseFile*/, 
+                            RPointerArray<TTestCaseInfo>& aTestCases )
+            {
+            TTestResult dummyResult;
+            return MainTestL(EEnumerateTestCases, -1, aTestCases, dummyResult); 
+            }
+
+        /**
+        * From CTestModuleBase RunTestCaseL is used to run an individual 
+        *   test case. 
+        * @since ?Series60_version
+        * @param aCaseNumber Test case number
+        * @param aTestCaseFile Test case file (optional)
+        * @param aResult Test case result returned to test framework (PASS/FAIL)
+        * @return Symbian OS error code (test case execution error, which is 
+        *           not reported in aResult parameter as test case failure).
+        */   
+        TInt RunTestCaseL( const TInt aCaseNumber, 
+                           const TFileName& /*aTestCaseFile*/,
+                           TTestResult& aResult )
+        {
+        if(!iVersionLogged)
+            {
+            SendTestModuleVersion();
+            iVersionLogged = ETrue;
+            }
+    
+        RPointerArray<TTestCaseInfo> aTestCases; //temporary
+    
+        // iNumberOfTestCases should contain valid number of test cases present in test module. This info
+        // is gathered in the enumeration procedure.
+        // However if test case crashes, test module is loaded again and enumeration is not performed.
+        // In such case counting procedure must be done.
+        if(iNumberOfTestCases == 0)
+            {
+            TRAPD(errCount, MainTestL(ECountTestCases, aCaseNumber, aTestCases, aResult));
+            if(errCount != KErrNone)
+                {
+        		    iLog->Log(_L("Error during counting test cases [%d]"), errCount);
+        		    return errCount;
+        		    }
+        	  }
+        
+        /**
+         * SetupL is responsible for inicialization of all fields (etc.) common for all testcases
+         * MainTestL starts required testcase
+         * TeardownL destroys all data that was created by SetupL
+         */
+        TInt errSetup = KErrNone;
+        TInt errTestcase = KErrNone;
+        
+        if(aCaseNumber > iNumberOfTestCases)
+            return KErrNotFound;
+        	
+        __UHEAP_MARK;
+        
+        TRAP(errSetup, MainTestL(ERunTestCase, STIF_RUN_SETUP, aTestCases, aResult); TRAP(errTestcase, MainTestL(ERunTestCase, aCaseNumber, aTestCases, aResult))\
+        		MainTestL(ERunTestCase, STIF_RUN_TEARDOWN, aTestCases, aResult));
+        
+        __UHEAP_MARKEND;
+        
+        if(errTestcase != KErrNone)
+            {
+            aResult.SetResult(errTestcase, _L("Testcase failed"));
+            }
+        if(errSetup != KErrNone)
+            {
+            aResult.SetResult(errSetup, _L("Setup or teardown failed"));
+            }
+       
+        return KErrNone;
+        }
+
+        /**
+        * From CTestModuleBase; OOMTestQueryL is used to specify is particular
+        * test case going to be executed using OOM conditions
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailureType OOM failure type (optional)
+        * @param aFirstMemFailure The first heap memory allocation failure value (optional)
+        * @param aLastMemFailure The last heap memory allocation failure value (optional)
+        * @return TBool
+        */
+        #ifdef STIFUNIT_OOMTESTQUERYL
+        virtual TBool OOMTestQueryL( const TFileName& aTestCaseFile, 
+                                     const TInt aCaseNumber, 
+                                     TOOMFailureType& aFailureType, 
+                                     TInt& aFirstMemFailure, 
+                                     TInt& aLastMemFailure);
+        #else
+        virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */, 
+                                     const TInt /* aCaseNumber */, 
+                                     TOOMFailureType& /* aFailureType */, 
+                                     TInt& /* aFirstMemFailure */, 
+                                     TInt& /* aLastMemFailure */ )
+            {
+            return EFalse;
+            }
+        #endif
+
+        /**
+        * From CTestModuleBase; OOMTestInitializeL may be used to initialize OOM
+        * test environment
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        */
+        #ifdef STIFUNIT_OOMTESTINITIALIZEL
+        virtual void OOMTestInitializeL( const TFileName& aTestCaseFile, 
+                                         const TInt aCaseNumber);
+        #else
+        virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */, 
+                                         const TInt /* aCaseNumber */ )
+            {
+            }
+        #endif 
+
+        /**
+        * From CTestModuleBase; OOMHandleWarningL
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @param aFailNextValue FailNextValue for OOM test execution (optional)
+        * @return None
+        *
+        * User may add implementation for OOM test warning handling. Usually no
+        * implementation is required.           
+        */
+        #ifdef STIFUNIT_OOMHANDLEWARNINGL
+        virtual void OOMHandleWarningL( const TFileName& aTestCaseFile,
+                                        const TInt aCaseNumber, 
+                                        TInt& aFailNextValue);
+        #else
+        virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
+                                        const TInt /* aCaseNumber */, 
+                                        TInt& /* aFailNextValue */)
+            {
+            }
+        #endif 
+
+        /**
+        * From CTestModuleBase; OOMTestFinalizeL may be used to finalize OOM
+        * test environment
+        * @param aTestCaseFile Test case file (optional)
+        * @param aCaseNumber Test case number (optional)
+        * @return None
+        *
+        */
+        #ifdef STIFUNIT_OOMTESTFINALIZEL
+        virtual void OOMTestFinalizeL( const TFileName& aTestCaseFile, 
+                                       const TInt aCaseNumber);
+        #else
+        virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */, 
+                                       const TInt /* aCaseNumber */ )
+            {
+            }
+        #endif
+
+        /**
+         * Method used to log version of test module
+         */
+        void SendTestModuleVersion()
+            {
+            TVersion moduleVersion;
+            moduleVersion.iMajor = TEST_MODULE_VERSION_MAJOR;
+            moduleVersion.iMinor = TEST_MODULE_VERSION_MINOR;
+            moduleVersion.iBuild = TEST_MODULE_VERSION_BUILD;
+            	
+            TFileName moduleName;
+            moduleName = STIF_UNIT_MODULE_NAME;
+            
+            TBool newVersionOfMethod = ETrue;
+            TestModuleIf().SendTestModuleVersion(moduleVersion, moduleName, newVersionOfMethod);
+            }
+
+    protected:  // New functions
+
+        /**
+        * ?member_description.
+        * @since ?Series60_version
+        * @param ?arg1 ?description
+        * @return ?description
+        */
+        //?type ?member_function( ?type ?arg1 );
+
+    protected:  // Functions from base classes
+
+        /**
+        * From ?base_class ?member_description
+        */
+        //?type ?member_function();
+
+    private:
+
+        /**
+        * C++ default constructor.
+        */
+        STIF_UNIT_MODULE_CLASS_NAME()
+            {
+            }
+
+        /**
+        * By default Symbian 2nd phase constructor is private.
+        */
+        void ConstructL()
+            {
+            iLog = CStifLogger::NewL( KUnitLogPath, KUnitLogFile);
+
+            // Sample how to use logging
+            iLog->Log( KLogStart );
+
+            iVersionLogged = EFalse;
+            iNumberOfTestCases = 0;
+            }
+
+        /**
+        * Method containing all test cases, setup and teardown sections.
+        */
+        TInt MainTestL(TCallReason aRunReason, TInt aTestToRun, RPointerArray<TTestCaseInfo>& aTestCases, TTestResult& aResult)
+            {
+            aResult.iResult = aResult.iResult; //for avoiding compiler warning when unit test does not use any assert macro  
+            if(aRunReason == ERunTestCase)
+                {
+                if(aTestToRun < 0)
+                    {
+                    iLog->Log(_L("Running setup or teardown"));
+                    }
+                else
+                    {
+                    iLog->Log(_L("Running test case #%d"), aTestToRun);
+                    }
+                }
+            else if(aRunReason == EEnumerateTestCases)
+                {
+                iLog->Log(_L("Enumerating test cases."));
+                }
+            else if(aRunReason == ECountTestCases)
+                {
+                iLog->Log(_L("Counting test cases."));
+                }
+            else
+                {
+                iLog->Log(_L("Unknown run reason [%d]."), aRunReason);
+                return KErrNotSupported;
+                }
+            
+            TInt _test_case_no = -1;
+            
+            //test cases, setup and teardown include
+            #define TEST_CASES
+            #include STIF_UNIT_TEST_CASES
+            #undef TEST_CASES
+            
+            if(aRunReason == EEnumerateTestCases)
+                {
+                iNumberOfTestCases = _test_case_no;
+                iLog->Log(_L("Enumeration completed."));
+                }
+            else if(aRunReason == ECountTestCases)
+                {
+                iNumberOfTestCases = _test_case_no;
+                iLog->Log(_L("Counting completed."));
+                }
+            
+            // Test case was executed
+            return KErrNone;
+            }
+
+    public:     // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    protected:  // Data
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+    private:    // Data
+        // Pointer to test (function) to be executed
+        TestFunction iMethod;
+
+        // Pointer to logger
+        CStifLogger * iLog; 
+
+        // Flag saying if version of test module was already sent
+        TBool iVersionLogged;
+        // Total number of test cases
+        TInt iNumberOfTestCases;
+
+        // ?one_line_short_description_of_data
+        //?data_declaration;
+
+        // Reserved pointer for future extension
+        //TAny* iReserved;
+        
+		#define TEST_VAR_DECLARATIONS
+        /**
+         * all testmodule-global variables declarations are inserted here
+         */
+        #include STIF_UNIT_TEST_CASES
+		#undef TEST_VAR_DECLARATIONS
+
+    public:     // Friend classes
+        //?friend_class_declaration;
+    protected:  // Friend classes
+        //?friend_class_declaration;
+    private:    // Friend classes
+        //?friend_class_declaration;
+
+    };
+
+EXPORT_C CTestModuleBase* LibEntryL()
+    {
+    return STIF_UNIT_MODULE_CLASS_NAME::NewL();
+    }
+#ifndef STIFUNIT_SETHEAPANDSTACKSIZE
+EXPORT_C TInt SetRequirements( CTestModuleParam*& /*aTestModuleParam*/, 
+                               TUint32& /*aParameterValid*/ )
+    {
+    return KErrNone;
+    }
+
+#endif
+#endif      // StifUnitGeneric_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifUnitMacros.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,217 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: STIFUnit macros declarations
+*
+*/
+
+#ifndef STIFUnit_MACROS_H
+#define STIFUnit_MACROS_H
+
+// Enumeration types
+// Reason for running test method
+enum TCallReason
+    {
+    EEnumerateTestCases,
+    ERunTestCase,
+    ECountTestCases, //Used to count test cases.
+                     //This should be already done by enumerating procedure,
+                     //however in case of test crash all internal data are
+                     //being lost.
+    };
+
+
+// Strings
+_LIT( KAssertFailedEquals, "AssertEquals Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotEquals, "AssertNotEquals Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNull, "AssertNull Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotNull, "AssertNotNull Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedSame, "AssertSame Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotSame, "AssertNotSame Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedTrue, "AssertTrue Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedFalse, "AssertFalse Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotLeaves, "AssertNotLeaves Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedLeaves, "AssertLeaves Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedLeavesWith, "AssertLeavesWith Failed [F:%s][L:%d]" );
+
+
+#ifdef _UNICODE
+	#define __STIF_WIDEN2(x) L ## x
+	#define __STIF_WIDEN(x) __STIF_WIDEN2(x)
+	#define __STIF_DBG_FILE__ __STIF_WIDEN(__FILE__)
+#else
+	#define __STIF_DBG_FILE__ __FILE__
+#endif
+
+
+// Logs to the STIF log file AND to the RDebug
+#define STIF_LOG( aMessage ) \
+    iLog->Log( _L( aMessage ) ); RDebug::Print( _L( aMessage ) );
+
+
+// Defines a separate test case which consists of two blocks - one for enumeration of test cases
+// second for running the testcase.
+#define STIF_TESTDEFINE( aTestName ) \
+_test_case_no++; \
+if( aRunReason == EEnumerateTestCases ) \
+	{ \
+  TTestCaseInfo* newCase = new( ELeave ) TTestCaseInfo(); \
+  CleanupStack::PushL( newCase ); \
+  newCase->iCaseNumber = _test_case_no; \
+  newCase->iTitle.Copy( _L( #aTestName ) ); \
+  User::LeaveIfError(aTestCases.Append ( newCase ) ); \
+  CleanupStack::Pop( newCase ); \
+	} \
+else if(aRunReason == ERunTestCase && _test_case_no == aTestToRun)
+
+#define STIF_RUN_SETUP -1
+#define STIF_RUN_TEARDOWN -2
+
+// Defines a setup section of MainTestL method
+#define STIF_SETUP \
+	if( aRunReason == ERunTestCase && aTestToRun == STIF_RUN_SETUP )
+
+// Defines a teardown section of MainTestL method
+#define STIF_TEARDOWN \
+	if( aRunReason == ERunTestCase && aTestToRun == STIF_RUN_TEARDOWN )
+		
+/*********************************************************************************
+ * Assert Macros
+ *********************************************************************************/
+#define __STIF_ASSERT_SHARED( aFunction, aMessage ) \
+	if(!aFunction) \
+		{ \
+		iLog->Log( aMessage, __STIF_DBG_FILE__, __LINE__ );\
+		aResult.SetResult( KErrGeneral, _L("Testcase failed"));\
+		User::Leave( KErrGeneral );\
+		}
+
+#define __STIF_ASSERT_SHARED_DESC( aFunction, aMessage, aDesc ) \
+	if(!aFunction) \
+		{ \
+		iLog->Log( aMessage, __STIF_DBG_FILE__, __LINE__ );\
+		aResult.SetResult( KErrGeneral, aDesc );\
+		User::Leave( KErrGeneral );\
+		} \
+	else \
+		{ \
+		aResult.SetResult( KErrNone, aDesc ); \
+		}
+		
+		
+
+#define STIF_ASSERT_EQUALS( aExpected, aActual ) \
+	__STIF_ASSERT_SHARED( AssertEquals( aExpected, aActual ) , KAssertFailedEquals );
+
+#define STIF_ASSERT_EQUALS_DESC( aExpected, aActual, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( AssertEquals( aExpected, aActual ) , KAssertFailedEquals, aDescription ); 
+
+#define STIF_ASSERT_NOT_EQUALS( aExpected, aActual ) \
+	__STIF_ASSERT_SHARED( !AssertEquals( aExpected, aActual ) , KAssertFailedNotEquals );
+
+#define STIF_ASSERT_NOT_EQUALS_DESC( aExpected, aActual, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( !AssertEquals( aExpected, aActual ) , KAssertFailedNotEquals, aDescription );
+
+#define STIF_ASSERT_NULL( aPtr ) \
+	__STIF_ASSERT_SHARED( AssertNull( aPtr ), KAssertFailedNull );
+
+#define STIF_ASSERT_NULL_DESC( aPtr, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( AssertNull( aPtr ), KAssertFailedNull, aDescription );
+
+#define STIF_ASSERT_NOT_NULL( aPtr ) \
+	__STIF_ASSERT_SHARED( !AssertNull( aPtr ), KAssertFailedNotNull );
+
+#define STIF_ASSERT_NOT_NULL_DESC( aPtr, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( !AssertNull( aPtr ), KAssertFailedNotNull, aDescription );
+
+#define STIF_ASSERT_SAME( aExpectedPtr, aActualPtr ) \
+	__STIF_ASSERT_SHARED( AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedSame );
+
+#define STIF_ASSERT_SAME_DESC( aExpectedPtr, aActualPtr, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedSame, aDescription );
+
+#define STIF_ASSERT_NOT_SAME( aExpectedPtr, aActualPtr) \
+	__STIF_ASSERT_SHARED( !AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedNotSame );
+
+#define STIF_ASSERT_NOT_SAME_DESC( aExpectedPtr, aActualPtr, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( !AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedNotSame, aDescription );
+
+#define STIF_ASSERT_TRUE( aCondition ) \
+	__STIF_ASSERT_SHARED( AssertTrue( aCondition ), KAssertFailedTrue );
+
+#define STIF_ASSERT_TRUE_DESC( aCondition, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( AssertTrue( aCondition ), KAssertFailedTrue, aDescription );
+
+#define STIF_ASSERT_FALSE( aCondition ) \
+	__STIF_ASSERT_SHARED( !AssertTrue( aCondition ), KAssertFailedFalse );
+
+#define STIF_ASSERT_FALSE_DESC( aCondition, aDescription ) \
+	__STIF_ASSERT_SHARED_DESC( !AssertTrue( aCondition), KAssertFailedFalse, aDescription );
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_NOT_LEAVES( aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( AssertEquals( __leaveValue, KErrNone ), KAssertFailedNotLeaves ); \
+    }
+
+#define STIF_ASSERT_NOT_LEAVES_DESC( aStatement, aDescription ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_DESC( AssertEquals( __leaveValue, KErrNone ), KAssertFailedNotLeaves, aDescription ); \
+    }    
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_LEAVES( aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( !AssertEquals( __leaveValue, KErrNone ), KAssertFailedLeaves ); \
+    }
+
+#define STIF_ASSERT_LEAVES_DESC( aStatement, aDescription ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_DESC( !AssertEquals( __leaveValue, KErrNone ), KAssertFailedLeaves, aDescription ); \
+    }   
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_LEAVES_WITH( aLeaveCode, aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( AssertEquals( __leaveValue, aLeaveCode ), KAssertFailedLeaves ); \
+    }
+
+#define STIF_ASSERT_LEAVES_WITH_DESC( aLeaveCode, aStatement, aDescription ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_DESC( AssertEquals( __leaveValue, aLeaveCode ), KAssertFailedLeaves, aDescription ); \
+    }
+
+#define STIF_ASSERT_PANIC( aPanicCode, aStatement ) \
+	{ \
+	TestModuleIf().SetExitReason( CTestModuleIf::EPanic, aPanicCode ); \
+	aStatement; \
+	}
+
+#define STIF_ASSERT_PANIC_DESC( aPanicCode, aStatement, aDescription ) \
+	{ \
+	TestModuleIf().SetExitReason( CTestModuleIf::EPanic, aPanicCode ); \
+	aResult.SetResult(KErrNone, aDescription); \
+	aStatement; \
+	}
+
+#include <StifUnitUtils.inl>
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/StifUnitUtils.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description:
+*
+*/
+
+template <class T>
+inline TBool AssertEquals(const T& aExpected, const T& aActual)
+/**
+ * AssertEquals
+ *
+ * @prototype
+ * @test
+ *
+ * @param aExpected - Expected result
+ * @param aActual - Actual result
+ * @return - True if equal
+ */
+	{
+	if( aExpected==aActual )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+template <class T>
+inline TBool AssertNull(const T* aPtr)
+/**
+ * AssertNull
+ *
+ * @prototype
+ * @test
+ *
+ * @param aPtr - Pointer
+ * @return - True if NULL
+ */
+	{
+	if( aPtr==NULL )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+template <class T>
+inline TBool AssertSame(const T* aExpectedPtr, const T* aActualPtr)
+/**
+ * AssertSame
+ *
+ * @prototype
+ * @test
+ *
+ * @param aExpectedPtr - Expected pointer
+ * @param aActualPtr - Actual pointer
+ * @return - True if equal
+ */
+	{
+	if( aExpectedPtr==aActualPtr )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+inline TBool AssertTrue(const TBool& aCondition)
+/**
+ * AssertTrue
+ *
+ * @prototype
+ * @test
+ *
+ * @param aCondition - Condition
+ * @return - True if aCondition is true
+ */
+	{
+	if( !aCondition )
+		{
+		return EFalse;
+		}
+	return ETrue;
+	}
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/TestEngineClient.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,555 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* RTestEngineServer, RTestEngine and RTestCase.
+*
+*/
+
+#ifndef TEST_ENGINE_CLIENT_H
+#define TEST_ENGINE_CLIENT_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <hal.h>
+#include <StifTestInterface.h>
+#include <StifTestEventInterface.h>
+#include <StifLogger.h>
+
+#include <StifTFwIfProt.h>
+
+// CONSTANTS
+// None
+
+// Start and end tags for STIF setting denitions
+_LIT( KStifSettingsStartTag, "[StifSettings]" );
+_LIT( KStifSettingsEndTag, "[EndStifSettings]" );
+// Tag for cabs modifier name
+_LIT( KCapsModifier, "CapsModifier=" );
+// Test module thread heap and stack names
+_LIT( KUserDefStackSize, "TestThreadStackSize=" );
+_LIT( KUserDefMinHeap, "TestThreadMinHeap=" );
+_LIT( KUserDefMaxHeap, "TestThreadMaxHeap=" );
+
+// Global mutex name
+_LIT( KStifTestServerStartupMutex, "KStifTestServerStartupMutex" );
+
+// MACROS
+// None
+
+// DATA TYPES
+
+// Opcodes used in message passing between client and server
+enum TTestEngineRequests
+    {
+    // RTestEngineServer requests
+    ETestEngineServerCloseSession,
+    // RTestEngine requests
+    ETestEngineCreateSubSession,
+    ETestEngineCloseSubSession,
+    ETestEngineSetAttribute,
+    ETestEngineAddTestModule,
+    ETestEngineRemoveTestModule,
+    ETestEngineAddConfigFile,
+    ETestEngineRemoveConfigFile,
+    ETestEngineEnumerateTestCases,
+    ETestEngineGetTestCases,    
+    ETestEngineCancelAsyncRequest,
+    ETestEngineEvent,
+    ETestEngineErrorNotification,
+    ETestEngineLoggerSettings,
+    ETestEngineCloseLoggerSettings,
+    ETestEngineReportTestCase, //Add info about executed test case to test report. Used by reboot mechanism
+    // RTestCase requests
+    ETestCaseCreateSubSession,
+    ETestCaseCloseSubSession,
+    ETestCaseRunTestCase,
+    ETestCasePause,
+    ETestCaseResume,
+    ETestCaseNotifyProgress,
+    ETestCaseNotifyRemoteType,
+    ETestCaseNotifyRemoteMsg,
+    ETestCaseCancelAsyncRequest,
+    ETestCaseNotifyCommand,
+    };
+
+// Package for test case count, used in EnumerateTestCases method
+typedef TPckgBuf<TInt> TCaseCount;
+
+// A set of test engine settings which can be set/read by SettingServer
+struct TEngineSettings
+    {
+    TBool iUITestingSupport;
+    TBool iSeparateProcesses;
+    };
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// Template class delivering test cases from Test Module
+template <class T> class CFixedFlatArray;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// RTestEngineServer is a client class of Test Engine Server
+// The connect function starts the server, if is not already running.
+// An RSessionBase sends messages to the server with
+// the function RSessionBase::SendReceive();
+// specifying an opcode (TTestEngineReq) and array of argument pointers.
+
+class RTestEngineServer
+        : public RSessionBase 
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Closes the RTestEngineServer session.
+        */
+        IMPORT_C void Close();
+
+    public:     // New functions
+
+        /**
+        * Connect method creates new RTestEngineServer session that is used
+        * to manage the test case execution.
+        */
+        IMPORT_C TInt Connect();
+
+        /**
+        * Version returns client side version number from the 
+        * RTestEngineServer.
+        */
+        IMPORT_C TVersion Version() const;
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+// DESCRIPTION
+
+// RTestEngine class represents a subsession with the RTestEngineServer.
+// Each RTestEngine corresponds to a specific CTestEngine (a CObject derived
+// class) in the server. Messages are passed via the RTestEngineServer.
+// A RTestEngine stores a handle from it's server side CTestEngine, and uses
+// this to identify the CTestEngine during communication.
+
+class RTestEngine
+        : public RSubSessionBase 
+    {
+
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Open creates a subsession to Test Engine and opens new handle to
+        * RTestEngine. The RTestEngineServer subsession shall be created by
+        * calling RTestEngineServer::Connect before calling Open to create new
+        * RTestEngine subsession.
+        */
+        IMPORT_C TInt Open( RTestEngineServer& aServer,
+                            const TFileName& aIniFile );
+
+        /**
+        * Closes the RTestEngine subsession.
+        */
+        IMPORT_C void Close();
+
+    public:     // New functions
+
+        /**
+        * Sets attributes to Test Framework
+        */
+        IMPORT_C TInt SetAttribute( TAttribute aAttribute,
+                                    const TDesC& aValue );
+
+        /**
+        * AddTestModule is used to add dynamically a new Test Module to the
+        * Test Framework. Test cases can then be run from the new Test Module
+        * without restarting the Test Framework.
+        * If the Test Module specified by aTestModule doesn't exists this
+        * method returns KErrNotFound. If the Test Module has been already
+        * loaded this method returns KErrAlreadyExists.
+        */
+        IMPORT_C TInt AddTestModule( const TName& aTestModule,
+                                     const TFileName& aIniFile );
+
+        /**
+        * RemoveTestModule is used to remove the existing Test Module from Test
+        * Framework. If there are not test cases executing in the Test Module
+        * it will be shut down.
+        * If there is test case running from the Test Module this method
+        * returns KErrInUse.
+        * If the Test Module specified by aTestModule is not loaded this method
+        * returns KErrNotFound.
+        */
+        IMPORT_C TInt RemoveTestModule( const TName& aTestModule );
+
+        /**
+        * AddConfigFile is used to add dynamically a new config file to the
+        * Test Module specified by aTestModule. New test cases are then 
+        * executed by calling first GetTestCases and then RunTestCase. Thus
+        * new test cases can be run from the Test Module without restarting
+        * the Test Framework.
+        */
+        IMPORT_C TInt AddConfigFile( const TName& aTestModule,
+                                     const TFileName& aConfigFile );
+
+        /**
+        * RemoveConfigFile is used to remove a config file from the
+        * Test Module specified by aTestModule. 
+        */
+        IMPORT_C TInt RemoveConfigFile( const TName& aTestModule,
+                                        const TFileName& aConfigFile );
+
+        /**
+        * Test cases are inquired by two-phased operation calling first the
+        * EnumerateTestCases method and then the GetTestCases. Test cases are
+        * inquired from Test Engine that will inquire them from Test Modules.
+        * EnumerateTestCases requests the needed array size for test cases that
+        * will be inquired by GetTestCases method. When the EnumerateTestCases
+        * is completed succesfully the GetTestCases method is called to
+        * retrieve test cases to CArrayFixFlat <TTestInfo> list object.
+        *
+        * TTestInfo defines individual test case and, if needed, a test set
+        * (TName iParent) where the test case belongs to. TTestInfo is used to
+        * create test case by calling RTestCase::Open that constructs the
+        * actual test case. Test case is then executed calling
+        * RTestCase::RunTestCase.
+        */
+        IMPORT_C void EnumerateTestCases( TCaseCount& aCount,
+                                          TRequestStatus& aStatus );
+
+        /**
+        * GetTestCases retrieves test cases from Test Modules to 
+        * aTestCaseBuffer that is a list consisting of several TTestInfo 
+        * objects. If this method is called without previously succesfully
+        * called EnumerateTestCases method, this function returns the
+        * KErrNotReady.
+        */
+        IMPORT_C TInt GetTestCases(
+                            CFixedFlatArray<TTestInfo>& aTestCaseBuffer );
+
+        /**
+        * Asynchronous request can be canceled with CancelAsyncRequest method.
+        * The aReqToCancel parameter defines the request that will be canceled.
+        */
+        IMPORT_C TInt CancelAsyncRequest( TInt aReqToCancel );
+        
+        /**
+        * Event is used to get and set events in STIF Test Framework.
+        * TEventIf defines the event request information.
+        */
+        IMPORT_C void Event( TEventIfPckg& aEvent,
+                             TRequestStatus& aStatus );
+
+        /**
+        * Used to get Logger's overwrite parameters.
+        */
+        IMPORT_C TInt OpenLoggerSession( RTestEngineServer& aServer,
+                                            TLoggerSettings& aLoggerSettings );
+
+        /**
+        * ErrorNotification obtains error notifications from test engine.
+        */
+        IMPORT_C void ErrorNotification( TErrorNotificationPckg& aError,
+                                         TRequestStatus& aStatus );
+
+        /**
+        * Add info about test case to test report.
+        */
+        IMPORT_C TInt AddTestCaseResultToTestReport(const TTestInfo& aTestInfo,
+                                                    const TFullTestResult& aTestResult,
+                                                    const TInt aError);
+                                         
+    public:     // Functions from base classes
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+    public:     // Data
+
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+    
+// DESCRIPTION
+
+// RTestCase class represents a subsession with the RTestEngineServer.
+// Each RTestCase corresponds to a specific CTestExecution (a CObject
+// derived class) in the server. Messages are passed via the RTestEngineServer.
+// A RTestCase stores a handle from it's server side CTestExecution,
+// and uses this to identify the CTestExecution during communication.
+
+class RTestCase
+        : public RSubSessionBase 
+    {
+
+    public:     // Structured classes
+
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+
+        /**
+        * Open creates a subsession for new test case. Test case is initialized
+        * using aTestCaseInfo parameter. The aTestCaseInfo is TTestInfoPckg 
+        * that is a packaged TTestInfo. TTestInfo is got from the Test Engine
+        * by calling RTestEngine::GetTestCases method.
+        * If there was previously called RemoveTestModule for the Test Module
+        * that is defined in aTestCaseInfo this method returns KErrLocked.
+        * This means that new test cases cannot be run from this Test Module
+        * and the user should inquire test cases available calling 
+        * RTestEngine::GetTestCases.
+        */
+        IMPORT_C TInt Open( RTestEngineServer& aServer,
+                                const TTestInfoPckg& aTestCaseInfo );
+
+        /**
+        * Closes the RTestCase subsession. Test case is normally closed
+        * immediately after the test case was completed.
+        */
+        IMPORT_C void Close();
+
+    public:     // New functions
+
+        /**
+        * RunTestCase is asynchronous method and it is completed when the test
+        * case is completed. Result of the test case is returned to 
+        * aTestResult. The aTestResult is TFullTestResultPckg that is a
+        * packaged TFullTestResult.
+        * The aStatus will have the completion result of this function. If the
+        * test case could be run (despite of succesfully or not) the KErrNone 
+        * is returned to aStatus.
+        */
+        IMPORT_C void RunTestCase( TFullTestResultPckg& aTestResult,
+                                    TRequestStatus& aStatus );
+
+        /**
+        * RunTestCase is asynchronous method and it is completed when the test
+        * case is completed. Result of the test case is returned to 
+        * aTestResult. The aTestResult is TFullTestResultPckg that is a
+        * packaged TFullTestResult.
+        * The aStatus will have the completion result of this function. If the
+        * test case could be run (despite of succesfully or not) the KErrNone 
+        * is returned to aStatus.
+        */
+        IMPORT_C void RunTestCase( TFullTestResultPckg& aTestResult,
+                                   const TDesC& aTestCaseArgs,
+                                   TRequestStatus& aStatus );        
+
+        /**
+        * Pause suspends the execution of the test case. The subsession where
+        * the test case is run is suspended and thus the test case execution is
+        * suspended. Test case execution can be later resumed by calling 
+        * Resume.
+        */
+        IMPORT_C TInt Pause();
+
+        /**
+        * Resume is used to resume the test case suspended by previously called
+        * Pause method. The test case execution should be continued immediately
+        * when the Resume is called.
+        */
+        IMPORT_C TInt Resume();
+
+        /**
+        * NotifyProgress requests different progress information from the test
+        * case execution. This information can be printed to UI. The progress
+        * information is returned to aProgress. The aProgress is
+        * TTestProgressPckg that is a packaged TTestProgress 
+        */
+        IMPORT_C void NotifyProgress( TTestProgressPckg& aProgress,
+                                        TRequestStatus& aStatus );
+                                        
+        /**
+        * NotifyRemoteType requests enable message waiting.
+        */
+        IMPORT_C void NotifyRemoteType( TStifCommandPckg& aType,
+                                        TPckg<TInt>& aMsgSize,
+                                        TRequestStatus& aStatus );
+        /**
+        * NotifyRemoteMsg gets messages.
+        */
+        IMPORT_C TInt NotifyRemoteMsg( TDes8& aMessage,
+                                       TStifCommand aType );
+
+        /**
+        * Asynchronous request can be canceled with CancelAsyncRequest method.
+        * The aReqToCancel parameter defines the request that will be canceled.
+        */
+        IMPORT_C TInt CancelAsyncRequest( TInt aReqToCancel );
+
+    public:     // Functions from base classes
+        
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:    // New functions
+
+    public:     // Data
+    
+    protected:  // Data
+
+    private:    // Data
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+/*
+-------------------------------------------------------------------------------
+
+    DESCRIPTION
+
+    This contains the CFixedFlatArray class definitions.
+
+-------------------------------------------------------------------------------
+*/
+template <class T>
+class CFixedFlatArray 
+        :public CBase
+    {
+    public:     // Enumerations
+
+    private:    // Enumerations
+
+    public:     // Constructors and destructor
+        
+        /**
+        * Two-phased constructor.
+        */
+        inline static CFixedFlatArray<T>* NewL(const TInt aSize);
+
+        /**
+        * Destructor.
+        */
+        inline ~CFixedFlatArray();
+
+    public:     // New functions
+
+        /**
+        * Return descriptor containing array. Used in server calls
+        */
+        inline TPtr8& Des();
+
+        /**
+        * Returns CFixedFlatArray internal array. Used in server calls
+        */
+        inline T& operator[] (TInt aIndex) const;
+
+        /**
+        * Returns count
+        */
+        inline TInt Count() const;
+
+        /**
+        * Sets aBuf to array slot specified by aIndex
+        */
+        inline void Set( TInt aIndex, T& aBuf );
+
+    public:     // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        inline void ConstructL(const TInt aSize);
+
+        /**
+        * C++ default constructor.
+        */
+        inline CFixedFlatArray();
+
+        /**
+        * Check that given index is correct.
+        */
+        inline void CheckIndex( TInt aIndex ) const;
+
+    protected:  // Data
+
+    private:    // Data
+        // Array
+        T*      iArray;
+
+        // Count
+        TInt    iCount;
+
+        // Buffer
+        HBufC8* iBuffer;
+        TPtr8   iBufferPtr;
+
+    public:     // Friend classes
+
+    protected:  // Friend classes
+
+    private:    // Friend classes
+
+    };
+
+#include <TestEngineClient.inl>
+
+
+#endif // TEST_ENGINE_CLIENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/TestEngineClient.inl	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,303 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains implementation of TestEngineClient's 
+* inline functions.
+*
+*/
+
+#ifndef TEST_ENGINE_CLIENT_INL
+#define TEST_ENGINE_CLIENT_INL
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+/*
+-------------------------------------------------------------------------------
+
+    Class:CFixedFlatArray
+
+    Method: CFixedFlatArray
+
+    Description: Default constructor
+
+    C++ default constructor can NOT contain any code, that
+    might leave.
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+template <class T>
+CFixedFlatArray<T>::CFixedFlatArray() :
+    iArray( NULL ),
+    iBufferPtr(0,0)
+    {
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFixedFlatArray
+
+    Method: ConstructL
+
+    Description: Symbian OS second phase constructor
+
+    Symbian OS default constructor can leave.
+
+    Parameters: const TInt aCount: in: Count of contents
+
+    Return Values: None
+
+    Errors/Exceptions: Leaves if memory allocation for iArray of iBuffer fails
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+template <class T>
+void CFixedFlatArray<T>::ConstructL( const TInt aCount )
+    {
+
+    iCount = aCount;
+    iArray = new (ELeave) T[iCount];
+
+    const TInt size = iCount * sizeof (T);
+    iBuffer = HBufC8::NewMaxL ( size );
+
+    iBufferPtr.Set( iBuffer->Des() );
+    iBufferPtr.SetLength( size );
+    iBufferPtr.Set( (TUint8*) iArray, size,size );
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFixedFlatArray
+
+    Method: NewL
+
+    Description: Two-phased constructor.
+
+    Parameters: None
+
+    Return Values: CFixedFlatArray<T>: Array of CFixedFlatArray<T> objects
+
+    Errors/Exceptions: Leaves if ConstructL leaves
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+template <class T>
+CFixedFlatArray<T>* CFixedFlatArray<T>::NewL(TInt aSize) 
+    {
+    CFixedFlatArray<T>* self = new ( ELeave ) CFixedFlatArray<T>();
+    CleanupStack::PushL( self );
+    self->ConstructL(aSize);
+    CleanupStack::Pop();
+    return self;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFixedFlatArray
+
+    Method: ~CFixedFlatArray
+
+    Description: Destructor
+
+    Parameters: None
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/    
+template <class T>
+CFixedFlatArray<T>::~CFixedFlatArray()
+    {    
+    delete[] iArray;
+    delete iBuffer;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFixedFlatArray
+
+    Method: Des
+
+    Description: Returns descriptor for array
+
+    Parameters: None
+
+    Return Values: TPtr8&: Descriptor for array
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/ 
+template <class T>
+TPtr8& CFixedFlatArray<T>::Des()
+    {   
+    return iBufferPtr;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFixedFlatArray
+
+    Method: operator[]
+
+    Description: Returns index operator
+
+    Parameters: TInt aIndex: in: Index of object to be returned
+
+    Return Values: T&: Reference to requested object
+
+    Errors/Exceptions: Panics if aIndex is out of range
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/ 
+template <class T>
+T& CFixedFlatArray<T>::operator[] ( TInt aIndex ) const
+    {
+    CheckIndex( aIndex );
+
+    return iArray[aIndex];
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFixedFlatArray
+
+    Method: Count
+
+    Description: Returns count
+
+    Parameters: None
+
+    Return Values: TInt: iCount
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+template <class T>
+TInt CFixedFlatArray<T>::Count() const
+    {
+    return iCount;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFixedFlatArray
+
+    Method: Set
+
+    Description: Set buffer to array.
+
+    Parameters: TInt aIndex: in: Index
+                T& aBuf: in: Buffer
+
+    Return Values: None
+
+    Errors/Exceptions: None
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+template <class T>
+void CFixedFlatArray<T>::Set( TInt aIndex, T& aBuf )
+    {
+    CheckIndex( aIndex );
+
+    iArray[aIndex] = aBuf;
+
+    }
+
+/*
+-------------------------------------------------------------------------------
+
+    Class: CFixedFlatArray
+
+    Method: CheckIndex
+
+    Description: Set buffer to array.
+
+    Parameters: TInt aIndex: in: Index to be checked
+
+    Return Values: None
+
+    Errors/Exceptions: Panics if index is incorrect
+
+    Status: Approved
+
+-------------------------------------------------------------------------------
+*/
+template <class T>
+void CFixedFlatArray<T>::CheckIndex( TInt aIndex ) const
+    {
+    if ( aIndex < 0 || aIndex >= iCount )
+        {
+        User::Panic( _L( "CFixedFlatArray: Array index out of range" ), KErrArgument );
+        }
+
+    }
+
+#endif      // TEST_ENGINE_CLIENT_INL
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/TestScripterInternal.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,234 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CScriptBase.
+*
+*/
+
+#ifndef SCRIPTRUNNERINTERNAL_H
+#define SCRIPTRUNNERINTERNAL_H
+
+// INCLUDES
+#include <StifTestModule.h>
+#include <StifLogger.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+#define ENTRY(A,B) \
+	{ (TText*) L ##A, (StifTestFunction) &B }
+
+// DATA TYPES
+
+// For function pointer operations. If need a new method that calls
+// from testscriptclass the testscripter. Add method's enum definition
+// here and implement the new method also TestScripterInternal.h need
+// new implementations.
+enum TStifTSCallBackType
+    {
+    EStifTSCallClass,
+    EStifTSGetObject,
+    };
+
+// FORWARD DECLARATIONS
+class CStifItemParser;
+class CTestScripter;
+class CScriptBase;
+
+// DATA TYPES
+typedef TInt (CScriptBase::* StifTestFunction)( CStifItemParser& );    
+class TStifFunctionInfo
+    {
+    public:
+        const TText* iFunctionName;
+        StifTestFunction iMethod;
+    };
+
+// FUNCTION PROTOTYPES
+// (Function pointer) Used to forward operations from test script class
+// to TestScripter.
+typedef TInt (*CallBackFunc)( CTestScripter* aTestScripter,
+                              TStifTSCallBackType aType,
+                              const TDesC& aLine );
+// CLASS DECLARATION
+// None
+
+// DESCRIPTION
+// This a Test Module interface template 
+// that does not really do anything.
+
+class CScriptBase 
+        :public CBase
+    {
+    public: // Enumerations
+       
+    private: // Enumerations
+       
+    public: // Constructors and destructor          
+    
+    public: // New functions
+       
+        /**
+        * Get reference to TestModuleIf API.
+        */ 
+        IMPORT_C CTestModuleIf& TestModuleIf();
+        
+        /**
+        * Signal TestScripter to continue from waittestclass.
+        */
+        IMPORT_C void Signal( TInt aError = KErrNone );
+        
+        // Called from test class. TestScripter forwards
+        // operations to other test class object.
+        // aLine: in: <object name> <method name> <parameters>
+        IMPORT_C TInt CallTestClass( const TDesC& aLine );
+        
+        // Get TestClass object pointer. Use CallTestClass instead if 
+        // you can, use this only with your own risk!!!
+        // aObjectName: in: <object name>
+        IMPORT_C CScriptBase* GetTestObject( const TDesC& aObjectName );
+        
+        // Result description can be set from within the test class method
+        IMPORT_C void SetResultDescription(const TDesC& aDescription);
+        
+    public: 
+        
+        /**
+        * Runs a script line, must be implemented in derived class.
+        */
+        virtual TInt RunMethodL( CStifItemParser& aItem ) = 0;  
+
+        /**
+        * Destructor of CScriptBase.
+        */
+        virtual ~CScriptBase(){ iSignalErrors.Reset(); iSignalErrors.Close();  };
+                
+    protected: // New functions
+
+        /**
+        * Constructor.
+        */
+        IMPORT_C CScriptBase( CTestModuleIf& aTestModuleIf );
+
+        /**
+        * Internal fuction to run specified method.
+        */
+        IMPORT_C virtual TInt RunInternalL( 
+            TStifFunctionInfo const aFunctions[], 
+            TInt aCount, 
+            CStifItemParser& aItem );
+
+        /**
+         * Internal fuction to get const value defined in 
+         * [Define]...[Enddefine] section of script file
+         */        
+        IMPORT_C TInt GetConstantValue( const TDesC& aName, TDes& aValue );
+
+
+        /**
+         * Internal fuction to get const value defined in 
+         * [Define]...[Enddefine] section of script file
+         */        
+        IMPORT_C TInt GetConstantValue( const TDesC& aName, TInt& aValue );
+
+
+        /**
+         * Internal fuction to get const value defined in 
+         * [Define]...[Enddefine] section of script file
+         */        
+        IMPORT_C TInt GetConstantValue( const TDesC& aName, TReal& aValue );
+        
+        /**
+         * Internal fuction to set value of local variable 
+         */        
+        IMPORT_C TInt SetLocalValue(const TDesC& aName, const TDesC& aValue);
+
+        /**
+         * Internal fuction to set value of local variable 
+         */        
+        IMPORT_C TInt SetLocalValue(const TDesC& aName, const TInt aValue);
+
+        /**
+         * Internal fuction to set value of local variable 
+         */        
+        IMPORT_C TInt SetLocalValue(const TDesC& aName, const TReal aValue);
+
+        /**
+         * Internal fuction to get value of local variable 
+         */        
+        IMPORT_C TInt GetLocalValue(const TDesC& aName, TDes& aValue);
+
+        /**
+         * Internal fuction to get value of local variable 
+         */        
+        IMPORT_C TInt GetLocalValue(const TDesC& aName, TInt& aValue);
+
+        /**
+         * Internal fuction to get value of local variable 
+         */        
+        IMPORT_C TInt GetLocalValue(const TDesC& aName, TReal& aValue);
+        
+    protected: // Functions from base classes
+        
+    private:
+    
+        IMPORT_C void EnableSignal( TRequestStatus& aStatus );           
+        
+        IMPORT_C void CancelSignal();
+        
+        // This set from TestScripter(Initializes function pointer to use)
+        IMPORT_C void SetScripter( CallBackFunc aFunc, CTestScripter* aTestScripter );
+
+    public: // Data
+        
+    protected: // Data
+    
+        /**
+        * Logger.
+        */
+        CStifLogger*    iLog;
+
+        /**
+        * Array for handling multiple 'waittestclass' given from testclass's
+        * test configure file.
+        */
+        RArray<TInt> iSignalErrors;
+
+    private: // Data
+        // Backpointer
+        CTestModuleIf& iTestModuleIf;
+        
+        // Completed when test class signals continue script execution
+        TRequestStatus* iStatus; 
+
+        // Backpointer to TestScripter
+        CallBackFunc iFunc;
+
+        // Backpointer
+        CTestScripter* iTestScripter;
+
+    public: // Friend classes
+        
+    protected: // Friend classes
+        
+    private: // Friend classes
+        friend class CTestScripter;
+        friend class CTestContinue;
+        
+    };
+
+#endif      // SCRIPTRUNNER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/TestServerClient.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,474 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* RTestServer, RTestModule and RTestExecution.
+*
+*/
+
+#ifndef TEST_SERVER_CLIENT_H
+#define TEST_SERVER_CLIENT_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include "TestEngineClient.h"
+#include "StifTestEventInterface.h"
+#include "StifTFwIfProt.h"
+
+// CONSTANTS
+_LIT( KDefaultExeName, "testserverstarter.exe" );
+_LIT( KDefaultUiExeName, "uitestserverstarter.exe" );
+
+// TestScripter related informations
+const TInt KTestScripterNameLength = 12;    // In STIF are two same name
+_LIT( KTestScripterName, "testscripter" );  // constants, change both when
+                                            // needed !!!
+
+// TestCombiner related information
+_LIT( KTestCombinerName, "testcombiner" );
+
+// Test module thread heap and stack sizes
+const TUint32 KTestThreadMinHeap = 4096;     // 4K heap min
+const TUint32 KTestThreadMaxHeap = 1048576;  // 1M heap max
+const TUint32 KStackSize         = 16384;    // 16K stack
+
+// MACROS
+
+// DATA TYPES
+// Opcodes used in message passing between client and server
+enum TTestServerRequests
+    {
+    // RTestServer requests
+    ETestServerCloseSession,
+    ETestServerGetServerThreadId,
+
+    // RTestModule requests
+    ETestModuleCreateSubSession,
+    ETestModuleCloseSubSession,
+    ETestModuleEnumerateTestCases,
+    ETestModuleGetTestCases,
+    ETestModuleCancelAsyncRequest,
+    ETestModuleErrorNotification,
+
+    // RTestExecution requests
+    ETestExecutionCreateSubSession,
+    ETestExecutionCloseSubSession,
+    ETestExecutionRunTestCase,      
+    ETestExecutionPause,
+    ETestExecutionResume,
+    ETestExecutionNotifyProgress,
+    ETestExecutionNotifyData,
+    ETestExecutionCancelAsyncRequest,
+    ETestExecutionNotifyEvent,
+    ETestExecutionNotifyRemoteCmd,
+    ETestExecutionReadRemoteCmdInfo,
+    ETestExecutionNotifyCommand,
+    };
+
+// 
+typedef TPckgBuf<TInt> TCaseSize;
+
+// FORWARD DECLARATIONS
+class CTestThreadContainerRunnerFactory;
+// FUNCTION PROTOTYPES
+
+// Function for starting the TestServer Server.
+IMPORT_C TInt StartNewServer( const TFileName& aModuleFileName, 
+                              TFileName& aServerName
+                            );
+
+// Function for starting the TestServer Server in either in
+// current thread or in new thread
+IMPORT_C TInt StartNewServer( const TFileName& aModuleFileName,
+                              TFileName& aServerName,
+                              const TBool aInNewThread,
+                              RSemaphore aSynchronisation
+                            );
+
+IMPORT_C TInt StartNewServer( const TFileName& aModuleFileName,
+					        TFileName& aServerName,
+					        const TBool aInNewThread,
+					        RSemaphore aSynchronisation,
+					        TBool aUiTestingServer,
+					        CTestThreadContainerRunnerFactory* aTestThreadContainerRunnerFactory
+					      );
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// RTestServer is a client class of Test Server
+// The connect function starts the server, if it not already running.
+// An RSessionBase sends messages to the server with the function 
+// RSessionBase::SendReceive();
+// specifying an opcode( TTestServerReq ) and array of argument pointers.
+
+class RTestServer
+        :public RSessionBase 
+    {
+    public: // Enumerations
+		// None
+
+    private: // Enumerations
+		// None
+
+    public:  // Constructors and destructor
+        
+        /**
+        * Constructor.
+        */
+        IMPORT_C RTestServer();
+
+        /**
+        * Closes the RTestServer session.
+        */
+        IMPORT_C void Close();
+
+    public: // New functions
+        
+        /**
+        * Connect method creates new RTestServer session that is used to manage
+        * the test case execution.
+        */
+        IMPORT_C TInt Connect( const TFileName& aModuleName,
+                               const TDesC& aConfigFile);
+
+        /**
+        * Version returns the client side version number from the RTestServer.
+        */
+        IMPORT_C TVersion Version() const;
+
+        /**
+        * GetServerThreadId returns the server thread id from the RTestServer.
+        */
+        IMPORT_C TInt GetServerThreadId( TThreadId& aId );
+    public: // Functions from base classes
+        // None
+        
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:  // Functions from base classes
+        // None
+
+        /**
+        * Find exe(CapsModifier) from file system
+        */
+        TInt FindExeL( TFileName aModuleName, TFileName& aPathAndExeModule );
+
+        /**
+        * Get caps modifier module name from TestScripter's test case(config)
+        * file.
+        */
+        TInt GetCapsModifier( const TDesC& aConfigFile,
+                                    TFileName& aCapsModifierName );
+
+    public:     // Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // None
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+    
+
+// DESCRIPTION
+
+// RTestModule class represents a subsession with the RTestServer.
+// Each RTestModule corresponds to a specific CTestModule( a CObject derived
+// class ) in the server. Messages are passed via the RTestServer.
+// A RTestModule stores a handle from it's server side CTestModule, and uses
+// this to identify the CTestModule during communication.
+
+class RTestModule
+        :public RSubSessionBase 
+    {
+    public: // Enumerations
+		// None
+
+    private: // Enumerations
+		// None
+
+    public:  // Constructors and destructor
+		// None
+
+    public: // New functions
+
+        /**
+        * Open creates a subsession to Test Server and opens handle.		
+        * The RTestServer server session shall be created by calling
+        * RTestServer::Connect before calling this function to create new
+        * RTestModule subsession.
+        */
+        IMPORT_C TInt Open( RTestServer& aServer, TFileName& aIniFile );
+
+        /**
+        * Closes the RTestModule subsession.
+        */
+        IMPORT_C void Close();
+
+        /**
+        * EnumerateTestCases requests the needed array size for test cases that
+        * will be inquired by GetTestCases method. The aConfigFile specifies the
+        *( optional ) config file where test cases are defined for this query.
+        * When the EnumerateTestCases is completed succesfully the GetTestCases
+        * method is called to retrieve test cases to
+        * CArrayFixFlat<RTestEngine::TTestInfo> list object.
+        */
+        IMPORT_C void EnumerateTestCases( TDesC& aConfigFile, 
+                                          TCaseSize& aCount,
+                                          TRequestStatus& aStatus );
+
+        /**
+        * GetTestCases is used to synchronously get test cases from Test Server.
+        * The list of test cases is retrieved to aTestCaseBuffer. Test Engine
+        * allocates needed memory for the test case array by calling
+        * EnumerateTestCases to inquire needed size of aTestCaseBuffer.
+        *
+        * If this method is called without previously succesfully called
+        * EnumerateTestCases the Test Server shall return KErrNotReady.
+        */              
+        IMPORT_C TInt GetTestCases( CFixedFlatArray<TTestCaseInfo>& aTestCaseBuffer );
+
+        
+        /**
+        *  
+        */
+        IMPORT_C void ErrorNotification( TErrorNotificationPckg& aError,                                           
+                                         TRequestStatus& aStatus );
+		
+        /**
+        * Asynchronous request can be canceled with CancelAsyncRequest method.
+        * The aReqToCancel parameter defines the request that will be canceled.
+        */
+        IMPORT_C TInt CancelAsyncRequest( TInt aReqToCancel );
+
+    public: // Functions from base classes
+        // None
+        
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:  // Functions from base classes
+        // None
+
+    public:     // Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // None
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+    
+
+// DESCRIPTION
+
+// RTestExecution class represents a subsession with the RTestServer.
+// Each RTestExecution corresponds to a specific CTestExecution( a CObject
+// derived class ) in the server. Messages are passed via the RTestServer.
+// A RTestExecution stores a handle from it's server side CTestExecution,
+// and uses this to identify the CTestExecution during communication.
+
+class RTestExecution
+        :public RSubSessionBase 
+    {
+    public: // Enumerations
+		// None
+
+    private: // Enumerations
+		// None
+
+    public:  // Constructors and destructor
+        // None       
+
+    public: // New functions
+
+        /**
+        * Open creates a subsession for new test case. Test case to be executed
+        * is specified by aTestCaseNumber. The aConfig specifies the optional
+        * config file where the test case is defined. Test cases that can be
+        * executed are retrieved from the Test Server by calling two-phased
+        * RTestModule::GetTestCases operation.
+        */
+        IMPORT_C TInt Open( RTestServer& aServer,
+                            const TInt aCaseNumber,
+                            const TFileName& aConfig );
+
+        /**
+        * Closes the RTestExecution subsession. Test case is normally closed
+        * immediately after the test case was completed.
+        */
+        IMPORT_C void Close();
+        
+         /**
+        * RunTestCase is used to execute the test case previously initialized by
+        * Open method. RunTestCase is asynchronous method and it is completed
+        * when the test case is completed.
+        * The result of the test case is returned to aStatus.
+        */
+        IMPORT_C void RunTestCase( TFullTestResultPckg& aResult,
+                                   TRequestStatus& aStatus );
+
+        /**
+       * RunTestCase is used to execute the test case previously initialized by
+       * Open method. RunTestCase is asynchronous method and it is completed
+       * when the test case is completed.
+       * The result of the test case is returned to aStatus.
+       */
+       IMPORT_C void RunTestCase( TFullTestResultPckg& aResult,
+                                  const TDesC& aTestCaseArgs,
+                                  TRequestStatus& aStatus );
+
+        /**
+        * Pause suspends the execution of the test case. The subsession where
+        * the test case is run will be suspended and thus the test case
+        * execution is suspended. The test case execution can be later resumed
+        * by calling Resume.
+        */
+        IMPORT_C TInt Pause();
+
+        /**
+        * Resume is used to resume the test case suspended by previously called
+        * Pause method. The test case execution should be continued immediately
+        * after the Resume is called.
+        */
+        IMPORT_C TInt Resume();
+
+        /**
+        * NotifyProgress requests different progress information from the Test
+        * DLL. This information can be e.g. printed to UI. Progress information
+        * is returned to aProgress. The aProgress is TTestProgressPckg that is
+        * a packaged TTestProgress.
+        */
+        IMPORT_C TInt NotifyProgress( TTestProgressPckg& aProgress,
+                                      TRequestStatus& aStatus );
+
+        /**
+        * NotifyData is used to receive different data from the Test Server,
+        * e.g. images or web pages which can be then viewed to tester or
+        * forwarded to some kind of comparison tool. 
+        */
+        IMPORT_C TInt NotifyData( TDes8& aData, TRequestStatus& aStatus );
+
+        /**
+        * Asynchronous request can be canceled with CancelAsyncRequest method.
+        * The aReqToCancel parameter defines the request that will be canceled.
+        */
+        IMPORT_C TInt CancelAsyncRequest( TInt aReqToCancel );
+
+        /**
+        * NotifyEvent is used to control event system.
+        */
+        IMPORT_C TInt NotifyEvent( TEventIfPckg& aEvent,
+                                   TRequestStatus& aStatus,
+                                   TInt aError=KErrNone );
+        
+        /**
+        * NotifyRemoteCmd is used to get notify.
+        */
+        IMPORT_C TInt NotifyRemoteCmd( TStifCommandPckg& aRemoteCommand,
+                                       TPckg<TInt>& aMsgSizePckg,
+                                       TRequestStatus& aStatus );
+                                   
+        /**
+        * ReadRemoteCmdInfo for remote message.
+        */
+        IMPORT_C TInt ReadRemoteCmdInfo( TDes8& aRemoteMsg,
+                                         TStifCommand aType,
+                                         TInt aError = KErrNone );
+
+        /**
+        * NotifyCommand is used to control commands from the test case.
+        * It was created to allow test case to kill itself. DEPRECATED !!
+        * Use NotifyCommand2 instead.
+        */
+        IMPORT_C TInt NotifyCommand(TCommandPckg& aCommandPckg,
+                                    TBuf8<KMaxCommandParamsLength>& aParamsPckg,
+                                    TRequestStatus& aStatus,
+                                    TInt aError = KErrNone);
+        
+        /**
+        * NotifyCommand is used to control commands from the test case.
+        * It was created to allow test case to kill itself.
+        */
+        IMPORT_C TInt NotifyCommand2(TCommandPckg& aCommandPckg,
+                                    TDes8& aParamsPckg,
+                                    TRequestStatus& aStatus,
+                                    TInt aError = KErrNone);
+
+    public: // Functions from base classes
+        // None
+        
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:  // Functions from base classes
+        // None
+
+    public:     // Data
+        // None
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // None
+
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+    };
+    
+
+#endif // TEST_SERVER_CLIENT_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/TestThreadContainerRunnerFactory.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CTestThreadContainerRunnerFactory class implementations.
+*
+*/
+
+#ifndef TESTTHREADCONTAINERRUNNERFACTORY_H_
+#define TESTTHREADCONTAINERRUNNERFACTORY_H_
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CTestThreadContainerRunner;
+class CUiEnvProxy;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestThreadContainerRunnerFactory class interface.
+class CTestThreadContainerRunnerFactory: public CActive
+	{
+	public: // Enumerations
+	    // None
+	
+	private: // Enumerations
+		/**
+		 * .Current operation type
+		 */
+		enum TOperationType { ECreate, // Create TestModuleContainer
+							  EDelete, // Delete TestModuleContainer
+							  ENone    // No operation
+							};
+	
+	public:  // Constructors and destructor
+		/**
+		 * C++ destructor.
+		 */
+		~CTestThreadContainerRunnerFactory();
+	
+	private:  // Constructors and destructor
+	    // None
+	
+	public: // New functions
+	    /**
+	    * NewL is first phase of two-phased constructor.
+	    */		
+		IMPORT_C static CTestThreadContainerRunnerFactory* NewL( TThreadId aThreadId, CActiveScheduler* aScheduler, CUiEnvProxy* aUiEnvProxy );
+	
+		/**
+		 * Creates new CTestThreadContainerRunner object.
+		 */
+		CTestThreadContainerRunner* CreateL();
+		
+		/**
+		 * Deletes CTestThreadContainerRunner object.
+		 */
+		void DeleteL( CTestThreadContainerRunner* aTestThreadContainerRunner );
+
+		/**
+		 * Gets UIEnvProxy.
+		 */
+		CUiEnvProxy* GetUiEnvProxy();
+	public: // Functions from base classes
+		/**
+		 * RunL derived from CActive handles the completed requests.
+		 */
+		void RunL();
+
+		/**
+		 * DoCancel derived from CActive handles the Cancel.
+		 */
+		void DoCancel();
+
+    protected:	// New functions
+        // None
+        
+    protected:	// Functions from base classes
+        // None
+        
+    private:	// New functions
+	    /**
+	    * C++ default constructor.
+	    */
+		CTestThreadContainerRunnerFactory();
+
+		/**
+	    * By default Symbian OS constructor is private.
+	    */
+		void ConstructL( TThreadId aThreadId, CActiveScheduler* aScheduler, CUiEnvProxy* aUiEnvProxy );
+
+    private:	// Functions from base classes
+        // None    
+    
+	public:		//Data
+	    // None
+        
+	protected:	// Data
+        // None
+        
+    private:	// Data
+		TThreadId iThreadId;				// Main thread id.
+		CActiveScheduler* iScheduler;		// Active scheduler from main thread.
+		CUiEnvProxy* iUiEnvProxy;			// UIEnvProxy.
+		
+		CTestThreadContainerRunner* iTestThreadContainerRunner; // Temporary pointer for CTestThreadContainerRunner
+																// which was created or should be delated.
+		TOperationType iOperation;			// Indicates current operation.
+		RSemaphore iOperationEndSemaphore;	// Operation end semaphore
+		
+    public:		// Friend classes
+        // None
+
+    protected:	// Friend classes
+        // None
+
+    private:	// Friend classes
+        // None
+	};
+
+
+#endif /*TESTTHREADCONTAINERRUNNERFACTORY_H_*/
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/TestclassAssert.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,231 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the testclass
+* assert macros.
+*
+*/
+
+#ifndef TestclassAssert_MACROS_H
+#define TestclassAssert_MACROS_H
+
+_LIT( KAssertFailedEquals, "AssertEquals Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotEquals, "AssertNotEquals Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNull, "AssertNull Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotNull, "AssertNotNull Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedSame, "AssertSame Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotSame, "AssertNotSame Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedTrue, "AssertTrue Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedFalse, "AssertFalse Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedNotLeaves, "AssertNotLeaves Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedLeaves, "AssertLeaves Failed [F:%s][L:%d]" );
+_LIT( KAssertFailedLeavesWith, "AssertLeavesWith Failed [F:%s][L:%d]" );
+
+
+#ifdef _UNICODE
+	#define __STIF_WIDEN2(x) L ## x
+	#define __STIF_WIDEN(x) __STIF_WIDEN2(x)
+	#define __STIF_DBG_FILE__ __STIF_WIDEN(__FILE__)
+#else
+	#define __STIF_DBG_FILE__ __FILE__
+#endif
+
+
+// Logs to the STIF log file AND to the RDebug
+#define STIF_LOG( aMessage ) \
+    iLog->Log( _L( aMessage ) ); RDebug::Print( _L( aMessage ) );
+
+		
+/*********************************************************************************
+ * Assert Macros
+ *********************************************************************************/
+#define __STIF_ASSERT_SHARED( aFunction, aMessage ) \
+	if(!aFunction) \
+		{ \
+		iLog->Log( aMessage, __STIF_DBG_FILE__, __LINE__ );\
+		return KErrGeneral;\
+		}
+
+#define __STIF_ASSERT_SHARED_RET( aFunction, aMessage, aFailedReturn ) \
+	if(!aFunction) \
+		{ \
+		iLog->Log( aMessage, __STIF_DBG_FILE__, __LINE__ );\
+		return aFailedReturn;\
+		}
+		
+
+#define STIF_ASSERT_EQUALS( aExpected, aActual ) \
+	__STIF_ASSERT_SHARED( AssertEquals( aExpected, aActual ) , KAssertFailedEquals );
+
+#define STIF_ASSERT_EQUALS_RET( aExpected, aActual, aFailedRet ) \
+	__STIF_ASSERT_SHARED_RET( AssertEquals( aExpected, aActual ) , KAssertFailedEquals, aFailedRet );
+
+#define STIF_ASSERT_NOT_EQUALS( aExpected, aActual ) \
+	__STIF_ASSERT_SHARED( !AssertEquals( aExpected, aActual ) , KAssertFailedNotEquals );
+
+#define STIF_ASSERT_NOT_EQUALS_RET( aExpected, aActual, aFailedRet ) \
+	__STIF_ASSERT_SHARED_RET( !AssertEquals( aExpected, aActual ) , KAssertFailedNotEquals, aFailedRet );
+
+#define STIF_ASSERT_NULL( aPtr ) \
+	__STIF_ASSERT_SHARED( AssertNull( aPtr ), KAssertFailedNull );
+
+#define STIF_ASSERT_NULL_RET( aPtr, aFailedRet ) \
+	__STIF_ASSERT_SHARED_RET( AssertNull( aPtr ), KAssertFailedNull, aFailedRet );
+
+#define STIF_ASSERT_NOT_NULL( aPtr ) \
+	__STIF_ASSERT_SHARED( !AssertNull( aPtr ), KAssertFailedNotNull );
+
+#define STIF_ASSERT_NOT_NULL_RET( aPtr, aFailedRet ) \
+	__STIF_ASSERT_SHARED_RET( !AssertNull( aPtr ), KAssertFailedNotNull, aFailedRet );
+
+#define STIF_ASSERT_SAME( aExpectedPtr, aActualPtr ) \
+	__STIF_ASSERT_SHARED( AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedSame );
+
+#define STIF_ASSERT_SAME_RET( aExpectedPtr, aActualPtr, aFailedRet ) \
+	__STIF_ASSERT_SHARED_RET( AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedSame, aFailedRet );
+
+#define STIF_ASSERT_NOT_SAME( aExpectedPtr, aActualPtr ) \
+	__STIF_ASSERT_SHARED( !AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedNotSame );
+
+#define STIF_ASSERT_NOT_SAME_RET( aExpectedPtr, aActualPtr, aFailedRet ) \
+	__STIF_ASSERT_SHARED_RET( !AssertSame( aExpectedPtr, aActualPtr ), KAssertFailedNotSame, aFailedRet );
+
+#define STIF_ASSERT_TRUE( aCondition ) \
+	__STIF_ASSERT_SHARED( AssertTrue( aCondition ), KAssertFailedTrue );
+
+#define STIF_ASSERT_TRUE_RET( aCondition, aFailedRet ) \
+	__STIF_ASSERT_SHARED_RET( AssertTrue( aCondition ), KAssertFailedTrue, aFailedRet );
+
+#define STIF_ASSERT_FALSE( aCondition ) \
+	__STIF_ASSERT_SHARED( !AssertTrue( aCondition ), KAssertFailedFalse );
+
+#define STIF_ASSERT_FALSE_RET( aCondition, aFailedRet ) \
+	__STIF_ASSERT_SHARED_RET( !AssertTrue( aCondition ), KAssertFailedFalse, aFailedRet );
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_NOT_LEAVES( aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( AssertEquals( __leaveValue, KErrNone ), KAssertFailedNotLeaves ); \
+    }
+
+#define STIF_ASSERT_NOT_LEAVES_RET( aStatement, aFailedRet ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_RET( AssertEquals( __leaveValue, KErrNone ), KAssertFailedNotLeaves, aFailedRet ); \
+    }
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_LEAVES( aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( !AssertEquals( __leaveValue, KErrNone ), KAssertFailedLeaves ); \
+    }
+
+#define STIF_ASSERT_LEAVES_RET( aStatement, aFailedRet ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_RET( !AssertEquals( __leaveValue, KErrNone ), KAssertFailedLeaves, aFailedRet ); \
+    }
+
+// Eclosing block is used to create the scope for the __leaveValue	
+#define STIF_ASSERT_LEAVES_WITH( aLeaveCode, aStatement ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED( AssertEquals( __leaveValue, aLeaveCode ), KAssertFailedLeaves ); \
+    }
+
+#define STIF_ASSERT_LEAVES_WITH_RET( aLeaveCode, aStatement, aFailedRet ) \
+    { \
+    TRAPD( __leaveValue, aStatement ); \
+    __STIF_ASSERT_SHARED_RET( AssertEquals( __leaveValue, aLeaveCode ), KAssertFailedLeaves, aFailedRet ); \
+    }
+
+#define STIF_ASSERT_PANIC( aPanicCode, aStatement ) \
+	{ \
+	TestModuleIf().SetExitReason( CTestModuleIf::EPanic, aPanicCode ); \
+	aStatement; \
+	}
+
+template <class T>
+inline TBool AssertEquals(const T& aExpected, const T& aActual)
+/**
+ * AssertEquals
+ *
+ *
+ * @param aExpected - Expected result
+ * @param aActual - Actual result
+ * @return - True if equal
+ */
+	{
+	if( aExpected==aActual )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+template <class T>
+inline TBool AssertNull(const T* aPtr)
+/**
+ * AssertNull
+ *
+ *
+ * @param aPtr - Pointer
+ * @return - True if NULL
+ */
+	{
+	if( aPtr==NULL )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+template <class T>
+inline TBool AssertSame(const T* aExpectedPtr, const T* aActualPtr)
+/**
+ * AssertSame
+ *
+ *
+ * @param aExpectedPtr - Expected pointer
+ * @param aActualPtr - Actual pointer
+ * @return - True if equal
+ */
+	{
+	if( aExpectedPtr==aActualPtr )
+		{
+		return ETrue;
+		}
+	return EFalse;
+	}
+
+inline TBool AssertTrue(const TBool& aCondition)
+/**
+ * AssertTrue
+ *
+ *
+ * @param aCondition - Condition
+ * @return - True if aCondition is true
+ */
+	{
+	if( !aCondition )
+		{
+		return EFalse;
+		}
+	return ETrue;
+	}
+
+#endif
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/UIEngine.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,297 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the UIEngine.
+*
+*/
+
+#ifndef UI_ENGINE_H
+#define UI_ENGINE_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifLogger.h>
+#include <StifTFwIf.h>
+
+#include <TestEngineClient.h>
+#include <StifTFwIfProt.h>
+
+
+// CONSTANTS
+// Log dir and file
+_LIT( KUiLogDir, "\\Logs\\TestFramework\\ui\\" );
+_LIT( KUiLogFile, "ui.txt" );
+
+// TestScripter related informations
+const TInt KTestScripterNameLength = 12;    
+_LIT( KTestScripterName, "testscripter" );  
+_LIT( KTestCombinerName, "testcombiner" ); 
+                                            
+
+// MACROS
+// None
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CUIEngineContainer;
+class CUIEngineEvent;
+class CUIEngineErrorPrinter;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+    
+// CUIIf is the interface class of STIF Test Framework UI engine 
+class CUIIf 
+    :public CBase
+    {
+    public: // Functions that the derived class may implement.
+
+        /**
+        * Test case executed.
+        *
+        * Returns Symbian OS error code.
+        */
+        virtual void TestExecuted ( CUIEngineContainer* aContainer,
+                                    TFullTestResult& aFullTestResult ) = 0;
+
+        /**
+        * Progress information from Test case execution.
+        *
+        * Returns Symbian OS error code.
+        */
+        virtual TInt PrintProg ( CUIEngineContainer* /* aContainer */,
+                                 TTestProgress& /* aProgress */ )
+                                 { return KErrNotSupported; };
+                                 
+        /**
+        * Error information from Test Framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        virtual TInt ErrorPrint ( TErrorNotification& /* aError */ )
+                                  { return KErrNotSupported; };
+    
+        /**
+        * Forward remote messages.
+        */
+        virtual TInt RemoteMsg( CUIEngineContainer* /* aContainer */,
+                                const TDesC& /* aMessage */ )
+                                 { return KErrNotSupported; };
+
+        /**
+        * Forward reboot indication.
+        */
+        virtual TInt GoingToReboot( CUIEngineContainer* /* aContainer */,
+                                    TRequestStatus& /* aStatus */ )
+                                 { return KErrNotSupported; };
+
+        /**
+        * Initialize logger.
+        */
+        virtual void InitializeLogger( CStifLogger* /*aLogger*/ ){};
+                             
+    };
+
+
+// CUIEngine is the main class of STIF Test Framework UI engine 
+class CUIEngine 
+    :public CBase
+    {
+    public: // Enumerations
+
+    protected: // Enumerations
+        
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+        
+        static CUIEngine* NewL( CUIIf* aUi );
+        
+        /**
+        * Destructor.
+        */
+        virtual ~CUIEngine();
+
+    public: // New functions
+
+        RTestEngine& TestEngine(){ return iTestEngine; }
+
+        /**
+        * Used to open TestFramework.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt Open( const TDesC& aTestFrameworkIni );
+
+        /**
+        * Used to close TestFramework.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt Close();
+
+        /**
+        * Used to add test module to test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt AddTestModule( const TDesC& aModuleName, 
+                            const TDesC& aIniFile );
+
+        /**
+        * Used to remove test module to test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt RemoveTestModule( const TDesC& aModuleName );
+
+        /**
+        * Used to add test case file for test module.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt AddTestCaseFile( const TDesC& aModuleName,
+                              const TDesC& aCaseFile );
+
+        /**
+        * Used to remove test case file from test module.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt RemoveTestCaseFile( const TDesC& aModuleName,
+                                 const TDesC& aCaseFile );
+
+        /**
+        * Get testcases from test modules. Returns test case information 
+        * in aTestinfo.
+        * Test module name and test case file can be used to limit the 
+        * set of test cases returned.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt GetTestCasesL( RPointerArray<CTestInfo>& aTestInfo,
+                            const TDesC& aTestModule = (TDesC&) KNullDesC(),
+                            const TDesC& aTestCaseFile = (TDesC&) KNullDesC() );
+
+        /**
+        * Start selected test case identified with CTestInfo.
+        * Return TestId, which is handle used in subsequent 
+        * test case execution control.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt StartTestCase( CUIEngineContainer*& aContainer,
+                            const CTestInfo& aTestInfo );
+    
+        /**
+        * Abort started test case.
+        */
+        void AbortStartedTestCase( CUIEngineContainer* aContainer );
+
+    protected: // Functions that the derived class may implement.
+
+    private:
+    
+        /**
+        * C++ default constructor.
+        */
+        CUIEngine( CUIIf* aUi );
+
+        /**
+        * Second phase constructor.
+        */
+        void ConstructL();
+
+        /**
+        * Test case executed.
+        *
+        * Returns Symbian OS error code.
+        */
+        void TestExecuted ( CUIEngineContainer* aContainer,
+                            TFullTestResult& aFullTestResult );
+
+        /**
+        * Progress information from Test case execution.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt PrintProg ( CUIEngineContainer* aContainer,
+                         TTestProgress& aProgress );
+                         
+        /**
+        * Error information from Test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt ErrorPrint ( TErrorNotification& aError );
+
+        /**
+        * Forward remote messages.
+        */
+        TInt RemoteMsg( CUIEngineContainer* aContainer,
+                        const TDesC& aMessage );
+
+        /**
+        * Forward reboot indication..
+        */
+        TInt GoingToReboot( CUIEngineContainer* aContainer, TRequestStatus& aStatus );
+
+        
+    public: // Data
+
+        // Logger 
+        CStifLogger*                            iLogger;
+
+    protected: // Data
+        // None
+        
+    private: // Data
+        
+        /**
+        * Handle to UI.
+        */
+        CUIIf*                                  iUi; 
+
+        // Handle to Test Engine Server
+        RTestEngineServer                       iTestEngineServ;
+
+        // Handle to Test Engine
+        RTestEngine                             iTestEngine;
+        
+        // Container array
+        RPointerArray<CUIEngineContainer>       iContainerArray;
+        
+        // Error printer
+        CUIEngineErrorPrinter*                  iError;
+                
+    public: // Friend classes
+        // None
+        
+    protected: // Friend classes
+        // None
+
+    private: // Friend classes
+        friend class CUIEngineContainer;
+        friend class CUIEngineEvent;
+        friend class CUIEngineErrorPrinter;
+    };
+
+#endif      // UI_ENGINE_H 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/UIEngineContainer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,243 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CUIEngine.
+*
+*/
+
+#ifndef STIF_TFW_IF_CONTAINER_H
+#define STIF_TFW_IF_CONTAINER_H
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+#include <StifTFwIf.h>
+
+#include <TestEngineClient.h>
+#include <stifinternal/UIEngine.h>
+
+// CONSTANTS
+// None
+_LIT( KUIStoreDefaultDir, "C:\\TestFramework\\" );
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+class CUIEngine;
+class CUIEngineRunner;
+class CUIEnginePrinter;
+class CUIEngineErrorPrinter;
+class CUIEngineRemote;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+
+// CUIEngineContainer is interface between main class CUIEngine
+// and CUIEngineRunner, which execute test cases
+class CUIEngineContainer
+        : public CBase
+    {
+    public: // Enumerations
+        // Case state
+        enum TCaseState
+            {
+            ENotStarted,
+            ERunning,
+            EPaused,
+            EExecuted,
+            EFinished,
+            };
+
+    private: // Enumerations
+        // None
+
+    public: // Constructor
+
+        /**
+        * NewL is two-phased constructor.
+        */
+        static CUIEngineContainer* NewL( CUIEngine* aUIEngine,
+                                const TTestInfo& aTestInfo,
+                                RTestEngineServer& aTestEngineServ,
+                                RTestEngine& aTestEngine );
+
+    public: // New functions
+
+
+    public: // Functions from base classes
+
+        /**
+        * StartContainerL starts test case execution.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt StartContainerL();
+
+        /**
+        * TestCaseExecuted informs that test case has executed.
+        */
+        void TestCaseExecuted( TFullTestResult& aResult, TInt aStatus );
+
+        /**
+        * PrintProgress forwards print information from test case.
+        */
+        void PrintProgress( TTestProgress& aProgress );
+
+        /**
+        * RemoteSend forwards remote protocol messages from master.
+        */
+        void RemoteSend( const TDesC& aRemoteMsg, TInt aStatus );
+        
+        /**
+        * GoingToReboot forwards reboot indication.
+        */
+        TInt GoingToReboot( TRequestStatus& aStatus );
+        
+        /**
+        * RemoteReceive forwards remote protocol messages to master.
+        */
+        TInt RemoteReceive( const TDesC& aRemoteMsg );
+
+        /**
+        * CancelTest cancels test case execution. TestCompleted() will be called 
+        * with aTestExecutionResult set to KErrCancel.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt CancelTest();
+
+        /**
+        * PauseTest pauses test case execution.
+        *  
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt PauseTest();
+
+        /**
+        * ResumeTest resumes test case execution.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt ResumeTest();
+        
+        /**
+        * Return remote identifier.
+        */
+        TUint32 RemoteId() const { return iRemoteId; };
+
+        /**
+        * Set remote identifier.
+        */
+        void SetRemoteId( TUint32 aRemoteId ){ iRemoteId = aRemoteId; };
+
+        /**
+        * Return master identifier.
+        */
+        TUint32 MasterId() const { return iMasterId; };
+        
+        /**
+        * Return test case execution state. 
+        */
+        TCaseState State() const { return iState; };
+        
+        /**
+        * Printer signals all prints done event.
+        */ 
+        void PrintsDone();
+
+    protected: // New functions
+        // None
+
+    protected: // Functions from base classes
+        // None
+
+    private:  // Constructors and destructor
+
+        /** 
+        * C++ default constructor.
+        */
+        CUIEngineContainer( CUIEngine* aUIEngine,
+            const TTestInfo& aTestInfo,
+            RTestEngineServer& aTestEngineServ,
+            RTestEngine& aTestEngine );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+        
+        /**
+        * Destructor of CUIEngineContainer.
+        */
+        ~CUIEngineContainer();
+
+    public: //Data
+        // Pointer to UIEngine
+        CUIEngine*                         iUIEngine;
+
+    protected: // Data
+        // None
+
+    private: // Data
+
+        // Handle to Test Engine Server
+        RTestEngineServer                   iTestEngineServ;
+
+        // Handle to Test Engine
+        RTestEngine                         iTestEngine;
+
+        // Handle to Test Case
+        RTestCase                           iTestCase;
+        
+        // Test case runner
+        CUIEngineRunner*                    iRunner;
+        
+        // Test case printer
+        CUIEnginePrinter*                   iPrinter;
+        
+        // Test case remote command handler
+        CUIEngineRemote*                    iRemote;
+
+        // Test info and package
+        TTestInfo                           iTestInfo;
+        TTestInfoPckg                       iTestInfoPckg;
+
+        // Case state
+        TCaseState                          iState;
+        
+        // Remote protocol identifier
+        TUint32                             iRemoteId;
+
+        // Master protocol identifier
+        TUint32                             iMasterId;
+
+    public: // Friend classes
+        friend class CUIEngine;
+
+    protected: // Friend classes
+   
+    private: // Friend classes
+
+    };
+
+
+#endif      // STIF_TFW_IF_CONTAINER_H 
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/UIStore.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,594 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CUIStore 
+* class
+*
+*/
+
+#ifndef UISTORE_H
+#define UISTORE_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+#include <stifinternal/UIEngine.h>
+#include <stifinternal/UIStoreIf.h>
+#include <stifinternal/UIStoreContainer.h>
+
+#include <StifLogger.h>
+
+// CONSTANTS
+_LIT( KDefaultIni, "\\testframework\\testframework.ini" );
+
+// Timeout for popups
+const TInt KDefaultPopupTimeout = 2100; // 35s. Note this is maximun time in
+                                        // current implementation(used in
+                                        // After()-method, 32bit).
+// Timeout for popups
+const TInt KRebootPopupTimeout = 1;
+
+// MACROS
+
+// DATA TYPES
+
+// Menu update type
+
+// FUNCTION PROTOTYPES
+//
+// FORWARD DECLARATIONS
+class CUIStoreIf;
+class CStartedTestCase;
+class CUIEngine;
+class CTestInfo;
+class CUIEngineContainer;
+class CStartedTestSet;
+class CUIStorePopup;
+
+// DESCRIPTION
+// CUIStore class
+class CUIStore
+        :public CUIIf
+    {
+    public: // Enumerations
+                
+    private: // Enumerations
+    
+        // Popup priorities
+        enum TPopupPriority
+            {
+            EPopupPriorityHighest,
+            EPopupPriorityNormal,
+            EPopupPriorityLow
+            };
+         
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */ 
+        static CUIStore* NewL( CUIStoreIf* iUIStoreIf );
+
+        /**
+        * Destructor of CUIStore.
+        */
+        ~CUIStore();
+
+
+    public: // New functions
+        
+        /**
+        * Used to open TestFramework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt Open( const TDesC& aTestFrameworkIni = KNullDesC );
+
+        /**
+        * Used to close TestFramework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt Close();
+
+        /**
+        * Used to add test module to test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt AddTestModule( const TDesC& aModuleName, 
+                                     const TDesC& aIniFile = KNullDesC );
+
+        /**
+        * Used to remove test module to test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt RemoveTestModule( const TDesC& aModuleName );
+
+        /**
+        * Used to add test case file for test module.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt AddTestCaseFile( const TDesC& aModuleName,
+                                       const TDesC& aCaseFile );
+
+        /**
+        * Used to remove test case file from test module.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt RemoveTestCaseFile( const TDesC& aModuleName,
+                                          const TDesC& aCaseFile );
+
+        /**
+        * Start selected test case identified with CTestInfo.
+        * anIndex contains index in StartedTestCase array, 
+        * which is valid only during execution of calling 
+        * function.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt StartTestCase( const CTestInfo& aTestInfo,
+                                     TInt& anIndex );
+                                        
+        /**
+        * Return array of existing test cases.
+        */
+        IMPORT_C TInt TestCases( RRefArray<CTestInfo>& aTestCases,
+                                 const TDesC& aTestModule = (TDesC&) KNullDesC(),
+                                 const TDesC& aTestCaseFile = (TDesC&) KNullDesC() );
+
+        
+        
+        /**
+        * Return started (running/runned) test case
+        */
+        IMPORT_C CStartedTestCase& StartedTestCaseL( TInt anIndex );
+      
+        /**
+        * Return started (running/runned) test cases
+        */
+        IMPORT_C TInt StartedTestCases( RRefArray<CStartedTestCase>& aTestCases,
+                               TInt aStatus = CUIStoreIf::EStatusAll,
+                               const TDesC& aTestModule = (TDesC&) KNullDesC(),
+                               const TDesC& aTestCaseFile = (TDesC&) KNullDesC() );        
+        
+        /**
+        * Return modules array
+        */
+        IMPORT_C TInt Modules( RRefArray<TDesC>& aTestModules );
+
+        /**
+        * Return test case files
+        */
+        IMPORT_C TInt TestCaseFiles( RRefArray<TDesC>& aTestCaseFiles,
+                            const TDesC& aTestModule = (TDesC&) KNullDesC() );
+
+
+        /**
+        * Loads all TestFramework test modules from \sys\bin\ directories 
+        * of all drives.
+        */
+        IMPORT_C TInt LoadAllModules();
+        
+        /**
+        * Lists all TestFramework test modules from \sys\bin\ directories 
+        * of all drives.
+        */
+        IMPORT_C TInt ListAllModules( RPointerArray<TDesC>& aModuleNames );
+
+
+        /**
+        * Test set support.
+        */
+                                     
+        /**
+        * Create new test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt CreateTestSet( const TDesC& aSetName );
+
+        /**
+        * Remove active test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt RemoveTestSet( const TDesC& aSetName );
+        
+        /**
+        * Query test sets.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt TestSets( RRefArray<CTestSetInfo>& aSetInfos );        
+
+        /**
+        * Query test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C const CTestSetInfo& TestSetL( const TDesC& aSetName  );                
+        
+        /**
+        * Add test case to test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt AddToTestSet( const TDesC& aSetName, const CTestInfo& aTestInfo );
+ 
+        /**
+        * Insert test case to test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt InsertToTestSet( const TDesC& aSetName, 
+                                       const CTestInfo& aTestInfo, 
+                                       TInt aPos );
+ 
+        /**
+        * Remove test case from test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt RemoveFromTestSet( const TDesC& aSetName, const CTestInfo& aTestInfo );
+        
+        /**
+        * Save test set. Depreceated, SaveTestSet2 to be used instead
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt SaveTestSet( const TDesC& aSetName );
+
+        /**
+        * Save test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt CUIStore::SaveTestSet2( TDes& aSetName );
+        /**
+        * Load test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt LoadTestSet( const TDesC& aSetName );
+
+        /**
+        * Unload active test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt UnloadTestSet( const TDesC& aSetName );
+        
+        
+        /**
+        * Load saved test cases.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt LoadSavedTestCases();
+                
+        /**
+        * Start selected test set identified with CTestSetInfo.
+        * anIndex contains index in StartedTestSet array, 
+        * which is valid only during execution of calling 
+        * function.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt StartTestSet( const CTestSetInfo& aTestSetInfo,
+                                    TInt& anIndex,
+                                    CStartedTestSet::TSetType aType = 
+                                        CStartedTestSet::ESetSequential );
+        IMPORT_C TInt StartTestSet( const CTestSetInfo& aTestSetInfo,
+                                    TInt& anIndex,
+                                    CStartedTestSet::TSetType aType,
+                                    TBool aNotStartedCasesMode);
+
+        /**
+        * Abort running test set.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt AbortTestSet( CStartedTestSet& aSetInfo );
+
+        /**
+        * Return started (running/runned) test set
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C CStartedTestSet& StartedTestSetL( TInt anIndex );
+      
+        /**
+        * Return started (running/runned) test cases
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt StartedTestSets( RRefArray<CStartedTestSet>& aTestCases,
+                                       TInt aStatus = CUIStoreIf::ESetAll );       
+
+        /**
+        * Updates information stored about test set in file.
+        *
+        * Returns Symbian OS error code.
+        */
+        IMPORT_C TInt UpdateTestSet(CTestSetInfo& aSetInfo);
+        
+        /**
+        * Reads filters (if any) from initialization file.
+        */
+        IMPORT_C void ReadFiltersL(RPointerArray<TDesC>& aFilters);
+        
+        /**
+        * Creates list of available Test Sets.
+        *
+        * Returns Symbian OS error code.
+        */
+        
+        IMPORT_C TInt GetTestSetsList( RRefArray<TDesC>& aArray );
+        
+
+    public: // Functions from base classes
+
+
+    protected:  // New functions
+        // None
+
+    protected:  // Functions from base classes
+        // None
+
+    private:
+
+        /** 
+        * C++ default constructor.
+        */
+        CUIStore( CUIStoreIf* iUIStoreIf );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL();
+        
+        /**
+        * Test case executed.
+        *
+        * Returns Symbian OS error code.
+        */
+        void TestExecuted ( CUIEngineContainer* aContainer,
+                            TFullTestResult& aFullTestResult );
+
+        /**
+        * Progress information from Test case execution.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt PrintProg ( CUIEngineContainer* aContainer,
+                         TTestProgress& aProgress );
+
+        /**
+        * Error information from Test framework.
+        *
+        * Returns Symbian OS error code.
+        */
+        TInt ErrorPrint( TErrorNotification& aError );
+                         
+        /**
+        * Remote protocol messages handler.
+        */
+        TInt RemoteMsg( CUIEngineContainer* aContainer,
+                        const TDesC& aMessage );
+        /**
+        * Reboot indication handler.
+        */
+        TInt GoingToReboot( CUIEngineContainer* aContainer,
+                            TRequestStatus& aStatus );
+        
+        TInt MsgRemote( CUIEngineContainer* aContainer,
+                        CStifTFwIfProt& aReq, 
+                        CStifTFwIfProt& aResp );
+        TInt MsgRemoteRun( CUIEngineContainer* aContainer,
+                           CStifTFwIfProt& aReq, 
+                           CStifTFwIfProt& aResp );
+        TInt MsgRemoteTestCtl( CUIEngineContainer* aContainer,
+                               CStifTFwIfProt& aReq, 
+                               CStifTFwIfProt& aResp );
+        TInt MsgRemoteEventCtl( CUIEngineContainer* aContainer,
+                                CStifTFwIfProt& aReq, 
+                                CStifTFwIfProt& aResp );
+
+        /**
+        * Asynchronous remote sendreceive message.
+        */
+        TInt MsgRemoteSendReceive( CUIEngineContainer* aContainer,
+                           CStifTFwIfProt& aReq, 
+                           CStifTFwIfProt& aResp );
+        
+        /**
+        * Initialize logger from UI engine.
+        */
+        inline void InitializeLogger( CStifLogger* aLogger )
+            { iLogger = aLogger; };
+        
+        /**
+        * Set update flag.
+        */
+        inline void RefreshAllCases()
+            { iUpdateNeeded = ETrue; };
+            
+        /**
+        * Update test case list if required.
+        */
+        TInt UpdateCases();
+        
+        /**
+        * Try to locate default initialization file.
+        */
+        void CheckIniL( TFileName& aIni );
+        
+        /**
+        * Find testcase by container.
+        */
+        TInt FindByContainer( CUIEngineContainer* const aContainer,
+                              CStartedTestCase*& aTestCase );
+
+        /**
+        * Loads all TestFramework test modules from \sys\bin\ directories .
+        */
+        void LoadAllModulesL();
+        
+        /**
+        * Lists all TestFramework test modules from \sys\bin\ directories.
+        */
+        void ListAllModulesL( RPointerArray<TDesC>& aModuleNames );
+        
+        /**
+        * Find test set by name.
+        */
+        TInt FindSetByName( const TDesC& aSetName, CTestSetInfo*& aSetInfo );
+        
+        /**
+        * Find test set by CStartedTestCase.
+        */
+        TInt FindStartedSetByCase( const CStartedTestCase* aTestCase, 
+                                   CStartedTestSet*& aSet  );
+   
+        /**
+        * Load test set.
+        */
+        void LoadTestSetL( const TDesC& aSetName, const TDesC& aSetFileName );
+        
+        /**
+        * Save test set.
+        */ 
+        void SaveTestSetL( CTestSetInfo& aSetInfo, const TDesC& aSetFileName );
+
+        /**
+        * Updates in file information about test set.
+        */ 
+        void UpdateTestSetL(CTestSetInfo& aSetInfo, const TDesC& aSetFileName);
+        
+        /**
+        * Read the whole line from the file.
+        */ 
+        void ReadLineL(RFile &file, TDes& buffer);
+
+        /**
+        * Write given line to the file and adds end of line.
+        */ 
+        void WriteLineL(RFile &file, const TDesC& buffer);
+
+        /**
+        * Load saved executed test cases.
+        *
+        * Returns Symbian OS error code.
+        */
+        void LoadExecutedTestCasesL();
+        
+        /**
+        * Load test modules and test case files used in 
+        * aTestCases if not already done.
+        */
+        void LoadTestModulesAndTestCaseFilesL( const RRefArray<const CTestInfo>& aTestCases );
+        
+        /**
+        * Parse test set name from test set file name.
+        */
+        TInt ParseTestSetName( const TDesC& aSetFileName, TPtrC& aSetName, TFileName& aFileName );
+        
+        /**
+        * Do remote popup. Added aPopupPriority parameter for prioritizing popups @js      
+        */
+        TInt RemotePopup( CUIEngineContainer* aContainer,
+                          const TDesC& aReq, 
+                          CStifTFwIfProt* aResp,
+                          TPopupPriority aPopupPriority = EPopupPriorityLow);        
+        
+        /**
+        * Callback from UIStorePopup.
+        */
+        TInt RemotePopupComplete( CUIStorePopup* aPopup, 
+                                  TInt aError,
+                                  CUIEngineContainer* aContainer,
+                                  CStifTFwIfProt* aResp,
+                                  TKeyCode aKeyCode );
+        /**
+        * Return slave id.
+        */
+        inline TInt16 DevId(){ return 1; };
+        
+        /**
+        * Prints the highest priority popup from queue
+        */
+        void SetRemotePopupFromQueue();
+        
+        /**
+        * Shuffles remote run result popups
+        */
+        void ShuffleRemoteRunResultPopups( CUIStorePopup* aPopup );
+        
+    public:   //Data
+        // Logger
+        CStifLogger*                        iLogger;
+
+    protected:  // Data
+        // None
+
+    private:    // Data
+    	RPointerArray<HBufC> 				iFileList;
+        // Pointer to UI (up)
+        CUIStoreIf*                         iUIStoreIf;   
+        
+        // Pointer to UI engine (down)
+        CUIEngine*                          iUIEngine;
+
+    	// Available test cases   
+        RPointerArray<CTestInfo>            iTestCases;    
+        // Started test cases    
+        RPointerArray<CStartedTestCase>     iStartedTestCases; 
+ 
+    	// Available test sets   
+        RPointerArray<CTestSetInfo>         iTestSets;    
+        // Started test sets    
+        RPointerArray<CStartedTestSet>      iStartedTestSets; 
+        
+        RPointerArray<CUIStorePopup>        iPopups;
+               
+        // Flag for update for test case list required
+        TBool                               iUpdateNeeded;
+        
+        // Tells if popup is already active
+        TBool                               iPopupActive;
+        
+        // Priority of the currently active popup
+        TPopupPriority                      iActivePopupPriority;        
+        
+        TFileName                           iTestFrameworkIni;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        friend class CUIStorePopup;
+
+    };
+    
+#endif // UISTORE_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/UIStoreContainer.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,349 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the 
+* CTestCaseRunnner, CTestCasePrinter and CStartedTestCase
+*
+*/
+
+#ifndef UISTORECASECONTAINER_H
+#define UISTORECASECONTAINER_H
+
+
+//  INCLUDES
+#include <e32std.h>
+#include <e32base.h>
+
+#include <StifTestInterface.h>
+
+#include <stifinternal/RRefArray.h>
+
+// CONSTANTS
+
+// MACROS
+
+// DATA TYPES
+
+// FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CUIEngineContainer;
+class CTestInfo;
+class CUIStore;
+class CTestSetInfo;
+
+// DESCRIPTION
+// CTestProgress defines the progress information from Test Module.
+class CTestProgress
+    :public CBase 
+    {
+    public:
+        static CTestProgress* NewL( const TTestProgress& aProgress );
+
+        ~CTestProgress();
+        
+        void ReplaceTextL( const TTestProgress& aProgress );
+    
+    private:
+        void ConstructL( const TTestProgress& aProgress );
+
+    public:
+        // "Priority" of the progress information.
+        TInt iPosition;
+        // Description of the data to be printed.
+        TPtrC iDescription;
+        // The actual progress information.
+        TPtrC iText;
+    
+    private:
+        // Description of the data to be printed.
+        HBufC* iDescriptionBuf;
+        // The actual progress information.
+        HBufC* iTextBuf;
+
+    };
+
+// DESCRIPTION
+// CStartedTestCase contains active objects that handles one test case
+class CStartedTestCase 
+    :public CBase  
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CStartedTestCase* NewL( const CTestInfo& aTestInfo, 
+                                       CUIEngineContainer& aContainer );
+
+        /**
+        * Destructor of CStartedTestCase.
+        */
+        virtual ~CStartedTestCase();
+
+    public: // New functions
+    
+        /**
+        * Get Engine container handle.
+        */
+        IMPORT_C CUIEngineContainer& UIEngineContainer() const;
+            
+        /**
+        * Set case result
+        */
+        void SetResult( const TFullTestResult& aResult );
+
+        /**
+        * Get test case info.
+        */    
+        inline CTestInfo const& TestInfo() const
+            { return *iTestInfo; }; 
+               
+        /**
+        * Return the result
+        */
+        inline const TFullTestResult& Result() const
+            { return iResult; };
+
+        /**
+        * Return the print array
+        */
+        inline RPointerArray<CTestProgress>& PrintArray()
+            { return iPrints; };
+        inline const RPointerArray<CTestProgress>& PrintArray() const
+            { return iPrints; };
+        
+        /**
+        * Get status.
+        */
+        inline TInt Status() const { return iStatus; }
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:   // Functions from base classes
+        
+        /** 
+        * C++ default constructor.
+        */
+        CStartedTestCase( CUIEngineContainer& aContainer );
+       
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const CTestInfo& aTestInfo );
+        
+        /**
+        * Private constructor for internal use.
+        */
+        CStartedTestCase( CTestInfo* aTestInfo, 
+                          TFullTestResult aResult, 
+                          TInt aStatus  );
+        
+    public:      //Data
+        /**
+        * Backpointer that can be utilized by UI, not used from UI Engine.
+        */
+        TAny*       iBackPtr;
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        CUIEngineContainer*             iContainer;
+        CTestInfo*                      iTestInfo;
+        TFullTestResult                 iResult;   // Test case result
+        
+        RPointerArray<CTestProgress>    iPrints;   // Prints from case
+
+        // Execution status (flags from CUIStoreIf::TUpdateFlags)
+        TInt                            iStatus;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        friend class CUIStore;
+
+    };
+
+// DESCRIPTION
+// CStartedTestSet contains test set information
+class CStartedTestSet 
+    :public CBase  
+    {
+    public: // Enumerations
+        enum TSetType
+            {
+            ESetSequential,
+            ESetParallel,
+            };
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CStartedTestSet* NewL( CUIStore* aUIStore, 
+                                      const CTestSetInfo& aTestSetInfo,
+                                      TSetType aType );
+
+        /**
+        * Destructor of CStartedTestCase.
+        */
+        virtual ~CStartedTestSet();
+
+    public: // New functions
+    
+        /**
+        * Get test case info.
+        */    
+        inline CTestSetInfo const& TestSetInfo() const
+            { return *iTestSetInfo; }; 
+               
+        /**
+        * Return the result
+        */
+        inline const TFullTestResult& Result() const
+            { return iResult; };
+
+        /**
+        * Get status.
+        */
+        inline TInt Status() const { return iStatus; }
+        
+        /**
+        * Get test cases runned/running in test set.
+        */
+        inline const RRefArray<CStartedTestCase>& TestCases() const
+            { return iTestCases; };
+        
+        /**
+        * Get type.
+        */ 
+        inline TSetType Type(){ return iType; };        
+        
+        /**
+        * Start next testcase. Returns KErrNotFound if does not exits.
+        */ 
+        TInt StartNext();
+        
+        /**
+        * Abort running testcases.
+        */ 
+        TInt Abort();
+        
+        /**
+        * Check if test case running in this test set.
+        */
+        TBool IsRunning( const CStartedTestCase* aTestCase ); 
+        
+        /**
+        * Test from this set completed.
+        */
+        TInt TestCompleted( const CStartedTestCase* aTestCase, 
+                            TFullTestResult aResult );
+                            
+        /**
+        * Sets mode in which only not executed tests will be run.
+        */
+        void SetNotStartedCasesMode(TBool aNotStartedCasesMode);
+        
+        /**
+        * Returns pointer to original test set.
+        */
+        CTestSetInfo* GetOriginalTestSet();
+
+        /**
+        * Sets pointer to original test set to NULL.
+        */
+        void NullOriginalTestSet();
+
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:   // Functions from base classes
+        /** 
+        * C++ default constructor.
+        */
+        CStartedTestSet( CUIStore* aUIStore, TSetType aType );
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const CTestSetInfo& aTestSetInfo );
+
+    public:      //Data
+        /**
+        * Backpointer that can be utilized by UI, not used from UI Engine.
+        */
+        TAny*       iBackPtr;
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        // Backpointer
+        CUIStore*                       iUIStore;
+        
+        CTestSetInfo*                   iTestSetInfo;
+        TFullTestResult                 iResult;   // Test case result
+        TBool                           iResultSet;
+        
+        RRefArray<CStartedTestCase>     iTestCases;
+        
+        TSetType                        iType;
+
+        // Execution status (flags from CUIStoreIf::TUpdateFlags)
+        TInt                            iStatus;
+        
+        // Next case to start        
+        TInt                            iNext;
+        // Number of running cases
+        TInt                            iRunningCases;
+        
+        // In this mode only not executed tests will be run
+        TBool                           iNotStartedCasesMode;
+        
+        // Original test set
+        CTestSetInfo*                   iOriginalTestSet;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif // UISTORECASECONTAINER_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/UIStoreIf.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,271 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CUIStore.
+*
+*/
+
+#ifndef UISTOREIF_H
+#define UISTOREIF_H
+
+// INCLUDES
+#include <e32std.h>
+#include <e32keys.h>
+
+#include <StifTestInterface.h>
+
+#include <stifinternal/RRefArray.h>
+
+// EXTERNAL DATA STRUCTURES
+
+// EXTERNAL FUNCTION PROTOTYPES  
+
+// CONSTANTS
+
+// MACROS
+
+// LOCAL CONSTANTS AND MACROS
+
+// MODULE DATA STRUCTURES
+
+// LOCAL FUNCTION PROTOTYPES
+
+// FORWARD DECLARATIONS
+class CUIStore;
+class CStartedTestCase;
+class CTestInfo;
+
+// CONSTANTS
+
+// CLASS DECLARATION
+
+/**
+* UI Store class interface. UI must derive this to use UI Store.
+*/
+class CUIStoreIf 
+    :public CBase
+    {
+    public: // Enumerations
+        // Updated flags
+        enum TUpdateFlags
+            {
+            // Test case status updates 
+            EStatusRunning  = 0x00000001,
+            EStatusExecuted = 0x00000002,
+            EStatusPassed   = 0x00000004,
+            EStatusFailed   = 0x00000008,
+            EStatusAborted  = 0x00000010,
+            EStatusCrashed  = 0x00000020,
+            EStatusAll      = 0x000000ff,
+            // Test set updates
+            ESetRunning     = 0x00000100,
+            ESetExecuted    = 0x00000200,
+            ESetPassed      = 0x00000400,
+            ESetFailed      = 0x00000800,
+            ESetAll         = 0x0000ff00,
+            // Other updates
+            EPrintUpdate    = 0x00010000,                              
+            };
+            
+    private: // Enumerations
+        // None
+        
+    public: // Constructors and destructor
+    
+        /**
+        * Destructor.
+        */      
+        IMPORT_C ~CUIStoreIf();
+        
+    protected:
+        /**
+        * Constructor
+        */
+        IMPORT_C CUIStoreIf();
+
+        /**
+        * Symbian OS second phase constructor. This must be called 
+        * from derived class ConstructL.
+        */      
+        IMPORT_C void ConstructL();
+        
+    public: // New functions
+        /**
+        * Returns reference to CUIStore object, 
+        * which handles test cases and test modules.
+        */
+        IMPORT_C CUIStore& UIStore();
+
+        /**
+        * Receives output update notification from CUIStore.
+        * UI implements this to get update notifications. 
+        * aFlags are from 
+        */
+        virtual void Update( CStartedTestCase* /*aTestCase*/, 
+                             TInt /* aFlags */ ){};
+                                   
+                                   
+        /**
+        * Function is called when test framework prints error.
+        */
+        virtual void Error( TErrorNotification& /*aError*/ ){};
+        
+        /**
+        * Function is called to print message to UI.
+        */
+        virtual TInt PopupMsg( const TDesC& /* aLine1 */, 
+                               const TDesC& /* aLine2 */, 
+                               TInt /* aTimeInSecs */ )
+            { return KErrNotSupported; };
+            
+        /**
+        * Function is called to print message to UI
+        * and wait key pressing.
+        */
+        virtual TInt PopupMsg( const TDesC& /* aLine1 */, 
+                               const TDesC& /* aLine2 */, 
+                               TInt /* aTimeInSecs */,
+                               TKeyCode& /* aKey */,
+                               TRequestStatus& /* aStatus */ )
+            { return KErrNotSupported; };
+       
+       /**
+        * Function is called to close instances.
+        */
+        virtual void Close( TInt /* aHandle */ ){};
+
+    public: // Functions from base classes
+
+    private: 
+
+    private:
+    
+    private: // Data
+		CUIStore*					    iUIStore;
+		
+    };
+    
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CTestSetInfo contains test set information
+class CTestSetInfo 
+    :public CBase  
+    {
+    public: // Enumerations
+
+    private: // Enumerations
+
+    public:  // Constructors and destructor
+
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        static CTestSetInfo* NewL( const TDesC& aName );
+
+        /**
+        * Destructor of CStartedTestCase.
+        */
+        virtual ~CTestSetInfo();
+
+    public: // New functions
+        
+        /**
+        * Get test set name.
+        */
+        inline const TDesC& Name() const 
+            { return *iName; };
+        
+        /**
+        * Get test cases.
+        */
+        inline const RRefArray<const CTestInfo>& TestCases() const
+            { return iTestCaseRefs; };
+        
+        /**
+        * Add test case to set.
+        */
+        TInt AddTestCase( const CTestInfo& aTestInfo );
+        
+        /**
+        * Insert test case to specific location.
+        */
+        TInt InsertTestCase( const CTestInfo& aTestInfo, TInt aPos );
+     
+        /**
+        * Remove test case from set.
+        */
+        TInt RemoveTestCase( const CTestInfo& aTestInfo );
+        
+        /**
+        * NewL is first phase of two-phased constructor.
+        */
+        void CopyL( const CTestSetInfo& aTestSetInfo );
+        
+        /**
+        * Sets the info which test case has been started lately.
+        */
+        void SetLastStartedCaseIndex(TUint aLastStartedCaseIndex);
+
+        /**
+        * Gets the info which test case has been started lately.
+        */
+        TUint GetLastStartedCaseIndex(void);
+        /**
+        * rename test set
+        */
+        void RenameTestSet(const TDesC& aTestSetName);
+                
+    public: // Functions from base classes
+
+    protected:  // New functions
+
+    protected:  // Functions from base classes
+
+    private:   // Functions from base classes
+        /** 
+        * C++ default constructor.
+        */
+        CTestSetInfo();       
+
+        /**
+        * By default Symbian OS constructor is private.
+        */
+        void ConstructL( const TDesC& aName );
+
+    public:     // Data
+    
+    protected:  // Data
+        // None
+
+    private:    // Data
+        RRefArray<const CTestInfo>      iTestCaseRefs;
+        RPointerArray<CTestInfo>        iTestCases;
+        HBufC*                          iName;
+        // Which test case was started as a last one (index)
+        TUint                           iLastStartedCaseIndex;
+        
+    public:     // Friend classes
+        // None
+
+    protected:  // Friend classes
+        // None
+
+    private:    // Friend classes
+        // None
+
+    };
+
+#endif // UISTOREIF_H
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/UiEnvProxy.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the UI Proxy 
+* interface.
+*
+*/
+
+#ifndef UIENVPROXY_H_
+#define UIENVPROXY_H_
+
+//  INCLUDES
+#include <e32base.h>
+
+// CONSTANTS
+// None
+
+// MACROS
+// None
+
+// DATA TYPES
+// None
+
+// FUNCTION PROTOTYPES
+// None
+
+// FORWARD DECLARATIONS
+// None
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// Interface class for the proxy betweene testscripter and AppUi.
+class CUiEnvProxy: public CBase
+	{
+	public: // Enumerations
+	    // None
+	
+	private: // Enumerations
+	    // None
+	
+	public:  // Constructors and destructor
+	    // None
+	
+	public: // New functions
+		/**
+		 * Parses key code.
+		 */
+		virtual TInt ParseKeyCode( const TDesC& aKeyCodeName, TUint& aKeyCode ) const = 0;
+		
+		/**
+		 * Parses key scan code.
+		 */
+		virtual TInt ParseKeyScanCode( const TDesC& aKeyScanCodeName, TInt& aKeyScanCode ) const = 0;
+		
+		/**
+		 * Parses key modifier.
+		 */
+		virtual TInt ParseModifier( const TDesC& aModifierName, TUint& aModifier ) const = 0;
+	
+		/**
+		 * Parse pointer event type
+		 */
+		virtual TInt ParsePointerEventType( const TDesC& aPointerEventTypeName, TUint& aPointerEventType ) const = 0;
+	
+		/**
+		 * Brings UI control container to foreground.
+		 */
+		virtual void BringToForeground() = 0;
+		
+		/**
+		 * Sends UI control container to background.
+		 */
+		virtual void SendToBackground() = 0;
+		
+		/**
+		 * Sends local key event to UI control.
+		 */
+		virtual void PressKeyL( TRequestStatus* aStatus, TUint aKeyCode, TInt aKeyScanCode = 0, 
+							   TUint aKeyModifiers = 0, TInt keyRepeats = 0 ) = 0;
+		
+		/**
+		 * Sends local key event to UI control.
+		 */
+		virtual void PressKeyL( TUint aKeyCode, TInt aKeyScanCode = 0, 
+							   TUint aKeyModifiers = 0, TInt keyRepeats = 0 ) = 0;
+
+		/**
+		 * Sends text to UI control.
+		 */
+		virtual void TypeTextL( TRequestStatus* aStatus, const TDesC& aText ) = 0;
+
+		/**
+		 * Sends text to UI control.
+		 */
+		virtual void TypeTextL( const TDesC& aText ) = 0;		
+		
+		/**
+		 * Send pointer event
+		 */
+		virtual void SendPointerEventL( TUint aType, const TPoint& aPosition ) = 0;
+
+		/**
+		 * Send local pointer event
+		 */
+		virtual void SendPointerEventL( TRequestStatus* aStatus, TUint aType, const TPoint& aPosition ) = 0;
+
+    public: // Functions from base classes
+        // None
+
+    protected:	// New functions
+        // None
+        
+    protected:	// Functions from base classes
+        // None
+        
+    private:	// New functions
+    	// None
+	
+	public:		//Data
+	    // None
+        
+	protected:	// Data
+        // None
+        
+    private:	// Data
+        // None
+		
+    public:		// Friend classes
+        // None
+
+    protected:	// Friend classes
+        // None
+
+    private:	// Friend classes
+        // None
+	};
+
+#endif // UIENVPROXY_H_
+
+// End of File
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stif/stif_plat/inc/atslogger.h	Wed Oct 13 16:17:58 2010 +0300
@@ -0,0 +1,581 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+* 
+* Description: This file contains the header file of the CAtsLogger 
+* class.
+*
+*/
+
+#ifndef __ATSLOGGER_H__
+#define __ATSLOGGER_H__
+
+//  INCLUDES
+#include <f32file.h>
+
+// CONSTANTS
+_LIT(KAtsLogger, "AtsLogger");
+_LIT(KAtsLoggerNa, "NA");
+_LIT(KAtsLoggerPassed, "PASSED");
+_LIT(KAtsLoggerFailed, "FAILED");
+_LIT(KAtsLoggerSkipped, "SKIPPED");
+_LIT(KAtsLoggerEmpty, "");
+_LIT(KAtsLoggerSemaphore, "AtsLogger");
+_LIT(KAtsLoggerXmlDirectory, "\\SPD_LOGS\\XML\\");
+_LIT(KAtsLoggerRawDirectory, "\\SPD_LOGS\\RAW\\");
+_LIT(KAtsLoggerXmlSuffix, ".xml");
+_LIT(KAtsLoggerRawSuffix, ".log");
+
+_LIT(KAtsLoggerTagOpen, "<");
+_LIT(KAtsLoggerSpace, " ");
+_LIT(KAtsLoggerAttr, "=\"");
+_LIT(KAtsLoggerAttrClose, "\">");
+_LIT(KAtsLoggerTagPost, ">");
+_LIT(KAtsLoggerTagClose, "</");
+_LIT(KAtsLoggerLf, "\n");
+_LIT(KAtsLoggerIndent, "  ");
+_LIT8(KAtsLoggerIndent8, "  ");
+_LIT(KAtsLoggerCommentOpen, "<!--");
+_LIT(KAtsLoggerCommentClose, "-->");
+_LIT(KAtsLoggerQuot, "&quot;");
+_LIT(KAtsLoggerAmp, "&amp;");
+_LIT(KAtsLoggerApos, "&apos;");
+_LIT(KAtsLoggerLt, "&lt;");
+_LIT(KAtsLoggerGt, "&gt;");
+
+_LIT8(KAtsLoggerQuot8, "&quot;");
+_LIT8(KAtsLoggerAmp8, "&amp;");
+_LIT8(KAtsLoggerApos8, "&apos;");
+_LIT8(KAtsLoggerLt8, "&lt;");
+_LIT8(KAtsLoggerGt8, "&gt;");
+_LIT8(KAtsLoggerEmpty8, "");
+
+_LIT(KAtsLoggerTagTestReport, "test-report");
+_LIT(KAtsLoggerTagTestSet, "test-batch");
+_LIT(KAtsLoggerTagTestCase, "test-case");
+_LIT(KAtsLoggerTagTestSetInit, "batch-init");
+_LIT(KAtsLoggerTagDescription, "description");
+_LIT(KAtsLoggerTagDate, "date");
+_LIT(KAtsLoggerTagFactory, "factory");
+_LIT(KAtsLoggerTagComponent, "component");
+_LIT(KAtsLoggerTagName, "name");
+_LIT(KAtsLoggerTagVersion, "version");
+_LIT(KAtsLoggerTagTestSetResult, "batch-result");
+_LIT(KAtsLoggerTagId, "id");
+_LIT(KAtsLoggerTagTestCaseInit, "case-init");
+_LIT(KAtsLoggerTagExpected, "expected-result");
+_LIT(KAtsLoggerTagRunTime, "run-time");
+_LIT(KAtsLoggerTagTestCaseResult, "case-result");
+_LIT(KAtsLoggerTagActual, "actual-result");
+_LIT(KAtsLoggerTagDebug, "debug-info");
+_LIT(KAtsLoggerTagWarning, "warning");
+_LIT(KAtsLoggerTagError, "error");
+_LIT(KAtsLoggerTagStatus, "status");
+_LIT(KAtsLoggerTimeStamp, "time-stamp");
+
+const TInt KAtsLoggerBufferSegmentGranularity = 32;
+
+// CLASS DECLARATION
+
+// DESCRIPTION
+// CAtsLogger defines API for test case result logging.
+class CAtsLogger : public CBase
+	{
+	public:	// Public enumerations
+		enum TReportStage
+			{
+			ENone,
+			EUninitialized,
+			EBeginTestReport,
+			EBeginTestSet,
+			EBeginTestCase,
+			ESetTestCaseVerdict,
+			EEndTestCase,
+			EEndTestSet,
+			EEndTestReport,
+			EFinished
+			};
+	private:	// Private enumerations
+				// None
+
+	public:	// Public constructors/desctructors
+		
+		/**
+		 * Symbian OS constructor
+		 */
+		IMPORT_C static CAtsLogger* NewL( const TDesC& aName, 
+		                                  TBool aAfterReboot = EFalse );
+
+		/**
+		 * C++ destructor
+		 */
+		IMPORT_C ~CAtsLogger();
+
+	public:	// Public new functions
+
+		/**
+		 * Returns error message. Also includes
+		 * base E32 error codes.
+		 */
+		IMPORT_C static const TPtrC ErrorMessage(const TInt& aError);
+
+		/**
+		 * Closes opened resources. Desctructor calls
+		 * this if it is not called before.
+		 */
+		IMPORT_C void CloseL();
+
+		/**
+		 * IsValid() returns ETrue if this logger is valid and
+		 * able to write log.
+		 */
+		IMPORT_C TBool IsValid();
+	
+		/**
+		 * BeginTestReportL() should be called at the beginning of the program,
+		 * before any testing begins
+		 */
+		IMPORT_C void BeginTestReportL();
+
+		/**
+		 * EndTestReportL() must be called at the end of the program
+		 */
+		IMPORT_C void EndTestReportL();
+		
+		/**
+		 * SaveForRebootL() should be called before reboot to save data.
+		 */
+		IMPORT_C void SaveForRebootL();
+
+		/**
+		 * ContinueAfterRebootL() must be called to continue 
+		 * after reboot.
+		 */
+		IMPORT_C void ContinueAfterRebootL();
+
+		/**
+		 * BeginTestSetL() must be called when a new test set begins
+		 *
+		 * factory     = component factory whose component is being tested
+		 * component   = name of the software component being tested
+		 * version     = version of the software component
+		 * description = short, optional description of the batch
+		 */
+		IMPORT_C void BeginTestSetL(const TDesC& aFactory = KAtsLoggerNa,
+								    const TDesC& aComponent = KAtsLoggerNa,
+								    const TDesC& aVersion = KAtsLoggerNa,
+								    const TDesC& aDescription = KAtsLoggerEmpty);
+
+		/**
+		 * EndTestSetL() must be called as soon as a test set ends
+		 */
+		IMPORT_C void EndTestSetL();
+
+		/**
+		 * BeginTestCaseL() is called whenever an individual testcase begins
+		 *
+		 * id       = unique id of the testcase
+		 * expected = expected result of the test (if applicable)
+		 * info     = short descritpion of the expected result (if applicable)
+		 */
+		IMPORT_C void BeginTestCaseL(const TDesC& aId,
+									 const TDesC& aExpected = KAtsLoggerNa,
+									 const TDesC& aInfo = KAtsLoggerEmpty,
+									 const TDesC& aVersion = KAtsLoggerEmpty);
+
+		/**
+		 * BeginTestCaseL() is called whenever an individual testcase begins
+		 *
+		 * id       = unique id of the testcase
+		 * expected = expected result code of the test (if applicable)
+		 * info     = short descritpion of the expected result (if applicable)
+		 */
+		IMPORT_C void BeginTestCaseL(const TDesC& aId,
+									 const TInt aExpected,
+									 const TDesC& aInfo = KAtsLoggerEmpty,
+									 const TDesC& aVersion = KAtsLoggerEmpty);
+									
+		/**
+		 * BeginTestCaseReportL() is called whenever an individual testcase report begins
+		 *
+		 * id       = unique id of the testcase
+		 * expected = expected result code of the test (if applicable)
+		 * startTime= test case starting time
+		 * info     = short descritpion of the expected result (if applicable)
+		 */
+		 IMPORT_C void BeginTestCaseReportL( const TDesC& aId,
+			                                const TDesC& aExpected,
+			                                const TTime& aStartTime,
+			                                const TDesC& aInfo = KAtsLoggerEmpty,
+			                                const TDesC& aVersion = KAtsLoggerEmpty );
+			                                
+		/**
+		 * BeginTestCaseReportL() is called whenever an individual testcase report begins
+		 *
+		 * id       = unique id of the testcase
+		 * expected = expected result code of the test (if applicable)
+		 * startTime= test case starting time
+		 * info     = short descritpion of the expected result (if applicable)
+		 */
+		 IMPORT_C void BeginTestCaseReportL( const TDesC& aId,
+			                                const TInt aExpected,
+			                                const TTime& aStartTime,
+			                                const TDesC& aInfo = KAtsLoggerEmpty,
+			                                const TDesC& aVersion = KAtsLoggerEmpty );
+
+		/**
+		 * EndTestCaseL() is called when an individual testcase ends
+		 */
+		IMPORT_C void EndTestCaseL();
+
+		/**
+		 * TestCasePassed() must be called between calls
+		 * to BeginTestCase() and EndTestCase(). This results
+		 * test case to be passed.
+		 */
+		IMPORT_C void TestCasePassed();
+		
+		
+		/**
+		 * TestCaseFailed() must be called between calls
+		 * to BeginTestCase() and EndTestCase(). This results
+		 * test case to be failed.
+		 */
+		IMPORT_C void TestCaseFailed();
+
+		/**
+		 * TestCaseSkipped() must be called between calls
+		 * to BeginTestCase() and EndTestCase(). This results
+		 * test case to be skipped.
+		 */
+		IMPORT_C void TestCaseSkipped();
+		
+		/**
+		 * TestCaseNa() must be called between calls
+		 * to BeginTestCase() and EndTestCase(). This results
+		 * test case to be N/A.
+		 */
+		IMPORT_C void TestCaseNa();
+
+		/**
+		 * SetTestCaseResultL() sets the actual result of the test (if applicable),
+		 * this should correspond to the expected result (see BeginTestCase) if
+		 * the test succeeds.
+
+		 * Must be called between calls to BeginTestCaseL() and EndTestCaseL().
+		 */
+		IMPORT_C void SetTestCaseResultL(const TInt aResult);
+		IMPORT_C void SetTestCaseResultL(const TDesC& aResult = KAtsLoggerEmpty);
+		IMPORT_C void SetTestCaseResultL(TRefByValue<const TDesC> aFmt,...);
+
+		/**
+		 * DebugL(), WarningL(), ErrorL() and CommentL() as used to place
+		 * informational messages of appropriate debug level into the test report.
+         * These functions can be called anywhere between BeginReportL() and EndReportL().
+		 */
+		IMPORT_C void DebugL(const TDesC& aMsg);
+		IMPORT_C void DebugL(TRefByValue<const TDesC> aFmt,...);
+
+		IMPORT_C void WarningL(const TDesC& aMsg);
+		IMPORT_C void WarningL(TRefByValue<const TDesC> aFmt,...);
+
+		IMPORT_C void ErrorL(const TDesC& aMsg);
+		IMPORT_C void ErrorL(TRefByValue<const TDesC> aFmt,...);
+
+		IMPORT_C void CommentL(const TDesC& aMsg);
+		IMPORT_C void CommentL(TRefByValue<const TDesC> aFmt,...);
+
+		/**
+		 * RawLogL() writes to a separate log file.
+		 */
+		IMPORT_C TInt RawLogL(const TDesC& aMsg);
+		IMPORT_C TInt RawLogL(TRefByValue<const TDesC> aFmt,...);
+
+		/**
+		 * DebugOutput() writes to RDebug
+		 */
+		IMPORT_C void DebugOutput(const TDesC& aMsg);
+
+		/**
+		 * Set this to ETrue if client should use
+		 * full set of reporting methods
+		 */
+		IMPORT_C void SetFullReporting(TBool aFlag);
+
+		/**
+		 * Set this to ETrue if XML log should be
+		 * written to the debug port also.
+		 */
+		IMPORT_C void SetDebugOutput(TBool aFlag);
+
+		/**
+		 * Set this to ETrue if XML log should have
+		 * indentation. This only adds human readability.
+		 */
+		IMPORT_C void SetIndentation(TBool aFlag);
+
+
+    public: // Public functions from base classes
+			// None
+	
+    protected:	// Protected new functions
+		/**
+		 * Outputs message closed by the tags.
+		 */
+		void TagL(const TDesC& aTag,
+			      const TDesC& aMsg);
+
+		/**
+		 * Adds attribute with value to the message and
+		 * outputs message closed by the tags.
+		 */
+		void TagL(const TDesC& aTag,
+			      const TDesC& aMsg,
+				  const TDesC& aAttribute,
+				  const TDesC& aValue);
+
+		/**
+		 * Outputs message closed by the tags. This is used with
+		 * DebugL(), WarningL(), ErrorL() and CommentL(). Time stamp is
+		 * added to the message.
+		 */
+		void TimeStampedMessageL(const TDesC& aTag,
+			                     const TDesC& aMsg);
+
+		/**
+		 * Opens a tag. 
+		 */
+		void OpenTagL(const TDesC& aTag);	
+
+		
+		/**
+		 * Opens a tag with attribute and value.
+		 */
+		void OpenTagL(const TDesC& aTag,
+					  const TDesC& aAttribute,
+					  const TDesC& aValue);
+		
+		/**
+		 * Opens a tag and increases indent level.
+		 */
+		void OpenTagIndentL(const TDesC& aTag);
+
+
+		/**
+		 * Opens a tag with attribute having value and increases indent level.
+		 */
+		void OpenTagIndentL(const TDesC& aTag,
+			                const TDesC& aAttribute,
+						    const TDesC& aValue);
+
+		/**
+		 * Closes a tag;
+		 */
+		void CloseTagL(const TDesC& aTag);
+
+		/**
+		 * Closes a tag and descreases indent level.
+		 */
+		void CloseTagIndentL(const TDesC& aTag);
+
+		/**
+		 * Outputs line feed.
+		 */
+		void LineFeedL();
+
+		/**
+		 * Writes data to the specified file.
+		 */
+		void WriteL(const TDesC& aData, RFile& aFile);
+
+		/**
+		 * Writes data to the XML file.
+		 */
+		void WriteL(const TDesC& aData);
+
+		/**
+		 * Encodes XML special chararacters from message
+		 */
+		HBufC* EncodeLC(const TDesC& aMsg);
+
+		/**
+		 * Checks whether report stage transition is legal.
+		 */
+		TBool IsTransitionLegal(const TReportStage& aNewStage);
+
+	protected:  // Protected functions from base classes
+				// None
+
+	protected:	// Protected data
+				// None
+	
+	private:	// Private functions
+        /**
+        * By default Symbian OS two-phase constructor is private.
+        */
+		void ConstructL( TBool aAfterReboot );
+
+		/**
+		 * C++ constructor
+		 */
+		CAtsLogger(const TDesC& aName);
+
+		/**
+		 * Checks whether directory exist or not
+		 */
+		TBool CheckDirectoryL(const TDesC& aDirName, TChar& aDrive);
+		
+		/**
+		 * Replaces file if already exist
+		 */
+		TInt ReplaceFileL(const TDesC& aFileName);
+
+		/**
+		 * Open existing file if already exist
+		 */
+		TInt OpenExistingFileL(const TDesC& aFileName);
+
+		/**
+		 * Formats given date to a format of yyyy-mm-dd hh:mm:ss
+		 */
+		HBufC* FormatDateLC(TDateTime aDate);
+
+		/**
+		 * Formats given time to a format of hh:mm:ss
+		 */
+		HBufC* FormatTimeLC(TTimeIntervalMicroSeconds aTime);
+
+		/**
+		 * Expands buffer and then writes aBuf into it.
+		 */
+		TInt BufferL(CBufBase* aBufBase, TInt& aLength,const TDesC& aBuf);
+		
+		/**
+		 * Writes whole buffer to a file. Does not reset buffer.
+		 */
+		TInt WriteBufferToFileL(CBufBase* aCBufBase, const TDesC& aFileName);
+
+		/**
+		 * Writes whole buffer to the debug port. Does not reset buffer.
+		 */
+		TInt WriteBufferToDebugPortL(CBufBase* aCBufBase);
+
+	protected:	// Protected data
+		// TTestSet data holder class definition and implementation
+		class TTestSet
+			{
+			public:
+				TTime iStartTime;
+			};
+		
+		// TCase data holder class definition and implementation
+		class TTestCase
+			{
+			public:
+				TTestCase() {  iResult = NULL; }
+				~TTestCase()
+					{
+					if (iResult)
+						{
+						delete iResult;
+						iResult = NULL;
+						}
+					}
+			public:
+				HBufC* iResult;
+				TPtrC iStatus;
+				TTime iStartTime;
+			
+			};
+
+		// Data holder for batch information
+		CAtsLogger::TTestSet iTestSet;
+
+		// Data holder for test case information
+		CAtsLogger::TTestCase iTestCase;
+
+		// Holds current report stage
+		CAtsLogger::TReportStage iReportStage;
+
+		// Test case and logger ID
+		const TFileName iName;
+
+	private: // Private data
+		// Dynamic buffer for XML data
+		CBufBase* iXmlBuffer;
+
+		// Current legth of iXmlBuffer
+		TInt iXmlBufferLength;
+		
+		// Indentation level of outputted XML
+		int iIndentLevel;
+
+		// Handle to file server
+		RFs iRfs;
+
+		// The name of XML file
+		TFileName iXmlLogFileName;
+
+		// The name of raw log file
+		TFileName iRawLogFileName;
+
+		// Flag to indicate that raw log should be done
+		TBool iRawLog;
+
+		// Flag to indicate that XML log should be done
+		TBool iXmlLog;
+
+		// Flag to indicate that logger is valid
+		TBool iValid;
+
+		// Flag to indicate that a line feed has been done
+		TBool iLineFeedDone;
+
+		// Flag to indicate that BeginTestCase() has been called
+		// and EndTestCase() hasn't yet been called.
+		TBool iInTestCase;
+
+		// Flag to indicate that logger is closed
+		TBool iClosed;
+
+		// Flag to indicate if client should use
+		// full set of logger methods:
+		//		BeginTestReportL()
+		//		BeginTestSetL();
+		//		BeginTestCaseL();
+		//		TestCasePassed(); // or other verdict method
+		//		EndTestCase();
+		//		EndTestSetL();
+		//		EndTestReportL();
+		TBool iFullReportingMode;
+
+		// Flag to indicate that XML log should be
+		// written to the debug port also
+		TBool iDoDebugOutput;
+
+		// Flag to indicate that logger does intendation
+		// to the XML file
+		TBool iDoIndentation;
+
+	public:	// Friend classes
+			// None
+        
+    protected:	// Friend classes
+				// None
+        
+    private:	// Friend classes
+				// None
+};
+
+#endif// End of File
+
+// End of File