Index: trunk/MagicSoft/Mars/mpedestal/MExtractPedestal.cc
===================================================================
--- trunk/MagicSoft/Mars/mpedestal/MExtractPedestal.cc	(revision 8128)
+++ trunk/MagicSoft/Mars/mpedestal/MExtractPedestal.cc	(revision 8151)
@@ -1,3 +1,5 @@
 /* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: MExtractPedestal.cc,v 1.23 2006-10-24 07:58:13 tbretz Exp $
+! --------------------------------------------------------------------------
 !
 ! *
@@ -17,6 +19,7 @@
 !
 !   Author(s): Markus Gaug 01/2004 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz 01/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
 !
-!   Copyright: MAGIC Software Development, 2000-2004
+!   Copyright: MAGIC Software Development, 2000-2006
 !
 !
@@ -159,5 +162,4 @@
 #include "MRawEvtHeader.h"  
 #include "MRawEvtPixelIter.h"
-#include "MRawEvtData.h"
 
 #include "MPedestalPix.h"
@@ -167,6 +169,6 @@
 #include "MGeomCam.h"
 
-#include "MTaskEnv.h"
 #include "MExtractTimeAndCharge.h"
+#include "MPedestalSubtractedEvt.h"
 
 ClassImp(MExtractPedestal);
@@ -174,7 +176,10 @@
 using namespace std;
 
-const TString MExtractPedestal::fgNamePedestalCam = "MPedestalCam";
-const TString MExtractPedestal::fgNameRawEvtData  = "MRawEvtData";
-const UInt_t  MExtractPedestal::fgNumDump = 500;
+const TString  MExtractPedestal::fgNamePedestalCam = "MPedestalCam";
+const TString  MExtractPedestal::fgNameRawEvtData  = "MRawEvtData";
+
+const UShort_t MExtractPedestal::fgCheckWinFirst   =  0;
+const UShort_t MExtractPedestal::fgCheckWinLast    = 29;
+const UShort_t MExtractPedestal::fgMaxSignalVar    = 40;
 
 // --------------------------------------------------------------------------
@@ -186,22 +191,15 @@
 //
 // Calls: 
-// - AddToBranchList("fHiGainPixId");
-// - AddToBranchList("fHiGainFadcSamples");
 // - Clear()
 //
 MExtractPedestal::MExtractPedestal(const char *name, const char *title)
-    : fGeom(NULL), fPedestalsIn(NULL), fPedestalsInter(NULL), fPedestalsOut(NULL), 
-      fExtractor(NULL), fExtractWinFirst(0), fExtractWinSize(0), fUseSpecialPixels(kFALSE)
+    : fGeom(NULL), fPedestalsIn(NULL), fPedestalsInter(NULL),
+    fPedestalsOut(NULL), fExtractor(NULL), fSignal(0),
+    fExtractWinFirst(0), fExtractWinSize(0), fUseSpecialPixels(kFALSE)
 {
     fName  = name  ? name  : "MExtractPedestal";
     fTitle = title ? title : "Base class to calculate pedestals";
 
-    AddToBranchList("fHiGainPixId");
-    AddToBranchList("fLoGainPixId");
-    AddToBranchList("fHiGainFadcSamples");
-    AddToBranchList("fLoGainFadcSamples");
- 
     SetIntermediateStorage( kFALSE );
-    SetPedestalUpdate     ( kTRUE  );
     SetRandomCalculation  ( kTRUE  );
 
@@ -210,9 +208,15 @@
     SetNamePedestalCamInter();
     SetNameRawEvtData();
-    SetNumDump();
+
+    SetCheckRange(fgCheckWinFirst, fgCheckWinLast);
+    SetMaxSignalVar(fgMaxSignalVar);
 
     Clear();
 }
 
+// --------------------------------------------------------------------------
+//
+// Call reset() of all Arays
+//
 void MExtractPedestal::ResetArrays()
 {
@@ -244,5 +248,4 @@
 // - fRawEvt to NULL
 // - fRunHeader to NULL
-// - fEvtHeader to NULL
 //
 void MExtractPedestal::Clear(const Option_t *o)
@@ -251,5 +254,4 @@
   fRawEvt       = NULL;
   fRunHeader    = NULL;
-  fEvtHeader    = NULL;
 
   // If the size is yet set, set the size
@@ -269,5 +271,5 @@
   Bool_t rc = kTRUE;
 
-  const Int_t odd  = windows & 0x1;
+  const Int_t odd  = TMath::Odd(windows);
   
   if (odd && !fExtractor)
@@ -275,6 +277,6 @@
       *fLog << warn << GetDescriptor();
       *fLog << " - WARNING: Window size in SetExtractWindow has to be even... ";
-      *fLog << " raising from " << windows << " to ";
-      windows += 1;
+      *fLog << " lowering from " << windows << " to ";
+      windows -= 1;
       *fLog << windows << "!" << endl;
       rc = kFALSE;
@@ -292,6 +294,76 @@
   fExtractWinFirst = windowf;
   fExtractWinLast  = fExtractWinFirst+fExtractWinSize-1;
+
+  return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetCheckRange: 
+// 
+// Exits, if the first argument is smaller than 0
+// Exits, if the the last argument is smaller than the first
+//
+Bool_t MExtractPedestal::SetCheckRange(UShort_t chfirst, UShort_t chlast)
+{
+
+  Bool_t rc = kTRUE;
   
+  if (chlast<=chfirst)
+    {
+      *fLog << warn << GetDescriptor();
+      *fLog << " - WARNING: Last slice in SetCheckRange smaller than first slice... set to first+2" << endl;
+      chlast = chfirst+1;
+      rc = kFALSE;
+    }
+
+  fCheckWinFirst = chfirst;
+  fCheckWinLast  = chlast;
+
   return rc;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Check (and if neccesary: correct) the extraction and check ranges.
+//
+void MExtractPedestal::CheckExtractionWindow()
+{
+    // fSignal->GetNumSamples() not yet initialized!!!
+    const UInt_t num = fRunHeader->GetNumSamplesHiGain()+fRunHeader->GetNumSamplesLoGain();
+
+    if (fCheckWinLast >= num)
+    {
+        *fLog << warn << endl;
+        *fLog << "Selected CheckWindow [" << fCheckWinFirst << "," << fCheckWinLast;
+        *fLog << "] ranges out of range [0," << num-1 << "]." << endl;
+        *fLog << "Resetting upper edge." << endl;
+
+        fCheckWinLast = num;
+    }
+
+    if (fExtractWinLast >= num)
+    {
+        *fLog << warn << endl;
+        *fLog << "Selected ExtractWindow [" << fExtractWinFirst << "," << fExtractWinLast;
+        *fLog << "] ranges out of range [0," << num-1 << "]." << endl;
+        *fLog << "Resetting upper edge." << endl;
+
+        fExtractWinLast = num;
+    }
+
+    fExtractWinSize = fExtractWinLast-fExtractWinFirst+1;
+
+    if (fExtractor || TMath::Even(fExtractWinSize))
+        return;
+
+    fExtractWinLast += fExtractWinLast==num-1 ? -1 : +1;
+
+    *fLog << warn << endl;
+    *fLog << "ExtractionWindow odd...";
+    *fLog << "New extraction window [" << fExtractWinFirst << "," << fExtractWinLast << "]" << endl;
+
+    fExtractWinSize = fExtractWinLast-fExtractWinFirst+1;
 }
 
@@ -338,15 +410,15 @@
   }
   
-  fEvtHeader = (MRawEvtHeader*)pList->FindObject(AddSerialNumber("MRawEvtHeader"));
-  if (!fEvtHeader)
-  {
-      *fLog << err << AddSerialNumber("MRawEvtHeader") << " not found... aborting." << endl;
-      return kFALSE;
-  }
-  
   fGeom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
   if (!fGeom)
   {
       *fLog << err << AddSerialNumber("MGeomCam") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  fSignal = (MPedestalSubtractedEvt*)pList->FindObject(AddSerialNumber("MPedestalSubtractedEvt"));
+  if (!fSignal)
+  {
+      *fLog << err << AddSerialNumber("MPedestalSubtractedEvt") << " not found... aborting." << endl;
       return kFALSE;
   }
@@ -376,10 +448,12 @@
   }
 
-  *fLog << inf;
-  Print();
-
   return fExtractor ? fExtractor->CallPreProcess(pList) : kTRUE;
 }
 
+//-----------------------------------------------------------------------
+//
+// Call Calc(). If fExtractor!=NULL enclose the call in setting the
+// NoiseCalculation to fRandomCalculation
+//
 Int_t MExtractPedestal::Process()
 {
@@ -491,13 +565,30 @@
     if (fExtractor)
     {
-        if (!((MTask*)fExtractor)->ReInit(pList))
+        if (!fExtractor->ReInit(pList))
             return kFALSE;
 
-        SetExtractWindow(fExtractor->GetHiGainFirst(), (Int_t)TMath::Nint(fExtractor->GetNumHiGainSamples()));
-    }
+        // If an extractor is set determin the window size automatically!
+        fExtractWinFirst = fExtractor->GetHiGainFirst();
+        fExtractWinLast  = fExtractor->GetHiGainLast();
+
+        // fSignal->GetNumSamples() not yet initialized!!!
+        const UInt_t num = fRunHeader->GetNumSamplesHiGain()+fRunHeader->GetNumSamplesLoGain();
+        if (fExtractWinLast >= num)
+        {
+            *fLog << err << GetDescriptor();
+            *fLog << " - ERROR: Selected fExtractWinLast out of range." << endl;
+            return kFALSE;
+        }
+    }
+
+    CheckExtractionWindow();
 
     return kTRUE;
 }
 
+// ---------------------------------------------------------------------------------
+//
+// PostProcess the extractor if available
+//
 Int_t MExtractPedestal::PostProcess()
 {
@@ -506,4 +597,97 @@
 }
 
+// ---------------------------------------------------------------------------------
+//
+// Check whether the signal variation between fCheckWinFirst and fCheckWinLast
+// exceeds fMaxSignalVar or the signal is greater than 250
+//
+Bool_t MExtractPedestal::CheckVariation(UInt_t idx) const
+{
+    // This is the fast workaround to put hi- and lo-gains together
+    Byte_t *slices = fSignal->GetSamplesRaw(idx);//pixel.GetSamples();
+
+    // Start 'real' work
+    UShort_t max = 0;
+    UShort_t min = (UShort_t)-1;
+
+    // Find the maximum and minimum signal per slice in the high gain window
+    for (Byte_t *slice=slices+fCheckWinFirst; slice<=slices+fCheckWinLast; slice++)
+    {
+        if (*slice > max)
+            max = *slice;
+        if (*slice < min)
+            min = *slice;
+    }
+
+    // If the maximum in the high gain window is smaller than
+    return max-min<fMaxSignalVar && max<250;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Invoke the hi-gain extraction starting at fExtractWinFirst+offset
+// for fExtractWinLast-fExtractWinFirst+1 slices. If Noise calculation
+// is set it is up to the signal extractor to do the right thing.
+//
+// Returns the extracted signal.
+//
+Float_t MExtractPedestal::CalcExtractor(const MRawEvtPixelIter &pixel, Int_t offset) const
+{
+    // Use the same extraction window as for signal extraction
+    const Int_t first = fExtractWinFirst;
+    const Int_t last  = fExtractWinLast;
+
+    const Int_t start = first+offset;
+
+    const Int_t range = last-first+1;
+
+    // This check is already done in CheckExtractionWindow
+    //    if (range>pixel.GetNumSamples()-start)
+    //        range = pixel.GetNumSamples()-start;
+
+    const Int_t idx = pixel.GetPixelId();
+
+    // Do some handling if maxpos is last slice?
+    const Int_t maxposhi = fSignal->GetMax(idx, start, start+range-1);
+
+    const Float_t *sig = fSignal->GetSamples(idx);
+
+    // The pedestal is extracted with the hi-gain extractor (eg. digital
+    // filter weights) but from the lo-gains
+    Float_t dummy[3];
+    Float_t sum = 0;
+    fExtractor->FindTimeAndChargeHiGain2(sig+start, range, sum,
+                                         dummy[0], dummy[1], dummy[2],
+                                         0, maxposhi);
+    return sum;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Sum slices from fExtractWinFirst to fExtractWinLast. The total sum is
+// returned. ab0 and ab1 will contain the total sum splitted by the
+// AB-flag. If the AB-flag is invalid ab0=ab1=0 is returned.
+//
+UInt_t MExtractPedestal::CalcSums(const MRawEvtPixelIter &pixel, Int_t offset, UInt_t &ab0, UInt_t &ab1) const
+{
+    const Int_t first = fExtractWinFirst+offset;
+
+    Byte_t *ptr = fSignal->GetSamplesRaw(pixel.GetPixelId())+first;
+    Byte_t *end = ptr + fExtractWinSize;
+
+    Int_t abflag = pixel.HasABFlag() + first;
+
+    UInt_t ab[2] = { 0, 0 };
+    while (ptr<end)
+        ab[abflag++ & 0x1] += *ptr++;
+
+    // This check if for old data without AB-Flag in the data
+    const Bool_t valid = pixel.IsABFlagValid();
+
+    ab0 = valid ? ab[0] : 0;
+    ab1 = valid ? ab[1] : 0;
+
+    return ab0+ab1;
+}
 
 // --------------------------------------------------------------------------
@@ -512,5 +696,4 @@
 //    ExtractWindowFirst:    15
 //    ExtractWindowSize:      6
-//    NumEventsDump:        500
 //    PedestalUpdate:       yes
 //    RandomCalculation:    yes
@@ -520,50 +703,8 @@
     Bool_t rc=kFALSE;
 
-    // find resource for numdump
-    if (IsEnvDefined(env, prefix, "NumDump", print))
-    {
-        const Int_t num = GetEnvValue(env, prefix, "NumDump", -1);
-        if (num<=0)
-        {
-            *fLog << err << GetDescriptor() << ": ERROR - NumDump invalid!" << endl;
-            return kERROR;
-        }
-
-        SetNumDump(num);
-        rc = kTRUE;
-    }
-
     // find resource for fUseSpecialPixels
     if (IsEnvDefined(env, prefix, "UseSpecialPixels", print))
     {
         SetUseSpecialPixels(GetEnvValue(env, prefix, "UseSpecialPixels", fUseSpecialPixels));
-        rc = kTRUE;
-    }
-
-    // find resource for numeventsdump
-    if (IsEnvDefined(env, prefix, "NumEventsDump", print))
-    {
-        SetNumEventsDump(GetEnvValue(env, prefix, "NumEventsDump", (Int_t)fNumEventsDump));
-        rc = kTRUE;
-    }
-
-    // find resource for numeventsdump
-    if (IsEnvDefined(env, prefix, "NumAreasDump", print))
-    {
-        SetNumAreasDump(GetEnvValue(env, prefix, "NumAreasDump", (Int_t)fNumAreasDump));
-        rc = kTRUE;
-    }
-
-    // find resource for numeventsdump
-    if (IsEnvDefined(env, prefix, "NumSectorsDump", print))
-    {
-        SetNumSectorsDump(GetEnvValue(env, prefix, "NumSectorsDump", (Int_t)fNumSectorsDump));
-        rc = kTRUE;
-    }
-
-    // find resource for pedestal update
-    if (IsEnvDefined(env, prefix, "PedestalUpdate", print))
-    {
-        SetPedestalUpdate(GetEnvValue(env, prefix, "PedestalUpdate", fPedestalUpdate));
         rc = kTRUE;
     }
@@ -598,4 +739,27 @@
     SetExtractWindow(ef,es);
 
+    // Find resources for CheckWindow
+    Int_t cfs = fCheckWinFirst;
+    Int_t cls = fCheckWinLast;
+    if (IsEnvDefined(env, prefix, "CheckWinFirst", print))
+    {
+        cfs = GetEnvValue(env, prefix, "CheckWinFirst", cfs);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "CheckWinLast", print))
+    {
+        cls = GetEnvValue(env, prefix, "CheckWinLast", cls);
+        rc = kTRUE;
+    }
+
+    SetCheckRange(cfs,cls);
+
+    // find resource for maximum signal variation
+    if (IsEnvDefined(env, prefix, "MaxSignalVar", print))
+    {
+        SetMaxSignalVar(GetEnvValue(env, prefix, "MaxSignalVar", fMaxSignalVar));
+        rc = kTRUE;
+    }
+
     // find resource for MPedestalCam
     if (IsEnvDefined(env, prefix, "NamePedestalCamIn", print))
@@ -648,8 +812,13 @@
     var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
     abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    // The pedestal extracted with the extractor is divided by
+    // the number of hi-gain samples because the calibration
+    // multiplies by this number
 
     // 5. Calculate the RMS from the Variance:
     const Double_t rms = var<0 ? 0 : TMath::Sqrt(var);
 
+    // abOffs contains only half of the signal as ped.
+    // Therefor abOffs is not the full, but the half amplitude
     (*fPedestalsOut)[pixid].Set(ped, rms, abOffs, nevts);
 }
@@ -683,4 +852,7 @@
     var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
     abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    // The pedestal extracted with the extractor is divided by
+    // the number of hi-gain samples because the calibration
+    // multiplies by this number
 
     // 5. Scale the mean, variance and AB-noise to the number of pixels:
@@ -692,4 +864,6 @@
     const Double_t rms = var<0 ? 0 : TMath::Sqrt(var);
 
+    // abOffs contains only half of the signal as ped.
+    // Therefor abOffs is not the full, but the half amplitude
     fPedestalsOut->GetAverageArea(aidx).Set(ped, rms, abOffs, nevts);
 }
@@ -723,4 +897,7 @@
     var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
     abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    // The pedestal extracted with the extractor is divided by
+    // the number of hi-gain samples because the calibration
+    // multiplies by this number
 
     // 5. Scale the mean, variance and AB-noise to the number of pixels:
@@ -732,7 +909,11 @@
     const Double_t rms = var<0 ? 0 : TMath::Sqrt(var);
 
+    // abOffs contains only half of the signal as ped.
+    // Therefor abOffs is not the full, but the half amplitude
     fPedestalsOut->GetAverageSector(sector).Set(ped, rms, abOffs, nevts);
 }
 
+//-----------------------------------------------------------------------
+//
 void MExtractPedestal::Print(Option_t *o) const
 {
@@ -742,12 +923,5 @@
     *fLog << "Name of output MPedestalCam:  " << (fPedestalsOut?fPedestalsOut->GetName():fNamePedestalCamOut.Data()) << " (" << fPedestalsOut << ")" << endl;
     *fLog << "Intermediate Storage is       " << (fIntermediateStorage?"on":"off") << endl;
-    *fLog << "Pedestal Update is            " << (fPedestalUpdate?"on":"off") << endl;
     *fLog << "Special pixel mode            " << (fUseSpecialPixels?"on":"off") << endl;
-    if (fPedestalUpdate)
-    {
-        *fLog << "Num evts for pedestal   calc: " << fNumEventsDump << endl;
-        *fLog << "Num evts for avg.areas  calc: " << fNumAreasDump << endl;
-        *fLog << "Num evts for avg.sector calc: " << fNumSectorsDump << endl;
-    }
     if (fExtractor)
     {
@@ -755,3 +929,6 @@
         *fLog << (fRandomCalculation?"":"non-") << "random)" << endl;
     }
-}
+    *fLog << "ExtractWindow from slice " << fExtractWinFirst << " to " << fExtractWinLast << " incl." << endl;
+    *fLog << "CheckWindow from slice " << fCheckWinFirst   << " to " << fCheckWinLast << " incl." << endl;
+    *fLog << "Max.allowed signal variation: " << fMaxSignalVar << endl;
+}
Index: trunk/MagicSoft/Mars/mpedestal/MExtractPedestal.h
===================================================================
--- trunk/MagicSoft/Mars/mpedestal/MExtractPedestal.h	(revision 8128)
+++ trunk/MagicSoft/Mars/mpedestal/MExtractPedestal.h	(revision 8151)
@@ -20,4 +20,6 @@
 class MRawEvtHeader;
 class MExtractTimeAndCharge;
+class MPedestalSubtractedEvt;
+class MRawEvtPixelIter;
 
 class MExtractPedestal : public MTask
@@ -26,5 +28,8 @@
   static const TString  fgNamePedestalCam;  //! "MPedestalCam"
   static const TString  fgNameRawEvtData;   //! "MRawEvtData"
-  static const UInt_t   fgNumDump;          //!
+
+  static const UShort_t fgCheckWinFirst;    //! First FADC slice to check for signal (currently set to: 0)
+  static const UShort_t fgCheckWinLast;     //! Last FADC slice to check for signal  (currently set to: 29)
+  static const UShort_t fgMaxSignalVar;     //! The maximum difference between the highest and lowest slice
 
   TString fNamePedestalCamIn;        // Name of the incoming 'MPedestalCam' container
@@ -45,16 +50,16 @@
   MRawEvtData   *fRawEvt;            //! Raw event data (time slices)
   MRawRunHeader *fRunHeader;         //! RunHeader information
-  MRawEvtHeader *fEvtHeader;         //! EvtHeader information
   MExtractTimeAndCharge *fExtractor; //  Possible Extractor
+  MPedestalSubtractedEvt *fSignal;   //!
   
   UShort_t fExtractWinFirst;         // First FADC slice to extract pedestal from
   UShort_t fExtractWinSize;          // Number of slices to calculate the pedestal from
   UShort_t fExtractWinLast;          // Last FADC slice to extract pedestal from 
-                                     
-  UInt_t  fNumEventsDump;            // Number of event after which MPedestalCam gets updated
-  UInt_t  fNumAreasDump;             // Number of events after which averaged areas gets updated
-  UInt_t  fNumSectorsDump;           // Number of events after which averaged sectors gets updated
- 
-  Bool_t  fPedestalUpdate;           // Flag if the pedestal shall be updated after every fNumEventsDump
+
+  UShort_t fCheckWinFirst;
+  UShort_t fCheckWinLast;
+
+  UShort_t fMaxSignalVar;
+
   Bool_t  fUseSpecialPixels;         // Flag if the special pixels shall be treated
 
@@ -92,4 +97,10 @@
   void CalcSectorResults(const UInt_t nevts, const UInt_t nspix, const UInt_t sector);
 
+  Float_t CalcExtractor(const MRawEvtPixelIter &pixel, Int_t offset) const;
+  UInt_t  CalcSums(const MRawEvtPixelIter &pixel, Int_t offset, UInt_t &ab0, UInt_t &ab1) const;
+  Bool_t  CheckVariation(UInt_t idx) const;
+
+  void CheckExtractionWindow();
+
 public:
   MExtractPedestal(const char *name=NULL, const char *title=NULL);
@@ -98,10 +109,9 @@
   void Print(const Option_t *o="") const;
 
+  // Setters
   Bool_t SetExtractWindow(UShort_t first, UShort_t size);
+  Bool_t SetCheckRange(UShort_t checkfirst=fgCheckWinFirst, UShort_t checklast=fgCheckWinLast);
 
-  void SetNumEventsDump (UInt_t dumpevents=fgNumDump)  { fNumEventsDump  = dumpevents; }
-  void SetNumAreasDump  (UInt_t dumpevents=fgNumDump)  { fNumAreasDump   = dumpevents; }
-  void SetNumSectorsDump(UInt_t dumpevents=fgNumDump)  { fNumSectorsDump = dumpevents; }
-  void SetNumDump       (UInt_t n=fgNumDump) { fNumEventsDump=n; fNumAreasDump=n; fNumSectorsDump=n; }
+  void SetMaxSignalVar(UShort_t maxvar=40)  { fMaxSignalVar = maxvar;    }
 
   // names
@@ -120,5 +130,4 @@
   void SetIntermediateStorage (Bool_t b=kTRUE) { fIntermediateStorage = b; }
   void SetUseSpecialPixels    (Bool_t b=kTRUE) { fUseSpecialPixels    = b; }
-  void SetPedestalUpdate      (Bool_t b=kTRUE) { fPedestalUpdate      = b; }
   void SetRandomCalculation   (Bool_t b=kTRUE) { fRandomCalculation   = b; }
 
Index: trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.cc
===================================================================
--- trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.cc	(revision 8128)
+++ trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.cc	(revision 8151)
@@ -1,3 +1,5 @@
 /* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: MPedCalcFromLoGain.cc,v 1.34 2006-10-24 07:58:13 tbretz Exp $
+! --------------------------------------------------------------------------
 !
 ! *
@@ -24,5 +26,5 @@
 !   Author(s): Nepomuk Otte 10/2004 <mailto:otte@mppmu.mpg.de>
 !
-!   Copyright: MAGIC Software Development, 2000-2004
+!   Copyright: MAGIC Software Development, 2000-2006
 !
 !
@@ -142,5 +144,4 @@
 #include "MRawRunHeader.h"  
 #include "MRawEvtPixelIter.h"
-#include "MRawEvtData.h"
 
 #include "MPedestalPix.h"
@@ -151,5 +152,5 @@
 
 #include "MExtractPedestal.h"
-#include "MExtractTimeAndCharge.h"
+#include "MPedestalSubtractedEvt.h"
 
 ClassImp(MPedCalcFromLoGain);
@@ -157,9 +158,7 @@
 using namespace std;
 
-const UShort_t MPedCalcFromLoGain::fgCheckWinFirst   =  0;
-const UShort_t MPedCalcFromLoGain::fgCheckWinLast    = 29;
 const UShort_t MPedCalcFromLoGain::fgExtractWinFirst = 17;
 const UShort_t MPedCalcFromLoGain::fgExtractWinSize  =  6;
-const UShort_t MPedCalcFromLoGain::fgMaxSignalVar    = 40;
+const UInt_t   MPedCalcFromLoGain::fgNumDump         = 500;
 
 // --------------------------------------------------------------------------
@@ -167,11 +166,6 @@
 // Default constructor: 
 //
-// Sets:
-// - all pointers to NULL
-//
 // Calls: 
-// - AddToBranchList("fHiGainPixId");
-// - AddToBranchList("fHiGainFadcSamples");
-// - SetCheckRange(fgCheckWinFirst, fgCheckWinLast, fgExtractWinFirst, fgExtractWinSize)
+// - SetExtractWindow(fgExtractWinFirst, fgExtractWinSize)
 //
 MPedCalcFromLoGain::MPedCalcFromLoGain(const char *name, const char *title)
@@ -180,10 +174,14 @@
     fTitle = title ? title : "Task to calculate pedestals from lo-gains";
 
-    SetCheckRange(fgCheckWinFirst, fgCheckWinLast);
     SetExtractWindow(fgExtractWinFirst, fgExtractWinSize);
-
-    SetMaxSignalVar(fgMaxSignalVar);
-}
-
+    SetPedestalUpdate(kTRUE);
+    SetNumDump();
+}
+
+// --------------------------------------------------------------------------
+//
+// Call MExtractPedestl::ResetArrays aand reset fNumAventsUsed and
+// fTotalCounter
+//
 void MPedCalcFromLoGain::ResetArrays()
 {
@@ -192,30 +190,4 @@
     fNumEventsUsed.Reset();
     fTotalCounter.Reset();
-}
-
-// --------------------------------------------------------------------------
-//
-// SetCheckRange: 
-// 
-// Exits, if the first argument is smaller than 0
-// Exits, if the the last argument is smaller than the first
-//
-Bool_t MPedCalcFromLoGain::SetCheckRange(UShort_t chfirst, UShort_t chlast)
-{
-
-  Bool_t rc = kTRUE;
-  
-  if (chlast<=chfirst)
-    {
-      *fLog << warn << GetDescriptor();
-      *fLog << " - WARNING: Last slice in SetCheckRange smaller than first slice... set to first+2" << endl;
-      chlast = chfirst+1;
-      rc = kFALSE;
-    }
-
-  fCheckWinFirst = chfirst;
-  fCheckWinLast  = chlast;
-
-  return rc;
 }
 
@@ -231,55 +203,16 @@
 Bool_t MPedCalcFromLoGain::ReInit(MParList *pList)
 {
-
-  const UShort_t hisamples = fRunHeader->GetNumSamplesHiGain();
-  const UShort_t losamples = fRunHeader->GetNumSamplesLoGain();
-  
-  fSlices.Set(hisamples+losamples);
-  
-  UShort_t lastavailable   = hisamples+losamples-1;
-
-  if (fExtractor)
-    fExtractWinLast = fExtractWinFirst + fExtractor->GetWindowSizeHiGain() - 1;
-  
-  // If the size is not yet set, set the size
-  if (fSumx.GetSize()==0)
-    {
-      const Int_t npixels  = fPedestalsOut->GetSize();
-      fNumEventsUsed.Set(npixels);
-      fTotalCounter.Set(npixels);
-    }
-  
-  if (fCheckWinLast > lastavailable) //changed to override check
-    {
-      *fLog << warn << GetDescriptor();
-      *fLog << " - WARNING: Last Check Window slice out of range...adjusting to last available slice ";
-      *fLog << lastavailable << endl;
-      
-      fCheckWinLast = lastavailable;
-    }
-  
-  if (fExtractWinLast > lastavailable) 
-    {
-      if (fExtractor)
-        {
-          *fLog << err << GetDescriptor();
-          *fLog << " - ERROR: Selected Last Extraction Window: " 
-                << fExtractWinFirst + fExtractor->GetWindowSizeHiGain()-1 
-                << "ranges out of range: " << lastavailable-1 << endl;
-          return kFALSE;
-        }
-      else
-        {
-          const UShort_t diff = fExtractWinLast - lastavailable;
-          *fLog << warn << GetDescriptor();
-          *fLog << " - WARNING: Selected Extract Window ranges out of range...adjusting to last available slice ";
-          *fLog << lastavailable << endl;
-          
-          fExtractWinLast -= diff;
-          fExtractWinSize -= diff;
-        }
-    }
-  
-  return MExtractPedestal::ReInit(pList);
+    // If the size is not yet set, set the size
+    if (fSumx.GetSize()==0)
+    {
+        const Int_t npixels = fPedestalsOut->GetSize();
+        fNumEventsUsed.Set(npixels);
+        fTotalCounter.Set(npixels);
+    }
+
+    if (!MExtractPedestal::ReInit(pList))
+        return kFALSE;
+
+    return kTRUE;
 }
 
@@ -292,10 +225,4 @@
 Int_t MPedCalcFromLoGain::Calc()
 {
-    // This is the workaround to put hi- and lo-gains together
-    const Int_t nhigain = fRunHeader->GetNumSamplesHiGain();
-    const Int_t nlogain = fRunHeader->GetNumSamplesLoGain();
-
-    Byte_t *slices = fSlices.GetArray();
-
     // Real Process
     MRawEvtPixelIter pixel(fRawEvt);
@@ -303,42 +230,17 @@
     while (pixel.Next())
     {
-        // This is the fast workaround to put hi- and lo-gains together
-        memcpy(slices,         pixel.GetHiGainSamples(), nhigain);
-        memcpy(slices+nhigain, pixel.GetLoGainSamples(), nlogain);
-
-        // Start 'real' work
         const UInt_t idx = pixel.GetPixelId();
+
+        if (!CheckVariation(idx))
+            continue;
+
+        //extract pedestal
+        UInt_t ab[2];
+        const Float_t sum = fExtractor ?
+            CalcExtractor(pixel, pixel.GetNumHiGainSamples()) :
+            CalcSums(pixel, pixel.GetNumHiGainSamples(), ab[0], ab[1]);
 
         const UInt_t aidx   = (*fGeom)[idx].GetAidx();
         const UInt_t sector = (*fGeom)[idx].GetSector();
-
-        UShort_t max = 0;
-        UShort_t min = (UShort_t)-1;
-
-        // Find the maximum and minimum signal per slice in the high gain window
-        for (Byte_t *slice=slices+fCheckWinFirst; slice<=slices+fCheckWinLast; slice++)
-        {
-            if (*slice > max)
-                max = *slice;
-            if (*slice < min)
-                min = *slice;
-        }
-      
-        // If the maximum in the high gain window is smaller than
-        if (max-min>=fMaxSignalVar || max>=250)
-            continue;
-
-        Float_t sum  = 0.;
-
-        //extract pedestal
-        if (fExtractor)
-            CalcExtractor(pixel, sum, (*fPedestalsIn)[idx]);
-        else
-        {
-            UInt_t  sumi = 0;
-            for(Byte_t *slice=slices+fExtractWinFirst; slice<=slices+fExtractWinLast; slice++)
-                sumi += *slice;
-            sum = (Float_t)sumi;
-        }
 
         const Float_t sqrsum = sum*sum;
@@ -352,5 +254,5 @@
 
         if (fIntermediateStorage)
-          (*fPedestalsInter)[idx].Set(sum,0.,0.,fNumEventsUsed[idx]);
+            (*fPedestalsInter)[idx].Set(sum, 0, 0, fNumEventsUsed[idx]);
 
         fNumEventsUsed[idx]   ++;
@@ -358,23 +260,12 @@
         fSectorFilled [sector]++;
 
-        if (!fExtractor)
+        if (!fExtractor && pixel.IsABFlagValid())
         {
-            //
-            // Calculate the amplitude of the 150MHz "AB" noise
-            //
-            const UShort_t abFlag = (fExtractWinFirst + pixel.HasABFlag()) & 0x1;
-
-            for (Byte_t *slice=slices+fExtractWinFirst; slice<=slices+fExtractWinLast; slice+=2)
-            {
-                const UShort_t ab0 = *(slice + abFlag);
-                const UShort_t ab1 = *(slice - abFlag + 1);
-
-                fSumAB0[idx]        += ab0;
-                fSumAB1[idx]        += ab1;
-                fAreaSumAB0[aidx]   += ab0;
-                fAreaSumAB1[aidx]   += ab1;
-                fSectorSumAB0[aidx] += ab0;
-                fSectorSumAB1[aidx] += ab1;
-            }
+            fSumAB0[idx]        += ab[0];
+            fSumAB1[idx]        += ab[1];
+            fAreaSumAB0[aidx]   += ab[0];
+            fAreaSumAB1[aidx]   += ab[1];
+            fSectorSumAB0[aidx] += ab[0];
+            fSectorSumAB1[aidx] += ab[1];
         }
 
@@ -425,15 +316,4 @@
             CalcAreaResults(fAreaFilled[aidx], fAreaValid[aidx], aidx);
 
-}
-
-void MPedCalcFromLoGain::CalcExtractor(const MRawEvtPixelIter &pixel, Float_t &sum, MPedestalPix &ped)
-{
-    Byte_t  sat  = 0;
-    Byte_t *logain = pixel.GetLoGainSamples() + fExtractWinFirst;
-
-    const Bool_t logainabflag = (pixel.HasABFlag() + pixel.GetNumHiGainSamples()) & 0x1;
-
-    Float_t dummy;
-    fExtractor->FindTimeAndChargeHiGain(logain,logain,sum,dummy,dummy,dummy,sat,ped,logainabflag);
 }
 
@@ -469,11 +349,7 @@
 }
 
-
 // --------------------------------------------------------------------------
 //
 //  The following resources are available:
-//    FirstCheckWindowSlice:  0
-//    LastCheckWindowSlice:  29
-//    MaxSignalVar:          40
 //
 Int_t MPedCalcFromLoGain::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
@@ -481,41 +357,59 @@
     Bool_t rc=kFALSE;
 
-    // Find resources for CheckWindow
-    Int_t fs = fCheckWinFirst;
-    Int_t ls = fCheckWinLast;
-    if (IsEnvDefined(env, prefix, "CheckWinFirst", print))
-    {
-        fs = GetEnvValue(env, prefix, "CheckWinFirst", fs);
+    // find resource for pedestal update
+    if (IsEnvDefined(env, prefix, "PedestalUpdate", print))
+    {
+        SetPedestalUpdate(GetEnvValue(env, prefix, "PedestalUpdate", fPedestalUpdate));
         rc = kTRUE;
     }
-    if (IsEnvDefined(env, prefix, "CheckWinLast", print))
-    {
-        ls = GetEnvValue(env, prefix, "CheckWinLast", ls);
+
+    // find resource for numdump
+    if (IsEnvDefined(env, prefix, "NumDump", print))
+    {
+        const Int_t num = GetEnvValue(env, prefix, "NumDump", -1);
+        if (num<=0)
+        {
+            *fLog << err << GetDescriptor() << ": ERROR - NumDump invalid!" << endl;
+            return kERROR;
+        }
+
+        SetNumDump(num);
         rc = kTRUE;
     }
 
-    SetCheckRange(fs,ls);
-
-    // find resource for maximum signal variation
-    if (IsEnvDefined(env, prefix, "MaxSignalVar", print))
-    {
-        SetMaxSignalVar(GetEnvValue(env, prefix, "MaxSignalVar", fMaxSignalVar));
+    // find resource for numeventsdump
+    if (IsEnvDefined(env, prefix, "NumEventsDump", print))
+    {
+        SetNumEventsDump(GetEnvValue(env, prefix, "NumEventsDump", (Int_t)fNumEventsDump));
         rc = kTRUE;
     }
 
-    return MExtractPedestal::ReadEnv(env,prefix,print) ? kTRUE : rc;
+    // find resource for numeventsdump
+    if (IsEnvDefined(env, prefix, "NumAreasDump", print))
+    {
+        SetNumAreasDump(GetEnvValue(env, prefix, "NumAreasDump", (Int_t)fNumAreasDump));
+        rc = kTRUE;
+    }
+
+    // find resource for numeventsdump
+    if (IsEnvDefined(env, prefix, "NumSectorsDump", print))
+    {
+        SetNumSectorsDump(GetEnvValue(env, prefix, "NumSectorsDump", (Int_t)fNumSectorsDump));
+        rc = kTRUE;
+    }
+
+    return rc;
 }
 
 void MPedCalcFromLoGain::Print(Option_t *o) const
 {
-
     MExtractPedestal::Print(o);
 
-    const Int_t last = fExtractor 
-      ? fExtractWinFirst + fExtractor->GetWindowSizeHiGain() -1
-      : fExtractWinLast;
-
-    *fLog << "ExtractWindow from slice " << fExtractWinFirst << " to " << last << " incl." << endl;
-    *fLog << "Max.allowed signal variation: " << fMaxSignalVar << endl;
-    *fLog << "CheckWindow from slice " << fCheckWinFirst   << " to " << fCheckWinLast << " incl." << endl;
-}
+    *fLog << "Pedestal Update is            " << (fPedestalUpdate?"on":"off") << endl;
+    if (fPedestalUpdate)
+    {
+        *fLog << "Num evts for pedestal   calc: " << fNumEventsDump << endl;
+        *fLog << "Num evts for avg.areas  calc: " << fNumAreasDump << endl;
+        *fLog << "Num evts for avg.sector calc: " << fNumSectorsDump << endl;
+    }
+}
Index: trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.h
===================================================================
--- trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.h	(revision 8128)
+++ trunk/MagicSoft/Mars/mpedestal/MPedCalcFromLoGain.h	(revision 8151)
@@ -14,5 +14,5 @@
 #endif
 
-class MRawEvtPixelIter;
+//class MRawEvtPixelIter;
 class MPedestalPix;
 
@@ -20,29 +20,29 @@
 {
 private:
-    static const UShort_t fgCheckWinFirst;    // First FADC slice to check for signal (currently set to: 0)
-    static const UShort_t fgCheckWinLast;     // Last FADC slice to check for signal  (currently set to: 29)
-    static const UShort_t fgMaxSignalVar;     // The maximum difference between the highest and lowest slice
     static const UShort_t fgExtractWinFirst;  // First FADC slice to use for pedestal calculation (currently set to: 15)
     static const UShort_t fgExtractWinSize;   // number of successive slices used to calculate pedestal (currently set to: 6)
+    static const UInt_t   fgNumDump;          //!
 
-    UShort_t fMaxSignalVar;
-    UShort_t fCheckWinFirst;
-    UShort_t fCheckWinLast;
+    UInt_t  fNumEventsDump;            // Number of event after which MPedestalCam gets updated
+    UInt_t  fNumAreasDump;             // Number of events after which averaged areas gets updated
+    UInt_t  fNumSectorsDump;           // Number of events after which averaged sectors gets updated
 
     TArrayI fNumEventsUsed;      //! Number of events used for pedestal calc for each pixel
     TArrayI fTotalCounter;       //! Counter for dumping values to Pedestal Container
 
-    MArrayB fSlices;             //! workaround to put hi- and lo-gain slices together
+    Bool_t  fPedestalUpdate;           // Flag if the pedestal shall be updated after every fNumEventsDump
 
-    Bool_t fRandomCalculation;
+    // MParContainer
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
 
+    // MTask
     Bool_t ReInit(MParList *pList);
-    Int_t  Calc();
     Int_t  PostProcess();
 
-    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+    // MExtractPedestal
+    Int_t  Calc();
 
     //Helper function to extract slice values by slice number
-    void CalcExtractor(const MRawEvtPixelIter &pixel, Float_t &sum, MPedestalPix &ped);
+    //void CalcExtractor(const MRawEvtPixelIter &pixel, Float_t &sum, MPedestalPix &ped);
     void ResetArrays();
 
@@ -53,12 +53,15 @@
     MPedCalcFromLoGain(const char *name=NULL, const char *title=NULL);
 
-    void Print(Option_t *o="") const;
-
-    // Setters
-    Bool_t SetCheckRange(UShort_t checkfirst=fgCheckWinFirst, UShort_t checklast=fgCheckWinLast);
-    void SetMaxSignalVar(UShort_t maxvar=40)  { fMaxSignalVar = maxvar;    }
-
     // Getters
     TArrayI *GetNumEventsUsed() { return &fNumEventsUsed; }
+
+    void SetNumEventsDump (UInt_t dumpevents=fgNumDump)  { fNumEventsDump  = dumpevents; }
+    void SetNumAreasDump  (UInt_t dumpevents=fgNumDump)  { fNumAreasDump   = dumpevents; }
+    void SetNumSectorsDump(UInt_t dumpevents=fgNumDump)  { fNumSectorsDump = dumpevents; }
+    void SetNumDump       (UInt_t n=fgNumDump) { fNumEventsDump=n; fNumAreasDump=n; fNumSectorsDump=n; }
+
+    void SetPedestalUpdate(Bool_t b=kTRUE) { fPedestalUpdate      = b; }
+
+    void Print(Option_t *o="") const;
 
     ClassDef(MPedCalcFromLoGain, 1)   // Task to calculate pedestals from data runs
Index: trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.cc
===================================================================
--- trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.cc	(revision 8128)
+++ trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.cc	(revision 8151)
@@ -1,3 +1,5 @@
 /* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: MPedCalcPedRun.cc,v 1.49 2006-10-24 07:58:13 tbretz Exp $
+! --------------------------------------------------------------------------
 !
 ! *
@@ -22,5 +24,5 @@
 !   Author(s): Markus Gaug 01/2004 <mailto:markus@ifae.es>
 !
-!   Copyright: MAGIC Software Development, 2000-2004
+!   Copyright: MAGIC Software Development, 2000-2006
 !
 !
@@ -137,5 +139,5 @@
 
 #include "MExtractPedestal.h"
-#include "MExtractTimeAndCharge.h"
+#include "MPedestalSubtractedEvt.h"
 
 #include "MTriggerPattern.h"
@@ -147,62 +149,31 @@
 const UShort_t MPedCalcPedRun::fgExtractWinFirst       = 0;
 const UShort_t MPedCalcPedRun::fgExtractWinSize        = 6;
+
 const UInt_t   MPedCalcPedRun::gkFirstRunWithFinalBits = 45605;
+
 // --------------------------------------------------------------------------
 //
 // Default constructor: 
 //
-// Sets:
-// - all pointers to NULL
-// - fWindowSizeHiGain to fgHiGainWindowSize
-// - fWindowSizeLoGain to fgLoGainWindowSize
-//
 // Calls: 
-// - AddToBranchList("fHiGainPixId");
-// - AddToBranchList("fHiGainFadcSamples");
-// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// - SetExtractWindow(fgExtractWinFirst, fgExtractWinSize)
 //
 MPedCalcPedRun::MPedCalcPedRun(const char *name, const char *title)
-    : fOverlap(0), fIsFirstPedRun(kFALSE), fUsedEvents(0), fTrigPattern(NULL)
-{
-  fName  = name  ? name  : "MPedCalcPedRun";
-  fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
-  
-  SetExtractWindow(fgExtractWinFirst, fgExtractWinSize);
-  
-  //  SetNumEventsDump(1001);
-  //  SetNumAreasDump(1001);
-  //  SetNumSectorsDump(1001);
-}
-
-// --------------------------------------------------------------------------
-//
-// In case that the variables fExtractLast is greater than the number of 
-// High-Gain FADC samples obtained from the run header, the flag 
-// fOverlap is set to the difference and fExtractLast is set back by the
-// same number of slices.
-//
-void MPedCalcPedRun::CheckExtractionWindow()
-{
-  const UShort_t lastavailable = fRunHeader->GetNumSamplesHiGain()-1;
-  
-  if (fExtractWinLast <= lastavailable)
-    return;
-  
-  const UShort_t diff = fExtractWinLast - lastavailable;
-  
-  *fLog << warn << endl;
-  *fLog << "Selected ExtractWindow [" << fExtractWinFirst << "," << fExtractWinLast;
-  *fLog << "] ranges out of range [0," << lastavailable << "]." << endl;
-  *fLog << "Using " << diff << " samples from the 'Lo-Gain' slices for the pedestal extraction" << endl;
-  
-  fExtractWinLast -= diff;
-  fOverlap         = diff;
-}
-
+    : fIsFirstPedRun(kFALSE), fUsedEvents(0), fTrigPattern(NULL)
+{
+    fName  = name  ? name  : "MPedCalcPedRun";
+    fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
+
+    SetExtractWindow(fgExtractWinFirst, fgExtractWinSize);
+}
+
+// --------------------------------------------------------------------------
+//
+// Call MExtractPedestal::reset and set fUsedEvents to 0.
+//
 void MPedCalcPedRun::Reset()
 {
-
-  MExtractPedestal::ResetArrays();
-  fUsedEvents    = 0;
+    MExtractPedestal::ResetArrays();
+    fUsedEvents = 0;
 }
 
@@ -213,14 +184,13 @@
 Int_t MPedCalcPedRun::PreProcess(MParList *pList)
 {
-
-  fUsedEvents    = 0;
-  fIsFirstPedRun = kTRUE;
-  fIsNotPedRun   = kFALSE;
-  
-  fTrigPattern = (MTriggerPattern*)pList->FindObject("MTriggerPattern");
-  if (!fTrigPattern)
-    *fLog << inf << "MTriggerPattern not found... Cannot use interlaced pedestal events." << endl;
-
-  return MExtractPedestal::PreProcess(pList);
+    fUsedEvents    = 0;
+    fIsFirstPedRun = kTRUE;
+    fIsNotPedRun   = kFALSE;
+
+    fTrigPattern = (MTriggerPattern*)pList->FindObject("MTriggerPattern");
+    if (!fTrigPattern)
+        *fLog << inf << "MTriggerPattern not found... Cannot use interlaced pedestal events." << endl;
+
+    return MExtractPedestal::PreProcess(pList);
 }
 
@@ -232,59 +202,56 @@
 Bool_t MPedCalcPedRun::ReInit(MParList *pList)
 {
-
-  if (!MExtractPedestal::ReInit(pList))
-    return kFALSE;
-
-  CheckExtractionWindow();
-
-  //
-  // If this is the first ped run, the next run (call to ReInit)
-  // is not the first anymore
-  //
-  switch (fRunHeader->GetRunType())
-  {
-  case MRawRunHeader::kRTPedestal:
-  case MRawRunHeader::kRTMonteCarlo:
-      fIsFirstPedRun = kFALSE;
-      fIsNotPedRun   = kFALSE;
-      return kTRUE;
-  
-  case MRawRunHeader::kRTCalibration:
-      {
-          TString proj(fRunHeader->GetProjectName());
-          proj.ToLower();
-
-          // test if a continuous light run has been declared as calibration...
-          if (proj.Contains("cl"))
-          {
-              fIsFirstPedRun = kFALSE;
-              fIsNotPedRun   = kFALSE;
-              return kTRUE;
-          }
-      }
-  }
-
-  fIsNotPedRun = kTRUE;
-
-  //
-  // If this is the first call to ReInit (before reading the first file)
-  // nothing should be done. It occurs for the case that the first treated 
-  // file is not of pedestal type.
-  //
-  if (fIsFirstPedRun)
+    if (!MExtractPedestal::ReInit(pList))
+        return kFALSE;
+
+    //
+    // If this is the first ped run, the next run (call to ReInit)
+    // is not the first anymore
+    //
+    switch (fRunHeader->GetRunType())
+    {
+    case MRawRunHeader::kRTPedestal:
+    case MRawRunHeader::kRTMonteCarlo:
+        fIsFirstPedRun = kFALSE;
+        fIsNotPedRun   = kFALSE;
+        return kTRUE;
+
+    case MRawRunHeader::kRTCalibration:
+        {
+            TString proj(fRunHeader->GetProjectName());
+            proj.ToLower();
+
+            // test if a continuous light run has been declared as calibration...
+            if (proj.Contains("cl"))
+            {
+                fIsFirstPedRun = kFALSE;
+                fIsNotPedRun   = kFALSE;
+                return kTRUE;
+            }
+        }
+    }
+
+    fIsNotPedRun = kTRUE;
+
+    //
+    // If this is the first call to ReInit (before reading the first file)
+    // nothing should be done. It occurs for the case that the first treated
+    // file is not of pedestal type.
+    //
+    if (fIsFirstPedRun)
+        return kTRUE;
+
+    //
+    // In the other case, produce the MPedestalCam to be use the subsequent
+    // (non-pedestal) events
+    //
+    *fLog << inf << "Finalizing pedestal calculations..." << flush;
+
+    if (!Finalize())
+        return kFALSE;
+
+    Reset();
+
     return kTRUE;
-  
-  //
-  // In the other case, produce the MPedestalCam to be use the subsequent
-  // (non-pedestal) events
-  //
-  *fLog << inf << "Finalizing pedestal calculations..." << flush;
-  
-  if (!Finalize())
-    return kFALSE;
-  
-  Reset();
-
-  return kTRUE;
 }
 
@@ -300,130 +267,54 @@
 Int_t MPedCalcPedRun::Calc()
 {
-  if (fIsNotPedRun && !IsPedBitSet())
+    if (fIsNotPedRun && !IsPedBitSet())
+        return kTRUE;
+
+    fUsedEvents++;
+
+    MRawEvtPixelIter pixel(fRawEvt);
+    while (pixel.Next())
+    {
+        const UInt_t idx = pixel.GetPixelId();
+
+        if (!CheckVariation(idx))
+            continue;
+
+        //extract pedestal
+        UInt_t ab[2];
+        const Float_t sum = fExtractor ?
+            CalcExtractor(pixel, 0) :
+            CalcSums(pixel, 0, ab[0], ab[1]);
+
+        if (fIntermediateStorage)
+            (*fPedestalsInter)[idx].Set(sum, 0, 0, fUsedEvents);
+
+        const Float_t sqrsum = sum*sum;
+
+        fSumx[idx]   += sum;
+        fSumx2[idx]  += sqrsum;
+
+        fSumAB0[idx] += ab[0];
+        fSumAB1[idx] += ab[1];
+
+        if (fUseSpecialPixels)
+            continue;
+
+        const UInt_t aidx   = (*fGeom)[idx].GetAidx();
+        const UInt_t sector = (*fGeom)[idx].GetSector();
+
+        fAreaSumx[aidx]      += sum;
+        fAreaSumx2[aidx]     += sqrsum;
+        fSectorSumx[sector]  += sum;
+        fSectorSumx2[sector] += sqrsum;
+
+        fAreaSumAB0[aidx]    += ab[0];
+        fAreaSumAB1[aidx]    += ab[1];
+        fSectorSumAB0[aidx]  += ab[0];
+        fSectorSumAB1[aidx]  += ab[1];
+    }
+
+    fPedestalsOut->SetReadyToSave();
+
     return kTRUE;
-  
-  //  if (fUsedEvents == fNumEventsDump)
-  //    {
-  //      *fLog << endl;
-  //      *fLog << inf << GetDescriptor() << " : Finalize pedestal calculations..." << flush;
-  //      Finalize();
-  //      Reset();
-  //    }
-  
-  fUsedEvents++;
-
-  MRawEvtPixelIter pixel(fRawEvt);
-  
-  while (pixel.Next())
-  {
-      const UInt_t idx = pixel.GetPixelId();
-
-      Float_t sum = 0.;
-      UInt_t  ab0 = 0;
-      UInt_t  ab1 = 0;
-      
-      if (fExtractor)
-        CalcExtractor(pixel, sum, (*fPedestalsIn)[idx]);
-      else
-        CalcSums(pixel, sum, ab0, ab1);
-
-      fSumx[idx] += sum;
-
-      if (fIntermediateStorage)
-        (*fPedestalsInter)[idx].Set(sum,0.,0.,fUsedEvents);
-
-      const Float_t sqrsum = sum*sum;
-
-      fSumx2[idx]  += sqrsum;
-      fSumAB0[idx] += ab0;
-      fSumAB1[idx] += ab1;
-
-      if (fUseSpecialPixels)
-	continue;
-
-      const UInt_t aidx   = (*fGeom)[idx].GetAidx();
-      const UInt_t sector = (*fGeom)[idx].GetSector();      
-
-      fAreaSumx[aidx]      += sum;
-      fSectorSumx[sector]  += sum;
-
-      fAreaSumx2[aidx]     += sqrsum;
-      fSectorSumx2[sector] += sqrsum;
-
-      fAreaSumAB0[aidx]    += ab0;
-      fAreaSumAB1[aidx]    += ab1;
-      
-      fSectorSumAB0[aidx]  += ab0;
-      fSectorSumAB1[aidx]  += ab1;
-  }
-  
-  fPedestalsOut->SetReadyToSave();
-
-  return kTRUE;
-}
-
-
-void MPedCalcPedRun::CalcExtractor(const MRawEvtPixelIter &pixel, Float_t &sum, MPedestalPix &ped)
-{
-    const Bool_t abflag = pixel.HasABFlag();
-
-    Byte_t *first  = pixel.GetHiGainSamples() + fExtractWinFirst;
-    Byte_t *logain = pixel.GetLoGainSamples();
-
-    Byte_t  sat = 0;
-
-    Float_t dummy;
-    fExtractor->FindTimeAndChargeHiGain(first,logain,sum,dummy,dummy,dummy,sat,ped,abflag);
-}
-
-void MPedCalcPedRun::CalcSums(const MRawEvtPixelIter &pixel, Float_t &sum, UInt_t &ab0, UInt_t &ab1)
-{
-
-  Byte_t *higain = pixel.GetHiGainSamples() + fExtractWinFirst;
-  Byte_t *ptr = higain;
-  Byte_t *end = ptr + fExtractWinSize;
-
-  const Bool_t abflag = pixel.HasABFlag();
-
-  Int_t sumi = 0;
-      
-  Int_t  cnt = 0;
-  do
-  {
-      sumi += *ptr;
-      if (!pixel.IsABFlagValid())
-          continue;
-
-      const Int_t abFlag = (fExtractWinFirst + abflag + cnt) & 0x1;
-      if (abFlag)
-          ab1 += *ptr;
-      else
-          ab0 += *ptr;
-
-      cnt++;
-  } while (++ptr != end);
-
-  if (fOverlap != 0)
-  {
-      ptr = pixel.GetLoGainSamples();
-      end = ptr + fOverlap;
-
-      do
-      {
-          sumi += *ptr;
-          if (!pixel.IsABFlagValid())
-              continue;
-
-          const Int_t abFlag = (fExtractWinFirst + abflag + cnt) & 0x1;
-          if (abFlag)
-              ab1 += *ptr;
-          else
-              ab0 += *ptr;
-
-          cnt++;
-      } while (++ptr != end);
-  }
-
-  sum = (Float_t)sumi;
 }
 
@@ -472,4 +363,8 @@
 }
 
+//-----------------------------------------------------------------------
+//
+// PostProcess MExtractPedestal and call Finalize
+//
 Int_t MPedCalcPedRun::PostProcess()
 {
@@ -501,14 +396,10 @@
 }
 
+//-----------------------------------------------------------------------
+//
 void MPedCalcPedRun::Print(Option_t *o) const
 {
     MExtractPedestal::Print(o);
 
-    const Int_t last = fExtractor 
-      ? fExtractWinFirst + fExtractor->GetWindowSizeHiGain() -1
-      : fExtractWinLast;
-
-    *fLog << "ExtractWindow from slice      " << fExtractWinFirst << " to " << last << " incl." << endl;
-    *fLog << "Num overlap lo-gain slices:   " << fOverlap << endl;
     *fLog << "First pedrun out of sequence: " << (fIsFirstPedRun?"yes":"no") << endl;
     *fLog << "Number of used events so far: " << fUsedEvents << endl;
Index: trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.h
===================================================================
--- trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.h	(revision 8128)
+++ trunk/MagicSoft/Mars/mpedestal/MPedCalcPedRun.h	(revision 8151)
@@ -7,5 +7,4 @@
 
 class MTriggerPattern;
-class MRawEvtPixelIter;
 class MPedestalPix;
 
@@ -16,6 +15,4 @@
     static const UShort_t fgExtractWinSize;   // Extraction Size Hi-Gain (currently set to: 14)
     static const UInt_t   gkFirstRunWithFinalBits; // First Run with pedestal trigger bit at place 3
-
-    UShort_t fOverlap;         // Number of overlapping slices from High-Gain to Low-Gain
 
     Bool_t  fIsFirstPedRun;    //! Flag to tell if the first run out of many is used
@@ -32,7 +29,7 @@
     Int_t  PostProcess();
 
-    void CheckExtractionWindow();
-    void CalcSums(const MRawEvtPixelIter &pixel, Float_t &sum, UInt_t &ab0, UInt_t &ab1);
-    void CalcExtractor(const MRawEvtPixelIter &pixel, Float_t &sum, MPedestalPix &ped);
+    //void CheckExtractionWindow();
+    //UInt_t CalcSums(const MRawEvtPixelIter &pixel, UInt_t &ab0, UInt_t &ab1);
+    //void CalcExtractor(const MRawEvtPixelIter &pixel, Float_t &sum, MPedestalPix &ped);
 
 public:
Index: trunk/MagicSoft/Mars/mpedestal/Makefile
===================================================================
--- trunk/MagicSoft/Mars/mpedestal/Makefile	(revision 8128)
+++ trunk/MagicSoft/Mars/mpedestal/Makefile	(revision 8151)
@@ -40,4 +40,7 @@
            MPedestalCam.cc \
 	   MPedestalPix.cc \
+           MHPedestalCor.cc \
+           MPedestalSubtract.cc \
+           MPedestalSubtractedEvt.cc \
 	   MPedCalcFromData.cc
 
Index: trunk/MagicSoft/Mars/mpedestal/PedestalLinkDef.h
===================================================================
--- trunk/MagicSoft/Mars/mpedestal/PedestalLinkDef.h	(revision 8128)
+++ trunk/MagicSoft/Mars/mpedestal/PedestalLinkDef.h	(revision 8151)
@@ -17,5 +17,9 @@
 #pragma link C++ class MPedestalCam+;
 #pragma link C++ class MPedestalPix+;
+#pragma link C++ class MPedestalSubtract+;
+#pragma link C++ class MPedestalSubtractedEvt+;
 #pragma link C++ class MPedCalcFromData+;
 
+#pragma link C++ class MHPedestalCor+;
+
 #endif
