Index: /trunk/FACT++/scripts/Main.js
===================================================================
--- /trunk/FACT++/scripts/Main.js	(revision 16048)
+++ /trunk/FACT++/scripts/Main.js	(revision 16049)
@@ -24,24 +24,4 @@
 //this is just the class implementation of 'Observation'
 include('scripts/Observation_class.js');
-
-/*
-// this file just contains the definition of
-// the variable observations, which builds our nightly schedule, hence the filename
-include('scripts/schedule.js');
-
-// make Observation objects from user input and check if 'date' is increasing.
-for (var i=0; i<observations.length; i++)
-{
-    observations[i] = new Observation(observations[i]);
-
-    // check if the start date given by the user is increasing.
-    if (i>0 && observations[i].start <= observations[i-1].start)
-    {
-        throw new Error("Start time '"+ observations[i].start.toUTCString()+
-                        "' in row "+i+" exceeds start time in row "+(i-1));
-    }
-}
-*/
-
 include('scripts/getSchedule.js');
 
@@ -106,241 +86,7 @@
 */
 
-// ----------------------------------------------------------------
-
-// ================================================================
-//  Code related to monitoring the fad system
-// ================================================================
-
-var sub_incomplete = new Subscription("FAD_CONTROL/INCOMPLETE");
-
-var incomplete = 0;
-
-sub_incomplete.onchange = function(evt)
-{
-    if (!evt.data)
-        return;
-
-    var inc = evt.obj['incomplete'];
-    if (!inc || inc>0xffffffffff)
-        return;
-
-    if (incomplete>0)
-        return;
-
-    if (dim.state("MCP").name!="TakingData")
-        return;
-
-    incomplete = inc;
-
-    console.out("", "Incomplete event detected, sending MCP/STOP");
-    dim.send("MCP/STOP");
-}
-
-
-// ================================================================
-//  Code related to taking data
-// ================================================================
-
-var sub_connections = new Subscription("FAD_CONTROL/CONNECTIONS");
-
-var startrun = new Subscription("FAD_CONTROL/START_RUN");
-startrun.get(5000);
-
-/**
- * reconnect to problematic FADs
- *
- * Dis- and Reconnects to FADs, found to be problematic by call-back function
- * onchange() to have a different CONNECTION value than 66 or 67. 
- * 
- * @returns
- *      a boolean is returned. 
- *      reconnect returns true if:
- *          * nothing needed to be reset --> no problems found by onchange()
- *          * the reconnection went fine.
- *      
- *      reconnect *never returns false* so far.
- *
- * @example
- *      if (!sub_connections.reconnect())
- *          exit();
- */
-function reconnect(list, txt)
-{ /*
-    var reset = [ ];
-
-    for (var i=0; i<list.length; i++)
-        {
-            console.out("  FAD %2d".$(list[i])+" lost during "+txt);
-            reset.push(parseInt(list[i]/10));
-        }
-
-    reset = reset.filter(function(elem,pos){return reset.indexOf(elem)==pos;});
-
-    console.out("");
-    console.out("  FADs belong to crate(s): "+reset);
-    console.out("");
-*/
-    console.out("");
-    console.out("Trying automatic reconnect ["+txt+"]...");
-
-    for (var i=0; i<list.length; i++)
-    {
-        console.out("   ...disconnect "+list[i]);
-        dim.send("FAD_CONTROL/DISCONNECT", list[i]);
-    }
-
-    console.out("   ...waiting for 3s");
-    v8.sleep(3000);
-
-    for (var i=0; i<list.length; i++)
-    {
-        console.out("   ...reconnect "+list[i]);
-        dim.send("FAD_CONTROL/CONNECT", list[i]);
-    }
-
-    console.out("   ...waiting for 1s");
-    v8.sleep(1000);
-    console.out("   ...checking connection");
-    dim.wait("FAD_CONTROL", "Connected", 3000);
-    console.out("");
-}
-
-function takeRun(type, count, time)
-{
-    if (!count)
-        count = -1;
-    if (!time)
-        time = -1;
-
-    var nextrun = startrun.get().obj['next'];
-    console.out("  Take run %3d".$(nextrun)+": N="+count+" T="+time+"s ["+type+"]");
-
-    // FIXME: Replace by callback?
-    //
-    // DN: I believe instead of waiting for 'TakingData' one could split this
-    // up into two checks with an extra condition:
-    //  if type == 'data':
-    //      wait until ThresholdCalibration starts:
-    //          --> this time should be pretty identical for each run
-    //      if this takes longer than say 3s:
-    //          there might be a problem with one/more FADs
-    //    
-    //      wait until "TakingData":
-    //          --> this seems to take even some minutes sometimes... 
-    //              (might be optimized rather soon, but still in the moment...)
-    //      if this takes way too long: 
-    //          there might be something broken, 
-    //          so maybe a very high time limit is ok here.
-    //          I think there is not much that can go wrong, 
-    //          when the Thr-Calib has already started. Still it might be nice 
-    //          If in the future RateControl is written so to find out that 
-    //          in case the threshold finding algorithm does 
-    //          *not converge as usual*
-    //          it can complain, and in this way give a hint, that the weather
-    //          might be a little bit too bad.
-    //  else:
-    //      wait until "TakingData":
-    //          --> in a non-data run this time should be pretty short again
-    //      if this takes longer than say 3s:
-    //          there might be a problem with one/more FADs
-    //  
-
-    // Use this if you use the rate control to calibrate by rates
-    //if (!dim.wait("MCP", "TakingData", -300000) )
-    //{
-    //    throw new Error("MCP took longer than 5 minutes to start TakingData"+
-    //                    "maybe this idicates a problem with one of the FADs?");
-    //}
-
-    // Here we could check and handle fad losses
-
-    incomplete = 0;
-
-    for (var n=0; n<3; n++)
-    {
-        dim.send("MCP/START", time?time:-1, count?count:-1, type);
-        try
-        {
-            dim.wait("MCP", "TakingData", 15000);
-            break;
-        }
-        catch (e)
-        {
-            console.out("");
-            console.out("MCP:         "+dim.state("MCP").name);
-            console.out("FAD_CONTROL: "+dim.state("FAD_CONTROL").name);
-            console.out("FTM_CONTROL: "+dim.state("FTM_CONTROL").name);
-            console.out("");
-
-            if (dim.state("MCP").name!="Configuring3" ||
-                dim.state("FAD_CONTROL").name!="Configuring2")
-                throw e;
-
-            console.out("");
-            console.out("Waiting for fadctrl to get configured timed out... checking for in-run FAD loss.");
-
-            var con  = sub_connections.get();
-            var stat = con.obj['status'];
-
-            console.out("Sending MCP/RESET");
-            dim.send("MCP/RESET");
-
-            dim.wait("FTM_CONTROL", "Idle",      3000);
-            dim.wait("FAD_CONTROL", "Connected", 3000);
-            dim.wait("MCP",         "Idle",      3000);
-
-            var list = [];
-            for (var i=0; i<40; i++)
-                if (stat[i]!=0x43)
-                    list.push(i);
-
-            reconnect(list, "configuration");
-
-            if (n==2)
-                throw e;
-
-            dim.wait("MCP", "Idle", 3000);
-        }
-    }
-
-    dim.wait("MCP", "Idle", time>0 ? time*1250 : undefined); // run time plus 25%
-
-    if (incomplete)
-    {
-        console.out("");
-        console.out("MCP:         "+dim.state("MCP").name);
-        console.out("FAD_CONTROL: "+dim.state("FAD_CONTROL").name);
-        console.out("FTM_CONTROL: "+dim.state("FTM_CONTROL").name);
-
-        dim.wait("MCP",         "Idle", 3000);
-        dim.wait("FTM_CONTROL", "Idle", 3000);
-
-        // Necessary to allow the disconnect, reconnect
-        dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
-        dim.wait("FAD_CONTROL", "Connected", 3000);
-
-        var list = [];
-        for (var i=0; i<40; i++)
-            if (incomplete&(1<<i))
-                list.push(i);
-
-        reconnect(list, "data taking");
-
-        return false;
-
-        //throw new Error("In-run FAD loss detected.");
-    }
-
-    //console.out("  Take run: end");
-
-    // DN: currently reconnect() never returns false 
-    //     .. but it can fail of course.
-    //if (!sub_connections.reconnect())
-    //    exit();
-
-    return true;//sub_connections.reconnect();
-}
-
-// ----------------------------------------------------------------
+// ================================================================
+//  Code to perform the DRS calib sequence
+// ================================================================
 
 function doDrsCalibration(where)
@@ -454,4 +200,9 @@
 
     var delta = evt.obj['DeltaBias'];
+
+    // It seems this can happen when the feedback was newly started. Why?
+    // What is the correct solution?
+    if (!delta)
+        return;
 
     var avg = 0;
@@ -606,5 +357,5 @@
     //v8.timeout(5*60000, func, this);
     while ((this.cnt==undefined || this.get().counter<=this.cnt+10) && (!this.voltageStep || this.voltageStep>0.02))
-        v8.sleep();
+        v8.sleep(100);
 
     console.out("  Feedback wait: end [dV=%.3f, cnt=%d, %.2fs]".$(this.voltageStep, this.get().counter, (new Date()-now)/1000));
@@ -781,4 +532,17 @@
 include('scripts/Startup.js');
 
+// ================================================================
+//  Code related to monitoring the fad system
+// ================================================================
+
+// This code is here, because scripts/Startup.js needs the
+// same subscriptions... to be revised.
+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);
+
+include('scripts/takeRun.js');
+
 // ----------------------------------------------------------------
 // Check that everything we need is availabel to receive commands
