Index: /trunk/MagicSoft/Mars/Changelog
===================================================================
--- /trunk/MagicSoft/Mars/Changelog	(revision 8995)
+++ /trunk/MagicSoft/Mars/Changelog	(revision 8996)
@@ -19,4 +19,76 @@
                                                  -*-*- END OF LINE -*-*-
 
+ 2008/07/05 Thomas Bretz
+
+   * datacenter/macros/fillcamera.C, datacenter/macros/findcacofiles.C:
+     - changed JOIN to use USING
+     - removed dependence on TEnv
+     - some improvement to includes
+
+   * datacenter/macros/filldotrbk.C, datacenter/macros/fillganymed.C,
+     datacenter/macros/filloptical.C, datacenter/macros/fillsignal.C,
+     datacenter/macros/fillsources.C, datacenter/macros/fillstar.C,
+     datacenter/macros/getdolist.C, datacenter/macros/insertcacofile.C,
+     datacenter/macros/insertdataset.C, datacenter/macros/plotoptical.C,
+     datacenter/macros/plotrundb.C, datacenter/macros/plotstat.C,
+     datacenter/macros/resetallruns.C,
+     datacenter/macros/writedatasetfile.C:
+     - removed dependence on TEnv
+     - some improvement to includes
+
+   * datacenter/macros/filldotrun.C:
+     - make it fail for everything except Magic 1
+     - removed dependence on TEnv
+     - some improvement to includes
+
+   * datacenter/macros/plotoptical.C:
+     - removed MPlot, use MPlot from plotdb instead
+
+   * datacenter/macros/setstatus.C:
+     - some improvement to includes
+
+   * mbase/MTime.[h,cc]:
+     - added function returning day of sunrise as MTime
+
+   * mhflux/MHAlpha.cc:
+     - use BinError instead of BinContents to decide whether the
+       excess time is plotted or not
+
+   * mimage/MHHillas.cc:
+     - changed title of "Center"
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added new class MSequenceSQL
+
+   * mjobs/MSequenceSQL.[h,cc]:
+     - added
+
+   * mjobs/MSequence.[h,cc]:
+     - replaced ReadLightCondition by the more flexible GetLightCondition
+     - added a new constrcutor constructing a MSequence from the database
+     - fixed the output in the comments in Print()
+     - The day and night was printed in a different format than 
+       expected when readin a sequence
+     - fLightCondition and the f*RunsSub were missing in the copy-
+       constructor
+
+   * mjobs/Makefile:
+     - added include of msql
+
+   * msql/MSQLMagic.[h,cc]:
+     - added a comment to ExistStr and allow to set an additional
+       where-clause
+
+   * msql/MSQLServer.cc:
+     - allow to init MSQLServer either by an url or from a named
+       resource file
+     - changed JOIN to use USING
+     - if doing an automatic join join _all_ primaries
+
+   * mtools/MCalendar.cc:
+     - added include of TObjArray needed in newer root versions
+
+
+
  2008/07/03 Thomas Bretz
 
@@ -44,5 +116,6 @@
 
    * sponde.cc:
-     - display only the base name of the ganymed file, not the full path
+     - display only the base name of the ganymed file, not the
+       full path
 
    * mbase/MMath.[h,cc]:
Index: /trunk/MagicSoft/Mars/datacenter/macros/fillcamera.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/fillcamera.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/fillcamera.C	(revision 8996)
@@ -47,5 +47,4 @@
 #include <iomanip>
 
-#include <TEnv.h>
 #include <TRegexp.h>
 #include <TObjectTable.h>
@@ -656,6 +655,6 @@
 //                        "where MCRunData.fRunNumber=%d;", RunNum));
     TString query3(Form("SELECT fMCParticleName, fSpectrum FROM MCRunData "
-                        "LEFT JOIN MCParticle ON MCRunData.fMCParticleKEY=MCParticle.fMCParticleKEY "
-                        "LEFT JOIN Spectrum ON Spectrum.fSpectrumKEY=MCRunData.fSpectrumKEY "
+                        "LEFT JOIN MCParticle USING (fMCParticleKEY) "
+                        "LEFT JOIN Spectrum USING (fSpectrumKEY) "
                         "WHERE MCRunData.fRunNumber=%d;", RunNum));
     res = serv.Query(query3);
@@ -773,7 +772,5 @@
 int fillcamera(TString fname, Bool_t dummy=kTRUE)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
@@ -797,7 +794,5 @@
 int fillcamera(TString path="/magic/montecarlo/camera", Bool_t dummy=kTRUE)
 {
-    TEnv env("mcsql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("mcsql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/filldotrbk.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/filldotrbk.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/filldotrbk.C	(revision 8996)
@@ -64,5 +64,4 @@
 #include <fstream>
 
-#include <TEnv.h>
 #include <TRegexp.h>
 
@@ -206,7 +205,5 @@
 int filldotrbk(TString path="/data/MAGIC/Period017/ccdata", Bool_t dummy=kTRUE)
 {
-    TEnv env("sql.rc");
-
-    MSQLServer serv(env);
+    MSQLServer serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/filldotrun.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/filldotrun.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/filldotrun.C	(revision 8996)
@@ -79,5 +79,4 @@
 #include <fstream>
 
-#include <TEnv.h>
 #include <TMath.h>
 #include <TRegexp.h>
@@ -148,4 +147,11 @@
             {
                 cout << "First character is not an M." << endl;
+                cout << strng << endl;
+                strng.ReadLine(fin);
+                continue;
+            }
+            if (strng[1]!='1')
+            {
+                cout << "Only MAGIC 1 implemented so far." << endl;
                 cout << strng << endl;
                 strng.ReadLine(fin);
@@ -580,7 +586,5 @@
 int filldotrun(const TString path="/data/MAGIC/Period018/ccdata", Bool_t dummy=kTRUE)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/fillganymed.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/fillganymed.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/fillganymed.C	(revision 8996)
@@ -55,5 +55,4 @@
 #include <iomanip>
 
-#include <TEnv.h>
 #include <TRegexp.h>
 
@@ -218,7 +217,5 @@
 int fillganymed(TString fname, Bool_t dummy=kTRUE)
 {
-    TEnv env("sql.rc");
-
-    MSQLServer serv(env);
+    MSQLServer serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/filloptical.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/filloptical.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/filloptical.C	(revision 8996)
@@ -46,5 +46,4 @@
 #include <TVector3.h>
 
-#include <TEnv.h>
 #include <TRegexp.h>
 
@@ -274,7 +273,5 @@
 int filloptical(TString path, Bool_t dummy=kTRUE)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/fillsources.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/fillsources.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/fillsources.C	(revision 8996)
@@ -36,9 +36,8 @@
 #include <fstream>
 
-#include <TEnv.h>
-
-#include <MSQLServer.h>
 #include <TSQLRow.h>
 #include <TSQLResult.h>
+
+#include "MSQLServer.h"
 
 using namespace std;
@@ -67,7 +66,5 @@
 int fillsources(TString catalog)
 {
-    TEnv env("sql.rc");
-
-    MSQLServer serv(env);
+    MSQLServer serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/fillstar.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/fillstar.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/fillstar.C	(revision 8996)
@@ -59,5 +59,4 @@
 #include <iomanip>
 
-#include <TEnv.h>
 #include <TRegexp.h>
 
@@ -310,7 +309,5 @@
 int fillstar(TString fname, Bool_t dummy=kTRUE)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/findcacofiles.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/findcacofiles.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/findcacofiles.C	(revision 8996)
@@ -57,10 +57,10 @@
 #include <fstream>
 
-#include <TEnv.h>
 #include <TSystem.h>
 
-#include "MSQLMagic.h"
 #include <TSQLRow.h>
 #include <TSQLResult.h>
+
+#include "MSQLMagic.h"
 
 using namespace std;
@@ -69,7 +69,5 @@
 int findcacofiles()
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
@@ -87,6 +85,6 @@
     query+=" DATE_FORMAT(ADDDATE(if(fRunStart='0000-00-00 00:00:00', fRunStop, fRunStart), INTERVAL +13 HOUR), '%Y/%m/%d') ";
     query+=" FROM RunProcessStatus ";
-    query+=" LEFT JOIN RunData ON RunData.fRunNumber=RunProcessStatus.fRunNumber ";
-    query+=" LEFT JOIN Source ON RunData.fSourceKEY=Source.fSourceKEY ";
+    query+=" LEFT JOIN RunData USING (fRunNumber) ";
+    query+=" LEFT JOIN Source USING (fSourceKEY) ";
     query+=" WHERE IsNull(fCaCoFileFound) AND fExcludedFDAKEY=1 ";
     query+=" AND RunProcessStatus.fRunNumber > 10000 AND NOT IsNull(fCCFileAvail)";
@@ -115,5 +113,5 @@
 
         query ="SELECT MAX(fCaCoFileFound) FROM RunProcessStatus ";
-        query+=" LEFT JOIN RunData ON RunData.fRunNumber=RunProcessStatus.fRunNumber ";
+        query+=" LEFT JOIN RunData USING (fRunNumber) ";
         query+=Form("WHERE DATE_FORMAT(ADDDATE(fRunStart, INTERVAL +13 HOUR), '%%Y/%%m/%%d')='%s' ",
                     (*row)[1]);
Index: /trunk/MagicSoft/Mars/datacenter/macros/getdolist.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/getdolist.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/getdolist.C	(revision 8996)
@@ -68,8 +68,9 @@
 #include <TSystem.h>
 
-#include <MSQLServer.h>
 #include <TSQLRow.h>
 #include <TSQLResult.h>
 
+#include "MSQLServer.h"
+
 using namespace std;
 
@@ -77,7 +78,5 @@
 int getdolist(TString table, TString column, TString date, TString listpath)
 {
-    TEnv env("sql.rc");
-
-    MSQLServer serv(env);
+    MSQLServer serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/insertcacofile.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/insertcacofile.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/insertcacofile.C	(revision 8996)
@@ -57,10 +57,10 @@
 #include <fstream>
 
-#include <TEnv.h>
 #include <TSystem.h>
 
-#include <MSQLServer.h>
 #include <TSQLRow.h>
 #include <TSQLResult.h>
+
+#include "MSQLServer.h"
 
 using namespace std;
@@ -68,7 +68,5 @@
 int insertcacofile(TString runnumber, TString newrunnumber)
 {
-    TEnv env("sql.rc");
-
-    MSQLServer serv(env);
+    MSQLServer serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/insertdataset.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/insertdataset.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/insertdataset.C	(revision 8996)
@@ -54,6 +54,4 @@
 #include <iomanip>
 
-#include <TEnv.h>
-
 #include "MSQLMagic.h"
 
@@ -62,7 +60,5 @@
 int insertdataset(TString number, TString source, TString wobble, TString comment, Bool_t dummy=kTRUE)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/plotoptical.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/plotoptical.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/plotoptical.C	(revision 8996)
@@ -1,4 +1,4 @@
 /* ======================================================================== *\
-! $Name: not supported by cvs2svn $:$Id: plotoptical.C,v 1.8 2007-10-07 21:11:01 tbretz Exp $
+! $Name: not supported by cvs2svn $:$Id: plotoptical.C,v 1.9 2008-07-05 19:01:42 tbretz Exp $
 ! --------------------------------------------------------------------------
 !
@@ -78,463 +78,7 @@
 //
 /////////////////////////////////////////////////////////////////////////////
-#include <iostream>
-#include <iomanip>
-
-#include <TH1.h>
-#include <TEnv.h>
-#include <TPad.h>
-#include <TLine.h>
-#include <TText.h>
-#include <TFrame.h>
-#include <TStyle.h>
-#include <TCanvas.h>
-#include <TPRegexp.h>
-#include <TSQLRow.h>
-#include <TSQLResult.h>
-#include <TGraphErrors.h>
-
-#include "MTime.h"
-#include "MAstro.h"
-#include "MDataSet.h"
-#include "MSQLMagic.h"
-#include "MStatusDisplay.h"
-
-class MPlot : public MParContainer
-{
-public:
-    // Possible constants to group-by (average) over a certain period
-    enum GroupBy_t
-    {
-        kNone,
-        kGroupByPrimary,
-        kGroupByHour,
-        kGroupByNight,
-        kGroupByWeek,
-        kGroupByMonth,
-        kGroupBySeason,
-        kGroupByYear
-    };
-
-private:
-    MSQLMagic &fServer;         // Reference to the sql-server class
-
-    MDataSet *fDataSet;         // A possible dtaset to highlite single points
-
-    TString   fPrimaryDate;     // The name of the data we plot
-    TString   fPrimaryNumber;   // The corresponding name for the key number
-    TString   fSecondary;       // The value versus which the second plot is made
-
-    TString   fRequestFrom;     // Start of a requested date range
-    TString   fRequestTo;       // End of a requested date range
-    Int_t     fRequestPeriod;   // A possible requested period
-
-    Float_t   fPlotMin;
-    Float_t   fPlotMax;
-
-    Float_t   fHistMin;
-    Float_t   fHistMax;
-
-    TString   fDescription;     // The description (title) of the plot
-    TString   fNameTab;         // The name of the tab in the display
-
-    TString   fCondition;       // An additional condition added to the query
-    GroupBy_t fGroupBy;         // A possible Group-By flag
-
-    // --------------------------------------------------------------------------
-    //
-    // Function to plot the result of the query
-    //
-    void PlotTable(TSQLResult &res, TString name, Float_t fmin, Float_t fmax, Float_t resolution)
-    {
-        // Enable all otions in the statistics box
-        gStyle->SetOptStat(111111);
-
-        // Create TGraph objects
-        TGraph &gt = res.GetFieldCount()>4 ? *new TGraphErrors : *new TGraph;
-        gt.SetNameTitle(name, Form("%s vs Time", name.Data()));
-        gt.SetMarkerStyle(kFullDotMedium);
-
-        TGraph gz;
-        gz.SetNameTitle(name, Form("%s vs <Zd>", name.Data()));
-        gz.SetMarkerStyle(kFullDotMedium);
-
-        TGraph gt0, gt1;
-        gt0.SetMarkerColor(kRed);
-        gt1.SetMarkerColor(kBlue);
-        gt0.SetMarkerStyle(kFullDotLarge);
-        gt1.SetMarkerStyle(kFullDotLarge);
-
-        TGraph gz0, gz1;
-        gz0.SetMarkerColor(kRed);
-        gz1.SetMarkerColor(kBlue);
-        gz0.SetMarkerStyle(kFullDotLarge);
-        gz1.SetMarkerStyle(kFullDotLarge);
-
-        Int_t first = -1;
-        Int_t last  = -1;
-
-        // Loop over the data
-        TSQLRow *row=0;
-        while ((row=res.Next()))
-        {
-            // Get all fields of this row
-            const char *date = (*row)[0];
-            const char *zd   = (*row)[1];
-            const char *val  = (*row)[2];
-            const char *snum = res.GetFieldCount()>3 ? (*row)[3] : 0;
-            const char *verr = res.GetFieldCount()>4 ? (*row)[5] : 0;
-
-            delete row;
-
-            if (!date || !val || !zd)
-                continue;
-
-            // check if date is valid
-            MTime t(date);
-            if (!t.SetSqlDateTime(date))
-                continue;
-
-            // check if it belongs to the requested MAGIC period
-            if (fRequestPeriod>0 && MAstro::GetMagicPeriod(t.GetMjd())!=fRequestPeriod)
-                continue;
-
-            // Get axis range
-            if (first<0)
-                first = TMath::Nint(TMath::Floor(t.GetMjd()));
-            last = TMath::Nint(TMath::Ceil(t.GetMjd()));
-
-            // Convert a possible key number into a integer
-            UInt_t seq = snum ? atoi(snum) : 0;
-
-            // convert primary and secondary value into floats
-            Float_t value = atof(val);
-            Float_t zenith = atof(zd);
-
-            // If a datset is given add the point to the special TGraphs
-            // used for highliting these dates
-            if (fDataSet)
-            {
-                if (fDataSet->HasOnSequence(seq))
-                {
-                    gt1.SetPoint(gt1.GetN(), t.GetAxisTime(), value);
-                    gz1.SetPoint(gz1.GetN(), zenith, value);
-                }
-
-                if (fDataSet->HasOffSequence(seq))
-                {
-                    gt0.SetPoint(gt0.GetN(), t.GetAxisTime(), value);
-                    gz0.SetPoint(gz0.GetN(), zenith, value);
-                }
-            }
-
-            // Add Data to TGraph
-            gt.SetPoint(gt.GetN(), t.GetAxisTime(), value);
-            gz.SetPoint(gz.GetN(), zenith, value);
-
-            // Set error-bar, if one
-            if (verr)
-                static_cast<TGraphErrors&>(gt).SetPointError(gt.GetN()-1, 0, atof(verr));
-        }
-
-        // If this is done earlier the plots remain empty since root 5.12/00
-        if (fmax>fmin)
-        {
-            gt.SetMinimum(fmin);
-            gt.SetMaximum(fmax);
-            gz.SetMinimum(fmin);
-            gz.SetMaximum(fmax);
-        }
-
-        gROOT->SetSelectedPad(0);
-
-        // Create a TCanvas or open a new tab
-        TString title = fNameTab.IsNull() ? name(name.First('.')+2, name.Length()) : fNameTab;
-        TCanvas &c = fDisplay ? fDisplay->AddTab(title) : *new TCanvas;
-        // Set fillcolor, remove border and divide pad
-        c.SetFillColor(kWhite);
-        c.SetBorderMode(0);
-        c.Divide(1,2);
-
-        // Output mean and rms to console
-        cerr << setprecision(4) << setw(10) << title << ":   ";
-        if (gt.GetN()==0)
-        {
-            cerr << "     <empty>" << endl;
-            return;
-        }
-        cerr << setw(8) << gt.GetMean(2) << "+-" << setw(8) << gt.GetRMS(2) << "   ";
-        if (gt0.GetN()>0 || gt1.GetN()>0)
-        {
-            cerr << setw(8) << gt1.GetMean(2) << "+-" << setw(8) << gt1.GetRMS(2) << "   ";
-            cerr << setw(8) << gt0.GetMean(2) << "+-" << setw(8) << gt0.GetRMS(2);
-        }
-        cerr << endl;
-
-        TVirtualPad *pad = gPad;
-
-        // draw contants of pad 2 (counting starts at 0)
-        pad->cd(2);
-        gPad->SetBorderMode(0);
-        gPad->SetFrameBorderMode(0);
-        gPad->SetGridy();
-
-        gPad->SetLeftMargin(0.06);
-        gPad->SetRightMargin(0.06);
-        gPad->SetBottomMargin(0.08);
-
-        // format axis
-        TH1 *h = gt.GetHistogram();
-
-        h->SetXTitle("Time");
-        h->SetYTitle(name);
-        h->GetXaxis()->SetTimeDisplay(1);
-        h->GetYaxis()->SetTitleOffset(0.8);
-        h->GetXaxis()->SetTitleOffset(1.0);
-        h->GetXaxis()->SetLabelOffset(0.01);
-
-        // draw TGraph
-        gt.DrawClone("AP");
-        if (gt0.GetN()>0)
-            gt0.DrawClone("P");
-        if (gt1.GetN()>0)
-            gt1.DrawClone("P");
-
-        // Add lines and text showing the MAGIC periods
-        TLine l;
-        TText t;
-        Int_t num=0;
-        l.SetLineStyle(kDotted);
-        l.SetLineColor(kBlue);
-        t.SetTextColor(kBlue);
-        l.SetLineWidth(1);
-        t.SetTextSize(h->GetXaxis()->GetLabelSize());
-        t.SetTextAlign(21);
-        Int_t p0 = MAstro::GetMagicPeriod(first);
-        for (Int_t p = first; p<last; p++)
-        {
-            Int_t p1 = MAstro::GetMagicPeriod(p);
-            if (p1!=p0)
-            {
-                l.DrawLine(MTime(p).GetAxisTime(), h->GetMinimum(), MTime(p).GetAxisTime(), h->GetMaximum());
-                t.DrawText(MTime(p+15).GetAxisTime(), h->GetMaximum(), Form("%d", p1));
-                num++;
-            }
-            p0 = p1;
-        }
-        if (num<4)
-            gPad->SetGridx();
-
-        const Double_t min = fHistMin>fHistMax ? h->GetMinimum()-resolution/2 : fHistMin;
-        const Double_t max = fHistMin>fHistMax ? h->GetMaximum()+resolution/2 : fHistMax;
-
-        // Use this to save the pad with the time development to a file
-        //gPad->SaveAs(Form("plotdb-%s.eps", title.Data()));
-
-        // Go back to first (upper) pad, format it and divide it again
-        pad->cd(1);
-        gPad->SetBorderMode(0);
-        gPad->SetFrameBorderMode(0);
-        gPad->Divide(2,1);
-
-        TVirtualPad *pad2 = gPad;
-
-        // format left pad
-        pad2->cd(1);
-        gPad->SetBorderMode(0);
-        gPad->SetFrameBorderMode(0);
-        gPad->SetGridx();
-        gPad->SetGridy();
-
-        // Create histogram
-        const Int_t n = resolution>0 ? TMath::Nint((max-min)/resolution) : 50;
-
-        TH1F hist("Hist", Form("Distribution of %s", fDescription.IsNull() ? name.Data() : fDescription.Data()), n, min, max);
-        hist.SetDirectory(0);
-
-        // Fill data into histogra,
-        for (int i=0; i<gt.GetN(); i++)
-            hist.Fill(gt.GetY()[i]);
-
-        // Format histogram
-        if (fDescription.IsNull())
-            hist.SetXTitle(name);
-        hist.SetYTitle("Counts");
-
-        // plot histogram
-        hist.DrawCopy("");
-
-        // format right pad
-        pad2->cd(2);
-        gPad->SetBorderMode(0);
-        gPad->SetFrameBorderMode(0);
-        gPad->SetGridy();
-
-        // format graph
-        TH1 *h2 = gz.GetHistogram();
-
-        h2->SetXTitle("Zd");
-        h2->SetYTitle(name);
-
-        // draw graph
-        gz.DrawClone("AP");
-
-        if (gz0.GetN()>0)
-            gz0.DrawClone("P");
-        if (gz1.GetN()>0)
-            gz1.DrawClone("P");
-    }
-
-public:
-    MPlot(MSQLMagic &server) : fServer(server), fDataSet(NULL),
-        fRequestPeriod(-1), fPlotMin(0), fPlotMax(-1), fHistMin(0), fHistMax(-1), fGroupBy(kNone)
-    {
-    }
-    ~MPlot()
-    {
-        if (fDataSet)
-            delete fDataSet;
-    }
-    void SetDataSet(const TString filename)
-    {
-        if (fDataSet)
-        {
-            delete fDataSet;
-            fDataSet = NULL;
-        }
-        if (!filename.IsNull())
-            fDataSet = new MDataSet(filename);
-    }
-    void SetPlotRange(Float_t min, Float_t max, Int_t n=5) { fPlotMin = min; fPlotMax = max; }
-    void SetHistRange(Float_t min, Float_t max) { fHistMin = min; fHistMax = max; }
-    void SetRequestRange(const char *from="", const char *to="") { fRequestFrom = from; fRequestTo = to; }
-    void SetRequestPeriod(Int_t n=-1) { fRequestPeriod = n; }
-    void SetCondition(const char *cond="") { fCondition = cond; }
-    void SetDescription(const char *d, const char *t=0) { fDescription = d; fNameTab = t; }
-    void SetGroupBy(GroupBy_t b=kGroupByWeek) { fGroupBy=b; }
-    void SetPrimaryDate(const char *ts) { fPrimaryDate=ts; }
-    void SetPrimaryNumber(const char *ts) { fPrimaryNumber=ts; }
-    void SetSecondary(const char *ts) { fSecondary=ts; }
-
-    Int_t QueryKeyOfSource(TString src)
-    {
-        return fServer.QueryKeyOfName("Object", src, kFALSE);
-    }
-
-    Bool_t Plot(const char *value, Float_t min=0, Float_t max=-1, Float_t resolution=0)
-    {
-        TString named  = fPrimaryDate;
-        TString named2 = fSecondary;
-        TString namev  = value;
-
-        TString tablev = namev(0, namev.First('.'));
-        TString valuev = namev(namev.First('.')+1, namev.Length());
-
-        TString tabled = named(0, named.First('.'));
-        TString valued = named(named.First('.')+1, named.Length());
-
-        TString query="SELECT ";
-        switch (fGroupBy)
-        {
-        case kNone:
-        case kGroupByPrimary:
-            query += Form("%s AS %s", valued.Data(), valued.Data()+1);
-            break;
-        case kGroupByHour:
-            query += Form("DATE_FORMAT(%s, '%%Y-%%m-%%d %%H:30:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
-            break;
-        case kGroupByNight:
-            query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%Y-%%m-%%d 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
-            break;
-        case kGroupByWeek:
-            query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%x%%v') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
-            break;
-        case kGroupByMonth:
-            query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%Y-%%m-15 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
-            break;
-        case kGroupBySeason:
-            //query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%Y-%%m-15 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
-            break;
-        case kGroupByYear:
-            query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%Y-08-15 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
-            break;
-        }
-
-        if (fGroupBy==kNone)
-        {
-            query += ", ";
-            query += fSecondary;
-            query += ", ";
-            query += value;
-            query += ", ";
-            query += fPrimaryNumber;
-            query += " ";
-        }
-        else
-        {
-            query += ", AVG(";
-            query += fSecondary;
-            query += "), AVG(";
-            query += value;
-            query += "), ";
-            query += fPrimaryNumber;
-            query += ", STD(";
-            query += fSecondary;
-            query += "), STD(";
-            query += value;
-            query += ") ";
-        }
-
-        query += Form("FROM %s ", tabled.Data());
-
-        TString where(fCondition);
-
-        const Bool_t interval = !fRequestFrom.IsNull() && !fRequestTo.IsNull();
-        if (interval)
-        {
-            if (!where.IsNull())
-                where += " AND ";
-            where += Form("%s BETWEEN '%s' AND '%s' ",
-                          fPrimaryDate.Data(), fRequestFrom.Data(), fRequestTo.Data());
-        }
-
-        if (!where.IsNull())
-            where += " AND ";
-        where += fCondition;
-        where += " ";
-
-        // ------------------------------
-
-        query += fServer.GetJoins(tabled, query+" "+where);
-
-        if (!where.IsNull())
-        {
-            query += "WHERE ";
-            query += where;
-        }
-
-        if (fGroupBy!=kNone)
-        {
-            query += Form("GROUP BY %s ", valued.Data()+1);
-            //query += Form(" HAVING COUNT(%s)=(COUNT(*)+1)/2 ", valuev.Data());
-        }
-        query += Form("ORDER BY %s ", valued.Data()+1);
-
-        // ------------------------------
-
-        TSQLResult *res = fServer.Query(query);
-        if (!res)
-            return kFALSE;
-
-        if (max>min)
-            PlotTable(*res, namev, min, max, resolution);
-        else
-            PlotTable(*res, namev, fPlotMin, fPlotMax, resolution);
-
-        delete res;
-        return kTRUE;
-    }
-};
-
-void plotall(MPlot &plot, TString source)
+#include "plotdb.C"
+
+void plotalloptical(MPlot &plot, TString source)
 {
     // Setup here the values for timestamp and secondary (upper/right) plot
@@ -548,9 +92,8 @@
     if (!source.IsNull())
     {
-        const Int_t key = plot.QueryKeyOfSource(source);
+        const Int_t key = plot.GetServer().QueryKeyOfName("Object", source, kFALSE);
         if (key<0)
             return;
         cond += Form(" AND Object.fObjectKEY=%d", key);
-
     }
 
@@ -625,7 +168,5 @@
 int plotoptical(TString from, TString to, const char *source=0)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
@@ -648,5 +189,5 @@
     plot.SetDisplay(d);
     plot.SetRequestRange(from, to);
-    plotall(plot, source);
+    plotalloptical(plot, source);
     // Use this to create output plots automatically
     //  d->SaveAsRoot("plotoptical.root");
@@ -658,7 +199,5 @@
 int plotoptical(const char *source)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
@@ -681,5 +220,5 @@
     plot.SetDisplay(d);
     plot.SetRequestRange("", "");
-    plotall(plot, source);
+    plotalloptical(plot, source);
     // Use this to create output plots automatically
     //  d->SaveAsRoot("plotoptical.root");
@@ -691,7 +230,5 @@
 int plotoptical(Int_t period, const char *source="")
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
@@ -714,5 +251,5 @@
     plot.SetDisplay(d);
     plot.SetRequestPeriod(period);
-    plotall(plot, source);
+    plotalloptical(plot, source);
 
     // Use this to create output plots automatically
Index: /trunk/MagicSoft/Mars/datacenter/macros/plotrundb.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/plotrundb.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/plotrundb.C	(revision 8996)
@@ -1,4 +1,4 @@
 /* ======================================================================== *\
-! $Name: not supported by cvs2svn $:$Id: plotrundb.C,v 1.5 2008-07-03 16:29:48 tbretz Exp $
+! $Name: not supported by cvs2svn $:$Id: plotrundb.C,v 1.6 2008-07-05 19:01:42 tbretz Exp $
 ! --------------------------------------------------------------------------
 !
@@ -111,7 +111,5 @@
 int plotrundb(TString from, TString to, const char *dataset=0)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
@@ -143,7 +141,5 @@
 int plotrundb(const char *ds)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
@@ -175,7 +171,5 @@
 int plotrundb(Int_t period, const char *dataset="")
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/plotstat.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/plotstat.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/plotstat.C	(revision 8996)
@@ -1,4 +1,4 @@
 /* ======================================================================== *\
-! $Name: not supported by cvs2svn $:$Id: plotstat.C,v 1.6 2008-06-19 15:18:57 tbretz Exp $
+! $Name: not supported by cvs2svn $:$Id: plotstat.C,v 1.7 2008-07-05 19:01:42 tbretz Exp $
 ! --------------------------------------------------------------------------
 !
@@ -48,5 +48,4 @@
 
 #include <TH2.h>
-#include <TEnv.h>
 #include <TPad.h>
 #include <TLine.h>
@@ -663,7 +662,5 @@
 int plotstat(Int_t first=-1, Int_t last=-1)
 {
-    TEnv env("sql.rc");
-
-    MSQLServer serv(env);
+    MSQLServer serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/resetallruns.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/resetallruns.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/resetallruns.C	(revision 8996)
@@ -49,9 +49,8 @@
 #include <fstream>
 
-#include <TEnv.h>
-
-#include <MSQLServer.h>
 #include <TSQLRow.h>
 #include <TSQLResult.h>
+
+#include "MSQLServer.h"
 
 using namespace std;
@@ -60,7 +59,5 @@
 int resetallruns(TString filename, TString column)
 {
-    TEnv env("sql.rc");
-
-    MSQLServer serv(env);
+    MSQLServer serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/datacenter/macros/setstatus.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/setstatus.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/setstatus.C	(revision 8996)
@@ -18,5 +18,5 @@
 !   Author(s): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
 !
-!   Copyright: MAGIC Software Development, 2000-2006
+!   Copyright: MAGIC Software Development, 2000-2008
 !
 !
@@ -50,5 +50,4 @@
 //
 /////////////////////////////////////////////////////////////////////////////
-
 #include <iostream>
 #include <iomanip>
@@ -56,10 +55,9 @@
 
 #include <TEnv.h>
-
-#include <MTime.h>
-
-#include <MSQLServer.h>
 #include <TSQLRow.h>
 #include <TSQLResult.h>
+
+#include "MTime.h"
+#include "MSQLServer.h"
 
 using namespace std;
Index: /trunk/MagicSoft/Mars/datacenter/macros/writedatasetfile.C
===================================================================
--- /trunk/MagicSoft/Mars/datacenter/macros/writedatasetfile.C	(revision 8995)
+++ /trunk/MagicSoft/Mars/datacenter/macros/writedatasetfile.C	(revision 8996)
@@ -1,4 +1,4 @@
 /* ======================================================================== *\
-! $Name: not supported by cvs2svn $:$Id: writedatasetfile.C,v 1.2 2007-01-12 17:33:10 snruegam Exp $
+! $Name: not supported by cvs2svn $:$Id: writedatasetfile.C,v 1.3 2008-07-05 19:01:43 tbretz Exp $
 ! --------------------------------------------------------------------------
 !
@@ -20,5 +20,5 @@
 !   Author(s): Thomas Bretz, 11/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
 !
-!   Copyright: MAGIC Software Development, 2000-2006
+!   Copyright: MAGIC Software Development, 2000-2008
 !
 !
@@ -50,5 +50,4 @@
 #include <TSQLResult.h>
 
-#include <TEnv.h>
 #include <errno.h>
 
@@ -91,6 +90,5 @@
     //get sequence information from database
     TString query0(Form("SELECT fSourceName, fComment, fDataSetName, fRunTime, fObservationModeKEY"
-                       " FROM DataSets LEFT JOIN Source ON"
-                       " Source.fSourceKEY=DataSets.fSourceKEY"
+                       " FROM DataSets LEFT JOIN Source USING (fSourceKEY)"
                        " WHERE fDataSetNumber=%d", dsno));
 
@@ -167,7 +165,5 @@
 int writedatasetfile(Int_t dsno, TString seqpath)
 {
-    TEnv env("sql.rc");
-
-    MSQLMagic serv(env);
+    MSQLMagic serv("sql.rc");
     if (!serv.IsConnected())
     {
Index: /trunk/MagicSoft/Mars/mbase/MTime.cc
===================================================================
--- /trunk/MagicSoft/Mars/mbase/MTime.cc	(revision 8995)
+++ /trunk/MagicSoft/Mars/mbase/MTime.cc	(revision 8996)
@@ -138,4 +138,20 @@
 // --------------------------------------------------------------------------
 //
+// Return date as year(y), month(m), day(d). If the time is afternoon
+// (>=13:00:00) the date of the next day is returned.
+//
+MTime MTime::GetDateOfSunrise() const
+{
+    UShort_t y;
+    Byte_t m;
+    Byte_t d;
+
+    MAstro::Mjd2Ymd(fMjd, y, m, d);
+
+    return MTime(y, m, d);
+}
+
+// --------------------------------------------------------------------------
+//
 // GetMoonPhase - calculate phase of moon as a fraction:
 //  Returns -1 if calculation failed
@@ -167,5 +183,5 @@
 //   53257.8 --> 53258
 //   53258.3 --> 53258
-// Which is the time between 13h and 12:59h of the following day. To
+ // Which is the time between 13h and 12:59h of the following day. To
 // this day-period we assign the moon-period at midnight. To get
 // the MAGIC definition we now substract 284.
Index: /trunk/MagicSoft/Mars/mbase/MTime.h
===================================================================
--- /trunk/MagicSoft/Mars/mbase/MTime.h	(revision 8995)
+++ /trunk/MagicSoft/Mars/mbase/MTime.h	(revision 8996)
@@ -117,4 +117,5 @@
     TString  GetFileName() const;
     void     GetDate(UShort_t &y, Byte_t &m, Byte_t &d) const;
+    MTime    GetDateOfSunrise() const;
     void     GetDateOfSunrise(UShort_t &y, Byte_t &m, Byte_t &d) const;
     TTime    GetRootTime() const;
Index: /trunk/MagicSoft/Mars/mhflux/MHAlpha.cc
===================================================================
--- /trunk/MagicSoft/Mars/mhflux/MHAlpha.cc	(revision 8995)
+++ /trunk/MagicSoft/Mars/mhflux/MHAlpha.cc	(revision 8996)
@@ -780,5 +780,5 @@
         delete pad->GetPad(2);
 
-    if (fTimeEffOn && fTime || fHTime.GetNbinsX()>1 || fHTime.GetBinContent(1)!=0)
+    if (fTimeEffOn && fTime || fHTime.GetNbinsX()>1 || fHTime.GetBinError(1)>0)
     {
         pad->cd(3);
Index: /trunk/MagicSoft/Mars/mimage/MHHillas.cc
===================================================================
--- /trunk/MagicSoft/Mars/mimage/MHHillas.cc	(revision 8995)
+++ /trunk/MagicSoft/Mars/mimage/MHHillas.cc	(revision 8996)
@@ -109,5 +109,5 @@
     bins.Apply(*fSize);
 
-    fCenter = new TH2F("Center", "Center of Ellipse", 51, -445, 445, 51, -445, 445);
+    fCenter = new TH2F("Center", "Center of gravity", 51, -445, 445, 51, -445, 445);
     fCenter->SetDirectory(NULL);
     fCenter->SetXTitle("x [mm]");
Index: /trunk/MagicSoft/Mars/mjobs/JobsLinkDef.h
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/JobsLinkDef.h	(revision 8995)
+++ /trunk/MagicSoft/Mars/mjobs/JobsLinkDef.h	(revision 8996)
@@ -6,4 +6,5 @@
 
 #pragma link C++ class MSequence+;
+#pragma link C++ class MSequenceSQL+;
 #pragma link C++ class MDataSet+;
 
Index: /trunk/MagicSoft/Mars/mjobs/MSequence.cc
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MSequence.cc	(revision 8995)
+++ /trunk/MagicSoft/Mars/mjobs/MSequence.cc	(revision 8996)
@@ -171,5 +171,5 @@
 //
 /////////////////////////////////////////////////////////////////////////////
-#include "MSequence.h"
+#include "MSequenceSQL.h"
 
 #include <stdlib.h>
@@ -575,9 +575,8 @@
 // --------------------------------------------------------------------------
 //
-// Get LightCondition from resource file and convert it to LIghtCondition_t
-//
-MSequence::LightCondition_t MSequence::ReadLightCondition(TEnv &env, const char *prefix) const
-{
-    TString str = GetEnvValue2(env, prefix, "LightConditions", "n/a");
+// Get LightCondition from str and convert it to LightCondition_t
+//
+MSequence::LightCondition_t MSequence::GetLightCondition(const TString &str) const
+{
     if (!str.CompareTo("n/a", TString::kIgnoreCase))
         return kNA;
@@ -634,9 +633,11 @@
     fPeriod    = GetEnvValue2(env, prefix, "Period",    -1);
 
-    fLightCondition = ReadLightCondition(env, prefix);
-
     TString str;
+    str = GetEnvValue2(env, prefix, "LightConditions", "n/a");
+    fLightCondition = GetLightCondition(str);
+
     str = GetEnvValue2(env, prefix, "Start", "");
     fStart.SetSqlDateTime(str);
+
     str = GetEnvValue2(env, prefix, "Night", "");
     str += " 00:00:00";
@@ -667,4 +668,9 @@
         env.PrintUntouched();
     }
+}
+
+MSequence::MSequence(const char *fname, UInt_t seq)
+{
+    *this = MSequenceSQL(fname, seq);
 }
 
@@ -875,6 +881,8 @@
         return;
     }
-    out << "# Path: " << GetFileName() << endl;
-    out << "# Name: " << GetBaseName() << endl;
+    if (!fFileName.IsNull())
+        out << "# FileName: " << fFileName << endl;
+    if (!fDataPath.IsNull())
+        out << "# DataPath: " << fDataPath << endl;
     out << endl;
     if (pre.IsNull())
@@ -885,5 +893,5 @@
         out << pre << "Period:         " << fPeriod << endl;
     if (fNight!=MTime())
-        out << pre << "Night:          " << fNight << endl;
+        out << pre << "Night:          " << fNight.GetStringFmt("%Y-%m-%d") << endl;
     out << endl;
     out << pre << "LightCondition: ";
@@ -894,9 +902,9 @@
     case kTwilight: out << "Twilight" << endl; break;
     case kMoon:     out << "Moon" << endl;     break;
-    case kDay:      out << "Day" << endl;     break;
+    case kDay:      out << "Day" << endl;      break;
     }
 
     if (fStart!=MTime())
-        out << pre << "Start:          " << fStart << endl;
+        out << pre << "Start:          " << fStart.GetSqlDateTime() << endl;
     if (fLastRun>=0)
         out << pre << "LastRun:        " << fLastRun << endl;
Index: /trunk/MagicSoft/Mars/mjobs/MSequence.h
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MSequence.h	(revision 8995)
+++ /trunk/MagicSoft/Mars/mjobs/MSequence.h	(revision 8996)
@@ -14,4 +14,5 @@
 class MSequence : public MParContainer
 {
+    friend class MSequenceSQL;
 public:
     enum LightCondition_t { kNA, kNoMoon, kTwilight, kMoon, kDay };
@@ -67,5 +68,5 @@
     void    Split(const TEnv &env, const TString &prefix, const char *name, TArrayI &data, TArrayI &sub) const;
 
-    LightCondition_t ReadLightCondition(TEnv &env, const char *prefix) const;
+    LightCondition_t GetLightCondition(const TString &str) const;
 
     // Helper for file setup
@@ -92,5 +93,5 @@
 public:
     MSequence() : fSequence((UInt_t)-1), fLastRun((UInt_t)-1),
-        fNumEvents((UInt_t)-1), fPeriod((UInt_t)-1), fMonteCarlo(kFALSE)
+        fNumEvents((UInt_t)-1), fPeriod((UInt_t)-1), fLightCondition(kNA), fMonteCarlo(kFALSE)
     {
         fName  = "MSequence";
@@ -98,12 +99,17 @@
     }
     MSequence(const char *fname, const char *path="", UInt_t id=(UInt_t)-1);
+    MSequence(const char *fname, UInt_t seq);
     MSequence(const MSequence &s) : MParContainer(s),
         fFileName(s.fFileName), fDataPath(s.fDataPath),
         fSequence(s.fSequence), fStart(s.fStart),
         fLastRun(s.fLastRun), fNumEvents(s.fNumEvents), fPeriod(s.fPeriod),
-        fNight(s.fNight), fProject(s.fProject), fSource(s.fSource),
+        fNight(s.fNight), fLightCondition(s.fLightCondition),
+        fProject(s.fProject), fSource(s.fSource),
         fTriggerTable(s.fTriggerTable), fHvSettings(s.fHvSettings),
-        fRuns(s.fRuns), fCalRuns(s.fCalRuns), fPedRuns(s.fPedRuns),
-        fDatRuns(s.fDatRuns), fMonteCarlo(s.fMonteCarlo) { }
+        fRuns(s.fRuns), fRunsSub(s.fRunsSub), fCalRuns(s.fCalRuns),
+        fCalRunsSub(s.fCalRunsSub), fPedRuns(s.fPedRuns),
+        fPedRunsSub(s.fPedRunsSub), fDatRuns(s.fDatRuns),
+        fDatRunsSub(s.fDatRunsSub), fExclRuns(s.fExclRuns),
+        fExclRunsSub(s.fExclRunsSub), fMonteCarlo(s.fMonteCarlo) { }
 
     // I/O
Index: /trunk/MagicSoft/Mars/mjobs/MSequenceSQL.cc
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MSequenceSQL.cc	(revision 8996)
+++ /trunk/MagicSoft/Mars/mjobs/MSequenceSQL.cc	(revision 8996)
@@ -0,0 +1,336 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 7/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSequenceSQL
+//
+// This is an extension to retrieve a sequence from a database instead
+// of readin it from a file
+//
+// Example 1:
+//    MSQLMagic serv("sql.rc");
+//    MSequenceSQL s(serv, 100002))
+//    if (s.IsValid())
+//        s.Print();
+//
+// Example 2:
+//    MSequenceSQL s("sql.rc", 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+// Example 2:
+//    MSequence s = MSequenceSQL("sql.rc", 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+// Instead of initializing the constructor directly you can
+// also use the function GetFromDatabase.
+//
+// Instead of a resource file sql.rc you can also give the qualified
+// path to the database:
+//
+//    mysql://user:password@url/database
+//
+//
+// This tool will work from Period017 (2004_05_17) on...
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSequenceSQL.h"
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MLogManip.h"
+
+#include "MSQLMagic.h"
+
+ClassImp(MSequenceSQL);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// get the list of runs according to the query. Add the runs to run-list
+// according to the type. Stop adding runs if the given number of events
+// is exceeded.
+//
+// return kFALSE in case of error or if no events are in the files.
+//
+Bool_t MSequenceSQL::GetRuns(MSQLMagic &serv, TString query, char type, UInt_t nevts)
+{
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    UInt_t cnt=0;
+    UInt_t evts=0;
+
+    TSQLRow *row=0;
+    while ((row = res->Next()) && evts<nevts)
+    {
+        AddFile(atoi((*row)[0]), 0, type);
+        evts += atoi((*row)[1]);
+        cnt++;
+    }
+
+    delete res;
+
+    if (cnt==0)
+    {
+        *fLog << err << "ERROR - No " << type << " belonging to this sequence found." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get start and stop time as requested and return stop time if start
+// time is invalid. Return a null string in case of an error or no valid time.
+//
+TString MSequenceSQL::GetTimeFromDatabase(MSQLMagic &serv, const TString &query)
+{
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return "";
+
+    // FIXME: Check for the right number of results?
+
+    TSQLRow *row=res->Next();
+
+    const TString start = (*row)[0] ? (*row)[0] : "";
+    const TString stop  = (*row)[1] ? (*row)[1] : "";
+
+    delete res;
+
+    if (!start.IsNull())
+        return start;
+
+    *fLog << warn << "WARNING - Requesting start time of first calibration run failed." << endl;
+
+    if (!stop.IsNull())
+        return stop;
+
+    *fLog << err << "ERROR - Neither start nor stop time of first calibration could be requested." << endl;
+    return "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert the result into the MSequence data members
+//
+Bool_t MSequenceSQL::GetFromDatabase(MSQLMagic &serv, TSQLRow &data)
+{
+    // Convert the keys from the sequence table to strings
+    TString str[6];
+    str[0] = serv.QueryNameOfKey("Project",         data[1]);
+    str[1] = serv.QueryNameOfKey("Source",          data[2]);
+    str[2] = serv.QueryNameOfKey("L1TriggerTable",  data[3]);
+    str[3] = serv.QueryNameOfKey("L2TriggerTable",  data[4]);
+    str[4] = serv.QueryNameOfKey("HvSettings",      data[5]);
+    str[5] = serv.QueryNameOfKey("LightConditions", data[6]);
+
+    // check that all strings are valid
+    if (str[0].IsNull() || str[1].IsNull() || str[2].IsNull() || str[3].IsNull() || str[4].IsNull() || str[5].IsNull())
+        return kFALSE;
+
+    // Setup the time and night
+    MTime time;
+    time.SetSqlDateTime(data[7]);
+    MTime night = time.GetDateOfSunrise();
+
+    SetNight(night.GetStringFmt("%Y-%m-%d"));
+
+    // set the other values
+    fStart         = time;
+    fLastRun       = atoi(data[0]);
+    fNumEvents     = atoi(data[8]);
+    fProject       = str[0];
+    fSource        = str[1];
+    fTriggerTable  = str[2]+":"+str[3];
+    fHvSettings    = str[4];
+    fLightCondition = GetLightCondition(str[5]);
+
+    // MISSING: ---> ZdMin, ZdMax, fComment, fMonteCarlo <---
+
+    // Now prepare queries to request the runs from the database
+    TString where(Form(" FROM RunData WHERE fSequenceFirst=%d AND fExcludedFDAKEY=1"
+                       " AND fRunTypeKEY%%s", fSequence));
+
+    const TString query1(Form("SELECT fRunNumber, fNumEvents %s", where.Data()));
+    const TString query2(Form("SELECT fRunStart, fRunStop %s", where.Data()));
+
+    const TString queryA(Form(query1.Data(), " BETWEEN 2 AND 4 ORDER BY fRunNumber"));
+    const TString queryC(Form(query1.Data(), "=4 ORDER BY fRunNumber"));
+    const TString queryD(Form(query1.Data(), "=2 ORDER BY fRunNumber"));
+    const TString queryT(Form(query2.Data(), "=4 ORDER BY fRunNumber LIMIT 1"));
+
+    // Try to get a valid time for the first calibration run
+    const TString timec = GetTimeFromDatabase(serv, queryT);
+    if (timec.IsNull())
+        return kFALSE;
+
+    // Query to get pedestal runs sorted in the order by distance to the cal run
+    const TString query4(Form("=3 ORDER BY ABS(TIME_TO_SEC(TIMEDIFF(fRunStop,'%s'))) ASC", timec.Data()));
+    const TString queryP(Form(query1.Data(), query4.Data()));
+
+    // get and setup runs
+    if (!GetRuns(serv, queryA))
+        return kFALSE;
+    if (!GetRuns(serv, queryC, 'C'))
+        return kFALSE;
+    if (!GetRuns(serv, queryP, 'P', 1000))
+        return kFALSE;
+    if (!GetRuns(serv, queryD, 'D'))
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a wrapper to get rid of the deletion of res in case of error.
+// It also checks that exactly one sequence has been found and all
+// requested column were returned.
+//
+Bool_t MSequenceSQL::GetFromDatabase(MSQLMagic &serv, TSQLResult &res)
+{
+    if (res.GetRowCount()==0)
+    {
+        *fLog << err << "ERROR - Requested Sequence not found in database." << endl;
+        return kFALSE;
+    }
+
+    if (res.GetRowCount()>1)
+    {
+        *fLog << err << "ERROR - Database request returned unexpected number of rows." << endl;
+        return kFALSE;
+    }
+
+    if (res.GetFieldCount()!=11)
+    {
+        *fLog << err << "ERROR - Database request returned unexpected number of rows." << endl;
+        return kFALSE;
+    }
+
+    TSQLRow *row = res.Next();
+
+    return row ? GetFromDatabase(serv, *row) : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the contents of a sequence from the database.
+// The sequence number is given as argument.
+//
+// Example 1:
+//    // Define the database url
+//    MSQLMagic serv("mysql://user:password@url/Database");
+//    MSequenceSQL s;
+//    s.GetFromDatabase(serv, 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+// Example 2:
+//    // Define the database in the resource file
+//    MSQLMagic serv("sql.rc");
+//    MSequenceSQL s;
+//    s.GetFromDatabase(serv, 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+//  In case of error the Sequence is set invalid and kFALSE is returned,
+//  kTrue in case of success.
+//
+Bool_t MSequenceSQL::GetFromDatabase(MSQLMagic &serv, Int_t sequno)
+{
+    // Check if we are connected to the sql server
+    if (!serv.IsConnected())
+    {
+        *fLog << err << "ERROR - No connection to database in GetSeqFromDatabase." << endl;
+        return kFALSE;
+    }
+
+    // check if any sequence number os avlid
+    if (sequno<0 && fSequence<0)
+    {
+        *fLog << err << "ERROR - No sequence number given in GetSeqFromDatabase." << endl;
+        return kFALSE;
+    }
+
+    // set "filename" and sequence number
+    fFileName = serv.GetName();
+    if (sequno>=0)
+        fSequence = sequno;
+
+    // get sequence information from database
+    TString query("SELECT fSequenceLast, fProjectKEY, fSourceKEY,"
+                  " fL1TriggerTableKEY, fL2TriggerTableKEY, fHvSettingsKEY, "
+                  " fLightConditionsKEY, fRunStart, fNumEvents, "
+                  " fZenithDistanceMin, fZenithDistanceMax "
+                  " FROM Sequences WHERE fSequenceFirst=");
+    query += fSequence;
+
+    // Request information from database
+    TSQLResult *res = serv.Query(query);
+    const Bool_t rc = GetFromDatabase(serv, *res);
+    delete res;
+
+    // invalidate sequence if retrieval failed
+    if (!rc)
+        fSequence = (UInt_t)-1;
+
+    // return result
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the contents of a sequence from the database.
+// The sequence number is given as argument.
+//
+// Example 1:
+//    // Define the database url
+//    MSequenceSQL s;
+//    s.GetFromDatabase("mysql://user:password@url/Database", 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+// Example 2:
+//    // Define the database in the resource file
+//    MSequenceSQL s;
+//    s.GetFromDatabase("sql.rc", 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+//  In case of error the Sequence is set invalid and kFALSE is returned,
+//  kTrue in case of success.
+//
+Bool_t MSequenceSQL::GetFromDatabase(const char *rc, Int_t sequno)
+{
+    MSQLMagic serv(rc);
+    return GetFromDatabase(serv, sequno);
+}
Index: /trunk/MagicSoft/Mars/mjobs/MSequenceSQL.h
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MSequenceSQL.h	(revision 8996)
+++ /trunk/MagicSoft/Mars/mjobs/MSequenceSQL.h	(revision 8996)
@@ -0,0 +1,33 @@
+#ifndef MARS_MSequenceSQL
+#define MARS_MSequenceSQL
+
+#ifndef MARS_MSequence
+#include "MSequence.h"
+#endif
+
+class TSQLRow;
+class TSQLResult;
+
+class MSQLMagic;
+
+class MSequenceSQL : public MSequence
+{
+private:
+    Bool_t  GetRuns(MSQLMagic &serv, TString query, char type='*', UInt_t nevts=(UInt_t)-1);
+    TString GetTimeFromDatabase(MSQLMagic &serv, const TString &query);
+    Bool_t  GetFromDatabase(MSQLMagic &serv, TSQLResult &res);
+    Bool_t  GetFromDatabase(MSQLMagic &serv, TSQLRow &data);
+
+public:
+    MSequenceSQL(MSQLMagic &serv, Int_t seqno=-1)  { GetFromDatabase(serv, seqno); }
+    MSequenceSQL(const char *rc, Int_t seqno=-1)   { GetFromDatabase(rc, seqno); }
+    MSequenceSQL(Int_t seqno=-1)                   { GetFromDatabase(seqno); }
+
+    Bool_t GetFromDatabase(MSQLMagic &serv, Int_t seqno=-1);
+    Bool_t GetFromDatabase(const char *rc, Int_t seqno=-1);
+    Bool_t GetFromDatabase(Int_t seqno=-1) { return GetFromDatabase("sql.rc", seqno); }
+
+    ClassDef(MSequenceSQL, 0) // Extension of MSequence to get a sequence from a database
+};
+
+#endif
Index: /trunk/MagicSoft/Mars/mjobs/Makefile
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/Makefile	(revision 8995)
+++ /trunk/MagicSoft/Mars/mjobs/Makefile	(revision 8996)
@@ -24,7 +24,8 @@
            -I../mtools -I../mimage -I../mpointing -I../mastro -I../mfbase \
            -I../mhvstime -I../mtrigger -I../mmuon -I../mmc -I../mmovie \
-           -I../mextralgo -I../mhflux
+           -I../mextralgo -I../mhflux -I../msql
 
 SRCFILES = MSequence.cc \
+           MSequenceSQL.cc \
            MDataSet.cc \
            MJob.cc \
Index: /trunk/MagicSoft/Mars/msql/MSQLMagic.cc
===================================================================
--- /trunk/MagicSoft/Mars/msql/MSQLMagic.cc	(revision 8995)
+++ /trunk/MagicSoft/Mars/msql/MSQLMagic.cc	(revision 8996)
@@ -187,7 +187,13 @@
 }
 
-Bool_t MSQLMagic::ExistStr(const char *column, const char *table, const char *test)
-{
-    TString query(Form("SELECT %s FROM %s WHERE %s='%s'", column, table, column, test));
+// --------------------------------------------------------------------------
+//
+// Check if the column of an entry in a table is existing and not null.
+// The entry is defined by column=test (column name) and a optional
+// WHERE statement.
+//
+Bool_t MSQLMagic::ExistStr(const char *column, const char *table, const char *test, const char *where)
+{
+    TString query(Form("SELECT %s FROM %s WHERE %s='%s' %s %s", column, table, column, test, where?"AND":"", where?where:""));
     TSQLResult *res = Query(query);
     if (!res)
Index: /trunk/MagicSoft/Mars/msql/MSQLMagic.h
===================================================================
--- /trunk/MagicSoft/Mars/msql/MSQLMagic.h	(revision 8995)
+++ /trunk/MagicSoft/Mars/msql/MSQLMagic.h	(revision 8996)
@@ -44,5 +44,5 @@
     Int_t   QueryKeyOfVal(const char *col, const char *val);
     Int_t   QueryKeyOf(const char *col, const char *ext, const char *val);
-    Bool_t  ExistStr(const char *column, const char *table, const char *test);
+    Bool_t  ExistStr(const char *column, const char *table, const char *test, const char *where=0);
 
     Int_t Insert(const char *table, const char *vars, const char *where=0);
Index: /trunk/MagicSoft/Mars/msql/MSQLServer.cc
===================================================================
--- /trunk/MagicSoft/Mars/msql/MSQLServer.cc	(revision 8995)
+++ /trunk/MagicSoft/Mars/msql/MSQLServer.cc	(revision 8996)
@@ -1,4 +1,4 @@
 /* ======================================================================== *\
-! $Name: not supported by cvs2svn $:$Id: MSQLServer.cc,v 1.15 2008-06-02 08:46:49 tbretz Exp $
+! $Name: not supported by cvs2svn $:$Id: MSQLServer.cc,v 1.16 2008-07-05 18:57:35 tbretz Exp $
 ! --------------------------------------------------------------------------
 !
@@ -668,15 +668,29 @@
 }
 
+// --------------------------------------------------------------------------
+//
+// Instantiate a dabase connection either by
+//   mysql://user:password@url/database
+// or by a resource file (in teh given string doesn't contain mysql://)
+//
 MSQLServer::MSQLServer(const char *u) : fType(kIsZombie) /*FOLD00*/
 {
-    TString url(u);
-    TString user, pasw;
-
-    if (!Split(url, user, pasw))
-    {
-        fType = kIsZombie;
-        return;
-    }
-    Init(url, user, pasw);
+    if (TString(u).Contains("mysql://", TString::kIgnoreCase))
+    {
+        TString url(u);
+        TString user, pasw;
+
+        if (!Split(url, user, pasw))
+        {
+            fType = kIsZombie;
+            return;
+        }
+        Init(url, user, pasw);
+    }
+    else
+    {
+        TEnv env(u);
+        InitEnv(env);
+    }
 }
 
@@ -781,6 +795,7 @@
         if (key=="PRI")
         {
-            rc = (*row)[0];
-            break;
+            if (!rc.IsNull())
+                rc += ", ";
+            rc += (*row)[0];
         }
         delete row;
@@ -823,5 +838,5 @@
 
         const TString tab = expr(0, expr.First('.'));
-        const TString var = expr(expr.First('.')+1, expr.Length());
+        //const TString var = expr(expr.First('.')+1, expr.Length());
 
         // If the table found is the primary table itself skip it.
@@ -838,6 +853,5 @@
             continue;
 
-        joins += Form("LEFT JOIN %s ON %s.%s=%s.%s ", tab.Data(),
-                      table, prim.Data(), tab.Data(), prim.Data());
+        joins += Form("LEFT JOIN %s USING (%s) ", tab.Data(), prim.Data());
     }
 
Index: /trunk/MagicSoft/Mars/mtools/MCalendar.cc
===================================================================
--- /trunk/MagicSoft/Mars/mtools/MCalendar.cc	(revision 8995)
+++ /trunk/MagicSoft/Mars/mtools/MCalendar.cc	(revision 8996)
@@ -262,4 +262,5 @@
 #include <TPaveText.h>
 #include <THashList.h>
+#include <TObjArray.h>
 
 #include "MEnv.h"
