Index: /trunk/MagicSoft/Mars/macros/readraw.C
===================================================================
--- /trunk/MagicSoft/Mars/macros/readraw.C	(revision 4608)
+++ /trunk/MagicSoft/Mars/macros/readraw.C	(revision 4609)
@@ -16,7 +16,7 @@
 !
 !
-!   Author(s): Thomas Bretz  12/2000 (tbretz@uni-sw.gwdg.de)
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
 !
-!   Copyright: MAGIC Software Development, 2000-2001
+!   Copyright: MAGIC Software Development, 2000-2004
 !
 !
@@ -24,10 +24,10 @@
 
 
-void readraw()
+void readraw(const char *fname="/data/MAGIC/Period016/mcdata/spot_1cm/standard/gamma/Gamma_zbin9_90_7_1740to1749_w0.root")
 {
     //
     // open the file
     //
-    TFile input("test.root", "READ");
+    TFile input(fname, "READ");
 
     //
@@ -46,5 +46,5 @@
     //
     MRawRunHeader *runheader = new MRawRunHeader();
-    runtree->GetBranch("MRawRunHeader")->SetAddress(&runheader);
+    runtree->GetBranch("MRawRunHeader.")->SetAddress(&runheader);
     runtree->GetEvent(0);
     runheader->Print();
@@ -53,21 +53,23 @@
     // open the Data Tree
     //
-    TTree *evttree = (TTree*) input.Get("Data") ;
+    TTree *evttree = (TTree*) input.Get("Events");
 
     //
     // create the instances of the data to read in
     //
-    MRawEvtHeader  *evtheader = new MRawEvtHeader();
-    MTime          *evttime   = new MTime();
-    MRawEvtData    *evtdata   = new MRawEvtData();
-    MRawCrateArray *evtcrate  = new MRawCrateArray();
+    MRawEvtHeader  *evtheader = 0;
+    MTime          *evttime   = 0;
+    MRawEvtData    *evtdata   = 0;
+    MRawCrateArray *evtcrate  = 0;
 
     //
     // enable the corresponding branches
     //
-    evttree->GetBranch("MRawEvtHeader")->SetAddress(&evtheader);
-    evttree->GetBranch("MTime")->SetAddress(&evttime);
-    evttree->GetBranch("MRawEvtData")->SetAddress(&evtdata);
-    evttree->GetBranch("MRawCrateArray")->SetAddress(&evtcrate);
+    evttree->GetBranch("MRawEvtHeader.")->SetAddress(&evtheader);
+    evttree->GetBranch("MRawEvtData.")->SetAddress(&evtdata);
+
+    // Use this for real data only
+    //evttree->GetBranch("MTime.")->SetAddress(&evttime);
+    //evttree->GetBranch("MRawCrateArray.")->SetAddress(&evtcrate);
 
     //
@@ -83,7 +85,9 @@
 
       evtheader->Print();
-      evttime->Print();
-      evtcrate->Print();
       evtdata->Print();
+
+      // Use this for real data only
+      //evttime->Print();
+      //evtcrate->Print();
     } 
 }
Index: /trunk/MagicSoft/Mars/mbase/MTaskEnv.cc
===================================================================
--- /trunk/MagicSoft/Mars/mbase/MTaskEnv.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mbase/MTaskEnv.cc	(revision 4609)
@@ -172,5 +172,5 @@
     if (!fTask)
     {
-        *fLog << err << GetDescriptor() << " - ERROR: Not task setup." << endl;
+        *fLog << err << GetDescriptor() << " - ERROR: No task setup." << endl;
         return kFALSE;
     }
Index: /trunk/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.cc
===================================================================
--- /trunk/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.cc	(revision 4609)
@@ -1524,7 +1524,8 @@
         }
 
-      *fLog << inf << GetDescriptor() << ": Mean overall F-Factor (photons to FADC counts) " 
-            << "with area index: " << i << ": " 
-            << Form("%4.2f+-%4.2f",mean,sigma) << endl;
+      *fLog << inf << endl;
+      *fLog << inf << GetDescriptor() << ": Mean F-Factor " 
+          << "with area index #" << i << ": "
+            << Form("%4.2f+-%4.2f",mean,sigma) << "fadc/ph" << endl;
 
       lowlim  [i] = 1.1;
@@ -1550,7 +1551,8 @@
       if ( ffactor < lowlim[aidx] || ffactor > upplim[aidx] )
         {
-          *fLog << warn << GetDescriptor() << ": Overall F-Factor: " 
-                << Form("%5.2f out of %3.1f sigma limit: ",ffactor,fFFactorErrLimit)
-                << Form("[%5.2f,%5.2f] pixel %4i",lowlim[aidx],upplim[aidx],i) << endl;
+          *fLog << warn << GetDescriptor() << ": Overall F-Factor "
+                << Form("%5.2f",ffactor) << " out of range ["
+                << Form("%5.2f,%5.2f",lowlim[aidx],upplim[aidx]) << "] pixel " << i << endl;
+
           bad.SetUncalibrated( MBadPixelsPix::kDeviatingFFactor );
           bad.SetUnsuitable  ( MBadPixelsPix::kUnsuitableRun    );
@@ -1857,2 +1859,52 @@
   return Form("%s/%s", (const char*)fOutputPath, (const char*)fOutputFile);
 }
+
+Int_t MCalibrationChargeCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "ChargeLimit", print))
+    {
+        SetChargeLimit(GetEnvValue(env, prefix, "ChargeLimit", fChargeLimit));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "ChargeErrLimit", print))
+    {
+        SetChargeErrLimit(GetEnvValue(env, prefix, "ChargeErrLimit", fChargeErrLimit));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "ChargeRelErrLimit", print))
+    {
+        SetChargeRelErrLimit(GetEnvValue(env, prefix, "ChargeRelErrLimit", fChargeRelErrLimit));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Debug", print))
+    {
+        SetDebug(GetEnvValue(env, prefix, "Debug", IsDebug()));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "FFactorErrLimit", print))
+    {
+        SetFFactorErrLimit(GetEnvValue(env, prefix, "FFactorErrLimit", fFFactorErrLimit));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LambdaErrLimit", print))
+    {
+        SetLambdaErrLimit(GetEnvValue(env, prefix, "LambdaErrLimit", fLambdaErrLimit));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LambdaCheckLimit", print))
+    {
+        SetLambdaCheckLimit(GetEnvValue(env, prefix, "LambdaCheckLimit", fLambdaCheckLimit));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "PheErrLimit", print))
+    {
+        SetPheErrLimit(GetEnvValue(env, prefix, "PheErrLimit", fPheErrLimit));
+        rc = kTRUE;
+    }
+    // void SetPulserColor(const MCalibrationCam::PulserColor_t col) { fPulserColor = col; }
+
+    return rc;
+}
Index: /trunk/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.h
===================================================================
--- /trunk/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.h	(revision 4609)
@@ -127,4 +127,5 @@
   Int_t  Process    ();
   Int_t  PostProcess();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
 
 public:
Index: /trunk/MagicSoft/Mars/mcalib/MHCalibrationCam.cc
===================================================================
--- /trunk/MagicSoft/Mars/mcalib/MHCalibrationCam.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mcalib/MHCalibrationCam.cc	(revision 4609)
@@ -1023,2 +1023,13 @@
 }
 
+Int_t MHCalibrationCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Debug", print))
+    {
+        SetDebug(GetEnvValue(env, prefix, "Debug", IsDebug()));
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: /trunk/MagicSoft/Mars/mcalib/MHCalibrationCam.h
===================================================================
--- /trunk/MagicSoft/Mars/mcalib/MHCalibrationCam.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mcalib/MHCalibrationCam.h	(revision 4609)
@@ -109,4 +109,6 @@
   void InitHists(MHGausEvents &hist, MBadPixelsPix &bad, const Int_t i);
 
+  Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
 public:
 
Index: /trunk/MagicSoft/Mars/mjobs/MJCalibration.cc
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MJCalibration.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mjobs/MJCalibration.cc	(revision 4609)
@@ -87,4 +87,5 @@
 #include "MJCalibration.h"
 
+#include <TEnv.h>
 #include <TFile.h>
 #include <TStyle.h>
@@ -96,4 +97,5 @@
 
 #include "MRunIter.h"
+#include "MSequence.h"
 #include "MParList.h"
 #include "MTaskList.h"
@@ -125,4 +127,5 @@
 #include "MRawFileRead.h"
 #include "MGeomApply.h"
+#include "MTaskEnv.h"
 #include "MBadPixelsMerge.h"
 #include "MBadPixelsCam.h"
@@ -158,5 +161,5 @@
 //
 MJCalibration::MJCalibration(const char *name, const char *title) 
-    : fRuns(0), fExtractor(NULL), fTimeExtractor(NULL), 
+    : fEnv(0), fRuns(0), fSequence(0), fExtractor(NULL), fTimeExtractor(NULL),
       fColor(MCalibrationCam::kNONE), fDisplayType(kNormalDisplay),
       fRelTimes(kFALSE), fDataCheck(kFALSE), fDebug(kFALSE)
@@ -171,4 +174,9 @@
 }
 
+MJCalibration::~MJCalibration()
+{
+    if (fEnv)
+        delete fEnv;
+}
 
 // --------------------------------------------------------------------------
@@ -224,5 +232,5 @@
     TString title = fDisplay->GetTitle();
     title += "--  Calibration ";
-    title += fRuns->GetRunsAsString();
+    title += fSequence ? Form("calib%06d", fSequence->GetSequence()) : fRuns->GetRunsAsString();
     title += "  --";
     fDisplay->SetTitle(title);
@@ -234,72 +242,38 @@
 
     // Create histograms to display
-    MHCamera disp1 (geomcam, Form("%s%s","Charge",(fRuns->GetRunsAsFileName()).Data()),
-                    "Fitted Mean Charges");
-    MHCamera disp2 (geomcam, Form("%s%s","SigmaCharge",(fRuns->GetRunsAsFileName()).Data()),
-                    "Sigma of Fitted Charges");
-    MHCamera disp3 (geomcam, Form("%s%s","RSigma",(fRuns->GetRunsAsFileName()).Data()),
-                    "Reduced Sigmas");
-    MHCamera disp4 (geomcam, Form("%s%s","RSigmaPerCharge",(fRuns->GetRunsAsFileName()).Data()),  
-                    "Reduced Sigma per Charge");
-    MHCamera disp5 (geomcam, Form("%s%s","NumPhes",(fRuns->GetRunsAsFileName()).Data()),
-                    "Nr. of Phe's (F-Factor Method)");
-    MHCamera disp6 (geomcam, Form("%s%s","ConvFADC2Phes",(fRuns->GetRunsAsFileName()).Data()),
-                    "Conversion Factor (F-Factor Method)");
-    MHCamera disp7 (geomcam, Form("%s%s","TotalFFactor",(fRuns->GetRunsAsFileName()).Data()),
-                    "Total F-Factor (F-Factor Method)");
-    MHCamera disp8 (geomcam, Form("%s%s","CascadesQEFFactor",(fRuns->GetRunsAsFileName()).Data()),
-                    "Cascades QE (F-Factor Method)");
-    MHCamera disp9 (geomcam, Form("%s%s","CascadesQEBlindPix",(fRuns->GetRunsAsFileName()).Data()),
-                    "Cascades QE (Blind Pixel Method)");
-    MHCamera disp10(geomcam, Form("%s%s","CascadesQEPINDiode",(fRuns->GetRunsAsFileName()).Data()),
-                    "Cascades QE (PIN Diode Method)");
-    MHCamera disp11(geomcam, Form("%s%s","CascadesQECombined",(fRuns->GetRunsAsFileName()).Data()),
-                    "Cascades QE (Combined Method)");
-    MHCamera disp12(geomcam, Form("%s%s","FFactorValid",(fRuns->GetRunsAsFileName()).Data()),
-                    "Pixels with valid F-Factor calibration");
-    MHCamera disp13(geomcam, Form("%s%s","BlindPixelValid",(fRuns->GetRunsAsFileName()).Data()), 
-                    "Pixels with valid BlindPixel calibration");
-    MHCamera disp14(geomcam, Form("%s%s","PINdiodeValid",(fRuns->GetRunsAsFileName()).Data()),
-                    "Pixels with valid PINDiode calibration");
-    MHCamera disp15(geomcam, Form("%s%s","CombinedValid",(fRuns->GetRunsAsFileName()).Data()),
-                    "Pixels with valid Combined calibration");
-    MHCamera disp16(geomcam, Form("%s%s","Saturation",(fRuns->GetRunsAsFileName()).Data()),
-                    "Pixels with saturated Hi Gain");
-    MHCamera disp17(geomcam, Form("%s%s","ConversionMeans",(fRuns->GetRunsAsFileName()).Data()), 
-                    "Conversion HiGain.vs.LoGain Means");
-    MHCamera disp18(geomcam, Form("%s%s","ConversionSigmas",(fRuns->GetRunsAsFileName()).Data()), 
-                    "Conversion HiGain.vs.LoGain Sigmas");
-    MHCamera disp19(geomcam, Form("%s%s","HiGainPickup",(fRuns->GetRunsAsFileName()).Data()),
-                    "Number Pickup events Hi Gain");
-    MHCamera disp20(geomcam, Form("%s%s","LoGainPickup",(fRuns->GetRunsAsFileName()).Data()),
-                    "Number Pickup events Lo Gain");
-    MHCamera disp21(geomcam, Form("%s%s","HiGainBlackout",(fRuns->GetRunsAsFileName()).Data()),
-                    "Number Blackout events Hi Gain");
-    MHCamera disp22(geomcam, Form("%s%s","LoGainBlackout",(fRuns->GetRunsAsFileName()).Data()), 
-                    "Number Blackout events Lo Gain");
-    MHCamera disp23(geomcam, Form("%s%s","Excluded",(fRuns->GetRunsAsFileName()).Data()),
-                    "Pixels previously excluded");
-    MHCamera disp24(geomcam, Form("%s%s","UnSuitable",(fRuns->GetRunsAsFileName()).Data()),
-                    "Pixels not suited for further analysis");
-    MHCamera disp25(geomcam, Form("%s%s","UnReliable",(fRuns->GetRunsAsFileName()).Data()),
-                    "Pixels not reliable for further analysis");
-    MHCamera disp26(geomcam, Form("%s%s","HiGainOscillating",(fRuns->GetRunsAsFileName()).Data()),
-                    "Oscillating Pixels High Gain");
-    MHCamera disp27(geomcam, Form("%s%s","LoGainOscillating",(fRuns->GetRunsAsFileName()).Data()),
-                    "Oscillating Pixels Low Gain");
-    MHCamera disp28(geomcam, Form("%s%s","AbsTimeMean",(fRuns->GetRunsAsFileName()).Data()),
-                    "Abs. Arrival Times");
-    MHCamera disp29(geomcam, Form("%s%s","AbsTimeRms",(fRuns->GetRunsAsFileName()).Data()),
-                    "RMS of Arrival Times");
-    MHCamera disp30(geomcam, Form("%s%s","MeanTime",(fRuns->GetRunsAsFileName()).Data()),
-                    "Mean Rel. Arrival Times");
-    MHCamera disp31(geomcam, Form("%s%s","SigmaTime",(fRuns->GetRunsAsFileName()).Data()),
-                    "Sigma Rel. Arrival Times");
-    MHCamera disp32(geomcam, Form("%s%s","TimeProb",(fRuns->GetRunsAsFileName()).Data()),
-                    "Probability of Time Fit");
-    MHCamera disp33(geomcam, Form("%s%s","TimeNotFitValid",(fRuns->GetRunsAsFileName()).Data()),
-                    "Pixels with not valid fit results");
-    MHCamera disp34(geomcam, Form("%s%s","TimeOscillating",(fRuns->GetRunsAsFileName()).Data()),
-                    "Oscillating Pixels");
+    MHCamera disp1 (geomcam, "Charge",            "Fitted Mean Charges");
+    MHCamera disp2 (geomcam, "SigmaCharge",       "Sigma of Fitted Charges");
+    MHCamera disp3 (geomcam, "RSigma",            "Reduced Sigmas");
+    MHCamera disp4 (geomcam, "RSigmaPerCharge",   "Reduced Sigma per Charge");
+    MHCamera disp5 (geomcam, "NumPhes",           "Nr. of Phe's (F-Factor Method)");
+    MHCamera disp6 (geomcam, "ConvFADC2Phes",     "Conversion Factor (F-Factor Method)");
+    MHCamera disp7 (geomcam, "TotalFFactor",      "Total F-Factor (F-Factor Method)");
+    MHCamera disp8 (geomcam, "CascadesQEFFactor", "Cascades QE (F-Factor Method)");
+    MHCamera disp9 (geomcam, "CascadesQEBlindPix","Cascades QE (Blind Pixel Method)");
+    MHCamera disp10(geomcam, "CascadesQEPINDiode","Cascades QE (PIN Diode Method)");
+    MHCamera disp11(geomcam, "CascadesQECombined","Cascades QE (Combined Method)");
+    MHCamera disp12(geomcam, "FFactorValid",      "Pixels with valid F-Factor calibration");
+    MHCamera disp13(geomcam, "BlindPixelValid",   "Pixels with valid BlindPixel calibration");
+    MHCamera disp14(geomcam, "PINdiodeValid",     "Pixels with valid PINDiode calibration");
+    MHCamera disp15(geomcam, "CombinedValid",     "Pixels with valid Combined calibration");
+    MHCamera disp16(geomcam, "Saturation",        "Pixels with saturated Hi Gain");
+    MHCamera disp17(geomcam, "ConversionMeans",   "Conversion HiGain.vs.LoGain Means");
+    MHCamera disp18(geomcam, "ConversionSigmas",  "Conversion HiGain.vs.LoGain Sigmas");
+    MHCamera disp19(geomcam, "HiGainPickup",      "Number Pickup events Hi Gain");
+    MHCamera disp20(geomcam, "LoGainPickup",      "Number Pickup events Lo Gain");
+    MHCamera disp21(geomcam, "HiGainBlackout",    "Number Blackout events Hi Gain");
+    MHCamera disp22(geomcam, "LoGainBlackout",    "Number Blackout events Lo Gain");
+    MHCamera disp23(geomcam, "Excluded",          "Pixels previously excluded");
+    MHCamera disp24(geomcam, "UnSuitable",        "Pixels not suited for further analysis");
+    MHCamera disp25(geomcam, "UnReliable",        "Pixels not reliable for further analysis");
+    MHCamera disp26(geomcam, "HiGainOscillating", "Oscillating Pixels High Gain");
+    MHCamera disp27(geomcam, "LoGainOscillating", "Oscillating Pixels Low Gain");
+    MHCamera disp28(geomcam, "AbsTimeMean",       "Abs. Arrival Times");
+    MHCamera disp29(geomcam, "AbsTimeRms",        "RMS of Arrival Times");
+    MHCamera disp30(geomcam, "MeanTime",          "Mean Rel. Arrival Times");
+    MHCamera disp31(geomcam, "SigmaTime",         "Sigma Rel. Arrival Times");
+    MHCamera disp32(geomcam, "TimeProb",          "Probability of Time Fit");
+    MHCamera disp33(geomcam, "TimeNotFitValid",   "Pixels with not valid fit results");
+    MHCamera disp34(geomcam, "TimeOscillating",   "Oscillating Pixels");
 
     // Fitted charge means and sigmas
@@ -665,6 +639,11 @@
 Bool_t MJCalibration::FindColor() 
 {
-
-  const UInt_t nruns = fRuns->GetNumRuns();
+    if (fSequence)
+    {
+        fColor = MCalibrationCam::kCT1;
+        return kTRUE;
+    }
+
+const UInt_t nruns = fRuns->GetNumRuns();
 
   if (nruns == 0)
@@ -880,9 +859,7 @@
     }
 
-  return kTRUE;
-}
-
-
-
+
+    return kTRUE;
+}
 
 // --------------------------------------------------------------------------
@@ -892,26 +869,41 @@
 const char* MJCalibration::GetOutputFile() const
 {
-
-  if (!fRuns)
-    return "";
-  
-  return Form("%s/%s-F1.root", (const char*)fOutputPath, (const char*)fRuns->GetRunsAsFileName());
-}
-
+    if (fSequence)
+        return Form("%s/calib%06d.root", (const char*)fOutputPath, fSequence->GetSequence());
+    if (!fRuns)
+        return "";
+
+    return Form("%s/%s-F1.root", (const char*)fOutputPath, (const char*)fRuns->GetRunsAsFileName());
+}
 
 Bool_t MJCalibration::IsUseBlindPixel() const 
 {
-  return TESTBIT(fDevices,kUseBlindPixel);
-}
-
+    return TESTBIT(fDevices,kUseBlindPixel);
+}
 
 Bool_t MJCalibration::IsUsePINDiode() const 
 {
-  return TESTBIT(fDevices,kUsePINDiode);
-}
-
-  
-
-
+    return TESTBIT(fDevices,kUsePINDiode);
+}
+
+void MJCalibration::SetEnv(const char *env)
+{
+    if (fEnv)
+        delete fEnv;
+    fEnv = new TEnv(env);
+}
+
+void MJCalibration::CheckEnv()
+{
+    if (!fEnv)
+        return;
+
+    TString e1 = fEnv->GetValue("MJCalibration.OutputPath", "");
+    if (!e1.IsNull())
+    {
+        e1.ReplaceAll("\015", "");
+        SetOutputPath(e1);
+    }
+}
 
 // --------------------------------------------------------------------------
@@ -925,4 +917,40 @@
 
     return kTRUE;
+}
+
+void MJCalibration::InitBlindPixel(MExtractBlindPixel &blindext,
+                                   MHCalibrationChargeBlindCam &blindcam)
+{
+    Int_t run = fSequence ? fSequence->GetLastRun() : fRuns->GetRuns()[fRuns->GetNumRuns()-1];
+
+    //
+    // Initialize the blind pixel. Unfortunately, there is a hardware difference
+    // in the first blind pixel until run "gkSecondBlindPixelInstallation" and the
+    // later setup. The first needs to use a filter because of the length of
+    // spurious NSB photon signals. The latter get better along extracting the amplitude
+    // from a small window.
+    //
+    if (run < gkSecondBlindPixelInstallation)
+    {
+        blindext.SetModified(kFALSE);
+        blindext.SetExtractionType(MExtractBlindPixel::kIntegral);
+        blindext.SetExtractionType(MExtractBlindPixel::kFilter);
+        blindext.SetRange(10,19,0,6);
+        blindext.SetNSBFilterLimit(70);
+        blindcam.SetFitFunc( MHCalibrationChargeBlindPix::kEPoisson5 );
+    }
+    else
+    {
+        blindext.SetModified(kTRUE);
+        blindext.SetExtractionType(MExtractBlindPixel::kAmplitude);
+        blindext.SetExtractionType(MExtractBlindPixel::kFilter);
+        blindext.SetRange(5,8,0,2);
+        blindext.SetNSBFilterLimit(38);
+
+        if (run < gkThirdBlindPixelInstallation)
+            blindext.SetNumBlindPixels(2);
+        else
+            blindext.SetNumBlindPixels(3);
+    }
 }
 
@@ -965,243 +993,211 @@
 Bool_t MJCalibration::ProcessFile(MPedestalCam &pedcam)
 {
-  if (!fRuns)
-    {
-      *fLog << err << "No Runs choosen... abort." << endl;
-      return kFALSE;
-    }
+    if (!fRuns && !fSequence)
+    {
+        *fLog << err << "No Runs choosen... abort." << endl;
+        return kFALSE;
+    }
+
+    if (!fSequence && fRuns->GetNumRuns() != fRuns->GetNumEntries())
+    {
+        *fLog << err << "Number of files found doesn't match number of runs... abort."
+            << fRuns->GetNumRuns() << " vs. " << fRuns->GetNumEntries() << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+
+    if (!FindColor())
+        return kFALSE;
+
+    *fLog << "Calculate MCalibrationCam from ";
+    if (fSequence)
+        *fLog << "Sequence #" << fSequence->GetSequence() << endl;
+    else
+        *fLog << "Runs " << fRuns->GetRunsAsString() << endl;
+    *fLog << endl;
+
+    // Setup Tasklist
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadMarsFile read("Events");
+    MRawFileRead rawread(NULL);
+
+    MDirIter iter;
+    if (fSequence)
+        fSequence->SetupCalRuns(iter);
+
+    if (fDataCheck)
+    {
+        rawread.AddFiles(fSequence ? iter : *fRuns);
+        tlist.AddToList(&rawread);
+    }
+    else
+    {
+        read.DisableAutoScheme();
+        static_cast<MRead&>(read).AddFiles(fSequence ? iter : *fRuns);
+        tlist.AddToList(&read);
+    }
+
+    MHCalibrationChargeCam      chargecam;
+    MHCalibrationChargeBlindCam blindcam;
+
+    plist.AddToList(&pedcam);
+    plist.AddToList(&chargecam);
+    plist.AddToList(&blindcam);
+    plist.AddToList(&fBadPixels);
+    plist.AddToList(&fQECam);
+    plist.AddToList(&fCalibrationCam);
+    plist.AddToList(&fCalibrationBlindCam);
+    plist.AddToList(&fCalibrationPINDiode);
+    plist.AddToList(&fRelTimeCam);
+
+    MGeomApply               apply;
+    MBadPixelsMerge          merge(&fBadPixels);
+    MExtractPINDiode         pinext;
+    MExtractBlindPixel       blindext;
+    InitBlindPixel(blindext, blindcam);
+    MExtractSlidingWindow    extract2;
+    MExtractTimeFastSpline   timespline;
+    MCalibrationChargeCalc   calcalc;
+    if (!fSequence)
+    {
+        calcalc.SetOutputPath(fOutputPath);
+        calcalc.SetOutputFile(Form("%s-ChargeCalibStat.txt",(const char*)fRuns->GetRunsAsFileName()));
+    }
+
+    if (fDebug)
+    {
+        chargecam.SetDebug();
+        calcalc.SetDebug();
+    }
+
+    //
+    // As long as there are no DM's, have to colour by hand
+    //
+    calcalc.SetPulserColor(fColor);
+
+    MFillH fillpin("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode");
+    MFillH fillbnd("MHCalibrationChargeBlindPix", "MExtractedSignalBlindPixel");
+    MFillH fillcam("MHCalibrationChargeCam",      "MExtractedSignalCam");
+    MFillH filltme("MHCalibrationRelTimeCam",     "MArrivalTimeCam");
+    fillpin.SetNameTab("PINDiode");
+    fillbnd.SetNameTab("BlindPix");
+    fillcam.SetNameTab("Charge");
+    filltme.SetNameTab("RelTimes");
   
-  if (fRuns->GetNumRuns() != fRuns->GetNumEntries())
-    {
-      *fLog << err << "Number of files found doesn't match number of runs... abort." 
-            << fRuns->GetNumRuns() << " vs. " << fRuns->GetNumEntries() << endl;
-      return kFALSE;
-    }
-
-  *fLog << inf;
-  fLog->Separator(GetDescriptor());
-
-  if (!FindColor())
-    return kFALSE;
-  
-  *fLog << "Calculate MCalibrationCam from Runs " << fRuns->GetRunsAsString() << endl;
-  *fLog << endl;
-  
-  // Setup Tasklist
-  MParList plist;
-  MTaskList tlist;
-  plist.AddToList(&tlist);
-  
-  MReadMarsFile read("Events");
-  MRawFileRead rawread(NULL);
-
-  if (fDataCheck)
-  {
-     rawread.AddFiles(*fRuns); 
-     tlist.AddToList(&rawread);
-  }
-  else
-  {
-      read.DisableAutoScheme();
-      static_cast<MRead&>(read).AddFiles(*fRuns);
-      tlist.AddToList(&read);
-  }
-
-  MHCalibrationChargeCam      chargecam;
-  MHCalibrationChargeBlindCam blindcam;
-
-  plist.AddToList(&pedcam);
-  plist.AddToList(&chargecam);  
-  plist.AddToList(&blindcam);  
-  plist.AddToList(&fBadPixels);
-  plist.AddToList(&fQECam);
-  plist.AddToList(&fCalibrationCam);
-  plist.AddToList(&fCalibrationBlindCam);
-  plist.AddToList(&fCalibrationPINDiode);
-  plist.AddToList(&fRelTimeCam);
-
-  MGeomApply               apply;
-  MExtractPINDiode         pinext;
-  MExtractBlindPixel       blindext;
-  
-  //
-  // Initialize the blind pixel. Unfortunately, there is a hardware difference 
-  // in the first blind pixel until run "gkSecondBlindPixelInstallation" and the 
-  // later setup. The first needs to use a filter because of the length of 
-  // spurious NSB photon signals. The latter get better along extracting the amplitude
-  // from a small window.
-  //
-  TArrayI arr = fRuns->GetRuns();
-  if (arr[fRuns->GetNumRuns()-1] < gkSecondBlindPixelInstallation)
-    {
-      blindext.SetModified(kFALSE);
-      blindext.SetExtractionType(MExtractBlindPixel::kIntegral);
-      blindext.SetExtractionType(MExtractBlindPixel::kFilter);
-      blindext.SetRange(10,19,0,6);
-      blindext.SetNSBFilterLimit(70);
-      blindcam.SetFitFunc( MHCalibrationChargeBlindPix::kEPoisson5 );
-    }
-  else
-    {
-      blindext.SetModified(kTRUE);
-      blindext.SetExtractionType(MExtractBlindPixel::kAmplitude);
-      blindext.SetExtractionType(MExtractBlindPixel::kFilter);
-      blindext.SetRange(5,8,0,2);
-      blindext.SetNSBFilterLimit(38);
-      if (arr[fRuns->GetNumRuns()-1] < gkThirdBlindPixelInstallation)
-        blindext.SetNumBlindPixels(2);
-      else
-        blindext.SetNumBlindPixels(3);
-    }
-  
-  MExtractSlidingWindow    extract2;
-  MExtractTimeFastSpline   timespline;
-  MCalibrationChargeCalc   calcalc;
-  calcalc.SetOutputPath(fOutputPath);
-  calcalc.SetOutputFile(Form("%s-ChargeCalibStat.txt",(const char*)fRuns->GetRunsAsFileName()));
-
-  if (fDebug)
-    {
-      chargecam.SetDebug();
-      calcalc.SetDebug();      
-    }
-
-  MCalibrationRelTimeCalc  timecalc;
-  timecalc.SetOutputPath(fOutputPath);
-  timecalc.SetOutputFile(Form("%s-TimeCalibStat.txt",(const char*)fRuns->GetRunsAsFileName()));
-  
-  // 
-  // As long as there are no DM's, have to colour by hand 
-  //
-  calcalc.SetPulserColor(fColor);
-  
-  MFillH fillpin("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode");
-  MFillH fillbnd("MHCalibrationChargeBlindCam", "MExtractedSignalBlindPixel");
-  MFillH fillcam("MHCalibrationChargeCam",      "MExtractedSignalCam");
-  MFillH filltme("MHCalibrationRelTimeCam",     "MArrivalTimeCam");
-  fillpin.SetNameTab("PINDiode");
-  fillbnd.SetNameTab("BlindPix");
-  fillcam.SetNameTab("Charge");
-  filltme.SetNameTab("RelTimes");
-
-  TString drawoption;
-
-  if (fDisplayType == kDataCheckDisplay)
-    drawoption += "datacheck";
-  if (fDisplayType == kFullDisplay)
-    drawoption += " all";
-  
-  fillcam.SetDrawOption(drawoption.Data());
-  fillbnd.SetDrawOption(drawoption.Data());
-  fillpin.SetDrawOption(drawoption.Data());
-  filltme.SetDrawOption(drawoption.Data());
-  // 
-  // Apply a filter against cosmics
-  // (will have to be needed in the future
-  // when the calibration hardware-trigger is working)
-  // 
-  MFCosmics cosmics;
-  MContinue cont(&cosmics);
-  
-  //    tlist.AddToList(&merge);
-  tlist.AddToList(&apply);
-
-  if (fExtractor)
-    tlist.AddToList(fExtractor);
-  else
-    {
-      *fLog << warn << GetDescriptor() 
-            << ": No extractor has been chosen, take default MExtractSlidingWindow " << endl;
-      tlist.AddToList(&extract2);
-    }
-  
-  tlist.AddToList(&pinext);  
-  tlist.AddToList(&blindext);
-  
-  if (fRelTimes)
-    {
-      if (fTimeExtractor)
-        tlist.AddToList(fTimeExtractor);
-      else
+    TString drawoption;
+
+    if (fDisplayType == kDataCheckDisplay)
+        drawoption += "datacheck";
+    if (fDisplayType == kFullDisplay)
+        drawoption += " all";
+
+    fillcam.SetDrawOption(drawoption.Data());
+    fillbnd.SetDrawOption(drawoption.Data());
+    fillpin.SetDrawOption(drawoption.Data());
+    filltme.SetDrawOption(drawoption.Data());
+
+    //
+    // Apply a filter against cosmics
+    // (will have to be needed in the future
+    // when the calibration hardware-trigger is working)
+    //
+    MFCosmics cosmics;
+    MContinue cont(&cosmics);
+
+    tlist.AddToList(&merge);
+    tlist.AddToList(&apply);
+
+    MTaskEnv taskenv("ExtractSignal");
+    taskenv.SetDefault(fExtractor ? fExtractor : &extract2);
+
+    tlist.AddToList(&taskenv);
+    tlist.AddToList(&pinext);
+    tlist.AddToList(&blindext);
+
+    MTaskEnv taskenv2("ExtractTime");
+    taskenv2.SetDefault(fTimeExtractor ? fTimeExtractor : &timespline);
+
+    if (fRelTimes)
+        tlist.AddToList(&taskenv2);
+
+    if (fColor == MCalibrationCam::kCT1)
+        tlist.AddToList(&cont);
+
+    tlist.AddToList(&fillcam);
+    tlist.AddToList(&calcalc);
+
+    MCalibrationRelTimeCalc timecalc;
+    if (fRelTimes)
+    {
+        tlist.AddToList(&filltme);
+        tlist.AddToList(&timecalc);
+    }
+
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (fEnv)
+        evtloop.ReadEnv(*fEnv);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    //
+    // The next lines are necessary in order to avoid that
+    // the last entry drawn by MFillH gets deleted again from
+    // the display. No idea where this comes from...
+    //
+    /*
+    if (fDisplay)
+    {
+        if (IsUsePINDiode())
         {
-          *fLog << warn << GetDescriptor() 
-                << ": No extractor has been chosen, take default MTimeExtractSpline " << endl;
-          tlist.AddToList(&timespline);
+            MHCalibrationChargePINDiode *pin =
+                (MHCalibrationChargePINDiode*)plist.FindObject("MHCalibrationChargePINDiode");
+            pin->DrawClone(Form("nonew %s",drawoption.Data()));
         }
-    }
-
-  if (fColor == MCalibrationCam::kCT1)
-    tlist.AddToList(&cont);
-
-  tlist.AddToList(&fillcam);
-
-  if (fRelTimes)
-    {
-      tlist.AddToList(&filltme);
-      tlist.AddToList(&timecalc);
-    }
-  
-  if (IsUseBlindPixel())
-    tlist.AddToList(&fillbnd);
-  if (IsUsePINDiode())
-    tlist.AddToList(&fillpin);
-
-  tlist.AddToList(&calcalc);
-
-  // Create and setup the eventloop
-  MEvtLoop evtloop(fName);
-  evtloop.SetParList(&plist);
-  evtloop.SetDisplay(fDisplay);
-  evtloop.SetLogStream(fLog);
-  
-  // Execute first analysis
-  if (!evtloop.Eventloop())
-    {
-      *fLog << err << GetDescriptor() << ": Failed." << endl;
-      return kFALSE;
-    }
-  
-  tlist.PrintStatistics();
-
-  //
-  // The next lines are necessary in order to avoid that 
-  // the last entry drawn by MFillH gets deleted again from 
-  // the display. No idea where this comes from...
-  //
-  if (fDisplay)
-    {
-      if (IsUsePINDiode())
+        else if (IsUseBlindPixel())
         {
-          MHCalibrationChargePINDiode *pin = 
-            (MHCalibrationChargePINDiode*)plist.FindObject("MHCalibrationChargePINDiode");
-          pin->DrawClone(Form("nonew %s",drawoption.Data()));
+            MHCalibrationChargeBlindCam *cam =
+                (MHCalibrationChargeBlindCam*)plist.FindObject("MHCalibrationChargeBlindCam");
+            cam->DrawClone(Form("nonew %s",drawoption.Data()));
         }
-      else if (IsUseBlindPixel())
+        else if (fRelTimes)
         {
-          MHCalibrationChargeBlindCam *cam = 
-            (MHCalibrationChargeBlindCam*)plist.FindObject("MHCalibrationChargeBlindCam");
-          cam->DrawClone(Form("nonew %s",drawoption.Data()));
+            MHCalibrationRelTimeCam *cam =
+                (MHCalibrationRelTimeCam*)plist.FindObject("MHCalibrationRelTimeCam");
+            cam->DrawClone(Form("nonew %s",drawoption.Data()));
         }
-      else if (fRelTimes)
+        else
         {
-          MHCalibrationRelTimeCam *cam = 
-            (MHCalibrationRelTimeCam*)plist.FindObject("MHCalibrationRelTimeCam");
-          cam->DrawClone(Form("nonew %s",drawoption.Data()));
+            MHCalibrationChargeCam *cam =
+                (MHCalibrationChargeCam*)plist.FindObject("MHCalibrationChargeCam");
+            cam->DrawClone(Form("nonew %s",drawoption.Data()));
         }
-      else
-        {
-          MHCalibrationChargeCam *cam = 
-            (MHCalibrationChargeCam*)plist.FindObject("MHCalibrationChargeCam");
-          cam->DrawClone(Form("nonew %s",drawoption.Data()));
-        }
-    }
-  
-  DisplayResult(plist);
-
-  if (!WriteResult())
-    return kFALSE;
-  
-  *fLog << inf << GetDescriptor() << ": Done." << endl;
-  
-  return kTRUE;
+    }
+    */
+
+    DisplayResult(plist);
+
+    if (!WriteResult())
+        return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
 }
 
Index: /trunk/MagicSoft/Mars/mjobs/MJCalibration.h
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MJCalibration.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mjobs/MJCalibration.h	(revision 4609)
@@ -21,95 +21,118 @@
 #endif
 
+class TEnv;
 class MRunIter;
+class MSequence;
 class MParList;
 class MPedestalCam;
 class MExtractor;
 class MExtractTime;
+
+class MExtractBlindPixel;
+class MHCalibrationChargeBlindCam;
+
 class MJCalibration : public MParContainer
 {
 private:
+    static const Int_t gkIFAEBoxInaugurationRun;         // Run number of first IFAE box calibration
+    static const Int_t gkSecondBlindPixelInstallation;   // Run number upon which second blind pixel was installed
+    static const Int_t gkThirdBlindPixelInstallation;    // Run number upon which third blind pixel was installed
 
-  static const Int_t gkIFAEBoxInaugurationRun;          // Run number of first IFAE box calibration
-  static const Int_t gkSecondBlindPixelInstallation;    // Run number upon which second blind pixel was installed
-  static const Int_t gkThirdBlindPixelInstallation;     // Run number upon which third blind pixel was installed  
+    TString fOutputPath;                                 // Path to the output files
 
-  TString fOutputPath;                                 // Path to the output files
+    TEnv           *fEnv;
+    MRunIter       *fRuns;                               // Calibration files
+    MSequence      *fSequence;                           // Sequence
+
+    MExtractor     *fExtractor;                          // Signal extractor
+    MExtractTime   *fTimeExtractor;                      // Arrival Time extractor
+
+    MBadPixelsCam              fBadPixels;               // Bad Pixels cam, can be set from previous runs
+    MCalibrationChargeCam      fCalibrationCam;          // Calibration conversion factors FADC2Phe
+    MCalibrationChargeBlindCam fCalibrationBlindCam;     // Calibration from Blind Pixel(s)
+    MCalibrationChargePINDiode fCalibrationPINDiode;     // Calibration from PIN Diode
+    MCalibrationQECam          fQECam;                   // Quantum efficiency, can be set from previous runs
+    MCalibrationRelTimeCam     fRelTimeCam;              // Calibration constants rel. times
+
+    MCalibrationCam::PulserColor_t fColor;               // Colour of the pulsed LEDs
+
+    enum  Display_t                                      // Possible Display types
+    {
+        kFullDisplay,
+        kDataCheckDisplay,
+        kNormalDisplay
+    };
+
+    Display_t fDisplayType;                              // Chosen Display type
+
+    enum  Device_t                                       // Possible devices for calibration
+    {
+        kUseBlindPixel,
+        kUsePINDiode
+    }; 
+
+    Byte_t fDevices;                                     // Bit-field for used devices for calibration
+
+    Bool_t fRelTimes;                                    // Flag if relative times have to be calibrated
+    Bool_t fDataCheck;                                   // Flag if the data check is run on raw data
+    Bool_t fDebug;
+
+    void   DisplayResult(MParList &plist);
+    Bool_t WriteResult();
+    void   CheckEnv();
+
+    // WORKAROUNDS!!!
+    Bool_t FindColor();
+    void   InitBlindPixel(MExtractBlindPixel &blindext,
+                          MHCalibrationChargeBlindCam &blindcam);
+
+public:
+    MJCalibration(const char *name=NULL, const char *title=NULL);
+    ~MJCalibration();
   
-  MRunIter       *fRuns;                               // Calibration files
-  MExtractor     *fExtractor;                          // Signal extractor
-  MExtractTime   *fTimeExtractor;                      // Arrival Time extractor
+    const char* GetOutputFile() const;
+    void SetEnv(const char *env);
+
+    MCalibrationChargeCam  &GetCalibrationCam() { return fCalibrationCam; }
+    MCalibrationRelTimeCam &GetRelTimeCam()     { return fRelTimeCam;     }
+    MCalibrationQECam      &GetQECam()          { return fQECam;          }
+    MBadPixelsCam          &GetBadPixels()      { return fBadPixels;      }
+
+    Bool_t IsUseBlindPixel() const;
+    Bool_t IsUsePINDiode()   const;
+
+    void SetBadPixels(const MBadPixelsCam &bad)    { bad.Copy(fBadPixels);   }
+    void SetExtractor(MExtractor* ext)             { fExtractor = ext; }
+    void SetTimeExtractor(MExtractTime* ext)       { fTimeExtractor = ext; }
+    void SetQECam(const MCalibrationQECam &qe)     { qe.Copy(fQECam);        }
+    void SetColor(const MCalibrationCam::PulserColor_t color) { fColor = color; }
+
+    void SetInput(MRunIter *iter) { fRuns=iter; }
+    void SetSequence(MSequence *seq) { fSequence=seq; }
+    void SetOutputPath(const char *path=".");
+
+    // Displays
+    void SetFullDisplay()      { fDisplayType = kFullDisplay;      }
+    void SetDataCheckDisplay() { fDisplayType = kDataCheckDisplay; }
+    void SetNormalDisplay()    { fDisplayType = kNormalDisplay;    }
+
+    // Rel. Time
+    void SetRelTimeCalibration(const Bool_t b=kTRUE) { fRelTimes = b; }
+
+    // Data Check
+    void SetDataCheck(const Bool_t b=kTRUE) { fDataCheck = b; SetDataCheckDisplay(); }
+
+    // Debug
+    void SetDebug(const Bool_t b=kTRUE) { fDebug = b; }
+
+    // Devices
+    void SetUseBlindPixel(const Bool_t b=kTRUE);
+    void SetUsePINDiode(const Bool_t b=kTRUE);
   
-  MBadPixelsCam              fBadPixels;               // Bad Pixels cam, can be set from previous runs
-  MCalibrationChargeCam      fCalibrationCam;          // Calibration conversion factors FADC2Phe
-  MCalibrationChargeBlindCam fCalibrationBlindCam;     // Calibration from Blind Pixel(s)
-  MCalibrationChargePINDiode fCalibrationPINDiode;     // Calibration from PIN Diode
-  MCalibrationQECam          fQECam;                   // Quantum efficiency, can be set from previous runs
-  MCalibrationRelTimeCam     fRelTimeCam;              // Calibration constants rel. times
+    Bool_t ReadCalibrationCam();
+    Bool_t ProcessFile(MPedestalCam &pedcam);
+    Bool_t Process(MPedestalCam &pedcam);
 
-  MCalibrationCam::PulserColor_t fColor;               // Colour of the pulsed LEDs
-
-  enum  Display_t   { kFullDisplay, kDataCheckDisplay, kNormalDisplay }; // Possible Display types
-  
-  Display_t fDisplayType;                              // Chosen Display type
-
-  enum  Device_t    { kUseBlindPixel, kUsePINDiode  }; // Possible devices for calibration
-
-  Byte_t fDevices;                                     // Bit-field for used devices for calibration
-  
-  Bool_t fRelTimes;                                    // Flag if relative times have to be calibrated
-  Bool_t fDataCheck;                                   // Flag if the data check is run on raw data
-  Bool_t fDebug;
-
-  void   DisplayResult(MParList &plist);
-  Bool_t WriteResult();
-  Bool_t FindColor();
-  
-public:
-
-  MJCalibration(const char *name=NULL, const char *title=NULL);
-  ~MJCalibration() {}
-  
-  const char* GetOutputFile() const;
-
-  MCalibrationChargeCam  &GetCalibrationCam()     { return fCalibrationCam; }  
-  MCalibrationRelTimeCam &GetRelTimeCam()         { return fRelTimeCam;     }
-  MCalibrationQECam      &GetQECam()              { return fQECam;          }    
-  MBadPixelsCam          &GetBadPixels()          { return fBadPixels;      }
-
-  Bool_t IsUseBlindPixel() const;
-  Bool_t IsUsePINDiode()   const;
-  
-  void SetBadPixels(const MBadPixelsCam &bad)     { bad.Copy(fBadPixels);   }
-  void SetExtractor(MExtractor* ext)              { fExtractor = ext; }
-  void SetTimeExtractor(MExtractTime* ext)       { fTimeExtractor = ext; }
-  void SetQECam    (const MCalibrationQECam &qe) { qe.Copy(fQECam);        }    
-  void SetColor    (const MCalibrationCam::PulserColor_t color) { fColor = color; }
-
-  void SetInput(MRunIter *iter) { fRuns=iter; }
-  void SetOutputPath(const char *path=".");
-  
-  // Displays
-  void SetFullDisplay()      { fDisplayType = kFullDisplay;      }
-  void SetDataCheckDisplay() { fDisplayType = kDataCheckDisplay; }
-  void SetNormalDisplay()    { fDisplayType = kNormalDisplay;    }
-  
-  // Rel. Time
-  void SetRelTimeCalibration(const Bool_t b=kTRUE) { fRelTimes         = b; }
-
-  // Data Check
-  void SetDataCheck         (const Bool_t b=kTRUE) { fDataCheck        = b; SetDataCheckDisplay(); }
-
-  // Debug
-  void SetDebug             (const Bool_t b=kTRUE) { fDebug           = b; }
-  
-  // Devices
-  void SetUseBlindPixel( const Bool_t b=kTRUE );
-  void SetUsePINDiode  ( const Bool_t b=kTRUE );  
-  
-  Bool_t ReadCalibrationCam();
-  Bool_t ProcessFile( MPedestalCam &pedcam );
-  Bool_t Process    ( MPedestalCam &pedcam );
-  
-  ClassDef(MJCalibration, 0) // Tool to run a calibration per pulser colour and intensity
+    ClassDef(MJCalibration, 0) // Tool to run a calibration per pulser colour and intensity
 };
 
Index: /trunk/MagicSoft/Mars/mjobs/MJPedestal.cc
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MJPedestal.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mjobs/MJPedestal.cc	(revision 4609)
@@ -104,5 +104,5 @@
 {
     if (fSequence)
-        return Form("%s/calped%05d", (const char*)fOutputPath, fSequence->GetSequence());
+        return Form("%s/calped%06d.root", (const char*)fOutputPath, fSequence->GetSequence());
 
     if (!fRuns)
@@ -422,4 +422,17 @@
 
     return kTRUE;
+}
+
+void MJPedestal::CheckEnv()
+{
+    if (!fEnv)
+        return;
+
+    TString e1 = fEnv->GetValue("MJPedestal.OutputPath", "");
+    if (!e1.IsNull())
+    {
+        e1.ReplaceAll("\015", "");
+        SetOutputPath(e1);
+    }
 }
 
@@ -449,4 +462,6 @@
     *fLog << endl;
 
+    CheckEnv();
+
     MParList  plist;
     MTaskList tlist;
@@ -493,4 +508,5 @@
         pedcalc.SetRange(fExtractor->GetHiGainFirst(), fExtractor->GetHiGainLast());
     }
+  /*
     else
     {
@@ -498,4 +514,5 @@
         *fLog << ": No extractor has been chosen, take default number of FADC samples " << endl;
     }
+    */
 
     tlist.AddToList(&geomapl);
Index: /trunk/MagicSoft/Mars/mjobs/MJPedestal.h
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MJPedestal.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mjobs/MJPedestal.h	(revision 4609)
@@ -58,4 +58,6 @@
     void   DisplayOutliers(TH1D *hist) const;
 
+    void   CheckEnv();
+
 public:
     MJPedestal(const char *name=NULL, const char *title=NULL);
Index: /trunk/MagicSoft/Mars/mjobs/MSequence.h
===================================================================
--- /trunk/MagicSoft/Mars/mjobs/MSequence.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mjobs/MSequence.h	(revision 4609)
@@ -50,4 +50,5 @@
     // Getter
     UInt_t GetSequence() const { return fSequence; }
+    UInt_t GetLastRun() const  { return fLastRun; }
 
     ClassDef(MSequence, 0)
Index: /trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.cc
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.cc	(revision 4609)
@@ -185,15 +185,17 @@
       fGeom(NULL), fPedContainerName("MPedestalCam")
 {
-  fName  = name  ? name  : "MPedCalcFromLoGain";
-  fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
-  
-  AddToBranchList("fHiGainPixId");
-  AddToBranchList("fHiGainFadcSamples");
-  
-  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
-
-  SetMaxHiGainVar(fgMaxHiGainVar);
-  SetPedestalUpdate(kTRUE);
-  Clear();
+    fName  = name  ? name  : "MPedCalcFromLoGain";
+    fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
+
+    AddToBranchList("fHiGainPixId");
+    AddToBranchList("fLoGainPixId");
+    AddToBranchList("fHiGainFadcSamples");
+    AddToBranchList("fLoGainFadcSamples");
+
+    SetRange();
+    SetMaxHiGainVar();
+    SetPedestalUpdate(kTRUE);
+
+    Clear();
 }
 
@@ -208,19 +210,19 @@
 void MPedCalcFromLoGain::Clear(const Option_t *o)
 {
-  fRawEvt    = NULL;
-  fRunHeader = NULL;
-  fPedestals = NULL;
-
-  // If the size is yet set, set the size
-  if (fSumx.GetSize()>0)
-  {
-      // Reset contents of arrays.
-      fSumx.Reset();
-      fSumx2.Reset();
-      fSumAB0.Reset();
-      fSumAB1.Reset();
-      fNumEventsUsed.Reset();
-      fTotalCounter.Reset();
-  }
+    fRawEvt    = NULL;
+    fRunHeader = NULL;
+    fPedestals = NULL;
+
+    // If the size is yet set, set the size
+    if (fSumx.GetSize()>0)
+    {
+        // Reset contents of arrays.
+        fSumx.Reset();
+        fSumx2.Reset();
+        fSumAB0.Reset();
+        fSumAB1.Reset();
+        fNumEventsUsed.Reset();
+        fTotalCounter.Reset();
+    }
 }
 
@@ -235,10 +237,10 @@
 void MPedCalcFromLoGain::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
 {
-  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
-
-  //
-  // Redo the checks if the window is still inside the ranges
-  //
-  SetWindowSize(fWindowSizeHiGain,fWindowSizeLoGain);
+    MExtractor::SetRange(hifirst, hilast, lofirst, lolast);
+
+    //
+    // Redo the checks if the window is still inside the ranges
+    //
+    SetWindowSize(fWindowSizeHiGain,fWindowSizeLoGain);
 }
 
@@ -247,5 +249,5 @@
 void MPedCalcFromLoGain::SetMaxHiGainVar(Byte_t maxvar)
 {
-  fMaxHiGainVar = maxvar;
+    fMaxHiGainVar = maxvar;
 }
 
@@ -265,43 +267,50 @@
 void MPedCalcFromLoGain::SetWindowSize(Byte_t windowh, Byte_t windowl)
 {
-  fWindowSizeHiGain = windowh & ~1;
-  fWindowSizeLoGain = windowl & ~1;
-
-  if (fWindowSizeHiGain != windowh)
-    *fLog << warn << GetDescriptor() << ": Hi Gain window size has to be even, set to: " 
-          << int(fWindowSizeHiGain) << " samples " << endl;
+    fWindowSizeHiGain = windowh & ~1;
+    fWindowSizeLoGain = windowl & ~1;
   
-  if (fWindowSizeLoGain != windowl)
-    *fLog << warn << GetDescriptor() << ": Lo Gain window size has to be even, set to: " 
-          << int(fWindowSizeLoGain) << " samples " << endl;
+    if (fWindowSizeHiGain != windowh)
+    {
+        *fLog << warn;
+        *fLog << GetDescriptor() << ": HiGain window has to be even, set to: ";
+        *fLog << int(fWindowSizeHiGain) << " samples " << endl;
+    }
     
-  const Byte_t availhirange = (fHiGainLast-fHiGainFirst+1) & ~1;
-  const Byte_t availlorange = (fLoGainLast-fLoGainFirst+1) & ~1;
-
-  if (fWindowSizeHiGain > availhirange)
-    {
-      *fLog << warn << GetDescriptor() 
-            << Form(": Hi Gain window size: %2i is bigger than available range: [%2i,%2i]",
-		    (int)fWindowSizeHiGain, (int)fHiGainFirst, (int)fHiGainLast) << endl;
-      *fLog << warn << GetDescriptor() 
-            << ": Will set window size to: " << (int)availhirange << endl;
-      fWindowSizeHiGain = availhirange;
-    }
+    if (fWindowSizeLoGain != windowl)
+    {
+        *fLog << warn;
+        *fLog << GetDescriptor() << ": Lo Gain window has to be even, set to: ";
+        *fLog << int(fWindowSizeLoGain) << " samples " << endl;
+    }
+      
+    const Byte_t availhirange = (fHiGainLast-fHiGainFirst+1) & ~1;
+    const Byte_t availlorange = (fLoGainLast-fLoGainFirst+1) & ~1;
   
-  if (fWindowSizeLoGain > availlorange)
-    {
-      *fLog << warn << GetDescriptor() 
-            << Form(": Lo Gain window size: %2i is bigger than available range: [%2i,%2i]",
-		    (int)fWindowSizeLoGain, (int)fLoGainFirst, (int)fLoGainLast) << endl;
-      *fLog << warn << GetDescriptor() 
-            << ": Will set window size to: " << (int)availlorange << endl;
-      fWindowSizeLoGain = availlorange;
-    }
-  
-  fNumHiGainSamples = (Float_t)fWindowSizeHiGain;
-  fNumLoGainSamples = (Float_t)fWindowSizeLoGain;
-  
-  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
-  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+    if (fWindowSizeHiGain > availhirange)
+    {
+        *fLog << warn;
+        *fLog << GetDescriptor() << ": HiGain window " << (int)fWindowSizeHiGain;
+        *fLog << " out of range [" << (int)fHiGainFirst;
+        *fLog << "," << (int)fHiGainLast << "]" << endl;
+        *fLog << "Will set window size to " << (int)availhirange << endl;
+        fWindowSizeHiGain = availhirange;
+    }
+    
+    if (fWindowSizeLoGain > availlorange)
+    {
+        *fLog << warn;
+        *fLog << GetDescriptor() << ": LoGain window " << (int)fWindowSizeLoGain;
+        *fLog << " out of range [" << (int)fLoGainFirst;
+        *fLog << "," << (int)fLoGainLast << "]" << endl;
+        *fLog << "Will set window size to " << (int)availlorange << endl;
+        fWindowSizeLoGain = availlorange;
+    }
+    /*
+     fNumHiGainSamples = (Float_t)fWindowSizeHiGain;
+     fNumLoGainSamples = (Float_t)fWindowSizeLoGain;
+
+     fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+     fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+    */
 }
 
@@ -369,98 +378,63 @@
 Bool_t MPedCalcFromLoGain::ReInit(MParList *pList)
 {
-  Int_t lastdesired   = (Int_t)fLoGainLast;
-  Int_t lastavailable = (Int_t)fRunHeader->GetNumSamplesLoGain()-1;
-  
-  if (lastdesired > lastavailable)
-    {
-      const Int_t diff = lastdesired - lastavailable;
-      *fLog << endl; 
-      *fLog << warn << GetDescriptor()
-            << Form(": Selected Lo Gain FADC Window [%2i,%2i] ranges out of the available limits: [0,%2i].",
-		    (int)fLoGainFirst, lastdesired, lastavailable) << endl;
-      *fLog << GetDescriptor() << ": Will reduce the upper edge to " << (int)(fLoGainLast - diff) << endl;
-      SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast-diff);
-    }
-
-  lastdesired   = (Int_t)fHiGainLast;
-  lastavailable = (Int_t)fRunHeader->GetNumSamplesHiGain()-1;
-  
-  if (lastdesired > lastavailable)
-    {
-      const Int_t diff = lastdesired - lastavailable;
-      *fLog << endl;
-      *fLog << warn << GetDescriptor()
-            << Form(": Selected Hi Gain Range [%2i,%2i] ranges out of the available limits: [0,%2i].",
-                    (int)fHiGainFirst, lastdesired, lastavailable) << endl;
-      *fLog << warn << GetDescriptor() 
-            << Form(": Will possibly use %2i samples from the Low-Gain for the High-Gain range", diff)
-            << endl;
-      fHiGainLast -= diff;
-      fHiLoLast    = diff;
-    }
-
-  lastdesired   = (Int_t)fHiGainFirst+fWindowSizeHiGain-1;
-  lastavailable = (Int_t)fRunHeader->GetNumSamplesHiGain()-1;
-  
-  if (lastdesired > lastavailable)
-    {
-      const Int_t diff = lastdesired - lastavailable;
-      *fLog << endl;
-      *fLog << warn << GetDescriptor()
-            << Form(": Selected Hi Gain FADC Window size %2i ranges out of the available limits: [0,%2i].",
-                    (int)fWindowSizeHiGain, lastavailable) << endl;
-      *fLog << warn << GetDescriptor() 
-            << Form(": Will use %2i samples from the Low-Gain for the High-Gain extraction", diff)
-            << endl;
-
-      if ((Int_t)fWindowSizeHiGain > diff)
-        {
-          fWindowSizeHiGain -= diff;
-          fWindowSizeLoGain += diff;
-        }
-      else
-        {
-          fWindowSizeLoGain += fWindowSizeHiGain;
-          fLoGainFirst       = diff-fWindowSizeHiGain;
-          fWindowSizeHiGain  = 0;
-        }
-    }
-
-
-  // If the size is not yet set, set the size
-  if (fSumx.GetSize()==0)
-  {
-      const Int_t npixels = fPedestals->GetSize();
-
-      fSumx. Set(npixels);
-      fSumx2.Set(npixels);
-      fSumAB0.Set(npixels);
-      fSumAB1.Set(npixels);
-      fNumEventsUsed.Set(npixels);
-      fTotalCounter.Set(npixels);
-
-      // Reset contents of arrays.
-      fSumx.Reset();
-      fSumx2.Reset();
-      fSumAB0.Reset();
-      fSumAB1.Reset();
-      fNumEventsUsed.Reset();
-      fTotalCounter.Reset();
-  }
-  
-  if (fWindowSizeHiGain==0 && fWindowSizeLoGain==0)
-  {
-      *fLog << err << GetDescriptor()
-            << ": Number of extracted Slices is 0, abort ... " << endl;
-      return kFALSE;
-  }
-
-  *fLog << endl;
-  *fLog << inf << GetDescriptor() << ": Taking " << (int)fWindowSizeHiGain
-        << " HiGain FADC samples starting with slice: " << (int)fHiGainFirst << endl;
-  *fLog << inf << GetDescriptor() << ": Taking " << (int)fWindowSizeLoGain
-        << " LoGain FADC samples starting with slice: " << (int)fLoGainFirst << endl;
-  
-  return kTRUE;
+    if (fRunHeader->GetNumSamplesHiGain()<1)
+    {
+        *fLog << err << "ERROR - Number of available HiGainSamples<1... abort." << endl;
+        return kFALSE;
+    }
+    if (fRunHeader->GetNumSamplesLoGain()<1)
+    {
+        *fLog << err << "ERROR - Number of available LoGainSamples<1... abort." << endl;
+        return kFALSE;
+    }
+
+    fHiGainFirst = TMath::Max(fHiGainFirst, 0);
+    fHiGainLast  = TMath::Min(fHiGainLast,  fRunHeader->GetNumSamplesHiGain()-1);
+
+    fLoGainFirst = TMath::Max(fLoGainFirst, 0);
+    fLoGainLast  = TMath::Min(fLoGainLast,  fRunHeader->GetNumSamplesLoGain()-1);
+
+    fWindowSizeHiGain = TMath::Min(fWindowSizeHiGain, fHiGainLast-fHiGainFirst+1);
+    fWindowSizeLoGain = TMath::Min(fWindowSizeLoGain, fLoGainLast-fLoGainFirst+1);
+
+    SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast);
+
+    *fLog << inf << endl;
+    *fLog << "Taking " << Form("%2d", (int)fWindowSizeHiGain) << " HiGain from " << (int)fHiGainFirst << endl;
+    *fLog << "Taking " << Form("%2d", (int)fWindowSizeLoGain) << " LoGain from " << (int)fLoGainFirst << endl;
+
+    if (fWindowSizeHiGain==0)
+    {
+        *fLog << err << "ERROR - HiGain windows size == 0... abort." << endl;
+        return kFALSE;
+    }
+    if (fWindowSizeLoGain==0)
+    {
+        *fLog << err << "ERROR - HiGain windows size == 0... abort." << endl;
+        return kFALSE;
+    }
+
+    // If the size is not yet set, set the size
+    if (fSumx.GetSize()==0)
+    {
+        const Int_t npixels = fPedestals->GetSize();
+
+        fSumx. Set(npixels);
+        fSumx2.Set(npixels);
+        fSumAB0.Set(npixels);
+        fSumAB1.Set(npixels);
+        fNumEventsUsed.Set(npixels);
+        fTotalCounter.Set(npixels);
+
+        // Reset contents of arrays.
+        fSumx.Reset();
+        fSumx2.Reset();
+        fSumAB0.Reset();
+        fSumAB1.Reset();
+        fNumEventsUsed.Reset();
+        fTotalCounter.Reset();
+    }
+
+    return kTRUE;
 }
 
@@ -515,10 +489,8 @@
         // Find the maximum and minimum signal per slice in the high gain window
         do {
-            if (*ptr > max) {
+            if (*ptr > max)
                 max = *ptr;
-            }
-            if (*ptr < min) {
+            if (*ptr < min)
                 min = *ptr;
-            }
         } while (++ptr != end);
 
@@ -527,12 +499,13 @@
             continue;
 
-        Byte_t *firstSlice = pixel.GetLoGainSamples() + fLoGainFirst;
-        Byte_t *lastSlice  = firstSlice + fWindowSizeLoGain;
-
-        Byte_t *slice = firstSlice;
+        ptr = pixel.GetLoGainSamples() + fLoGainFirst;
+        end = ptr + fWindowSizeLoGain;
+
+        Byte_t *firstSlice = ptr;
+
         do {
-            sum += *slice;
-            sqr += *slice * *slice;
-        } while (++slice != lastSlice);
+            sum += *ptr;
+            sqr += *ptr * *ptr;
+        } while (++ptr != end);
 
         const Float_t msum   = (Float_t)sum;
@@ -569,5 +542,8 @@
 
     if (fPedestalUpdate)
+    {
+        fPedestals->ReCalc(*fGeom);
         fPedestals->SetReadyToSave();
+    }
 
     return kTRUE;
@@ -581,8 +557,10 @@
 {
     // Compute pedestals and rms from the whole run
-    if (fPedestalUpdate)
+    if (fPedestalUpdate || GetNumExecutions()<1)
         return kTRUE;
 
-    *fLog << flush << inf << "Calculating Pedestals..." << flush;
+    *fLog << flush << inf << "Calculating pedestals..." << flush;
+
+    Double_t sum = 0;
 
     const Int_t npix = fGeom->GetNumPixels();
@@ -592,6 +570,11 @@
         if (n>1)
             Calc(n, idx);
-    }
-
+        sum += n;
+    }
+
+    *fLog << flush << inf << "Calculating means..." << flush;
+
+    fPedestals->SetTotalEntries((UInt_t)(sum/npix*(fWindowSizeLoGain+fWindowSizeHiGain)));
+    fPedestals->ReCalc(*fGeom);
     fPedestals->SetReadyToSave();
     return kTRUE;
@@ -621,27 +604,21 @@
         SetWindowSize(hw, lw);
 
-    Int_t num = fNumEventsDump;
     if (IsEnvDefined(env, prefix, "NumEventsDump", print))
     {
-        num = GetEnvValue(env, prefix, "NumEventsDump", num);
+        SetDumpEvents(GetEnvValue(env, prefix, "NumEventsDump", fNumEventsDump));
         rc = kTRUE;
     }
-    SetDumpEvents(num);
-
-    Byte_t max = fMaxHiGainVar;
+
     if (IsEnvDefined(env, prefix, "MaxHiGainVar", print))
     {
-        max = GetEnvValue(env, prefix, "MaxHiGainVar", max);
+        SetMaxHiGainVar(GetEnvValue(env, prefix, "MaxHiGainVar", fMaxHiGainVar));
         rc = kTRUE;
     }
-    SetMaxHiGainVar(max);
-
-    Bool_t upd = fPedestalUpdate;
+
     if (IsEnvDefined(env, prefix, "PedestalUpdate", print))
     {
-        upd = GetEnvValue(env, prefix, "PedestalUpdate", upd);
+        SetPedestalUpdate(GetEnvValue(env, prefix, "PedestalUpdate", fPedestalUpdate));
         rc = kTRUE;
     }
-    SetPedestalUpdate(upd);
 
     return rc;
Index: /trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.h
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.h	(revision 4609)
@@ -62,7 +62,7 @@
 
     // Setter
-    void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
-    void SetWindowSize(Byte_t windowh=0, Byte_t windowl=0);
-    void SetMaxHiGainVar(Byte_t maxvar=0);
+    void SetRange(Byte_t hifirst=fgHiGainFirst, Byte_t hilast=fgHiGainLast, Byte_t lofirst=fgLoGainFirst, Byte_t lolast=fgLoGainLast);
+    void SetWindowSize(Byte_t windowh=fgHiGainWindowSize, Byte_t windowl=fgLoGainWindowSize);
+    void SetMaxHiGainVar(Byte_t maxvar=fgMaxHiGainVar);
     void SetDumpEvents(UInt_t dumpevents = 0) {fNumEventsDump = dumpevents;}
     void SetPedestalUpdate(Bool_t pedupdate)  {fPedestalUpdate = pedupdate;}
Index: /trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.cc
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.cc	(revision 4609)
@@ -394,6 +394,6 @@
 
   const Int_t npixels  = fPedestals->GetSize();
-  const Int_t areas    = fPedestals->GetAverageAreas();
-  const Int_t sectors  = fPedestals->GetAverageSectors();
+//  const Int_t areas    = fPedestals->GetAverageAreas();
+//  const Int_t sectors  = fPedestals->GetAverageSectors();
   
   if (fSumx.GetSize()==0)
@@ -402,11 +402,11 @@
       fSumx2.Set(npixels);
       
-      fAreaSumx. Set(areas);
-      fAreaSumx2.Set(areas);
-      fAreaValid.Set(areas);
-      
-      fSectorSumx. Set(sectors);
-      fSectorSumx2.Set(sectors);
-      fSectorValid.Set(sectors);
+//      fAreaSumx. Set(areas);
+//      fAreaSumx2.Set(areas);
+//      fAreaValid.Set(areas);
+      
+//      fSectorSumx. Set(sectors);
+//      fSectorSumx2.Set(sectors);
+//      fSectorValid.Set(sectors);
       
       fSumx.Reset();
@@ -439,4 +439,66 @@
 Int_t MPedCalcPedRun::Process()
 {
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    while (pixel.Next())
+    {
+        const UInt_t idx    = pixel.GetPixelId();
+
+        Byte_t *ptr = pixel.GetHiGainSamples() + fHiGainFirst;
+        Byte_t *end = ptr + fWindowSizeHiGain;
+
+        UInt_t sum = 0;
+        UInt_t sqr = 0;
+
+        if (fWindowSizeHiGain != 0)
+        {
+            do
+            {
+                sum += *ptr;
+                sqr += *ptr * *ptr;
+            }
+            while (++ptr != end);
+        }
+
+        if (fWindowSizeLoGain != 0)
+        {
+            ptr = pixel.GetLoGainSamples() + fLoGainFirst;
+            end = ptr + fWindowSizeLoGain;
+
+            do
+            {
+                sum += *ptr;
+                sqr += *ptr * *ptr;
+            }
+            while (++ptr != end);
+        }
+
+        const Float_t msum = (Float_t)sum;
+
+        //
+        // These three lines have been uncommented by Markus Gaug
+        // If anybody needs them, please contact me!!
+        //
+        //	const Float_t higainped = msum/fNumHiGainSlices;
+        //	const Float_t higainrms = TMath::Sqrt((msqr-msum*msum/fNumHiGainSlices)/(fNumHiGainSlices-1.));
+        //	(*fPedestals)[idx].Set(higainped, higainrms);
+
+        fSumx[idx]          += msum;
+        //
+        // The old version:
+        //
+        //       const Float_t msqr = (Float_t)sqr;
+        //	fSumx2[idx] += msqr;
+        //
+        // The new version:
+        //
+        const Float_t sqrsum  = msum*msum;
+        fSumx2[idx]          += sqrsum;
+    }
+
+    fNumSamplesTot += fWindowSizeHiGain + fWindowSizeLoGain;
+
+    return kTRUE;
+/*
   MRawEvtPixelIter pixel(fRawEvt);
   
@@ -445,5 +507,5 @@
       const UInt_t idx    = pixel.GetPixelId();
       const UInt_t aidx   = (*fGeom)[idx].GetAidx();
-      const UInt_t sector = (*fGeom)[idx].GetSector();      
+      const UInt_t sector = (*fGeom)[idx].GetSector();
 
       Byte_t *ptr = pixel.GetHiGainSamples() + fHiGainFirst;
@@ -490,5 +552,5 @@
       fSumx[idx]          += msum;
       fAreaSumx[aidx]     += msum;
-      fSectorSumx[sector] += msum;      
+      fSectorSumx[sector] += msum;
       //
       // The old version:
@@ -502,10 +564,10 @@
       fSumx2[idx]          += sqrsum;
       fAreaSumx2[aidx]     += sqrsum;
-      fSectorSumx2[sector] += sqrsum;      
+      fSectorSumx2[sector] += sqrsum;
     }
   
   fPedestals->SetReadyToSave();
   fNumSamplesTot += fWindowSizeHiGain + fWindowSizeLoGain;
-
+*/
   return kTRUE;
 }
@@ -517,42 +579,82 @@
 Int_t MPedCalcPedRun::PostProcess()
 {
-  // Compute pedestals and rms from the whole run
-  const ULong_t n     = fNumSamplesTot;
-  const ULong_t nevts = GetNumExecutions();
-
-  MRawEvtPixelIter pixel(fRawEvt);
-  
-  while (pixel.Next())
-    {
-
-      const Int_t  pixid  = pixel.GetPixelId();
-      const UInt_t aidx   = (*fGeom)[pixid].GetAidx();
-      const UInt_t sector = (*fGeom)[pixid].GetSector();      
-      
-      fAreaValid  [aidx]++;
-      fSectorValid[sector]++;
-
-      const Float_t sum  = fSumx.At(pixid);
-      const Float_t sum2 = fSumx2.At(pixid);
-      const Float_t higainped = sum/n;
-      //
-      // The old version:
-      //
-      //      const Float_t higainrms = TMath::Sqrt((sum2-sum*sum/n)/(n-1.));
-      //
-      // The new version:
-      //
-      // 1. Calculate the Variance of the sums:
-      Float_t higainVar = (sum2-sum*sum/nevts)/(nevts-1.);
-      // 2. Scale the variance to the number of slices:
-      higainVar /= (Float_t)(fWindowSizeHiGain+fWindowSizeLoGain);
-      // 3. Calculate the RMS from the Variance:
-      (*fPedestals)[pixid].Set(higainped, higainVar < 0 ? 0. : TMath::Sqrt(higainVar));
-
-    }
+    const ULong_t nevts = GetNumExecutions();
+    if (nevts<1)
+    {
+        *fLog << err << "ERROR - Not enough events recorded...abort." << endl;
+        return kFALSE;
+    }
+
+    *fLog << flush << inf << "Calculating pedestals..." << flush;
+
+    // Compute pedestals and rms from the whole run
+    const ULong_t n     = fNumSamplesTot;
+    const ULong_t npix  = fGeom->GetNumPixels();
+
+    for (UInt_t pixidx=0; pixidx<npix; pixidx++)
+    {
+        const Float_t sum  = fSumx.At(pixidx);
+        const Float_t sum2 = fSumx2.At(pixidx);
+        const Float_t higainped = sum/n;
+        //
+        // The old version:
+        //
+        //      const Float_t higainrms = TMath::Sqrt((sum2-sum*sum/n)/(n-1.));
+        //
+        // The new version:
+        //
+        // 1. Calculate the Variance of the sums:
+        Float_t higainVar = (sum2-sum*sum/nevts)/(nevts-1.);
+        // 2. Scale the variance to the number of slices:
+        higainVar /= (Float_t)(fWindowSizeHiGain+fWindowSizeLoGain);
+        // 3. Calculate the RMS from the Variance:
+        (*fPedestals)[pixidx].Set(higainped, higainVar < 0 ? 0. : TMath::Sqrt(higainVar), 0, nevts);
+    }
+
+    *fLog << flush << inf << "Calculating means..." << flush;
+
+    fPedestals->SetTotalEntries(fNumSamplesTot);
+    fPedestals->ReCalc(*fGeom);
+    fPedestals->SetReadyToSave();
+
+    return kTRUE;
 
   //
   // Loop over the (two) area indices to get the averaged pedestal per aidx
   //
+  /*
+
+   // Compute pedestals and rms from the whole run
+    const ULong_t n     = fNumSamplesTot;
+    const ULong_t nevts = GetNumExecutions();
+
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    while (pixel.Next())
+    {
+        const Int_t  pixid  = pixel.GetPixelId();
+        const UInt_t aidx   = (*fGeom)[pixid].GetAidx();
+        const UInt_t sector = (*fGeom)[pixid].GetSector();
+
+        fAreaValid  [aidx]++;
+        fSectorValid[sector]++;
+
+        const Float_t sum  = fSumx.At(pixid);
+        const Float_t sum2 = fSumx2.At(pixid);
+        const Float_t higainped = sum/n;
+        //
+        // The old version:
+        //
+        //      const Float_t higainrms = TMath::Sqrt((sum2-sum*sum/n)/(n-1.));
+        //
+        // The new version:
+        //
+        // 1. Calculate the Variance of the sums:
+        Float_t higainVar = (sum2-sum*sum/nevts)/(nevts-1.);
+        // 2. Scale the variance to the number of slices:
+        higainVar /= (Float_t)(fWindowSizeHiGain+fWindowSizeLoGain);
+        // 3. Calculate the RMS from the Variance:
+        (*fPedestals)[pixid].Set(higainped, higainVar < 0 ? 0. : TMath::Sqrt(higainVar), 0, nevts);
+    }
   for (Int_t aidx=0; aidx<fAreaValid.GetSize(); aidx++)
     {
@@ -582,8 +684,9 @@
       fPedestals->GetAverageArea(aidx).Set(higainped, higainrms);
     }
-  
+    */
   //
   // Loop over the (six) sector indices to get the averaged pedestal per sector
   //
+  /*
   for (Int_t sector=0; sector<fSectorValid.GetSize(); sector++)
     {
@@ -613,9 +716,9 @@
       fPedestals->GetAverageSector(sector).Set(higainped, higainrms);
     }
-  
   fPedestals->SetTotalEntries(fNumSamplesTot);
   fPedestals->SetReadyToSave();
 
   return kTRUE;
+    */
 }
 
Index: /trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.h
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.h	(revision 4609)
@@ -33,4 +33,5 @@
     TArrayD fSumx;             // sum of values
     TArrayD fSumx2;            // sum of squared values
+    /*
     TArrayD fAreaSumx;         // averaged sum of values per area idx
     TArrayD fAreaSumx2;        // averaged sum of squared values per area idx
@@ -39,4 +40,5 @@
     TArrayD fSectorSumx2;      // averaged sum of squared values per sector
     TArrayI fSectorValid;      // number of valid pixel with sector idx
+    */
 
     Int_t  PreProcess (MParList *pList);
Index: /trunk/MagicSoft/Mars/mpedestal/MPedPhotCam.cc
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedPhotCam.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedPhotCam.cc	(revision 4609)
@@ -229,10 +229,7 @@
 void MPedPhotCam::ReCalc(const MGeomCam &geom, MBadPixelsCam *bad)
 {
-    
     const Int_t np = GetSize();
     const Int_t ns = GetNumSectors();
     const Int_t na = GetNumAreas();
-
-    
 
     TArrayI acnt(na);
@@ -243,11 +240,8 @@
     TArrayD ssumr(ns);
 
-
     for (int i=0; i<np; i++)
     {
-        
-
-      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
-	continue; //was: .IsBad()       
+        if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+            continue; //was: .IsBad()
 
         // Create sums for areas and sectors
@@ -268,17 +262,17 @@
 	ssumr[sect] += ne*rms;
         scnt[sect]  += ne;
-    
-
-    }
-
-    for (int i=0; i<ns; i++){
-      if (scnt[i]>0)  GetSector(i).Set(ssumx[i]/scnt[i], ssumr[i]/scnt[i], scnt[i]);
-      else GetSector(i).Set(-1., -1., 0);
-    }
-
-    for (int i=0; i<na; i++){
-      if (acnt[i]>0) GetArea(i).Set(asumx[i]/acnt[i], asumr[i]/acnt[i], acnt[i]);
-      else  GetArea(i).Set(-1., -1., 0);
-    }
+    }
+
+    for (int i=0; i<ns; i++)
+        if (scnt[i]>0)
+            GetSector(i).Set(ssumx[i]/scnt[i], ssumr[i]/scnt[i], scnt[i]);
+        else
+            GetSector(i).Clear();
+
+    for (int i=0; i<na; i++)
+        if (acnt[i]>0)
+            GetArea(i).Set(asumx[i]/acnt[i], asumr[i]/acnt[i], acnt[i]);
+        else
+            GetArea(i).Clear();
 }
 
Index: /trunk/MagicSoft/Mars/mpedestal/MPedPhotCam.h
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedPhotCam.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedPhotCam.h	(revision 4609)
@@ -51,5 +51,5 @@
     void Print(Option_t *o="") const;
 
-    void ReCalc(const MGeomCam &geom, MBadPixelsCam *bad);
+    void ReCalc(const MGeomCam &geom, MBadPixelsCam *bad=NULL);
 
     Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
Index: /trunk/MagicSoft/Mars/mpedestal/MPedestalCam.cc
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedestalCam.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedestalCam.cc	(revision 4609)
@@ -35,4 +35,7 @@
 #include "MPedestalPix.h"
 
+#include <TArrayI.h>
+#include <TArrayD.h>
+
 #include <TClonesArray.h>
 
@@ -43,4 +46,8 @@
 
 #include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
 
 ClassImp(MPedestalCam);
@@ -311,37 +318,96 @@
 }
 
-Bool_t MPedestalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const {
-
-  if (GetSize() <= idx)
-    return kFALSE;
-
-  if (!(*this)[idx].IsValid())
-    return kFALSE;
-
-  switch (type) {
+// --------------------------------------------------------------------------
+//
+// Calculates the avarage pedestal and pedestal rms for all sectors
+// and pixel sizes. The geometry container is used to get the necessary
+// geometry information (sector number, size index) If the bad pixel
+// container is given all pixels which have the flag 'bad' are ignored
+// in the calculation of the sector and size average.
+//
+void MPedestalCam::ReCalc(const MGeomCam &geom, MBadPixelsCam *bad)
+{
+    const Int_t np = GetSize();
+    const Int_t ns = geom.GetNumSectors();
+    const Int_t na = geom.GetNumAreas();
+
+    TArrayI acnt(na);
+    TArrayI scnt(ns);
+    TArrayD asumx(na);
+    TArrayD ssumx(ns);
+    TArrayD asumr(na);
+    TArrayD ssumr(ns);
+
+    for (int i=0; i<np; i++)
+    {
+        if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+            continue; //was: .IsBad()
+
+        // Create sums for areas and sectors
+        const UInt_t aidx = geom[i].GetAidx();
+        const UInt_t sect = geom[i].GetSector();
+
+        const MPedestalPix &pix = (*this)[i];
+
+        const UInt_t  ne   = pix.GetNumEvents();
+        const Float_t mean = pix.GetPedestal();
+        const Float_t rms  = pix.GetPedestalRms();
+
+        asumx[aidx] += ne*mean;
+        asumr[aidx] += ne*rms;
+        acnt[aidx]  += ne;
+
+        ssumx[sect] += ne*mean;
+        ssumr[sect] += ne*rms;
+        scnt[sect]  += ne;
+    }
+
+    for (int i=0; i<ns; i++)
+        if (scnt[i]>0)
+            GetAverageSector(i).Set(ssumx[i]/scnt[i], ssumr[i]/scnt[i], 0, scnt[i]);
+        else
+            GetAverageSector(i).Clear();
+
+    for (int i=0; i<na; i++)
+        if (acnt[i]>0)
+            GetAverageArea(i).Set(asumx[i]/acnt[i], asumr[i]/acnt[i], 0, acnt[i]);
+        else
+            GetAverageArea(i).Clear();
+}
+
+Bool_t MPedestalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (GetSize() <= idx)
+        return kFALSE;
+
+    if (!(*this)[idx].IsValid())
+        return kFALSE;
+
+    switch (type)
+    {
     case 0:
-      val = (*this)[idx].GetPedestal();
-      break;
+        val = (*this)[idx].GetPedestal();
+        break;
     case 1:
-      val = fTotalEntries > 0 ? 
-	  (*this)[idx].GetPedestalRms()/TMath::Sqrt((Float_t)fTotalEntries) 
-	: (*this)[idx].GetPedestalError();
-      break;
+        val = fTotalEntries > 0 ?
+            (*this)[idx].GetPedestalRms()/TMath::Sqrt((Float_t)fTotalEntries)
+            : (*this)[idx].GetPedestalError();
+        break;
     case 2:
-      val = (*this)[idx].GetPedestalRms();
-      break;
+        val = (*this)[idx].GetPedestalRms();
+        break;
     case 3:
-      val = fTotalEntries > 0 ?
-	  (*this)[idx].GetPedestalRms()/TMath::Sqrt((Float_t)fTotalEntries)/2. 
-	: (*this)[idx].GetPedestalRmsError();
-      break;
+        val = fTotalEntries > 0 ?
+            (*this)[idx].GetPedestalRms()/TMath::Sqrt((Float_t)fTotalEntries)/2.
+            : (*this)[idx].GetPedestalRmsError();
+        break;
     default:
-      return kFALSE;
+        return kFALSE;
     }
-  return kTRUE;
+    return kTRUE;
 }
 
 void MPedestalCam::DrawPixelContent(Int_t idx) const
 {
-  *fLog << warn << "MPedestalCam::DrawPixelContent - not available." << endl;
-}
+    *fLog << warn << "MPedestalCam::DrawPixelContent - not available." << endl;
+}
Index: /trunk/MagicSoft/Mars/mpedestal/MPedestalCam.h
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedestalCam.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedestalCam.h	(revision 4609)
@@ -13,4 +13,5 @@
 class MGeomCam;
 class MPedestalPix;
+class MBadPixelsCam;
 
 class MPedestalCam : public MParContainer, public MCamEvent
@@ -51,4 +52,6 @@
   void  InitAverageSectors             ( const UInt_t i      );
 
+  void ReCalc(const MGeomCam &geom, MBadPixelsCam *bad=NULL);
+
   void Print(Option_t *o="") const;
   
Index: /trunk/MagicSoft/Mars/mpedestal/MPedestalPix.h
===================================================================
--- /trunk/MagicSoft/Mars/mpedestal/MPedestalPix.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mpedestal/MPedestalPix.h	(revision 4609)
@@ -37,4 +37,6 @@
     Float_t GetPedestalRmsError() const { return fNumEvents>0 ? fPedestalRms/TMath::Sqrt((Float_t)fNumEvents/2) : 0; }
 
+    UInt_t  GetNumEvents() const { return fNumEvents; }
+
     Bool_t IsValid() const;
 
Index: /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.cc
===================================================================
--- /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.cc	(revision 4608)
+++ /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.cc	(revision 4609)
@@ -74,5 +74,5 @@
 //
 // UInt_t  fNumTrigLvl2
-// ------------------ -
+// --------------------
 //
 // Number of second level trigger
@@ -90,5 +90,24 @@
 // Type of Trigger. 
 // This is a Byte (8 bit) to indicated if any of the pixels 
-// have a non-negligible low gain (1) or not (0) 
+// have a non-negligible low gain (1) or not (0)
+//
+// UInt_t fCalibPattern
+// --------------------
+//
+// Bits 1-16: Pulser slot pattern: 16 LEDs slots (see Diploma Thesis
+// of Michele)
+//
+// Bits 17-24: Power of Continous light source: 256 level
+//
+// Bits 25-28: Farbe der Continuous Light: red-amber-green/blue-uv
+//
+// Bit 29: Calibration trigger On/off
+// Bit 30: Pedestal trigger on/off
+// Bit 31: PIN Diode calibration trigger on/off
+//
+//
+// Class Version 2:
+// ---------------
+//  - added fCalibPattern
 //
 /////////////////////////////////////////////////////////////////////////////
@@ -379,2 +398,29 @@
     return fTrigPattern[0];
 }
+
+// --------------------------------------------------------------------------
+//
+// return pulser slot patter, see class reference
+//
+UShort_t MRawEvtHeader::GetPulserSlotPattern() const
+{
+    return fTrigPattern[1] & 0xffff;
+}
+
+// --------------------------------------------------------------------------
+//
+// return power of continous light, see class reference
+//
+Byte_t MRawEvtHeader::GetPowerOfContLight() const
+{
+    return (fTrigPattern[1]<<16) & 0xff;
+}
+
+// --------------------------------------------------------------------------
+//
+// return color of continous light, see class reference
+//
+MRawEvtHeader::CalibCol_t MRawEvtHeader::GetContLedColor() const
+{
+    return (CalibCol_t)((fTrigPattern[1]<<24)&0xf);
+}
Index: /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.h
===================================================================
--- /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.h	(revision 4608)
+++ /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.h	(revision 4609)
@@ -24,4 +24,12 @@
         kTTPedestal    = 1,
         kTTCalibration = 2
+    };
+
+    enum CalibCol_t {
+        kColRed   = BIT(0),
+        kColAmber = BIT(1),
+        kColGreen = BIT(2),
+        kColBlue  = BIT(3),
+        kColUV    = BIT(4)
     };
 
@@ -60,13 +68,17 @@
     void FillHeader(UInt_t, Float_t=0);
 
-    UShort_t GetTrigType() const     { return fTrigType; }
-    UInt_t   GetNumTrigLvl1() const  { return fNumTrigLvl1; }
-    UInt_t   GetNumTrigLvl2() const  { return fNumTrigLvl2; }
-    UInt_t   GetDAQEvtNumber() const { return fDAQEvtNumber; }
+    UShort_t   GetTrigType() const     { return fTrigType; }
+    UInt_t     GetNumTrigLvl1() const  { return fNumTrigLvl1; }
+    UInt_t     GetNumTrigLvl2() const  { return fNumTrigLvl2; }
+    UInt_t     GetDAQEvtNumber() const { return fDAQEvtNumber; }
     
-    UInt_t GetTriggerID() const;
+    UInt_t     GetTriggerID() const;
+
+    UShort_t   GetPulserSlotPattern() const;
+    Byte_t     GetPowerOfContLight() const;
+    CalibCol_t GetContLedColor() const;
 
     Int_t ReadEvt(istream& fin, UShort_t ver);
-    void SkipEvt(istream& fin, UShort_t ver);
+    void  SkipEvt(istream& fin, UShort_t ver);
 
     ClassDef(MRawEvtHeader, 1) // Parameter Conatiner for raw EVENT HEADER
