Index: /trunk/demos/CircleFollower/simulator/build_core2_64/bin/simulator_x4.sh
===================================================================
--- /trunk/demos/CircleFollower/simulator/build_core2_64/bin/simulator_x4.sh	(revision 233)
+++ /trunk/demos/CircleFollower/simulator/build_core2_64/bin/simulator_x4.sh	(revision 234)
@@ -8,3 +8,3 @@
 . $FLAIR_ROOT/flair-dev/scripts/distribution_specific_hack.sh
 
-$EXEC -n x4_0 -t x4 -p 9000 -a 127.0.0.1 -x setup_x4.xml -o 10 -m $FLAIR_ROOT/flair-bin/models -s $FLAIR_ROOT/flair-bin/models/indoor_flight_arena.xml
+$EXEC -n x4_0 -t x4 -p 9000 -a 127.0.0.1 -x setup_x4.xml -o 100 -m $FLAIR_ROOT/flair-bin/models -s $FLAIR_ROOT/flair-bin/models/indoor_flight_arena.xml
Index: /trunk/lib/FlairCore/src/FrameworkManager_impl.cpp
===================================================================
--- /trunk/lib/FlairCore/src/FrameworkManager_impl.cpp	(revision 233)
+++ /trunk/lib/FlairCore/src/FrameworkManager_impl.cpp	(revision 234)
@@ -193,8 +193,4 @@
       Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
 
-    status = UDT::close(file_sock);
-    if (status != 0)
-      Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
-
     SleepMS(200); // a revoir, sinon UDT::cleanup bloque en RT
     UDT::cleanup();
@@ -210,4 +206,6 @@
     return;
   }
+  this->address=address;
+  this->port=port;
 																							
 	UDT::startup(1024*256,1024*256,1024*256);
@@ -216,6 +214,6 @@
   // socket file_socket, doit être créé en premier, cf station sol
   Printf("Connecting to %s:%i\n", address.c_str(), port);
-  file_sock = GetSocket(address, port);
-  com_sock = GetSocket(address, port);
+  //file_sock = GetSocket(address, port);
+  com_sock = GetSocket();
 
   // receive buffer allocation
@@ -226,12 +224,4 @@
 
   com = new ui_com(this, com_sock);
-
-  // file managment
-  bool blocking = true;
-  UDT::setsockopt(file_sock, 0, UDT_SNDSYN, &blocking, sizeof(bool));
-  UDT::setsockopt(file_sock, 0, UDT_RCVSYN, &blocking, sizeof(bool));
-
-  int timeout = 100; // ms
-  UDT::setsockopt(com_sock, 0, UDT_RCVTIMEO, &timeout, sizeof(int));
 
   Start();
@@ -292,14 +282,14 @@
   while (!ToBeStopped()) {
     ssize_t bytesRead;
-
     bytesRead = com->Receive(rcv_buf, rcv_buf_size);
-
+    com->CheckConnection();
+//printf("%i\n",bytesRead);
     if (bytesRead == (ssize_t)rcv_buf_size)
       Err("FrameworkManager max receive size, augmenter le buffer size!\n");
 
     if (bytesRead > 0) {
-      // printf("recu %ld, trame %x\n",bytesRead,(uint8_t)rcv_buf[0]);
-      // rcv_buf[bytesRead-1]=0;//pour affichage
-      // printf("%s\n",rcv_buf);
+       //printf("recu %ld, trame %x %lld\n",bytesRead,(uint8_t)rcv_buf[0],GetTime()/(1000000));
+       //rcv_buf[bytesRead-1]=0;//pour affichage
+       //printf("%s\n",rcv_buf);
 
       switch ((uint8_t)rcv_buf[0]) {
@@ -376,5 +366,5 @@
 }
 
-void FrameworkManager_impl::SendFile(string path, string name) {
+void FrameworkManager_impl::SendFile(UDTSOCKET socket,string path, string name) {
   char *buf, *more_buf;
   int size;
@@ -411,5 +401,5 @@
   Printf("sending %s, size: %i\n", filename.c_str(), size);
   // send file information
-  UDT::sendmsg(file_sock, buf, sizeof(uint8_t) + sizeof(int) + name.size(), -1,true);
+  UDT::sendmsg(socket, buf, sizeof(uint8_t) + sizeof(int) + name.size(), -1,true);
 
   more_buf = (char *)realloc((void *)buf, size);
@@ -424,5 +414,5 @@
   pbuf->sgetn(buf, size);
   // send the file
-  nb_write = UDT::sendmsg(file_sock, buf, size, -1, true);
+  nb_write = UDT::sendmsg(socket, buf, size, -1, true);
 
   if (nb_write < 0) {
@@ -436,9 +426,9 @@
 }
 
-void FrameworkManager_impl::FinishSending() {
+void FrameworkManager_impl::FinishSending(UDTSOCKET socket) {
   char rm_cmd[256];
 
   // send orignal xml
-  SendFile(log_path, "setup.xml");
+  SendFile(socket,log_path, "setup.xml");
   sprintf(rm_cmd, "rm %s/setup.xml", log_path.c_str());
   system(rm_cmd);
@@ -447,5 +437,5 @@
   for (size_t i = 0; i < xml_changes.size(); i++) {
     // Printf("%s\n",xml_changes.at(i).c_str());
-    SendFile(log_path, xml_changes.at(i).c_str());
+    SendFile(socket,log_path, xml_changes.at(i).c_str());
     sprintf(rm_cmd, "rm %s/%s", log_path.c_str(), xml_changes.at(i).c_str());
     system(rm_cmd);
@@ -454,6 +444,6 @@
 
   // end notify
-  char buf = END;
-  int nb_write = UDT::sendmsg(file_sock, &buf, 1, -1, true);
+  char buf = END_SENDING_FILES;
+  int nb_write = UDT::sendmsg(socket, &buf, 1, -1, true);
 
   if (nb_write < 0) {
@@ -464,5 +454,5 @@
 
   //wait end ACK
-  int nb_read = UDT::recvmsg(file_sock,&buf,1);
+  int nb_read = UDT::recvmsg(socket,&buf,1);
   if(nb_read<0) {
     Err("UDT::recvmsg error (%s)\n",UDT::getlasterror().getErrorMessage());
@@ -472,5 +462,5 @@
 }
 
-UDTSOCKET FrameworkManager_impl::GetSocket(string address, uint16_t port) {
+UDTSOCKET FrameworkManager_impl::GetSocket(void) {
   while (1) {
     UDTSOCKET new_fd;
@@ -854,4 +844,17 @@
               caller->gcs_watchdog->Join();
           }
+          //create a socket for files
+          UDTSOCKET file_sock = caller->GetSocket();
+          char data=START_SENDING_FILES;
+          ssize_t nb_write = UDT::sendmsg(file_sock, &data, 1, -1, true);
+          if (nb_write < 0) {
+            caller->Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
+            if (UDT::getlasterror().getErrorCode() == CUDTException::ECONNLOST ||
+                UDT::getlasterror().getErrorCode() == CUDTException::EINVSOCK) {
+            }
+          } else if (nb_write != 1) {
+            caller->Err("%s, code %i (%ld/%ld)\n", UDT::getlasterror().getErrorMessage(),
+                UDT::getlasterror().getErrorCode(), nb_write, 1);
+          }
           for (size_t i = 0; i < logs.size(); i++) {
             if (logs.at(i).dbtFile != NULL) {
@@ -859,5 +862,5 @@
 
               string filename = caller->FileName(logs.at(i).device) + ".dbt";
-              caller->SendFile(caller->log_path, filename);
+              caller->SendFile(file_sock,caller->log_path, filename);
 
               fstream txt_file;
@@ -870,10 +873,14 @@
               txt_file.close();
 
-              caller->SendFile(caller->log_path, filename);
+              caller->SendFile(file_sock,caller->log_path, filename);
             }
           }
           // a revoir celui ci est le xml enregistré et pas forcement l'actuel
           // if(caller->xml_file!="") caller->SendFile(caller->xml_file);
-          caller->FinishSending();
+          caller->FinishSending(file_sock);
+          
+          int status = UDT::close(file_sock);
+          if (status != 0)
+            caller->Err("Error udt::close %s", UDT::getlasterror().getErrorMessage());
 
           logs.clear();
Index: /trunk/lib/FlairCore/src/ui_com.cpp
===================================================================
--- /trunk/lib/FlairCore/src/ui_com.cpp	(revision 233)
+++ /trunk/lib/FlairCore/src/ui_com.cpp	(revision 234)
@@ -223,4 +223,14 @@
 }
 
+void ui_com::CheckConnection(void) {
+  int32_t val,len;
+  
+  int result=UDT::getsockopt(socket_fd,0,UDT_STATE,&val,&len); 
+   if (result < 0) {
+    Printf("UDT::getsockopt error (%s)\n", UDT::getlasterror().getErrorMessage());
+   }
+ // printf("opt: %i %i %i\n",result,val,len);
+}
+
 void ui_com::Run(void) {
   // check endianness
Index: /trunk/lib/FlairCore/src/unexported/FrameworkManager_impl.h
===================================================================
--- /trunk/lib/FlairCore/src/unexported/FrameworkManager_impl.h	(revision 233)
+++ /trunk/lib/FlairCore/src/unexported/FrameworkManager_impl.h	(revision 234)
@@ -82,9 +82,9 @@
 private:
   flair::core::FrameworkManager *self;
-  UDTSOCKET file_sock, com_sock;
-  UDTSOCKET GetSocket(std::string address, uint16_t port);
+  UDTSOCKET com_sock;
+  UDTSOCKET GetSocket(void);
   void Run();
-  void SendFile(std::string path, std::string name);
-  void FinishSending(void);
+  void SendFile(UDTSOCKET socket,std::string path, std::string name);
+  void FinishSending(UDTSOCKET socket);
   std::string FileName(flair::core::IODevice *device);
   void SaveXmlChange(char *buf);
@@ -92,4 +92,6 @@
   size_t rcv_buf_size;
   char *rcv_buf;
+  std::string address;
+  uint16_t port;
 #ifdef __XENO__
   int CreatePipe(RT_PIPE *fd, std::string name);
Index: /trunk/lib/FlairCore/src/unexported/communication.h
===================================================================
--- /trunk/lib/FlairCore/src/unexported/communication.h	(revision 233)
+++ /trunk/lib/FlairCore/src/unexported/communication.h	(revision 234)
@@ -6,15 +6,15 @@
 #define COMMUNICATION_H
 
-// messages file socket
-#define FILE_INFO_LITTLE_ENDIAN 0x01
-#define FILE_INFO_BIG_ENDIAN 0x02
-#define END 0x03
-
+// messages data socket
 #define XML_HEADER 0x3c
 #define ZLIB_HEADER 0x78
 #define WATCHDOG_HEADER 0x01
+#define DATAS_LITTLE_ENDIAN 0x02
+#define DATAS_BIG_ENDIAN 0x03
 
-#define DATAS_LITTLE_ENDIAN 0xfd
-#define DATAS_BIG_ENDIAN 0xfe
+#define START_SENDING_FILES 0x10
+#define FILE_INFO_LITTLE_ENDIAN 0x11
+#define FILE_INFO_BIG_ENDIAN 0x12
+#define END_SENDING_FILES 0x13
 
 #endif // COMMUNICATION_H
Index: /trunk/lib/FlairCore/src/unexported/ui_com.h
===================================================================
--- /trunk/lib/FlairCore/src/unexported/ui_com.h	(revision 233)
+++ /trunk/lib/FlairCore/src/unexported/ui_com.h	(revision 234)
@@ -48,5 +48,5 @@
   void UnBlock(void);
   bool ConnectionLost(void);
-
+  void CheckConnection(void);
 private:
   ssize_t send_size;
Index: /trunk/tools/Dbt2csv/CMakeLists.txt
===================================================================
--- /trunk/tools/Dbt2csv/CMakeLists.txt	(revision 233)
+++ /trunk/tools/Dbt2csv/CMakeLists.txt	(revision 234)
@@ -4,4 +4,6 @@
 
 if("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "i686" OR "${CMAKE_SYSTEM_PROCESSOR}" MATCHES "i586" OR "${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86_64")
+warn("${PROJECT_NAME} is broken since changes in FlairGCS/src/file_ui.cpp")
+return()
 
 SET(PROJECT_SOURCE_FILES
Index: /trunk/tools/FlairGCS/src/ConnectionLayout.cpp
===================================================================
--- /trunk/tools/FlairGCS/src/ConnectionLayout.cpp	(revision 233)
+++ /trunk/tools/FlairGCS/src/ConnectionLayout.cpp	(revision 234)
@@ -8,78 +8,22 @@
 #include <qendian.h>
 #include "communication.h"
-#include <zlib.h>
-#include <assert.h>
-
-#define COMPRESS_CHUNK 1024
-#define RX_TIME 5000
 
 ConnectionLayout::ConnectionLayout(UdtSocket *socket, QString name)
     : Layout(NULL, name, "root") {
-  isRemoteNameDefined = false;
   this->socket = socket;
-
-  total_received=0;
-  receive_timer = new QTimer(this);
-  connect(receive_timer, SIGNAL(timeout()), this, SLOT(computeRxRate()));
-  receive_timer->start(RX_TIME);
+  this->name = name;
 }
 
 ConnectionLayout::~ConnectionLayout() {
-  receive_timer->stop();
 }
 
-void ConnectionLayout::computeRxRate(void) {
-  float receive_rate=((float)total_received/(RX_TIME/1000))/1000;//in Ko/s
-  total_received=0;
-  computedRxRate(receive_rate);
+QString ConnectionLayout::getUDTStats() {
+  return socket->getUDTStats();
 }
 
 void ConnectionLayout::receive(char *buf, int size) {
-  total_received+=size-1;
   // printf("trame %x\n",buf[0]);
   // for(int i=0; i<size;i++) printf("%x ",buf[i]);
   // printf("\n");
-  switch (buf[0]) {
-  case ZLIB_HEADER: {
-    ssize_t out_size;
-    char *uncompressbuf;
-    uncompressBuffer(buf, size, &uncompressbuf, &out_size);
-    handleUncompressedFrame(uncompressbuf, out_size);
-    free(uncompressbuf);
-    break;
-  }
-  default:
-    handleUncompressedFrame(buf, size);
-  }
-  free(buf);
-}
-
-void ConnectionLayout::XmlToSend(QDomDocument doc) {
-  // printf("xml to send\n%s\n",doc.toString().toLocal8Bit().constData());
-  // xml to send a mettre dans le manager
-  QMetaObject::invokeMethod(
-      socket, "write", Qt::BlockingQueuedConnection,
-      Q_ARG(const char *, doc.toString().toLocal8Bit().constData()),
-      Q_ARG(qint64, doc.toString().toLocal8Bit().length()));
-}
-
-void ConnectionLayout::LoadXml(QDomDocument to_parse) {
-  if (!isRemoteNameDefined) {
-    printf("load xml: name not defined!\n");
-    return;
-  }
-
-  QDomElement tmp = to_parse.firstChildElement("root");
-  while (tmp.attribute("name") != remoteName && !tmp.isNull())
-    tmp = to_parse.nextSiblingElement("root");
-
-  if (!tmp.isNull()) {
-    XmlWidget::LoadXml(tmp);
-  } else {
-    printf("%s not found in xml file \n", remoteName.toLocal8Bit().constData());
-  }
-}
-
-void ConnectionLayout::handleUncompressedFrame(char *buf, ssize_t size) {
   switch ((unsigned char)buf[0]) {
   case XML_HEADER: {
@@ -92,11 +36,4 @@
     if (!doc.setContent(xml)) {
       printf("prob setContent fichier\n");
-    }
-
-    if (!isRemoteNameDefined) {
-      isRemoteNameDefined = true;
-      remoteName = doc.firstChildElement("root").attribute("name");
-      setRemoteName(remoteName);
-      SetAttribute("name", remoteName);
     }
 
@@ -127,4 +64,27 @@
 }
 
+void ConnectionLayout::XmlToSend(QDomDocument doc) {
+  // printf("xml to send\n%s\n",doc.toString().toLocal8Bit().constData());
+  
+  // xml to send a mettre dans le manager
+  socket->write(doc.toString().toLocal8Bit().constData(),doc.toString().toLocal8Bit().length());/*
+  QMetaObject::invokeMethod(
+      socket, "write", Qt::BlockingQueuedConnection,
+      Q_ARG(const char *, doc.toString().toLocal8Bit().constData()),
+      Q_ARG(qint64, doc.toString().toLocal8Bit().length()));*/
+}
+
+void ConnectionLayout::LoadXml(QDomDocument to_parse) {
+  QDomElement tmp = to_parse.firstChildElement("root");
+  while (tmp.attribute("name") != name && !tmp.isNull())
+    tmp = to_parse.nextSiblingElement("root");
+
+  if (!tmp.isNull()) {
+    XmlWidget::LoadXml(tmp);
+  } else {
+    printf("%s not found in xml file \n", name.toLocal8Bit().constData());
+  }
+}
+
 void ConnectionLayout::removeDataRemote(DataRemote *data) {
   dataremotes.removeOne(data);
@@ -135,5 +95,5 @@
 }
 
-QString ConnectionLayout::getRemoteName() { return remoteName; }
+QString ConnectionLayout::getName() { return name; }
 
 void ConnectionLayout::drawDatas(char *buf, int buf_size, uint16_t period,
@@ -144,46 +104,14 @@
 }
 
-int ConnectionLayout::uncompressBuffer(char *in, ssize_t in_size, char **out,
-                                       ssize_t *out_size) {
-  int ret;
-  unsigned have;
-  z_stream strm;
+QString ConnectionLayout::getDocRootName(char* buf, int size) {
+  QString xml;
+  QDomDocument doc;
+  xml = QString((char *)buf);
+  xml.resize(size);
 
-  // allocate inflate state
-  strm.zalloc = Z_NULL;
-  strm.zfree = Z_NULL;
-  strm.opaque = Z_NULL;
-  strm.avail_in = 0;
-  strm.next_in = Z_NULL;
-  ret = inflateInit(&strm);
-  if (ret != Z_OK)
-    return ret;
-
-  *out = (char *)malloc(COMPRESS_CHUNK);
-  if (!(*out))
-    return Z_BUF_ERROR;
-
-  strm.avail_in = in_size;
-  strm.next_in = (unsigned char *)in;
-  strm.avail_out = COMPRESS_CHUNK;
-  strm.next_out = (unsigned char *)*out;
-
-  ret = inflate(&strm, Z_NO_FLUSH);
-  assert(ret != Z_STREAM_ERROR); // state not clobbered
-  switch (ret) {
-  case Z_NEED_DICT:
-    ret = Z_DATA_ERROR; // and fall through
-  case Z_DATA_ERROR:
-  case Z_MEM_ERROR:
-    (void)inflateEnd(&strm);
-    return ret;
+  if (!doc.setContent(xml)) {
+    printf("prob setContent fichier\n");
   }
-  have = COMPRESS_CHUNK - strm.avail_out;
-  *out_size = have;
-
-  // printf("%i -> %i\n",in_size,have);
-  // printf("%s\n",*out);
-  // clean up and return
-  (void)inflateEnd(&strm);
-  return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
+  
+  return doc.firstChildElement("root").attribute("name");
 }
Index: /trunk/tools/FlairGCS/src/ConnectionLayout.h
===================================================================
--- /trunk/tools/FlairGCS/src/ConnectionLayout.h	(revision 233)
+++ /trunk/tools/FlairGCS/src/ConnectionLayout.h	(revision 234)
@@ -6,5 +6,4 @@
 #define CONNECTIONLAYOUT_H
 
-#include <QTimer>
 #include "Layout.h"
 
@@ -22,26 +21,20 @@
   void removeDataRemote(DataRemote *data);
   void LoadXml(QDomDocument to_parse);
-  QString getRemoteName();
+  QString getName();
+  QString getUDTStats();
+  static QString getDocRootName(char* buf, int size);
 
 private:
-  static int uncompressBuffer(char *in, ssize_t in_size, char **out,
-                              ssize_t *out_size);
-  void handleUncompressedFrame(char *buf, ssize_t size);
   void drawDatas(char *buf, int buf_size, uint16_t period,
                  bool big_endian = false);
-  bool isRemoteNameDefined;
-  QString remoteName;
+  QString name;
   UdtSocket *socket;
   QList<DataRemote *> dataremotes;
-  unsigned int total_received;
-  QTimer *receive_timer;
-
+  
 private slots:
   void receive(char *buf, int size);
-  void computeRxRate(void);
 
 signals:
-  void setRemoteName(QString name);
-  void computedRxRate(float rxRate);
+  void UDTStats(QString stats);  
 };
 
Index: /trunk/tools/FlairGCS/src/DataRemote.cpp
===================================================================
--- /trunk/tools/FlairGCS/src/DataRemote.cpp	(revision 233)
+++ /trunk/tools/FlairGCS/src/DataRemote.cpp	(revision 234)
@@ -57,7 +57,5 @@
   if (action == setRefreshRate) {
     bool ok;
-    // uint16_t time = QInputDialog::getInt(this, QString("Set refresh rate
-    // (%1)").arg(title().text()),tr("Value (ms):"),
-    // (uint16_t)(qRound(refresh_rate*1000)), 1, 65535, 10, &ok);
+  
     uint16_t time = QInputDialog::getInt(
         parent, "Set refresh rate ", "Value (ms):",
@@ -83,7 +81,5 @@
   SetAttribute("period", period);
   SetAttribute("enabled", auto_refresh);
-
   connectionLayout()->XmlToSend(XmlDoc());
-
   RemoveAttribute("period");
   RemoveAttribute("enabled");
Index: /trunk/tools/FlairGCS/src/Manager.cpp
===================================================================
--- /trunk/tools/FlairGCS/src/Manager.cpp	(revision 233)
+++ /trunk/tools/FlairGCS/src/Manager.cpp	(revision 234)
@@ -7,4 +7,5 @@
 #include "ConnectionLayout.h"
 #include "communication.h"
+#include "file_ui.h"
 #include <QDate>
 #include <QFileDialog>
@@ -17,5 +18,5 @@
 #include <QVBoxLayout>
 #include <QModelIndex>
-//#include <qmetatype.h>
+#include <QStatusBar>
 #include <qendian.h>
 #include <iostream>
@@ -36,7 +37,7 @@
   qRegisterMetaType<QModelIndex>("QModelIndex"); // pour le file ui??
   this->name = name;
-
+//fprintf(stderr,"Manager %x\n",thread());
   setWindowTitle(name);
-//statusBar()->showMessage(tr("Ready to serve"));
+
   // manager layout
   managerLayout = new QVBoxLayout;
@@ -79,5 +80,5 @@
   bool blocking = false;
   UDT::setsockopt(serv, 0, UDT_RCVSYN, &blocking, sizeof(bool));
-
+//UDT::setsockopt(serv, 0, UDT_CC, new CCCFactory<CUDPBlast>, sizeof(CCCFactory<CUDPBlast>));
   sockaddr_in my_addr;
   my_addr.sin_family = AF_INET;
@@ -96,16 +97,20 @@
   QTimer *timer = new QTimer(this);
   connect(timer, SIGNAL(timeout()), this, SLOT(acceptConnections()));
-  timer->start(20);
+  timer->start(500);
 }
 
 Manager::~Manager() {
-  emit killUdtSockets();
+  printf("%i\n",udtSockets.count());
+  for (int i = 0; i < udtSockets.count(); i++) {
+    udtSockets.at(i)->kill();
+    udtSockets.at(i)->thread()->wait();
+  }
 
   // delete main_layout;
   UDT::cleanup();
+  printf("ok\n");
 }
 
 void Manager::acceptConnections(void) {
-  static UDTSOCKET first_socket = 0;
   UDTSOCKET socket;
 
@@ -113,59 +118,37 @@
   int namelen = sizeof(their_addr);
 
-  if (UDT::INVALID_SOCK ==
-      (socket = UDT::accept(serv, (sockaddr *)&their_addr, &namelen))) {
+  if (UDT::INVALID_SOCK ==(socket = UDT::accept(serv, (sockaddr *)&their_addr, &namelen))) {
     if (UDT::getlasterror().getErrorCode() != 6002)
-      printf("accept: %s, code %i\n", UDT::getlasterror().getErrorMessage(),
-             UDT::getlasterror().getErrorCode());
+      printf("accept error: %s, code %i\n", UDT::getlasterror().getErrorMessage(),UDT::getlasterror().getErrorCode());
     return;
   } else {
-    printf("connected to %s:%i\n", inet_ntoa(their_addr.sin_addr),
-           their_addr.sin_port);
-
-    if (!first_socket) {
-      first_socket = socket;
-      return;
-    } else {
-      QThread *thread = new QThread(this);
-      UdtSocket *new_udt = new UdtSocket(first_socket, socket, name);
-      new_udt->moveToThread(thread);
-
-      newConnection(new_udt);
-
-      connect(this, SIGNAL(killUdtSockets()), thread, SLOT(quit()));
-      connect(this, SIGNAL(killUdtSockets()), new_udt, SLOT(kill()),
-              Qt::BlockingQueuedConnection);
-
-      connect(thread, SIGNAL(started()), new_udt, SLOT(handleConnections()));
-
-      thread->start();
-      first_socket = 0;
-    }
-  }
-}
-
-void Manager::newConnection(UdtSocket *socket) {
-
-  // no tabs to 2 tabs
-  if (connectionsLayout.count() == 1) {
-    tabBar->addTab(hiddenTabName);
-    currentTab = 0;
-    connectionsWidget.at(0)->show();
-  }
-
-  // layout utilisateur
-  ConnectionLayout *newLayout = new ConnectionLayout(socket, "interface");
+    QString name=QString("%1:%2").arg(inet_ntoa(their_addr.sin_addr)).arg(their_addr.sin_port);
+    printf("connected to %s\n",name.toLocal8Bit().constData());
+    
+    QThread *thread = new QThread(this);
+    UdtSocket *udtSocket = new UdtSocket(socket,name);
+    udtSocket->moveToThread(thread);
+    udtSockets.append(udtSocket);
+
+    connect(udtSocket, SIGNAL(newFileUI(UDTSOCKET)), this, SLOT(newFileUI(UDTSOCKET)));
+    connect(udtSocket, SIGNAL(newConnectionLayout(QString)), this, SLOT(newConnectionLayout(QString)),Qt::BlockingQueuedConnection);
+    connect(thread, SIGNAL(started()), udtSocket, SLOT(receiveData()));
+
+    thread->start();  
+  }
+}
+
+void Manager::newConnectionLayout(QString name) {
+  UdtSocket* udtSocket=(UdtSocket *)sender();
+  
+  ConnectionLayout *newLayout = new ConnectionLayout(udtSocket, name);
   connectionsLayout.append(newLayout);
-  connect(newLayout, SIGNAL(setRemoteName(QString)), this,
-          SLOT(tabName(QString)));
-  connect(newLayout, SIGNAL(computedRxRate(float)), this,
-          SLOT(printRxRates(float)));
-  connect(socket, SIGNAL(dataReady(char *, int)), newLayout,
-          SLOT(receive(char *, int)));
-  connect(newLayout, SIGNAL(destroyed(QObject *)), this,
-          SLOT(layoutDestroyed(QObject *)));
-  connect(socket, SIGNAL(destroyed()), newLayout, SLOT(deleteLater()));
-
-  // widget
+  connect(udtSocket, SIGNAL(UDTStats(QString)), newLayout, SIGNAL(UDTStats(QString)));//connection in 2 steps to get udtsocket as sender
+  connect(newLayout, SIGNAL(UDTStats(QString)), this, SLOT(printUDTStats(QString)));
+  connect(udtSocket, SIGNAL(dataReady(char *, int)), newLayout,SLOT(receive(char *, int)),Qt::BlockingQueuedConnection);
+  connect(newLayout, SIGNAL(destroyed(QObject *)), this, SLOT(layoutDestroyed(QObject *)));
+  connect(udtSocket, SIGNAL(destroyed()), newLayout, SLOT(deleteLater()));
+  
+   // widget
   QWidget *newWidget = new QWidget();
   connectionsWidget.append(newWidget);
@@ -173,19 +156,66 @@
   managerLayout->insertWidget(1, newWidget);
   newWidget->hide();
-
+  
+  //tab: avoid having only 1 tab (0, 2 or more)
   if (connectionsLayout.count() == 1) { // first connection
-    newWidget->show();
-  } else { // add a tab for the new connection
-    tabBar->addTab("unknown");
-  }
-}
-
-void Manager::printRxRates(float rxRate) {
+    connectionsWidget.at(0)->show();
+    hiddenTabName = name;
+  }
+  if (connectionsLayout.count() == 2) {
+    tabBar->addTab(hiddenTabName);
+    currentTab = 0;
+  }
+  if (connectionsLayout.count() > 1) {
+    tabBar->addTab(name);
+  }
+}
+
+void Manager::layoutDestroyed(QObject *obj) {
+  int index = connectionsLayout.indexOf((ConnectionLayout *)obj);
+
+  //tab: avoid having only 1 tab (0, 2 or more)
+  if (tabBar->count() > 1) {
+    tabBar->removeTab(index);
+  }
+
+  delete connectionsWidget.at(index);
+  connectionsWidget.removeAt(index);
+  connectionsLayout.removeOne((ConnectionLayout *)obj);
+
+  if (connectionsLayout.count() == 1) {
+    hiddenTabName = tabBar->tabText(0);
+    tabBar->removeTab(0);
+  }
+
+  if (connectionsLayout.count() == 0) {
+    status->showMessage("");
+  }
+}
+
+void Manager::newFileUI(UDTSOCKET socket) {
+  //remove udtsocket as it will be automatically destroyed
+  udtSockets.removeOne((UdtSocket *)sender());
+  
+  QThread *thread = new QThread(this);
+  file_ui* fileUi = new file_ui(socket,name);
+  fileUi->moveToThread(thread);
+  connect(thread, SIGNAL(started()), fileUi, SLOT(receive()));
+  connect(fileUi, SIGNAL(finished()), this, SLOT(deleteFileUI()));
+  thread->start();
+}
+
+void Manager::deleteFileUI(void) {
+  sender()->thread()->quit();
+  delete sender();
+}
+
+void Manager::printUDTStats(QString stats) {
   int index = connectionsLayout.indexOf((ConnectionLayout *)sender());
-
+  if(index==-1) return;
+  
   if (tabBar->count() == 0) {
-    status->showMessage(tr("rx rate %1 kB/s").arg(rxRate,0,'f',3));
+    status->showMessage(stats);
   } else if (index==tabBar->currentIndex()) {
-    status->showMessage(tr("%1 rx rate %2 kB/s").arg(tabBar->tabText(index)).arg(rxRate,0,'f',3));
+    status->showMessage(QString("%1: %2").arg(tabBar->tabText(index)).arg(stats));
   }
 }
@@ -200,33 +230,9 @@
     connectionsWidget.at(0)->show();
   }
-}
-
-void Manager::tabName(QString name) {
-  int index = connectionsLayout.indexOf((ConnectionLayout *)sender());
+  
   if (tabBar->count() == 0) {
-    hiddenTabName = name;
+    status->showMessage(connectionsLayout.at(0)->getUDTStats());
   } else {
-    tabBar->setTabText(index, name);
-  }
-}
-
-void Manager::layoutDestroyed(QObject *obj) {
-  int index = connectionsLayout.indexOf((ConnectionLayout *)obj);
-
-  if (tabBar->count() > 1) {
-    tabBar->removeTab(index);
-  }
-
-  delete connectionsWidget.at(index);
-  connectionsWidget.removeAt(index);
-  connectionsLayout.removeOne((ConnectionLayout *)obj);
-
-  if (connectionsLayout.count() == 1) {
-    hiddenTabName = tabBar->tabText(0);
-    tabBar->removeTab(0);
-  }
-
-  if (connectionsLayout.count() == 0) {
-    status->showMessage("");
+    status->showMessage(QString("%1: %2").arg(tabBar->tabText(index)).arg(connectionsLayout.at(index)->getUDTStats()));
   }
 }
@@ -240,9 +246,9 @@
       QFile *file;
       file = new QFile(dir_name + "/" +
-                       connectionsLayout.at(i)->getRemoteName() + ".xml");
+                       connectionsLayout.at(i)->getName() + ".xml");
       if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
         QMessageBox::warning(this, "Warning",
                              "Enable to load " +
-                                 connectionsLayout.at(i)->getRemoteName() +
+                                 connectionsLayout.at(i)->getName() +
                                  ".xml");
         continue;
@@ -256,5 +262,5 @@
         QMessageBox::critical(
             this, "Error",
-            "unable to read " + connectionsLayout.at(i)->getRemoteName() +
+            "unable to read " + connectionsLayout.at(i)->getName() +
                 ".xml" + " (" + errorMsg + " at " + QString::number(errorLine) +
                 "," + QString::number(errorColumn) + ")");
@@ -312,5 +318,5 @@
     connectionsLayout.at(i)->GetFullXml((QDomElement *)xml);
 
-    QFile fichier(dir_name + "/" + connectionsLayout.at(i)->getRemoteName() +
+    QFile fichier(dir_name + "/" + connectionsLayout.at(i)->getName() +
                   ".xml");
     QString write_doc = (xml->ownerDocument()).toString();
@@ -322,6 +328,5 @@
     }
     QTextStream stream(&fichier);
-    stream << write_doc; // On utilise l'opérateur << pour écrire write_doc dans
-                         // le document XML.
+    stream << write_doc;
     fichier.close();
 
Index: /trunk/tools/FlairGCS/src/Manager.h
===================================================================
--- /trunk/tools/FlairGCS/src/Manager.h	(revision 233)
+++ /trunk/tools/FlairGCS/src/Manager.h	(revision 234)
@@ -9,5 +9,4 @@
 #include <udt.h>
 #include <qdom.h>
-#include <QStatusBar>
 
 class UdtSocket;
@@ -17,4 +16,5 @@
 class QPushButton;
 class QGridLayout;
+class QStatusBar;
 
 class Manager : public QWidget {
@@ -30,4 +30,5 @@
   QList<ConnectionLayout *> connectionsLayout;
   QList<QWidget *> connectionsWidget;
+  QList<UdtSocket *> udtSockets;
   QTabBar *tabBar;
   QString name, hiddenTabName;
@@ -41,6 +42,4 @@
   QStatusBar *status;
 
-  void newConnection(UdtSocket *socket);
-
 private slots:
   void acceptConnections(void);
@@ -49,11 +48,10 @@
   void save(void);
   void reset(void);
+  void tabBarCurrentChanged(int index);
+  void printUDTStats(QString stats);
+  void newFileUI(UDTSOCKET socket);
+  void deleteFileUI(void);
+  void newConnectionLayout(QString name);
   void layoutDestroyed(QObject *obj);
-  void tabBarCurrentChanged(int index);
-  void tabName(QString name);
-  void printRxRates(float rxRate);
-
-signals:
-  void killUdtSockets(void);
 
 protected:
Index: /trunk/tools/FlairGCS/src/UdtSocket.cpp
===================================================================
--- /trunk/tools/FlairGCS/src/UdtSocket.cpp	(revision 233)
+++ /trunk/tools/FlairGCS/src/UdtSocket.cpp	(revision 234)
@@ -4,4 +4,5 @@
 // %flair:license}
 #include "UdtSocket.h"
+#include "ConnectionLayout.h"
 #include <stdio.h>
 #include <stdlib.h>
@@ -10,6 +11,9 @@
 #include <QDir>
 #include <QDate>
-#include "file_ui.h"
 #include "communication.h"
+#include <zlib.h>
+#include <assert.h>
+#include <QThread>
+#define COMPRESS_CHUNK 1024*100
 
 #ifndef WIN32
@@ -20,29 +24,39 @@
 #endif
 
+#define COMPUTE_UDT_STATS_TIMER 2000
+#define HEARTBEAT_TIMER 200
+
 using namespace std;
 
-UdtSocket::UdtSocket(UDTSOCKET file_socket, UDTSOCKET com_socket, QString name)
-    : QObject() {
-  this->file_socket = file_socket;
-  this->com_socket = com_socket;
-  this->name = name;
+UdtSocket::UdtSocket(UDTSOCKET socket,QString name): QObject() {
+  this->socket = socket;
+  this->name=name;
   stop = false;
-  file_dialog = new file_ui();
-
-  bool blocking = true;
-  UDT::setsockopt(file_socket, 0, UDT_RCVSYN, &blocking, sizeof(bool));
-
+  destroySocket=true;
+  socketType=unknown;
+  total_received=0;
+ 
+  bool blocking = false;
+  if (UDT::setsockopt(socket, 0, UDT_RCVSYN, &blocking, sizeof(bool)) != 0)
+    printf("UDT::setsockopt error (UDT_RCVSYN)\n");
+    
   heartbeat_timer = new QTimer(this);
   connect(heartbeat_timer, SIGNAL(timeout()), this, SLOT(heartbeat()));
-  heartbeat_timer->start(200);
+  heartbeat_timer->start(HEARTBEAT_TIMER);
+  
+  udtstats_timer = new QTimer(this);
+  connect(udtstats_timer, SIGNAL(timeout()), this, SLOT(getUTDStats()));
+  udtstats_timer->start(COMPUTE_UDT_STATS_TIMER);
 }
 
 UdtSocket::~UdtSocket() {
   heartbeat_timer->stop();
-
-  UDT::close(file_socket);
-  UDT::close(com_socket);
-
-  file_dialog->deleteLater();
+  udtstats_timer->stop();
+  if(destroySocket) UDT::close(socket);         
+}
+
+void UdtSocket::setName(QString name) {
+  printf("  %s is %s\n",this->name.toLocal8Bit().constData(),name.toLocal8Bit().constData());
+  this->name=name;
 }
 
@@ -52,180 +66,204 @@
 void UdtSocket::heartbeat(void) {
   char data = WATCHDOG_HEADER;
-  write(&data, 1);
+  quint64 sent=write(&data, 1,HEARTBEAT_TIMER,false);
+  if (sent != 1 && UDT::getlasterror().getErrorCode() == 2001) {
+    heartbeat_timer->stop();
+  }
+  
+}
+
+void UdtSocket::getUTDStats(void) {
+  float rxRate=((float)total_received/(COMPUTE_UDT_STATS_TIMER/1000))/1000;//in Ko/s
+  total_received=0;
+  
+  UDT::TRACEINFO perf;
+  if (UDT::ERROR == UDT::perfmon(socket, &perf))   {
+    printf("perfmon: %s\n",UDT::getlasterror().getErrorMessage());
+  }/* else {
+    printf("%s socket stats:\n",name.toLocal8Bit().constData());
+    printf("total number of sent packets, including retransmissions: %i\n",perf.pktSentTotal);
+    printf("total number of received packets: %i\n",perf.pktRecvTotal);
+    printf("total number of lost packets, measured in the sending side: %i\n",perf.pktSndLossTotal);
+    printf("total number of lost packets, measured in the receiving side: %i\n",perf.pktRcvLossTotal);
+    printf("total number of retransmitted packets, measured in the sending side: %i\n",perf.pktRetransTotal);
+    printf("total number of sent ACK packets: %i\n",perf.pktSentACKTotal);
+    printf("total number of received ACK packets: %i\n",perf.pktRecvACKTotal);
+    printf("total number of sent NAK packets: %i\n",perf.pktSentNAKTotal);
+    printf("total number of received NAK packets: %i\n",perf.pktRecvNAKTotal);
+    printf("round trip time: %fms\n",perf.msRTT);
+      
+  }*/
+  stats=QString("rx rate %1kB/s, round trip %2ms, lost packets %3").arg(rxRate,0,'f',3).arg(perf.msRTT,0,'f',3).arg(perf.pktSndLossTotal);
+  UDTStats(stats);
+  
+}
+
+QString UdtSocket::getUDTStats() {
+  return stats;
 }
 
 void UdtSocket::kill(void) {
-  printf("disconnected\n");
   stop = true;
   deleteLater();
 }
 
-void UdtSocket::handleConnections(void) {
+void UdtSocket::receiveData(void) {
+  int buf_size;
+  int opt_size;
+  UDT::getsockopt(socket, 0, UDT_RCVBUF, &buf_size, &opt_size);
+  char *buf = (char *)malloc(buf_size);
+  if (!buf) {
+    printf("error malloc UdtSocket::receiveData buffer\n");
+    return;
+  }
+  char *uncompressbuf=(char *)malloc(COMPRESS_CHUNK);
+  if (!uncompressbuf) {
+    printf("error malloc UdtSocket::receiveData uncompress buffer\n");
+    free(buf);
+    return;
+  }
+  //fprintf(stderr,"receiveData %x\n",thread());
+  
   while (!stop) {
+    QCoreApplication::processEvents();
+    
+    //we need to use epoll?
+    //tests are showing that UDT::recvmsg is waiting for the entire timeout before returning
+    //note that in flair::core the behaviour of UDT::recvmsg timeout is as expected
+    //is it a difference between client and server??
+    //tests also show that we need to recreate the eid every time, otherwise wait returns immediately
     int eid = UDT::epoll_create();
     if (eid < 0) {
-      printf("epoll_create error: %s\n", UDT::getlasterror().getErrorMessage());
-    }
-
-    if (UDT::epoll_add_usock(eid, file_socket) < 0) {
+      printf("%s: epoll_create error (%s)\n",name.toLocal8Bit().constData(),UDT::getlasterror().getErrorMessage());
+    }
+
+    if (UDT::epoll_add_usock(eid, socket) < 0) {
       if (UDT::getlasterror().getErrorCode() == 5004) {
-        printf("epoll_add_usock error\n");
-        break;
+        printf("disconnected from %s\n",name.toLocal8Bit().constData());
+        heartbeat_timer->stop();
+        deleteLater();
+        stop=true;;
       } else {
-        printf("epoll_add_usock error: %s\n",
-               UDT::getlasterror().getErrorMessage());
+        printf("%s: epoll_add_usock error (%s)\n",name.toLocal8Bit().constData(),UDT::getlasterror().getErrorMessage());
       }
     }
-    if (UDT::epoll_add_usock(eid, com_socket) < 0) {
-      if (UDT::getlasterror().getErrorCode() == 5004) {
-        printf("epoll_add_usock error\n");
-        break;
-      } else {
-        printf("epoll_add_usock error: %s\n",
-               UDT::getlasterror().getErrorMessage());
-      }
-    }
-
-    set<UDTSOCKET> readfds;
-
-    int rv = UDT::epoll_wait(eid, &readfds, NULL, 10);
-
+  
+    int num = 1;
+    UDTSOCKET readfds;
+    int rv = UDT::epoll_wait2(eid, &readfds, &num,NULL, NULL,100);
+  
     if (rv == -1) {
       if (UDT::getlasterror().getErrorCode() != 6003)
         printf("prob %i\n", UDT::getlasterror().getErrorCode());
-      // printf("wait\n");
-    } else if (rv == 0) {
-      printf("timeout\n"); // a timeout occured
+    } else if(readfds==socket && num==1 && rv==1) {
+       
+      int size=UDT::recvmsg(socket, buf, buf_size);
+      if (size > 0) {
+        total_received+=size;
+        
+        switch ((unsigned char)buf[0]) {
+          case ZLIB_HEADER: {
+            ssize_t out_size;
+            uncompressBuffer(buf, size, uncompressbuf, &out_size);
+            if((unsigned char)uncompressbuf[0]==XML_HEADER && socketType==unknown) {
+              socketType=gui;
+              QString remoteName=ConnectionLayout::getDocRootName(uncompressbuf, out_size);
+              setName(remoteName);
+              emit newConnectionLayout(remoteName);//connection is Qt::BlockingQueuedConnection
+            }
+            emit dataReady(uncompressbuf, out_size);//connection is Qt::BlockingQueuedConnection, as we have only one buffer
+            break;
+          }
+          case START_SENDING_FILES: {
+            if((unsigned char)uncompressbuf[0]==XML_HEADER && socketType==unknown) {
+              socketType=log;
+            }
+            setName("log files");
+            heartbeat_timer->stop();
+            emit newFileUI(socket);
+            deleteLater();
+            stop=true;
+            destroySocket=false;
+            break;
+          }
+          case XML_HEADER:
+            if(socketType==unknown) {
+              socketType=gui;
+              QString remoteName=ConnectionLayout::getDocRootName(buf, size );
+              setName(remoteName);
+              emit newConnectionLayout(remoteName);
+            }
+          case DATAS_BIG_ENDIAN:
+          case DATAS_LITTLE_ENDIAN:
+            emit dataReady(buf, size );
+            break;
+        }
+      } else {
+        //if(UDT::getlasterror().getErrorCode()!=6002) 
+        printf("udt socket:%s\n",UDT::getlasterror().getErrorMessage());
+        //UDT::close(socket);//si deconnecté
+        //free(buf);
+        //break;
+      }
     } else {
-      /*
-      if(UDT::getlasterror().getErrorCode()==2001) {
-          UDT::epoll_release(eid);
-      }*/
-      for (set<UDTSOCKET>::iterator i = readfds.begin(); i != readfds.end();
-           i++) {
-        // printf("a\n");
-        if (*i == file_socket)
-          receiveFile();
-        if (*i == com_socket)
-          receiveData();
-      }
-    }
-
-    UDT::epoll_remove_usock(eid, file_socket);
-    UDT::epoll_remove_usock(eid, com_socket);
+      printf("udt socket:%s\n",UDT::getlasterror().getErrorMessage());
+    }
+    UDT::epoll_remove_usock(eid, socket);
     UDT::epoll_release(eid);
-
-    QCoreApplication::processEvents();
-  }
-  kill();
-}
-
-void UdtSocket::receiveFile(void) {
-  char *recv_buf;
-  int bytesRead;
-  static bool flag_new_seq = true;
-  static QString folder_name;
-
-  // receive file info
-  recv_buf = (char *)malloc(1024);
-  bytesRead = UDT::recvmsg(file_socket, recv_buf, 1024);
-
-  if (bytesRead <= 0) {
-    free(recv_buf);
-    return;
-  }
-
-  int size;
-  memcpy(&size, &recv_buf[1], sizeof(int));
-  if (recv_buf[0] == FILE_INFO_BIG_ENDIAN)
-    size = qFromBigEndian(size);
-
-  // printf("file_ui recu %i %x\n",bytesRead,recv_buf[0]);
-  if ((recv_buf[0] == FILE_INFO_LITTLE_ENDIAN ||
-       recv_buf[0] == FILE_INFO_BIG_ENDIAN) &&
-      size > 0) {
-    if (flag_new_seq == true) {
-      // create directory for storage
-      QDateTime dateTime = QDateTime::currentDateTime();
-      folder_name = dateTime.toString("yyyyMMdd_hhmm") + "_" + name;
-      if (QDir().exists(folder_name) == true) {
-        folder_name = dateTime.toString("yyyyMMdd_hhmm_ss") + "_" + name;
-      }
-      QDir().mkdir(folder_name);
-
-      flag_new_seq = false;
-      file_dialog->log("Creating directory " + folder_name);
-    }
-
-    QString file_name =
-        QString::fromAscii((const char *)&recv_buf[5], bytesRead - 5);
-    QString file_path = folder_name + "/" + file_name;
-    file_dialog->log(
-        QString("receiving %1 (%2 bytes)").arg(file_name).arg(size));
-    QFile fichier(file_path);
-
-    if (!fichier.open(QIODevice::WriteOnly)) {
-      file_dialog->log("      could not write to file!");
-    } else {
-      // receive file
-      recv_buf = (char *)realloc((void *)recv_buf, size);
-      bytesRead = UDT::recvmsg(file_socket, recv_buf, size);
-      if (bytesRead != size) {
-        file_dialog->log(QString("      error receiving file! (%1/%2)")
-                             .arg(bytesRead)
-                             .arg(size));
-        free(recv_buf);
-        return;
-      } else {
-        file_dialog->log("      ok");
-      }
-
-      QDataStream stream(&fichier);
-      stream.writeRawData(recv_buf, size);
-      fichier.close();
-
-      file_dialog->addFile(file_path);
-    }
-
-    free(recv_buf);
-  } else if (recv_buf[0] == END) {
-    file_dialog->endOfFiles();
-    flag_new_seq = true;
-    //end ack
-    UDT::sendmsg(file_socket,&recv_buf[0],1);
-  }
-}
-
-void UdtSocket::receiveData(void) {
-  while (1) {
-    int buf_size;
-    int opt_size;
-    UDT::getsockopt(com_socket, 0, UDT_RCVBUF, &buf_size, &opt_size);
-
-    char *buf = (char *)malloc(buf_size);
-    int size;
-    size = UDT::recvmsg(com_socket, buf, buf_size);
-    buf = (char *)realloc(buf, size + 1);
-
-    if (size > 0) {
-      buf[size] = 0;
-      emit dataReady(buf, size + 1);
-    } else {
-      // if(UDT::getlasterror().getErrorCode()!=6002) printf("udt socket:
-      // %s\n",UDT::getlasterror().getErrorMessage());
-      free(buf);
-      break;
-    }
-  }
-}
-
-void UdtSocket::write(const char *buf, qint64 size) {
-  // printf("write\n%s\n",buf);
-  qint64 sent = UDT::sendmsg(com_socket, buf, size, -1, true);
+  }
+  free(uncompressbuf);
+  free(buf);
+  thread()->quit();
+}
+
+qint64 UdtSocket::write(const char *buf, qint64 size,int ttl,bool inOrder) {
+  qint64 sent = UDT::sendmsg(socket, buf, size, ttl, inOrder);
   if (sent != size) {
-    printf("erreur envoi: %s\n", UDT::getlasterror().getErrorMessage());
+    printf("%s, error writting to udt (%s)\n",name.toLocal8Bit().constData(), UDT::getlasterror().getErrorMessage());
     if (UDT::getlasterror().getErrorCode() == 2001) {
       stop = true;
-    }
-  }
-}
+      heartbeat_timer->stop();
+      deleteLater();
+    }
+  }
+  return sent;
+}
+
+int UdtSocket::uncompressBuffer(char *in, ssize_t in_size, char *out,
+                                       ssize_t *out_size) {
+  int ret;
+  unsigned have;
+  z_stream strm;
+
+  // allocate inflate state
+  strm.zalloc = Z_NULL;
+  strm.zfree = Z_NULL;
+  strm.opaque = Z_NULL;
+  strm.avail_in = 0;
+  strm.next_in = Z_NULL;
+  ret = inflateInit(&strm);
+  if (ret != Z_OK)
+    return ret;
+
+  strm.avail_in = in_size;
+  strm.next_in = (unsigned char *)in;
+  strm.avail_out = COMPRESS_CHUNK;
+  strm.next_out = (unsigned char *)out;
+
+  ret = inflate(&strm, Z_NO_FLUSH);
+  assert(ret != Z_STREAM_ERROR); // state not clobbered
+  switch (ret) {
+  case Z_NEED_DICT:
+    ret = Z_DATA_ERROR; // and fall through
+  case Z_DATA_ERROR:
+  case Z_MEM_ERROR:
+    (void)inflateEnd(&strm);
+    return ret;
+  }
+  have = COMPRESS_CHUNK - strm.avail_out;
+  *out_size = have;
+
+  // clean up and return
+  (void)inflateEnd(&strm);
+  return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
+}
Index: /trunk/tools/FlairGCS/src/UdtSocket.h
===================================================================
--- /trunk/tools/FlairGCS/src/UdtSocket.h	(revision 233)
+++ /trunk/tools/FlairGCS/src/UdtSocket.h	(revision 234)
@@ -16,25 +16,34 @@
 
 public:
-  UdtSocket(UDTSOCKET file_socket, UDTSOCKET com_socket, QString name);
+  UdtSocket(UDTSOCKET socket,QString name);
   ~UdtSocket();
+  void setName(QString name);
+  QString getUDTStats();
 
 private:
-  UDTSOCKET file_socket, com_socket;
-  file_ui *file_dialog;
-  bool stop;
+  UDTSOCKET socket;
+  bool stop,destroySocket;
+  QTimer *heartbeat_timer,*udtstats_timer;
   QString name;
-  QTimer *heartbeat_timer;
-  void receiveData(void);
-  void receiveFile(void);
+  static int uncompressBuffer(char *in, ssize_t in_size, char *out,ssize_t *out_size);
+  enum SocketType { unknown, gui, log };
+  SocketType socketType;
+  unsigned int total_received;
+  QString stats;
 
 signals:
   void dataReady(char *, int size);
+  void newFileUI(UDTSOCKET socket);
+  void newConnectionLayout(QString name);
+  void UDTStats(QString stats);
 
 public slots:
-  void handleConnections(void);
+  void receiveData(void);
   void kill(void);
-  void write(const char *buf, qint64 size);
+  qint64 write(const char *buf, qint64 size,int ttl=-1,bool inOrder=true);
+  
 private slots:
   void heartbeat(void);
+  void getUTDStats(void);
 };
 
Index: /trunk/tools/FlairGCS/src/file_ui.cpp
===================================================================
--- /trunk/tools/FlairGCS/src/file_ui.cpp	(revision 233)
+++ /trunk/tools/FlairGCS/src/file_ui.cpp	(revision 234)
@@ -4,6 +4,7 @@
 // %flair:license}
 #include "file_ui.h"
+#include "communication.h"
+
 #include <stdio.h>
-
 #include <cstring>
 #include <cstdlib>
@@ -22,16 +23,27 @@
 #include <QStringList>
 #include <QFormLayout>
-
-#ifndef WIN32
-#include <arpa/inet.h>
-#else
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#endif
-
+#include <QThread>
+
+#include <unistd.h>
 using namespace std;
 
-file_ui::file_ui() {
+file_ui::file_ui(UDTSOCKET socket,QString name): QObject() {
+  this->socket=socket;
+  this->name=name;
+  
+  bool blocking = true;
+  if (UDT::setsockopt(socket, 0, UDT_SNDSYN, &blocking, sizeof(bool))!= 0) {
+    printf("UDT::setsockopt error (UDT_SNDSYN) %s\n",UDT::getlasterror().getErrorMessage());
+  }
+    
+  linger _linger;
+  _linger.l_onoff=1;
+  _linger.l_linger=180;
+  
+  if (UDT::setsockopt(socket, 0, UDT_LINGER, &_linger, sizeof(struct linger)) != 0)
+    printf("UDT::setsockopt error (UDT_LINGER) %s\n",UDT::getlasterror().getErrorMessage());
+    
   dialog = new QDialog();
+//fprintf(stderr,"creator file ui %x\n",thread());
   dialog->setWindowTitle("log files");
   QGridLayout *main_layout = new QGridLayout(dialog);
@@ -42,5 +54,4 @@
   input_text->setText("add your log comment here");
   input_cleared = false;
-
   ok_button->setEnabled(false);
 
@@ -56,19 +67,90 @@
   main_layout->addWidget(ok_button, 3, 0);
 
-  connect(ok_button, SIGNAL(clicked()), this, SLOT(save()),
-          Qt::QueuedConnection);
-  connect(this, SIGNAL(showDialog()), dialog, SLOT(show()),
-          Qt::QueuedConnection);
-  connect(this, SIGNAL(appendToLog(QString)), log_text, SLOT(append(QString)),
-          Qt::QueuedConnection);
-  connect(input_text, SIGNAL(cursorPositionChanged()), this,
-          SLOT(clearInputText()), Qt::QueuedConnection);
+  //connect for multithreaded stuffs
+  connect(ok_button, SIGNAL(clicked()), this, SLOT(save()),Qt::QueuedConnection);
+  connect(input_text, SIGNAL(cursorPositionChanged()), this,SLOT(clearInputText()),Qt::DirectConnection);
+  connect(this, SIGNAL(appendToLog(QString)), log_text, SLOT(append(QString)));
 
   file_names = new QStringList();
-}
-
-file_ui::~file_ui() { delete dialog; }
-
-void file_ui::log(QString text) { appendToLog(text); }
+  
+  dialog->show();
+}
+
+file_ui::~file_ui() { 
+  delete dialog;
+}
+
+void file_ui::receive(void) {
+  char *recv_buf;
+  int bytesRead;
+  bool flag_new_seq = true;
+  QString folder_name;
+//fprintf(stderr,"file_ui thread %x\n",thread());
+  while(1) {
+    // receive file info
+    recv_buf = (char *)malloc(1024);
+    bytesRead = UDT::recvmsg(socket, recv_buf, 1024);
+    if (bytesRead <= 0) {
+      free(recv_buf);
+      break;
+    }
+
+    int size;
+    memcpy(&size, &recv_buf[1], sizeof(int));
+    if (recv_buf[0] == FILE_INFO_BIG_ENDIAN)
+      size = qFromBigEndian(size);
+
+    // printf("file_ui recu %i %x\n",bytesRead,recv_buf[0]);
+    if ((recv_buf[0]==FILE_INFO_LITTLE_ENDIAN || recv_buf[0]==FILE_INFO_BIG_ENDIAN) && size>0) {
+      if (flag_new_seq == true) {
+        // create directory for storage
+        QDateTime dateTime = QDateTime::currentDateTime();
+        folder_name = dateTime.toString("yyyyMMdd_hhmm") + "_" + name;
+        if (QDir().exists(folder_name) == true) {
+          folder_name = dateTime.toString("yyyyMMdd_hhmm_ss") + "_" + name;
+        }
+        QDir().mkdir(folder_name);
+
+        flag_new_seq = false;
+        appendToLog("Creating directory " + folder_name);
+      }
+
+      QString file_name=QString::fromAscii((const char *)&recv_buf[5], bytesRead - 5);
+      QString file_path=folder_name+"/"+file_name;
+      appendToLog(QString("receiving %1 (%2 bytes)").arg(file_name).arg(size));
+      QFile fichier(file_path);
+
+      if (!fichier.open(QIODevice::WriteOnly)) {
+        appendToLog("      could not write to file!");
+      } else {
+        // receive file
+        recv_buf = (char *)realloc((void *)recv_buf, size);
+        bytesRead = UDT::recvmsg(socket, recv_buf, size);
+        if (bytesRead != size) {
+          appendToLog(QString("      error receiving file! (%1/%2)").arg(bytesRead).arg(size));
+          free(recv_buf);
+          break;
+        } else {
+          appendToLog("      ok");
+        }
+
+        QDataStream stream(&fichier);
+        stream.writeRawData(recv_buf, size);
+        fichier.close();
+
+        addFile(file_path);
+      }
+
+      free(recv_buf);
+    } else if (recv_buf[0] == END_SENDING_FILES) {
+      //end ack
+      UDT::sendmsg(socket,&recv_buf[0],1);
+      endOfFiles();
+      UDT::close(socket);
+      printf("disconnected from log files\n");
+      break;
+    }
+  }
+}
 
 void file_ui::addFile(QString file_path) {
@@ -86,9 +168,4 @@
     dbt2csv(file_path.replace(QString(".txt"), QString(".dbt")));
   }
-
-  if (file_names->size() == 1) {
-    input_cleared = false;
-    showDialog();
-  }
 }
 
@@ -101,6 +178,5 @@
     if (info.size() > max_file_size) {
       max_file_size = info.size();
-      csv_combo->setCurrentIndex(i +
-                                 1); // first item of combobox is already taken
+      csv_combo->setCurrentIndex(i+1); // first item of combobox is already taken
     }
   }
@@ -112,6 +188,5 @@
   QStringList data_type;
 
-  QString filename =
-      file_path.section('/', -1); // remove path for displaying on logs
+  QString filename =file_path.section('/', -1); // remove path for displaying on logs
   appendToLog(QString("converting %1 to csv").arg(filename));
 
@@ -145,7 +220,5 @@
       break;
     QString txt_line = txt_in.readLine();
-    data_type.append(txt_line.section(
-        "(",
-        -1)); // on part de la fin pour trouver la premiere parenthese ouvrante
+    data_type.append(txt_line.section("(",-1)); // on part de la fin pour trouver la premiere parenthese ouvrante
     // printf("type %s\n",txt_line.section("(",-1).toLocal8Bit().constData());
   }
@@ -241,13 +314,4 @@
   }
 
-  log_text->clear();
-  input_cleared = true; // avoid clearing it with setText
-  input_text->setText("add your log comment here");
-  file_names->clear();
-  csv_combo->clear();
-  csv_combo->addItem(QString("(no base time)"));
-
-  dialog->setVisible(false);
-  ok_button->setEnabled(false);
   emit finished();
 }
Index: /trunk/tools/FlairGCS/src/file_ui.h
===================================================================
--- /trunk/tools/FlairGCS/src/file_ui.h	(revision 233)
+++ /trunk/tools/FlairGCS/src/file_ui.h	(revision 234)
@@ -7,4 +7,5 @@
 
 #include <QObject>
+#include <udt.h>
 
 class QStringList;
@@ -19,5 +20,5 @@
 
 public:
-  file_ui();
+  file_ui(UDTSOCKET socket,QString name);
   ~file_ui();
   void log(QString text);
@@ -36,7 +37,11 @@
   void dbt2csv(QString file_path);
   bool is_greater(qint64 ref_us, qint64 csv_us, int ref_ns, int csv_ns);
-  void closeEvent(QCloseEvent *e);
   bool input_cleared;
+  UDTSOCKET socket;
+  QString name;
 
+public slots:
+  void receive(void);
+  
 private slots:
   void save(void);
@@ -44,7 +49,6 @@
 
 signals:
-  void showDialog(void);
+  void finished(void);
   void appendToLog(QString);
-  void finished();
 };
 
Index: /trunk/tools/FlairGCS/src/main.cpp
===================================================================
--- /trunk/tools/FlairGCS/src/main.cpp	(revision 233)
+++ /trunk/tools/FlairGCS/src/main.cpp	(revision 234)
@@ -6,4 +6,5 @@
 #include <QCleanlooksStyle>
 #include <QLocale>
+#include <QTextCursor>
 #include <qmetatype.h>
 #include <tclap/CmdLine.h>
@@ -74,4 +75,6 @@
 
   qRegisterMetaType<const char *>("const char*");
+  qRegisterMetaType<UDTSOCKET>("UDTSOCKET");
+  qRegisterMetaType<QTextCursor>("QTextCursor");
   QLocale::setDefault(QLocale::C);
   QApplication app(argc, argv);
Index: /trunk/tools/VrpnBridge/src/main.cpp
===================================================================
--- /trunk/tools/VrpnBridge/src/main.cpp	(revision 233)
+++ /trunk/tools/VrpnBridge/src/main.cpp	(revision 234)
@@ -58,5 +58,5 @@
 
   while (1) {
-    usleep(10000);
+    usleep(5000);
     server_connection->mainloop();
     client_connection->mainloop();
