Index: trunk/FACT++/scripts/CheckUnderflow.js
===================================================================
--- trunk/FACT++/scripts/CheckUnderflow.js	(revision 16570)
+++ trunk/FACT++/scripts/CheckUnderflow.js	(revision 16571)
@@ -84,16 +84,20 @@
     dim.send("FAD_CONTROL/SET_FILE_FORMAT", 0);
 
-    // This needs a better solution! The problem is that the
-    // event builder might still be writing a file (WritingData),
-    // but even if the file is closed (CLOSE_OPEN_FILES) the
-    // thread sending data (EVENT_DATA) might still be processing
-    // events. Thus there is no real guarantee that we do not receive
-    // data of the previous run after we have started a new one.
-    if (dim.state("FAD_CONTROL").name=="RunInProgress")
+    var sub_startrun = new Subscription("FAD_CONTROL/START_RUN");
+    var sruns = sub_startrun.get(5000);
+
+    if (dim.state("FAD_CONTROL").name=="RunInProgress" || sruns.obj['run']!=-1)
     {
         dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
         dim.wait("FAD_CONTROL", "Connected", 3000);
-    }
-    v8.sleep(1000); // Let 'timeout' in SendRawData pass
+
+        console.out("Waiting for open files to be closed...");
+        v8.timeout(60000, function() { if (sub_startrun.get().obj['run']==-1) return true; });
+
+        // Although the file should be closed now, the processing might still be on-going
+        // and delayed events might be received. The only fix for that issue is to
+        // add the run number to the data we are waiting for
+        v8.sleep(10000);
+    }
 
     console.out("Starting drs-gain... waiting for new event");
@@ -101,6 +105,4 @@
     var sub_incomplete = new Subscription("FAD_CONTROL/INCOMPLETE");
     var sub_connections = new Subscription("FAD_CONTROL/CONNECTIONS");
-    var sub_startrun = new Subscription("FAD_CONTROL/START_RUN");
-    sub_startrun.get(5000);
     sub_connections.get(5000);
     sub_startrun.get(5000);
@@ -118,5 +120,5 @@
                 if (dim.state("MCP").name=="TakingData" && service_event.get(0, false).counter>event_counter)
                 {
-                    dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
+                    //dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
                     dim.send("MCP/STOP");
                     return;
