Index: /trunk/FACT++/src/ftm.cc
===================================================================
--- /trunk/FACT++/src/ftm.cc	(revision 10517)
+++ /trunk/FACT++/src/ftm.cc	(revision 10517)
@@ -0,0 +1,629 @@
+#include <iostream>
+#include <string>
+#include <boost/asio.hpp>
+#include <boost/bind.hpp>
+#include <boost/lexical_cast.hpp>
+#include <boost/asio/deadline_timer.hpp>
+#include <boost/enable_shared_from_this.hpp>
+
+using boost::lexical_cast;
+
+#include "Time.h"
+#include "Converter.h"
+
+#include "HeadersFTM.h"
+
+using namespace std;
+using namespace FTM;
+
+namespace ba    = boost::asio;
+namespace bs    = boost::system;
+namespace dummy = ba::placeholders;
+
+using boost::lexical_cast;
+using ba::ip::tcp;
+
+int Port = 0;
+
+// ------------------------------------------------------------------------
+
+
+// ------------------------------------------------------------------------
+
+class tcp_connection : public ba::ip::tcp::socket, public boost::enable_shared_from_this<tcp_connection>
+{
+private:
+
+    double fStartTime;
+
+    void AsyncRead(ba::mutable_buffers_1 buffers)
+    {
+        ba::async_read(*this, buffers,
+                       boost::bind(&tcp_connection::HandleReceivedData, shared_from_this(),
+                                   dummy::error, dummy::bytes_transferred));
+    }
+
+    void AsyncWrite(const ba::const_buffers_1 &buffers)
+    {
+        ba::async_write(*this, buffers,
+                        boost::bind(&tcp_connection::HandleSentData, shared_from_this(),
+                                    dummy::error, dummy::bytes_transferred));
+    }
+    void AsyncWait(ba::deadline_timer &timer, int seconds,
+                               void (tcp_connection::*handler)(const bs::error_code&))// const
+    {
+        timer.expires_from_now(boost::posix_time::seconds(seconds));
+        timer.async_wait(boost::bind(handler, shared_from_this(), dummy::error));
+    }
+
+    ba::deadline_timer deadline_;
+
+    ba::deadline_timer fTriggerDynData;
+
+    // The constructor is prvate to force the obtained pointer to be shared
+    tcp_connection(ba::io_service& ioservice) : ba::ip::tcp::socket(ioservice),
+        deadline_(ioservice), fTriggerDynData(ioservice)
+    {
+        deadline_.expires_at(boost::posix_time::pos_infin);
+
+        fHeader.fDelimiter=kDelimiterStart;
+        fHeader.fState=FTM::kFtmIdle;
+        fHeader.fBoardId=0xaffe;
+        fHeader.fFirmwareId=0x42;
+
+        fDelimiter = htons(kDelimiterEnd);
+
+        fStaticData.clear();
+
+        fStaticData.fCoincidencePhysics = 1;
+        fStaticData.fCoincidenceCalib   = 40;
+        fStaticData.fWindowCalib        = 1;
+        fStaticData.fWindowPhysics      = 0;
+        fStaticData.fDelayTrigger       = 21;
+        fStaticData.fDelayTimeMarker    = 42;
+        fStaticData.fDeadTime           = 84;
+
+        fStaticData.fClockConditioner[0] = 100;
+        fStaticData.fClockConditioner[1] = 1;
+        fStaticData.fClockConditioner[2] = 8;
+        fStaticData.fClockConditioner[3] = 9;
+        fStaticData.fClockConditioner[4] = 11;
+        fStaticData.fClockConditioner[5] = 13;
+        fStaticData.fClockConditioner[6] = 14;
+        fStaticData.fClockConditioner[7] = 15;
+
+        fStaticData.fTriggerSequence = 1 | (2<<5) | (3<<10);
+
+        fStaticData.fGeneralSettings =
+            FTM::StaticData::kTrigger |
+            FTM::StaticData::kLP1     |
+            FTM::StaticData::kPedestal;
+
+        fStaticData.fActiveFTU[0] = 0x3ff;
+        fStaticData.fActiveFTU[3] = 0x3ff;
+
+        for (int i=0; i<40; i++)
+        {
+            for (int p=0; p<4; p++)
+                fStaticData[i].fEnable[p] = 0x5555;
+
+            for (int p=0; p<5; p++)
+                fStaticData[i].fDAC[p]    = (p+1)*10;
+
+            fStaticData[i].fPrescaling    = 42;
+        }
+
+        for (unsigned long long i=0; i<40; i++)
+        {
+            fFtuList[i].fDNA      = (i<<48)|(i<<32)|(i<<16)|i;
+            fFtuList[i].fPingAddr = i;
+        }
+    }
+
+    // Callback when writing was successfull or failed
+    void HandleSentData(const boost::system::error_code& error, size_t bytes_transferred)
+    {
+        cout << "Data sent: (transmitted=" << bytes_transferred << ") rc=" << error.message() << " (" << error << ")" << endl;
+    }
+
+    vector<uint16_t> fBufCommand;
+    vector<uint16_t> fBufHeader;
+    vector<uint16_t> fBufFtuList;
+    vector<uint16_t> fBufStaticData;
+    vector<uint16_t> fBufDynamicData;
+
+    vector<uint16_t> fCommand;
+    FTM::Header      fHeader;
+    FTM::FtuList     fFtuList;
+    FTM::StaticData  fStaticData;
+    FTM::DynamicData fDynamicData;
+
+    //vector<uint16_t> fStaticData;
+
+    uint16_t fDelimiter;
+    uint16_t fBufRegister;
+
+    uint16_t fCounter;
+
+    bool fReportsDisabled;
+
+    void SendDynamicData()
+    {
+        if (fReportsDisabled)
+            return;
+
+        if (fHeader.fState == FTM::kFtmRunning)
+            fDynamicData.fOnTimeCounter = lrint(Time().UnixTime()-fStartTime);
+
+        fDynamicData.fTempSensor[0] = (23. + (6.*rand()/RAND_MAX-3))*10;
+        fDynamicData.fTempSensor[1] = (55. + (6.*rand()/RAND_MAX-3))*10;
+        fDynamicData.fTempSensor[2] = (39. + (6.*rand()/RAND_MAX-3))*10;
+        fDynamicData.fTempSensor[3] = (42. + (6.*rand()/RAND_MAX-3))*10;
+
+        for (int i=0; i<40; i++)
+            for (int p=0; p<4; p++)
+                fDynamicData[i].fRatePatch[p] = (1000 + (float(rand())/RAND_MAX-0.5)*25*p);
+
+        fHeader.fType=kDynamicData;     // FtuList
+        fHeader.fDataSize=sizeof(FTM::DynamicData)/2+1;
+        fHeader.fTriggerCounter = fCounter++;
+        fHeader.fTimeStamp = lrint(Time().UnixTime());
+
+        fBufHeader      = fHeader.HtoN();
+        fBufDynamicData = fDynamicData.HtoN();
+
+        AsyncWrite(ba::buffer(ba::const_buffer(&fBufHeader[0],      fBufHeader.size()*2)));
+        AsyncWrite(ba::buffer(ba::const_buffer(&fBufDynamicData[0], sizeof(FTM::DynamicData))));
+        AsyncWrite(ba::buffer(ba::const_buffer(&fDelimiter, 2)));
+    }
+
+    void SendStaticData()
+    {
+        fHeader.fType=kStaticData;     // FtuList
+        fHeader.fDataSize=sizeof(FTM::StaticData)/2+1;
+        fHeader.fTriggerCounter = fCounter++;
+        fHeader.fTimeStamp = lrint(Time().UnixTime());
+
+        for (int i=0; i<4; i++)
+            fFtuList.fActiveFTU[i] = fStaticData.fActiveFTU[i];
+
+        fBufHeader     = fHeader.HtoN();
+        fBufStaticData = fStaticData.HtoN();
+
+        AsyncWrite(ba::buffer(ba::const_buffer(&fBufHeader[0],     fBufHeader.size()*2)));
+        AsyncWrite(ba::buffer(ba::const_buffer(&fBufStaticData[0], fBufStaticData.size()*2)));
+        AsyncWrite(ba::buffer(ba::const_buffer(&fDelimiter, 2)));
+    }
+
+    void HandleReceivedData(const boost::system::error_code& error, size_t bytes_received)
+    {
+        // Do not schedule a new read if the connection failed.
+        if (bytes_received==0)
+        {
+            // Close the connection
+            close();
+            deadline_.cancel();
+            return;
+        }
+
+        // No command received yet
+        if (fCommand.size()==0)
+        {
+            transform(fBufCommand.begin(), fBufCommand.begin()+bytes_received/2,
+                      fBufCommand.begin(), ntohs);
+
+            if (fBufCommand[0]!='@')
+            {
+                cout << "Inavlid command: 0x" << hex << fBufCommand[0] << dec << endl;
+                cout << "Received b=" << bytes_received << ": " << error.message() << " (" << error << ")" << endl;
+                cout << "Hex:" << Converter::GetHex<uint16_t>(&fBufCommand[0], bytes_received) << endl;
+                return;
+            }
+
+            switch (fBufCommand[1])
+            {
+            case kCmdToggleLed:
+                cout << "-> TOGGLE_LED" << endl;
+
+                fBufCommand.resize(5);
+                AsyncRead(ba::buffer(fBufCommand));
+                return;
+
+            case kCmdPing:
+                cout << "-> PING" << endl;
+
+                fHeader.fType=kFtuList;     // FtuList
+                fHeader.fDataSize=sizeof(FTM::FtuList)/2+1;
+                fHeader.fTriggerCounter = fCounter++;
+                fHeader.fTimeStamp = lrint(Time().UnixTime());
+
+                fBufHeader  = fHeader.HtoN();
+                fBufFtuList = fFtuList.HtoN();
+
+                AsyncWrite(ba::buffer(ba::const_buffer(&fBufHeader[0],  fBufHeader.size()*2)));
+                AsyncWrite(ba::buffer(ba::const_buffer(&fBufFtuList[0], fBufFtuList.size()*2)));
+                AsyncWrite(ba::buffer(ba::const_buffer(&fDelimiter, 2)));
+
+                fBufCommand.resize(5);
+                AsyncRead(ba::buffer(fBufCommand));
+                return;
+
+            case kCmdRead: // kCmdRead
+                cout << "-> READ" << endl;
+                switch (fBufCommand[2])
+                {
+                case kReadStaticData:
+                    cout << "-> STATIC" << endl;
+
+                    SendStaticData();
+
+                    fBufCommand.resize(5);
+                    AsyncRead(ba::buffer(fBufCommand));
+
+                    return;
+
+                case kReadDynamicData:
+                    cout << "-> DYNAMIC" << endl;
+
+                    SendDynamicData();
+
+                    fBufCommand.resize(5);
+                    AsyncRead(ba::buffer(fBufCommand));
+
+                    return;
+
+                case kReadRegister:
+                    fCommand = fBufCommand;
+                    cout << "-> REGISTER" << endl;
+
+                    fBufCommand.resize(1);
+                    AsyncRead(ba::buffer(fBufCommand));
+                    return;
+                }
+                break;
+
+
+            case kCmdWrite:
+                switch (fBufCommand[2])
+                {
+                case kWriteRegister:
+                    fCommand = fBufCommand;
+                    cout << "-> REGISTER" << endl;
+
+                    fBufCommand.resize(2);
+                    AsyncRead(ba::buffer(fBufCommand));
+                    return;
+
+                case kWriteStaticData:
+                    fCommand = fBufCommand;
+                    cout << "-> STATIC DATA" << endl;
+
+                    fBufCommand.resize(sizeof(StaticData)/2);
+                    AsyncRead(ba::buffer(fBufCommand));
+                    return;
+                }
+                break;
+
+            case kCmdDisableReports:
+                cout << "-> DISABLE REPORTS " << !fBufCommand[2] << endl;
+                fReportsDisabled = !fBufCommand[2];
+
+                fBufCommand.resize(5);
+                AsyncRead(ba::buffer(fBufCommand));
+                return;
+
+            case kCmdStartRun:
+                fHeader.fState = FTM::kFtmRunning;
+
+                fStartTime = Time().UnixTime();
+
+                fBufCommand.resize(5);
+                AsyncRead(ba::buffer(fBufCommand));
+                return;
+
+            case kCmdStopRun:
+                fHeader.fState = FTM::kFtmIdle;
+
+                fBufCommand.resize(5);
+                AsyncRead(ba::buffer(fBufCommand));
+                return;
+            }
+
+            cout << "Received b=" << bytes_received << ": " << error.message() << " (" << error << ")" << endl;
+            cout << "Hex:" << Converter::GetHex<uint16_t>(&fBufCommand[0], bytes_received) << endl;
+            return;
+        }
+
+        // Command data received
+
+        // Prepare reception of next command
+        switch (fCommand[1])
+        {
+        case kCmdRead: // kCmdRead
+            {
+                const uint16_t addr = ntohs(fBufCommand[0]);
+                const uint16_t val  = reinterpret_cast<uint16_t*>(&fStaticData)[addr];
+
+                cout << "-> GET REGISTER[" << addr << "]=" << val << endl;
+
+                fHeader.fType=kRegister;     // FtuList
+                fHeader.fDataSize=2;
+                fHeader.fTriggerCounter = fCounter++;
+                fHeader.fTimeStamp = lrint(Time().UnixTime());
+
+                fBufHeader = fHeader.HtoN();
+                fBufStaticData[addr] = htons(val);
+
+                AsyncWrite(ba::buffer(ba::const_buffer(&fBufHeader[0], fBufHeader.size()*2)));
+                AsyncWrite(ba::buffer(ba::const_buffer(&fBufStaticData[addr], 2)));
+                AsyncWrite(ba::buffer(ba::const_buffer(&fDelimiter, 2)));
+                break;
+            }
+
+        case kCmdWrite:
+            switch (fCommand[2])
+            {
+            case kWriteRegister:
+                {
+                    const uint16_t addr = ntohs(fBufCommand[0]);
+                    const uint16_t val  = ntohs(fBufCommand[1]);
+
+                    cout << "-> SET REGISTER[" << addr << "]=" << val << endl;
+
+                    reinterpret_cast<uint16_t*>(&fStaticData)[addr] = val;
+                }
+                break;
+
+            case kWriteStaticData:
+                {
+                    cout << "-> SET STATIC DATA" << endl;
+                    fStaticData = fBufCommand;
+                }
+                break;
+            }
+            break;
+        }
+
+        fCommand.resize(0);
+
+        fBufCommand.resize(5);
+        AsyncRead(ba::buffer(fBufCommand));
+    }
+
+    void check_deadline(const boost::system::error_code &)
+    {
+        if (!is_open())
+        {
+            // For example: Here we could schedule a new accept if we
+            // would not want to allow two connections at the same time.
+            return;
+        }
+
+        // Check whether the deadline has passed. We compare the deadline
+        // against the current time since a new asynchronous operation
+        // may have moved the deadline before this actor had a chance
+        // to run.
+        if (deadline_.expires_at() <= ba::deadline_timer::traits_type::now())
+        {
+            // The deadline has passed. Stop the session. The other
+            // actors will terminate as soon as possible.
+//            AsyncWrite(ba::buffer(ba::const_buffer(&fHeader, sizeof(FTM::Header))));
+//            AsyncWait(deadline_, 3, &tcp_connection::check_deadline);
+
+            return;
+        }
+
+        AsyncWait(deadline_, 3, &tcp_connection::check_deadline);
+    }
+
+    void SendDynData(const boost::system::error_code &)
+    {
+        if (!is_open())
+        {
+            // For example: Here we could schedule a new accept if we
+            // would not want to allow two connections at the same time.
+            return;
+        }
+
+        // Check whether the deadline has passed. We compare the deadline
+        // against the current time since a new asynchronous operation
+        // may have moved the deadline before this actor had a chance
+        // to run.
+        if (deadline_.expires_at() <= ba::deadline_timer::traits_type::now())
+            return;
+
+        // The deadline has passed.
+        SendDynamicData();
+
+        AsyncWait(fTriggerDynData, 1, &tcp_connection::SendDynData);
+        return;
+    }
+
+public:
+    typedef boost::shared_ptr<tcp_connection> shared_ptr;
+
+    static shared_ptr create(ba::io_service& io_service)
+    {
+        return shared_ptr(new tcp_connection(io_service));
+    }
+
+    void start()
+    {
+        // Ownership of buffer must be valid until Handler is called.
+
+        // Emit something to be written to the socket
+        fBufCommand.resize(5);
+        AsyncRead(ba::buffer(fBufCommand));
+
+        AsyncWait(fTriggerDynData, 1, &tcp_connection::SendDynData);
+
+//        AsyncWrite(ba::buffer(ba::const_buffer(&fHeader, sizeof(FTM::Header))));
+//        AsyncWait(deadline_, 3, &tcp_connection::check_deadline);
+
+    }
+};
+
+
+class tcp_server : public tcp::acceptor
+{
+public:
+    tcp_server(ba::io_service& ioservice, int port) :
+        tcp::acceptor(ioservice, tcp::endpoint(tcp::v4(), port))
+
+    {
+        // We could start listening for more than one connection
+        // here, but since there is only one handler executed each time
+        // it would not make sense. Before one handle_accept is not
+        // finished no new handle_accept will be called.
+        // Workround: Start a new thread in handle_accept
+        start_accept();
+    }
+
+private:
+    void start_accept()
+    {
+        cout << "Start accept..." << flush;
+        tcp_connection::shared_ptr new_connection = tcp_connection::create(/*acceptor_.*/io_service());
+
+        // This will accept a connection without blocking
+        async_accept(*new_connection,
+                     boost::bind(&tcp_server::handle_accept,
+                                 this,
+                                 new_connection,
+                                 ba::placeholders::error));
+
+        cout << "start-done." << endl;
+    }
+
+    void handle_accept(tcp_connection::shared_ptr new_connection, const boost::system::error_code& error)
+    {
+        // The connection has been accepted and is now ready to use
+
+        // not installing a new handler will stop run()
+        cout << "Handle accept..." << flush;
+        if (!error)
+        {
+            new_connection->start();
+
+            // The is now an open connection/server (tcp_connection)
+            // we immediatly schedule another connection
+            // This allowed two client-connection at the same time
+            start_accept();
+        }
+        cout << "handle-done." << endl;
+    }
+};
+
+int main(int argc, const char **argv)
+{
+    try
+    {
+        ba::io_service io_service;
+
+        Port = argc==2 ? lexical_cast<int>(argv[1]) : 5000;
+
+        tcp_server server(io_service, Port);
+        //  ba::add_service(io_service, &server);
+        //  server.add_service(...);
+        cout << "Run..." << flush;
+
+        // Calling run() from a single thread ensures no concurrent access
+        // of the handler which are called!!!
+        io_service.run();
+
+        cout << "end." << endl;
+    }
+    catch (std::exception& e)
+    {
+        std::cerr << e.what() << std::endl;
+    }
+
+    return 0;
+}
+/*  ====================== Buffers ===========================
+
+char d1[128]; ba::buffer(d1));
+std::vector<char> d2(128); ba::buffer(d2);
+boost::array<char, 128> d3; by::buffer(d3);
+
+// --------------------------------
+char d1[128];
+std::vector<char> d2(128);
+boost::array<char, 128> d3;
+
+boost::array<mutable_buffer, 3> bufs1 = {
+   ba::buffer(d1),
+   ba::buffer(d2),
+   ba::buffer(d3) };
+sock.read(bufs1);
+
+std::vector<const_buffer> bufs2;
+bufs2.push_back(boost::asio::buffer(d1));
+bufs2.push_back(boost::asio::buffer(d2));
+bufs2.push_back(boost::asio::buffer(d3));
+sock.write(bufs2);
+
+
+// ======================= Read functions =========================
+
+ba::async_read_until --> delimiter
+
+streambuf buf; // Ensure validity until handler!
+by::async_read(s, buf, ....);
+
+ba::async_read(s, ba:buffer(data, size), handler);
+ // Single buffer
+ boost::asio::async_read(s,
+                         ba::buffer(data, size),
+ compl-func -->          ba::transfer_at_least(32),
+                         handler);
+
+ // Multiple buffers
+boost::asio::async_read(s, buffers,
+ compl-func -->         boost::asio::transfer_all(),
+                        handler);
+                        */
+
+// ================= Others ===============================
+
+        /*
+        strand   Provides serialised handler execution.
+        work     Class to inform the io_service when it has work to do.
+
+
+io_service::
+dispatch   Request the io_service to invoke the given handler.
+poll       Run the io_service's event processing loop to execute ready
+           handlers.
+poll_one   Run the io_service's event processing loop to execute one ready
+           handler.
+post       Request the io_service to invoke the given handler and return
+           immediately.
+reset      Reset the io_service in preparation for a subsequent run()
+           invocation.
+run        Run the io_service's event processing loop.
+run_one    Run the io_service's event processing loop to execute at most
+           one handler.
+stop       Stop the io_service's event processing loop.
+wrap       Create a new handler that automatically dispatches the wrapped
+           handler on the io_service.
+
+strand::         The io_service::strand class provides the ability to
+                 post and dispatch handlers with the guarantee that none
+                 of those handlers will execute concurrently.
+
+dispatch         Request the strand to invoke the given handler.
+get_io_service   Get the io_service associated with the strand.
+post             Request the strand to invoke the given handler and return
+                 immediately.
+wrap             Create a new handler that automatically dispatches the
+                 wrapped handler on the strand.
+
+work::           The work class is used to inform the io_service when
+                 work starts and finishes. This ensures that the io_service's run() function will not exit while work is underway, and that it does exit when there is no unfinished work remaining.
+get_io_service   Get the io_service associated with the work.
+work             Constructor notifies the io_service that work is starting.
+
+*/
+
+
Index: /trunk/FACT++/src/ftmctrl.cc
===================================================================
--- /trunk/FACT++/src/ftmctrl.cc	(revision 10517)
+++ /trunk/FACT++/src/ftmctrl.cc	(revision 10517)
@@ -0,0 +1,1311 @@
+#include <boost/bind.hpp>
+#include <boost/array.hpp>
+#include <boost/thread.hpp>
+#include <boost/asio/error.hpp>
+#include <boost/asio/deadline_timer.hpp>
+
+#include "Event.h"
+#include "Shell.h"
+#include "StateMachineDim.h"
+#include "Connection.h"
+#include "Configuration.h"
+#include "Timers.h"
+#include "Console.h"
+#include "Converter.h"
+
+#include "tools.h"
+
+#include "LocalControl.h"
+#include "HeadersFTM.h"
+
+namespace ba = boost::asio;
+namespace bs = boost::system;
+
+using namespace std;
+using namespace FTM;
+
+// ------------------------------------------------------------------------
+
+class ConnectionFTM : public Connection
+{
+    vector<uint16_t> fBuffer;
+
+    bool fHasHeader;
+    int  fState;
+
+    bool fIsVerbose;
+    bool fIsDynamicOut;
+    bool fIsHexOutput;
+
+    // --verbose
+    // --hex-out
+    // --dynamic-out
+    // --load-file
+    // --leds
+    // --trigger-interval
+    // --physcis-coincidence
+    // --calib-coincidence
+    // --physcis-window
+    // --physcis-window
+    // --trigger-delay
+    // --time-marker-delay
+    // --dead-time
+    // --clock-conditioner-r0
+    // --clock-conditioner-r1
+    // --clock-conditioner-r8
+    // --clock-conditioner-r9
+    // --clock-conditioner-r11
+    // --clock-conditioner-r13
+    // --clock-conditioner-r14
+    // --clock-conditioner-r15
+    // ...
+
+    map<uint16_t, int> fCounter;
+
+protected:
+    FTM::Header      fHeader;
+    FTM::FtuList     fFtuList;
+    FTM::StaticData  fStaticData;
+    FTM::DynamicData fDynamicData;
+    FTM::Error       fError;
+
+    virtual void UpdateFirstHeader()
+    {
+        // FIXME: Message() ?
+        Out() << endl << kBold << "First header received:" << endl;
+        Out() << fHeader;
+        if (fIsHexOutput)
+            Out() << Converter::GetHex<uint16_t>(fHeader, sizeof(fHeader), 16) << endl;
+    }
+
+    virtual void UpdateHeader()
+    {
+        // emit service with trigger counter from header
+        if (!fIsVerbose)
+            return;
+
+        if (fHeader.fType==kDynamicData && !fIsDynamicOut)
+            return;
+
+        Out() << endl << kBold << "Header received:" << endl;
+        Out() << fHeader;
+        if (fIsHexOutput)
+            Out() << Converter::GetHex<uint16_t>(fHeader, sizeof(fHeader), 16) << endl;
+    }
+
+    virtual void UpdateFtuList()
+    {
+        if (!fIsVerbose)
+            return;
+
+        Out() << endl << kBold << "FtuList received:" << endl;
+        Out() << fFtuList;
+        if (fIsHexOutput)
+            Out() << Converter::GetHex<uint16_t>(fFtuList, 16) << endl;
+    }
+
+    virtual void UpdateStaticData()
+    {
+        if (!fIsVerbose)
+            return;
+
+        Out() << endl << kBold << "Static data received:" << endl;
+        Out() << fStaticData;
+        if (fIsHexOutput)
+            Out() << Converter::GetHex<uint16_t>(fStaticData, 16) << endl;
+    }
+
+    virtual void UpdateDynamicData()
+    {
+        if (!fIsDynamicOut)
+            return;
+
+        Out() << endl << kBold << "Dynamic data received:" << endl;
+        Out() << fDynamicData;
+        if (fIsHexOutput)
+            Out() << Converter::GetHex<uint16_t>(fDynamicData, 16) << endl;
+    }
+
+    virtual void UpdateError()
+    {
+        if (!fIsVerbose)
+            return;
+
+        Out() << endl << kBold << "Error list received:" << endl;
+        Out() << fError;
+        if (fIsHexOutput)
+            Out() << Converter::GetHex<uint16_t>(fError, 16) << endl;
+    }
+
+private:
+    void HandleReceivedData(const bs::error_code& err, size_t bytes_received, int /*type*/)
+    {
+        // Do not schedule a new read if the connection failed.
+        if (bytes_received==0 || err)
+        {
+            if (err==ba::error::eof)
+                Warn("Connection closed by remote host (FTM).");
+
+            // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
+            // 125: Operation canceled
+            if (err && err!=ba::error::eof &&                     // Connection closed by remote host
+                err!=ba::error::basic_errors::not_connected &&    // Connection closed by remote host
+                err!=ba::error::basic_errors::operation_aborted)  // Connection closed by us
+            {
+                stringstream str;
+                str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
+                Error(str);
+            }
+            PostClose(err!=ba::error::basic_errors::operation_aborted);
+            return;
+        }
+
+        // If we have not yet received a header we expect one now
+        // This could be moved to a HandleReceivedHeader function
+        if (!fHasHeader)
+        {
+            if (bytes_received!=sizeof(FTM::Header))
+            {
+                stringstream str;
+                str << "Excepted " << sizeof(FTM::Header) << " bytes (FTM::Header) but received " << bytes_received << ".";
+                Error(str);
+                PostClose(false);
+                return;
+            }
+
+            fHeader = fBuffer;
+
+            // Check the data integrity
+            if (fHeader.fDelimiter!=kDelimiterStart)
+            {
+                stringstream str;
+                str << "Invalid header received: start delimiter wrong, received " << hex << fHeader.fDelimiter << " expected " << kDelimiterStart << ".";
+                Error(str);
+                PostClose(false);
+                return;
+            }
+
+            fHasHeader = true;
+
+            // Convert FTM state into FtmCtrl state
+            switch (fHeader.fState)
+            {
+            case FTM::kFtmIdle:
+            case FTM::kFtmConfig:
+                fState = FTM::kIdle;
+                break;
+
+            case FTM::kFtmCalib:
+            case FTM::kFtmRunning:
+                fState = FTM::kTakingData;
+                break;
+            }
+
+            if (++fCounter[kHeader]==1)
+                UpdateFirstHeader();
+
+            UpdateHeader();
+
+            // Start reading of data
+            switch (fHeader.fType)
+            {
+            case kStaticData:
+            case kDynamicData:
+            case kFtuList:
+            case kRegister:
+            case kErrorList:
+                // This is not very efficient because the space is reallocated
+                // maybe we can check if the capacity of the std::vector
+                // is ever decreased. If not, everythign is fine.
+                fBuffer.resize(fHeader.fDataSize);
+                AsyncRead(ba::buffer(fBuffer));
+                AsyncWait(fInTimeout, 50, &Connection::HandleReadTimeout);
+                return;
+
+            default:
+                stringstream str;
+                str << "Unknonw type " << fHeader.fType << " in received header." << endl;
+                Error(str);
+                PostClose(false);
+                return;
+            }
+
+            return;
+        }
+
+        // Check the data integrity (check end delimiter)
+        if (ntohs(fBuffer.back())!=FTM::kDelimiterEnd)
+        {
+            stringstream str;
+            str << "Invalid data received: end delimiter wrong, received ";
+            str << hex << ntohs(fBuffer.back()) << " expected " << kDelimiterEnd << ".";
+            Error(str);
+            PostClose(false);
+            return;
+        }
+
+        // Remove end delimiter
+        fBuffer.pop_back();
+
+        try
+        {
+            // If we have already received a header this is the data now
+            // This could be moved to a HandleReceivedData function
+
+            fCounter[fHeader.fType]++;
+
+            switch (fHeader.fType)
+            {
+            case kFtuList:
+                fFtuList = fBuffer;
+                UpdateFtuList();
+                break;
+
+            case kStaticData:
+                fStaticData = fBuffer;
+                UpdateStaticData();
+            break;
+
+            case kDynamicData:
+                fDynamicData = fBuffer;
+                UpdateDynamicData();
+                break;
+
+            case kRegister:
+                if (fIsVerbose)
+                {
+                    Out() << endl << kBold << "Register received: " << endl;
+                    Out() << "Value: " << ntohs(fBuffer[0]) << endl;
+                }
+                break;
+
+            case kErrorList:
+                fError = fBuffer;
+                UpdateError();
+                break;
+
+            default:
+                stringstream str;
+                str << "Unknonw type " << fHeader.fType << " in header." << endl;
+                Error(str);
+                PostClose(false);
+                return;
+            }
+        }
+        catch (const logic_error &e)
+        {
+            stringstream str;
+            str << "Exception converting buffer into data structure: " << e.what();
+            Error(str);
+            PostClose(false);
+            return;
+        }
+
+        fInTimeout.cancel();
+
+        fHeader.clear();
+        fHasHeader = false;
+        fBuffer.resize(sizeof(FTM::Header)/2);
+        AsyncRead(ba::buffer(fBuffer));
+    }
+
+    // This is called when a connection was established
+    void ConnectionEstablished()
+    {
+        fState = FTM::kConnected;
+        fCounter.clear();
+
+        fHeader.clear();
+        fHasHeader = false;
+        fBuffer.resize(sizeof(FTM::Header)/2);
+        AsyncRead(ba::buffer(fBuffer));
+
+        // Get a header and configdata!
+        CmdReqStatDat();
+
+        // get the DNA of the FTUs
+        CmdPing();
+    }
+
+    void HandleReadTimeout(const bs::error_code &error)
+    {
+        if (error && error!=ba::error::basic_errors::operation_aborted)
+        {
+            stringstream str;
+            str << "Read timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
+            Error(str);
+
+            PostClose();
+            return;
+
+        }
+
+        if (!is_open())
+        {
+            // For example: Here we could schedule a new accept if we
+            // would not want to allow two connections at the same time.
+            return;
+        }
+
+        // Check whether the deadline has passed. We compare the deadline
+        // against the current time since a new asynchronous operation
+        // may have moved the deadline before this actor had a chance
+        // to run.
+        if (fInTimeout.expires_at() > ba::deadline_timer::traits_type::now())
+            return;
+
+        Error("Timeout reading data from "+URL());
+
+        PostClose();
+    }
+
+
+    template<size_t N>
+    void PostCmd(boost::array<uint16_t, N> dat, uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
+    {
+        boost::array<uint16_t, 5> cmd = {{ '@', u1, u2, u3, u4 }};
+
+        stringstream msg;
+        msg << "Sending command:" << hex;
+        msg << " 0x" << setw(4) << setfill('0') << cmd[0];
+        msg << " 0x" << setw(4) << setfill('0') << u1;
+        msg << " 0x" << setw(4) << setfill('0') << u2;
+        msg << " 0x" << setw(4) << setfill('0') << u3;
+        msg << " 0x" << setw(4) << setfill('0') << u4;
+        msg << " (+" << dec << dat.size() << " words)";
+        Message(msg);
+
+        vector<uint16_t> out(cmd.size()+dat.size());
+
+        transform(cmd.begin(), cmd.end(), out.begin(), htons);
+        transform(dat.begin(), dat.end(), out.begin()+cmd.size(), htons);
+
+        PostMessage(out);
+    }
+
+    void PostCmd(vector<uint16_t> dat, uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
+    {
+        boost::array<uint16_t, 5> cmd = {{ '@', u1, u2, u3, u4 }};
+
+        stringstream msg;
+        msg << "Sending command:" << hex;
+        msg << " 0x" << setw(4) << setfill('0') << cmd[0];
+        msg << " 0x" << setw(4) << setfill('0') << u1;
+        msg << " 0x" << setw(4) << setfill('0') << u2;
+        msg << " 0x" << setw(4) << setfill('0') << u3;
+        msg << " 0x" << setw(4) << setfill('0') << u4;
+        msg << " (+" << dec << dat.size() << " words)";
+        Message(msg);
+
+        vector<uint16_t> out(cmd.size()+dat.size());
+
+        transform(cmd.begin(), cmd.end(), out.begin(), htons);
+        copy(dat.begin(), dat.end(), out.begin()+cmd.size());
+
+        PostMessage(out);
+    }
+
+    void PostCmd(uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
+    {
+        PostCmd(boost::array<uint16_t, 0>(), u1, u2, u3, u4);
+    }
+public:
+
+    static const uint16_t kMaxAddr;
+
+public:
+    ConnectionFTM(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
+        fIsVerbose(true), fIsDynamicOut(false), fIsHexOutput(false)
+    {
+        cout << "xFTM" << endl;
+        SetLogStream(&imp);
+        cout << "check" << endl;
+    }
+
+    void CmdToggleLed()
+    {
+        PostCmd(kCmdToggleLed);
+    }
+
+    void CmdPing()
+    {
+        PostCmd(kCmdPing);
+    }
+
+    void CmdReqDynDat()
+    {
+        PostCmd(kCmdRead, kReadDynamicData);
+    }
+
+    void CmdReqStatDat()
+    {
+        PostCmd(kCmdRead, kReadStaticData);
+    }
+
+    void CmdSendStatDat()
+    {
+        PostCmd(fStaticData.HtoN(), kCmdWrite, kWriteStaticData);
+
+        // Request the changed configuration to ensure the
+        // change is distributed in the network
+        CmdReqStatDat();
+    }
+
+    void CmdStartRun()
+    {
+        PostCmd(kCmdStartRun, kStartRun);
+
+        // Update state information by requesting a new header
+        CmdGetRegister(0);
+    }
+
+    void CmdStopRun()
+    {
+        PostCmd(kCmdStopRun);
+
+        // Update state information by requesting a new header
+        CmdGetRegister(0);
+    }
+
+    void CmdTakeNevents(uint32_t n)
+    {
+        const boost::array<uint16_t, 2> data = {{ uint16_t(n>>16), uint16_t(n&0xffff) }};
+        PostCmd(data, kCmdStartRun, kTakeNevents);
+
+        // Update state information by requesting a new header
+        CmdGetRegister(0);
+    }
+
+    bool CmdSetRegister(uint16_t addr, uint16_t val)
+    {
+        if (addr>kMaxAddr)
+            return false;
+
+        const boost::array<uint16_t, 2> data = {{ addr, val }};
+        PostCmd(data, kCmdWrite, kWriteRegister);
+
+        // Request the changed configuration to ensure the
+        // change is distributed in the network
+        CmdReqStatDat();
+
+        return true;
+    }
+
+    bool CmdGetRegister(uint16_t addr)
+    {
+        if (addr>kMaxAddr)
+            return false;
+
+        const boost::array<uint16_t, 1> data = {{ addr }};
+        PostCmd(data, kCmdRead, kReadRegister);
+
+        return true;
+    }
+
+    bool CmdDisableReports(bool b)
+    {
+        PostCmd(kCmdDisableReports, b ? uint16_t(0) : uint16_t(1));
+        return true;
+    }
+
+    void SetVerbose(bool b)
+    {
+        fIsVerbose = b;
+    }
+
+    bool LoadStaticData(string name)
+    {
+        if (name.rfind(".bin")!=name.length()-5)
+            name += ".bin";
+
+        ifstream fin(name);
+        if (!fin)
+            return false;
+
+        FTM::StaticData data;
+
+        fin.read(reinterpret_cast<char*>(&data), sizeof(FTM::StaticData));
+
+        if (fin.gcount()<streamsize(sizeof(FTM::StaticData)))
+            return false;
+
+        if (fin.fail() || fin.eof())
+            return false;
+
+        if (fin.peek()!=-1)
+            return false;
+
+        fStaticData = data;
+
+        CmdSendStatDat();
+
+        return true;
+    }
+
+    bool SaveStaticData(string name) const
+    {
+        if (name.rfind(".bin")!=name.length()-5)
+            name += ".bin";
+
+        ofstream fout(name);
+        if (!fout)
+            return false;
+
+        fout.write(reinterpret_cast<const char*>(&fStaticData), sizeof(FTM::StaticData));
+
+        return !fout.bad();
+    }
+
+    int GetState() const { return IsConnected() ? fState : (int)FTM::kDisconnected; }
+};
+
+const uint16_t ConnectionFTM::kMaxAddr = 0xfff;
+
+// ------------------------------------------------------------------------
+
+#include "DimDescriptionService.h"
+
+class ConnectionDimFTM : public ConnectionFTM
+{
+private:
+
+    DimDescribedService fDimPassport;
+    DimDescribedService fDimTriggerCounter;
+    DimDescribedService fDimError;
+    DimDescribedService fDimFtuList;
+    DimDescribedService fDimStaticData;
+    DimDescribedService fDimDynamicData;
+
+    template<class T>
+        void Update(DimDescribedService &svc, const T &data) const
+    {
+        //cout << "Update: " << svc.getName() << " (" << sizeof(T) << ")" << endl;
+        svc.setData(const_cast<T*>(&data), sizeof(T));
+        svc.updateService();
+    }
+
+    virtual void UpdateFirstHeader()
+    {
+        ConnectionFTM::UpdateFirstHeader();
+
+        const DimPassport data(fHeader);
+        Update(fDimPassport, data);
+    }
+
+    virtual void UpdateHeader()
+    {
+        ConnectionFTM::UpdateHeader();
+
+        const DimTriggerCounter data(fHeader);
+        Update(fDimTriggerCounter, data);
+    }
+
+    virtual void UpdateFtuList()
+    {
+        ConnectionFTM::UpdateFtuList();
+
+        const DimFtuList data(fHeader, fFtuList);
+        Update(fDimFtuList, data);
+    }
+
+    virtual void UpdateStaticData()
+    {
+        ConnectionFTM::UpdateStaticData();
+
+        const DimStaticData data(fHeader, fStaticData);
+        Update(fDimStaticData, data);
+    }
+
+    virtual void UpdateDynamicData()
+    {
+        ConnectionFTM::UpdateDynamicData();
+
+        const DimDynamicData data(fHeader, fDynamicData);
+        Update(fDimDynamicData, data);
+    }
+
+    virtual void UpdateError()
+    {
+        ConnectionFTM::UpdateError();
+
+        const DimError data(fHeader, fError);
+        Update(fDimError, data);
+    }
+
+public:
+    ConnectionDimFTM(ba::io_service& ioservice, MessageImp &imp) :
+        ConnectionFTM(ioservice, imp),
+        fDimPassport      ("FTM_CONTROL/PASSPORT",        "X:1;S:1",      NULL, 0, ""),
+        fDimTriggerCounter("FTM_CONTROL/TRIGGER_COUNTER", "X:1;L:1",      NULL, 0, ""),
+        fDimError         ("FTM_CONTROL/ERROR",           "X:1;S:1;S:28", NULL, 0, ""),
+        fDimFtuList       ("FTM_CONTROL/FTU_LIST",        "X:1;X:1;S:1;C:4;X:40;C:40;C:40", NULL, 0, ""),
+        fDimStaticData    ("FTM_CONTROL/STATIC_DATA",     "X:1;S:1;S:1;X:1;S:1;S:3;S:1;S:1;S:1;S:1;S:1;S:1;I:1;S:8;S:80;S:160;S:40;S:40", NULL, 0, ""),
+        fDimDynamicData   ("FTM_CONTROL/DYNAMIC_DATA",    "X:1;X:1;F:4;I:160;I:40;S:40;S:40", NULL, 0, "")
+    {
+    }
+
+    // A B [C] [D] E [F] G H [I] J K [L] M N O P Q R [S] T U V W [X] Y Z
+};
+
+// ------------------------------------------------------------------------
+
+template <class T, class S>
+class StateMachineFTM : public T, public ba::io_service, public ba::io_service::work
+{
+    int Wrap(boost::function<void()> f)
+    {
+        f();
+        return T::GetCurrentState();
+    }
+
+    boost::function<int(const EventImp &)> Wrapper(boost::function<void()> func)
+    {
+        return boost::bind(&StateMachineFTM::Wrap, this, func);
+    }
+
+private:
+    S fFTM;
+
+    enum states_t
+    {
+        kStateDisconnected = FTM::kDisconnected,
+        kStateConnected    = FTM::kConnected,
+        kStateIdle         = FTM::kIdle,
+        kStateTakingData   = FTM::kTakingData,
+/*
+        kCmdToggleLed,
+        kCmdPing,
+        kCmdReqDynData,
+        kCmdReqStatData,
+        kCmdReqRegister,
+        kCmdSetRegister,
+  */
+        kCmdTest
+    };
+
+    int SetRegister(const Event &evt)
+    {
+        if (evt.GetSize()!=8)
+        {
+            stringstream msg;
+            msg << "SetRegister - Received event has " << evt.GetSize() << " bytes, but expected 8.";
+            T::Fatal(msg);
+
+            return T::kSM_FatalError;
+        }
+
+        const unsigned int *dat = reinterpret_cast<const unsigned int*>(evt.GetData());
+
+        if (dat[1]>uint16_t(-1))
+        {
+            stringstream msg;
+            msg << hex << "Value " << dat[1] << " out of range.";
+            T::Error(msg);
+            return T::GetCurrentState();
+        }
+
+
+        if (dat[0]>uint16_t(-1) || !fFTM.CmdSetRegister(dat[0], dat[1]))
+        {
+            stringstream msg;
+            msg << hex << "Address " << dat[0] << " out of range.";
+            T::Error(msg);
+        }
+
+        return T::GetCurrentState();
+    }
+
+    int GetRegister(const Event &evt)
+    {
+        if (evt.GetSize()!=4)
+        {
+            stringstream msg;
+            msg << "GetRegister - Received event has " << evt.GetSize() << "bytes,  but expected 2.";
+            T::Fatal(msg);
+            return T::kSM_FatalError;
+        }
+
+        const unsigned int addr = evt.GetInt();
+        if (addr>uint16_t(-1) || !fFTM.CmdGetRegister(addr))
+        {
+            stringstream msg;
+            msg << hex << "Address " << addr << " out of range.";
+            T::Error(msg);
+        }
+
+        return T::GetCurrentState();
+    }
+
+    int TakeNevents(const Event &evt)
+    {
+        if (evt.GetSize()!=4)
+        {
+            stringstream msg;
+            msg << "TakeNevents - Received event has " << evt.GetSize() << " bytes, but expected 4.";
+            T::Fatal(msg);
+
+            return T::kSM_FatalError;
+        }
+
+        const unsigned int dat = evt.GetUInt();
+
+        /*
+        if (dat[1]>uint32_t(-1))
+        {
+            stringstream msg;
+            msg << hex << "Value " << dat[1] << " out of range.";
+            T::Error(msg);
+            return T::GetCurrentState();
+        }*/
+
+        fFTM.CmdTakeNevents(dat);
+
+        return T::GetCurrentState();
+    }
+
+    int DisableReports(const Event &evt)
+    {
+        if (evt.GetSize()!=1)
+        {
+            stringstream msg;
+            msg << "DisableReports - Received event has " << evt.GetSize() << " bytes, but expected 1.";
+            T::Fatal(msg);
+
+            return T::kSM_FatalError;
+        }
+
+        fFTM.CmdDisableReports(evt.GetText()[0]!=0);
+
+        return T::GetCurrentState();
+    }
+
+    int SetVerbosity(const Event &evt)
+    {
+        if (evt.GetSize()!=1)
+        {
+            stringstream msg;
+            msg << "SetVerbosity - Received event has " << evt.GetSize() << " bytes, but expected 1.";
+            T::Fatal(msg);
+
+            return T::kSM_FatalError;
+        }
+
+        fFTM.SetVerbose(evt.GetText()[0]!=0);
+
+        return T::GetCurrentState();
+    }
+
+    int LoadStaticData(const Event &evt)
+    {
+        if (fFTM.LoadStaticData(evt.GetString()))
+            return T::GetCurrentState();
+
+        stringstream msg;
+        msg << "Loading static data from file '" << evt.GetString() << "' failed ";
+
+        if (errno)
+            msg << "(" << strerror(errno) << ")";
+        else
+            msg << "(wrong size, expected " << sizeof(FTM::StaticData) << " bytes)";
+
+        T::Warn(msg);
+
+        return T::GetCurrentState();
+    }
+
+    int SaveStaticData(const Event &evt)
+    {
+        if (fFTM.SaveStaticData(evt.GetString()))
+            return T::GetCurrentState();
+
+        stringstream msg;
+        msg << "Writing static data to file '" << evt.GetString() << "' failed ";
+        msg << "(" << strerror(errno) << ")";
+
+        T::Warn(msg);
+
+        return T::GetCurrentState();
+    }
+
+
+    int Disconnect()
+    {
+        // Close all connections
+        fFTM.PostClose(false);
+
+        /*
+         // Now wait until all connection have been closed and
+         // all pending handlers have been processed
+         poll();
+         */
+
+        return T::GetCurrentState();
+    }
+
+    int Reconnect(const Event &evt)
+    {
+        // Close all connections to supress the warning in SetEndpoint
+        fFTM.PostClose(false);
+
+        // Now wait until all connection have been closed and
+        // all pending handlers have been processed
+        poll();
+
+        if (evt.GetText()[0]!=0)
+            fFTM.SetEndpoint(evt.GetString());
+
+        // Now we can reopen the connection
+        fFTM.PostClose(true);
+
+        return T::GetCurrentState();
+    }
+
+    /*
+    int Transition(const Event &evt)
+    {
+        switch (evt.GetTargetState())
+        {
+        case kStateDisconnected:
+        case kStateConnected:
+        }
+
+        return T::kSM_FatalError;
+    }*/
+
+    int Execute()
+    {
+        // Dispatch (execute) at most one handler from the queue. In contrary
+        // to run_one(), it doesn't wait until a handler is available
+        // which can be dispatched, so poll_one() might return with 0
+        // handlers dispatched. The handlers are always dispatched/executed
+        // synchronously, i.e. within the call to poll_one()
+        poll_one();
+
+        return fFTM.GetState();
+    }
+
+public:
+    StateMachineFTM(ostream &out=cout) :
+        T(out, "FTM_CONTROL"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
+        fFTM(*this, *this)
+    {
+        cout << "FTM" << endl;
+
+        // ba::io_service::work is a kind of keep_alive for the loop.
+        // It prevents the io_service to go to stopped state, which
+        // would prevent any consecutive calls to run()
+        // or poll() to do nothing. reset() could also revoke to the
+        // previous state but this might introduce some overhead of
+        // deletion and creation of threads and more.
+
+        // State names
+        AddStateName(kStateDisconnected, "Disconnected",
+                     "FTM board not connected via ethernet.");
+
+        AddStateName(kStateConnected, "Connected",
+                     "Ethernet connection to FTM established (no state received yet).");
+
+        AddStateName(kStateIdle, "Idle",
+                     "Ethernet connection to FTM established, FTM in idle state.");
+
+        AddStateName(kStateTakingData, "TakingData",
+                     "Ethernet connection to FTM established, FTM is in taking data state.");
+
+        // FTM Commands
+        AddConfiguration("TOGGLE_LED", kStateIdle)
+            (Wrapper(boost::bind(&ConnectionFTM::CmdToggleLed, &fFTM)))
+            ("toggle led");
+
+        AddConfiguration("PING", kStateIdle)
+            (Wrapper(boost::bind(&ConnectionFTM::CmdPing, &fFTM)))
+            ("send ping");
+
+        AddConfiguration("REQUEST_DYNAMIC_DATA", kStateIdle)
+            (Wrapper(boost::bind(&ConnectionFTM::CmdReqDynDat, &fFTM)))
+            ("request transmission of dynamic data block");
+
+        AddConfiguration("REQUEST_STATIC_DATA", kStateIdle)
+            (Wrapper(boost::bind(&ConnectionFTM::CmdReqStatDat, &fFTM)))
+            ("request transmission of static data from FTM to memory");
+
+        AddConfiguration("GET_REGISTER", "I", kStateIdle)
+            (boost::bind(&StateMachineFTM::GetRegister, this, _1))
+            ("read register from address addr"
+            "|addr[short]:Address of register");
+
+        AddConfiguration("SET_REGISTER", "I:2", kStateIdle)
+            (boost::bind(&StateMachineFTM::SetRegister, this, _1))
+            ("set register to value"
+            "|addr[short]:Address of register"
+            "|val[short]:Value to be set");
+
+        AddConfiguration("START_RUN", kStateIdle)
+            (Wrapper(boost::bind(&ConnectionFTM::CmdStartRun, &fFTM)))
+            ("start a run (start distributing triggers)");
+
+        AddConfiguration("STOP_RUN", kStateTakingData)
+            (Wrapper(boost::bind(&ConnectionFTM::CmdStopRun, &fFTM)))
+            ("stop a run (stop distributing triggers)");
+
+        AddConfiguration("TAKE_N_EVENTS", "I", kStateIdle)
+            (boost::bind(&StateMachineFTM::TakeNevents, this, _1))
+            ("take n events (distribute n triggers)|number[int]:Number of events to be taken");
+
+        AddConfiguration("DISABLE_REPORTS", "B", kStateIdle)
+            (boost::bind(&StateMachineFTM::DisableReports, this, _1))
+            ("disable sending rate reports"
+             "|status[bool]:disable or enable that the FTM sends rate reports (yes/no)");
+
+        T::AddConfiguration("SET_VERBOSE", "B")
+            (boost::bind(&StateMachineFTM::SetVerbosity, this, _1))
+            ("set verbosity state"
+             "|verbosity[bool]:disable or enable verbosity for received data (yes/no)");
+
+        T::AddConfiguration("SAVE", "C", kStateIdle)
+            (boost::bind(&StateMachineFTM::SaveStaticData, this, _1))
+            ("Saves the static data (FTM configuration) from memory to a file"
+             "|filename[string]:Filename (can include a path), .bin is automatically added");
+
+        T::AddConfiguration("LOAD", "C", kStateIdle)
+            (boost::bind(&StateMachineFTM::LoadStaticData, this, _1))
+            ("Loads the static data (FTM configuration) from a file into memory and sends it to the FTM"
+             "|filename[string]:Filename (can include a path), .bin is automatically added");
+
+        // Conenction commands
+        AddConfiguration("DISCONNECT", kStateConnected, kStateIdle)
+            (boost::bind(&StateMachineFTM::Disconnect, this))
+            ("disconnect from ethernet");
+
+        AddConfiguration("RECONNECT", "O", kStateDisconnected, kStateConnected, kStateIdle)
+            (boost::bind(&StateMachineFTM::Reconnect, this, _1))
+            ("(Re)connect ethernet connection to FTM, a new address can be given"
+             "|[host][string]:new ethernet address in the form <host:port>");
+
+        // Other
+        AddTransition(kCmdTest, "TEST", "O")
+            (boost::bind(&StateMachineFTM::Test, this, _1))
+            ("Just for test purpose, do not use");
+
+        fFTM.StartConnect();
+
+
+        // RESET_THRESHOLD        val
+        // --> SetThreshold(-1, val)
+
+        // SET_THRESHOLD          idx val
+        // ---> SetThreshold(idx, val)
+
+
+        // ENABLE_FTU             idx bool  (-1 for all)
+        // ---> EnableFtu(idx, bool)
+
+
+        // ENABLE_TRIGGER         bool
+        // ENABLE_EXT1            bool
+        // ENABLE_EXT2            bool
+        // ENABLE_TIM             bool
+        // ENABLE_VETO            bool
+        // ---> Enable(bit, bool)
+
+
+        // SET_TRIGGER_SEQUENCE   val val val
+        // ---> SetTriggerSequence(val, val, val)
+
+
+        // SET_TRIGGER_INTERVAL   val
+        // SET_TRIGGER_DELAY      val
+        // SET_TIME_MARKER_DELAY  val
+        // SET_DEAD_TIME          val
+        // ---> SetXYZ(val)
+
+
+        // SET_PRESCALING         idx val
+        // ---> SetPrescaling(-1, val)
+
+        // RESET_PRESCALING       val
+        // ---> SetPrescaling(idx, val)
+    }
+
+        /// Just for test purpose, do not touch
+    int Test(const Event &evt)
+    {
+        const Converter conv(T::Out(), evt.GetFormat(), false);
+        T::Out() << kBlue << evt.GetName();
+        T::Out() << " " << conv.GetString(evt.GetData(), evt.GetSize());
+        T::Out() << endl;
+
+        return T::GetCurrentState();
+    }
+
+    void SetEndpoint(const string &url)
+    {
+        fFTM.SetEndpoint(url);
+    }
+
+    bool SetConfiguration(const Configuration &conf)
+    {
+        SetEndpoint(conf.Get<string>("addr"));
+        return true;
+    }
+};
+
+// ------------------------------------------------------------------------
+
+void RunThread(StateMachineImp *io_service)
+{
+    // This is necessary so that the StateMachien Thread can signal the
+    // Readline to exit
+    io_service->Run();
+    Readline::Stop();
+}
+
+template<class S, class T>
+int RunDim(Configuration &conf)
+{
+    WindowLog wout;
+
+    /*
+    static Test shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
+
+    WindowLog &win  = shell.GetStreamIn();
+    WindowLog &wout = shell.GetStreamOut();
+    */
+    cout << "Start" << endl;
+
+    if (conf.Has("log"))
+        if (!wout.OpenLogFile(conf.Get<string>("log")))
+            wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
+    cout << "Start" << endl;
+
+    // Start io_service.Run to use the StateMachineImp::Run() loop
+    // Start io_service.run to only use the commandHandler command detaching
+    StateMachineFTM<S, T> io_service(wout);
+    cout << "Start" << endl;
+    if (!io_service.SetConfiguration(conf))
+        return -1;
+
+    cout << "Start" << endl;
+    io_service.Run();
+
+    /*
+    shell.SetReceiver(io_service);
+
+    boost::thread t(boost::bind(RunThread, &io_service));
+    // boost::thread t(boost::bind(&StateMachineFTM<S>::Run, &io_service));
+
+    shell.Run();                 // Run the shell
+    io_service.Stop();           // Signal Loop-thread to stop
+    // io_service.Close();       // Obsolete, done by the destructor
+
+    // Wait until the StateMachine has finished its thread
+    // before returning and destroying the dim objects which might
+    // still be in use.
+    t.join();
+    */
+
+    return 0;
+}
+
+template<class T, class S, class R>
+int RunShell(Configuration &conf)
+{
+    static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
+
+    WindowLog &win  = shell.GetStreamIn();
+    WindowLog &wout = shell.GetStreamOut();
+
+    if (conf.Has("log"))
+        if (!wout.OpenLogFile(conf.Get<string>("log")))
+            win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
+
+    StateMachineFTM<S, R> io_service(wout);
+    if (!io_service.SetConfiguration(conf))
+        return -1;
+
+    shell.SetReceiver(io_service);
+
+    boost::thread t(boost::bind(RunThread, &io_service));
+    // boost::thread t(boost::bind(&StateMachineFTM<S>::Run, &io_service));
+
+    shell.Run();                 // Run the shell
+    io_service.Stop();           // Signal Loop-thread to stop
+    // io_service.Close();       // Obsolete, done by the destructor
+
+    // Wait until the StateMachine has finished its thread
+    // before returning and destroying the dim objects which might
+    // still be in use.
+    t.join();
+
+    return 0;
+}
+
+void SetupConfiguration(Configuration &conf)
+{
+    const string n = conf.GetName()+".log";
+
+    po::options_description config("Program options");
+    config.add_options()
+        ("dns",       var<string>("localhost"), "Dim nameserver host name (Overwites DIM_DNS_NODE environment variable)")
+        ("log,l",     var<string>(n), "Write log-file")
+        ("no-dim,d",  po_switch(),    "Disable dim services")
+        ("console,c", var<int>(),     "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
+        ;
+
+    po::options_description control("FTM control options");
+    control.add_options()
+        ("addr",      var<string>("localhost:5000"),  "Network address of FTM")
+        ;
+
+    conf.AddEnv("dns", "DIM_DNS_NODE");
+
+    conf.AddOptions(config);
+    conf.AddOptions(control);
+}
+
+/*
+ Extract usage clause(s) [if any] for SYNOPSIS.
+ Translators: "Usage" and "or" here are patterns (regular expressions) which
+ are used to match the usage synopsis in program output.  An example from cp
+ (GNU coreutils) which contains both strings:
+  Usage: cp [OPTION]... [-T] SOURCE DEST
+    or:  cp [OPTION]... SOURCE... DIRECTORY
+    or:  cp [OPTION]... -t DIRECTORY SOURCE...
+ */
+void PrintUsage()
+{
+    cout <<
+        "The ftmctrl controls the FTM (FACT Trigger Master) board.\n"
+        "\n"
+        "The default is that the program is started without user intercation. "
+        "All actions are supposed to arrive as DimCommands. Using the -c "
+        "option, a local shell can be initialized. With h or help a short "
+        "help message about the usuage can be brought to the screen.\n"
+        "\n"
+        "Usage: ftmctrl [-c type] [OPTIONS]\n"
+        "  or:  ftmctrl [OPTIONS]\n"
+        "\n"
+        "Options:\n"
+        "The following describes the available commandline options. "
+        "For further details on how command line option are parsed "
+        "and in which order which configuration sources are accessed "
+        "please refer to the class reference of the Configuration class.";
+    cout << endl;
+
+}
+
+void PrintHelp()
+{
+}
+
+/*
+ The first line of the --version information is assumed to be in one
+ of the following formats:
+
+   <version>
+   <program> <version>
+   {GNU,Free} <program> <version>
+   <program> ({GNU,Free} <package>) <version>
+   <program> - {GNU,Free} <package> <version>
+
+ and separated from any copyright/author details by a blank line.
+
+ Handle multi-line bug reporting sections of the form:
+
+   Report <program> bugs to <addr>
+   GNU <package> home page: <url>
+   ...
+*/
+void PrintVersion(const char *name)
+{
+    cout <<
+        name << " - "PACKAGE_STRING"\n"
+        "\n"
+        "Written by Thomas Bretz et al.\n"
+        "\n"
+        "Report bugs to <"PACKAGE_BUGREPORT">\n"
+        "Home page: "PACKAGE_URL"\n"
+        "\n"
+        "Copyright (C) 2011 by the FACT Collaboration.\n"
+        "This is free software; see the source for copying conditions.\n"
+        << endl;
+}
+
+int main(int argc, const char* argv[])
+{
+    Configuration conf(argv[0]);
+    conf.SetPrintUsage(PrintUsage);
+    SetupConfiguration(conf);
+
+    po::variables_map vm;
+    try
+    {
+        vm = conf.Parse(argc, argv);
+    }
+#if BOOST_VERSION > 104000
+    catch (po::multiple_occurrences &e)
+    {
+        cout << "Error: " << e.what() << " of '" << e.get_option_name() << "' option." << endl;
+        cout << endl;
+        return -1;
+    }
+#endif
+    catch (std::exception &e)
+    {
+        cout << "Error: " << e.what() << endl;
+        cout << endl;
+
+        return -1;
+    }
+
+    if (conf.HasPrint())
+        return -1;
+
+    if (conf.HasVersion())
+    {
+        PrintVersion(argv[0]);
+        return -1;
+    }
+
+    if (conf.HasHelp())
+    {
+        PrintHelp();
+        return -1;
+    }
+
+    // To allow overwriting of DIM_DNS_NODE set 0 to 1
+    setenv("DIM_DNS_NODE", conf.Get<string>("dns").c_str(), 1);
+
+    //try
+    {
+        // No console access at all
+        if (!conf.Has("console"))
+        {
+            if (conf.Get<bool>("no-dim"))
+                return RunDim<StateMachine, ConnectionFTM>(conf);
+            else
+                return RunDim<StateMachineDim, ConnectionDimFTM>(conf);
+        }
+        // Cosole access w/ and w/o Dim
+        if (conf.Get<bool>("no-dim"))
+        {
+            if (conf.Get<int>("console")==0)
+                return RunShell<LocalShell, StateMachine, ConnectionFTM>(conf);
+            else
+                return RunShell<LocalConsole, StateMachine, ConnectionFTM>(conf);
+        }
+        else
+        {
+            if (conf.Get<int>("console")==0)
+                return RunShell<LocalShell, StateMachineDim, ConnectionDimFTM>(conf);
+            else
+                return RunShell<LocalConsole, StateMachineDim, ConnectionDimFTM>(conf);
+        }
+    }
+    /*catch (std::exception& e)
+    {
+        cerr << "Exception: " << e.what() << endl;
+        return -1;
+    }*/
+
+    return 0;
+}
