Index: /trunk/FACT++/src/makeschedule.cc
===================================================================
--- /trunk/FACT++/src/makeschedule.cc	(revision 18435)
+++ /trunk/FACT++/src/makeschedule.cc	(revision 18436)
@@ -1,5 +1,4 @@
 #include "externals/Prediction.h"
 
-//#include <unordered_map>
 #include <boost/algorithm/string/join.hpp>
 
@@ -10,42 +9,8 @@
 #include "Configuration.h"
 
-/*
-#include <TROOT.h>
-#include <TH1.h>
-#include <TGraph.h>
-#include <TCanvas.h>
-#include <TLegend.h>
-*/
-
 using namespace std;
 using namespace Nova;
 
 // -----------------------------------------------------------------------
-
-/*
-void CheckForGap(TCanvas &c, TGraph &g, double axis)
-{
-    if (g.GetN()==0 || axis-g.GetX()[g.GetN()-1]<450)
-        return;
-
-    c.cd();
-    ((TGraph*)g.DrawClone("C"))->SetBit(kCanDelete);
-    while (g.GetN())
-        g.RemovePoint(0);
-}
-
-void DrawClone(TCanvas &c, TGraph &g)
-{
-    if (g.GetN()==0)
-        return;
-
-    c.cd();
-    ((TGraph*)g.DrawClone("C"))->SetBit(kCanDelete);
-}
-*/
-
-// ========================================================================
-// ========================================================================
-// ========================================================================
 
 void SetupConfiguration(Configuration &conf)
@@ -55,4 +20,5 @@
         ("date", var<string>(), "SQL time (UTC), e.g. '2016-12-24'")
         ("source-database", var<string>(""), "Database link as in\n\tuser:password@server[:port]/database.")
+        ("schedule-database", var<string>(""), "Database link as in\n\tuser:password@server[:port]/database.")
         ("max-current", var<double>(90), "Global maximum current limit in uA")
         ("max-zd", var<double>(75), "Global zenith distance limit in degree")
@@ -63,4 +29,5 @@
         ("data-taking.start", var<double>(-12), "Begin of data-taking in degree of sun below horizon")
         ("data-taking.end", var<double>(-13.75), "End of data-taking in degree of sun below horizon")
+        ("enter-schedule-into-database", var<bool>(), "Enter schedule into database (required schedule-database, false: dry-run)")
         ;
 
@@ -471,4 +438,72 @@
 }
 
+int FillSql(Database &db, int enter, const vector<Source> &obs, double startup_offset)
+{
+    const string query0 = "SELECT COUNT(*) FROM Schedule WHERE DATE(ADDTIME(fStart, '-12:00')) = '"+Time(obs[0].begin).GetAsStr("%Y-%m-%d")+"'";
+
+    const mysqlpp::StoreQueryResult res0 = db.query(query0).store();
+
+    if (res0.num_rows()!=1)
+    {
+        cout << "Check for schedule size failed." << endl;
+        return 10;
+    }
+
+    if (uint32_t(res0[0][0])!=0)
+    {
+        cout << "Schedule not empty." << endl;
+        return 11;
+    }
+
+    const mysqlpp::StoreQueryResult res1 = db.query("SELECT fSourceName, fSourceKEY FROM Source").store();
+
+    map<string, uint32_t> keys;
+    for (const auto &row: res1)
+        keys.emplace(string(row[0]), uint32_t(row[1]));
+
+    const mysqlpp::StoreQueryResult res2 = db.query("SELECT fMeasurementTypeName, fMeasurementTypeKEY FROM MeasurementType").store();
+
+    map<string, uint32_t> types;
+    for (const auto &row: res2)
+        types.emplace(string(row[0]), uint32_t(row[1]));
+
+    ostringstream str;
+    str << "INSERT INTO Schedule (fStart, fUser, fMeasurementID, fMeasurementTypeKEY, fSourceKEY) VALUES\n";
+
+    str << "('" << Time(obs[0].begin-startup_offset).GetAsStr() << "', auto, 0, " << types["Startup"] << ", NULL), [Startup]\n";
+    for (const auto& src: obs)
+    {
+        string tm = Time(src.begin).GetAsStr();
+
+        /*
+         if (src.preobs.size()>0)
+         {
+         for (const auto& pre: src.preobs)
+         {
+         str << tm << "  " << pre << "\n";
+         tm = "                   ";
+         }
+         }*/
+
+        if (src.name!="SLEEP")
+            str << "('" << tm << "', auto, 0, " << types["Data"] << ", " << keys[src.name] << "), [Data: " << src.name << "]\n";
+        else
+            str << "('" << tm << "', auto, 0, " << types["Sleep"] << ", NULL), [Sleep]\n";
+    }
+
+    str << "('" << Time(obs.back().end).GetAsStr() << "', auto, 0, " << types["Shutdown"] << ", NULL) [Shutdown]";
+
+    if (enter<0)
+    {
+        cout << str.str() << endl;
+        return 0;
+    }
+
+    db.query(str.str());
+
+    cout << "Schedule entered successfully into database." << endl;
+    return 0;
+}
+
 int main(int argc, const char* argv[])
 {
@@ -484,7 +519,14 @@
     // ------------------ Eval config ---------------------
 
+    const int enter = conf.Has("enter-schedule-into-database") ? (conf.Get<bool>("enter-schedule-into-database") ? 1 : -1) : 0;
+    if (enter && !conf.Has("schedule-database"))
+        throw runtime_error("enter-schedule-into-database required schedule-database.");
+
     Time time;
     if (conf.Has("date"))
-        time.SetFromStr(conf.Get<string>("date")+" 12:00:00");
+        time.SetFromStr(conf.Get<string>("date"));
+
+    if (enter && floor(time.JD())<ceil(Time().JD()))
+        throw runtime_error("Only future schedules can be entered into the database.");
 
     Source::max_current = conf.Get<double>("max-current");
@@ -508,6 +550,6 @@
     // Sun set with the same date than th provided date
     // Sun rise on the following day
-    const RstTime sun_set  = GetSolarRst(time.JD()-0.5, angle_sun_set);
-    const RstTime sun_rise = GetSolarRst(time.JD()+0.5, angle_sun_rise);
+    const RstTime sun_set  = GetSolarRst(floor(time.JD())-0.5, angle_sun_set);
+    const RstTime sun_rise = GetSolarRst(floor(time.JD())+0.5, angle_sun_rise);
 
     const double sunset  = ceil(sun_set.set*24*60)/24/60;
@@ -530,7 +572,7 @@
         query += " AND fSourceName IN ('" + boost::algorithm::join(sourcenames, "', '")+"')";
 
-    const string fDatabase = conf.Get<string>("source-database");
+    const string sourcedb = conf.Get<string>("source-database");
     const mysqlpp::StoreQueryResult res =
-        Database(fDatabase).query(query).store();
+        Database(sourcedb).query(query).store();
 
     // ------------------ Eval config ---------------------
@@ -609,5 +651,5 @@
     {
         cout << "No source found." << endl;
-        return 0;
+        return 1;
     }
 
@@ -637,160 +679,21 @@
     // ---------------------------------------------------------------------
 
-    return 1;
-
-    // ------------- Create canvases and frames ---------------------
-/*
-    // It is important to use an offset which is larger than
-    // 1970-01-01 00:00:00. This one will not work if your
-    // local time zone is positive!
-    TH1S hframe("", "", 1, Time(sunset).Mjd()*24*3600, Time(sunrise).Mjd()*24*3600);
-    hframe.SetStats(kFALSE);
-    hframe.GetXaxis()->SetTimeFormat("%Hh%M%F1995-01-01 00:00:00 GMT");
-    hframe.GetXaxis()->SetTitle((Time(jd).GetAsStr("%d/%m/%Y")+"  -  "+Time(jd+1).GetAsStr("%d/%m/%Y")+"  [UTC]").c_str());
-    hframe.GetXaxis()->CenterTitle();
-    hframe.GetYaxis()->CenterTitle();
-    hframe.GetXaxis()->SetTimeDisplay(true);
-    hframe.GetYaxis()->SetTitleSize(0.040);
-    hframe.GetXaxis()->SetTitleSize(0.040);
-    hframe.GetXaxis()->SetTitleOffset(1.1);
-    hframe.GetYaxis()->SetLabelSize(0.040);
-    hframe.GetXaxis()->SetLabelSize(0.040);
-
-    TCanvas c1;
-    c1.SetFillColor(kWhite);
-    c1.SetBorderMode(0);
-    c1.SetFrameBorderMode(0);
-    c1.SetLeftMargin(0.085);
-    c1.SetRightMargin(0.01);
-    c1.SetTopMargin(0.03);
-    c1.SetGrid();
-    hframe.GetYaxis()->SetTitle("Altitude [deg]");
-    hframe.SetMinimum(15);
-    hframe.SetMaximum(90);
-    hframe.DrawCopy();
-
-    TCanvas c2;
-    c2.SetFillColor(kWhite);
-    c2.SetBorderMode(0);
-    c2.SetFrameBorderMode(0);
-    c2.SetLeftMargin(0.085);
-    c2.SetRightMargin(0.01);
-    c2.SetTopMargin(0.03);
-    c2.SetGrid();
-    hframe.GetYaxis()->SetTitle("Predicted Current [#muA]");
-    hframe.SetMinimum(0);
-    hframe.SetMaximum(100);
-    hframe.DrawCopy();
-
-    TCanvas c3;
-    c3.SetFillColor(kWhite);
-    c3.SetBorderMode(0);
-    c3.SetFrameBorderMode(0);
-    c3.SetLeftMargin(0.085);
-    c3.SetRightMargin(0.01);
-    c3.SetTopMargin(0.03);
-    c3.SetGrid();
-    c3.SetLogy();
-    hframe.GetYaxis()->SetTitle("Estimated relative threshold");
-    hframe.GetYaxis()->SetMoreLogLabels();
-    hframe.SetMinimum(0.9);
-    hframe.SetMaximum(11);
-    hframe.DrawCopy();
-
-    TCanvas c4;
-    c4.SetFillColor(kWhite);
-    c4.SetBorderMode(0);
-    c4.SetFrameBorderMode(0);
-    c4.SetLeftMargin(0.085);
-    c4.SetRightMargin(0.01);
-    c4.SetTopMargin(0.03);
-    c4.SetGrid();
-    hframe.GetYaxis()->SetTitle("Distance to moon [deg]");
-    hframe.SetMinimum(0);
-    hframe.SetMaximum(180);
-    hframe.DrawCopy();
-    Int_t color[] = { kBlack, kRed, kBlue, kGreen, kCyan, kMagenta };
-    Int_t style[] = { kSolid, kDashed, kDotted };
-
-    //    TLegend leg(0, 0, 1, 1);
-
-    // ------------- Loop over sources ---------------------
-
-    for (vector<mysqlpp::Row>::const_iterator v=res.begin(); v<res.end(); v++, cnt++)
-    {
-        // Eval row
-        const string name = (*v)[0].c_str();
-
-        EquPosn pos;
-        pos.ra  = double((*v)[1])*15;
-        pos.dec = double((*v)[2]);
-
-        // Loop over 24 hours
-        for (double h=0; h<1; h+=1./(24*12))
-        {
-            const SolarObjects so(jd+h);
-
-            // get local position of source
-            const HrzPosn hrz = GetHrzFromEqu(pos, so.fJD);
-
-            if (v==res.begin())
-                cout << Time(so.fJD) <<" " << 90-so.fMoonHrz.alt <<  endl;
-
-            const double cur = FACT::PredictI(so, pos);
-
-            // Relative  energy threshold prediction
-            const double ratio = pow(cos((90-hrz.alt)*M_PI/180), -2.664);
-
-            // Add points to curve
-            const double axis = Time(so.fJD).Mjd()*24*3600;
-
-            // If there is a gap of more than one bin, start a new curve
-
-            // Add data
-            if (no_limits || cur<max_current)
-                g1.SetPoint(g1.GetN(), axis, hrz.alt);
-
-            if (no_limits || 90-hrz.alt<max_zd)
-                g2.SetPoint(g2.GetN(), axis, cur);
-
-            if (no_limits || (cur<max_current && 90-hrz.alt<max_zd))
-                g3.SetPoint(g3.GetN(), axis, ratio*pow(cur/6.2, 0.394));
-
-            if (no_limits || (cur<max_current && 90-hrz.alt<max_zd))
-            {
-                const double angle = GetAngularSeparation(so.fMoonEqu, pos);
-                g4.SetPoint(g4.GetN(), axis, angle);
-            }
-
-            if (cnt==0)
-                gm.SetPoint(gm.GetN(), axis, so.fMoonHrz.alt);
-        }
-    }
-
-    // Save three plots
-    TCanvas c5;
-    c5.SetFillColor(kWhite);
-    c5.SetBorderMode(0);
-    c5.SetFrameBorderMode(0);
-    leg.Draw();
-
-    const string t = Time(jd).GetAsStr("%Y%m%d");
-
-    c1.SaveAs((t+"-ZenithDistance.eps").c_str());
-    c2.SaveAs((t+"-PredictedCurrent.eps").c_str());
-    c3.SaveAs((t+"-RelativeThreshold.eps").c_str());
-    c4.SaveAs((t+"-MoonDist.eps").c_str());
-    c5.SaveAs((t+"-Legend.eps").c_str());
-
-    c1.SaveAs((t+"-ZenithDistance.root").c_str());
-    c2.SaveAs((t+"-PredictedCurrent.root").c_str());
-    c3.SaveAs((t+"-RelativeThreshold.root").c_str());
-    c4.SaveAs((t+"-MoonDist.root").c_str());
-
-    c1.Print((t+".pdf(").c_str(), "pdf");
-    c2.Print((t+".pdf" ).c_str(), "pdf");
-    c3.Print((t+".pdf" ).c_str(), "pdf");
-    c4.Print((t+".pdf" ).c_str(), "pdf");
-    c5.Print((t+".pdf)").c_str(), "pdf");
-*/
-}
+    if (!enter)
+        return 0;
+
+    const string scheduledb = conf.Get<string>("schedule-database");
+
+    Database db(scheduledb);
+
+    if (enter>0)
+        db.query("LOCK TABLES Schedule WRITE");
+
+    const int rc = FillSql(db, enter, obs, startup_offset);
+
+    if (enter>0)
+        db.query("UNLOCK TABLES");
+
+    // ---------------------------------------------------------------------
+
+    return rc;
+}
